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:
Compiling a regex inside a function that's called multiple times
If you compile a regex inside a function, and that function gets called multiple times, does Python recompile the regex each time, or does Python cache the compiled regex (assuming the regex doesn't change)?
For example:
def contains_text_of_interest(line):
r = re.compile(r"foo\dbar\d")
return r.match(line)
def parse_file(fname):
for line in open(fname):
if contains_text_of_interest(line):
# Do something interesting
A:
Actually, if you look at the code in the re module, the re.compile function uses the cache just as all the other functions do, so compiling the same regex over and over again is very very cheap (a dictionary lookup). In other words, write the code to be the most understandable or maintainable or expressive, and don't worry about the overhead of compiling regexes.
A:
If you want to avoid the overhead of calling re.compile() every time, you can do:
def contains_text_of_interest(line, r = re.compile(r"foo\dbar\d")):
return r.match(line)
A:
Why don't you just put the re.compile outside functions (at module or class level), give it an explicit name and just use it ? That kind of regex is a kind of constant and you can treat it the same way.
MATCH_FOO_BAR = re.compile(r"foo\dbar\d")
def contains_text_of_interest(line):
return MATCH_FOO_BAR.match(line)
A:
Dingo's solution is a good one [edit: Ned Batchelder's explanation is even better], but here's another one which I think is neat: use closures! If that sounds like a "big word" to you, don't worry. The concept is simple:
def make_matching_function():
matcher = re.compile(r"foo\dbar\d")
def f(line):
return matcher.match(line)
return f
contains_text_of_interest = make_matching_function()
make_matching_function is called only once, and therefore the regex is compiled only once. The function f, which is assigned to contains_text_of_interest, knows about the compiled regex matcher because it's in the surrounding scope, and will always know about it, even if you use contains_text_of_interest somewhere else (that's closures: code that takes the surrounding scope with it).
Not the most Pythonic solution to this problem, surely. But it's a good idiom to have up your sleeve, for when the time is right :)
A:
It does the "wrong" thing, here's a longer thread on the topic.
I'm using Python regexes in a criminally inefficient manner
| Compiling a regex inside a function that's called multiple times | If you compile a regex inside a function, and that function gets called multiple times, does Python recompile the regex each time, or does Python cache the compiled regex (assuming the regex doesn't change)?
For example:
def contains_text_of_interest(line):
r = re.compile(r"foo\dbar\d")
return r.match(line)
def parse_file(fname):
for line in open(fname):
if contains_text_of_interest(line):
# Do something interesting
| [
"Actually, if you look at the code in the re module, the re.compile function uses the cache just as all the other functions do, so compiling the same regex over and over again is very very cheap (a dictionary lookup). In other words, write the code to be the most understandable or maintainable or expressive, and d... | [
14,
6,
2,
2,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0003427329_python_regex.txt |
Q:
Saving a temporary file
I'm using xlwt in python to create a Excel spreadsheet. You could interchange this for almost anything else that generates a file; it's what I want to do with the file that's important.
from xlwt import *
w = Workbook()
#... do something
w.save('filename.xls')
I want to I have two use cases for the file: I stream it out to the user's browser or I attach it to an email. In both cases the file only needs to exist the duration of the web request that generates it.
What I'm getting at, the reason for starting this thread is saving to a real file on the filesystem has its own hurdles (stopping overwriting, cleaning up the file once done). Is there somewhere I could "save" it where it lives only in memory and only for the duration of the request?
A:
cStringIO
(or mmap if it should be mutable)
A:
Generalising the answer, as you suggested: If the "anything else that generates a file" won't accept a file-like object as well as a filepath, then you can reduce the hassle by using tempfile.NamedTemporaryFile
| Saving a temporary file | I'm using xlwt in python to create a Excel spreadsheet. You could interchange this for almost anything else that generates a file; it's what I want to do with the file that's important.
from xlwt import *
w = Workbook()
#... do something
w.save('filename.xls')
I want to I have two use cases for the file: I stream it out to the user's browser or I attach it to an email. In both cases the file only needs to exist the duration of the web request that generates it.
What I'm getting at, the reason for starting this thread is saving to a real file on the filesystem has its own hurdles (stopping overwriting, cleaning up the file once done). Is there somewhere I could "save" it where it lives only in memory and only for the duration of the request?
| [
"cStringIO\n(or mmap if it should be mutable)\n",
"Generalising the answer, as you suggested: If the \"anything else that generates a file\" won't accept a file-like object as well as a filepath, then you can reduce the hassle by using tempfile.NamedTemporaryFile\n"
] | [
5,
1
] | [] | [] | [
"python",
"xlwt"
] | stackoverflow_0003406061_python_xlwt.txt |
Q:
Eclipse: Debug script that expects command line parameters
I have a python script I am trying to debug in eclipse. I can execute it, breakpoint all that jazz, but this specific script requires a handful of command line parameters. Is it possible to setup my dev environment in eclipse to put these parameters in?
Right now my program is just generating the line to execute, like:
script.py -aword -banother -cword -dmore -eparams -flast -gone
so could I just copy and paste everything after script.py somewhere? or can I hard code them into eclipse? or will I have to hard code the variables within my script?
A:
Use a launch configuration
To create:
- Right mouse button on your script, => Run as / Python Run
=> this creates a Run configuration
- Right mouser button again, Run as / Run Configurations
=> opens this specific configuration
- Tab 'Arguments', enter your arguments
To use:
- from the same step above
OR
- access it from the 'Debug' and 'Run' icons in the toolbar
This configuration will be shared between the 'Run' and 'Debug' mode.
You can even check it in to share with the other members of your team by filling up the 'Save as' in the 'Common' tab.
This is very useful if you have a complicated settings that require arguments, VM arguments, environment variables, ...
A:
Yes, if you go into the project settings you can setup command line arguments to pass to your program. See the section titled: Running A Python Script
| Eclipse: Debug script that expects command line parameters | I have a python script I am trying to debug in eclipse. I can execute it, breakpoint all that jazz, but this specific script requires a handful of command line parameters. Is it possible to setup my dev environment in eclipse to put these parameters in?
Right now my program is just generating the line to execute, like:
script.py -aword -banother -cword -dmore -eparams -flast -gone
so could I just copy and paste everything after script.py somewhere? or can I hard code them into eclipse? or will I have to hard code the variables within my script?
| [
"Use a launch configuration\nTo create:\n - Right mouse button on your script, => Run as / Python Run\n => this creates a Run configuration\n - Right mouser button again, Run as / Run Configurations\n => opens this specific configuration\n - Tab 'Arguments', enter your arguments\nTo use:\n - from the same... | [
3,
2
] | [] | [] | [
"eclipse",
"pydev",
"python"
] | stackoverflow_0003418270_eclipse_pydev_python.txt |
Q:
are there tutorials on how to name variables?
as you can probably tell from my previous posts i have horrific naming conventions. do you know of any tutorials dealing with how to name stuff?
A:
i will recommend to check this book
http://www.amazon.com/Code-Complete-Practical-Handbook-Construction/dp/0735619670/ref=sr_1_1?s=books&ie=UTF8&qid=1281129036&sr=1-1
A:
I don't think there will be any good tutorials, because there aren't any hard-and-fast rules. Here are some tips:
Conform to convention: Loop variables are i, j, and k; variable numbers of arguments go in *args and **kwargs; use camelCase or underscored_names.
Be consistent.
Be concise. list_of_drugs_used_in_this_program is much less clear than drugs. Similarly, you don't need to include the datatype of the variable in the name: drugs_list is redundant.
Don't go overboard with the underscores. I've never needed more than one. 2+ is pushing it.
Never ever ever use metasyntactic variables (foo, spam...) in anything but quick-and-dirty examples. method1 is also out.
But you could summarise all of that with:
Don't be silly.
Tee hee.
Variable naming conventions can often
turn into a religious war, but I’m
entirely confident when I declare The
World’s Worst Variable Name to be:
$data
Of course it’s data! That’s what
variables contain! That’s all they
ever can contain. It’s like you’re
packing up your belongings to move to
a new house, and on the side of the
box you write, in big black marker,
“matter.”
http://www.oreillynet.com/onlamp/blog/2004/03/the_worlds_two_worst_variable.html
A:
A bad convention followed fully is better than a combination of different good "conventions" (which aren't conventions at all any more, if they aren't kept to).
However, a convention that is making something less clear than if it had been ignored, should be ignored.
Those are the only two I would state as any sort of rule. Beyond that convention preferences are a matter of opinions quickly turning into rants. The rest of this post is exactly that, and shouldn't be read as anything else.
For collections, use natural language plurals. In English, this means data, schemata, children, indices, criteria, formulae (and indeed foci, geese, feet, men, women, teeth) not made-up words like datums schemas, childs, indexes, criterions, formulas (and likewise focuses, gooses, foots, mans, womans, tooths, believe it or not I've actually seen some of those in use). Camel-casing and abbreviatiating does enough damage to English as it is, without doing more. Okay, I've never seen datums, but I have seen the meta-plural datas. Sweet Aradia, why?
That said, use American English for names, even if you use a different dialect of English. Most coders with such dialects have learnt to think of "color" as a word for colours in a computer context by the age of 12, and the principle applies more widely. If we can deal with "color" (one of Webster's worse bastardisations) we can deal with -ize and -ization (-ise and -isation is a pseudo-French 18th C affectation anyway, the Americans are the traditionalists on this one).
Similarly, if you aren't sure how to spell a word that you are using as the whole or part of a name, look it up (google it and see what google says). Somebody may spend a long time distracted by your misspelling that is so liberally distributed throughout running code as to make fixing it daunting.
Hungarian is bad (in many modern languages, though in some it has its place) but the principle is good. If you can tell a const, static, instance, local and parameter variable from each other in a split-second, that's good. If you can tell something of the intent immediately, that's good too.
Related to that, _ before public variables makes them non CLR compiant. That's actually a good thing for private variables (if you make them public for a quick experiment, and forget to fix the visibility, the compiler will warn you).
Remember Postel's Law, "be conservative in what you do, be liberal in what you accept from others". One example of this is to act as if you are using a case-sensitive langauge, even if you're using a case-insensitive one. A related one is to be more of a stickler in public names than private ones. Yet another is to pay more attention to following conventions well than to complaining about those who don't.
A:
All the answers here are quite valid. Most important: be consistent.
That said, here are my rules (C#):
camelCase identifiers -- I personally
find this much easier to read than
underscores
Public properties start
with a capital letter
Something I
should never touch starts with an
underscore -- example, the backing
field to a property should only be
touched from the property. If I have
underscores elsewhere, I know I'm
wrong
Apps Hungarian where
appropriate -- ints describing row
IDs perhaps could be named
rowSelected, rowNextUnread, et
cetera. This is different than
Systems Hungarian, which would mark
them as ints such as iSelected,
iNextUnread. Systems Hungarian
doesn't add much if anything, where
Apps Hungarian gives information the
type doesn't: it tells me adding
rowItemsPerPage and colSelected is a
meaningless operation, even though it
compiles just fine.
A:
Not a tutorial... more like a guide/best practice kind of thing:
http://msdn.microsoft.com/en-us/library/xzf533w0(VS.71).aspx
A:
I'd recommend purchasing a copy of "Clean Code" by Robert C. Martin. It is full of great suggstions ranging from naming conventions to how to write easy-to-understand functions and much more. Definitely worth a read. I know it influenced my coding style since reading it.
A:
hi for me you should always put the most explicit names:
string_to_hash = "blabla"
hash(sring_to_hash)
and respect the pep8 style guide. You code should then be very easy to read.
A:
There are many different views on the specifics of naming conventions, but the overall gist could be summed up as:
Each variable name should be relevant
to whatever data is stored in the
variable.
Your naming scheme should be consistent.
So a major no-no would be
single letter variables (some people
use i and j for indexing loops, which
is OK because every programmer knows
what they are. Nevertheless, I prefer
'idx' instead of 'i'). Also out are
names like 'method1', it means nothing
- it should indicate what the variable holds.
Another (less common) convention is the 'Hungarian' notation where the data type is prefixed to the variable name such as 'int i_idx'. This is quite useless in modern, object oriented programming languages. Not to mention a blatant violation of the DRY principle.
The second point, consistency, is just as important. camelCase, UpperCamelCase, whatever - just don't switch between them for no reason.
You'll find that naming conventions vary from language to language and often, a company will have their own rules on naming.
Its a worthwhile investment to properly name your variables because when you come to maintain your code much later on and you have forgotten what everything means, it will pay dividends.
A:
You didn't specify what language are you looking for. Since your question is flagged .NET, here is a document I follow when writing C# code: http://weblogs.asp.net/lhunt/pages/CSharp-Coding-Standards-document.aspx.
A:
Have you read Code Complete? He does a full treatise on this in the book. Definitely the best naming strategy I've seen in print... And it's easy to find like 1000 programmers at the drop of a hat who name this one of the top 5 resources for programmers and program design.
Just my $.05
A:
Can I make a shameless plug for the "Names" chapter in my book, "A Sane Approach to Database Design" ? I'm specifically talking about names for things in databases, but most of the same considerations apply to variables in programs.
A:
It's not clear if your question relates to Python naming conventions.
If so, for starters I would try to follow just these simple rules:
ClassName - upper case for class names
variable_name - lower case and underscore for variables (I try to keep them at two words maximum)
| are there tutorials on how to name variables? | as you can probably tell from my previous posts i have horrific naming conventions. do you know of any tutorials dealing with how to name stuff?
| [
"i will recommend to check this book \nhttp://www.amazon.com/Code-Complete-Practical-Handbook-Construction/dp/0735619670/ref=sr_1_1?s=books&ie=UTF8&qid=1281129036&sr=1-1\n",
"I don't think there will be any good tutorials, because there aren't any hard-and-fast rules. Here are some tips:\n\nConform to convention:... | [
11,
7,
5,
4,
3,
3,
3,
3,
2,
2,
1,
1
] | [] | [] | [
".net",
"language_agnostic",
"naming_conventions",
"python"
] | stackoverflow_0003427795_.net_language_agnostic_naming_conventions_python.txt |
Q:
XML and Python: Get the namespaces declared in root element
How do I access the multiple xmlns declarations at the root element of an XML tree? For example:
import xml.etree.cElementTree as ET
data = """<root
xmlns:one="http://www.first.uri/here/"
xmlns:two="http://www.second.uri/here/">
...all other child elements here...
</root>"""
tree = ET.fromstring(data)
# I don't know what to do here afterwards
I want to get a dictionary similar to this one, or at least some format to make it easier to get the URI and the matching tag
{'one':"http://www.first.uri/here/", 'two':"http://www.second.uri/here/"}
A:
I'm not sure how this might be done with xml.etree, but with lxml.etree you could do this:
import lxml.etree as le
data = """<root
xmlns:one="http://www.first.uri/here/"
xmlns:two="http://www.second.uri/here/">
...all other child elements here...
</root>"""
tree = le.XML(data)
print(tree.nsmap)
# {'two': 'http://www.second.uri/here/', 'one': 'http://www.first.uri/here/'}
| XML and Python: Get the namespaces declared in root element | How do I access the multiple xmlns declarations at the root element of an XML tree? For example:
import xml.etree.cElementTree as ET
data = """<root
xmlns:one="http://www.first.uri/here/"
xmlns:two="http://www.second.uri/here/">
...all other child elements here...
</root>"""
tree = ET.fromstring(data)
# I don't know what to do here afterwards
I want to get a dictionary similar to this one, or at least some format to make it easier to get the URI and the matching tag
{'one':"http://www.first.uri/here/", 'two':"http://www.second.uri/here/"}
| [
"I'm not sure how this might be done with xml.etree, but with lxml.etree you could do this:\nimport lxml.etree as le\ndata = \"\"\"<root\n xmlns:one=\"http://www.first.uri/here/\"\n xmlns:two=\"http://www.second.uri/here/\">\n\n ...all other child elements here...\n </root>... | [
2
] | [] | [] | [
"python",
"xml",
"xml_namespaces"
] | stackoverflow_0003428792_python_xml_xml_namespaces.txt |
Q:
Elegant Python?
I am trying to teach myself Python, and I have realized that the only way I really learn stuff is by reading the actual programs. Tutorials/manuals just cause me to feel deeply confused.
It's just my learning style, and I'm like that with everything I've studied (including natural languages -- I've managed to teach myself three of them by just getting into the actual 'flow of it').
Classical music once had the concept of a 'gamut' -- playing the entire range of an instrument in an artful manner. I'm guessing that there may be a few well-written scripts out there that really show off every feature of the language. It doesn't matter what they do, I just want to start studying Python by reading programs themselves.
I remember coming across a similar method years ago when I studied some LISP. It was a book, published by Springer Verlag, consisting solely of AI programs, to be read for their didactic merit.
A:
I would recommend studying the Standard Python Library (all the parts of it that are coded in Python, that is) -- it's not uniformly excellent in elegance, but it sets a pretty high standard. Plus, the study has the extra benefit of making you very familiar with the library itself (an absolutely crucial part of mastering Python), in addition to showing you a lot good to excellent Python style code;-).
Edit: I have to point out (or my wife and co-author Anna has threatened to not cook the yummy steak I see waiting;-) that the Python Cookbook, 2nd printed edition, also has a lot of code examples, in the best style Anna and I could make them, and with substantial discussion of style variations and alternatives. However, it's stuck back in time to the days of Python 2.4 (sorry, no time to do a third edition for now...), and that's a real block for some people (though I think that having learned good Python 2.4 style, moving to good 2.7 or 3.1 style is really an "incremental" matter, that's definitely a subjective opinion). "Declaring my interest": Anna and I still get some royalties if you buy the book, and, more importantly, the Python Software Foundation (near and dear to both our hearts -- our Prius's vanity license plate reads "P♥THON"...!-) gets more -- so obviously we're biased in the book's favor;-). If you don't want to spend money, you can read some parts of the book online and for free on Google Books (O'Reilly gets to pick and choose which parts are thus freely readable, so please don't complain to me [[or Anna]] about those choices...!-).
I wish I could recommend the online edition of the Cookbook, which does have recipes that are very recent as well as the classic old ones among which we picked and chose most of the printed edition's ones -- but, unfortunately, there are lots of style issues with too many of the online recipes to recommend them collectively as "good style examples" (and that goes for the good recipes too: most of the recipes we picked for the book, we also heavily edited to improve style (and readability, and performance, but those often go hand-in-hand with Python).
A:
I agree with Alex.
The Standard Library is a great learning resource.
As someone once pointed, the doctest module is a "good read":
http://svn.python.org/projects/sandbox/trunk/setuptools/doctest.py
| Elegant Python? | I am trying to teach myself Python, and I have realized that the only way I really learn stuff is by reading the actual programs. Tutorials/manuals just cause me to feel deeply confused.
It's just my learning style, and I'm like that with everything I've studied (including natural languages -- I've managed to teach myself three of them by just getting into the actual 'flow of it').
Classical music once had the concept of a 'gamut' -- playing the entire range of an instrument in an artful manner. I'm guessing that there may be a few well-written scripts out there that really show off every feature of the language. It doesn't matter what they do, I just want to start studying Python by reading programs themselves.
I remember coming across a similar method years ago when I studied some LISP. It was a book, published by Springer Verlag, consisting solely of AI programs, to be read for their didactic merit.
| [
"I would recommend studying the Standard Python Library (all the parts of it that are coded in Python, that is) -- it's not uniformly excellent in elegance, but it sets a pretty high standard. Plus, the study has the extra benefit of making you very familiar with the library itself (an absolutely crucial part of m... | [
18,
3
] | [] | [] | [
"python"
] | stackoverflow_0003428245_python.txt |
Q:
python regex to find any link that contains the text 'abc123'
I am using beautifuly soup to find all href tags.
links = myhtml.findAll('a', href=re.compile('????'))
I need to find all links that have 'abc123' in the href text.
I need help with the regex , see ??? in my code snippet.
A:
If 'abc123' is literally what you want to search for, anywhere in the href, then re.compile('abc123') as suggested by other answers is correct. If the actual string you want to match contains punctuation, e.g. 'abc123.com', then use instead
re.compile(re.escape('abc123.com'))
The re.escape part will "escape" any punctuation so that it's taken literally, just like alphanumerics are; without it, some punctuation gets interpreted in various ways by RE's engine, for example the dot ('.') in the above example would be taken as "any single character whatsoever", so re.compile('abc123.com') would match, e.g. 'abc123zcom' (and many other strings of a similar nature).
A:
"abc123" should give you what you want
if that doesn't work, than BS is probably using re.match in which case you would want ".*abc123.*"
A:
If you want all the links with exactly 'abc123' you can simply put:
links = myhtml.findAll('a', href=re.compile('abc123'))
| python regex to find any link that contains the text 'abc123' | I am using beautifuly soup to find all href tags.
links = myhtml.findAll('a', href=re.compile('????'))
I need to find all links that have 'abc123' in the href text.
I need help with the regex , see ??? in my code snippet.
| [
"If 'abc123' is literally what you want to search for, anywhere in the href, then re.compile('abc123') as suggested by other answers is correct. If the actual string you want to match contains punctuation, e.g. 'abc123.com', then use instead\nre.compile(re.escape('abc123.com'))\n\nThe re.escape part will \"escape\... | [
2,
1,
1
] | [] | [] | [
"beautifulsoup",
"python",
"regex"
] | stackoverflow_0003428845_beautifulsoup_python_regex.txt |
Q:
Is there a way to automate restarting the python process after every change I make to Django models?
I am using Django with Passenger on Dreamhost.
Every time I make a change to models, settings or views I need to pkill python from a terminal session. Does anyone know of a way to automate this? Is this something that Passenger can do?
A:
My advice would be to test locally using Django's builtin server.
It does precisely auto-reload, so that any change to your code will be available.
I'm not familiar with Dreamhost, but if modwsgi is on embedded mode this is not possible.
In Daemon mode, you could write some code to detect file changes and restart the processes.
| Is there a way to automate restarting the python process after every change I make to Django models? | I am using Django with Passenger on Dreamhost.
Every time I make a change to models, settings or views I need to pkill python from a terminal session. Does anyone know of a way to automate this? Is this something that Passenger can do?
| [
"My advice would be to test locally using Django's builtin server.\nIt does precisely auto-reload, so that any change to your code will be available.\nI'm not familiar with Dreamhost, but if modwsgi is on embedded mode this is not possible.\nIn Daemon mode, you could write some code to detect file changes and resta... | [
2
] | [] | [] | [
"django",
"passenger",
"python",
"wsgi"
] | stackoverflow_0003427287_django_passenger_python_wsgi.txt |
Q:
Forgetting self qualifier: how to catch this mistake?
I understand why Python requires explicit self qualifier when referring to instance attributes.
But I often forget it, since I didn't need it in C++.
The bug I introduce this way is sometimes extremely hard to catch; e.g., suppose I write
if x is not None:
f()
instead of
if self.x is not None:
f()
Suppose attribute x is usually None, so f() is rarely called. And suppose f() only creates a subtle side effect (e.g., a change in a numeric value, or clearing the cache, etc.). Unless I have insane amount of unit tests, this mistake is likely to remain unnoticed for a long time.
I am wondering if anyone knows coding techniques or IDE features that could help me catch or avoid this type of bug.
A:
Don't name your instance attributes the same things as your globals/locals.
If there isn't a global/local of the same name, you'll get a global "foo" is not defined error when you try to access self.foo but forget the self..
As a corollary: give your variables descriptive names. Don't name everything x - not only does this make it far less likely you'll have variables with the same name as attributes, it also makes your code easier to read.
| Forgetting self qualifier: how to catch this mistake? | I understand why Python requires explicit self qualifier when referring to instance attributes.
But I often forget it, since I didn't need it in C++.
The bug I introduce this way is sometimes extremely hard to catch; e.g., suppose I write
if x is not None:
f()
instead of
if self.x is not None:
f()
Suppose attribute x is usually None, so f() is rarely called. And suppose f() only creates a subtle side effect (e.g., a change in a numeric value, or clearing the cache, etc.). Unless I have insane amount of unit tests, this mistake is likely to remain unnoticed for a long time.
I am wondering if anyone knows coding techniques or IDE features that could help me catch or avoid this type of bug.
| [
"Don't name your instance attributes the same things as your globals/locals.\nIf there isn't a global/local of the same name, you'll get a global \"foo\" is not defined error when you try to access self.foo but forget the self..\nAs a corollary: give your variables descriptive names. Don't name everything x - not o... | [
5
] | [] | [] | [
"debugging",
"python",
"self"
] | stackoverflow_0003429073_debugging_python_self.txt |
Q:
Python requires a GIL. But Jython & IronPython don't. Why?
Why is it that you can run Jython and IronPython without the need for a GIL but Python (CPython) requires a GIL?
A:
Parts of the Interpreter aren't threadsafe, though mostly because making them all threadsafe by massive lock usage would slow single-threaded extremely (source). This seems to be related to the CPython garbage collector using reference counting (the JVM and CLR don't, and therefore don't need to lock/release a reference count every time). But even if someone thought of an acceptable solution and implemented it, third party libraries would still have the same problems.
Note that extensions written in C can in fact get rid of the GIL: http://docs.python.org/c-api/init.html#thread-state-and-the-global-interpreter-lock
A:
My guess, because the C libraries that CPython is built upon aren't thread-safe. Whereas Jython and IronPython are built against the Java and .Net respectively.
| Python requires a GIL. But Jython & IronPython don't. Why? | Why is it that you can run Jython and IronPython without the need for a GIL but Python (CPython) requires a GIL?
| [
"Parts of the Interpreter aren't threadsafe, though mostly because making them all threadsafe by massive lock usage would slow single-threaded extremely (source). This seems to be related to the CPython garbage collector using reference counting (the JVM and CLR don't, and therefore don't need to lock/release a ref... | [
11,
3
] | [] | [] | [
"gil",
"ironpython",
"jython",
"multithreading",
"python"
] | stackoverflow_0003429159_gil_ironpython_jython_multithreading_python.txt |
Q:
Convert html entities to ascii in Python
I need to convert any html entity into its ASCII equivalent using Python. My use case is that I am cleaning up some HTML used to build emails to create plaintext emails from the HTML.
Right now, I only really know how to create unicode from these entities when I need ASCII (I think) so that the plaintext email reads correctly with things like accented characters. I think a basic example is the html entity "& aacute;" or á being encoded into ASCII.
Furthermore, I'm not even 100% sure that ASCII is what I need for a plaintext email. As you can tell, I'm completely lost on this encoding stuff.
A:
Here is a complete implementation that also handles unicode html entities. You might find it useful.
It returns a unicode string that is not ascii, but if you want plain ascii, you can modify the replace operations so that it replaces the entities to empty string.
def convert_html_entities(s):
matches = re.findall("&#\d+;", s)
if len(matches) > 0:
hits = set(matches)
for hit in hits:
name = hit[2:-1]
try:
entnum = int(name)
s = s.replace(hit, unichr(entnum))
except ValueError:
pass
matches = re.findall("&#[xX][0-9a-fA-F]+;", s)
if len(matches) > 0:
hits = set(matches)
for hit in hits:
hex = hit[3:-1]
try:
entnum = int(hex, 16)
s = s.replace(hit, unichr(entnum))
except ValueError:
pass
matches = re.findall("&\w+;", s)
hits = set(matches)
amp = "&"
if amp in hits:
hits.remove(amp)
for hit in hits:
name = hit[1:-1]
if htmlentitydefs.name2codepoint.has_key(name):
s = s.replace(hit, unichr(htmlentitydefs.name2codepoint[name]))
s = s.replace(amp, "&")
return s
Edit: added matching for hexcodes. I've been using this for a while now, and ran into my first situation with ' which is a single quote/apostrophe.
A:
ASCII is the American Standard Code for Information Interchange and does not include any accented letters. Your best bet is to get Unicode (as you say you can) and encode it as UTF-8 (maybe ISO-8859-1 or some weird codepage if you're dealing with seriously badly coded user-agents/clients, sigh) -- the content type header of that part together with text/plain can express what encoding you've chosen to use (I do recommend trying UTF-8 unless you have positively demonstrated it cannot work -- it's almost universally supported these days and MUCH more flexible than any ISO-8859 or "codepage" hack!).
A:
You can use the htmlentitydefs package:
import htmlentitydefs
print htmlentitydefs.entitydefs['aacute']
Basically, entitydefs is just a dictionary, and you can see this by printing it at the python prompt:
from pprint import pprint
pprint htmlentitydefs.entitydefs
A:
We put up a little module with agazso's function:
http://github.com/ARTFL/util/blob/master/ents.py
We find agazso's function to faster than the alternatives for ent conversion. Thanks for posting it.
| Convert html entities to ascii in Python | I need to convert any html entity into its ASCII equivalent using Python. My use case is that I am cleaning up some HTML used to build emails to create plaintext emails from the HTML.
Right now, I only really know how to create unicode from these entities when I need ASCII (I think) so that the plaintext email reads correctly with things like accented characters. I think a basic example is the html entity "& aacute;" or á being encoded into ASCII.
Furthermore, I'm not even 100% sure that ASCII is what I need for a plaintext email. As you can tell, I'm completely lost on this encoding stuff.
| [
"Here is a complete implementation that also handles unicode html entities. You might find it useful.\nIt returns a unicode string that is not ascii, but if you want plain ascii, you can modify the replace operations so that it replaces the entities to empty string.\ndef convert_html_entities(s):\n matches = re.... | [
8,
2,
1,
0
] | [] | [] | [
"ascii",
"python"
] | stackoverflow_0001197981_ascii_python.txt |
Q:
Pylons formencode - How do I POST an array of data?
I have a form that is similar to the following:
Enter Name:
Enter Age:
[add more]
That add more field copies the Name and Age inputs and can be clicked as many times as the user wants. Potentially, they could end up submitting 50 sets of Name and Age data.
How can I handle this received data when it's posted to my Pylons application? I basically need to do something like:
for name, age in postedform:
print name + ' ' + age
I've come across formencode's variabledecode function. But can't for the life of me figure out how to use it :/
Cheers.
A:
You would post something like this (URL encoded, of course)
users-0.name=John
users-0.age=21
users-1.name=Mike
users-1.age=30
...
Do that for users 0-N where N is as many users as you have, zero-indexed. Then, on the Python side after you run this through variabledecode, you'll have:
users = UserSchema.to_python(request.POST)
print users
# prints this:
{'Users': [{'name': 'John', 'age': '21'}, {'name': 'Mike', 'age': '30'}]}
The values may differ depending on the validation you have going on in your schema. So to get what you're looking for, you would then do:
for user in users.iteritems():
print "{name} {age}".format(**user)
Update
To embed a list within an dictionary, you would do this:
users-0.name=John
users-0.age=21
users-0.hobbies-0=snorkeling
users-0.hobbies-1=billiards
users-1.name=Mike
...
So on and so forth. The pattern basically repeats itself: {name-N} will embed the Nth index in a list, starting with 0. Be sure that it starts with 0 and that the values are consecutive. A . starts the beginning of a property, which can be a scalar, a list, or a dictionary.
This is Pylons-specific documentation of how to use formencode, look at table 6-3 for an example.
| Pylons formencode - How do I POST an array of data? | I have a form that is similar to the following:
Enter Name:
Enter Age:
[add more]
That add more field copies the Name and Age inputs and can be clicked as many times as the user wants. Potentially, they could end up submitting 50 sets of Name and Age data.
How can I handle this received data when it's posted to my Pylons application? I basically need to do something like:
for name, age in postedform:
print name + ' ' + age
I've come across formencode's variabledecode function. But can't for the life of me figure out how to use it :/
Cheers.
| [
"You would post something like this (URL encoded, of course)\nusers-0.name=John\nusers-0.age=21\nusers-1.name=Mike\nusers-1.age=30\n...\n\nDo that for users 0-N where N is as many users as you have, zero-indexed. Then, on the Python side after you run this through variabledecode, you'll have:\nusers = UserSchema.to... | [
1
] | [] | [] | [
"arrays",
"formencode",
"pylons",
"python"
] | stackoverflow_0003429348_arrays_formencode_pylons_python.txt |
Q:
getting a list of files in a custom directory using glob()
Im trying to write a program that renames files when a use input their own custom file directory.
I'm at a very early part of it. And this is my first time using the OS and glob commands.
My code is below. However when I tried running that, the result was an empty list. I tried typing a file root directory into the glob command directly, it somehow works, but the result isn't what I wanted.
Hope you guys can help me.
Thanks.
import os, glob
def fileDirectory():
#Asks the user for a file root directory
fileroot = raw_input("Please input the file root directory \n\n")
#Returns a list with all the files inside the file root directory
filelist = glob.glob(fileroot)
print filelist
fileDirectory()
A:
Python is white-space sensitive, so you need to make sure that everything you want inside the function is indented.
Stackoverflow has its own indentation requirements for code, which makes it hard to be sure what indentation your code originally had.
import os, glob
def fileDirectory():
#Asks the user for a file root directory
fileroot = raw_input("Please input the file root directory \n\n")
#Returns a list with all the files inside the file root directory
filelist = glob.glob(fileroot)
print filelist
fileDirectory()
The next thing is that glob returns a the results of a glob - it doesn't list a directory, which appears to be what you're trying to do.
Either you want os.listdir, or os.walk or you actually should ask for a glob expression rather than a directory.
Finally raw_input might give you some extra whitespace that you'll have to strip off. Check what fileroot is.
You might want to split up your program, so that you can investigate each function separately.
| getting a list of files in a custom directory using glob() | Im trying to write a program that renames files when a use input their own custom file directory.
I'm at a very early part of it. And this is my first time using the OS and glob commands.
My code is below. However when I tried running that, the result was an empty list. I tried typing a file root directory into the glob command directly, it somehow works, but the result isn't what I wanted.
Hope you guys can help me.
Thanks.
import os, glob
def fileDirectory():
#Asks the user for a file root directory
fileroot = raw_input("Please input the file root directory \n\n")
#Returns a list with all the files inside the file root directory
filelist = glob.glob(fileroot)
print filelist
fileDirectory()
| [
"Python is white-space sensitive, so you need to make sure that everything you want inside the function is indented.\nStackoverflow has its own indentation requirements for code, which makes it hard to be sure what indentation your code originally had.\nimport os, glob\ndef fileDirectory():\n #Asks the user for ... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0003429584_python.txt |
Q:
sort date objects in Python
I start out with date strings:
from operator import itemgetter
import datetime as DT
# unsorted dates
raw = (map(int, "2010-08-01".split("-")),
map(int, "2010-03-25".split("-")),
map(int, "2010-07-01".split("-")))
transactions = []
for year, month, day in raw:
new = (DT.date(year, month, day), "Some data here")
transactions.append(new)
# transactions is now a list with tuples nested inside, for example
# [(date, "Some data here"), (date, "Some data here")]
sorted(transactions, key=itemgetter(0))
for info in transactions:
print info
I get the following, and its not sorted according to date:
(datetime.date(2010, 8, 1), 'Some data here')
(datetime.date(2010, 3, 25), 'Some data here')
(datetime.date(2010, 7, 1), 'Some data here')
How do I sort these according to date?
A:
Well, the reason it's not sorted is that you haven't reassigned the sorted list back to transactions; you want:
transactions = sorted(transactions, key=itemgetter(0))
I should point out that datetime has a strptime function that does what you're doing manually:
transactions = [ ( DT.datetime.strptime( datestring, "%Y-%m-%d" ).date(), "Some data here" ) for datestring in datestrings ]
You might also prefer a collections.OrderedDict, although maybe not...
alt_transactions = collections.OrderedDict( sorted( transactions.items( ) ) )
A:
sorted returns a sorted list, but the input itself remains unmodified. Try
transactions.sort(key=itemgetter(0))
instead. (By default tuples are compared lexicographically, so you don't need the key).
A:
You should use sort method if you want to modify your original data, often it is better to preserve the original data and to sort by sorted() and assign the value in new variable.
transactions.sort()
The key itemgetter is unnecessary as you want normal sorting.
My version for your whole code:
import datetime as DT
# unsorted dates
raw = ("2010-08-01","2010-03-25","2010-07-01")
datetuples = [tuple(int(numstr) for numstr in dt.split('-'))
for dt in raw] ## numbers from strings
transactions = [(DT.date(* dateint),
"Some data here") for dateint in datetuples]
transactions.sort()
for info in transactions:
print info
| sort date objects in Python | I start out with date strings:
from operator import itemgetter
import datetime as DT
# unsorted dates
raw = (map(int, "2010-08-01".split("-")),
map(int, "2010-03-25".split("-")),
map(int, "2010-07-01".split("-")))
transactions = []
for year, month, day in raw:
new = (DT.date(year, month, day), "Some data here")
transactions.append(new)
# transactions is now a list with tuples nested inside, for example
# [(date, "Some data here"), (date, "Some data here")]
sorted(transactions, key=itemgetter(0))
for info in transactions:
print info
I get the following, and its not sorted according to date:
(datetime.date(2010, 8, 1), 'Some data here')
(datetime.date(2010, 3, 25), 'Some data here')
(datetime.date(2010, 7, 1), 'Some data here')
How do I sort these according to date?
| [
"Well, the reason it's not sorted is that you haven't reassigned the sorted list back to transactions; you want: \ntransactions = sorted(transactions, key=itemgetter(0))\n\nI should point out that datetime has a strptime function that does what you're doing manually:\ntransactions = [ ( DT.datetime.strptime( datest... | [
4,
3,
2
] | [] | [] | [
"date",
"object",
"python",
"sorting"
] | stackoverflow_0003429985_date_object_python_sorting.txt |
Q:
python regex to get all text until a (, and get text inside brackets
I need help with two regex operations.
Get all text until an open bracket.
e.g. 'this is so cool (234)' => 'this is so cool'
Get the text inside the brackets, so the number '234'
A:
Up until the paren: regex = re.compile("(.*?)\s*\(")
Inside the first set of parens: regex = re.compile(".*?\((.*?)\)")
Edit: Single regex version: regex = re.compile("(.*?)\s*\((.*?)\)")
Example output:
>>> import re
>>> r1 = re.compile("(.*?)\s*\(")
>>> r2 = re.compile(".*?\((.*?)\)")
>>> text = "this is so cool (234)"
>>> m1 = r1.match(text)
>>> m1.group(1)
'this is so cool'
>>> m2 = r2.match(text)
>>> m2.group(1)
'234'
>>> r3 = re.compile("(.*?)\s*\((.*?)\)")
>>> m3 = r3.match(text)
>>> m3.group(1)
'this is so cool'
>>> m3.group(2)
'234'
>>>
Note of course that this won't work right with multiple sets of parens, as it's only expecting one parenthesized block of text (as per your example). The language of matching opening/closing parens of arbitrary recurrence is not regular.
A:
Sounds to me like you could just do this:
re.findall('[^()]+', mystring)
Splitting would work, too:
re.split('[()]', mystring)
Either way, the text before the first parenthesis will be the first item in the resulting array, and the text inside the first set of parens will be the second item.
A:
No need for regular expression.
>>> s="this is so cool (234)"
>>> s.split("(")[0]
'this is so cool '
>>> s="this is so cool (234) test (123)"
>>> for i in s.split(")"):
... if "(" in i:
... print i.split("(")[-1]
...
234
123
A:
Here is my own library function version without regex.
def between(left,right,s):
before,_,a = s.partition(left)
a,_,after = a.partition(right)
return before,a,after
s="this is so cool (234)"
print('\n'.join(between('(',')',s)))
| python regex to get all text until a (, and get text inside brackets | I need help with two regex operations.
Get all text until an open bracket.
e.g. 'this is so cool (234)' => 'this is so cool'
Get the text inside the brackets, so the number '234'
| [
"Up until the paren: regex = re.compile(\"(.*?)\\s*\\(\")\nInside the first set of parens: regex = re.compile(\".*?\\((.*?)\\)\")\nEdit: Single regex version: regex = re.compile(\"(.*?)\\s*\\((.*?)\\)\")\nExample output:\n>>> import re\n>>> r1 = re.compile(\"(.*?)\\s*\\(\")\n>>> r2 = re.compile(\".*?\\((.*?)\\)\")\... | [
7,
3,
0,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0003429086_python_regex.txt |
Q:
Howto import a function with python
I'm developing a Python application for the GAE.
The application consists of a bunch of classes and functions which are at the moment all in the same file main.py.
The application is running without problems.
Now, I want to refactor the application and outsource all the classes. Every class should be in her own file. The files shall be arranged in directories like this:
main.py
/directory1/class1.py
/directory1/class2.py
/directory2/class1.py
My problem is that inside these outsourced classes, I cannot use the functions of main.py.
I tried this inside the class-files.
from main import name_of_function
But the compiler says
from main import name_of_function
ImportError: cannot import name name_of_function
What did I wrong?
The name of the funktion is login. Maybe this causes the problem?
A:
Try moving the extra functions from main.py into a separate file.
main.py
library.py # contains login() and other functions from main
/directory1/class1.py
/directory1/class2.py
/directory2/class1.py
A:
Sometimes it is good to leave classes in same module not separate without purpose if they belong together.
The problem of using function from main is sign that you should refactor one module say common_utils.py out of those functions and separate it from main. You can import that to your modules, which use those. Do not think classes only think whole use case.
If you could give pseudo code of your program's logic, we could check the refactoring better together.
| Howto import a function with python | I'm developing a Python application for the GAE.
The application consists of a bunch of classes and functions which are at the moment all in the same file main.py.
The application is running without problems.
Now, I want to refactor the application and outsource all the classes. Every class should be in her own file. The files shall be arranged in directories like this:
main.py
/directory1/class1.py
/directory1/class2.py
/directory2/class1.py
My problem is that inside these outsourced classes, I cannot use the functions of main.py.
I tried this inside the class-files.
from main import name_of_function
But the compiler says
from main import name_of_function
ImportError: cannot import name name_of_function
What did I wrong?
The name of the funktion is login. Maybe this causes the problem?
| [
"Try moving the extra functions from main.py into a separate file.\nmain.py\nlibrary.py # contains login() and other functions from main\n/directory1/class1.py\n/directory1/class2.py\n/directory2/class1.py\n\n",
"Sometimes it is good to leave classes in same module not separate without purpose if they belong toge... | [
2,
0
] | [] | [] | [
"function",
"google_app_engine",
"python"
] | stackoverflow_0003429874_function_google_app_engine_python.txt |
Q:
Using Pylons validate and authenticate_form decorator
The validate and authenticate_form decorators don't seem to play nice together. This is my template:
<html>
<title>Test</title>
<body>
${h.secure_form('/meow/do_post')}
<input type="text" name="dummy">
<form:error name="dummy"><br>
<input type="submit" name="doit" value="Do It">
${h.end_form()}
</body>
</html>
And this is the controller:
import logging
from pylons import request, response, session, tmpl_context as c, url
from pylons.controllers.util import abort, redirect
from ocust.lib.base import BaseController, render
import formencode
import formencode.validators
from formencode import htmlfill
from pylons.decorators import validate
from pylons.decorators.secure import authenticate_form
class MeowForm(formencode.Schema):
allow_extra_fields = True
dummy = formencode.validators.NotEmpty()
class MeowController(BaseController):
def index(self):
return render('/index.mako')
@authenticate_form
@validate(schema=MeowForm(), form='index')
def do_post(self):
return 'posted OK'
If validation fails, the form is re-rendered using htmlfill.render by the @validate decorator, but this strips out the authentication token, so a 403 CSRF detected error is shown the next time the form is submitted.
The authentication token seems to be stripped because @authenticate_form deletes the authentication token from request.POST.
If this is used instead:
@validate(schema=MeowForm(), form='index', force_defaults=False)
it works fine. Is there anything bad that can happen if force_defaults is set to False? The docs for htmlfill seem to recommend it be set to True when the defaults "are the result of a form submission".
A:
@validate(schema=MeowForm(), form='index')
@authenticate_form
def do_post(self):
You need to change order of decorators, authenticate decorator must be last
| Using Pylons validate and authenticate_form decorator | The validate and authenticate_form decorators don't seem to play nice together. This is my template:
<html>
<title>Test</title>
<body>
${h.secure_form('/meow/do_post')}
<input type="text" name="dummy">
<form:error name="dummy"><br>
<input type="submit" name="doit" value="Do It">
${h.end_form()}
</body>
</html>
And this is the controller:
import logging
from pylons import request, response, session, tmpl_context as c, url
from pylons.controllers.util import abort, redirect
from ocust.lib.base import BaseController, render
import formencode
import formencode.validators
from formencode import htmlfill
from pylons.decorators import validate
from pylons.decorators.secure import authenticate_form
class MeowForm(formencode.Schema):
allow_extra_fields = True
dummy = formencode.validators.NotEmpty()
class MeowController(BaseController):
def index(self):
return render('/index.mako')
@authenticate_form
@validate(schema=MeowForm(), form='index')
def do_post(self):
return 'posted OK'
If validation fails, the form is re-rendered using htmlfill.render by the @validate decorator, but this strips out the authentication token, so a 403 CSRF detected error is shown the next time the form is submitted.
The authentication token seems to be stripped because @authenticate_form deletes the authentication token from request.POST.
If this is used instead:
@validate(schema=MeowForm(), form='index', force_defaults=False)
it works fine. Is there anything bad that can happen if force_defaults is set to False? The docs for htmlfill seem to recommend it be set to True when the defaults "are the result of a form submission".
| [
"@validate(schema=MeowForm(), form='index')\n@authenticate_form\ndef do_post(self):\n\nYou need to change order of decorators, authenticate decorator must be last\n"
] | [
2
] | [] | [] | [
"formencode",
"htmlfill",
"pylons",
"python"
] | stackoverflow_0002981555_formencode_htmlfill_pylons_python.txt |
Q:
pymacs: General question and Installation problem
I am trying to setup emacs for python development.
From what I read, it is recommended to use python-mode.el rather than the default python.el from Emacs 22.3. So I embark on the new adventure.
From what I understand, python-mode has the several dependencies, so I need to install rope, ropemode and ropemacs. Then on top of that I need to install pymacs.
Q: is it correct?
This is my new .emacs now:
(custom-set-variables
;; custom-set-variables was added by Custom.
;; If you edit it by hand, you could mess it up, so be careful.
;; Your init file should contain only one such instance.
;; If there is more than one, they won't work right.
'(inhibit-startup-screen t)
'(tab-width 4))
(custom-set-faces
;; custom-set-faces was added by Custom.
;; If you edit it by hand, you could mess it up, so be careful.
;; Your init file should contain only one such instance.
;; If there is more than one, they won't work right.
)
(setq emacs-config-path "~/.emacs.d/")
(setq base-lisp-path "~/.emacs.d/site-lisp/")
(setq site-lisp-path (concat emacs-config-path "/site-lisp"))
(defun add-path (p)
(add-to-list 'load-path (concat base-lisp-path p)))
(add-path "")
(add-to-list 'load-path "~/.emacs.d")
(require 'psvn)
;; python-mode
;;
(setq auto-mode-alist (cons '("\\.py$" . python-mode) auto-mode-alist))
(setq interpreter-mode-alist (cons '("python" . python-mode) interpreter-mode-alist))
(autoload 'python-mode "python-mode" "Python editing mode." t)
(setq pymacs-load-path '( "~/.emacs.d/site-lisp/rope"
"~/.emacs.d/site-lisp/ropemode"
"~/.emacs.d/site-lisp/ropemacs"))
(setq interpreter-mode-alist
(cons '("python" . python-mode)
interpreter-mode-alist)
python-mode-hook
'(lambda () (progn
(set-variable 'py-indent-offset 4)
(set-variable 'py-smart-indentation nil)
(set-variable 'indent-tabs-mode nil)
;;(highlight-beyond-fill-column)
(define-key python-mode-map "\C-m" 'newline-and-indent)
(pabbrev-mode)
(abbrev-mode)
)
)
)
;; pymacs
(autoload 'pymacs-apply "pymacs")
(autoload 'pymacs-call "pymacs")
(autoload 'pymacs-eval "pymacs" nil t)
(autoload 'pymacs-exec "pymacs" nil t)
(autoload 'pymacs-load "pymacs" nil t)
;; Search local path for emacs rope
;;
;; enable pymacs
;;
(require 'pymacs)
(pymacs-load "ropemacs" "rope-")
Now, when i start emacs, I got this error message:
("C:\\opt\\emacs-22.3\\bin\\emacs.exe")
Loading encoded-kb...done
Loading regexp-opt...done
Loading easy-mmode...done
Loading wid-edit...done
Loading edmacro...done
Loading derived...done
Loading advice...done
Loading cl-macs...done
Loading byte-opt...done
An error has occurred while loading `c:/opt/cygwin/home/akong/.emacs':
File error: Cannot open load file, pymacs
To ensure normal operation, you should investigate and remove the
cause of the error in your initialization file. Start Emacs with
the `--debug-init' option to view a complete error backtrace.
For information about GNU Emacs and the GNU system, type C-h C-a. [2 times]
To make it slightly more complicated:
For work reason I have to use python 2.4, but I have python 2.6 installed on my PC. But obviously rope does not like 2.4 so I did not run setup.py. I untar/unzip these packages and put these files under ~/.emacs.d/site-lisp. By default if python is invoked in command prompt, it is the python 2.4 executable.
Q: How can I successfully load 'pymacs'?
A:
I have never used pymacs so far, but one thing which catches my eye when I look at your .emacs is that you apparently didn't add the pymacs directory to the emacs load-path but only to the pymacs one:
(setq pymacs-load-path '( "~/.emacs.d/site-lisp/rope"
"~/.emacs.d/site-lisp/ropemode"
"~/.emacs.d/site-lisp/ropemacs"))
You will probably need also something like:
(add-to-list 'load-path "~/.emacs.d/site-lisp/rope")
(add-to-list 'load-path "~/.emacs.d/site-lisp/ropemode")
(add-to-list 'load-path "~/.emacs.d/site-lisp/ropemacs")
(or whereever you have pymacs.el) so that emacs can find the lisp files. Also mentioned in the pymacs documentation
2.4 Install the Pymacs proper ... for the Emacs part ...
This is usually done by hand now.
First select some directory along the
list kept in your Emacs load-path, for
which you have write access, and copy
file pymacs.el in that directory.
A:
It turns out I missed these two:
(add-to-list 'load-path "~/.emacs.d/site-lisp/Pymacs-0.23")
Obviously I need to load the pymac script.
And I have set the env var PYMACS_PYTHON to python 2.6 because I am using python 2.4 as default python interpreter, for work reason.
A:
If paths are missing then this will easily be spotted in the startup log or by getting a backtrace at emacs start. If in doubt M-x load-library is the way to go.
I too am getting company-ropemacs refusing to load with both emacs 23 and emacs 24 after latest Debian Testing updates which then means you can not save files because of rope save hooks. I would be interested to hear from anyone with it working. company-ropemacs and python in general with emacs has been a thorn for some time now. I intend to try and debug it some more later and will update this thread then.
| pymacs: General question and Installation problem | I am trying to setup emacs for python development.
From what I read, it is recommended to use python-mode.el rather than the default python.el from Emacs 22.3. So I embark on the new adventure.
From what I understand, python-mode has the several dependencies, so I need to install rope, ropemode and ropemacs. Then on top of that I need to install pymacs.
Q: is it correct?
This is my new .emacs now:
(custom-set-variables
;; custom-set-variables was added by Custom.
;; If you edit it by hand, you could mess it up, so be careful.
;; Your init file should contain only one such instance.
;; If there is more than one, they won't work right.
'(inhibit-startup-screen t)
'(tab-width 4))
(custom-set-faces
;; custom-set-faces was added by Custom.
;; If you edit it by hand, you could mess it up, so be careful.
;; Your init file should contain only one such instance.
;; If there is more than one, they won't work right.
)
(setq emacs-config-path "~/.emacs.d/")
(setq base-lisp-path "~/.emacs.d/site-lisp/")
(setq site-lisp-path (concat emacs-config-path "/site-lisp"))
(defun add-path (p)
(add-to-list 'load-path (concat base-lisp-path p)))
(add-path "")
(add-to-list 'load-path "~/.emacs.d")
(require 'psvn)
;; python-mode
;;
(setq auto-mode-alist (cons '("\\.py$" . python-mode) auto-mode-alist))
(setq interpreter-mode-alist (cons '("python" . python-mode) interpreter-mode-alist))
(autoload 'python-mode "python-mode" "Python editing mode." t)
(setq pymacs-load-path '( "~/.emacs.d/site-lisp/rope"
"~/.emacs.d/site-lisp/ropemode"
"~/.emacs.d/site-lisp/ropemacs"))
(setq interpreter-mode-alist
(cons '("python" . python-mode)
interpreter-mode-alist)
python-mode-hook
'(lambda () (progn
(set-variable 'py-indent-offset 4)
(set-variable 'py-smart-indentation nil)
(set-variable 'indent-tabs-mode nil)
;;(highlight-beyond-fill-column)
(define-key python-mode-map "\C-m" 'newline-and-indent)
(pabbrev-mode)
(abbrev-mode)
)
)
)
;; pymacs
(autoload 'pymacs-apply "pymacs")
(autoload 'pymacs-call "pymacs")
(autoload 'pymacs-eval "pymacs" nil t)
(autoload 'pymacs-exec "pymacs" nil t)
(autoload 'pymacs-load "pymacs" nil t)
;; Search local path for emacs rope
;;
;; enable pymacs
;;
(require 'pymacs)
(pymacs-load "ropemacs" "rope-")
Now, when i start emacs, I got this error message:
("C:\\opt\\emacs-22.3\\bin\\emacs.exe")
Loading encoded-kb...done
Loading regexp-opt...done
Loading easy-mmode...done
Loading wid-edit...done
Loading edmacro...done
Loading derived...done
Loading advice...done
Loading cl-macs...done
Loading byte-opt...done
An error has occurred while loading `c:/opt/cygwin/home/akong/.emacs':
File error: Cannot open load file, pymacs
To ensure normal operation, you should investigate and remove the
cause of the error in your initialization file. Start Emacs with
the `--debug-init' option to view a complete error backtrace.
For information about GNU Emacs and the GNU system, type C-h C-a. [2 times]
To make it slightly more complicated:
For work reason I have to use python 2.4, but I have python 2.6 installed on my PC. But obviously rope does not like 2.4 so I did not run setup.py. I untar/unzip these packages and put these files under ~/.emacs.d/site-lisp. By default if python is invoked in command prompt, it is the python 2.4 executable.
Q: How can I successfully load 'pymacs'?
| [
"I have never used pymacs so far, but one thing which catches my eye when I look at your .emacs is that you apparently didn't add the pymacs directory to the emacs load-path but only to the pymacs one:\n(setq pymacs-load-path '( \"~/.emacs.d/site-lisp/rope\"\n \"~/.emacs.d/site-lisp/ropemod... | [
1,
1,
1
] | [] | [] | [
"emacs",
"pymacs",
"python",
"rope"
] | stackoverflow_0001078069_emacs_pymacs_python_rope.txt |
Q:
is this code useful?
def _oauth_escape(val):
if isinstance(val, unicode):# useful ?
val = val.encode("utf-8")#useful ?
return urllib.quote(val, safe="~")
i think it is not useful ,
yes ??
updated
i think unicode is ‘utf-8’ ,yes ?
A:
utf-8 is an encoding, a recipe for concretely representing unicode data as a series of bytes. This is one of many such encodings. Python str objects are bytestrings, which can represent arbitrary binary data, such as text in a specific encoding.
Python's unicode type is an abstract, not-encoded way to represent text. unicode strings can be encoded in any of many encodings.
A:
As others have said already, unicode and utf-8 are not the same. Utf-8 is one of many encodings for unicode.
Think of unicode objects as "unencoded" unicode strings, while string objects are encoded in a particular encoding (unfortunately, string objects don't have an attribute that tells you how they are encoded).
val.encode("utf-8") converts this unicode object into an utf-8 encoded string object.
In Python 2.6, this is necessary, as urllib can't handle unicode properly.
>>> import urllib
>>> urllib.quote(u"")
''
>>> urllib.quote(u"ä")
/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/urllib.py:1216: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
res = map(safe_map.__getitem__, s)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/urllib.py", line 1216, in quote
res = map(safe_map.__getitem__, s)
KeyError: u'\xe4'
>>> urllib.quote(u"ä".encode("utf-8"))
'%C3%A4'
Python 3.x however, where all strings are unicode (the Python 3 equivalent to an encoded string is a bytes object), it is not necessary anymore.
>>> import urllib.parse
>>> urllib.parse.quote("ä")
'%C3%A4'
A:
In Python 3.0 all strings support Unicode, but with previous versions one has to explicitly encode strings to Unicode strings. Could that be it?
(utf-8 is not the only, but the most common encoding for Unicode. Read this.)
| is this code useful? | def _oauth_escape(val):
if isinstance(val, unicode):# useful ?
val = val.encode("utf-8")#useful ?
return urllib.quote(val, safe="~")
i think it is not useful ,
yes ??
updated
i think unicode is ‘utf-8’ ,yes ?
| [
"utf-8 is an encoding, a recipe for concretely representing unicode data as a series of bytes. This is one of many such encodings. Python str objects are bytestrings, which can represent arbitrary binary data, such as text in a specific encoding.\nPython's unicode type is an abstract, not-encoded way to represent t... | [
1,
1,
0
] | [] | [] | [
"encode",
"python"
] | stackoverflow_0002880499_encode_python.txt |
Q:
Demonstrating instruction level parallelism at work
I'm trying to show instruction level parallelism at work. What I was originally doing was using python (willing to change) and doing the following:
def test():
for i in range(5000):
j = 0
k = 0
l = 0
def test2():
for i in range(5000):
j = i * i
k = j * 2
l = k * i
if __name__=='__main__':
from timeit import Timer
t = Timer("test()", "from __main__ import test")
print t.timeit()
t2 = Timer("test2()", "from __main__ import test2")
print t2.timeit()
However a professor tells me that this doesn't demonstrate ILP, rather it shows whether the python interpreter is optimized or not.
What is it that I can do to demonstrate working ILP?
A:
Your professor is correct. I think an acceptable demonstration would have to be written in assembler, or at most C/C++, possibly using something like the MMX instruction set.
A:
There is a chance that your professor might be correct -- you might prove him wrong if you could show that cpython is actually using ILP to do that, but I don't think it's worth it.
On the other hand, ILP is fairly hardware-bound and it is rarely, if ever, actually done by the programmer explicitly, so if you did it in C++ or ASM the best you could show is that the compiler (or the assembler) is optimized. My bet is that the snippet you've written is the kind of thing he's looking for, but he just doesn't agree to your language.
Like pjc50 above, I don't think this is actually an acceptable example of ILP but it might just cut it and get your grade right. If you are not actually looking only for the grade, perhaps this might be of assistance: http://developer.apple.com/hardwaredrivers/ve/software_pipelining.html .
A:
mingw by default doesn't add any optimizations. so what i did was use some C code and because there are no loop optimizations, it showed ILP working
| Demonstrating instruction level parallelism at work | I'm trying to show instruction level parallelism at work. What I was originally doing was using python (willing to change) and doing the following:
def test():
for i in range(5000):
j = 0
k = 0
l = 0
def test2():
for i in range(5000):
j = i * i
k = j * 2
l = k * i
if __name__=='__main__':
from timeit import Timer
t = Timer("test()", "from __main__ import test")
print t.timeit()
t2 = Timer("test2()", "from __main__ import test2")
print t2.timeit()
However a professor tells me that this doesn't demonstrate ILP, rather it shows whether the python interpreter is optimized or not.
What is it that I can do to demonstrate working ILP?
| [
"Your professor is correct. I think an acceptable demonstration would have to be written in assembler, or at most C/C++, possibly using something like the MMX instruction set.\n",
"There is a chance that your professor might be correct -- you might prove him wrong if you could show that cpython is actually using ... | [
3,
1,
0
] | [] | [] | [
"parallel_processing",
"python"
] | stackoverflow_0003405640_parallel_processing_python.txt |
Q:
FastCGI, Apache, Django and 500 Error
I am getting 500 Internal error with Apache and FastCGI. Spent the whole day to find the reason :-/
/etc/apache2/vhost.d/mysite.conf
FastCGIExternalServer /home/me/web/mysite.fcgi -socket /home/me/web/mysite.sock
Listen 80
<VirtualHost *:80>
ServerName os.me #That's my localhost machine
DocumentRoot /home/me/web
Alias /media/ /home/me/develop/projects/media
<Directory "/home/me/web">
AllowOverride All
Allow from all
Order allow,deny
</Directory>
</VirtualHost>
/home/me/web/.htaccess
Options +Indexes +FollowSymlinks
AddHandler fastcgi-script .fcgi
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ mysite.fcgi/$1 [QSA,L]
/home/me/web/mysite.fcgi
#!/usr/bin/python
import sys, os
os.chdir("/home/me/develop/projects/mysite")
os.environ['DJANGO_SETTINGS_MODULE'] = "mysite.settings"
from django.core.servers.fastcgi import runfastcgi
runfastcgi(method="threaded",daemonize="false")
/var/log/apache2/error_log
...
[Sat Aug 07 01:41:13 2010] [error] [client 127.0.0.1] (2)No such file or directory: FastCGI: failed to connect to server "/home/me/web/mysite.fcgi": connect() failed
[Sat Aug 07 01:41:13 2010] [error] [client 127.0.0.1] FastCGI: incomplete headers (0 bytes) received from server "/home/me/web/mysite.fcgi"
Executing of .fcgi file (it works as html page got status "200 OK" and was rendered as it should be):
me@os ~/web $ python mysite.fcgi
WSGIServer: missing FastCGI param REQUEST_METHOD required by WSGI!
WSGIServer: missing FastCGI param SERVER_NAME required by WSGI!
WSGIServer: missing FastCGI param SERVER_PORT required by WSGI!
WSGIServer: missing FastCGI param SERVER_PROTOCOL required by WSGI!
Status: 200 OK
Content-Type: text/html
...
A:
See
http://iamtgc.com/2007/07/04/django-on-lighttpd-with-fastcgi/
WSGIServer errors when trying to run Django app
A:
Thanks to help from #django irc channel (specially to zk).
FastCGIExternalServer /home/me/web/mysite.fcgi -socket /home/me/web/mysite.sock
Must be changed to (as apache should spawn fcgi processes itself):
FastCGIServer /home/me/web/mysite.fcgi -socket /home/me/web/mysite.sock
| FastCGI, Apache, Django and 500 Error | I am getting 500 Internal error with Apache and FastCGI. Spent the whole day to find the reason :-/
/etc/apache2/vhost.d/mysite.conf
FastCGIExternalServer /home/me/web/mysite.fcgi -socket /home/me/web/mysite.sock
Listen 80
<VirtualHost *:80>
ServerName os.me #That's my localhost machine
DocumentRoot /home/me/web
Alias /media/ /home/me/develop/projects/media
<Directory "/home/me/web">
AllowOverride All
Allow from all
Order allow,deny
</Directory>
</VirtualHost>
/home/me/web/.htaccess
Options +Indexes +FollowSymlinks
AddHandler fastcgi-script .fcgi
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ mysite.fcgi/$1 [QSA,L]
/home/me/web/mysite.fcgi
#!/usr/bin/python
import sys, os
os.chdir("/home/me/develop/projects/mysite")
os.environ['DJANGO_SETTINGS_MODULE'] = "mysite.settings"
from django.core.servers.fastcgi import runfastcgi
runfastcgi(method="threaded",daemonize="false")
/var/log/apache2/error_log
...
[Sat Aug 07 01:41:13 2010] [error] [client 127.0.0.1] (2)No such file or directory: FastCGI: failed to connect to server "/home/me/web/mysite.fcgi": connect() failed
[Sat Aug 07 01:41:13 2010] [error] [client 127.0.0.1] FastCGI: incomplete headers (0 bytes) received from server "/home/me/web/mysite.fcgi"
Executing of .fcgi file (it works as html page got status "200 OK" and was rendered as it should be):
me@os ~/web $ python mysite.fcgi
WSGIServer: missing FastCGI param REQUEST_METHOD required by WSGI!
WSGIServer: missing FastCGI param SERVER_NAME required by WSGI!
WSGIServer: missing FastCGI param SERVER_PORT required by WSGI!
WSGIServer: missing FastCGI param SERVER_PROTOCOL required by WSGI!
Status: 200 OK
Content-Type: text/html
...
| [
"See \n\nhttp://iamtgc.com/2007/07/04/django-on-lighttpd-with-fastcgi/\nWSGIServer errors when trying to run Django app\n\n",
"Thanks to help from #django irc channel (specially to zk). \nFastCGIExternalServer /home/me/web/mysite.fcgi -socket /home/me/web/mysite.sock\n\nMust be changed to (as apache should spawn ... | [
1,
1
] | [] | [] | [
"apache",
"django",
"fastcgi",
"python"
] | stackoverflow_0003428384_apache_django_fastcgi_python.txt |
Q:
is json package included in Python for Windows?
is json package included in Python for Windows?
A:
Yes, the json module is part of the Python standard library since version 2.6. All standard Python library modules are available on all platforms unless specifically indicated otherwise.
| is json package included in Python for Windows? | is json package included in Python for Windows?
| [
"Yes, the json module is part of the Python standard library since version 2.6. All standard Python library modules are available on all platforms unless specifically indicated otherwise.\n"
] | [
2
] | [] | [] | [
"json",
"python",
"windows"
] | stackoverflow_0003430701_json_python_windows.txt |
Q:
MVC Webframeworks
Possible Duplicate:
Choosing a Java Web Framework now?
I know that Ruby-on-Rails and Django are 2 MVC oriented webframeworks, in Ruby and Python respectively. Are there any other MVC frameworks ? Any MVC frameworks that use Java ?
A:
Something closer to rails in Java (well, not really Java) would be Grails.
Of course you'd need Groovy to use that, but it's worth a shot.
A:
CakePHP is a PHP MVC framework that's fairly simple to use.
A:
Spring MVC and Struts are two popular MVC web frameworks for Java.
| MVC Webframeworks |
Possible Duplicate:
Choosing a Java Web Framework now?
I know that Ruby-on-Rails and Django are 2 MVC oriented webframeworks, in Ruby and Python respectively. Are there any other MVC frameworks ? Any MVC frameworks that use Java ?
| [
"Something closer to rails in Java (well, not really Java) would be Grails.\nOf course you'd need Groovy to use that, but it's worth a shot.\n",
"CakePHP is a PHP MVC framework that's fairly simple to use.\n",
"Spring MVC and Struts are two popular MVC web frameworks for Java.\n"
] | [
3,
1,
0
] | [] | [] | [
"django",
"java",
"model_view_controller",
"python",
"ruby_on_rails"
] | stackoverflow_0003430780_django_java_model_view_controller_python_ruby_on_rails.txt |
Q:
Select columns of data from .txt to .csv
I am quite new to python (well more like I've only been using it for the past week). My task seems fairly simple, yet I am struggling. I have several large text files each with many columns of data in them from different regions. I would like to take the data from one text file and extract only the columns of data that I need and write it into a new .csv file. Currently they are tab delimitated but I would like the output to be comma delimitated.
I have:
#YY MM DD hh mm WVHT SwH SwP WWH WWP SwD WWD MWD
#yr mo dy hr mn m m sec m sec - degT degT
2010 07 16 17 00 0.5 0.5 5.0 0.3 4.0 SSE SSE 163
2010 07 16 16 00 0.6 0.5 5.9 0.3 3.8 SSE SSE 165
2010 07 16 15 00 0.5 0.5 6.7 0.3 3.6 SSE SW 151
2010 07 16 14 00 0.6 0.5 5.6 0.3 3.8 SSE SSE 153
I only want to keep: DD, WVHT, and MWD
Thanks in advance,
Harper
A:
You need to format this question a little more legibly. :)
Take a look at the python csv module for writing your csv files from your now-stored data: http://docs.python.org/library/csv.html
EDIT: Here's some better, more concise code, based on comments + csv module:
import csv
csv_out = csv.writer(open('out.csv', 'w'), delimiter=',')
f = open('myfile.txt')
for line in f:
vals = line.split('\t')
# DD, WVHT, MWD
csv_out.writerow(vals[2], vals[5], vals[12])
f.close()
A:
One easy way to achieve this is by using the csv module in the standard library.
First, create a CSVReader and a CSVWriter object:
>>> import csv
>>> csv_in = csv.reader(open('eggs.txt', 'rb'), delimiter='\t')
>>> csv_out = csv.writer(open('spam.csv', 'w'), delimiter=',')
Then just put the information you want into the new csv file.
>>> for line in csv_in:
... csv_out.writerow(line[2], line[5], line[-1])
A:
One of the problems appears to be that all of your data is on a single line:
2010 07 16 17 00 0.5 0.5 5.0 0.3 4.0 SSE SSE 163 2010 07 16 16 00 0.6 0.5 5.9 0.3 3.8 SSE SSE 165 2010 07 16 15 00 0.5 0.5 6.7 0.3 3.6 SSE SW 151 2010 07 16 14 00 0.6 0.5 5.6 0.3 3.8 SSE SSE 153
If this is the case, you will need to split the input line up. If you know your data are regular, then you could be sneaky and split on the 2010:
f = open('data.txt')
for line in f:
for portion in line.split(' 2010') #space is significant
# write to csv
If your data span multiple years, then Python itertools module can be very handy. I often find myself using the grouper recipe.
import csv
from itertools import izip_longest
csv_writer = csv.writer(open('eggs.csv', 'wb'), delimiter=',')
def grouper(n, iterable, fillvalue=None):
"""
>>> grouper(3, 'ABCDEFG', 'x')
['ABC', 'DEF', 'Gxx']
"""
args = [iter(iterable)] * n
return izip_longest(fillvalue=fillvalue, *args)
f = open('spam.txt')
for line in grouper(22, f.split('\t')):
csv_writer.writerow(line[2], line[12])
A:
Here is a basic thing since it is a basic need and since there is no extensive use of csv, here's a snippet without the csv module.
DD = 2
WVHT = 5
MWD = 12
INPUT = "input.txt"
OUTPUT = "output.csv"
from os import linesep
def main():
t = []
fi = open(INPUT)
fo = open(OUTPUT, "w")
try:
for line in fi.xreadlines():
line = line.split()
t.append("%s,%s,%s" %(line[DD], line[WVHT], line[MWD]))
fo.writelines(linesep.join(t))
finally:
fi.close()
fo.close()
if __name__ == "__main__":
main()
| Select columns of data from .txt to .csv | I am quite new to python (well more like I've only been using it for the past week). My task seems fairly simple, yet I am struggling. I have several large text files each with many columns of data in them from different regions. I would like to take the data from one text file and extract only the columns of data that I need and write it into a new .csv file. Currently they are tab delimitated but I would like the output to be comma delimitated.
I have:
#YY MM DD hh mm WVHT SwH SwP WWH WWP SwD WWD MWD
#yr mo dy hr mn m m sec m sec - degT degT
2010 07 16 17 00 0.5 0.5 5.0 0.3 4.0 SSE SSE 163
2010 07 16 16 00 0.6 0.5 5.9 0.3 3.8 SSE SSE 165
2010 07 16 15 00 0.5 0.5 6.7 0.3 3.6 SSE SW 151
2010 07 16 14 00 0.6 0.5 5.6 0.3 3.8 SSE SSE 153
I only want to keep: DD, WVHT, and MWD
Thanks in advance,
Harper
| [
"You need to format this question a little more legibly. :)\nTake a look at the python csv module for writing your csv files from your now-stored data: http://docs.python.org/library/csv.html\nEDIT: Here's some better, more concise code, based on comments + csv module:\nimport csv\n\ncsv_out = csv.writer(open('out.... | [
2,
0,
0,
0
] | [] | [] | [
"csv",
"python",
"text"
] | stackoverflow_0003429277_csv_python_text.txt |
Q:
python package for distributed auction simulation
Does anyone know of a package that allows for a distributed agent-based double auction simulation?
I've looked at SimPy, but that's a discrete-event simulator and difficult to get working in a distributed fashion.
regs,
Vivek
A:
You're welcome to try my own GarlicSim. If I understand your need correctly, it will work well for you.
The official website is here, the documentation is here, and there's a blog here.
If you'll need help or have questions, you can email me directly or use the mailing lists. I'll help you get your double-auction simpack up and running.
| python package for distributed auction simulation | Does anyone know of a package that allows for a distributed agent-based double auction simulation?
I've looked at SimPy, but that's a discrete-event simulator and difficult to get working in a distributed fashion.
regs,
Vivek
| [
"You're welcome to try my own GarlicSim. If I understand your need correctly, it will work well for you. \nThe official website is here, the documentation is here, and there's a blog here.\nIf you'll need help or have questions, you can email me directly or use the mailing lists. I'll help you get your double-aucti... | [
2
] | [] | [] | [
"distributed",
"python",
"simulation"
] | stackoverflow_0003430360_distributed_python_simulation.txt |
Q:
Django update table
obj = Info(name= sub,question=response_dict["question"])
obj.save()
After saving the data how to update another field of the same table
obj.err_flag=1
obj.update()//Will this work
A:
Just resave that instance:
obj.some_field = some_var
obj.save()
Django automatically knows when to UPDATE vs. INSERT your instance in the database.
This is explained in the
Django docs.
A:
obj = Info(name=sub,question=response_dict["question"])
obj.save()
And then later you want to get it and update it (I'm assuming name is unique identifier):
obj = Info.objects.get(name=sub)
obj.err_flag=1
obj.save()
A:
If in the question you mean to say same object or same row where you say same table, then if you do this
obj = Info(name= sub,question=response_dict["question"])
obj.save()
and then after a few lines you need to do this
obj = Info.objects.get(name=sub)
obj.err_flag=1
obj.save()
then obj = Info.objects.get(name=sub) is unnecessary.
You simply do
obj = Info(name= sub,question=response_dict["question"])
obj.save()
#
#do what you want to do, check what you want to check
#
obj.err_flag=1
obj.save()
| Django update table | obj = Info(name= sub,question=response_dict["question"])
obj.save()
After saving the data how to update another field of the same table
obj.err_flag=1
obj.update()//Will this work
| [
"Just resave that instance:\nobj.some_field = some_var\nobj.save()\n\nDjango automatically knows when to UPDATE vs. INSERT your instance in the database.\nThis is explained in the \nDjango docs.\n",
"obj = Info(name=sub,question=response_dict[\"question\"])\nobj.save()\n\nAnd then later you want to get it and upd... | [
7,
3,
2
] | [] | [] | [
"django",
"django_models",
"django_templates",
"django_views",
"python"
] | stackoverflow_0003430432_django_django_models_django_templates_django_views_python.txt |
Q:
Stop SQL query in python
Is there a way to let the user stop the execution of a sql query in python if it takes some long time? I am thinking of using a progress bar with a cancel button, but I wonder if there is a way to stop it in a clean way instead of killing abruptly the associated thread? (I am using both pysqlite2 and MySQLdb packages)
A:
the only solution i see is to get the process id:
SHOW PROCESSLIST;
and kill it:
KILL <thread_id>;
i would execute those commands with mysqldb.
However, you should be carefull about the rollback. See for example:
If I stop a long running query, does it rollback?
hope it helps
| Stop SQL query in python | Is there a way to let the user stop the execution of a sql query in python if it takes some long time? I am thinking of using a progress bar with a cancel button, but I wonder if there is a way to stop it in a clean way instead of killing abruptly the associated thread? (I am using both pysqlite2 and MySQLdb packages)
| [
"the only solution i see is to get the process id:\nSHOW PROCESSLIST;\n\nand kill it:\nKILL <thread_id>;\n\ni would execute those commands with mysqldb.\nHowever, you should be carefull about the rollback. See for example:\nIf I stop a long running query, does it rollback?\nhope it helps\n"
] | [
3
] | [] | [] | [
"python",
"sql"
] | stackoverflow_0003431323_python_sql.txt |
Q:
Where does django dev server (manage.py runserver) get its path from?
I recently moved a django app from c:\Users\user\django-projects\foo\foobar to c:\Python25\Lib\site-packages\foo\foobar (which is on the python path). I started a new app in the django-projects directory, and added foo.foobar to the INSTALLED_APPS setting. When I try to run the dev server (manage.py runserver) for my new app, I get the error ImportError: No module named foobar.
Looking through the traceback, it's looking in the c:\Users\user\django-projects\foo\..\foo\foobar for the foobar app. I checked my PATH and PYTHONPATH environment variables, and neither point to c:\Users\user\django-projects\foo and It doesn't show up in sys.path when I run the python interpreter.
I'm guessing I somehow added c:\Users\user\django-projects\foo to django's path sometime along the development of foo but I don't remember how I did it.
So, with all that lead up, my question is "how do I make manage.py look in c:\Python25\Lib\site-packages instead of c:\Users\user\django-projects\foo?"
Thanks,
Lexo
A:
manage.py imports settings.py from the current directory and pass settings as parameter to execute_manager. You probably defined project root in settings.py.
A:
I fixed it, although I don't know which solution worked. First, I deleted the .pyc files from my project, then I reindexed my Windows search (I'm guessing this did it). This changed the error message to the correct directory. After which, i realized I had
from baz import settings
in my foobar/baz/models.py file, which was causing the problem all along. I changed this to
import settings
which fixed the problem. Thanks to laurent for all your help :-)
| Where does django dev server (manage.py runserver) get its path from? | I recently moved a django app from c:\Users\user\django-projects\foo\foobar to c:\Python25\Lib\site-packages\foo\foobar (which is on the python path). I started a new app in the django-projects directory, and added foo.foobar to the INSTALLED_APPS setting. When I try to run the dev server (manage.py runserver) for my new app, I get the error ImportError: No module named foobar.
Looking through the traceback, it's looking in the c:\Users\user\django-projects\foo\..\foo\foobar for the foobar app. I checked my PATH and PYTHONPATH environment variables, and neither point to c:\Users\user\django-projects\foo and It doesn't show up in sys.path when I run the python interpreter.
I'm guessing I somehow added c:\Users\user\django-projects\foo to django's path sometime along the development of foo but I don't remember how I did it.
So, with all that lead up, my question is "how do I make manage.py look in c:\Python25\Lib\site-packages instead of c:\Users\user\django-projects\foo?"
Thanks,
Lexo
| [
"manage.py imports settings.py from the current directory and pass settings as parameter to execute_manager. You probably defined project root in settings.py.\n",
"I fixed it, although I don't know which solution worked. First, I deleted the .pyc files from my project, then I reindexed my Windows search (I'm gues... | [
1,
1
] | [] | [] | [
"devserver",
"django",
"django_manage.py",
"path",
"python"
] | stackoverflow_0003411131_devserver_django_django_manage.py_path_python.txt |
Q:
How do I write only certain lines to a file in Python?
I have a file that looks like this(have to put in code box so it resembles file):
text
(starts with parentheses)
tabbed info
text
(starts with parentheses)
tabbed info
...repeat
I want to grab only "text" lines from the file(or every fourth line) and copy them to another file. This is the code I have, but it copies everything to the new file:
import sys
def process_file(filename):
output_file = open("data.txt", 'w')
input_file = open(filename, "r")
for line in input_file:
line = line.strip()
if not line.startswith("(") or line.startswith(""):
output_file.write(line)
output_file.close()
if __name__ == "__main__":
process_file(sys.argv[1])
A:
The reason why your script is copying every line is because line.startswith("") is True, no matter what line equals.
You might try using isspace to test if line begins with a space:
def process_file(filename):
with open("data.txt", 'w') as output_file:
with open(filename, "r") as input_file:
for line in input_file:
line=line.rstrip()
if not line.startswith("(") or line[:1].isspace():
output_file.write(line)
A:
with open('data.txt','w') as of:
of.write(''.join(textline
for textline in open(filename)
if textline[0] not in ' \t(')
)
To write every fourth line use slice result[::4]
with open('data.txt','w') as of:
of.write(''.join([textline
for textline in open(filename)
if textline[0] not in ' \t('][::4])
)
I need not to rstrip the newlines as I use them with write.
A:
In addition to line.startswith("") always being true, line.strip() will remove the leading tab forcing the tabbed data to be written as well. change it to line.rstrip() and use \t to test for a tab. That part of your code should look like:
line = line.rstrip()
if not line.startswith(('(', '\t')):
#....
In response to your question in the comments:
#edited in response to comments in post
for i, line in input_file:
if i % 4 == 0:
output_file.write(line)
A:
try:
if not line.startswith("(") and not line.startswith("\t"):
without doing line.strip() (this will strip the tabs)
A:
So the issue is that (1) you are misusing boolean logic, and (2) every possible line starts with "".
First, the boolean logic:
The way the or operator works is that it returns True if either of its operands is True. The operands are "not line.startswith('(')" and "line.startswith('')". Note that the not only applies to one of the operands. If you want to apply it to the total result of the or expression, you will have to put the whole thing in parentheses.
The second issue is your use of the startswith() method with a zero-length strong as an argument. This essentially says "match any string where the first zero characters are nothing. It matches any strong you could give it.
See other answers for what you should be doing here.
| How do I write only certain lines to a file in Python? | I have a file that looks like this(have to put in code box so it resembles file):
text
(starts with parentheses)
tabbed info
text
(starts with parentheses)
tabbed info
...repeat
I want to grab only "text" lines from the file(or every fourth line) and copy them to another file. This is the code I have, but it copies everything to the new file:
import sys
def process_file(filename):
output_file = open("data.txt", 'w')
input_file = open(filename, "r")
for line in input_file:
line = line.strip()
if not line.startswith("(") or line.startswith(""):
output_file.write(line)
output_file.close()
if __name__ == "__main__":
process_file(sys.argv[1])
| [
"The reason why your script is copying every line is because line.startswith(\"\") is True, no matter what line equals.\nYou might try using isspace to test if line begins with a space:\ndef process_file(filename):\n with open(\"data.txt\", 'w') as output_file:\n with open(filename, \"r\") as input_file:\... | [
1,
1,
0,
0,
0
] | [] | [] | [
"file",
"python"
] | stackoverflow_0003431673_file_python.txt |
Q:
Python: Completer for path to dir/file
I'm writing a CLI app and there is a place, where user should to write path to using dir. Of couse, I can read it with raw_input(), but standart Completer can't autocomplete path by TAB. So is there any solution in python (or somewhere else) or should I to write my own Completer?
A:
Have a look at this SO question, the readline module, and readline.clear_history() / readline.add_history().
| Python: Completer for path to dir/file | I'm writing a CLI app and there is a place, where user should to write path to using dir. Of couse, I can read it with raw_input(), but standart Completer can't autocomplete path by TAB. So is there any solution in python (or somewhere else) or should I to write my own Completer?
| [
"Have a look at this SO question, the readline module, and readline.clear_history() / readline.add_history().\n"
] | [
0
] | [] | [] | [
"command_line_interface",
"python"
] | stackoverflow_0003431850_command_line_interface_python.txt |
Q:
Get big TAR(gz)-file contents by dir levels
I use python tarfile module.
I have a system backup in tar.gz file.
I need to get first level dirs and files list without getting ALL the list of files in the archive because it's TOO LONG.
For example: I need to get ['bin/', 'etc/', ... 'var/'] and that's all.
How can I do it? May be not even with a tar-file? Then how?
A:
You can't scan the contents of a tar without scanning the entire file; it has no central index. You need something like a ZIP.
| Get big TAR(gz)-file contents by dir levels | I use python tarfile module.
I have a system backup in tar.gz file.
I need to get first level dirs and files list without getting ALL the list of files in the archive because it's TOO LONG.
For example: I need to get ['bin/', 'etc/', ... 'var/'] and that's all.
How can I do it? May be not even with a tar-file? Then how?
| [
"You can't scan the contents of a tar without scanning the entire file; it has no central index. You need something like a ZIP.\n"
] | [
1
] | [] | [] | [
"python",
"tar"
] | stackoverflow_0003431844_python_tar.txt |
Q:
how to convert python/cython unicode string to array of long integers, to do levenshtein edit distance
Possible Duplicate:
How to correct bugs in this Damerau-Levenshtein implementation?
I have the following Cython code (adapted from the bpbio project) that does Damerau-Levenenshtein edit-distance calculation:
#---------------------------------------------------------------------------
cdef extern from "stdlib.h":
ctypedef unsigned int size_t
size_t strlen(char *s)
void *malloc(size_t size)
void *calloc(size_t n, size_t size)
void free(void *ptr)
int strcmp(char *a, char *b)
char * strcpy(char *a, char *b)
#---------------------------------------------------------------------------
cdef extern from "Python.h":
object PyTuple_GET_ITEM(object, int)
void Py_INCREF(object)
#---------------------------------------------------------------------------
cdef inline size_t imin(int a, int b, int c):
if a < b:
if c < a:
return c
return a
if c < b:
return c
return b
#---------------------------------------------------------------------------
cpdef int editdistance( char *a, char *b ):
"""Given two byte strings ``a`` and ``b``, return their absolute Damerau-
Levenshtein distance. Each deletion, insertion, substitution, and
transposition is counted as one difference, so the edit distance between
``abc`` and ``ab``, ``abcx``, ``abx``, ``acb``, respectively, is ``1``."""
#.........................................................................
if strcmp( a, b ) == 0: return 0
#.........................................................................
cdef int alen = strlen( a )
cdef int blen = strlen( b )
cdef int R
cdef char *ctmp
cdef size_t i
cdef size_t j
cdef size_t achr
cdef size_t bchr
#.........................................................................
if alen > blen:
ctmp = a;
a = b;
b = ctmp;
alen, blen = blen, alen
#.........................................................................
cdef char *m1 = <char *>calloc( blen + 2, sizeof( char ) )
cdef char *m2 = <char *>calloc( blen + 2, sizeof( char ) )
cdef char *m3 = <char *>malloc( ( blen + 2 ) * sizeof( char ) )
#.........................................................................
for i from 0 <= i <= blen:
m2[ i ] = i
#.........................................................................
for i from 1 <= i <= alen:
m1[ 0 ] = i + 1
achr = a[ i - 1 ]
for j from 1 <= j <= blen:
bchr = b[ j- 1 ]
if achr == bchr:
m1[ j ] = m2[ j - 1 ]
else:
m1[ j ] = 1 + imin( m1[ j - 1 ], m2[ j - 1 ], m2[ j ] )
if i != 1 and j != 1 and achr == b[ j - 2 ] and bchr == a[ i - 2 ]:
m1[ j ] = m3[ j - 1 ]
#.......................................................................
m1, m2 = m2, m1
strcpy( m3, m2 )
#.........................................................................
R = <int>m2[ blen ]
#.........................................................................
# cleanup:
free( m3 )
free( m1 )
free( m2 )
#.........................................................................
return R
The code runs fine and fast (300,000...400,000 comparisons per second on my PC).
the challenge is to make this code work with unicode strings as well. i am running Python 3.1 and retrieve texts from a database that are then matched to a query text.
encoding these strings to bytes before passing them to the Cython function for comparison is not be a good idea, since performance would suffer considerably (tested) and results would likely be wrong for any text containing characters outside of 7bit US ASCII.
the (very terse) Cython manual does mention unicode strings, but is hardly helpful for the problem at hand.
as i see it, a unicode string can be conceived of as an array of integer number, each representing a single codepoint, and the code above is basically operating on arrays of chars already, so my guess is that i should (1) extend it to handle C arrays of integers; (2) add code to convert a python unicode string to a C array; (3) profit!.
( Note: there are two potential issues with this approach: one is handling unicode surrogate characters, but i guess i know what to do with those. the other problem is that unicode codepoints do not really map 1:1 to the concept of 'characters'. i am well aware of that but i consider it outside of the scope of this question. please assume that one unicode codepoint is one unit of comparison.)
so i am asking for suggestions how to
write a fast Cython function that accepts a python unicode string and returns a C array of Cython unsigned ints (4 bytes);
modify the code shown to handle those arrays and do the correct memory allocations / deallocations (this is pretty foreign stuff to me).
Edit: John Machin has pointed out that the curious typecasts char *m1 etc are probably done for speed and/or memory optimization; these variables are still treated as arrays of numbers. i realize that the code does nothing to prevent a possible overflow with long strings; erroneous results may occur when one array element exceeds 127 or 255 (depending on the C compiler used). sort of surprising for code coming from a bioinformatics project.
that said, i am only interested in precise results for largely identical strings of less than say a hundred characters or so. results below 60% sameness could for my purposes be safely reported as 'completely different' (by returning the length of the longer text), so i guess it will be best to leave the char *m1 casts in place, but add some code to check against overflow and early abortion in case of rampant dissimilarity.
A:
Use ord() to convert characters to their integer code point. It works characters from either unicode or str string types:
codepoints = [ord(c) for c in text]
A:
Caveat lector: I've never done this. The following is a rough sketch of what I'd try.
You will need to use the PyUnicode_AsUnicode function and the next one, PyUnicode_GetSize. In declarations, where you currently have char, use Py_UNICODE instead. Presumably with a narrow (UCS2) build you will copy the internal structure, converting surrogate pairs as you go. With a wide (UCS4) build you might operate directly on the internal structure.
A:
i close this question because i have found a better algorithm... with its own problems. see you over there.
| how to convert python/cython unicode string to array of long integers, to do levenshtein edit distance |
Possible Duplicate:
How to correct bugs in this Damerau-Levenshtein implementation?
I have the following Cython code (adapted from the bpbio project) that does Damerau-Levenenshtein edit-distance calculation:
#---------------------------------------------------------------------------
cdef extern from "stdlib.h":
ctypedef unsigned int size_t
size_t strlen(char *s)
void *malloc(size_t size)
void *calloc(size_t n, size_t size)
void free(void *ptr)
int strcmp(char *a, char *b)
char * strcpy(char *a, char *b)
#---------------------------------------------------------------------------
cdef extern from "Python.h":
object PyTuple_GET_ITEM(object, int)
void Py_INCREF(object)
#---------------------------------------------------------------------------
cdef inline size_t imin(int a, int b, int c):
if a < b:
if c < a:
return c
return a
if c < b:
return c
return b
#---------------------------------------------------------------------------
cpdef int editdistance( char *a, char *b ):
"""Given two byte strings ``a`` and ``b``, return their absolute Damerau-
Levenshtein distance. Each deletion, insertion, substitution, and
transposition is counted as one difference, so the edit distance between
``abc`` and ``ab``, ``abcx``, ``abx``, ``acb``, respectively, is ``1``."""
#.........................................................................
if strcmp( a, b ) == 0: return 0
#.........................................................................
cdef int alen = strlen( a )
cdef int blen = strlen( b )
cdef int R
cdef char *ctmp
cdef size_t i
cdef size_t j
cdef size_t achr
cdef size_t bchr
#.........................................................................
if alen > blen:
ctmp = a;
a = b;
b = ctmp;
alen, blen = blen, alen
#.........................................................................
cdef char *m1 = <char *>calloc( blen + 2, sizeof( char ) )
cdef char *m2 = <char *>calloc( blen + 2, sizeof( char ) )
cdef char *m3 = <char *>malloc( ( blen + 2 ) * sizeof( char ) )
#.........................................................................
for i from 0 <= i <= blen:
m2[ i ] = i
#.........................................................................
for i from 1 <= i <= alen:
m1[ 0 ] = i + 1
achr = a[ i - 1 ]
for j from 1 <= j <= blen:
bchr = b[ j- 1 ]
if achr == bchr:
m1[ j ] = m2[ j - 1 ]
else:
m1[ j ] = 1 + imin( m1[ j - 1 ], m2[ j - 1 ], m2[ j ] )
if i != 1 and j != 1 and achr == b[ j - 2 ] and bchr == a[ i - 2 ]:
m1[ j ] = m3[ j - 1 ]
#.......................................................................
m1, m2 = m2, m1
strcpy( m3, m2 )
#.........................................................................
R = <int>m2[ blen ]
#.........................................................................
# cleanup:
free( m3 )
free( m1 )
free( m2 )
#.........................................................................
return R
The code runs fine and fast (300,000...400,000 comparisons per second on my PC).
the challenge is to make this code work with unicode strings as well. i am running Python 3.1 and retrieve texts from a database that are then matched to a query text.
encoding these strings to bytes before passing them to the Cython function for comparison is not be a good idea, since performance would suffer considerably (tested) and results would likely be wrong for any text containing characters outside of 7bit US ASCII.
the (very terse) Cython manual does mention unicode strings, but is hardly helpful for the problem at hand.
as i see it, a unicode string can be conceived of as an array of integer number, each representing a single codepoint, and the code above is basically operating on arrays of chars already, so my guess is that i should (1) extend it to handle C arrays of integers; (2) add code to convert a python unicode string to a C array; (3) profit!.
( Note: there are two potential issues with this approach: one is handling unicode surrogate characters, but i guess i know what to do with those. the other problem is that unicode codepoints do not really map 1:1 to the concept of 'characters'. i am well aware of that but i consider it outside of the scope of this question. please assume that one unicode codepoint is one unit of comparison.)
so i am asking for suggestions how to
write a fast Cython function that accepts a python unicode string and returns a C array of Cython unsigned ints (4 bytes);
modify the code shown to handle those arrays and do the correct memory allocations / deallocations (this is pretty foreign stuff to me).
Edit: John Machin has pointed out that the curious typecasts char *m1 etc are probably done for speed and/or memory optimization; these variables are still treated as arrays of numbers. i realize that the code does nothing to prevent a possible overflow with long strings; erroneous results may occur when one array element exceeds 127 or 255 (depending on the C compiler used). sort of surprising for code coming from a bioinformatics project.
that said, i am only interested in precise results for largely identical strings of less than say a hundred characters or so. results below 60% sameness could for my purposes be safely reported as 'completely different' (by returning the length of the longer text), so i guess it will be best to leave the char *m1 casts in place, but add some code to check against overflow and early abortion in case of rampant dissimilarity.
| [
"Use ord() to convert characters to their integer code point. It works characters from either unicode or str string types:\ncodepoints = [ord(c) for c in text]\n\n",
"Caveat lector: I've never done this. The following is a rough sketch of what I'd try.\nYou will need to use the PyUnicode_AsUnicode function and t... | [
3,
0,
-2
] | [] | [] | [
"cython",
"edit_distance",
"levenshtein_distance",
"python",
"python_3.x"
] | stackoverflow_0003367795_cython_edit_distance_levenshtein_distance_python_python_3.x.txt |
Q:
Why Does Specifying choices to a Widget not work in ModelForm.__init__
I'm trying to understand why I can't specify choices to a form field's widget if I'm overriding a ModelForm's field in Django. It works if I give the choices to the field but not the widget. My understanding is/was that if you give choices to a field it'll be passed onto the widget for rendering. I know I can get this to work with any of the first three snippets below but I just wanted to fully understand why this one way doesn't work.
This is my ModelForm code, thanks!
from django import forms
from models import Guest
class RSVPForm(forms.ModelForm):
class Meta:
model = Guest
def __init__(self, *args, **kwargs):
"""
Override a form's field to change the widget
"""
super(RSVPForm, self).__init__(*args, **kwargs)
# This works
self.fields['attending_ceremony'].required = True
self.fields['attending_ceremony'].widget=forms.RadioSelect(choices=Guest.CHOICES)
# This works
self.fields['attending_ceremony'].required = True
self.fields['attending_ceremony'].widget=forms.RadioSelect()
self.fields['attending_ceremony'].choices=Guest.CHOICES
# This works
self.fields['attending_ceremony'] = forms.TypedChoiceField(
required=True,
widget=forms.RadioSelect,
choices=Guest.CHOICES
)
# This doesn't - the choices aren't set (it's an empty list)
self.fields['attending_ceremony'] = forms.TypedChoiceField(
required=True,
widget=forms.RadioSelect(choices=Guest.CHOICES)
)
A:
I think the best way of explaining is to walk through the code for ChoiceField, the superclass of TypeChoiceField.
class ChoiceField(Field):
widget = Select
default_error_messages = {
'invalid_choice': _(u'Select a valid choice. %(value)s is not one of the available choices.'),
}
def __init__(self, choices=(), required=True, widget=None, label=None,
initial=None, help_text=None, *args, **kwargs):
super(ChoiceField, self).__init__(required=required, widget=widget, label=label,
initial=initial, help_text=help_text, *args, **kwargs)
self.choices = choices
def _get_choices(self):
return self._choices
def _set_choices(self, value):
# Setting choices also sets the choices on the widget.
# choices can be any iterable, but we call list() on it because
# it will be consumed more than once.
self._choices = self.widget.choices = list(value)
choices = property(_get_choices, _set_choices)
With your example,
self.fields['attending_ceremony'] = forms.TypedChoiceField(
required=True,
widget=forms.RadioSelect(choices=Guest.CHOICES)
)
The widget is initialised, with choices=guest.Choices
super(ChoiceField, self).__init__ sets self.widget=widget. The widget's choices are still set.
self.choices=choices sets the choices for the field and the widget to the default (), because it wasn't specified (see _set_choices above).
Hope that makes sense. Looking at the code also explains why your other examples work. Either the choices are set for the widget and the choice field at the same time, or widget's choices are set after the choice field has been initialised.
| Why Does Specifying choices to a Widget not work in ModelForm.__init__ | I'm trying to understand why I can't specify choices to a form field's widget if I'm overriding a ModelForm's field in Django. It works if I give the choices to the field but not the widget. My understanding is/was that if you give choices to a field it'll be passed onto the widget for rendering. I know I can get this to work with any of the first three snippets below but I just wanted to fully understand why this one way doesn't work.
This is my ModelForm code, thanks!
from django import forms
from models import Guest
class RSVPForm(forms.ModelForm):
class Meta:
model = Guest
def __init__(self, *args, **kwargs):
"""
Override a form's field to change the widget
"""
super(RSVPForm, self).__init__(*args, **kwargs)
# This works
self.fields['attending_ceremony'].required = True
self.fields['attending_ceremony'].widget=forms.RadioSelect(choices=Guest.CHOICES)
# This works
self.fields['attending_ceremony'].required = True
self.fields['attending_ceremony'].widget=forms.RadioSelect()
self.fields['attending_ceremony'].choices=Guest.CHOICES
# This works
self.fields['attending_ceremony'] = forms.TypedChoiceField(
required=True,
widget=forms.RadioSelect,
choices=Guest.CHOICES
)
# This doesn't - the choices aren't set (it's an empty list)
self.fields['attending_ceremony'] = forms.TypedChoiceField(
required=True,
widget=forms.RadioSelect(choices=Guest.CHOICES)
)
| [
"I think the best way of explaining is to walk through the code for ChoiceField, the superclass of TypeChoiceField.\nclass ChoiceField(Field):\n widget = Select\n default_error_messages = {\n 'invalid_choice': _(u'Select a valid choice. %(value)s is not one of the available choices.'),\n }\n\n de... | [
2
] | [] | [] | [
"django",
"django_forms",
"python"
] | stackoverflow_0003431923_django_django_forms_python.txt |
Q:
Serving Python scripts with CGIHTTPServer on Mac OS X
I'm trying to set up Python's CGIHTTPServer on Mac OS X to be able to serve CGI scripts locally, but I seem to be unable to do this.
I've got a simple test script:
#!/usr/bin/env python
import cgi
cgi.test()
It has permissions -rwxr-xr-x@ and is located in ~/WWW (with permissions drwxr-xr-x). It runs just fine from the shell and I have this script to serve them using CGIHTTPServer:
import CGIHTTPServer
import BaseHTTPServer
class Handler(CGIHTTPServer.CGIHTTPRequestHandler):
cgi_directories = ["~/WWW"]
PORT = 8000
httpd = BaseHTTPServer.HTTPServer(("", PORT), Handler)
print "serving at port", PORT
But when I run it, going to localhost:8000 just serves the content of the script, not the result (i.e. it gives back the code, not the output).
What am I doing wrong?
A:
The paths in cgi_directories are matched against the path part of the URL, not the actual filesystem path. Setting it to ["/"] or [""] will probably work better.
| Serving Python scripts with CGIHTTPServer on Mac OS X | I'm trying to set up Python's CGIHTTPServer on Mac OS X to be able to serve CGI scripts locally, but I seem to be unable to do this.
I've got a simple test script:
#!/usr/bin/env python
import cgi
cgi.test()
It has permissions -rwxr-xr-x@ and is located in ~/WWW (with permissions drwxr-xr-x). It runs just fine from the shell and I have this script to serve them using CGIHTTPServer:
import CGIHTTPServer
import BaseHTTPServer
class Handler(CGIHTTPServer.CGIHTTPRequestHandler):
cgi_directories = ["~/WWW"]
PORT = 8000
httpd = BaseHTTPServer.HTTPServer(("", PORT), Handler)
print "serving at port", PORT
But when I run it, going to localhost:8000 just serves the content of the script, not the result (i.e. it gives back the code, not the output).
What am I doing wrong?
| [
"The paths in cgi_directories are matched against the path part of the URL, not the actual filesystem path. Setting it to [\"/\"] or [\"\"] will probably work better.\n"
] | [
4
] | [] | [] | [
"cgi",
"macos",
"python"
] | stackoverflow_0003431984_cgi_macos_python.txt |
Q:
python data attributes in sqlalchemy model
I'm getting myself into issues with python class attributes vs data attributes in my sqlalchemy model. This is a small example to demonstrate what's happening:
# -*- coding: utf-8 -*-
import cherrypy
import sqlalchemy
from sqlalchemy import create_engine
from sqlalchemy import Table, Column, Integer, String, MetaData, ForeignKey
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
engine = create_engine('mysql://USER:PASS@localhost/SCHEMA?charset=utf8', echo=True)
Session = sessionmaker(bind=engine)
session = Session()
Base = declarative_base()
class User(Base):
__tablename__ = 'user'
id = Column(Integer, primary_key=True)
username = Column(String, nullable=False)
name = Column(String, nullable=False)
email = Column(String, nullable=False)
def __init__(self, username, name, email):
self.username = username
self.name = name
self.email = email
self.data_attribute = "my data attribute"
print "__init__"
def __repr__(self):
print "__repr__"
return "<User('%s','%s', '%s')>" % (self.username, self.name, self.email)
class Root(object):
@cherrypy.expose
def test(self):
our_user = session.query(User).one()
return our_user.data_attribute #error
if __name__ == '__main__':
cherrypy.tree.mount(Root())
cherrypy.server.quickstart()
cherrypy.engine.start()
That code errors because when the objects are taken from the DB __init__ doesn't run so data_attribute doesn't exist. If I put data_attribute in with the Column objects is becomes a class attribute (I think) and therefore carries the same value for all instances of User. This is not what I want.
What do I need to do to have a data attribute on my User object that doesn't come from the DB but also is unique for each instance of User?
Edit: I should probably point out that data_attribute will not always just be a simple string set in __init__ - this is just to demonstrate the problem.
A:
SQLAlchemy provides special syntax for such cases, http://docs.sqlalchemy.org/en/latest/orm/constructors.html?highlight=object%20initialization
A:
You should be using super() to call the base class constructor:
def __init__(self, username, name, email, *args, **kwargs ):
super( User, self ).__init__( *args, **kwargs ) # Python 2.x or 3.x
#super().__init__( *args, **kwargs ) # Python 3.x only
self.username = username
...
| python data attributes in sqlalchemy model | I'm getting myself into issues with python class attributes vs data attributes in my sqlalchemy model. This is a small example to demonstrate what's happening:
# -*- coding: utf-8 -*-
import cherrypy
import sqlalchemy
from sqlalchemy import create_engine
from sqlalchemy import Table, Column, Integer, String, MetaData, ForeignKey
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
engine = create_engine('mysql://USER:PASS@localhost/SCHEMA?charset=utf8', echo=True)
Session = sessionmaker(bind=engine)
session = Session()
Base = declarative_base()
class User(Base):
__tablename__ = 'user'
id = Column(Integer, primary_key=True)
username = Column(String, nullable=False)
name = Column(String, nullable=False)
email = Column(String, nullable=False)
def __init__(self, username, name, email):
self.username = username
self.name = name
self.email = email
self.data_attribute = "my data attribute"
print "__init__"
def __repr__(self):
print "__repr__"
return "<User('%s','%s', '%s')>" % (self.username, self.name, self.email)
class Root(object):
@cherrypy.expose
def test(self):
our_user = session.query(User).one()
return our_user.data_attribute #error
if __name__ == '__main__':
cherrypy.tree.mount(Root())
cherrypy.server.quickstart()
cherrypy.engine.start()
That code errors because when the objects are taken from the DB __init__ doesn't run so data_attribute doesn't exist. If I put data_attribute in with the Column objects is becomes a class attribute (I think) and therefore carries the same value for all instances of User. This is not what I want.
What do I need to do to have a data attribute on my User object that doesn't come from the DB but also is unique for each instance of User?
Edit: I should probably point out that data_attribute will not always just be a simple string set in __init__ - this is just to demonstrate the problem.
| [
"SQLAlchemy provides special syntax for such cases, http://docs.sqlalchemy.org/en/latest/orm/constructors.html?highlight=object%20initialization\n",
"You should be using super() to call the base class constructor:\ndef __init__(self, username, name, email, *args, **kwargs ):\n super( User, self ).__init__( *ar... | [
3,
1
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0003422408_python_sqlalchemy.txt |
Q:
How to correct bugs in this Damerau-Levenshtein implementation?
I'm back with another longish question. Having experimented with a number of Python-based Damerau-Levenshtein
edit distance implementations, I finally found the one listed below as editdistance_reference(). It
seems to deliver correct results and appears to have an efficient implementation.
So I set down to convert the code to Cython. on my test data, the reference method manages to deliver results
for 11,000 comparisons (for pairs of words aound 12 letters long), while the Cythonized method does over
200,000 comparisons per second. Sadly, the results are incorrect: when you look at the variable thisrow
which I print out for debugging, my version has it filled with ones no matter what data I throw at it,
while the reference output shows another picture. For example, testing 'helo' against 'world'
produces the following output (ED marks my function, EDR is the correctly working reference):
From editdistance():
#ED A [0, 0, 0, 0, 0, 1]
#ED B [1, 0, 0, 0, 0, 1]
#ED B [1, 1, 0, 0, 0, 1]
#ED B [1, 1, 1, 0, 0, 1]
#ED B [1, 1, 1, 1, 0, 1]
#ED B [1, 1, 1, 1, 1, 1]
#ED A [0, 0, 0, 0, 0, 2]
#ED B [1, 0, 0, 0, 0, 2]
#ED B [1, 1, 0, 0, 0, 2]
#ED B [1, 1, 1, 0, 0, 2]
#ED B [1, 1, 1, 1, 0, 2]
#ED B [1, 1, 1, 1, 1, 2]
#ED A [0, 0, 0, 0, 0, 3]
#ED B [1, 0, 0, 0, 0, 3]
#ED B [1, 1, 0, 0, 0, 3]
#ED B [1, 1, 1, 0, 0, 3]
#ED B [1, 1, 1, 1, 0, 3]
#ED B [1, 1, 1, 1, 1, 3]
#ED A [0, 0, 0, 0, 0, 4]
#ED B [1, 0, 0, 0, 0, 4]
#ED B [1, 1, 0, 0, 0, 4]
#ED B [1, 1, 1, 0, 0, 4]
#ED B [1, 1, 1, 1, 0, 4]
#ED B [1, 1, 1, 1, 1, 4]
from editdistance_reference():
#EDR A [0, 0, 0, 0, 0, 1]
#EDR B [1, 0, 0, 0, 0, 1]
#EDR B [1, 2, 0, 0, 0, 1]
#EDR B [1, 2, 3, 0, 0, 1]
#EDR B [1, 2, 3, 4, 0, 1]
#EDR B [1, 2, 3, 4, 5, 1]
#EDR A [0, 0, 0, 0, 0, 2]
#EDR B [2, 0, 0, 0, 0, 2]
#EDR B [2, 2, 0, 0, 0, 2]
#EDR B [2, 2, 3, 0, 0, 2]
#EDR B [2, 2, 3, 4, 0, 2]
#EDR B [2, 2, 3, 4, 5, 2]
#EDR A [0, 0, 0, 0, 0, 3]
#EDR B [3, 0, 0, 0, 0, 3]
#EDR B [3, 3, 0, 0, 0, 3]
#EDR B [3, 3, 3, 0, 0, 3]
#EDR B [3, 3, 3, 3, 0, 3]
#EDR B [3, 3, 3, 3, 4, 3]
#EDR A [0, 0, 0, 0, 0, 4]
#EDR B [4, 0, 0, 0, 0, 4]
#EDR B [4, 4, 0, 0, 0, 4]
#EDR B [4, 4, 4, 0, 0, 4]
#EDR B [4, 4, 4, 4, 0, 4]
#EDR B [4, 4, 4, 4, 4, 4]
i must be very dumb as the error is probably one of those very very obvious things. but i can't seem to find it.
there is a second problem: i malloc space for the three arrays twoago, oneago, and thisrow,
then they get swapped around in a circular fashion. when i try to free( twoago ) and so on, i get a
line where glibc complains about double free or corruption. i googled for that; could it be that the
pointer-swapping business makes glibc a bit dizzy so it becomes unable to correctly free memory?
below i list first the setup.py that is needed to do the compilation
(/path/to/python3.1 ./setup.py build_ext --inplace), then the edit distance code proper, so interested
people find it easier to replicate.
one more thing: this is run with Python3.1; one funny thing is that inside the *.pyx file we do have
bare unicode strings, but print is still a statement, not a function.
and yes i know this is a lot of code to paste here but the thing is the code is simply not runnable when you
cut it down all too much. i believe all methods except editdistance() to work correctly, but feel free
to point out any problems you perceive.
setup.py:
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
setup(
name = 'cython_dameraulevenshtein',
ext_modules = [
Extension( 'cython_dameraulevenshtein', [ 'cython_dameraulevenshtein.pyx', ] ), ],
cmdclass = {
'build_ext': build_ext }, )
cython_dameraulevenshtein.pyx (scroll all the way to the end to see the interesting stuff):
############################################################################################################
cdef extern from "stdlib.h":
ctypedef unsigned int size_t
void *malloc(size_t size)
void *realloc( void *ptr, size_t size )
void free(void *ptr)
#-----------------------------------------------------------------------------------------------------------
cdef inline unsigned int _minimum_of_two_uints( unsigned int a, unsigned int b ):
if a < b: return a
return b
#-----------------------------------------------------------------------------------------------------------
cdef inline unsigned int _minimum_of_three_uints( unsigned int a, unsigned int b, unsigned int c ):
if a < b:
if c < a:
return c
return a
if c < b:
return c
return b
#-----------------------------------------------------------------------------------------------------------
cdef inline int _warp( unsigned int limit, int value ):
return value if value >= 0 else limit + value
############################################################################################################
# ARRAYS THAT SAY SIZE ;-)
#-----------------------------------------------------------------------------------------------------------
cdef class Array_of_unsigned_int:
cdef unsigned int *data
cdef unsigned int length
#---------------------------------------------------------------------------------------------------------
def __cinit__( self, unsigned int length, fill_value = None ):
self.length = length
self.data = <unsigned int *>malloc( length * sizeof( unsigned int ) ) ###OBS### must check malloc doesn't return NULL pointer
if fill_value is not None:
self.fill( fill_value )
#---------------------------------------------------------------------------------------------------------
cdef fill( self, unsigned int value ):
cdef unsigned int idx
cdef unsigned int *d = self.data
for idx from 0 <= idx < self.length:
d[ idx ] = value
#---------------------------------------------------------------------------------------------------------
cdef resize( self, unsigned int length ):
self.data = <unsigned int *>realloc( self.data, length * sizeof( unsigned int ) ) ###OBS### must check realloc doesn't return NULL pointer
self.length = length
#---------------------------------------------------------------------------------------------------------
def free( self ):
"""Always remember the milk: Free up memory."""
free( self.data ) ###OBS### should free memory here
#---------------------------------------------------------------------------------------------------------
def as_list( self ):
"""Return the array as a Python list."""
R = []
cdef unsigned int idx
cdef unsigned int *d = self.data
for idx from 0 <= idx < self.length:
R.append( d[ idx ] )
return R
############################################################################################################
# CONVERTING UNICODE TO CHARACTER IDs (CIDs)
#---------------------------------------------------------------------------------------------------------
cdef unsigned int _UMX_surrogate_lower_bound = 0x10000
cdef unsigned int _UMX_surrogate_upper_bound = 0x10ffff
cdef unsigned int _UMX_surrogate_hi_lower_bound = 0xd800
cdef unsigned int _UMX_surrogate_hi_upper_bound = 0xdbff
cdef unsigned int _UMX_surrogate_lo_lower_bound = 0xdc00
cdef unsigned int _UMX_surrogate_lo_upper_bound = 0xdfff
cdef unsigned int _UMX_surrogate_foobar_factor = 0x400
#---------------------------------------------------------------------------------------------------------
cdef Array_of_unsigned_int _cids_from_text( text ):
"""Givn a ``text`` either as a Unicode string or as a ``bytes`` or ``bytearray``, return an instance of
``Array_of_unsigned_int`` that enumerates either the Unicode codepoints of each character or the value of
each byte. Surrogate pairs will be condensed into single values, so on narrow Python builds the length of
the array returned may be less than ``len( text )``."""
#.........................................................................................................
# Make sure ``text`` is either a Unicode string (``str``) or a ``bytes``-like thing:
is_bytes = isinstance( text, ( bytes, bytearray, ) )
assert is_bytes or isinstance( text, str ), '#121'
#.........................................................................................................
# Whether it is a ``str`` or a ``bytes``, we know the result can only have at most as many elements as
# there are characters in ``text``, so we can already reserve that much space (in the case of a Unicode
# text, there may be fewer CIDs if there happen to be surrogate characters):
cdef unsigned int length = <unsigned int>len( text )
cdef Array_of_unsigned_int R = Array_of_unsigned_int( length )
#.........................................................................................................
# If ``text`` is empty, we can return an empty array right away:
if length == 0: return R
#.........................................................................................................
# Otherwise, prepare to copy data:
cdef unsigned int idx = 0
#.........................................................................................................
# If ``text`` is a ``bytes``-like thing, use simplified processing; we just have to copy over all byte
# values and are done:
if is_bytes:
for idx from 0 <= idx < length:
R.data[ idx ] = <unsigned int>text[ idx ]
return R
#.........................................................................................................
cdef unsigned int cid = 0
cdef bool is_surrogate = False
cdef unsigned int hi = 0
cdef unsigned int lo = 0
cdef unsigned int chr_count = 0
#.........................................................................................................
# Iterate over all indexes in text:
for idx from 0 <= idx < length:
#.......................................................................................................
# If we met with a surrogate CID in the last cycle, then that was a high surrogate CID, and the
# corresponding low CID is on the current position. Having both, we can compute the intended CID
# and reset the flag:
if is_surrogate:
lo = <unsigned int>ord( text[ idx ] )
# IIRC, this formula was documented in Unicode 3:
cid = ( ( hi - _UMX_surrogate_hi_lower_bound ) * _UMX_surrogate_foobar_factor
+ ( lo - _UMX_surrogate_lo_lower_bound ) + _UMX_surrogate_lower_bound )
is_surrogate = False
#.......................................................................................................
else:
# Otherwise, we retrieve the CID from the current position:
cid = <unsigned int>ord( text[ idx ] )
#.....................................................................................................
if _UMX_surrogate_hi_lower_bound <= cid <= _UMX_surrogate_hi_upper_bound:
# If this CID is a high surrogate CID, set ``hi`` to this value and set a flag so we'll come back
# in the next cycle:
hi = cid
is_surrogate = True
continue
#.......................................................................................................
R.data[ chr_count ] = cid
chr_count += 1
#.........................................................................................................
# Surrogate CIDs take up two characters but end up as a single resultant CID, so the return value may
# have fewer elements than the naive string length indicated; in this case, we want to free some memory
# and correct array length data:
if chr_count != length:
R.resize( chr_count )
#.........................................................................................................
return R
#---------------------------------------------------------------------------------------------------------
def cids_from_text( text ):
cdef Array_of_unsigned_int c_R =_cids_from_text( text )
R = c_R.as_list()
c_R.free() ###OBS### should free memory here
return R
############################################################################################################
# SECOND-ORDER SIMILARITY
#-----------------------------------------------------------------------------------------------------------
cpdef float similarity( char *a, char *b ):
"""Given two byte strings ``a`` and ``b``, return their Damerau-Levenshtein similarity as a float between
0.0 and 1.1. Similarity is computed as ``1 - relative_editdistance( a, b )``, so a result of ``1.0``
indicates identity, while ``0.0`` indicates complete dissimilarity."""
return 1.0 - relative_editdistance( a, b )
#-----------------------------------------------------------------------------------------------------------
cpdef float relative_editdistance( char *a, char *b ):
"""Given two byte strings ``a`` and ``b``, return their relative Damerau-Levenshtein distance. The return
value is a float between 0.0 and 1.0; it is calculated as the absolute edit distance, divided by the
length of the longer string. Therefore, ``0.0`` indicates identity, while ``1.0`` indicates complete
dissimilarity."""
cdef int length = max( len( a ), len( b ) )
if length == 0: return 0.0
return editdistance( a, b ) / <float>length
############################################################################################################
# EDIT DISTANCE
#-----------------------------------------------------------------------------------------------------------
cpdef unsigned int editdistance( text_a, text_b ):
"""Given texts as Unicode strings or ``bytes`` / ``bytearray`` objects, return their absolute
Damerau-Levenshtein distance. Each deletion, insertion, substitution, and transposition is counted as one
difference, so the edit distance between ``abc`` and ``ab``, ``abcx``, ``abx``, ``acb``, respectively, is
``1``."""
#.........................................................................................................
# This should be fast in Python, as it can (and probably is) implemented by doing an identity check in
# the case of ``bytes`` and ``str`` objects:
if text_a == text_b: return 0
#.........................................................................................................
# Convert Unicode text to C array of unsigned integers:
cdef Array_of_unsigned_int a = _cids_from_text( text_a )
cdef Array_of_unsigned_int b = _cids_from_text( text_b )
R = c_editdistance( a, b )
#.........................................................................................................
# Always remember the milk:
a.free()
b.free()
#.........................................................................................................
return R
#-----------------------------------------------------------------------------------------------------------
cdef unsigned int c_editdistance( Array_of_unsigned_int cids_a, Array_of_unsigned_int cids_b ):
# Conceptually, this is based on a len(a) + 1 * len(b) + 1 matrix.
# However, only the current and two previous rows are needed at once,
# so we only store those.
#.........................................................................................................
# This shortcut is pretty useless if comparison is not very fast; therefore, it is done in the function
# that deals with the Python objects, q.v.
# if cids_a.equals( cids_b ): return 0
#.........................................................................................................
cdef unsigned int a_length = cids_a.length
cdef unsigned int b_length = cids_b.length
#.........................................................................................................
# Another shortcut: if one of the texts is empty, then the edit distance is trivially the length of the
# other text. This also works for two empty texts, but those have already been taken care of by the
# previous shortcut:
#.........................................................................................................
if a_length == 0: return b_length
if b_length == 0: return a_length
#.........................................................................................................
cdef unsigned int row_length = b_length + 1
cdef unsigned int row_length_1 = row_length - 1
cdef unsigned int row_bytecount = sizeof( unsigned int ) * row_length
cdef unsigned int *oneago = <unsigned int *>malloc( row_bytecount ) ###OBS### must check malloc doesn't return NULL pointer
cdef unsigned int *twoago = <unsigned int *>malloc( row_bytecount ) ###OBS### must check malloc doesn't return NULL pointer
cdef unsigned int *thisrow = <unsigned int *>malloc( row_bytecount ) ###OBS### must check malloc doesn't return NULL pointer
cdef unsigned int idx = 0
cdef unsigned int idx_a = 0
cdef unsigned int idx_b = 0
cdef int idx_a_1_text = 0
cdef int idx_b_1_row = 0
cdef int idx_b_2_row = 0
cdef int idx_b_1_text = 0
cdef unsigned int deletion_cost = 0
cdef unsigned int addition_cost = 0
cdef unsigned int substitution_cost = 0
#.........................................................................................................
# Equivalent of ``thisrow = list( range( 1, b_length + 1 ) ) + [ 0 ]``:
#print( '#305', cids_a.as_list(), cids_b.as_list(), a_length, b_length, row_length, row_length_1 )
for idx from 1 <= idx < row_length:
thisrow[ idx - 1 ] = idx
thisrow[ row_length - 1 ] = 0
#.........................................................................................................
for idx_a from 0 <= idx_a < a_length:
idx_a_1_text = _warp( a_length, idx_a - 1 )
twoago, oneago = oneago, thisrow
#.......................................................................................................
# Equivalent of ``thisrow = [ 0 ] * b_length + [ idx_a + 1 ]``:
for idx from 0 <= idx < row_length_1:
thisrow[ idx ] = 0
thisrow[ row_length - 1 ] = idx_a + 1
#.......................................................................................................
# some diagnostic output:
x = []
for idx from 0 <= idx < row_length: x.append( thisrow[ idx ] )
print
print '#ED A', x
#.......................................................................................................
for idx_b from 0 <= idx_b < b_length:
#.....................................................................................................
idx_b_1_row = _warp( row_length, idx_b - 1 )
idx_b_1_text = _warp( b_length, idx_b - 1 )
#.....................................................................................................
assert 0 <= idx_b_1_row < row_length, ( '#323', idx_b_1_row, )
assert 0 <= idx_a_1_text < a_length, ( '#324', idx_a_1_text, )
assert 0 <= idx_b_1_text < b_length, ( '#325', idx_b_1_text, )
#.....................................................................................................
deletion_cost = oneago[ idx_b ] + 1
addition_cost = thisrow[ idx_b_1_row ] + 1
substitution_cost = oneago[ idx_b_1_row ] + ( 1 if cids_a.data[ idx_a ]
!= cids_b.data[ idx_b ] else 0 )
thisrow[ idx_b ] = _minimum_of_three_uints( deletion_cost, addition_cost, substitution_cost )
#.....................................................................................................
# Transpositions:
if ( idx_a > 0
and idx_b > 0
and cids_a.data[ idx_a ] == cids_b.data[ idx_b_1_text ]
and cids_a.data[ idx_a_1_text ] == cids_b.data[ idx_b ]
and cids_a.data[ idx_a ] != cids_b.data[ idx_b ] ):
#...................................................................................................
idx_b_2_row = _warp( row_length, idx_b - 2 )
assert 0 <= idx_b_2_row < row_length, ( '#340', idx_b_2_row, )
thisrow[ idx_b ] = _minimum_of_two_uints( thisrow[ idx_b ], twoago[ idx_b_2_row ] + 1 )
#.....................................................................................................
# some diagnostic output:
x = []
for idx from 0 <= idx < row_length: x.append( thisrow[ idx ] )
print '#ED B', x
#.........................................................................................................
# Here, ``b_length - 1`` can't become negative, since we already tested for ``b_length == 0`` in the
# shortcut above:
cdef unsigned int R = thisrow[ b_length - 1 ]
#.........................................................................................................
# Always remember the milk:
# BUG: Activating below lines leads to glibc failing with ``double free or corruption``
#free( twoago )
#free( oneago )
#free( thisrow )e
#.........................................................................................................
return R
#-----------------------------------------------------------------------------------------------------------
def editdistance_reference( text_a, text_b ):
"""This method is believed to compute a correct Damerau-Levenshtein edit distance, with deletions,
insertions, substitutions, and transpositions. Do not touch it; it is here to validate results returned
from the above method. Code adapted from
http://mwh.geek.nz/2009/04/26/python-damerau-levenshtein-distance"""
# Conceptually, the implementation is based on a ``( len( seq1 ) + 1 ) * ( len( seq2 ) + 1 )`` matrix.
# However, only the current and two previous rows are needed at once, so we only store those. Python
# lists wrap around for negative indices, so we put the leftmost column at the *end* of the list. This
# matches with the zero-indexed strings and saves extra calculation.
b_length = len( text_b )
oneago = None
thisrow = list( range( 1, b_length + 1 ) ) + [ 0 ]
for idx_a in range( len( text_a ) ):
twoago, oneago, thisrow = oneago, thisrow, [ 0 ] * b_length + [ idx_a + 1 ]
#.......................................................................................................
# some diagnostic output:
print
print '#EDR A', thisrow
#.......................................................................................................
for idx_b in range( b_length ):
deletion_cost = oneago[ idx_b ] + 1
addition_cost = thisrow[ idx_b - 1 ] + 1
substitution_cost = oneago[ idx_b - 1 ] + ( text_a[ idx_a ] != text_b[ idx_b ] )
thisrow[ idx_b ] = min( deletion_cost, addition_cost, substitution_cost )
if ( idx_a > 0
and idx_b > 0
and text_a[ idx_a ] == text_b[ idx_b - 1 ]
and text_a[ idx_a - 1 ] == text_b[ idx_b ]
and text_a[ idx_a ] != text_b[ idx_b ] ):
thisrow[ idx_b ] = min( thisrow[ idx_b ], twoago[ idx_b - 2 ] + 1 )
#.....................................................................................................
# some diagnostic output:
print '#EDR B', thisrow
#.....................................................................................................
return thisrow[ len( text_b ) - 1 ]
edit i also posted this text to pastebin and the Cython list.
A:
Do some elementary debugging. You know that it is going wrong in the 2nd output line marked #ED B. The wrong values seem to indicate that it finds one edit early on and never finds any more. This is possibly because one of the min() args is somehow clamped at 1. Print deletion_cost, substitution_cost, addition_cost ... which is wrong? Why is it wrong? Print the input text values. Temporarily disable the transposition section to see if that makes the problem go away. Check and re-check the _warp caper (a tricksy hobbit gimmick if I ever saw one) and the usage thereof. What happens if you compare "aaaaa" with "aaaaa"? "qwerty" with "qwerty"? "xxxxx" with "yyyyy"? Does the problem happen with all of bytes, bytearray and str input?
The free problem: I'd suspect corruption, not dizzyness. Print the three arrays; are their contents as expected? Try enabling the free() one array at a time -- all broken? only one? which one?
Some asides on memory management: You may like to read this and consider using the Python-specific routines instead of malloc/free. Downsizing your array if there have been surrogates seems over the top.
Update: Followed my own suggestions. Deletion cost was stuffed. "oneago" was same as "thisrow". Problem causing both the wrong answer and the doubled (-! not corrupted !-) free: circular shuffle of pointers wasn't circular.
# twoago, oneago = oneago, thisrow ### BUG ###
twoago, oneago, thisrow = oneago, thisrow, twoago ### FIXED ###
Update 2: [comment capacity too small] No mojo, just plain ordinary debugging spadework, as I suggested. "concentrating on this for my fix" is not "super-readible". The reference code does create a new list for each pass, which it CAN do because thisrow refers to nothing carried over from the previous pass. It doesn't NEED to do this, and in fact the initialisation apart from the first and last elements could consist of random numbers, and are only there to fill out the list so that it can be indexed into instead of appended to as some non-tricksy implementations do. So you can slavishly emulate the "reference implementation", at the cost of doing an extra (wasted) malloc/free, or you could ignore the Python-specific implementation details and use the reference implementation solely as a source of presumably correct answers. Then you could accept my fix, and later go on to saving time by chopping out most of the initialisation of the thisrow array.
Update 3: Here's a replacement reference implementation for you. It allocates 3 rows initially, in order to avoid the overhead of list creation inside the outer loop. It also avoids the unnecessary initialisation of all but the last element of thisrow. This eases the translation into C/Cython.
def damlevref2(seq1, seq2):
# For Python 2.x as was the original.
# Appears to work on Python 1.5.2 as well :-)
seq2len = len(seq2)
twoago = [-777] * (seq2len + 1) # pseudo-malloc; any old rubbish will do
oneago = [-666] * (seq2len + 1) # ditto
thisrow = range(1, seq2len + 1) + [0]
for x in xrange(len(seq1)):
twoago, oneago, thisrow = oneago, thisrow, twoago # circular "pointer" shuffle
thisrow[-1] = x + 1
for y in xrange(seq2len):
delcost = oneago[y] + 1
addcost = thisrow[y - 1] + 1
subcost = oneago[y - 1] + (seq1[x] != seq2[y])
thisrow[y] = min(delcost, addcost, subcost)
if (x > 0 and y > 0 and seq1[x] == seq2[y - 1]
and seq1[x-1] == seq2[y] and seq1[x] != seq2[y]):
thisrow[y] = min(thisrow[y], twoago[y - 2] + 1)
return thisrow[seq2len - 1]
| How to correct bugs in this Damerau-Levenshtein implementation? | I'm back with another longish question. Having experimented with a number of Python-based Damerau-Levenshtein
edit distance implementations, I finally found the one listed below as editdistance_reference(). It
seems to deliver correct results and appears to have an efficient implementation.
So I set down to convert the code to Cython. on my test data, the reference method manages to deliver results
for 11,000 comparisons (for pairs of words aound 12 letters long), while the Cythonized method does over
200,000 comparisons per second. Sadly, the results are incorrect: when you look at the variable thisrow
which I print out for debugging, my version has it filled with ones no matter what data I throw at it,
while the reference output shows another picture. For example, testing 'helo' against 'world'
produces the following output (ED marks my function, EDR is the correctly working reference):
From editdistance():
#ED A [0, 0, 0, 0, 0, 1]
#ED B [1, 0, 0, 0, 0, 1]
#ED B [1, 1, 0, 0, 0, 1]
#ED B [1, 1, 1, 0, 0, 1]
#ED B [1, 1, 1, 1, 0, 1]
#ED B [1, 1, 1, 1, 1, 1]
#ED A [0, 0, 0, 0, 0, 2]
#ED B [1, 0, 0, 0, 0, 2]
#ED B [1, 1, 0, 0, 0, 2]
#ED B [1, 1, 1, 0, 0, 2]
#ED B [1, 1, 1, 1, 0, 2]
#ED B [1, 1, 1, 1, 1, 2]
#ED A [0, 0, 0, 0, 0, 3]
#ED B [1, 0, 0, 0, 0, 3]
#ED B [1, 1, 0, 0, 0, 3]
#ED B [1, 1, 1, 0, 0, 3]
#ED B [1, 1, 1, 1, 0, 3]
#ED B [1, 1, 1, 1, 1, 3]
#ED A [0, 0, 0, 0, 0, 4]
#ED B [1, 0, 0, 0, 0, 4]
#ED B [1, 1, 0, 0, 0, 4]
#ED B [1, 1, 1, 0, 0, 4]
#ED B [1, 1, 1, 1, 0, 4]
#ED B [1, 1, 1, 1, 1, 4]
from editdistance_reference():
#EDR A [0, 0, 0, 0, 0, 1]
#EDR B [1, 0, 0, 0, 0, 1]
#EDR B [1, 2, 0, 0, 0, 1]
#EDR B [1, 2, 3, 0, 0, 1]
#EDR B [1, 2, 3, 4, 0, 1]
#EDR B [1, 2, 3, 4, 5, 1]
#EDR A [0, 0, 0, 0, 0, 2]
#EDR B [2, 0, 0, 0, 0, 2]
#EDR B [2, 2, 0, 0, 0, 2]
#EDR B [2, 2, 3, 0, 0, 2]
#EDR B [2, 2, 3, 4, 0, 2]
#EDR B [2, 2, 3, 4, 5, 2]
#EDR A [0, 0, 0, 0, 0, 3]
#EDR B [3, 0, 0, 0, 0, 3]
#EDR B [3, 3, 0, 0, 0, 3]
#EDR B [3, 3, 3, 0, 0, 3]
#EDR B [3, 3, 3, 3, 0, 3]
#EDR B [3, 3, 3, 3, 4, 3]
#EDR A [0, 0, 0, 0, 0, 4]
#EDR B [4, 0, 0, 0, 0, 4]
#EDR B [4, 4, 0, 0, 0, 4]
#EDR B [4, 4, 4, 0, 0, 4]
#EDR B [4, 4, 4, 4, 0, 4]
#EDR B [4, 4, 4, 4, 4, 4]
i must be very dumb as the error is probably one of those very very obvious things. but i can't seem to find it.
there is a second problem: i malloc space for the three arrays twoago, oneago, and thisrow,
then they get swapped around in a circular fashion. when i try to free( twoago ) and so on, i get a
line where glibc complains about double free or corruption. i googled for that; could it be that the
pointer-swapping business makes glibc a bit dizzy so it becomes unable to correctly free memory?
below i list first the setup.py that is needed to do the compilation
(/path/to/python3.1 ./setup.py build_ext --inplace), then the edit distance code proper, so interested
people find it easier to replicate.
one more thing: this is run with Python3.1; one funny thing is that inside the *.pyx file we do have
bare unicode strings, but print is still a statement, not a function.
and yes i know this is a lot of code to paste here but the thing is the code is simply not runnable when you
cut it down all too much. i believe all methods except editdistance() to work correctly, but feel free
to point out any problems you perceive.
setup.py:
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
setup(
name = 'cython_dameraulevenshtein',
ext_modules = [
Extension( 'cython_dameraulevenshtein', [ 'cython_dameraulevenshtein.pyx', ] ), ],
cmdclass = {
'build_ext': build_ext }, )
cython_dameraulevenshtein.pyx (scroll all the way to the end to see the interesting stuff):
############################################################################################################
cdef extern from "stdlib.h":
ctypedef unsigned int size_t
void *malloc(size_t size)
void *realloc( void *ptr, size_t size )
void free(void *ptr)
#-----------------------------------------------------------------------------------------------------------
cdef inline unsigned int _minimum_of_two_uints( unsigned int a, unsigned int b ):
if a < b: return a
return b
#-----------------------------------------------------------------------------------------------------------
cdef inline unsigned int _minimum_of_three_uints( unsigned int a, unsigned int b, unsigned int c ):
if a < b:
if c < a:
return c
return a
if c < b:
return c
return b
#-----------------------------------------------------------------------------------------------------------
cdef inline int _warp( unsigned int limit, int value ):
return value if value >= 0 else limit + value
############################################################################################################
# ARRAYS THAT SAY SIZE ;-)
#-----------------------------------------------------------------------------------------------------------
cdef class Array_of_unsigned_int:
cdef unsigned int *data
cdef unsigned int length
#---------------------------------------------------------------------------------------------------------
def __cinit__( self, unsigned int length, fill_value = None ):
self.length = length
self.data = <unsigned int *>malloc( length * sizeof( unsigned int ) ) ###OBS### must check malloc doesn't return NULL pointer
if fill_value is not None:
self.fill( fill_value )
#---------------------------------------------------------------------------------------------------------
cdef fill( self, unsigned int value ):
cdef unsigned int idx
cdef unsigned int *d = self.data
for idx from 0 <= idx < self.length:
d[ idx ] = value
#---------------------------------------------------------------------------------------------------------
cdef resize( self, unsigned int length ):
self.data = <unsigned int *>realloc( self.data, length * sizeof( unsigned int ) ) ###OBS### must check realloc doesn't return NULL pointer
self.length = length
#---------------------------------------------------------------------------------------------------------
def free( self ):
"""Always remember the milk: Free up memory."""
free( self.data ) ###OBS### should free memory here
#---------------------------------------------------------------------------------------------------------
def as_list( self ):
"""Return the array as a Python list."""
R = []
cdef unsigned int idx
cdef unsigned int *d = self.data
for idx from 0 <= idx < self.length:
R.append( d[ idx ] )
return R
############################################################################################################
# CONVERTING UNICODE TO CHARACTER IDs (CIDs)
#---------------------------------------------------------------------------------------------------------
cdef unsigned int _UMX_surrogate_lower_bound = 0x10000
cdef unsigned int _UMX_surrogate_upper_bound = 0x10ffff
cdef unsigned int _UMX_surrogate_hi_lower_bound = 0xd800
cdef unsigned int _UMX_surrogate_hi_upper_bound = 0xdbff
cdef unsigned int _UMX_surrogate_lo_lower_bound = 0xdc00
cdef unsigned int _UMX_surrogate_lo_upper_bound = 0xdfff
cdef unsigned int _UMX_surrogate_foobar_factor = 0x400
#---------------------------------------------------------------------------------------------------------
cdef Array_of_unsigned_int _cids_from_text( text ):
"""Givn a ``text`` either as a Unicode string or as a ``bytes`` or ``bytearray``, return an instance of
``Array_of_unsigned_int`` that enumerates either the Unicode codepoints of each character or the value of
each byte. Surrogate pairs will be condensed into single values, so on narrow Python builds the length of
the array returned may be less than ``len( text )``."""
#.........................................................................................................
# Make sure ``text`` is either a Unicode string (``str``) or a ``bytes``-like thing:
is_bytes = isinstance( text, ( bytes, bytearray, ) )
assert is_bytes or isinstance( text, str ), '#121'
#.........................................................................................................
# Whether it is a ``str`` or a ``bytes``, we know the result can only have at most as many elements as
# there are characters in ``text``, so we can already reserve that much space (in the case of a Unicode
# text, there may be fewer CIDs if there happen to be surrogate characters):
cdef unsigned int length = <unsigned int>len( text )
cdef Array_of_unsigned_int R = Array_of_unsigned_int( length )
#.........................................................................................................
# If ``text`` is empty, we can return an empty array right away:
if length == 0: return R
#.........................................................................................................
# Otherwise, prepare to copy data:
cdef unsigned int idx = 0
#.........................................................................................................
# If ``text`` is a ``bytes``-like thing, use simplified processing; we just have to copy over all byte
# values and are done:
if is_bytes:
for idx from 0 <= idx < length:
R.data[ idx ] = <unsigned int>text[ idx ]
return R
#.........................................................................................................
cdef unsigned int cid = 0
cdef bool is_surrogate = False
cdef unsigned int hi = 0
cdef unsigned int lo = 0
cdef unsigned int chr_count = 0
#.........................................................................................................
# Iterate over all indexes in text:
for idx from 0 <= idx < length:
#.......................................................................................................
# If we met with a surrogate CID in the last cycle, then that was a high surrogate CID, and the
# corresponding low CID is on the current position. Having both, we can compute the intended CID
# and reset the flag:
if is_surrogate:
lo = <unsigned int>ord( text[ idx ] )
# IIRC, this formula was documented in Unicode 3:
cid = ( ( hi - _UMX_surrogate_hi_lower_bound ) * _UMX_surrogate_foobar_factor
+ ( lo - _UMX_surrogate_lo_lower_bound ) + _UMX_surrogate_lower_bound )
is_surrogate = False
#.......................................................................................................
else:
# Otherwise, we retrieve the CID from the current position:
cid = <unsigned int>ord( text[ idx ] )
#.....................................................................................................
if _UMX_surrogate_hi_lower_bound <= cid <= _UMX_surrogate_hi_upper_bound:
# If this CID is a high surrogate CID, set ``hi`` to this value and set a flag so we'll come back
# in the next cycle:
hi = cid
is_surrogate = True
continue
#.......................................................................................................
R.data[ chr_count ] = cid
chr_count += 1
#.........................................................................................................
# Surrogate CIDs take up two characters but end up as a single resultant CID, so the return value may
# have fewer elements than the naive string length indicated; in this case, we want to free some memory
# and correct array length data:
if chr_count != length:
R.resize( chr_count )
#.........................................................................................................
return R
#---------------------------------------------------------------------------------------------------------
def cids_from_text( text ):
cdef Array_of_unsigned_int c_R =_cids_from_text( text )
R = c_R.as_list()
c_R.free() ###OBS### should free memory here
return R
############################################################################################################
# SECOND-ORDER SIMILARITY
#-----------------------------------------------------------------------------------------------------------
cpdef float similarity( char *a, char *b ):
"""Given two byte strings ``a`` and ``b``, return their Damerau-Levenshtein similarity as a float between
0.0 and 1.1. Similarity is computed as ``1 - relative_editdistance( a, b )``, so a result of ``1.0``
indicates identity, while ``0.0`` indicates complete dissimilarity."""
return 1.0 - relative_editdistance( a, b )
#-----------------------------------------------------------------------------------------------------------
cpdef float relative_editdistance( char *a, char *b ):
"""Given two byte strings ``a`` and ``b``, return their relative Damerau-Levenshtein distance. The return
value is a float between 0.0 and 1.0; it is calculated as the absolute edit distance, divided by the
length of the longer string. Therefore, ``0.0`` indicates identity, while ``1.0`` indicates complete
dissimilarity."""
cdef int length = max( len( a ), len( b ) )
if length == 0: return 0.0
return editdistance( a, b ) / <float>length
############################################################################################################
# EDIT DISTANCE
#-----------------------------------------------------------------------------------------------------------
cpdef unsigned int editdistance( text_a, text_b ):
"""Given texts as Unicode strings or ``bytes`` / ``bytearray`` objects, return their absolute
Damerau-Levenshtein distance. Each deletion, insertion, substitution, and transposition is counted as one
difference, so the edit distance between ``abc`` and ``ab``, ``abcx``, ``abx``, ``acb``, respectively, is
``1``."""
#.........................................................................................................
# This should be fast in Python, as it can (and probably is) implemented by doing an identity check in
# the case of ``bytes`` and ``str`` objects:
if text_a == text_b: return 0
#.........................................................................................................
# Convert Unicode text to C array of unsigned integers:
cdef Array_of_unsigned_int a = _cids_from_text( text_a )
cdef Array_of_unsigned_int b = _cids_from_text( text_b )
R = c_editdistance( a, b )
#.........................................................................................................
# Always remember the milk:
a.free()
b.free()
#.........................................................................................................
return R
#-----------------------------------------------------------------------------------------------------------
cdef unsigned int c_editdistance( Array_of_unsigned_int cids_a, Array_of_unsigned_int cids_b ):
# Conceptually, this is based on a len(a) + 1 * len(b) + 1 matrix.
# However, only the current and two previous rows are needed at once,
# so we only store those.
#.........................................................................................................
# This shortcut is pretty useless if comparison is not very fast; therefore, it is done in the function
# that deals with the Python objects, q.v.
# if cids_a.equals( cids_b ): return 0
#.........................................................................................................
cdef unsigned int a_length = cids_a.length
cdef unsigned int b_length = cids_b.length
#.........................................................................................................
# Another shortcut: if one of the texts is empty, then the edit distance is trivially the length of the
# other text. This also works for two empty texts, but those have already been taken care of by the
# previous shortcut:
#.........................................................................................................
if a_length == 0: return b_length
if b_length == 0: return a_length
#.........................................................................................................
cdef unsigned int row_length = b_length + 1
cdef unsigned int row_length_1 = row_length - 1
cdef unsigned int row_bytecount = sizeof( unsigned int ) * row_length
cdef unsigned int *oneago = <unsigned int *>malloc( row_bytecount ) ###OBS### must check malloc doesn't return NULL pointer
cdef unsigned int *twoago = <unsigned int *>malloc( row_bytecount ) ###OBS### must check malloc doesn't return NULL pointer
cdef unsigned int *thisrow = <unsigned int *>malloc( row_bytecount ) ###OBS### must check malloc doesn't return NULL pointer
cdef unsigned int idx = 0
cdef unsigned int idx_a = 0
cdef unsigned int idx_b = 0
cdef int idx_a_1_text = 0
cdef int idx_b_1_row = 0
cdef int idx_b_2_row = 0
cdef int idx_b_1_text = 0
cdef unsigned int deletion_cost = 0
cdef unsigned int addition_cost = 0
cdef unsigned int substitution_cost = 0
#.........................................................................................................
# Equivalent of ``thisrow = list( range( 1, b_length + 1 ) ) + [ 0 ]``:
#print( '#305', cids_a.as_list(), cids_b.as_list(), a_length, b_length, row_length, row_length_1 )
for idx from 1 <= idx < row_length:
thisrow[ idx - 1 ] = idx
thisrow[ row_length - 1 ] = 0
#.........................................................................................................
for idx_a from 0 <= idx_a < a_length:
idx_a_1_text = _warp( a_length, idx_a - 1 )
twoago, oneago = oneago, thisrow
#.......................................................................................................
# Equivalent of ``thisrow = [ 0 ] * b_length + [ idx_a + 1 ]``:
for idx from 0 <= idx < row_length_1:
thisrow[ idx ] = 0
thisrow[ row_length - 1 ] = idx_a + 1
#.......................................................................................................
# some diagnostic output:
x = []
for idx from 0 <= idx < row_length: x.append( thisrow[ idx ] )
print
print '#ED A', x
#.......................................................................................................
for idx_b from 0 <= idx_b < b_length:
#.....................................................................................................
idx_b_1_row = _warp( row_length, idx_b - 1 )
idx_b_1_text = _warp( b_length, idx_b - 1 )
#.....................................................................................................
assert 0 <= idx_b_1_row < row_length, ( '#323', idx_b_1_row, )
assert 0 <= idx_a_1_text < a_length, ( '#324', idx_a_1_text, )
assert 0 <= idx_b_1_text < b_length, ( '#325', idx_b_1_text, )
#.....................................................................................................
deletion_cost = oneago[ idx_b ] + 1
addition_cost = thisrow[ idx_b_1_row ] + 1
substitution_cost = oneago[ idx_b_1_row ] + ( 1 if cids_a.data[ idx_a ]
!= cids_b.data[ idx_b ] else 0 )
thisrow[ idx_b ] = _minimum_of_three_uints( deletion_cost, addition_cost, substitution_cost )
#.....................................................................................................
# Transpositions:
if ( idx_a > 0
and idx_b > 0
and cids_a.data[ idx_a ] == cids_b.data[ idx_b_1_text ]
and cids_a.data[ idx_a_1_text ] == cids_b.data[ idx_b ]
and cids_a.data[ idx_a ] != cids_b.data[ idx_b ] ):
#...................................................................................................
idx_b_2_row = _warp( row_length, idx_b - 2 )
assert 0 <= idx_b_2_row < row_length, ( '#340', idx_b_2_row, )
thisrow[ idx_b ] = _minimum_of_two_uints( thisrow[ idx_b ], twoago[ idx_b_2_row ] + 1 )
#.....................................................................................................
# some diagnostic output:
x = []
for idx from 0 <= idx < row_length: x.append( thisrow[ idx ] )
print '#ED B', x
#.........................................................................................................
# Here, ``b_length - 1`` can't become negative, since we already tested for ``b_length == 0`` in the
# shortcut above:
cdef unsigned int R = thisrow[ b_length - 1 ]
#.........................................................................................................
# Always remember the milk:
# BUG: Activating below lines leads to glibc failing with ``double free or corruption``
#free( twoago )
#free( oneago )
#free( thisrow )e
#.........................................................................................................
return R
#-----------------------------------------------------------------------------------------------------------
def editdistance_reference( text_a, text_b ):
"""This method is believed to compute a correct Damerau-Levenshtein edit distance, with deletions,
insertions, substitutions, and transpositions. Do not touch it; it is here to validate results returned
from the above method. Code adapted from
http://mwh.geek.nz/2009/04/26/python-damerau-levenshtein-distance"""
# Conceptually, the implementation is based on a ``( len( seq1 ) + 1 ) * ( len( seq2 ) + 1 )`` matrix.
# However, only the current and two previous rows are needed at once, so we only store those. Python
# lists wrap around for negative indices, so we put the leftmost column at the *end* of the list. This
# matches with the zero-indexed strings and saves extra calculation.
b_length = len( text_b )
oneago = None
thisrow = list( range( 1, b_length + 1 ) ) + [ 0 ]
for idx_a in range( len( text_a ) ):
twoago, oneago, thisrow = oneago, thisrow, [ 0 ] * b_length + [ idx_a + 1 ]
#.......................................................................................................
# some diagnostic output:
print
print '#EDR A', thisrow
#.......................................................................................................
for idx_b in range( b_length ):
deletion_cost = oneago[ idx_b ] + 1
addition_cost = thisrow[ idx_b - 1 ] + 1
substitution_cost = oneago[ idx_b - 1 ] + ( text_a[ idx_a ] != text_b[ idx_b ] )
thisrow[ idx_b ] = min( deletion_cost, addition_cost, substitution_cost )
if ( idx_a > 0
and idx_b > 0
and text_a[ idx_a ] == text_b[ idx_b - 1 ]
and text_a[ idx_a - 1 ] == text_b[ idx_b ]
and text_a[ idx_a ] != text_b[ idx_b ] ):
thisrow[ idx_b ] = min( thisrow[ idx_b ], twoago[ idx_b - 2 ] + 1 )
#.....................................................................................................
# some diagnostic output:
print '#EDR B', thisrow
#.....................................................................................................
return thisrow[ len( text_b ) - 1 ]
edit i also posted this text to pastebin and the Cython list.
| [
"Do some elementary debugging. You know that it is going wrong in the 2nd output line marked #ED B. The wrong values seem to indicate that it finds one edit early on and never finds any more. This is possibly because one of the min() args is somehow clamped at 1. Print deletion_cost, substitution_cost, addition_cos... | [
2
] | [] | [] | [
"cython",
"edit_distance",
"levenshtein_distance",
"python",
"python_3.x"
] | stackoverflow_0003431933_cython_edit_distance_levenshtein_distance_python_python_3.x.txt |
Q:
Scraping landing pages of a list of domains
I have a reasonably long list of websites that I want to download the
landing (index.html or equivalent) pages for. I am currently using Scrapy (much love to the guys behind it -- this is a fabulous framework). Scrapy is slower on this particular task than I'd like and I am wondering if wget or an other alternative would be faster given how straightforward the task is. Any ideas?
(Here's what I am doing with Scrapy. Anything I can do to optimize scrapy for this task? )
So, I have a start URLs list like
start_urls=[google.com
yahoo.com
aol.com]
And I scrape the text from each response and store this in an xml. I need to turn of the offsitemiddleware to allow for multiple domains.
Scrapy works as expected, but seems slow (About 1000 in an hour or 1
every 4 seconds). Is there a way to speed this up by increasing the
number of CONCURRENT_REQUESTS_PER_SPIDER while running a single
spider? Anything else?
A:
If you want a way to concurrently download multiple sites with python, you can do so with the standard libraries like this:
import threading
import urllib
maxthreads = 4
sites = ['google.com', 'yahoo.com', ] # etc.
class Download(threading.Thread):
def run (self):
global sites
while sites:
site = sites.pop()
print "start", site
urllib.urlretrieve('http://' + site, site)
print "end ", site
for x in xrange(min(maxthreads, len(sites))):
Download().start()
You could also check out httplib2 or PycURL to do the downloading for you instead of urllib.
I'm not clear exactly how you want the scraped text as xml to look, but you could use xml.etree.ElementTree from the standard library or you could install BeautifulSoup (which would be better as it handles malformed markup).
| Scraping landing pages of a list of domains | I have a reasonably long list of websites that I want to download the
landing (index.html or equivalent) pages for. I am currently using Scrapy (much love to the guys behind it -- this is a fabulous framework). Scrapy is slower on this particular task than I'd like and I am wondering if wget or an other alternative would be faster given how straightforward the task is. Any ideas?
(Here's what I am doing with Scrapy. Anything I can do to optimize scrapy for this task? )
So, I have a start URLs list like
start_urls=[google.com
yahoo.com
aol.com]
And I scrape the text from each response and store this in an xml. I need to turn of the offsitemiddleware to allow for multiple domains.
Scrapy works as expected, but seems slow (About 1000 in an hour or 1
every 4 seconds). Is there a way to speed this up by increasing the
number of CONCURRENT_REQUESTS_PER_SPIDER while running a single
spider? Anything else?
| [
"If you want a way to concurrently download multiple sites with python, you can do so with the standard libraries like this:\nimport threading\nimport urllib\n\nmaxthreads = 4\n\nsites = ['google.com', 'yahoo.com', ] # etc.\n\nclass Download(threading.Thread):\n def run (self):\n global sites\n while ... | [
4
] | [] | [] | [
"python",
"scrapy",
"screen_scraping"
] | stackoverflow_0002501838_python_scrapy_screen_scraping.txt |
Q:
Building a comet server from twisted.web, for a twisted.web site
So I have a website already set up, and I need a comet server for a chat application. The site is built with twisted.web, and I want to build the comet server with twisted as well since I'm already somewhat familiar with it.
But I'm not sure how to do it. I've looked at this post and understand the mechanics in the code snippet -- but I tried it and the page takes AGES to load, and when it does, it's already full of times, and then continues adding them.
My idea of how this would work is, I would have this running as a separate process, and then run my twisted site on another. A page in the twisted site would have an ajax call to the comet server, which would wait for a response. But would that response take ages to return like the page load did?
And how would the comet server best get data from the website server? It wouldn't just poll the website or I may as well have no comet server -- would I just put an infinite loop in the GET handler for the comet server, and have the website call it and interrupt? How would the comet server and website share data? Like, how would the comet server know anything about a user's session data -- who they are, what they're waiting for, what it can send to them?
Also, I'm not sure about this, but do I have to incorporate threading into the comet server, or is it multithreaded already?
A:
You can use Orbited (which is a comet server based on Twisted) and run it in the same process as your web server. It's pretty slick. Instead of using its built-in proxy, you just use its guts directly. You'd do something like:
from orbited.cometsession import Port
...
reactor.listenWith(Port, factory=someFactoryYouWrote, resource=someResourceYouWrote, childName='tcp')
| Building a comet server from twisted.web, for a twisted.web site | So I have a website already set up, and I need a comet server for a chat application. The site is built with twisted.web, and I want to build the comet server with twisted as well since I'm already somewhat familiar with it.
But I'm not sure how to do it. I've looked at this post and understand the mechanics in the code snippet -- but I tried it and the page takes AGES to load, and when it does, it's already full of times, and then continues adding them.
My idea of how this would work is, I would have this running as a separate process, and then run my twisted site on another. A page in the twisted site would have an ajax call to the comet server, which would wait for a response. But would that response take ages to return like the page load did?
And how would the comet server best get data from the website server? It wouldn't just poll the website or I may as well have no comet server -- would I just put an infinite loop in the GET handler for the comet server, and have the website call it and interrupt? How would the comet server and website share data? Like, how would the comet server know anything about a user's session data -- who they are, what they're waiting for, what it can send to them?
Also, I'm not sure about this, but do I have to incorporate threading into the comet server, or is it multithreaded already?
| [
"You can use Orbited (which is a comet server based on Twisted) and run it in the same process as your web server. It's pretty slick. Instead of using its built-in proxy, you just use its guts directly. You'd do something like:\nfrom orbited.cometsession import Port\n...\nreactor.listenWith(Port, factory=someFactor... | [
1
] | [] | [] | [
"comet",
"python",
"twisted.web"
] | stackoverflow_0003432452_comet_python_twisted.web.txt |
Q:
Hot swapping python code (duck type functions?)
I've been thinking about this far too long and haven't gotten any idea, maybe some of you can help.
I have a folder of python scripts, all of which have the same surrounding body (literally, I generated it from a shell script), but have one chunk that's different than all of them. In other words:
Top piece of code (always the same)
Middle piece of code (changes from file to file)
Bottom piece of code (always the same)
And I realized today that this is a bad idea, for example, if I want to change something from the top or bottom sections, I need to write a shell script to do it. (Not that that's hard, it just seems like it's very bad code wise).
So what I want to do, is have one outer python script that is like this:
Top piece of code
Dynamic function that calls the middle piece of code (based on a parameter)
Bottom piece of code
And then every other python file in the folder can simply be the middle piece of code. However, normal module wouldn't work here (unless I'm mistaken), because I would get the code I need to execute from the arguement, which would be a string, and thus I wouldn't know which function to run until runtime.
So I thought up two more solutions:
I could write up a bunch of if statements, one to run each script based on a certain parameter. I rejected this, as it's even worse than the previous design.
I could use:
os.command(sys.argv[0] scriptName.py)
which would run the script, but calling python to call python doesn't seem very elegant to me.
So does anyone have any other ideas? Thank you.
A:
If you know the name of the function as a string and the name of module as a string, then you can do
mod = __import__(module_name)
fn = getattr(mod, fn_name)
fn()
A:
Another possible solution is to have each of your repetitive files import the functionality from the main file
from topAndBottom import top, bottom
top()
# do middle stuff
bottom()
A:
In addition to the several answers already posted, consider the Template Method design pattern: make an abstract class such as
class Base(object):
def top(self): ...
def bottom(self): ...
def middle(self): raise NotImplementedError
def doit(self):
self.top()
self.middle()
self.bottom()
Every pluggable module then makes a class which inherits from this Base and must override middle with the relevant code.
Perhaps not warranted for this simple case (you do still have to import the right module in order to instantiate its class and call doit on it), but still worth keeping in mind (together with its many Pythonic variations, which I have amply explained in many tech talks now available on youtube) for cases where the number or complexity of "pluggable pieces" keeps growing -- Template Method (despite its horrid name;-) is a solid, well-proven and highly scalable pattern [[sometimes a tad too rigid, but that's exactly what I address in those many tech talks -- and that problem doesn't apply to this specific use case]].
A:
However, normal module wouldn't work here (unless I'm mistaken), because I would get the code I need to execute from the arguement, which would be a string, and thus I wouldn't know which function to run until runtime.
It will work just fine - use __import__ builtin or, if you have very complex layout, imp module to import your script. And then you can get the function by module.__dict__[funcname] for example.
A:
Importing a module (as explained in other answers) is definitely the cleaner way to do this, but if for some reason that doesn't work, as long as you're not doing anything too weird you can use exec. It basically runs the content of another file as if it were included in the current file at the point where exec is called. It's the closest thing Python has to a source statement of the kind included in many shells. As a bare minimum, something like this should work:
exec(open(filename).read(None))
A:
How about this?
function do_thing_one():
pass
function do_thing_two():
pass
dispatch = { "one" : do_thing_one,
"two" : do_thing_two,
}
# do something to get your string from the command line (optparse, argv, whatever)
# and put it in variable "mystring"
# do top thing
f = dispatch[mystring]
f()
# do bottom thing
| Hot swapping python code (duck type functions?) | I've been thinking about this far too long and haven't gotten any idea, maybe some of you can help.
I have a folder of python scripts, all of which have the same surrounding body (literally, I generated it from a shell script), but have one chunk that's different than all of them. In other words:
Top piece of code (always the same)
Middle piece of code (changes from file to file)
Bottom piece of code (always the same)
And I realized today that this is a bad idea, for example, if I want to change something from the top or bottom sections, I need to write a shell script to do it. (Not that that's hard, it just seems like it's very bad code wise).
So what I want to do, is have one outer python script that is like this:
Top piece of code
Dynamic function that calls the middle piece of code (based on a parameter)
Bottom piece of code
And then every other python file in the folder can simply be the middle piece of code. However, normal module wouldn't work here (unless I'm mistaken), because I would get the code I need to execute from the arguement, which would be a string, and thus I wouldn't know which function to run until runtime.
So I thought up two more solutions:
I could write up a bunch of if statements, one to run each script based on a certain parameter. I rejected this, as it's even worse than the previous design.
I could use:
os.command(sys.argv[0] scriptName.py)
which would run the script, but calling python to call python doesn't seem very elegant to me.
So does anyone have any other ideas? Thank you.
| [
"If you know the name of the function as a string and the name of module as a string, then you can do\nmod = __import__(module_name)\nfn = getattr(mod, fn_name)\nfn()\n\n",
"Another possible solution is to have each of your repetitive files import the functionality from the main file\nfrom topAndBottom import top... | [
4,
4,
2,
0,
0,
0
] | [] | [] | [
"blender",
"python",
"python_3.x"
] | stackoverflow_0003432506_blender_python_python_3.x.txt |
Q:
How to get the size of a python object in bytes on Google AppEngine?
I need to compute the sizes of some python objects, so I can break them up and store them in memcache without hitting size limits.
'sizeof()' doesn't seem to be present on python objects in the GAE environment and sys.getsizeof() is also unavailable.
GAE itself is clearly checking sizes behind the scenes to enforce the limits. Any ideas for how to accomplish this? Thanks.
A:
memcache internally and invariably uses pickle and stores the resulting string, so you can check with len(pickle.dumps(yourobject, -1)). Note that sys.getsizeof (which requires 2.6 or better, which is why it's missing on GAE) would not really help you at all:
>>> import sys
>>> sys.getsizeof(23)
12
>>> import pickle
>>> len(pickle.dumps(23, -1))
5
since the size of a serialized pickle of the object can be quite different from the size of the object in memory, as you can see (so I guess you should feel grateful to GAE for not offering sizeof, which would have led you astray;-).
| How to get the size of a python object in bytes on Google AppEngine? | I need to compute the sizes of some python objects, so I can break them up and store them in memcache without hitting size limits.
'sizeof()' doesn't seem to be present on python objects in the GAE environment and sys.getsizeof() is also unavailable.
GAE itself is clearly checking sizes behind the scenes to enforce the limits. Any ideas for how to accomplish this? Thanks.
| [
"memcache internally and invariably uses pickle and stores the resulting string, so you can check with len(pickle.dumps(yourobject, -1)). Note that sys.getsizeof (which requires 2.6 or better, which is why it's missing on GAE) would not really help you at all:\n>>> import sys\n>>> sys.getsizeof(23)\n12\n>>> import... | [
13
] | [] | [] | [
"google_app_engine",
"memcached",
"pickle",
"python"
] | stackoverflow_0003432402_google_app_engine_memcached_pickle_python.txt |
Q:
File object in memory using Python
I'm not sure how to word this exactly but I have a script that downloads an SSL certificate from a web server to check it's expiration date.
To do this, I need to download the CA certificates. Currently I write them to a temporary file in the /tmp directory and read it back later but I am sure there must be a way to do this without writing to disk.
Here's the portion that's downloading the certificates
CA_FILE = '/tmp/ca_certs.txt'
root_cert = urllib.urlopen('https://www.cacert.org/certs/root.txt')
class3_cert = urllib.urlopen('https://www.cacert.org/certs/class3.txt')
temp_file = open(CA_FILE, 'w')
temp_file.write(root_cert.read())
temp_file.write(class3_cert.read())
temp_file.close()
EDIT
Here's the portion that uses the file to get the certificate
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ssl_sock = ssl.wrap_socket(s, ca_certs=CA_FILE, cert_reqs=ssl.CERT_REQUIRED)
ssl_sock.connect(('mail.google.com', 443))
date = ssl_sock.getpeercert()['notAfter']
A:
the response from urllib is a file object. just use those wherever you are using the actual files instead. This is assuming that the code that consumes the file objects doesn't need to write to them of course.
A:
Wow, don't do this. You're hitting cacert's site every time? That's INCREDIBLY rude and needlessly eats their resources. It's also ridiculously bad security practice. You're supposed to get the root certificate once and validate that it's the correct root cert and not some forgery, otherwise you can't rely on the validity of certificates signed by it.
Cache their root cert, or better yet, install it with the rest of the root certificates on your system like you're supposed to.
A:
In the following line:
temp_file.write(root_cert.read())
you are actually reading the certificate into memory, and writing it out again. That line is equivalent to:
filedata = root_cert.read()
temp_file.write(filedata)
Now filedata is a variable containing the bytes of the root certificate, that you can use in any way you like (including not writing it to temp_file and doing something else with it instead).
| File object in memory using Python | I'm not sure how to word this exactly but I have a script that downloads an SSL certificate from a web server to check it's expiration date.
To do this, I need to download the CA certificates. Currently I write them to a temporary file in the /tmp directory and read it back later but I am sure there must be a way to do this without writing to disk.
Here's the portion that's downloading the certificates
CA_FILE = '/tmp/ca_certs.txt'
root_cert = urllib.urlopen('https://www.cacert.org/certs/root.txt')
class3_cert = urllib.urlopen('https://www.cacert.org/certs/class3.txt')
temp_file = open(CA_FILE, 'w')
temp_file.write(root_cert.read())
temp_file.write(class3_cert.read())
temp_file.close()
EDIT
Here's the portion that uses the file to get the certificate
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ssl_sock = ssl.wrap_socket(s, ca_certs=CA_FILE, cert_reqs=ssl.CERT_REQUIRED)
ssl_sock.connect(('mail.google.com', 443))
date = ssl_sock.getpeercert()['notAfter']
| [
"the response from urllib is a file object. just use those wherever you are using the actual files instead. This is assuming that the code that consumes the file objects doesn't need to write to them of course.\n",
"Wow, don't do this. You're hitting cacert's site every time? That's INCREDIBLY rude and needlessly... | [
4,
4,
1
] | [] | [] | [
"file",
"memory",
"python"
] | stackoverflow_0003432911_file_memory_python.txt |
Q:
Generating custom forms from DB schema
I am a current web2py user, but find I still go back to Django once in a while (where I started). Specifically when working on projects where I want to make use of some specific django apps/plugins/extensions that don't yet exist in web2py.
One thing that I can't live without in web2py, which I am looking for a solution for in Django, is the way to create html forms from a db table and being able to then customize their look and layout in the view, without javascript.
Key things I am looking for:
Generate html form from a db table
Assign custom css classes/ids to each field in the generated html form (js disabled)
Place each form field/element in a pre-made html view via a method call in the view
i.e.
I have a table A. In web2py I can do (in controller):
def display_form():
form = SQLFORM(db.table_A)
#Can I do the following in Django? Assign custom CSS to each form field?
form.element(_name='email')['_class'] = = "custom_css_classes, list"
if form.accepts(request.vars, session):
response.flash = 'form accepted'
elif form.errors:
response.flash = 'form has errors'
else:
response.flash = 'please fill out the form'
return dict(form=form)
Then, in the View I can do:
form.custom.start
form.custom.widget.name
form.custom.widget.email
form.custom.widget.form_field_name
...
<div class="span-5 last"><input type="submit" class="register_btn" value="Sign Up"></input></div>
form.custom.end
The above takes a DB table, creates an HTML form, and then lets me stick each separate form field in any place in the pre-made HTML that I want (using those "custom" method calls on the passed "form" object. Including the custom css classes I assigned to each separate field of the generated html form.
See documentation for details on the above code:
http://web2py.com/book/default/chapter/06?search=define_table
http://web2py.com/book/default/chapter/07?search=sqlform#SQLFORM
http://web2py.com/book/default/chapter/05?search=#Server-side-DOM-and-Parsing
http://web2py.com/book/default/chapter/07?search=form.custom
How do I do the above in Django without dirtying my javascript with layout hacks. Assume javascript is disabled in the browsers where I need my app to run. Furthermore, I would love to make use of Django admin. Pylons solutions also welcome!
Links to articles/tutorials/howtos for this would be greatly appreciated.
Also, please make an equivalent result of the above code using the method you mention in your response...
A:
If you haven't already, take a look at Django's ModelForm. I am assuming that you have models mapped to the tables in question. Vanilla ModelForm instances will work without JS. However ModelForms are usually defined ahead of time and not constructed on the fly. I suppose they can be created on the fly but that would be a bit tricky.
A:
Use ModelForm and override any field you wanna customize by explicitly declaring them.
If you want to set field attributes like class and id, you need to do something like this:
name = forms.CharField(
widget=forms.TextInput(attrs={'class':'special'}))
In case you are interested, you may change the order of the fields by specifying a fields sequence in your Meta class:
class Meta:
model = YourModel
fields = ('title', 'content')
You may read the full documentation here:
http://docs.djangoproject.com/en/dev/ref/forms/widgets/#django.forms.Widget.attrs
| Generating custom forms from DB schema | I am a current web2py user, but find I still go back to Django once in a while (where I started). Specifically when working on projects where I want to make use of some specific django apps/plugins/extensions that don't yet exist in web2py.
One thing that I can't live without in web2py, which I am looking for a solution for in Django, is the way to create html forms from a db table and being able to then customize their look and layout in the view, without javascript.
Key things I am looking for:
Generate html form from a db table
Assign custom css classes/ids to each field in the generated html form (js disabled)
Place each form field/element in a pre-made html view via a method call in the view
i.e.
I have a table A. In web2py I can do (in controller):
def display_form():
form = SQLFORM(db.table_A)
#Can I do the following in Django? Assign custom CSS to each form field?
form.element(_name='email')['_class'] = = "custom_css_classes, list"
if form.accepts(request.vars, session):
response.flash = 'form accepted'
elif form.errors:
response.flash = 'form has errors'
else:
response.flash = 'please fill out the form'
return dict(form=form)
Then, in the View I can do:
form.custom.start
form.custom.widget.name
form.custom.widget.email
form.custom.widget.form_field_name
...
<div class="span-5 last"><input type="submit" class="register_btn" value="Sign Up"></input></div>
form.custom.end
The above takes a DB table, creates an HTML form, and then lets me stick each separate form field in any place in the pre-made HTML that I want (using those "custom" method calls on the passed "form" object. Including the custom css classes I assigned to each separate field of the generated html form.
See documentation for details on the above code:
http://web2py.com/book/default/chapter/06?search=define_table
http://web2py.com/book/default/chapter/07?search=sqlform#SQLFORM
http://web2py.com/book/default/chapter/05?search=#Server-side-DOM-and-Parsing
http://web2py.com/book/default/chapter/07?search=form.custom
How do I do the above in Django without dirtying my javascript with layout hacks. Assume javascript is disabled in the browsers where I need my app to run. Furthermore, I would love to make use of Django admin. Pylons solutions also welcome!
Links to articles/tutorials/howtos for this would be greatly appreciated.
Also, please make an equivalent result of the above code using the method you mention in your response...
| [
"If you haven't already, take a look at Django's ModelForm. I am assuming that you have models mapped to the tables in question. Vanilla ModelForm instances will work without JS. However ModelForms are usually defined ahead of time and not constructed on the fly. I suppose they can be created on the fly but that wo... | [
1,
1
] | [] | [] | [
"django",
"django_forms",
"pylons",
"python",
"web2py"
] | stackoverflow_0003431722_django_django_forms_pylons_python_web2py.txt |
Q:
Number in python - 010
Possible Duplicate:
How do you express binary literals in Python?
When using the interactive shell:
print 010
I get back an 8.
I started playing around using other numbers having zeroes before (0110 = 72, 013 = 11) but I could not figure it out...
What is going on here?
A:
Numbers entered with a leading zero are interpreted as octal (base 8).
007 == 7
010 == 8
011 == 9
A:
like many languages, an integer with a leading zero is interpreted as an octal. this means that it's base eight. for example, 020 has decimal value 16 and 030 has decimal value 24.
for the sake of completeness, this is how it works. value takes a string and returns the decimal value of that string interpreted as an octal. It doesn't do any error checking so you have to make sure that each digit is between 0 and 8. no leading 0 is necessary.
def value(s):
digits = [int(c) for c in s]
digits.reverse()
return sum(d * 8**k for k, d in enumerate(digits))
A:
Python adopted C's notation for octal and hexadecimal literals: Integer literals starting with 0 are octal, and those starting with 0x are hex.
The 0 prefix was considered error-prone, so Python 3.0 changed the octal prefix to 0o.
| Number in python - 010 |
Possible Duplicate:
How do you express binary literals in Python?
When using the interactive shell:
print 010
I get back an 8.
I started playing around using other numbers having zeroes before (0110 = 72, 013 = 11) but I could not figure it out...
What is going on here?
| [
"Numbers entered with a leading zero are interpreted as octal (base 8).\n007 == 7\n010 == 8\n011 == 9\n\n",
"like many languages, an integer with a leading zero is interpreted as an octal. this means that it's base eight. for example, 020 has decimal value 16 and 030 has decimal value 24.\nfor the sake of complet... | [
13,
3,
3
] | [] | [] | [
"numbers",
"python",
"python_2.x",
"syntax"
] | stackoverflow_0003433150_numbers_python_python_2.x_syntax.txt |
Q:
type enforcement on _ssl.sslwrap function params
The _ssl.sslwrap function appears to check to see if the sock passed in is a subclass of _socket.socket. I am passing in a class that implements the interface of _socket.socket.
It gets mad because my socket isn't a subclass. Is this something I should fix on my side, or is this something that I should ask about from the python-dev guys?
Here is the code from ssl.SSLSocket.init that is giving me grief:
self._sslobj = _ssl.sslwrap(self._sock, server_side,
keyfile, certfile,
cert_reqs, ssl_version, ca_certs,
ciphers)
In my case, self._sock is an instance of my custom socket class.
UPDATE:
I am going to look into how twisted does some of this stuff. My fake socket is getting too complicated. However, I am still curious why the _ssl module is enforcing the socket type the way it is.
A:
I agree that explicitly enforcing the type hierarchy seems un-Pythonic and that you might want to ask the developers about that.
OTOH, I wonder if it has to do with _ssl and _socket being the implementation modules for ssl and socket. I haven't used ssl, and I've barely used socket, but is it actually routinely necessary when using them to directly use _ssl or _socket?
Anyway, in the meantime, one workaround might be a proxy object that:
(a) inherits from _socket.socket (and thus does claim that it isinstance of _socket.socket), yet
(b) passes all its messages on to your actual "socket interface" compliant object.
I haven't tested this code, so I hope it is not an ignoble contribution:
def socketify( socket_protocol_compliant_object ):
import _socket
class proxy( _socket.socket ):
def __init__( self ): pass
def __getattribute__( self, attr_name ):
return getattr( socket_protocol_compliant_object, attr_name )
def __setattribute__( self, attr_name, new_value ):
setattr( socket_protocol_compliant_object, attr_name, new_value )
return proxy()
self._sslobj = _ssl.sslwrap( socketify(self._sock), server_side, keyfile, ... )
What do other Pythonists think? Is this a good idea?
| type enforcement on _ssl.sslwrap function params | The _ssl.sslwrap function appears to check to see if the sock passed in is a subclass of _socket.socket. I am passing in a class that implements the interface of _socket.socket.
It gets mad because my socket isn't a subclass. Is this something I should fix on my side, or is this something that I should ask about from the python-dev guys?
Here is the code from ssl.SSLSocket.init that is giving me grief:
self._sslobj = _ssl.sslwrap(self._sock, server_side,
keyfile, certfile,
cert_reqs, ssl_version, ca_certs,
ciphers)
In my case, self._sock is an instance of my custom socket class.
UPDATE:
I am going to look into how twisted does some of this stuff. My fake socket is getting too complicated. However, I am still curious why the _ssl module is enforcing the socket type the way it is.
| [
"I agree that explicitly enforcing the type hierarchy seems un-Pythonic and that you might want to ask the developers about that.\nOTOH, I wonder if it has to do with _ssl and _socket being the implementation modules for ssl and socket. I haven't used ssl, and I've barely used socket, but is it actually routinely n... | [
1
] | [] | [] | [
"python",
"sockets",
"ssl"
] | stackoverflow_0003433115_python_sockets_ssl.txt |
Q:
Elegant way to count frequency and correlation of many-to-many relationships with Django ORM?
I have a Pizza model and a Topping model, with a many-to-many relationship between the two.
Can you recommend an elegant way to extract:
the popularity (frequency) of each
topping
the correlation between
toppings (i.e. which sets of
toppings are most frequent)
Thanks
A:
Update: Found a better way using a separate model for the join table. Consider a relationship like this:
class Weapon(models.Model):
name = models.CharField(...)
class Unit(models.Model):
weapons = models.ManyToManyField(Weapon, through = 'Units_Weapons')
class Units_Weapons(models.Model):
unit = models.ForeignKey(Unit)
weapon = models.ForeignKey(Weapon)
Now you can do this:
from django.db.models import Count
Units_Weapons.objects.values('weapon').annotate(Count('unit'))
Original Answer:
I faced a similar situation before. In my case the models were Unit and Weapon. They had a many to many relationship. I wanted to count the popularity of weapons. This is how I went about it:
class Weapon(models.Model):
name = models.CharField(...)
class Unit(models.Model):
weapons = models.ManyToManyField(Weapon)
for weapon in Weapon.objects.all():
print "%s: %s" % (weapon.name, weapon.unit_set.count())
I think you can do the same for Pizza and Topping. I suspect there might be other (better) ways to do it.
| Elegant way to count frequency and correlation of many-to-many relationships with Django ORM? | I have a Pizza model and a Topping model, with a many-to-many relationship between the two.
Can you recommend an elegant way to extract:
the popularity (frequency) of each
topping
the correlation between
toppings (i.e. which sets of
toppings are most frequent)
Thanks
| [
"Update: Found a better way using a separate model for the join table. Consider a relationship like this:\nclass Weapon(models.Model):\n name = models.CharField(...)\n\nclass Unit(models.Model):\n weapons = models.ManyToManyField(Weapon, through = 'Units_Weapons')\n\nclass Units_Weapons(models.Model):\n un... | [
1
] | [] | [] | [
"django",
"django_orm",
"python"
] | stackoverflow_0003432184_django_django_orm_python.txt |
Q:
Is there a way to have a class evaluate as a number?
i have a python class like so:
class TAG_Short(NBTTag):
def __init__(self, value=None):
self.name = None
self.value = value
def __repr__(self):
return "TAG_Short: %i" % self.value
This tag is filled out at runtime, but i'd also like to be able to use it like:
mytag = TAG_Short(3)
mycalc = 3 + ( mytag % 2) / mytag
is there any method i need to add to the tag to allow me to use it as a valid numeric type?
A:
You have to overload some operators. For the example you present, these are the methods you should overload:
def __add__(self, other):
return self.value + other
def __mod__(self, other):
return self.value % other
def __rdiv__(self, other):
return other / self.value
See this guide for additional info
A:
I see-- what you would like is to have something like a __as_number__ method you can define in TAG_Short, which would allow you to return a number which is then used in any place where a ValueError would be about to be raised. I have no idea if there is any way to do something like that, short of implementing that metafeature yourself.
What you can do is define __add__, __radd__, __mul__, __rmul__, etc (you must define every numeric method if you want your object to truly behave like a number in every situation), and have each of them return the result of doing the desired operation with what you consider to be the number representation of the TAG_Short object.
If you find yourself doing this often enough, you may consider implementing the metafeature you describe (or first looking for a stable implementation to reuse). It would be quite feasible in Python. I think it might even be as easy as a good-old-fashioned class to be inherited from (untested code follows), with something kind of like:
class AbstractNumberImpersonator:
# child classes should define method .to_number()
def __add__( self, other ):
return self.to_number() + other
__radd__ = __add__
def __mul__( self, other ):
return self.to_number() * other
__rmul__ = __mul__
# etc - implement all the others in the same fashion
Then you could do something like:
class TAG_Short(NBTTag,AbstractNumberImpersonator):
def __init__(self, value=None):
self.name = None
self.value = value
def __repr__(self):
return "TAG_Short: %i" % self.value
def to_number(self):
return self.value
A:
http://docs.python.org/reference/datamodel.html#emulating-numeric-types
__add__, __div__ and __sub__ should get you started
A:
Yes. Overload the add method and make it behave appropriately.
| Is there a way to have a class evaluate as a number? | i have a python class like so:
class TAG_Short(NBTTag):
def __init__(self, value=None):
self.name = None
self.value = value
def __repr__(self):
return "TAG_Short: %i" % self.value
This tag is filled out at runtime, but i'd also like to be able to use it like:
mytag = TAG_Short(3)
mycalc = 3 + ( mytag % 2) / mytag
is there any method i need to add to the tag to allow me to use it as a valid numeric type?
| [
"You have to overload some operators. For the example you present, these are the methods you should overload:\ndef __add__(self, other):\n return self.value + other\n\ndef __mod__(self, other):\n return self.value % other\n\ndef __rdiv__(self, other):\n return other / self.value\n\nSee this guide for additional ... | [
4,
3,
1,
1
] | [] | [] | [
"class",
"python"
] | stackoverflow_0003433227_class_python.txt |
Q:
Python--How do I write the value of a variable into the pasteboard in iPhone (iOS 4)/
I am running iOS 4 on a jailbroken iPhone 3GS. Before I upgraded to iOS 4, I had installed Python on the iPhone and had found the following snippet of Python code to copy a variable (key in this case) to the pasteboard. I then was able to open another application and paste the value into a text field.
out = os.popen('\usr\bin\pbcopy', 'w')
out.write(key)
out.close()
Since upgrading to iOS 4, this code no longer works. I receive the following error message:
sh: pbcopy: command not found
I looked in the \usr\bin\ directory, and there is no pbcopy (or pbpaste) command listed.
Does anyone know of another way that I can use Python to copy the value of a variable into the pasteboard?
I'd greatly appreciate any help that anyone can provide.
A:
You need to install the package "Erica Utilities" available in the modmyi repository (enabled by default) in Cydia.
| Python--How do I write the value of a variable into the pasteboard in iPhone (iOS 4)/ | I am running iOS 4 on a jailbroken iPhone 3GS. Before I upgraded to iOS 4, I had installed Python on the iPhone and had found the following snippet of Python code to copy a variable (key in this case) to the pasteboard. I then was able to open another application and paste the value into a text field.
out = os.popen('\usr\bin\pbcopy', 'w')
out.write(key)
out.close()
Since upgrading to iOS 4, this code no longer works. I receive the following error message:
sh: pbcopy: command not found
I looked in the \usr\bin\ directory, and there is no pbcopy (or pbpaste) command listed.
Does anyone know of another way that I can use Python to copy the value of a variable into the pasteboard?
I'd greatly appreciate any help that anyone can provide.
| [
"You need to install the package \"Erica Utilities\" available in the modmyi repository (enabled by default) in Cydia.\n"
] | [
2
] | [] | [] | [
"ios4",
"iphone",
"pyobjc",
"python"
] | stackoverflow_0003432827_ios4_iphone_pyobjc_python.txt |
Q:
Python tags loop
How would you replace these tags with actual data:
[|RSSITEMS:]
[|RSSITEM:TITLE|]
[|RSSITEM:CONTENT|]
[|END:RSSITEMS|]
[|RSSITEMS:] starts loop at the top and ends its [|END:RSSITEMS|]
[|RSSITEM:TITLE|] and [|RSSITEM:CONTENT|] should be replaced with data from rss feeds.
Feed data is already in database.
Can not use django templates, as HTML above will be different in most cases, can not use templates. the HTML is stored in database.
A:
Maybe you could use an existing template engine instead, such as Cheetah (example) or the one from Django (example with for loop).
A:
Don't use custom templates for RSS. There is a syndication framework:
http://docs.djangoproject.com/en/dev/ref/contrib/syndication/
| Python tags loop | How would you replace these tags with actual data:
[|RSSITEMS:]
[|RSSITEM:TITLE|]
[|RSSITEM:CONTENT|]
[|END:RSSITEMS|]
[|RSSITEMS:] starts loop at the top and ends its [|END:RSSITEMS|]
[|RSSITEM:TITLE|] and [|RSSITEM:CONTENT|] should be replaced with data from rss feeds.
Feed data is already in database.
Can not use django templates, as HTML above will be different in most cases, can not use templates. the HTML is stored in database.
| [
"Maybe you could use an existing template engine instead, such as Cheetah (example) or the one from Django (example with for loop).\n",
"Don't use custom templates for RSS. There is a syndication framework:\nhttp://docs.djangoproject.com/en/dev/ref/contrib/syndication/\n"
] | [
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0003433201_python.txt |
Q:
pyGTK Multiple line input fields?
Already searched on google... doesnt seem to be there... help!
A:
http://www.pygtk.org/pygtk2tutorial/sec-TextViews.html
http://www.pygtk.org/docs/pygtk/class-gtktextview.html
| pyGTK Multiple line input fields? | Already searched on google... doesnt seem to be there... help!
| [
"http://www.pygtk.org/pygtk2tutorial/sec-TextViews.html\nhttp://www.pygtk.org/docs/pygtk/class-gtktextview.html\n"
] | [
4
] | [] | [] | [
"pygtk",
"python"
] | stackoverflow_0003433776_pygtk_python.txt |
Q:
"Vanilla" web python
I was reading on web2py framework for a hobby project of mine I am doing. I learned how to program in Python when I was younger so I do have a grasp on it. Right now I am more of a PHP dev but kindda loathe it.
I just have this doubt that pops in: Is there a way to use "Vanilla" python on the backend? I mean Vanilla like PHP, without a Framework. How does templating work in that way? I mean, with indentation and Everything it kinda misses the point.
Anyway I am trying web2py and really liking it.
A:
The mixing of logic, content, and presentation as naïvely encouraged by PHP is an abomination. It is the polar opposite of good design practice, and should not be imported to other languages (it shouldn't even be used in PHP, and thankfully the PHP world in general is ever so slowly moving away from it).
You should learn about Model-View-Controller (MVC) which, while not the final word on good real-world design, forms an important basis for modern web development practices, and serves as common ground, or a sort of lingua franca, in discussions about application layout.
Most of the time, you should be using some form of web framework, particularly one that provides templating. web2py is not a bad choice. Other popular frameworks include Pylons and Django.
Most Python web frameworks are very modular. You can use them in their entirety for everything in your app, or just bits and pieces. You might, for example, use Django's URL dispatcher, but not its models/ORM, or maybe you use everything in it except its templating engine, pulling in, say, Jinja. It's up to you.
You can even write traditional CGI scripts (take a look at the CGI module), while still using a templating engine of your choice.
You should start learning about all of these things and finding what works best for you. But the one thing you should not do is try to treat Python web development like PHP.
A:
There is no reason to do that :) but if you insist you can write on top of WSGI
I suggest that you can try a micro-framework such as web.py if u like it Vanilla style
A:
without a framework, you use WSGI. to do this, you write a function application like so:
def application(environment, start_response):
start_response("200 OK", [('Content-Type', 'text/plain')])
return "hello world"
environment contains cgi variables and other stuff. Normally what happens is application will call other functions with the same call signature and you get a chain of functions each of which handles a particular aspect of processing the request.
You are of course responsible for handling your own templates. Nothing about it is built into the language.
| "Vanilla" web python | I was reading on web2py framework for a hobby project of mine I am doing. I learned how to program in Python when I was younger so I do have a grasp on it. Right now I am more of a PHP dev but kindda loathe it.
I just have this doubt that pops in: Is there a way to use "Vanilla" python on the backend? I mean Vanilla like PHP, without a Framework. How does templating work in that way? I mean, with indentation and Everything it kinda misses the point.
Anyway I am trying web2py and really liking it.
| [
"The mixing of logic, content, and presentation as naïvely encouraged by PHP is an abomination. It is the polar opposite of good design practice, and should not be imported to other languages (it shouldn't even be used in PHP, and thankfully the PHP world in general is ever so slowly moving away from it).\nYou shou... | [
3,
2,
2
] | [] | [] | [
"backend",
"python"
] | stackoverflow_0003433806_backend_python.txt |
Q:
Python window focus
I would like to find out if a window has focus. I am using pyGTK and would be helpful to us that but have got some Xlib in my script as well.
I've used:
self.window.add_events( gdk.FOCUS_CHANGE_MASK )
self.window.connect("focus-in-event", self.helloworld)
but this gives me the event every time the window is being focused in, even if it is already focused. I want it to tell me just if it isn't focused before.
A:
You can check whether a window is active using the is-active property. Connect to notify::is-active to get a notification when the property value changes.
Example:
def is_active_changed(window, param):
print window.props.is_active
window.connect('notify::is-active', is_active_changed)
| Python window focus | I would like to find out if a window has focus. I am using pyGTK and would be helpful to us that but have got some Xlib in my script as well.
I've used:
self.window.add_events( gdk.FOCUS_CHANGE_MASK )
self.window.connect("focus-in-event", self.helloworld)
but this gives me the event every time the window is being focused in, even if it is already focused. I want it to tell me just if it isn't focused before.
| [
"You can check whether a window is active using the is-active property. Connect to notify::is-active to get a notification when the property value changes.\nExample:\ndef is_active_changed(window, param):\n print window.props.is_active\nwindow.connect('notify::is-active', is_active_changed)\n\n"
] | [
2
] | [] | [] | [
"focus",
"gtk",
"pygtk",
"python",
"xlib"
] | stackoverflow_0003433615_focus_gtk_pygtk_python_xlib.txt |
Q:
import django module
I am trying to import from django.http import HttpResponse, but I am getting the following exception:
ImportError: Settings cannot be imported, because environment variable
DJANGO_SETTINGS_MODULE is undefined.
Could anyone help me please?
Thanks in advance
A:
If you want to use Django from a (say) Python script, you have to setup the settings module as you said.
Another way of doing, is as follow:
#!/usr/bin/python
from django.core.management import setup_environ
import os
import settings
os.environ['DJANGO_SETTINGS_MODULE'] = "mysite.settings" # or just "settings" if it's on the same directory as settings.py
from mysite.myapp.models import * # import models, etc, only *after* setting up the settings module
setup_environ(settings)
# insert your code here, say saving an entry
c = MyClass()
c.text = "Hello!"
c.save()
A:
Django uses an environment variable named DJANGO_SETTINGS_MODULE to figure out where the global configuration file is. DJANGO_SETTINGS_MODULE must refer to a Python module that contains your configuration settings, and this module must be on the Python path. If you don't want to use a global configuration module for whatever reason, you have to call settings.configure from django.conf before using any Django code that uses settings:
from django.conf import settings
settings.configure(DEBUG=True, TEMPLATE_DEBUG=True,
TEMPLATE_DIRS=('/home/web-apps/myapp',
'/home/web-apps/base'))
More information is to be found in the Django docs.
| import django module | I am trying to import from django.http import HttpResponse, but I am getting the following exception:
ImportError: Settings cannot be imported, because environment variable
DJANGO_SETTINGS_MODULE is undefined.
Could anyone help me please?
Thanks in advance
| [
"If you want to use Django from a (say) Python script, you have to setup the settings module as you said.\nAnother way of doing, is as follow:\n#!/usr/bin/python\nfrom django.core.management import setup_environ\nimport os\nimport settings\n\nos.environ['DJANGO_SETTINGS_MODULE'] = \"mysite.settings\" # or just \"se... | [
4,
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003433885_django_python.txt |
Q:
add item to dictionary
i read a lot in that forum, but i couldn't find a proper way to add all items to my dictionary... So maybe someone can help me!
first a explanation:
rows = cur.fetchall()
columns=[desc[0] for desc in cur.description]
GID_Distances = {}
if len(rows) > 0:
for row in rows:
items = zip(columns, row)
GID_Distances = {}
for (name, value) in items:
GID_Distances[name]=value
rows is a list from a sql-statement. so in that list are several values with the same key... I just want to get something like a table
something like this:
{['id': 1, 'point':2], ['id':2, 'point':3]}
but for the loop above is the result just the last item, because it overwrites all before. Any ideas????
A:
If you have an iterable of pairs i.e. [(k1,v1),(k2,v2),...], you could apply dict on it to make it a dictionary. Therefore, your code could be written simply as
rows = cur.fetchall()
columns = [desc[0] for desc in cur.description]
# or: columns = list(map(operator.itemgetter(0), cur.description))
# don't call list() in Python 2.x.
GID_Distances = [dict(zip(columns, row)) for row in rows]
# note: use itertools.izip in Python 2.x
A:
you are redefining GID_Distances to a blank dictionary in the loop without first storing the value. store the rows in a list like so:
rows = cur.fetchall()
columns=[desc[0] for desc in cur.description]
results = []
for row in rows:
GID_Distances = {}
items = zip(columns, row)
for (name, value) in items:
GID_Distances[name]=value
results.append(GID_Distances)
| add item to dictionary | i read a lot in that forum, but i couldn't find a proper way to add all items to my dictionary... So maybe someone can help me!
first a explanation:
rows = cur.fetchall()
columns=[desc[0] for desc in cur.description]
GID_Distances = {}
if len(rows) > 0:
for row in rows:
items = zip(columns, row)
GID_Distances = {}
for (name, value) in items:
GID_Distances[name]=value
rows is a list from a sql-statement. so in that list are several values with the same key... I just want to get something like a table
something like this:
{['id': 1, 'point':2], ['id':2, 'point':3]}
but for the loop above is the result just the last item, because it overwrites all before. Any ideas????
| [
"If you have an iterable of pairs i.e. [(k1,v1),(k2,v2),...], you could apply dict on it to make it a dictionary. Therefore, your code could be written simply as\nrows = cur.fetchall() \ncolumns = [desc[0] for desc in cur.description] \n# or: columns = list(map(operator.itemgetter(0), cur.description))\n# don'... | [
3,
2
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0003433971_dictionary_python.txt |
Q:
Django - how to extend 3rd party models without modifying
I want to add a column to a database table but I don't want to modify the 3rd party module in case I need/decide to upgrade the module in the future. Is there a way I can add this field within my code so that with new builds I don't have to add the field manually?
A:
You can use ModelName.add_to_class (or .contribute_to_class), but if you have already run syncdb, then there is no way to automatically have it add the columns you need.
For maintainable code, you will probably want to extend by sub-classing the desired model in your own app, and use something like south to handle the database migrations, or just use a OneToOneField, and have a related model (like UserProfile is to auth.User).
A:
Take a look to Django model inheritance and abstract classes
http://docs.djangoproject.com/en/dev/topics/db/models/#multi-table-inheritance
| Django - how to extend 3rd party models without modifying | I want to add a column to a database table but I don't want to modify the 3rd party module in case I need/decide to upgrade the module in the future. Is there a way I can add this field within my code so that with new builds I don't have to add the field manually?
| [
"You can use ModelName.add_to_class (or .contribute_to_class), but if you have already run syncdb, then there is no way to automatically have it add the columns you need.\nFor maintainable code, you will probably want to extend by sub-classing the desired model in your own app, and use something like south to handl... | [
10,
1
] | [] | [] | [
"django",
"django_models",
"model",
"python"
] | stackoverflow_0003433131_django_django_models_model_python.txt |
Q:
Django model attribute to refer to arbitrary model instance
I'm working on a logging app in Django to record when models in other apps are created, changed, or deleted. All I really need to record is the user who did it, a timestamp, a type of action, and the item that was changed. The user, timestamp, and action type are all easy, but I'm not sure what a good way to store the affected item is beyond storing an id value and a class name so the item can be retrieved later. I imagine that storing the class name will result in a bit of a hacky solution in order to find the actual class, so I'm wondering if there's a better way. Does anyone know of one?
A:
Use generic relations which do just that (use instance id and model class) but are integrated in Django and you also get a shortcut attribute that returns related instance so you don't have to query it yourself. Example usage.
A:
Check out generic relations.
| Django model attribute to refer to arbitrary model instance | I'm working on a logging app in Django to record when models in other apps are created, changed, or deleted. All I really need to record is the user who did it, a timestamp, a type of action, and the item that was changed. The user, timestamp, and action type are all easy, but I'm not sure what a good way to store the affected item is beyond storing an id value and a class name so the item can be retrieved later. I imagine that storing the class name will result in a bit of a hacky solution in order to find the actual class, so I'm wondering if there's a better way. Does anyone know of one?
| [
"Use generic relations which do just that (use instance id and model class) but are integrated in Django and you also get a shortcut attribute that returns related instance so you don't have to query it yourself. Example usage.\n",
"Check out generic relations.\n"
] | [
4,
1
] | [] | [] | [
"django",
"django_models",
"generic_relations",
"python"
] | stackoverflow_0003434402_django_django_models_generic_relations_python.txt |
Q:
testing urllib2 application, http responses loaded from files
My python application makes many http requests to many urls using urllib2. I would like to build a unit test suite to test my data parsing and error handling code.
I have a directory full of test data, with a number of files, each file containing a single http response, with headers and response data. (using curl -i) In some cases, these files contain http error messages (needed to test the error handling)
Ideally, I would like to create a mock object to replace urllib2.urlopen and return a mock response object.
I'm wondering if there is an easy way to have urllib2 load an HTTP response directly from a file and have urllib2 parse this data to create the appropriate response object (as if the response was read from a url.
I tried using url's constructed with "file://" protocol, however the http response headers at the top of the file were not read nor parsed properly.
Alternatively I am considering writing a small web server class to serve the test files, however this seems like a little more work than I'd like. It would be easier to have urllib2 somehow reconstruct the response object from the http responses I've already saved in files (without having to build a web server to serve them again)
Any ideas?
A:
I think the best approach is to mock a subset of httplib.HTTPConnection (call the resulting class mockcon for concreteness in the following) and add a handler using it and subclassing HTTPHandler (to use in build_opener -- the subclassing means it can replace HTTPHandler that build_opener uses by default):
class MockHTTPHandler(urllib2.HTTPHandler):
def http_open(self, req):
return self.do_open(mockcon, req)
The mockcon class must supply the methods do_open call -- several can be dummies (i.e. accept and ignore arbitrary args and kwds and do nothing):
set_debuglevel
_set_tunnel
request
(may be interested in the 2nd arg of request, as it gives the "selector" part of the URL).
The __init__ method of mockcon gets the host part of the URL as the first arg (i.e., first after self of course) and should ignore following kwds (used to set a timeout).
The get_response method of mockcon (no args, beyond of course self) must return an http response object -- i.e., a file-like readable object which also has attributes .msg, .status, and .reason, and a method get_full_url() to return the URL.
You could use an actual httplib.HTTPResponse instance for the latter role, but you must initialize it with one mock/dummy arg that has a makefile argument (ignores its args and kwds and returns whatever), and, right after initializing it, reset its .fp argument to be a rb open file giving exactly the bytes that a real HTTP response would receive on its socket.
I think that building a full-fledged mock for the whole urllib2.urlopen call might be simpler than this attempt to reuse most of the functionality of urllib2 (and httplib which it uses internally), though perhaps not quite as simple as the "local web server" approach which you appear to think is more work. But it's worth considering all the three approaches (the mock would surely be most-lightweight/fast in operation, the local web server slowest... and would also require somehow modifying the URLs by prefixing an http://localhost:someport/ to them, of course).
A:
The server approach is definitely not more work, it's probably the easiest and least work of all your alternatives.
Check out: http://docs.python.org/library/simplehttpserver.html
A 7 line python program that when run from a certain directory will serve up all the files(and, recursively, any files in subdirectories) over HTTP.
You could probably have your unit test code start and stop the server so you don't need to leave it running even when not testing.
| testing urllib2 application, http responses loaded from files | My python application makes many http requests to many urls using urllib2. I would like to build a unit test suite to test my data parsing and error handling code.
I have a directory full of test data, with a number of files, each file containing a single http response, with headers and response data. (using curl -i) In some cases, these files contain http error messages (needed to test the error handling)
Ideally, I would like to create a mock object to replace urllib2.urlopen and return a mock response object.
I'm wondering if there is an easy way to have urllib2 load an HTTP response directly from a file and have urllib2 parse this data to create the appropriate response object (as if the response was read from a url.
I tried using url's constructed with "file://" protocol, however the http response headers at the top of the file were not read nor parsed properly.
Alternatively I am considering writing a small web server class to serve the test files, however this seems like a little more work than I'd like. It would be easier to have urllib2 somehow reconstruct the response object from the http responses I've already saved in files (without having to build a web server to serve them again)
Any ideas?
| [
"I think the best approach is to mock a subset of httplib.HTTPConnection (call the resulting class mockcon for concreteness in the following) and add a handler using it and subclassing HTTPHandler (to use in build_opener -- the subclassing means it can replace HTTPHandler that build_opener uses by default):\nclass ... | [
2,
1
] | [] | [] | [
"python",
"urllib2"
] | stackoverflow_0003278418_python_urllib2.txt |
Q:
How to use os.spawnv to send email copy using Python?
First let me say that I know it's better to use the subprocess module, but I'm editing other people's code and I'm trying to make as few changes as possible, which includes avoiding the importing any new modules. So I'd like to stick to the currently-imported modules (os, sys, and paths) if at all possible.
The code is currently (in a file called postfix-to-mailman.py that some of you may be familiar with):
if local in ('postmaster', 'abuse', 'mailer-daemon'):
os.execv("/usr/sbin/sendmail", ("/usr/sbin/sendmail", 'first@place.com'))
sys.exit(0)
This works fine (though I think sys.exit(0) might be never be called and thus be unnecessary).
I believe this replaces the current process with a call to /usr/sbin/sendmail passing it the arguments /usr/sbin/sendmail (for argv[0] i.e. itself) and 'someaddress@someplace.com', then passes the environment of the current process - including the email message in sys.stdin - to the child process.
What I'd like to do is essentially send another copy of the message before doing this. I can't use execv again because then execution will stop. So I've tried the following:
if local in ('postmaster', 'abuse', 'mailer-daemon'):
os.spawnv(os.P_WAIT, "/usr/sbin/sendmail", ("/usr/sbin/sendmail", 'other@place.com'))
os.execv("/usr/sbin/sendmail", ("/usr/sbin/sendmail", 'first@place.com'))
sys.exit(0)
However, while it sends the message to other@place.com, it never sends it to first@place.com
This surprised me because I thought using spawn would start a child process and then continue execution in the current process when it returns (or without waiting, if P_NOWAIT is used).
Incidentally, I tried os.P_NOWAIT first, but the message I got at other@place.com was empty, so at least when I used P_WAIT the message came through intact. But it still never got sent to first@place.com which is a problem.
I'd rather not use os.system if I can avoid it because I'd rather not go out to a shell environment if it can be avoided (security issues, possible performance? I admit I'm being paranoid here, but if I can avoid os.system I'd still like to).
The only thing I can think of is that the call to os.spawnv is somehow consuming/emptying the contents of sys.stdin, but that doesn't really make sense either. Ideas?
A:
While it might not make sense, that does appear to be the case
import os
os.spawnv(os.P_WAIT,"/usr/bin/wc", ("/usr/bin/wc",))
os.execv("/usr/bin/wc", ("/usr/bin/wc",))
$ cat j.py | python j.py
4 6 106
0 0 0
In which case you might do something like this
import os
import sys
buf = sys.stdin.read()
wc = os.popen("usr/sbin/sendmail other@place.com","w")
wc.write(buf)
wc.close()
wc = os.popen("usr/sbin/sendmail first@place.com","w")
wc.write(buf)
wc.close()
sys.exit(0)
A:
sys.stdin is a pipe and those aren't seekable so you can never rewind that file-like object to read its contents again. To actually invoke sendmail(1) twice, you need to save the contents of stdin, preferably in a temporary file but if the data is guaranteed to have a limited size you could safe it in memory instead.
But why go through the trouble? Do you specifically need the email copy to be a separately queued email (and if so, why)? Just add the wanted recipient in your original invocation of sendmail(1). The additional recipient will not be seen in the email headers.
if local in ('postmaster', 'abuse', 'mailer-daemon'):
os.execv("/usr/sbin/sendmail", ("/usr/sbin/sendmail",
'first@place.com',
'otheruser@example.com'))
sys.exit(0)
Oh, and the sys.exit(0) line will be executed if os.execv() for some reason fails. This'll happen if /usr/sbin/sendmail cannot be executed, e.g. if the executable file doesn't exist or isn't actually executable. In other words, this is an error condition that you should take care of.
| How to use os.spawnv to send email copy using Python? | First let me say that I know it's better to use the subprocess module, but I'm editing other people's code and I'm trying to make as few changes as possible, which includes avoiding the importing any new modules. So I'd like to stick to the currently-imported modules (os, sys, and paths) if at all possible.
The code is currently (in a file called postfix-to-mailman.py that some of you may be familiar with):
if local in ('postmaster', 'abuse', 'mailer-daemon'):
os.execv("/usr/sbin/sendmail", ("/usr/sbin/sendmail", 'first@place.com'))
sys.exit(0)
This works fine (though I think sys.exit(0) might be never be called and thus be unnecessary).
I believe this replaces the current process with a call to /usr/sbin/sendmail passing it the arguments /usr/sbin/sendmail (for argv[0] i.e. itself) and 'someaddress@someplace.com', then passes the environment of the current process - including the email message in sys.stdin - to the child process.
What I'd like to do is essentially send another copy of the message before doing this. I can't use execv again because then execution will stop. So I've tried the following:
if local in ('postmaster', 'abuse', 'mailer-daemon'):
os.spawnv(os.P_WAIT, "/usr/sbin/sendmail", ("/usr/sbin/sendmail", 'other@place.com'))
os.execv("/usr/sbin/sendmail", ("/usr/sbin/sendmail", 'first@place.com'))
sys.exit(0)
However, while it sends the message to other@place.com, it never sends it to first@place.com
This surprised me because I thought using spawn would start a child process and then continue execution in the current process when it returns (or without waiting, if P_NOWAIT is used).
Incidentally, I tried os.P_NOWAIT first, but the message I got at other@place.com was empty, so at least when I used P_WAIT the message came through intact. But it still never got sent to first@place.com which is a problem.
I'd rather not use os.system if I can avoid it because I'd rather not go out to a shell environment if it can be avoided (security issues, possible performance? I admit I'm being paranoid here, but if I can avoid os.system I'd still like to).
The only thing I can think of is that the call to os.spawnv is somehow consuming/emptying the contents of sys.stdin, but that doesn't really make sense either. Ideas?
| [
"While it might not make sense, that does appear to be the case\nimport os\n\nos.spawnv(os.P_WAIT,\"/usr/bin/wc\", (\"/usr/bin/wc\",))\nos.execv(\"/usr/bin/wc\", (\"/usr/bin/wc\",))\n\n$ cat j.py | python j.py \n 4 6 106\n 0 0 0\n\nIn which case you might do something like this\nim... | [
1,
0
] | [] | [] | [
"mailman",
"postfix_mta",
"process",
"python"
] | stackoverflow_0003269770_mailman_postfix_mta_process_python.txt |
Q:
How to develop an Avahi client/server
I am trying to develop a client/server solution using python, the server must broadcast the service availability using Avahi. I am using the following code to publish the service:
import avahi
import dbus
__all__ = ["ZeroconfService"]
class ZeroconfService:
"""A simple class to publish a network service with zeroconf using
avahi.
"""
def __init__(self, name, port, stype="_http._tcp",
domain="", host="", text=""):
self.name = name
self.stype = stype
self.domain = domain
self.host = host
self.port = port
self.text = text
def publish(self):
bus = dbus.SystemBus()
server = dbus.Interface(
bus.get_object(
avahi.DBUS_NAME,
avahi.DBUS_PATH_SERVER),
avahi.DBUS_INTERFACE_SERVER)
g = dbus.Interface(
bus.get_object(avahi.DBUS_NAME,
server.EntryGroupNew()),
avahi.DBUS_INTERFACE_ENTRY_GROUP)
g.AddService(avahi.IF_UNSPEC, avahi.PROTO_UNSPEC,dbus.UInt32(0),
self.name, self.stype, self.domain, self.host,
dbus.UInt16(self.port), self.text)
g.Commit()
self.group = g
def unpublish(self):
self.group.Reset()
def test():
service = ZeroconfService(name="TestService", port=3000)
service.publish()
raw_input("Press any key to unpublish the service ")
service.unpublish()
if __name__ == "__main__":
test()
As for the client, I am trying to search for the the service with:
# http://avahi.org/wiki/PythonBrowseExample
import dbus, gobject, avahi
from dbus import DBusException
from dbus.mainloop.glib import DBusGMainLoop
# Looks for iTunes shares
TYPE = "_http._tcp"
def service_resolved(*args):
print 'service resolved'
print 'name:', args[2]
print 'address:', args[7]
print 'port:', args[8]
def print_error(*args):
print 'error_handler'
print args[0]
def myhandler(interface, protocol, name, stype, domain, flags):
print "Found service '%s' type '%s' domain '%s' " % (name, stype, domain)
if flags & avahi.LOOKUP_RESULT_LOCAL:
# local service, skip
pass
server.ResolveService(interface, protocol, name, stype,
domain, avahi.PROTO_UNSPEC, dbus.UInt32(0),
reply_handler=service_resolved, error_handler=print_error)
loop = DBusGMainLoop()
bus = dbus.SystemBus(mainloop=loop)
server = dbus.Interface( bus.get_object(avahi.DBUS_NAME, '/'),
'org.freedesktop.Avahi.Server')
sbrowser = dbus.Interface(bus.get_object(avahi.DBUS_NAME,
server.ServiceBrowserNew(avahi.IF_UNSPEC,
avahi.PROTO_UNSPEC, TYPE, 'local', dbus.UInt32(0))),
avahi.DBUS_INTERFACE_SERVICE_BROWSER)
sbrowser.connect_to_signal("ItemNew", myhandler)
gobject.MainLoop().run()
However the client is not detecting when the service is started. Any ideas on what I am doing wrong ?
A:
I have found that the code works as expect. I had firewall rules blocking the avahi related publishing.
| How to develop an Avahi client/server | I am trying to develop a client/server solution using python, the server must broadcast the service availability using Avahi. I am using the following code to publish the service:
import avahi
import dbus
__all__ = ["ZeroconfService"]
class ZeroconfService:
"""A simple class to publish a network service with zeroconf using
avahi.
"""
def __init__(self, name, port, stype="_http._tcp",
domain="", host="", text=""):
self.name = name
self.stype = stype
self.domain = domain
self.host = host
self.port = port
self.text = text
def publish(self):
bus = dbus.SystemBus()
server = dbus.Interface(
bus.get_object(
avahi.DBUS_NAME,
avahi.DBUS_PATH_SERVER),
avahi.DBUS_INTERFACE_SERVER)
g = dbus.Interface(
bus.get_object(avahi.DBUS_NAME,
server.EntryGroupNew()),
avahi.DBUS_INTERFACE_ENTRY_GROUP)
g.AddService(avahi.IF_UNSPEC, avahi.PROTO_UNSPEC,dbus.UInt32(0),
self.name, self.stype, self.domain, self.host,
dbus.UInt16(self.port), self.text)
g.Commit()
self.group = g
def unpublish(self):
self.group.Reset()
def test():
service = ZeroconfService(name="TestService", port=3000)
service.publish()
raw_input("Press any key to unpublish the service ")
service.unpublish()
if __name__ == "__main__":
test()
As for the client, I am trying to search for the the service with:
# http://avahi.org/wiki/PythonBrowseExample
import dbus, gobject, avahi
from dbus import DBusException
from dbus.mainloop.glib import DBusGMainLoop
# Looks for iTunes shares
TYPE = "_http._tcp"
def service_resolved(*args):
print 'service resolved'
print 'name:', args[2]
print 'address:', args[7]
print 'port:', args[8]
def print_error(*args):
print 'error_handler'
print args[0]
def myhandler(interface, protocol, name, stype, domain, flags):
print "Found service '%s' type '%s' domain '%s' " % (name, stype, domain)
if flags & avahi.LOOKUP_RESULT_LOCAL:
# local service, skip
pass
server.ResolveService(interface, protocol, name, stype,
domain, avahi.PROTO_UNSPEC, dbus.UInt32(0),
reply_handler=service_resolved, error_handler=print_error)
loop = DBusGMainLoop()
bus = dbus.SystemBus(mainloop=loop)
server = dbus.Interface( bus.get_object(avahi.DBUS_NAME, '/'),
'org.freedesktop.Avahi.Server')
sbrowser = dbus.Interface(bus.get_object(avahi.DBUS_NAME,
server.ServiceBrowserNew(avahi.IF_UNSPEC,
avahi.PROTO_UNSPEC, TYPE, 'local', dbus.UInt32(0))),
avahi.DBUS_INTERFACE_SERVICE_BROWSER)
sbrowser.connect_to_signal("ItemNew", myhandler)
gobject.MainLoop().run()
However the client is not detecting when the service is started. Any ideas on what I am doing wrong ?
| [
"I have found that the code works as expect. I had firewall rules blocking the avahi related publishing.\n"
] | [
4
] | [] | [] | [
"avahi",
"python"
] | stackoverflow_0003430245_avahi_python.txt |
Q:
How to get unpickling to work with iPython?
I'm trying to load pickled objects in iPython.
The error I'm getting is:
AttributeError: 'FakeModule' object has no attribute 'World'
Anybody know how to get it to work, or at least a workaround for loading objects in iPython in order to interactively browse them?
Thanks
edited to add:
I have a script called world.py that basically does:
import pickle
class World:
""
if __name__ == '__main__':
w = World()
pickle.dump(w, open("file", "wb"))
Than in a REPL I do:
import pickle
from world import World
w = pickle.load(open("file", "rb"))
which works in the vanilla python REPL but not with iPython.
I'm using Python 2.6.5 and iPython 0.10 both from the Enthought Python Distribution but I was also having the problem with previous versions.
A:
Looks like you've modified FakeModule between the time you pickled your data, and the time you're trying to unpickle it: specifically, you have removed from that module some top-level object named World (perhaps a class, perhaps a function).
Pickling serializes classes and function "by name", so they need to be names at their module's top level and that module must not be modified (at least not in such way to affect those names badly -- definitely not by removing those names from the module!) between pickling time and unpickling time.
Once you've identified exactly what change you've done that impedes the unpickling, it can often be hacked around if for other reasons you can't just revert the change. For example, if you've just moved World from FakeModule to CoolModule, do:
import FakeModule
import CoolModule
FakeModule.World = CoolModule.World
just before unpickling (and remember to pickle again with the new structure so you won't have to keep repeating these hacks every time you unpickle;-).
Edit: the OP's edit of the Q makes his error much easier to understand. Since he's now testing if __name__ equals '__main__', this makes it obvious that the pickle, when written, will be saving an object of class __main__.World. Since he's using ASCII pickles (a very bad choice for performance and disk space, by the way), it's trivial to check:
$ cat file
(i__main__
World
p0
(dp1
the module being looked up is (clearly and obviously) __main__. Now, without even bothering ipython but with a simple Python interactive interpreter:
$ py26
Python 2.6.5 (r265:79359, Mar 24 2010, 01:32:55)
[GCC 4.0.1 (Apple Inc. build 5493)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import world
>>> import pickle
>>> pickle.load(open("file", "rb"))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/pickle.py", line 1370, in load
return Unpickler(file).load()
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/pickle.py", line 858, in load
dispatch[key](self)
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/pickle.py", line 1069, in load_inst
klass = self.find_class(module, name)
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/pickle.py", line 1126, in find_class
klass = getattr(mod, name)
AttributeError: 'module' object has no attribute 'World'
>>>
the error can be easily reproduced, and its reason is just as obvious: the module in which the class name's lookup is performed (that is, __main__) does indeed have no attribute named "World". Module world does have one, but the OP has not "connected the dots" as I explained in the previous part of the answer, putting a reference with the right name in the module in which the pickled file needs it. That is:
>>> World = world.World
>>> pickle.load(open("file", "rb"))
<world.World instance at 0xf5300>
>>>
now this works just perfectly, of course (and as I'd said earlier). Perhaps the OP is not seeing this problem because he's using the form of import I detest, from world import World (importing directly a function or class from within a module, rather than the module itself).
The hack to work around the problem in ipython is exactly the same in terms of underlying Python architecture -- just requires a couple more lines of code because ipython, to supply all of its extra services, does not make module __main__ directly available to record directly what happens at the interactive command line, but rather interposes one (called FakeModule, as the OP found out from the error msg;-) and does black magic with it in order to be "cool" &c. Still, whenever you want to get directly to a module with a given name, it's pretty trivial in Python, of course:
In [1]: import world
In [2]: import pickle
In [3]: import sys
In [4]: sys.modules['__main__'].World = world.World
In [5]: pickle.load(open("file", "rb"))
Out[5]: <world.World instance at 0x118fc10>
In [6]:
Lesson to retain, number one: avoid black magic, at least unless and until you're good enough as a sorcerer's apprentice to be able to spot and fix its occasional runaway situations (otherwise, those bucket-carrying brooms may end up flooding the world while you nap;-).
Or, alternative reading: to properly use a certain layer of abstraction (such as the "cool" ones ipython puts on top of Python) you need strong understanding of the underlying layer (here, Python itself and its core mechanisms such as pickling and sys.modules).
Lesson number two: that pickle file is essentially broken, due to the way you've written it, because it can be loaded only when module __main__ has a class by name Word, which of course it normally will not have without some hacks like the above. The pickle file should instead record the class as living in module world. If you absolutely feel you must produce the file on an if __name__ == '__main__': clause in world.py, then use some redundancy for the purpose:
import pickle
class World:
""
if __name__ == '__main__':
import world
w = world.World()
pickle.dump(w, open("file", "wb"))
this works fine and without hacks (at least if you follow the Python best practice of never having any substantial code at module top level -- only imports, class, def, and trivial assignments -- everything else belongs in functions; if you haven't followed this best practice, then edit your code to do so, it will make you much happier in terms of both flexibility and performance).
A:
When you pickle w in the __main__ module with pickle.dump(w, open("file", "wb")), the fact that w comes from the __main__ module is recorded on the first line of file:
% xxd file
0000000: 2869 5f5f 6d61 696e 5f5f 0a57 6f72 6c64 (i__main__.World
0000010: 0a70 300a 2864 7031 0a62 2e .p0.(dp1.b.
When IPython tries to unpickle file, it executes these lines:
/usr/lib/python2.6/pickle.pyc in find_class(self, module, name)
1124 __import__(module)
1125 mod = sys.modules[module]
-> 1126 klass = getattr(mod, name)
1127 return klass
1128
In particular, it tries to execute __import__('__main__'). If you try that in the REPL, you get
In [29]: fake=__import__('__main__')
In [32]: fake
Out[32]: <module '__main__' from '/usr/lib/pymodules/python2.6/IPython/FakeModule.pyc'>
This is the FakeModule that IPython mentions in the AttributeError.
If you look inside fake.__dict__ you'll see it doesn't include World even if you say from test import World before or after the __import__.
If you run
In [35]: fake.__dict__['World']=World
Then pickle.load will work:
In [37]: w = pickle.load(open("file", "rb"))
There might be a cleaner way; I don't know. Any way you can think of that puts World in the fake namespace should work.
PS. In 2008 Fernando Perez, the creator of IPython, wrote a little bit on this issue. He might have fixed this in some way that avoid my dirty hack. You might want to ask on the IPython-user mailing list, or, perhaps simpler, just don't pickle inside the __main__ namespace.
| How to get unpickling to work with iPython? | I'm trying to load pickled objects in iPython.
The error I'm getting is:
AttributeError: 'FakeModule' object has no attribute 'World'
Anybody know how to get it to work, or at least a workaround for loading objects in iPython in order to interactively browse them?
Thanks
edited to add:
I have a script called world.py that basically does:
import pickle
class World:
""
if __name__ == '__main__':
w = World()
pickle.dump(w, open("file", "wb"))
Than in a REPL I do:
import pickle
from world import World
w = pickle.load(open("file", "rb"))
which works in the vanilla python REPL but not with iPython.
I'm using Python 2.6.5 and iPython 0.10 both from the Enthought Python Distribution but I was also having the problem with previous versions.
| [
"Looks like you've modified FakeModule between the time you pickled your data, and the time you're trying to unpickle it: specifically, you have removed from that module some top-level object named World (perhaps a class, perhaps a function).\nPickling serializes classes and function \"by name\", so they need to be... | [
12,
2
] | [] | [] | [
"ipython",
"pickle",
"python"
] | stackoverflow_0003431419_ipython_pickle_python.txt |
Q:
simplify simple C++ code -- something like Pythons any
Right now, I have this code:
bool isAnyTrue() {
for(std::list< boost::shared_ptr<Foo> >::iterator i = mylist.begin(); i != mylist.end(); ++i) {
if( (*i)->isTrue() )
return true;
}
return false;
}
I have used Boost here and then but I couldn't really remember any simple way to write it somewhat like I would maybe write it in Python, e.g.:
def isAnyTrue():
return any(o.isTrue() for o in mylist)
Is there any construct in STL/Boost to write it more or less like this?
Or maybe an equivalent to this Python Code:
def isAnyTrue():
return any(map(mylist, lambda o: o.isTrue()))
Mostly I am wondering if there is any existing any (and all) equivalent in Boost / STL yet. Or why there is not (because it seems quite useful and I use it quite often in Python).
A:
C++ does not (yet) have a foreach construct. You have to write that yourself/
That said, you can use the std::find_if algorithm here:
bool isAnyTrue()
{
return std::find_if(mylist.begin(), mylist.end(), std::mem_fun(&Foo::isTrue))
!= mylist.end();
}
Also, you should probably be using std::vector or std::deque rather than std::list.
EDIT: sth has just informed me that this won't actually compile because your list contains shared_ptr instead of the actual objects... because of that, you're going to need to write your own functor, or rely on boost:
//#include <boost/ptr_container/indirect_fun.hpp>
bool isAnyTrue()
{
return std::find_if(mylist.begin(), mylist.end(),
boost::make_indirect_fun(std::mem_fun(&Foo::isTrue))) != mylist.end();
}
Note, I haven't tested this second solution.
A:
Instead of find_if I'd go with a custom any. I like it better in terms of readability over find_if but that's a matter of taste.
template<class ForwardIterator, class Pred>
bool any(ForwardIterator begin, ForwardIterator end, Pred pred) {
for( ; begin != end; ++begin)
if(pred(*begin)) return true;
return false;
//or
//return std::find_if(mylist.begin(), mylist.end(), std::mem_fun(&Foo::isTrue))
// != mylist.end();
}
bool isAnyTrue() {
return any(mylist.begin(), mylist.end(), std::mem_fun(&Foo::isTrue));
}
Edit: Alternative any with find_if by Billy ONeal.
A:
The new C++ standard has std::any_of, e.g.
bool isAnyTrue()
{
return std::any_of(mylist.begin(), mylist.end(), std::mem_fn(&Foo::isTrue)); // Note std::mem_fn and not std::mem_fun
}
VS2010 has this implemented.
| simplify simple C++ code -- something like Pythons any | Right now, I have this code:
bool isAnyTrue() {
for(std::list< boost::shared_ptr<Foo> >::iterator i = mylist.begin(); i != mylist.end(); ++i) {
if( (*i)->isTrue() )
return true;
}
return false;
}
I have used Boost here and then but I couldn't really remember any simple way to write it somewhat like I would maybe write it in Python, e.g.:
def isAnyTrue():
return any(o.isTrue() for o in mylist)
Is there any construct in STL/Boost to write it more or less like this?
Or maybe an equivalent to this Python Code:
def isAnyTrue():
return any(map(mylist, lambda o: o.isTrue()))
Mostly I am wondering if there is any existing any (and all) equivalent in Boost / STL yet. Or why there is not (because it seems quite useful and I use it quite often in Python).
| [
"C++ does not (yet) have a foreach construct. You have to write that yourself/\nThat said, you can use the std::find_if algorithm here:\nbool isAnyTrue()\n{\n return std::find_if(mylist.begin(), mylist.end(), std::mem_fun(&Foo::isTrue))\n != mylist.end();\n}\n\nAlso, you should probably be using std::v... | [
6,
4,
4
] | [] | [] | [
"any",
"c++",
"python"
] | stackoverflow_0003434582_any_c++_python.txt |
Q:
Python : Allowing methods not specifically defined to be called ala __getattr__
I'm trying to write a Python class that has the ability to do the following:
c = MyClass()
a = c.A("a name for A") # Calls internally c.create("A", "a name for A")
b = c.B("a name for B") # Calls internally c.create("B", "a name for B")
A and B could be anything (well, they're defined in a database, but I don't want to explicitly define them in my code)
A hacky workaround for it would be to do the following:
class MyClass():
def __init__(self):
self.createItem = ""
def create(self, itemType, itemName):
print "Creating item %s with name %s" % (itemType, itemName)
def create_wrapper(self, name):
self.create(self.createItem, name)
def __getattr__(self, attrName):
self.createItem = attrName
return self.create_wrapper
This will work when the user calls something like:
a = c.A("nameA")
b = c.B("nameB")
However, it will fall over in situations where the function pointers are stored without being called:
aFunc = c.A
bFunc = c.B
aFunc("nameA") # Is actually calling c.create("B", "nameA"),
# as c.B was the last __getattr__() call
bFunc("nameB")
Any suggestions for anything I'm missing here?
Thanks
Edit: I appear to have just figured this one out, but Philipp has a far more elegant solution....
My solution was:
class MyClassCreator():
def __init__(self, origClass, itemType):
self.origClass = origClass
self.itemType = itemType
def create_wrapper(self, name):
return self.origClass.create(self.itemType, name)
class MyClass():
def __init__(self):
self.createItem = ""
def create(self, itemType, itemName):
print "Creating item %s with name %s" % (itemType, itemName)
def __getattr__(self, attrName):
return MyClassCreator(self, attrName).create_wrapper
The version that I actually ended up using (as I needed more complexity than a single argument) is: (I don't know if this can be done using a lambda function...)
def __getattr__(self, attrName):
def find_entity_wrapper(*args, **kwargs):
return self.find_entity(attrName, *args, **kwargs)
return find_entity_wrapper
A:
Have __getattr__ return a local wrapper function:
class MyClass(object):
def create(self, itemType, itemName):
print "Creating item %s with name %s" % (itemType, itemName)
def __getattr__(self, attrName):
def create_wrapper(name):
self.create(attrName, name)
return create_wrapper
There are other ways to create the wrapper function. The simplest one in this case is to use functools.partial:
import functools
class MyClass(object):
def create(self, itemType, itemName, *args, **kwargs):
print "Creating item %s with name %s, args %r and kwargs %r" % (itemType, itemName, args, kwargs)
def __getattr__(self, attrName):
return functools.partial(self.create, attrName)
c = MyClass()
bFunc = c.B
bFunc("nameB", 1, 2, foo=3)
This will automatically pass all remaining args to the wrapped function.
A:
You can get what you want by simplifying:
class MyClass():
def create(self, itemType, itemName):
print "Creating item %s with name %s" % (itemType, itemName)
def __getattr__(self, attrName):
return lambda x: self.create(attrName, x)
c = MyClass()
a = c.A("nameA")
b = c.B("nameB")
af = c.A
bf = c.B
af("nameA")
bf("nameB")
prints:
Creating item A with name nameA
Creating item B with name nameB
Creating item A with name nameA
Creating item B with name nameB
| Python : Allowing methods not specifically defined to be called ala __getattr__ | I'm trying to write a Python class that has the ability to do the following:
c = MyClass()
a = c.A("a name for A") # Calls internally c.create("A", "a name for A")
b = c.B("a name for B") # Calls internally c.create("B", "a name for B")
A and B could be anything (well, they're defined in a database, but I don't want to explicitly define them in my code)
A hacky workaround for it would be to do the following:
class MyClass():
def __init__(self):
self.createItem = ""
def create(self, itemType, itemName):
print "Creating item %s with name %s" % (itemType, itemName)
def create_wrapper(self, name):
self.create(self.createItem, name)
def __getattr__(self, attrName):
self.createItem = attrName
return self.create_wrapper
This will work when the user calls something like:
a = c.A("nameA")
b = c.B("nameB")
However, it will fall over in situations where the function pointers are stored without being called:
aFunc = c.A
bFunc = c.B
aFunc("nameA") # Is actually calling c.create("B", "nameA"),
# as c.B was the last __getattr__() call
bFunc("nameB")
Any suggestions for anything I'm missing here?
Thanks
Edit: I appear to have just figured this one out, but Philipp has a far more elegant solution....
My solution was:
class MyClassCreator():
def __init__(self, origClass, itemType):
self.origClass = origClass
self.itemType = itemType
def create_wrapper(self, name):
return self.origClass.create(self.itemType, name)
class MyClass():
def __init__(self):
self.createItem = ""
def create(self, itemType, itemName):
print "Creating item %s with name %s" % (itemType, itemName)
def __getattr__(self, attrName):
return MyClassCreator(self, attrName).create_wrapper
The version that I actually ended up using (as I needed more complexity than a single argument) is: (I don't know if this can be done using a lambda function...)
def __getattr__(self, attrName):
def find_entity_wrapper(*args, **kwargs):
return self.find_entity(attrName, *args, **kwargs)
return find_entity_wrapper
| [
"Have __getattr__ return a local wrapper function:\nclass MyClass(object):\n def create(self, itemType, itemName):\n print \"Creating item %s with name %s\" % (itemType, itemName)\n\n def __getattr__(self, attrName):\n def create_wrapper(name):\n self.create(attrName, name)\n r... | [
8,
6
] | [] | [] | [
"class",
"methods",
"python"
] | stackoverflow_0003434938_class_methods_python.txt |
Q:
Calculate exact result of complex throw of two D30
Okay, this bugged me for several years, now. If you sucked in statistics and higher math at school, turn away, now. Too late.
Okay. Take a deep breath. Here are the rules. Take two thirty sided dice (yes, they do exist) and roll them simultaneously.
Add the two numbers
If both dice show <= 5 or >= 26, throw again and add the result to what you have
If one is <= 5 and the other >= 26, throw again and subtract the result from what
you have
Repeat until either is > 5 and < 26!
If you write some code (see below), roll those dice a few million times and you count how often you receive each number as the final result, you get a curve that is pretty flat left of 1, around 45° degrees between 1 and 60 and flat above 60. The chance to roll 30.5 or better is greater than 50%, to roll better than 18 is 80% and to roll better than 0 is 97%.
Now the question: Is it possible to write a program to calculate the exact value f(x), i.e. the probability to roll a certain value?
Background: For our role playing game "Jungle of Stars" we looked for a way to keep random events in check. The rules above guarantee a much more stable outcome for something you try :)
For the geeks around, the code in Python:
import random
import sys
def OW60 ():
"""Do an open throw with a "60" sided dice"""
val = 0
sign = 1
while 1:
r1 = random.randint (1, 30)
r2 = random.randint (1, 30)
#print r1,r2
val = val + sign * (r1 + r2)
islow = 0
ishigh = 0
if r1 <= 5:
islow += 1
elif r1 >= 26:
ishigh += 1
if r2 <= 5:
islow += 1
elif r2 >= 26:
ishigh += 1
if islow == 2 or ishigh == 2:
sign = 1
elif islow == 1 and ishigh == 1:
sign = -1
else:
break
#print sign
#print val
return val
result = [0] * 2000
N = 100000
for i in range(N):
r = OW60()
x = r+1000
if x < 0:
print "Too low:",r
if i % 1000 == 0:
sys.stderr.write('%d\n' % i)
result[x] += 1
i = 0
while result[i] == 0:
i += 1
j = len(result) - 1
while result[j] == 0:
j -= 1
pSum = 0
# Lower Probability: The probability to throw this or less
# Higher Probability: The probability to throw this or higher
print "Result;Absolut Count;Probability;Lower Probability;Rel. Lower Probability;Higher Probability;Rel. Higher Probability;"
while i <= j:
pSum += result[i]
print '%d;%d;%.10f;%d;%.10f;%d;%.10f' % (i-1000, result[i], (float(result[i])/N), pSum, (float(pSum)/N), N-pSum, (float(N-pSum)/N))
i += 1
A:
I had to first rewrite your code before I could understand it:
def OW60(sign=1):
r1 = random.randint (1, 30)
r2 = random.randint (1, 30)
val = sign * (r1 + r2)
islow = (r1<=5) + (r2<=5)
ishigh = (r1>=26) + (r2>=26)
if islow == 2 or ishigh == 2:
return val + OW60(1)
elif islow == 1 and ishigh == 1:
return val + OW60(-1)
else:
return val
Maybe you might find this less readable; I don't know. (Do check if it is equivalent to what you had in mind.) Also, regarding the way you use "result" in your code -- do you know of Python's dicts?
Anyway, matters of programming style aside: Suppose F(x) is the CDF of OW60(1), i.e.
F(x) = the probability that OW60(1) returns a value ≤ x.
Similarly let
G(x) = the probability that OW60(-1) returns a value ≤ x.
Then you can calculate F(x) from the definition, by summing over all (30×30) possible values of the result of the first throw. For instance, if the first throw is (2,3) then you'll roll again, so this term contributes (1/30)(1/30)(5+F(x-5)) to the expression for F(x). So you'll get some obscenely long expression like
F(x) = (1/900)(2+F(x-2) + 3+F(x-3) + ... + 59+F(x-59) + 60+F(x-60))
which is a sum over 900 terms, one for each pair (a,b) in [30]×[30]. The pairs (a,b) with both ≤ 5 or both ≥26 have a term a+b+F(x-a-b), the pairs with one ≤5 and one ≥26 have a term a+b+G(x-a-b), and the rest have a term like (a+b), because you don't throw again.
Similarly you have
G(x) = (1/900)(-2+F(x-2) + (-3)+F(x-3) + ... + (-59)+F(x-59) + (-60)+F(x-60))
Of course, you can collect coefficients; the only F terms that occur are from F(x-60) to F(x-52) and from F(x-10) to F(x-2) (for a,b≥26 or both≤5), and the only G terms that occur are from G(x-35) to G(x-27) (for one of a,b≥26 and the other ≤5), so there are fewer terms than 30 terms. In any case, defining the vector V(x) as
V(x) = [F(x-60) G(x-60) ... F(x-2) G(x-2) F(x-1) G(x-1) F(x) G(x)]
(say), you have (from those expressions for F and G) a relation of the form
V(x) = A*V(x-1) + B
for an appropriate matrix A and an appropriate vector B (which you can calculate), so starting from initial values of the form V(x) = [0 0] for x sufficiently small, you can find F(x) and G(x) for x in the range you want to arbitrarily close precision. (And your f(x), the probability of throwing x, is just F(x)-F(x-1), so that comes out as well.)
There might be a better way. All said and done, though, why are you doing this? Whatever kind of distribution you want, there are nice and simple probability distributions, with the appropriate parameters, that have good properties (e.g. small variance, one-sided errors, whatever). There is no reason to make up your own ad-hoc procedure to generate random numbers.
A:
I've done some basic statistics on a sample of 20 million throws. Here are the results:
Median: 17 (+18, -?) # This result is meaningless
Arithmetic Mean: 31.0 (±0.1)
Standard Deviation: 21 (+1, -2)
Root Mean Square: 35.4 (±0.7)
Mode: 36 (seemingly accurate)
The errors were determined experimentally. The arithmetic mean and the mode are really accurate, and changing the parameters even quite aggressively doesn't seem to influence them much. I suppose the behaviour of the median has already been explained.
Note: don't take these number for a proper mathematical description of the function. Use them to quickly get a picture of what the distribution looks like. For anything else, they aren't accurate enough (even though they might be precise.
Perhaps this is helpful to someone.
Edit 2:
Based on just 991 values. I could've crammed more values into it, but they would've distorted the result. This sample happens to be fairly typical.
Edit 1:
here are the above values for just one sixty-sided die, for comparison:
Median: 30.5
Arithmetic Mean: 30.5
Standard Deviation: 7.68114574787
Root Mean Square: 35.0737318611
Note that these values are calculated, not experimental.
A:
Compound unbounded probability is... non-trivial. I was going to tackle the problem the same way as James Curran, but then I saw from your source code that there could be a third set of rolls, and a fourth, and so on. The problem is solvable, but far beyond most die rolling simulators.
Is there any particular reason that you need a random range from -Inf to +Inf with such a complex curve around 1-60? Why is the bell curve of 2D30 not acceptable? If you explain your requirements, it is likely someone could provide a simpler and more bounded algorithm.
A:
Well, let's see. The second throw (which will sometimes be added or subtracted to the first roll) has a nice easily predictable bell curve around 31. The first roll, of course, is the problem.
For the first roll, we have 900 possible combinations.
50 combinations result in adding the second roll.
25 combinations result in subtracting the second roll.
Leaving 825 combinations which match the bell curve of the second roll.
The subtracting set (pre-subtraction) will form a bell curve in the range (27..35).
The lower half of the adding set will form a bell curve in the range (2..10), while the upper half will form a bell curve in the range (52...60)
My probablity is a bit rusty, so I can't figure the exact values for you, but it should be clear that these lead to predictable values.
| Calculate exact result of complex throw of two D30 | Okay, this bugged me for several years, now. If you sucked in statistics and higher math at school, turn away, now. Too late.
Okay. Take a deep breath. Here are the rules. Take two thirty sided dice (yes, they do exist) and roll them simultaneously.
Add the two numbers
If both dice show <= 5 or >= 26, throw again and add the result to what you have
If one is <= 5 and the other >= 26, throw again and subtract the result from what
you have
Repeat until either is > 5 and < 26!
If you write some code (see below), roll those dice a few million times and you count how often you receive each number as the final result, you get a curve that is pretty flat left of 1, around 45° degrees between 1 and 60 and flat above 60. The chance to roll 30.5 or better is greater than 50%, to roll better than 18 is 80% and to roll better than 0 is 97%.
Now the question: Is it possible to write a program to calculate the exact value f(x), i.e. the probability to roll a certain value?
Background: For our role playing game "Jungle of Stars" we looked for a way to keep random events in check. The rules above guarantee a much more stable outcome for something you try :)
For the geeks around, the code in Python:
import random
import sys
def OW60 ():
"""Do an open throw with a "60" sided dice"""
val = 0
sign = 1
while 1:
r1 = random.randint (1, 30)
r2 = random.randint (1, 30)
#print r1,r2
val = val + sign * (r1 + r2)
islow = 0
ishigh = 0
if r1 <= 5:
islow += 1
elif r1 >= 26:
ishigh += 1
if r2 <= 5:
islow += 1
elif r2 >= 26:
ishigh += 1
if islow == 2 or ishigh == 2:
sign = 1
elif islow == 1 and ishigh == 1:
sign = -1
else:
break
#print sign
#print val
return val
result = [0] * 2000
N = 100000
for i in range(N):
r = OW60()
x = r+1000
if x < 0:
print "Too low:",r
if i % 1000 == 0:
sys.stderr.write('%d\n' % i)
result[x] += 1
i = 0
while result[i] == 0:
i += 1
j = len(result) - 1
while result[j] == 0:
j -= 1
pSum = 0
# Lower Probability: The probability to throw this or less
# Higher Probability: The probability to throw this or higher
print "Result;Absolut Count;Probability;Lower Probability;Rel. Lower Probability;Higher Probability;Rel. Higher Probability;"
while i <= j:
pSum += result[i]
print '%d;%d;%.10f;%d;%.10f;%d;%.10f' % (i-1000, result[i], (float(result[i])/N), pSum, (float(pSum)/N), N-pSum, (float(N-pSum)/N))
i += 1
| [
"I had to first rewrite your code before I could understand it:\ndef OW60(sign=1):\n r1 = random.randint (1, 30)\n r2 = random.randint (1, 30)\n val = sign * (r1 + r2)\n\n islow = (r1<=5) + (r2<=5)\n ishigh = (r1>=26) + (r2>=26)\n\n if islow == 2 or ishigh == 2:\n return val + OW60(1)\n ... | [
6,
2,
1,
0
] | [] | [] | [
"math",
"puzzle",
"python",
"statistics"
] | stackoverflow_0000302379_math_puzzle_python_statistics.txt |
Q:
How do you mix raw SQL with ORM APIs when you use django.db?
ORM tools are great when the queries we need are simple select or insert clauses.
But sometimes we may have to fall back to use raw SQL queries, because we may need to make queries so complex that simply using the ORM API can not give us an efficient and effective solution.
What do you do to deal with the difference between objects returned from raw queries and orm queries?
A:
I personally strive to design my models so I don't have to deffer to writing raw SQL queries, or fallback to mixing in the ContentTypes framework for complex relationships, so I have no experience on the topic.
The documentation covers the topic of the APIs for performing raw SQL queries. You can either use the Manager.raw() on your models (MyModel.objects.raw()), for queries where you can map columns back to actual model fields, or user cursor to query raw rows on your database connection.
If your going to use Manager.raw(), you'll work with the RawQuerySet instead of the usual QuerySet. For all things concerned, when working with result objects the two emulate containers identically, but the QuerySet is a more feature-packed monad.
I can imagine that performing raw SQL queries in Django would be more rewarding than working with a framework with no ORM support—Django can manage your database schema and provide you with a database connection and you'll only have to manually create queries and position query arguments. The resulting rows can be accessed as lists or dictionaries, both of which make it suitable for displaying in templates or performing additional lifting.
A:
SQLAlchemy allows a fair bit of complexity in formulating queries so you can usually get away without raw sql. If you do need to dip down to raw sql, you can use connection.execute. But there are helpers like the text and select functions to make this easier when programming. As far as dealing with the returned objects, you get a list of tuples which are simple to deal with in a pythonic way.
In general, if you need to treat rows (list of tuples, etc) as what your ORM returns, one approach would be to write an adapter class which mimics a queryset interface. This could be initialized with the "schema" of the returned tuples, and then iterate and return objects with properties instead of tuples. I haven't really needed this, but I can see how it might be useful if, for example, you have a framework which relies on querysets being passed around.
| How do you mix raw SQL with ORM APIs when you use django.db? | ORM tools are great when the queries we need are simple select or insert clauses.
But sometimes we may have to fall back to use raw SQL queries, because we may need to make queries so complex that simply using the ORM API can not give us an efficient and effective solution.
What do you do to deal with the difference between objects returned from raw queries and orm queries?
| [
"I personally strive to design my models so I don't have to deffer to writing raw SQL queries, or fallback to mixing in the ContentTypes framework for complex relationships, so I have no experience on the topic.\nThe documentation covers the topic of the APIs for performing raw SQL queries. You can either use the M... | [
3,
1
] | [] | [] | [
"django_models",
"orm",
"python",
"sql"
] | stackoverflow_0003433707_django_models_orm_python_sql.txt |
Q:
Dynamic wx.RadioButtons
I'm having some trouble with the procedure below. First pass through the procedure, everything appears to work OK. Subsequent passes, the labels overwrite the previous label w/o erasing, plus the initial loop that hides the buttons doesn't appear to function.
def drawbutton(self, event):
rbuttons = [
wx.RadioButton(self,-1,'xxxxxxxxxx', (190,60),style = wx.RB_GROUP),
wx.RadioButton(self, -1,'xxxxxxxxxx', (190,80)),
wx.RadioButton(self, -1,'xxxxxxxxxx', (190,100)),
wx.RadioButton(self, -1,'xxxxxxxxxx', (190,120)),
wx.RadioButton(self, -1,'xxxxxxxxxx', (190,140)),
wx.RadioButton(self, -1,'xxxxxxxxxx', (190,160)),
wx.RadioButton(self, -1,'xxxxxxxxxx', (190,180)), ]
for i in range(7):
rbuttons[i].Hide()
i = 0
if self.combobox.GetValue() == "555-1212":
voice1 = Voice()
voice1.login("user1","abcdef")
nphones = len(voice1.phones)
for i in range(nphones):
rbuttons[i].SetLabel(voice1.phones[i].name)
rbuttons[i].Show()
i = i + 1
rbuttons[i].SetLabel('Voicemail')
rbuttons[i].Show()
else:
voice2 = Voice()
voice2.login("user2","abcdef")
nphones = len(voice2.phones)
i = 0
for i in range(nphones):
rbuttons[i].SetLabel(voice2.phones[i].name)
rbuttons[i].Show()
i = i + 1
rbuttons[i].SetLabel('Voicemail')
rbuttons[i].Show()
A:
try calling self.Refresh() to force a repaint.
http://www.wxpython.org/docs/api/wx.Window-class.html#Refresh
BTW, the way you're using the 'i' is kinda confusing on the scope...
i = 0
....
for i in range(nphones):
rbuttons[i].SetLabel(voice1.phones[i].name)
rbuttons[i].Show()
i = i + 1
rbuttons[i].SetLabel('Voicemail')
rbuttons[i].Show()
try:
for i in range(nphones):
rbuttons[i].SetLabel(voice1.phones[i].name)
rbuttons[i].Show()
vm_idx = nphones
rbuttons[vm_idx].SetLabel('Voicemail')
rbuttons[vm_idx].Show()
| Dynamic wx.RadioButtons | I'm having some trouble with the procedure below. First pass through the procedure, everything appears to work OK. Subsequent passes, the labels overwrite the previous label w/o erasing, plus the initial loop that hides the buttons doesn't appear to function.
def drawbutton(self, event):
rbuttons = [
wx.RadioButton(self,-1,'xxxxxxxxxx', (190,60),style = wx.RB_GROUP),
wx.RadioButton(self, -1,'xxxxxxxxxx', (190,80)),
wx.RadioButton(self, -1,'xxxxxxxxxx', (190,100)),
wx.RadioButton(self, -1,'xxxxxxxxxx', (190,120)),
wx.RadioButton(self, -1,'xxxxxxxxxx', (190,140)),
wx.RadioButton(self, -1,'xxxxxxxxxx', (190,160)),
wx.RadioButton(self, -1,'xxxxxxxxxx', (190,180)), ]
for i in range(7):
rbuttons[i].Hide()
i = 0
if self.combobox.GetValue() == "555-1212":
voice1 = Voice()
voice1.login("user1","abcdef")
nphones = len(voice1.phones)
for i in range(nphones):
rbuttons[i].SetLabel(voice1.phones[i].name)
rbuttons[i].Show()
i = i + 1
rbuttons[i].SetLabel('Voicemail')
rbuttons[i].Show()
else:
voice2 = Voice()
voice2.login("user2","abcdef")
nphones = len(voice2.phones)
i = 0
for i in range(nphones):
rbuttons[i].SetLabel(voice2.phones[i].name)
rbuttons[i].Show()
i = i + 1
rbuttons[i].SetLabel('Voicemail')
rbuttons[i].Show()
| [
"try calling self.Refresh() to force a repaint. \nhttp://www.wxpython.org/docs/api/wx.Window-class.html#Refresh\nBTW, the way you're using the 'i' is kinda confusing on the scope... \ni = 0\n....\nfor i in range(nphones):\n rbuttons[i].SetLabel(voice1.phones[i].name)\n rbuttons[i].Show()\n\ni =... | [
0
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0003434371_python_wxpython.txt |
Q:
Get selected path from response
I am using
response.headers['Content-Type'] = gluon.contenttype.contenttype('.xls')
response.headers['Content-disposition'] = 'attachment; filename=projects.xls'
to generate save as dialog box.
Is there a way to get the selected path by the user?
A:
The browser displays the Save As dialog box to the user, then writes your content into that file. It doesn't inform the server what path the content was saved to. I'm afraid you can't get that information.
A:
If your question is about how to send the file contents to the user, you simply write the content to your response object. The browser takes care of actually writing the file to the path selected by the user.
In Django, you would do something like:
def view(request):
# get the file content from somewhere
response = HttpResponse(file_content, mimetype='application/vnd.ms-excel')
response['Content-Disposition'] = 'attachment; filename=projects.xls'
return response
The browser will then prompt the user for a path and save the file "projects.xls" to that path.
| Get selected path from response | I am using
response.headers['Content-Type'] = gluon.contenttype.contenttype('.xls')
response.headers['Content-disposition'] = 'attachment; filename=projects.xls'
to generate save as dialog box.
Is there a way to get the selected path by the user?
| [
"The browser displays the Save As dialog box to the user, then writes your content into that file. It doesn't inform the server what path the content was saved to. I'm afraid you can't get that information.\n",
"If your question is about how to send the file contents to the user, you simply write the content to... | [
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0003434088_python.txt |
Q:
What is the best Python IDE for Mac OS X?
Possible Duplicate:
What’s a good IDE for Python on the Mac?
Hi,
I'm going to start a quite big python project development under Mac OS X. What is the best python IDE for Mac OS X -recommended freeware-.
A:
Pydev with Eclipse.
| What is the best Python IDE for Mac OS X? |
Possible Duplicate:
What’s a good IDE for Python on the Mac?
Hi,
I'm going to start a quite big python project development under Mac OS X. What is the best python IDE for Mac OS X -recommended freeware-.
| [
"Pydev with Eclipse.\n"
] | [
2
] | [] | [] | [
"ide",
"macos",
"python"
] | stackoverflow_0003435458_ide_macos_python.txt |
Q:
Unpacking big-endian encoded port number
I'm trying to convert a big-endian 2 byte string into a numeric port number. I've already got some code, but I have no idea if it's right:
from struct import unpack
def unpack_port(big_endian-port):
return unpack("!H", big_endian-port)[0]
The port (using Python repr() ) is \x1a\xe1, and I get 6881 out of that function.
Is that correct?
A:
Yes, '!' is the character that says 'network byte order', and 'H' says '16-bit unsigned integer', so your code is correct. 6881 is typically a Bittorrent port.
In this case, I believe '!' is the correct character. Since it's a port number, I expect your data is coming from a network. But, if you knew your data to be big-endian for some other reason, '>' might be more appropriate. They mean the exact same thing and always will. It's more a matter of commenting your code to indicate intent than any semantic difference.
| Unpacking big-endian encoded port number | I'm trying to convert a big-endian 2 byte string into a numeric port number. I've already got some code, but I have no idea if it's right:
from struct import unpack
def unpack_port(big_endian-port):
return unpack("!H", big_endian-port)[0]
The port (using Python repr() ) is \x1a\xe1, and I get 6881 out of that function.
Is that correct?
| [
"Yes, '!' is the character that says 'network byte order', and 'H' says '16-bit unsigned integer', so your code is correct. 6881 is typically a Bittorrent port.\nIn this case, I believe '!' is the correct character. Since it's a port number, I expect your data is coming from a network. But, if you knew your data... | [
4
] | [] | [] | [
"endianness",
"networking",
"python"
] | stackoverflow_0003435589_endianness_networking_python.txt |
Q:
What language (Java or Python) + framework for mid sized web project?
I plan to start a mid sized web project, what language + framework would you recommend?
I know Java and Python. I am looking for something simple.
Is App Engine a good option? I like the overall simplicity and free hosting, but I am worried about the datastore (how difficult is it to make it similarly fast as a standard SQL solution? + I need fulltext search + I need to filter objects by several parameters).
What about Java with Stripes? Should I use another framework in addition to Stripes (e.g. for database).
UPDATE:
Thanks for the advice, I finally decided to use Django with Eclipse/PyDev as an IDE.
Python/Django is simple and elegant, it's widely used and there is a great documentation. A small disadvantage is that perhaps I'll have to buy a VPS, but it shouldn't be very hard to port the project to App Engine, which is free to some extent.
A:
Since you mentioned python, I would suggest looking into Django. You may need to look harder for hosting options, however...
A:
Is App Engine a good option? I like the overall simplicity and free hosting, but I am worried about the datastore (how difficult is it to make it similarly fast as a standard SQL solution? + I need fulltext search + I need to filter objects by several parameters).
App Engine is nice. It supports Python or Java (with some limitations), and it provides free hosting for small needs (rare, at least for Java). But I wouldn't expect the exact same performances as with dedicated servers, the cloud is about scalability, not performance (you won't always get the fastest response time for a single hit; however, GAE would handle gazillions of concurrent hits without any problem while your servers would be on fire). But this scalability is not without cost; if you don't need it, the development tradeoffs may be too much trouble. And also note that it does not support full-text search out of the box (what an irony), you will have to use extra tooling.
What about Java with Stripes? Should I use another framework besides Stripes (e.g. for database).
I like Stripes very much. I love its conventions over configuration approach, it's a very elegant and simple framework (but still powerful). Definitely not a bad choice. For persistence, if you go for GAE, you will have to use JPA or JDO. If you don't, it's at your discretion (although I would go for JPA).
See also
Google AppEngine - A Second Look
A:
As many things in life, this depends on what your goals are. If you intend to learn a web framework that is used in corporate environments, then choose a Java solution. If not, don't. Python is certainly more elegant and generally more fun in pretty much every way.
As to which framework to use, django has the most mindshare, as evidenced by the number of questions asked about it here. My understanding is that it's also pretty good. It's best suited for CMS-like web sites, though - at least that's what it's coming from and what it's optimized for. You might also have a look at one of the simpler, nimbler ones, such as the relatively new flask. All of these are enjoyable, though they may not all have all features on AppEngine.
A:
Kay and Tipfy are excellent Python framework choices when you target specifically GAE. Kay is modelled after and similar to Django, but is better suited to GAE.
A:
I've been kick App Engine around a little bit, and so far the DataStore is pretty quick... there is a bit of a learning curve compared to SQL, but I've had no real issues. I'm not sure about fulltext search, however filtering is simple, you would just run each filter one at a time.
class DBModel(db.Model):
field1 = db.StringProperty()
field2 = db.StringProperty()
field3 = db.IntegerProperty()
GQLObj = DBModel.all().filter('field1 =', 'Foo')
GQLObj = GQLObj.filter('field2 =', 'Bar')
As far as hosting, with GAE I'm not sure you even get a choice, I know you can register your own domain with google though.
A:
I don't think the datastore is a problem. Many people will reject it out of hand because they want a standard relational database; if you are willing to consider a datastore in general then I doubt you will have any problems with the GAE datastore. Personally, I quite like it.
The thing that might trip you up is the operational limitations. For example, did you know that an HTTP request must complete within 10 seconds?
What if you get 50% of the way through a project and then find that a web service you are using sometimes take 15 seconds to respond? Now you are toast. You can't pay extra to get the limit raised or anything like that.
So, my point is that you must approach GAE with great care. Learn about the limitations and make sure that they will not be a problem before you start using it.
A:
It depends on your personality. There's no right answer to this question any more than there's a right answer to "what kind of car should I drive?"
If you're artistic and believe code should be beautiful, use Rails.
If you're a real hacker type, I think you'll find a full-stack framework such as Rails or Django to be unsatisfying. These frameworks are "opinionated" software, which means you have to really embrace the author's vision to be most productive.
The wonderful thing about web development in the Python world is there's several great minimal frameworks. I've used several, including web.py, GAE's webapp, and cherrypy. These frameworks are like "here's a request, give me a string to serve up." It's raw. Don't think you'll be stuck in Python concatenating strings though, God no. There's also several excellent templating libraries for Python. I can personally recommend Cheetah but Mako also looks good.
A:
Google App Engine + GWT and you have a pretty powerful combination for developing web applications. The datastore is quite fast, and it has so far done the job quite nicely for me.
In my project I had to do a lot of redesigning of my database model, because it was made for a traditional relational database, and some things were not (directly) possible with the datastore.
GWT has a fairly moderate learning curve, but it gets the job done very well. The gui code is really easy to get started with, but it's the asynchronous way of thinking that's the hardest part.
As for search I don't think it's supported in the framework. Filtering is possible on parameters.
There are some limitations to GAE, and you should consider them before putting all your eggs in that basket. The fact that GAE uses J2EE distribution standards makes the application very easy to move to a dedicated server, should the limitations of GAE become a problem. In fact I only think you would have to refactor the part of your code that makes the queries and stores the data (which shouldn't be much more than 100 lines).
A:
I've built several apps on GAE (with Python) over the last year. It's hard to beat the ease with which you can get an app up and running quickly. Don't discount the value in that alone.
While you may not understand the datastore yet, it is extremely well documented and there are great resources - including this one - to help you get past any problem you might have.
| What language (Java or Python) + framework for mid sized web project? | I plan to start a mid sized web project, what language + framework would you recommend?
I know Java and Python. I am looking for something simple.
Is App Engine a good option? I like the overall simplicity and free hosting, but I am worried about the datastore (how difficult is it to make it similarly fast as a standard SQL solution? + I need fulltext search + I need to filter objects by several parameters).
What about Java with Stripes? Should I use another framework in addition to Stripes (e.g. for database).
UPDATE:
Thanks for the advice, I finally decided to use Django with Eclipse/PyDev as an IDE.
Python/Django is simple and elegant, it's widely used and there is a great documentation. A small disadvantage is that perhaps I'll have to buy a VPS, but it shouldn't be very hard to port the project to App Engine, which is free to some extent.
| [
"Since you mentioned python, I would suggest looking into Django. You may need to look harder for hosting options, however...\n",
"\nIs App Engine a good option? I like the overall simplicity and free hosting, but I am worried about the datastore (how difficult is it to make it similarly fast as a standard SQL so... | [
4,
3,
2,
1,
0,
0,
0,
0,
0
] | [] | [] | [
"google_app_engine",
"java",
"python",
"stripes",
"web_applications"
] | stackoverflow_0003427946_google_app_engine_java_python_stripes_web_applications.txt |
Q:
Multi-split in Python
How would I split a string by two opposing values? For example ( and ) are the "deliminators" and I have the following string:
Wouldn't it be (most) beneficial to have (at least) some idea?
I need the following output (as an array)
["Wouldn't it be ", "most", " beneficial to have ", "at least", " some idea?"]
A:
re.split()
s = "Wouldn't it be (most) beneficial to have (at least) some idea?"
l = re.split('[()]', s);
A:
In this particular case, sounds like it would make more sense to first split by space and then trim the brackets.
out = []
for element in "Wouldn't it be (most) beneficial to have (at least) some idea?".split():
out.append(element.strip('()'))
Hm... re-reading the question, you wanted to preserve some of the spaces, so maybe not :) but keeping it here still.
A:
You can use the split of a regular expression:
import re
pattern = re.compile(r'[()]')
pattern.split("Wouldn't it be (most) beneficial to have (at least) some idea?")
["Wouldn't it be ", 'most', ' beneficial to have ', 'at least', ' some idea?']
A:
Use a regular expression, matching both () characters:
import re
re.split('[()]', string)
| Multi-split in Python | How would I split a string by two opposing values? For example ( and ) are the "deliminators" and I have the following string:
Wouldn't it be (most) beneficial to have (at least) some idea?
I need the following output (as an array)
["Wouldn't it be ", "most", " beneficial to have ", "at least", " some idea?"]
| [
"re.split()\ns = \"Wouldn't it be (most) beneficial to have (at least) some idea?\"\nl = re.split('[()]', s);\n\n",
"In this particular case, sounds like it would make more sense to first split by space and then trim the brackets.\nout = []\nfor element in \"Wouldn't it be (most) beneficial to have (at least) som... | [
13,
1,
0,
0
] | [] | [] | [
"python",
"split",
"string"
] | stackoverflow_0003435900_python_split_string.txt |
Q:
I need a message/queuing solution for my web-based system
I am looking for a message/queuing solution for my web based system running on Ubuntu.
The system was built on the following technologies:
Javascript (Extjs framework) - Frontend
PHP
Python (Daemon service which interacts with the encryption device)
Python pyserial - (Serial port interactions)
MySQL
Linux - Ccustom bash scripts(to update DB/mail reports)
The system serves the following purpose:
Capture client information on a distributed platform
Encrypt/decrypt sensitive transactions using a Hardware device
System breakdown:
The user gains access to the system using a web browser
The user captures client information and on pressing "submit" button
The data is sent to the encryption device and the system enters a wait state
The data is then encrypted on the device and sent back to the browser
The encrypted data is saved to the DB
System exits wait state and displays DONE message
Please note: I have already taken care of waiting/progress messages so lets omit that.
What I have done so far:
I created a python daemon which monitors a DB view for any new requests
The daemon service executes new requests on the device using pyserial and updates
the requests table with a "response" ie. the encrypted content
I created a polling service in PHP which frequently checks if there is a "response" in >the requests table for the specific request
Created the Extjs frontend with appropriate wait/done status messages
The problem with the current setup:
Concurreny - We expect > 20 users at any time submitting encryption/decryption requests
using a database as a message/queuing solution is not scalable due to table locking and only 1 listening process which monitors for requests
Daemon service - Relying on a daemon service is a bit risky and the DB overhead seems a bit high polling the view for new requests every second
Development - It would simplify my development tasks by just sending requests to a encrypt/decrypt service instead of doing this whole process of inserting a request in the db,polling for the response and processing the request in the daemon service.
My Question:
What would be the ideal message/queening solution in this situation? Please take into >account my system exclusively runs on a Ubuntu O/S.
I have done a few Google services and came accross something called a "Stomp" server but it prove somewhat difficult to setup and lacked some documentation. Also I prefer the advice from individuals who have some experience in setting up something like this instead of some "how to" guide :)
Thank You for your time
A:
I believe the popular RabbitMQ implementation of AMQP offers a PHP extension (here) and you can definitely access AMQP in Python, e.g. via Qpid. RabbitMQ is also easy to install on Ubuntu (or Debian), see e.g. here.
Whether via RabbitMQ or otherwise, adopting an open messaging and queueing protocol such as AMQP has obvious and definite advantages in comparison to more "closed" solutions (even if technically open source, such solutions just won't offer as many implementations, and therefore flexibility, as a widely adopted open, standard protocol).
A:
I would do:
The web component connects to the encryption daemon/service, sends the data and waits for the answer
The encryption daemon/service would:
On startup, start a thread (SerialThread) of each of the available serial devices
All 'serial threads' would then do a SerialQueue.get (blocking waiting for messages)
A multi threaded TCP server, check ThreadingMixIn from http://docs.python.org/library/socketserver.html
The TCP Server threads would receive the plain data and put it on the SerialQueue
A random SerialThread (Python's Queue class manages the multi thread required locking for you) would receive the request, encrypt and return the encrypted data to the TCP Server thread
The TCP Server thread would write the data back to the web component
I am using this logic on a project, you can check the source at http://bazaar.launchpad.net/~mirror-selector-devs/mirror-selector/devel/files/head:/mirrorselector/, on my case the input is an URL, the processing is to scan for an available mirror, the output is a mirror url.
| I need a message/queuing solution for my web-based system | I am looking for a message/queuing solution for my web based system running on Ubuntu.
The system was built on the following technologies:
Javascript (Extjs framework) - Frontend
PHP
Python (Daemon service which interacts with the encryption device)
Python pyserial - (Serial port interactions)
MySQL
Linux - Ccustom bash scripts(to update DB/mail reports)
The system serves the following purpose:
Capture client information on a distributed platform
Encrypt/decrypt sensitive transactions using a Hardware device
System breakdown:
The user gains access to the system using a web browser
The user captures client information and on pressing "submit" button
The data is sent to the encryption device and the system enters a wait state
The data is then encrypted on the device and sent back to the browser
The encrypted data is saved to the DB
System exits wait state and displays DONE message
Please note: I have already taken care of waiting/progress messages so lets omit that.
What I have done so far:
I created a python daemon which monitors a DB view for any new requests
The daemon service executes new requests on the device using pyserial and updates
the requests table with a "response" ie. the encrypted content
I created a polling service in PHP which frequently checks if there is a "response" in >the requests table for the specific request
Created the Extjs frontend with appropriate wait/done status messages
The problem with the current setup:
Concurreny - We expect > 20 users at any time submitting encryption/decryption requests
using a database as a message/queuing solution is not scalable due to table locking and only 1 listening process which monitors for requests
Daemon service - Relying on a daemon service is a bit risky and the DB overhead seems a bit high polling the view for new requests every second
Development - It would simplify my development tasks by just sending requests to a encrypt/decrypt service instead of doing this whole process of inserting a request in the db,polling for the response and processing the request in the daemon service.
My Question:
What would be the ideal message/queening solution in this situation? Please take into >account my system exclusively runs on a Ubuntu O/S.
I have done a few Google services and came accross something called a "Stomp" server but it prove somewhat difficult to setup and lacked some documentation. Also I prefer the advice from individuals who have some experience in setting up something like this instead of some "how to" guide :)
Thank You for your time
| [
"I believe the popular RabbitMQ implementation of AMQP offers a PHP extension (here) and you can definitely access AMQP in Python, e.g. via Qpid. RabbitMQ is also easy to install on Ubuntu (or Debian), see e.g. here.\nWhether via RabbitMQ or otherwise, adopting an open messaging and queueing protocol such as AMQP ... | [
5,
0
] | [] | [] | [
"message_queue",
"mysql",
"python",
"ubuntu"
] | stackoverflow_0003435954_message_queue_mysql_python_ubuntu.txt |
Q:
Datetime/time issue with python (18 hours off)
I'm working on making a small ban system, and the snippet below will tell the client how much time of their ban is remaining.
The problem:
When you call Bans.timeleft_str(), rather then showing something less then a day, it will show the timestamp + 18 hours.
Snippet: http://pastebin.com/Zumn0tLv
This problem occurs if I change self.length = WEEK, etc. Rather then 7d 00h 00m, it will be 7d 18h 00m.
I originally tested this on my ubuntu vbox, and then tried it on my windows python shell, and still got the same result.
You may need to change self.timestamp to a time in the past.
Thanks in advance.
A:
time.time, as the docs I just pointed to say, works in UTC (once known as "Greenwich" time, now "universal time coordinate"). mktime, again as said in its docs, takes as argument
9-tuple [...] which expresses the time in local time, not UTC.
strptime may work either way (but you're not supplying a timezone, so it's going to use local time).
So, overall, you're getting deep into timezone confusion;-).
I recommend (as always) that you standardize on UTC (the local timezone of your server can well not be the same as that of its users, after all), e.g. with a %Z directive in the format you pass to strptime and a corresponding timezone of 'UTC' (which is guaranteed to be recognized on all platforms) in the corresponding part of the string you're parsing.
| Datetime/time issue with python (18 hours off) | I'm working on making a small ban system, and the snippet below will tell the client how much time of their ban is remaining.
The problem:
When you call Bans.timeleft_str(), rather then showing something less then a day, it will show the timestamp + 18 hours.
Snippet: http://pastebin.com/Zumn0tLv
This problem occurs if I change self.length = WEEK, etc. Rather then 7d 00h 00m, it will be 7d 18h 00m.
I originally tested this on my ubuntu vbox, and then tried it on my windows python shell, and still got the same result.
You may need to change self.timestamp to a time in the past.
Thanks in advance.
| [
"time.time, as the docs I just pointed to say, works in UTC (once known as \"Greenwich\" time, now \"universal time coordinate\"). mktime, again as said in its docs, takes as argument \n9-tuple [...] which expresses the time in local time, not UTC.\n\nstrptime may work either way (but you're not supplying a timezo... | [
1
] | [] | [] | [
"datetime",
"python",
"time"
] | stackoverflow_0003436262_datetime_python_time.txt |
Q:
Confusion while counting elapsed time in python?
So I wanted to compare the performance of python between 2.6 and 3.1, so I wrote this simple program test.py that will perform some basic lengthy operation:
from time import time
start = time()
q = 2 ** 1000000000
q += 3 << 1000000000
print(q.__sizeof__(), time() - start)
I didn't get what I expected, since after launching the commands time python2.6 test.py and time python3.1 test.py respectively, the output was the following:
(133333364, 0.37349200248718262)
real 0m35.586s
user 0m28.130s
sys 0m2.110s
and,
133333360 0.312520027161
real 0m26.413s
user 0m17.330s
sys 0m2.190s
I assumed that the results for both versions would be close when comparing the output of the time command and that done inside the program. What is the explanation for this?
A:
There may be many explanations, such as a different set of directories (and zipfiles) on sys.path, automatically loaded/executed code at initialization, other processes running on the platform -- your code is not at all isolated nor repeatable, therefore its results are of very little value. Use python -mtimeit to measure things much, much better.
Edit: some numbers...:
$ py26 -mtimeit 'q=2**1000000000; q+=3<<1000000000'
10 loops, best of 3: 466 msec per loop
$ py31 -mtimeit 'q=2**1000000000; q+=3<<1000000000'
10 loops, best of 3: 444 msec per loop
these accurately measure the += time (slightly better / more optimized in 3.1, repeatably). If you want to measure the shifting or raising to power times, then you can't use literals, of course (since literal expressions get computed at compile time, not at run time: part of why you want all your significant code to be in functions in modules, not in top-level code nor in your main script... so the compiler can do as much of the work as easily feasible, despite its lack of any serious optimizations;-). E.g.:
$ py31 -mtimeit -s't=2' 'q=t**1000000'
10 loops, best of 3: 19.4 msec per loop
$ py31 -mtimeit -s't=3' 'q=t<<1000000'
10000 loops, best of 3: 150 usec per loop
(just takes too long to do them with the larger RHS operand you're using and I'm getting impatient;-). Mixing the ops would of course be a sad disaster in terms of measuring, since the relatively fast ones would essentially disappear in the mix!-) Fortunately, there is no good reason for such mixing -- timeit, after all, is for micro benchmarking!-)
A:
Heh, iteresting problem, took me a while to figure it out:
from time import time
start = time()
q = 2 ** 1000000000 # number literal
q += 3 << 1000000000 # still a literal
print(q.__sizeof__(), time() - start)
Python's compiler (!) computes q. When the script runs, the interpreter takes the time, loads the already computed value and takes the time again. Now unsurprisingly, the two times are pretty much the same.
time on the other hand measures how long the full run (compile+run) takes.
| Confusion while counting elapsed time in python? | So I wanted to compare the performance of python between 2.6 and 3.1, so I wrote this simple program test.py that will perform some basic lengthy operation:
from time import time
start = time()
q = 2 ** 1000000000
q += 3 << 1000000000
print(q.__sizeof__(), time() - start)
I didn't get what I expected, since after launching the commands time python2.6 test.py and time python3.1 test.py respectively, the output was the following:
(133333364, 0.37349200248718262)
real 0m35.586s
user 0m28.130s
sys 0m2.110s
and,
133333360 0.312520027161
real 0m26.413s
user 0m17.330s
sys 0m2.190s
I assumed that the results for both versions would be close when comparing the output of the time command and that done inside the program. What is the explanation for this?
| [
"There may be many explanations, such as a different set of directories (and zipfiles) on sys.path, automatically loaded/executed code at initialization, other processes running on the platform -- your code is not at all isolated nor repeatable, therefore its results are of very little value. Use python -mtimeit t... | [
3,
2
] | [] | [] | [
"python",
"time"
] | stackoverflow_0003436291_python_time.txt |
Q:
Gender problem in a django i18n translation
I need to solve a gender translation problem, and Django doesn't seem to have gettext contexts implemented yet...
I need to translate from english:
<p>Welcome, {{ username }}</p>
In two forms of spanish, one for each gender. If user is a male:
<p>Bienvenido, {{ username }}</p>
and if is a female:
<p>Bienvenida, {{ username }}</p>
note the difference (bienvenido/bienvenida)
Is there any way of getting this done?
Thanks,
H.
A:
The way that I've solved this is:
{% if profile.male %}
{% blocktrans with profile.name as male %}Welcome, {{ male }}{% endblocktrans %}
{% else %}
{% blocktrans with profile.name as female %}Welcome, {{ female }}{% endblocktrans %}
{% endif %}
A:
Django is just Python so you can use the Python gettext bindings directly if you need to, I don't see any reason you couldn't write a {% gender_trans [gender] %} tag.
A:
While waiting for contexts to be supported, an easy alternative would be to slightly change the Spanish sentence and use a greeting that does not vary according to a person's gender. For example, you could use "hola", or some other equivalent term.
| Gender problem in a django i18n translation | I need to solve a gender translation problem, and Django doesn't seem to have gettext contexts implemented yet...
I need to translate from english:
<p>Welcome, {{ username }}</p>
In two forms of spanish, one for each gender. If user is a male:
<p>Bienvenido, {{ username }}</p>
and if is a female:
<p>Bienvenida, {{ username }}</p>
note the difference (bienvenido/bienvenida)
Is there any way of getting this done?
Thanks,
H.
| [
"The way that I've solved this is:\n{% if profile.male %}\n{% blocktrans with profile.name as male %}Welcome, {{ male }}{% endblocktrans %}\n{% else %}\n{% blocktrans with profile.name as female %}Welcome, {{ female }}{% endblocktrans %}\n{% endif %}\n\n",
"Django is just Python so you can use the Python gettext ... | [
10,
4,
2
] | [] | [] | [
"django",
"internationalization",
"localization",
"python"
] | stackoverflow_0001329115_django_internationalization_localization_python.txt |
Q:
numpy arrays type conversion in C
I would like to convert the numpy double array to numpy float array in C(Swig).
I am trying to use
PyObject *object = PyArray_FROM_OT(input,NPY_FLOAT)
or
PyObject *object = PyArray_FROMANY(input,NPY_FLOAT,0,0,NPY_DEFAULT)
or
PyObject *object = PyArray_FromObject(input,NPY_FLOAT,0,0)
or
PyObject *object = PyArray_ContiguousFromAny(input,NPY_FLOAT,0,0)
But all of them return NULL? Am I missing anything?
A:
Your approach is correct, yet your assumption about they numpy C API is not. NPY_FLOAT is just an integral constant, yet the functions you posted require the type parameter to be a pointer to a PyArray_Descr struct.
In order to get a type description from a mere type, you can call PyArray_DescrFromType, so your call could look like this:
PyArrayObject* float_array = (PyArrayObject*)PyArray_FromAny(input,PyArray_DescrFromType(NPY_FLOAT64), 0,0, flags);
...with flags being whatever flags you deem meaningful when converting - please have a look at the numpy API, both for correct API invocation and for the meaning of different flags and values.
| numpy arrays type conversion in C | I would like to convert the numpy double array to numpy float array in C(Swig).
I am trying to use
PyObject *object = PyArray_FROM_OT(input,NPY_FLOAT)
or
PyObject *object = PyArray_FROMANY(input,NPY_FLOAT,0,0,NPY_DEFAULT)
or
PyObject *object = PyArray_FromObject(input,NPY_FLOAT,0,0)
or
PyObject *object = PyArray_ContiguousFromAny(input,NPY_FLOAT,0,0)
But all of them return NULL? Am I missing anything?
| [
"Your approach is correct, yet your assumption about they numpy C API is not. NPY_FLOAT is just an integral constant, yet the functions you posted require the type parameter to be a pointer to a PyArray_Descr struct.\nIn order to get a type description from a mere type, you can call PyArray_DescrFromType, so your c... | [
5
] | [] | [] | [
"numpy",
"python",
"swig"
] | stackoverflow_0003213654_numpy_python_swig.txt |
Q:
Accessing the underlying struct of a PyObject
I am working on creating a python c extension but am having difficulty finding documentation on what I want to do. I basically want to create a pointer to a cstruct and be able to have access that pointer. The sample code is below. Any help would be appreciated.
typedef struct{
int x;
int y;
} Point;
typedef struct {
PyObject_HEAD
Point* my_point;
} PointObject;
static PyTypeObject PointType = {
PyObject_HEAD_INIT(NULL)
0, /*ob_size*/
"point", /*tp_name*/
sizeof(PointObject), /*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, /*tp_flags*/
"point objects", /* tp_doc */
};
static PyObject* set_point(PyObject* self, PyObject* args)
{
PyObject* point;
if (!PyArg_ParseTuple(args, "O", &point))
{
return NULL;
}
//code to access my_point
}
A:
Your PyArg_ParseTuple should not use format O but O! (see the docs):
O! (object) [typeobject, PyObject *]
Store a Python object in a C object
pointer. This is similar to O, but
takes two C arguments: the first is
the address of a Python type object,
the second is the address of the C
variable (of type PyObject*) into
which the object pointer is stored. If
the Python object does not have the
required type, TypeError is raised.
Once you've done that, you know that in your function's body (PointObject*)point will be a correct and valid pointer to a PointObject, and therefore its ->my_point will be the Point* you seek. With a plain format O you'd have to do the type checking yourself.
Edit: the OP in a comments asks for the source...:
static PyObject*
set_point(PyObject* self, PyObject* args)
{
PyObject* point;
if (!PyArg_ParseTuple(args, "O!", &PointType, &point))
{
return NULL;
}
Point* pp = ((PointObject*)point)->my_point;
// ... use pp as the pointer to Point you were looking for...
// ... and incidentally don't forget to return a properly incref'd
// PyObject*, of course;-)
}
| Accessing the underlying struct of a PyObject | I am working on creating a python c extension but am having difficulty finding documentation on what I want to do. I basically want to create a pointer to a cstruct and be able to have access that pointer. The sample code is below. Any help would be appreciated.
typedef struct{
int x;
int y;
} Point;
typedef struct {
PyObject_HEAD
Point* my_point;
} PointObject;
static PyTypeObject PointType = {
PyObject_HEAD_INIT(NULL)
0, /*ob_size*/
"point", /*tp_name*/
sizeof(PointObject), /*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, /*tp_flags*/
"point objects", /* tp_doc */
};
static PyObject* set_point(PyObject* self, PyObject* args)
{
PyObject* point;
if (!PyArg_ParseTuple(args, "O", &point))
{
return NULL;
}
//code to access my_point
}
| [
"Your PyArg_ParseTuple should not use format O but O! (see the docs):\nO! (object) [typeobject, PyObject *]\n\n\nStore a Python object in a C object\n pointer. This is similar to O, but\n takes two C arguments: the first is\n the address of a Python type object,\n the second is the address of the C\n variable ... | [
3
] | [] | [] | [
"c",
"pointers",
"python",
"structure"
] | stackoverflow_0003436730_c_pointers_python_structure.txt |
Q:
Python to C code?
I wrote a program in python (using standard python libraries) long ago. Now I need to write the same program in standard C due to the lack of python support for that device.
Please suggest me programs or conversion method to convert that python code into C code.
Thanks in advance.
A:
Shedskin could do the trick:
Shed Skin is an experimental compiler,
that can translate pure, but
implicitly statically typed Python
programs into optimized C++. It can
generate stand-alone programs or
extension modules that can be imported
and used in larger Python programs.
A:
So there is a C library for the device? You should be able to wrap the C library with a Python module.
You can also use cython to write the interface to the C code
| Python to C code? | I wrote a program in python (using standard python libraries) long ago. Now I need to write the same program in standard C due to the lack of python support for that device.
Please suggest me programs or conversion method to convert that python code into C code.
Thanks in advance.
| [
"Shedskin could do the trick:\n\nShed Skin is an experimental compiler,\n that can translate pure, but\n implicitly statically typed Python\n programs into optimized C++. It can\n generate stand-alone programs or\n extension modules that can be imported\n and used in larger Python programs.\n\n",
"So there ... | [
4,
1
] | [] | [] | [
"c",
"python"
] | stackoverflow_0003434524_c_python.txt |
Q:
Using beautifulSoup, trying to get all table rows that have a string in them
I need to get all table rows on a page that contain a specific string 'abc123123' in them.
The string is inside a TD, but I need the entire TR if it contains the 'abc123123' anywhere inside.
I tried this:
userrows = s.findAll('tr', contents = re.compile('abc123123'))
I'm not sure if contents is the write property.
My html looks something like:
<tr>
<td>
</td>
<td><table>.... abc123123 </table><tr>
..
</tr>
<tr>
..
</tr>
..
..
A:
No, the extra keyword arguments beyond the specified ones (name, attrs, recursive, text, limit) all refer to attributes of the tag you're searching for.
You cannot search for name and text at the same time (if you specify text, BS ignores name) so you need separate calls, e.g:
allrows = s.findAll('tr')
userrows = [t for t in allrows if t.findAll(text=re.compile('abc123123'))]
Here I'm using a list comprehension since I assume you want a list of the relevant tag objects, as findAll itself gives you.
| Using beautifulSoup, trying to get all table rows that have a string in them | I need to get all table rows on a page that contain a specific string 'abc123123' in them.
The string is inside a TD, but I need the entire TR if it contains the 'abc123123' anywhere inside.
I tried this:
userrows = s.findAll('tr', contents = re.compile('abc123123'))
I'm not sure if contents is the write property.
My html looks something like:
<tr>
<td>
</td>
<td><table>.... abc123123 </table><tr>
..
</tr>
<tr>
..
</tr>
..
..
| [
"No, the extra keyword arguments beyond the specified ones (name, attrs, recursive, text, limit) all refer to attributes of the tag you're searching for.\nYou cannot search for name and text at the same time (if you specify text, BS ignores name) so you need separate calls, e.g:\nallrows = s.findAll('tr')\nuserrows... | [
4
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0003436770_beautifulsoup_python.txt |
Q:
Expanding tuples in python
In the following code:
a = 'a'
tup = ('tu', 'p')
b = 'b'
print 'a: %s, t[0]: %s, t[1]: %s, b:%s'%(a, tup[0], tup[1], b)
How can I "expand" (can't figure out a better verb) tup so that I don't have to explicitly list all its elements?
NOTE That I don't want to print tup per-se, but its individual elements. In other words, the following code is not what I'm looking for
>>> print 'a: %s, tup: %s, b: %s' % (a, tup, b)
a: a, tup: ('tu', 'p'), b: b
The code above printed tup, but I want to print it's elements independently, with some text between the elements.
The following doesn't work:
print 'a: %s, t[0]: %s, t[1]: %s, b:%s'%(a, tup, b)
In [114]: print '%s, %s, %s, %s'%(a, tup, b)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
TypeError: not enough arguments for format string
A:
It is possible to flatten a tuple, but I think in your case, constructing a new tuple by concatenation is easier.
'a: %s, t[0]: %s, t[1]: %s, b:%s'%((a,) + tup + (b,))
# ^^^^^^^^^^^^^^^^^
A:
If you want to use the format method instead, you can just do:
"{0}{2}{3}{1}".format(a, b, *tup)
You have to name every paramater after tup because the syntax for unpacking tuples to function calls using * requires this.
A:
>>> print 'a: {0}, t[0]: {1[0]}, t[1]: {1[1]}, b:{2}'.format(a, tup, b)
a: a, t[0]: tu, t[1]: p, b:b
You can also use named parameters if you prefer
>>> print 'a: {a}, t[0]: {t[0]}, t[1]: {t[1]}, b:{b}'.format(a=a, t=tup, b=b)
a: a, t[0]: tu, t[1]: p, b:b
| Expanding tuples in python | In the following code:
a = 'a'
tup = ('tu', 'p')
b = 'b'
print 'a: %s, t[0]: %s, t[1]: %s, b:%s'%(a, tup[0], tup[1], b)
How can I "expand" (can't figure out a better verb) tup so that I don't have to explicitly list all its elements?
NOTE That I don't want to print tup per-se, but its individual elements. In other words, the following code is not what I'm looking for
>>> print 'a: %s, tup: %s, b: %s' % (a, tup, b)
a: a, tup: ('tu', 'p'), b: b
The code above printed tup, but I want to print it's elements independently, with some text between the elements.
The following doesn't work:
print 'a: %s, t[0]: %s, t[1]: %s, b:%s'%(a, tup, b)
In [114]: print '%s, %s, %s, %s'%(a, tup, b)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
TypeError: not enough arguments for format string
| [
"It is possible to flatten a tuple, but I think in your case, constructing a new tuple by concatenation is easier.\n'a: %s, t[0]: %s, t[1]: %s, b:%s'%((a,) + tup + (b,))\n# ^^^^^^^^^^^^^^^^^\n\n",
"If you want to use the format method instead, you can just do:\n\"{0}{2}{3}{1}\".fo... | [
9,
3,
2
] | [] | [] | [
"python",
"tuples"
] | stackoverflow_0003433913_python_tuples.txt |
Q:
source code trees: wide or deep
After writing a few python appengine apps I find myself torn between two approaches to organizing my source code tree: wide or deep.
For concreteness, consider an internal application for a small consulting shop to manage business operations like contact management, project tracking & reporting, and employee management. The application might use key entities like: Company, Users, Contacts, Customers, Projects, Timesheets, etc. Without going into details, one can imagine that these models are cross-cutting across the functions of the website. This likely means there is some coupling.
In this example, is it preferable to organize in a deep-manner, e.g.:
models/
people.py
accounting.py
projects.py
foo.py
controllers/
reporting.py
employeeops.py
accounting.py
crm.py
views/
...
or a wide-manner, e.g., by "application":
people/
models/
views/
controllers/
contact-mgmt/
models/
views/
controllers/
time-tracking/
models/
views/
controllers/
project-reporting/
models/
views/
controllers/
I know all design involves trade-offs, so when responding can you indicate your preference and some reasoning (e.g., assumptions, modulating concerns, framework limits, scalability issues, code maintenance considerations, impact of development team structure, etc.).
A:
Caveat: I haven't worked in python specifically. Having said that...
Wide, and I'll tell you why: It never hurts to be able to remove things quickly. In my career I am often asked to add things and given a relatively reasonable schedule on which to do it, but when something needs to be removed, the request almost never comes with impact analysis or time to mess around. When you break things out by major functional modules, you usually end up with a much less coupled design. It can be a real pain in the ass, but for those times when you absolutely have to get the work order module turned off by the end of the week, it is a life saver.
A:
Too deep a folder structure makes it confusing. Too wide makes it confusing. I prefer to keep a balance between them. On the project I'm working on, we had no idea what we'd need, so we didn't prematurely create a massive folder structure. After all, we only started with 5 files, so we didn't really have a need for a folder structure. As the project got bigger, we organised things to keep it neat as we went; no folders having more than 10 files, grouping things into folders clearly. It would take a few minutes to move it all around. Now we have well over a hundred files, and it's always clear where things are. My recommendation is to do similar - keep it neat, don't go too far with either depth or width, or you'll over-complicate things.
A:
In your case I think the "wide" model is better. You should try to create your apps so they reusable even if you don't plan to reuse them anywhere as this will encourage looser coupling bewteen different apps and make maintenance easier in the long run.
A:
Actually I prefer a mix. Software is divided into Horizontal and Vertical Components.
Horizontal components are reusable across all modules and represent common code to be reused that is not application specific, instead is architecture specific.
So I have folders for common Utilities, Frameworks, reusable infrastructure libraries, such as Persistence, Communications, Security, logging etc...
Vertical components are the individual Use Cases.
For each use case I have a folder that has UI, Server and under UI I have views and controllers. The model is often shared between the two.
If your project is really large then you probably have different areas of responsibility, such as Inventory Control, Sales, Contact management, Reporting etc ... Add these to your folder structure and put the use cases that apply under them.
Feel free if there is any reuse to move any components up the tree.
| source code trees: wide or deep | After writing a few python appengine apps I find myself torn between two approaches to organizing my source code tree: wide or deep.
For concreteness, consider an internal application for a small consulting shop to manage business operations like contact management, project tracking & reporting, and employee management. The application might use key entities like: Company, Users, Contacts, Customers, Projects, Timesheets, etc. Without going into details, one can imagine that these models are cross-cutting across the functions of the website. This likely means there is some coupling.
In this example, is it preferable to organize in a deep-manner, e.g.:
models/
people.py
accounting.py
projects.py
foo.py
controllers/
reporting.py
employeeops.py
accounting.py
crm.py
views/
...
or a wide-manner, e.g., by "application":
people/
models/
views/
controllers/
contact-mgmt/
models/
views/
controllers/
time-tracking/
models/
views/
controllers/
project-reporting/
models/
views/
controllers/
I know all design involves trade-offs, so when responding can you indicate your preference and some reasoning (e.g., assumptions, modulating concerns, framework limits, scalability issues, code maintenance considerations, impact of development team structure, etc.).
| [
"Caveat: I haven't worked in python specifically. Having said that...\nWide, and I'll tell you why: It never hurts to be able to remove things quickly. In my career I am often asked to add things and given a relatively reasonable schedule on which to do it, but when something needs to be removed, the request alm... | [
4,
3,
2,
0
] | [] | [] | [
"directory_structure",
"google_app_engine",
"python"
] | stackoverflow_0003436867_directory_structure_google_app_engine_python.txt |
Q:
escaping characters in a regex
The regular expression below:
[a-z]+[\\.\\?]
Why is \\ slash used twice instead of once?
A:
The regular expression below:
[a-z]+[\\.\\?]
...is not a regular expression but a string (which could be the pattern for a regular expression; you can build a RE for it by passing it to re.compile, for example).
Why is \\ slash used twice instead of
once?
You may be misunderstanding what's going on...:
>>> s = '[a-z]+[\\.\\?]'
>>> s
'[a-z]+[\\.\\?]'
>>> print(s)
[a-z]+[\.\?]
You enter the \ twice in each case in order to have the first one "escape" the second one, that is, stop it from forming an "escape sequence" with the next following character. You see it twice when you look at the string's repr (which is what the interactive Python shell is showing you when you just enter at its prompt the name the string object is boound to, for example). But you see it only once when you just look at the string, for example with print -- the string itself has no duplications, you're probably just being confused by the "entering twice" and "displaying twice" (in repr) features.
Another handier way to enter exactly the same string value, also as a literal:
>>> z = r'[a-z]+[\.\?]'
>>> z
'[a-z]+[\\.\\?]'
>>> print(z)
[a-z]+[\.\?]
>>> z == s
True
The r prefix (for "raw literal") means that none of the following backslashes are considered part of escape sequence -- each stands for itself, so no doubling up is needed.
Note that z behaves exactly like s and indeed is equal to it: the leading r does not make "strings of a different type", just offers a handy way to enter strings with lots of backslashes without doubling them up (this is intended to facilitate the entering of literal strings meant as regular-expression patterns; the r can alternatively be taken as standing for "regular-expression pattern":-).
A:
Both the . and the ? are being escaped.
However, with a regular expression character class (within []), that's not needed. This will work the same way:
[a-z]+[.?]
Edit: with your edit, asking about \\, it depends. Is this regular expression in a string within ""? Depending on the language, sometimes \ has to be escaped an extra time within double quotes. But inside '' it might not be needed. Where are you getting this from?
A:
The first one escapes the period. The second one escapes the question mark.
| escaping characters in a regex | The regular expression below:
[a-z]+[\\.\\?]
Why is \\ slash used twice instead of once?
| [
"\nThe regular expression below:\n\n [a-z]+[\\\\.\\\\?]\n\n...is not a regular expression but a string (which could be the pattern for a regular expression; you can build a RE for it by passing it to re.compile, for example).\n\nWhy is \\\\ slash used twice instead of\n once?\n\nYou may be misunderstanding what's ... | [
3,
2,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0003437072_python_regex.txt |
Q:
determining the first sprite to animate in python/pygame
so I have this spritesheet (4 sprites in a row and 3 in a coloumn) which I use to animate a character in a game I make. It animates just fine without a problem, like I want it to
the problem start to arise when I want to change the state from "dash" (running to the enemy) to "attack" (well, attack the enemy) it doesn't seem to play the attack sprite from the start (index 0)
I've used self._currentFrame = 3 on the set_state(self) function so that when the function changes it resets the frame to the third frame, which makes (self.currentFrame + 1) % 4 returns 0
but still, sometimes it doesn't do what I want, and start the animation at about index 2 or 3 (the end of animation). How do I make sure that my animation starts at index 0?
my updating code is as follows, if it helps
self.frameTime += dt
if self.fps is not -1:
while self.frameTime > 1.0 / self.fps:
self.frameTime -= 1.0 / self.fps
self.currentFrame = (self.currentFrame + 1) % 4
self.currentVFrame = (self.currentVFrame + 1) % 3
A:
Have you tested to ensure the starting value actually is 3, before that logic is executed? I ask because your summary includes reference to self._currentFrame, when your code refers to self.currentFrame -- are you assigning to one variable and checking another?
Edit regarding the additional 'answer' posted by the question starter:
Please see https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work for instructions on how (and when) to accept an answer, as well as why it's advantageous for you to do so with each question you ask.
A:
Thanks Andrew, but I've solved it. It turned out I just need to adjust the self.fps(the animation fps, not the screen) so that 1.0 / self.fps is smaller than self.frameTime
Thanks Andrew, is there any way I can give you reputation? or end this question?
edit:
why the currentFrame printed as 3?
The Actor class (the class that inherited from AnimatedGameObject) has a set_state(self, newState) function (which changes the self.currentFrame to 3) that changes the state, so that the update code above (as I've explained) returns 0 and the animation starts at the beginning of the frame
The problem is when the self.fps in the update(self, dt) function has a value of 4, the 1.0 / self.fps has a lesser value than the self.frameTime and as the effect, the self.currentFrame is not set to 0 at the beginning of the animation
So I actually just need to double the self.fps to 8 and the code works just like I want it to
| determining the first sprite to animate in python/pygame | so I have this spritesheet (4 sprites in a row and 3 in a coloumn) which I use to animate a character in a game I make. It animates just fine without a problem, like I want it to
the problem start to arise when I want to change the state from "dash" (running to the enemy) to "attack" (well, attack the enemy) it doesn't seem to play the attack sprite from the start (index 0)
I've used self._currentFrame = 3 on the set_state(self) function so that when the function changes it resets the frame to the third frame, which makes (self.currentFrame + 1) % 4 returns 0
but still, sometimes it doesn't do what I want, and start the animation at about index 2 or 3 (the end of animation). How do I make sure that my animation starts at index 0?
my updating code is as follows, if it helps
self.frameTime += dt
if self.fps is not -1:
while self.frameTime > 1.0 / self.fps:
self.frameTime -= 1.0 / self.fps
self.currentFrame = (self.currentFrame + 1) % 4
self.currentVFrame = (self.currentVFrame + 1) % 3
| [
"Have you tested to ensure the starting value actually is 3, before that logic is executed? I ask because your summary includes reference to self._currentFrame, when your code refers to self.currentFrame -- are you assigning to one variable and checking another?\nEdit regarding the additional 'answer' posted by the... | [
0,
0
] | [] | [] | [
"animation",
"pygame",
"python"
] | stackoverflow_0003435718_animation_pygame_python.txt |
Q:
django 'module' object has no attribute 'call_command'
I wrote a function like
def cmd_run(host="localhost", port="8000"):
"""Run server at given host port (or localhost 8000)"""
from django.core import management
host_port = '%s:%s' % (host, port)
management.call_command('runserver', host_port)
When I executed it, an Exception was thrown:
Traceback (most recent call last):
File "/home/leona/workspace/bettyskitchen/lib/djangocliutils/bin/djangoctl", line 8, in <module> cli(*sys.argv[1:])
File "/home/leona/workspace/bettyskitchen/lib/djangocliutils/cmds.py", line 119, in __call__
print method(*args) or ""
File "/home/leona/workspace/bettyskitchen/lib/djangocliutils/cmds.py", line 170, in __call__
return self.method(*args, **kw)
File "/home/leona/workspace/bettyskitchen/lib/djangocliutils/djangocmds/basic.py", line 19, in cmd_run
management.call_command('runserver', host_port)
AttributeError: 'module' object has no attribute 'call_command'
How can I fix it?
A:
Well, here it works... maybe your version of django has not this function? Try it in managed shell python manage.py shell and try help(management) to see if it is there on your version.
Another possibility is corruption or modification of the __init__.py file (where call_command is defined) in django.core.management directory not importing the call_command function.
A:
This problem is resolved, the django that I used was 0.96 not support call_command function, so I changed into :
def cmd_run(host="localhost", port="8000"):
"""Run server at given host port (or localhost 8000)"""
from django.core import management
management.runserver(host, port)
and this time it works!
| django 'module' object has no attribute 'call_command' | I wrote a function like
def cmd_run(host="localhost", port="8000"):
"""Run server at given host port (or localhost 8000)"""
from django.core import management
host_port = '%s:%s' % (host, port)
management.call_command('runserver', host_port)
When I executed it, an Exception was thrown:
Traceback (most recent call last):
File "/home/leona/workspace/bettyskitchen/lib/djangocliutils/bin/djangoctl", line 8, in <module> cli(*sys.argv[1:])
File "/home/leona/workspace/bettyskitchen/lib/djangocliutils/cmds.py", line 119, in __call__
print method(*args) or ""
File "/home/leona/workspace/bettyskitchen/lib/djangocliutils/cmds.py", line 170, in __call__
return self.method(*args, **kw)
File "/home/leona/workspace/bettyskitchen/lib/djangocliutils/djangocmds/basic.py", line 19, in cmd_run
management.call_command('runserver', host_port)
AttributeError: 'module' object has no attribute 'call_command'
How can I fix it?
| [
"Well, here it works... maybe your version of django has not this function? Try it in managed shell python manage.py shell and try help(management) to see if it is there on your version.\nAnother possibility is corruption or modification of the __init__.py file (where call_command is defined) in django.core.managem... | [
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003436932_django_python.txt |
Q:
Why does this provided regular expression return true?
I would like to know why following regular expression returns true:
reg = re.compile (r'[0-9]%')
reg.search ("50%")
[0-9] would match any single digit, in this case 5. But then 0 doesn't match %, so it should return false, but it returns true.
My code might have syntax errors, but you get the gist of it.
A:
reg.search() matches the pattern anywhere in the string (so it matches the 0%). If you want the entire string to match, try this:
re.compile(r'^[0-9]%$')
^ - matches the start of the string
$ - matches the end of the string
A:
This regex would match on the 0% portion of 50%.
A:
If you are searching for single-digit percentages inside a longer string, you could use a negative lookbehind:
In [171]: print(re.search('(?<!\d)\d%',"Foo is 5% complete"))
<_sre.SRE_Match object at 0xab302f8>
In [172]: print(re.search('(?<!\d)\d%',"Foo is 50% complete"))
None
In [173]: print(re.search('(?<!\d)\d%',"5% complete"))
<_sre.SRE_Match object at 0xab301a8>
In [174]: print(re.search('(?<!\d)\d%',"50% complete"))
None
A:
As gfdunn2 mentioned, it does a 'rolling-match' of the entire string. There are a couple things you can do to control it a bit better though.
The braces {} below can control how many characters you get, so it will give you much tighter matching.
>>> import re
#exactly 1 digit and %
>>> test = re.compile(r'[0-9]{1}%')
>>> print test.search("50%").group(0)
0%
#exactly 2 digits and %
>>> test = re.compile(r'[0-9]{2}%')
>>> print test.search("50%").group(0)
50%
#one or more digits
>>> test = re.compile(r'[0-9]+%')
>>> print test.search("50%").group(0)
50%
#in the event you want to include floating point percentages
>>> test = re.compile(r'[0-9.]+%')
>>> print test.search("50.4%").group(0)
50.4%
>>> print test.search("50.34%").group(0)
50.34%
| Why does this provided regular expression return true? | I would like to know why following regular expression returns true:
reg = re.compile (r'[0-9]%')
reg.search ("50%")
[0-9] would match any single digit, in this case 5. But then 0 doesn't match %, so it should return false, but it returns true.
My code might have syntax errors, but you get the gist of it.
| [
"reg.search() matches the pattern anywhere in the string (so it matches the 0%). If you want the entire string to match, try this:\nre.compile(r'^[0-9]%$')\n^ - matches the start of the string\n$ - matches the end of the string\n",
"This regex would match on the 0% portion of 50%.\n",
"If you are searching for... | [
8,
5,
1,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0003436950_python_regex.txt |
Q:
python read last line !
My problem is in this code:
try:
PassL = open(sys.argv[3], "r").readlines()
print "[+] Passwords:",len(PassL),"\n"
except(IOError):
print "[-] Error: Check your wordlist path\n"
sys.exit(1)
for word in PassL:
word = word.replace("\r","").replace("\n","")
login_form_seq = [
('log', sys.argv[2]),
('pwd', word),
('rememberme', 'forever'),
('wp-submit', 'Login >>'),
('redirect_to', 'wp-admin/')]
try:
login_form_data = urllib.urlencode(login_form_seq)
opener = urllib2.build_opener()
except:
print'Unknown ERROR'
try:
OP = opener.open(host, login_form_data).read()
except(urllib2.URLError), msg:
print msg
OP = ""
else:
'wrong?'
if re.search("WordPress requires Cookies",OP):
print "[-] Failed: WordPress has cookies enabled\n"
sys.exit(1)
#Change this response if different. (language)
if re.search("<strong>ERROR</strong>",OP):
print "[-] Login Failed :",word
else:
print "\n[!] Login Successfull:",'[#]The Information:',sys.argv[2],':',word
So the problem is, I provide sys.argv[2] and that gets the txt file. For example:
www.py wow.txt
Then in my python script I try to login to a web site with the password in wow.txt. The problem is, I put 15 passwords in wow.txt and my www.py script reads the last line!
The purpose of the script is because I forget a lot of my Wordpress accounts (around six accounts), and actually am thinking of trying 25 passwords for each. So make it easy for me -- don't say "go and try it manually", just give me the code or the right way.
A:
Most of your code never runs at all, because it's in an except block and unconditionally follows a sys.exit -- so execution will never get there, even if the exception does occur to trigger the except (if it doesn't occur of course the whole except is never entered). Look again at the code you posted...:
except(IOError):
print "[-] Error: Check your wordlist path\n"
sys.exit(1)
for word in PassL:
word = word.replace("\r","").replace("\n","")
login_form_seq = [ (etc etc)
Clearly your indentation is all wrong. I suspect what you want is:
except(IOError):
print "[-] Error: Check your wordlist path\n"
sys.exit(1)
for word in PassL:
word = word.replace("\r","").replace("\n","")
login_form_seq = [ (etc etc)
that is, deintenting only two lines (so the rest remain part of the loop).
How you could perpetrate such atrocious indentation in your code, I don't know. Maybe you're using tabs (instead of using 4 spaces, exclusively, for every indent) and your editor or IDE is set in some way that's misleading you about what the indents actually are.
A:
Your for word in PassL loop is only one line long, but it looks as if you probably want the rest of the script to be indented to also be part of that loop.
At the moment, the loop iterates through the list, replacing the variable word with a new value (as per the replace commands). When the loop ends, the last value in word is the last value in the list (without a line ending).
Increasing the indent on the rest of the script will run all of that code for each line in the file.
| python read last line ! | My problem is in this code:
try:
PassL = open(sys.argv[3], "r").readlines()
print "[+] Passwords:",len(PassL),"\n"
except(IOError):
print "[-] Error: Check your wordlist path\n"
sys.exit(1)
for word in PassL:
word = word.replace("\r","").replace("\n","")
login_form_seq = [
('log', sys.argv[2]),
('pwd', word),
('rememberme', 'forever'),
('wp-submit', 'Login >>'),
('redirect_to', 'wp-admin/')]
try:
login_form_data = urllib.urlencode(login_form_seq)
opener = urllib2.build_opener()
except:
print'Unknown ERROR'
try:
OP = opener.open(host, login_form_data).read()
except(urllib2.URLError), msg:
print msg
OP = ""
else:
'wrong?'
if re.search("WordPress requires Cookies",OP):
print "[-] Failed: WordPress has cookies enabled\n"
sys.exit(1)
#Change this response if different. (language)
if re.search("<strong>ERROR</strong>",OP):
print "[-] Login Failed :",word
else:
print "\n[!] Login Successfull:",'[#]The Information:',sys.argv[2],':',word
So the problem is, I provide sys.argv[2] and that gets the txt file. For example:
www.py wow.txt
Then in my python script I try to login to a web site with the password in wow.txt. The problem is, I put 15 passwords in wow.txt and my www.py script reads the last line!
The purpose of the script is because I forget a lot of my Wordpress accounts (around six accounts), and actually am thinking of trying 25 passwords for each. So make it easy for me -- don't say "go and try it manually", just give me the code or the right way.
| [
"Most of your code never runs at all, because it's in an except block and unconditionally follows a sys.exit -- so execution will never get there, even if the exception does occur to trigger the except (if it doesn't occur of course the whole except is never entered). Look again at the code you posted...:\nexcept(... | [
3,
2
] | [] | [] | [
"python"
] | stackoverflow_0003437250_python.txt |
Q:
How to step through Python threads independently? (WinPDB)
I am trying to debug Python using WinPDB and I have multiple threads using threading.Thread. I can never seem to control the threads individually. If I break execution, the entire script breaks. If I step through the source code of one thread, all of the others continue to be interleaved and continue some of their execution. This is true with Synchronicity turned on or off. Isn't there a way to step through a thread individually while keeping the others at a breakpoint?
Is WinPDB the wrong tool to use for this? I just don't know what to use. Eclipse PyDev barely works at all because the debugger itself seems to get race errors when starting multiple threads.
What is a tool that will actually robustly debug a multi-threaded Python program?
Thank you.
A:
I had a similar issue, it's not the most ideal answer, but I'll describe it for you and maybe you can work off of it.
I more or less wrote a mini debugger. Udp Client / Server and a function that did nothing but grab a global lock, sleep .1 seconds, and then release it. This function got passed to each thread. I then put a call to this function between critical areas that i wanted to debug. After starting the program, the udp server would listen for the client, and if i typed "pause", it would grab the same global lock used by the shared function, and not give it up until i typed "play" in the client. So doing this, you can get a fairly tight stop ... depending on the application.
Hope it helps ... Tiny snippet below. My application was for a test platform so what i did was add the function pointer to the base class constructor, and use this instead of time.sleep() .. giving me mild debugability. What you can do is pass this to each thread and add calls to the pause function at the beginning and end of your functions, and it would allow you to break, etc. I removed some of the commands but you can see that this can be made as extensive as you need it.
PAUSE_NOW = thread.allocate_lock()
def pause(s):
'''
FUNCTION: testStatus
DESCRIPTION: function passed to all test objects
INPUTS: none
RETURNS: none
'''
global Pause_NOW
PAUSE_NOW.acquire()
time.sleep(s)
PAUSE_NOW.release()
`
def server():
'''
\r\n
FUNCTION: server
DESCRIPTION: UDP server that launches a UDP client. The client it
starts can issue commands defined in cmdlineop. Most
functions return a status, but some are meant to block
the main thread as a means of pausing a test, in which case
a default response is returned.
INPUTS: none
RETURNS: none
'''
global EXIT
global Pause_NOW
host = "localhost"
port = 21567
buf = 1024
addr = (host,port)
UDPSock = socket(AF_INET,SOCK_DGRAM)
UDPSock.bind(addr)
sleep(1)
os.startfile('client.py')
#os.system('start python client.py')
cmdlineop = {
'pausenow' : "PAUSE_NOW.acquire()",
'playnow' : "PAUSE_NOW.release()",
}
while 1:
output = 'RECEIVED CMD'
# if EXIT: break
data,addr = UDPSock.recvfrom(buf)
if not data:
break
else:
if cmdlineop.has_key(data.split()[0]):
exec(cmdlineop[(data.split()[0])])
UDPSock.sendto(('\n'+output+'\n'),addr)
data = ''
else:
UDPSock.sendto('INVALID CMD',addr)
UDPSock.close()
| How to step through Python threads independently? (WinPDB) | I am trying to debug Python using WinPDB and I have multiple threads using threading.Thread. I can never seem to control the threads individually. If I break execution, the entire script breaks. If I step through the source code of one thread, all of the others continue to be interleaved and continue some of their execution. This is true with Synchronicity turned on or off. Isn't there a way to step through a thread individually while keeping the others at a breakpoint?
Is WinPDB the wrong tool to use for this? I just don't know what to use. Eclipse PyDev barely works at all because the debugger itself seems to get race errors when starting multiple threads.
What is a tool that will actually robustly debug a multi-threaded Python program?
Thank you.
| [
"I had a similar issue, it's not the most ideal answer, but I'll describe it for you and maybe you can work off of it.\nI more or less wrote a mini debugger. Udp Client / Server and a function that did nothing but grab a global lock, sleep .1 seconds, and then release it. This function got passed to each thread. ... | [
1
] | [] | [] | [
"debugging",
"multithreading",
"python",
"winpdb"
] | stackoverflow_0003417212_debugging_multithreading_python_winpdb.txt |
Q:
How to call bash process from within django / wsgi?
I'm using mod_wsgi apache2 adapter for a django site and I like to call some bash process within a view, using the usual
...
p = subprocess.Popen("/home/example.com/restart-tomcat.sh", shell=True)
sts = os.waitpid(p.pid, 0)[1]
...
This code works perfectly from within a usual python shell but does nothing (I can trace right now) when called within django. Am I missing some wsgi constraints? The script has 755 perms, so it should be executable.
A quick test
p = subprocess.Popen("date >> home/example.com/wsgi-test.txt", shell=True)
sts = os.waitpid(p.pid, 0)[1]
reveals that it does not even executes trivial commands. I am out of ideas at the moment and thankful for any input.
Thanks.
A:
The script itself may have 755 permissions, but things it calls might not have the correct permissions. Especially if you have tomcat running on port 80, which is a privileged port.
There are ways you can get around this sort of thing (setuid, sudo), but you'd better know exactly what you're doing.
I'd change your Popen call to open a different script that has the contents date >> /home/example.com/test.txt just to see if it's executing it at all, and then you can worry about trying to debug permissions.
A:
Writing To Standard Output
here: http://code.google.com/p/modwsgi/wiki/ApplicationIssues
Does that apply here? I'm researching a similar problem....
| How to call bash process from within django / wsgi? | I'm using mod_wsgi apache2 adapter for a django site and I like to call some bash process within a view, using the usual
...
p = subprocess.Popen("/home/example.com/restart-tomcat.sh", shell=True)
sts = os.waitpid(p.pid, 0)[1]
...
This code works perfectly from within a usual python shell but does nothing (I can trace right now) when called within django. Am I missing some wsgi constraints? The script has 755 perms, so it should be executable.
A quick test
p = subprocess.Popen("date >> home/example.com/wsgi-test.txt", shell=True)
sts = os.waitpid(p.pid, 0)[1]
reveals that it does not even executes trivial commands. I am out of ideas at the moment and thankful for any input.
Thanks.
| [
"The script itself may have 755 permissions, but things it calls might not have the correct permissions. Especially if you have tomcat running on port 80, which is a privileged port.\nThere are ways you can get around this sort of thing (setuid, sudo), but you'd better know exactly what you're doing.\nI'd change y... | [
2,
0
] | [] | [] | [
"bash",
"django",
"python",
"subprocess",
"tomcat"
] | stackoverflow_0002608464_bash_django_python_subprocess_tomcat.txt |
Q:
Python PySerial read-line timeout
I'm using pyserial to communicate with a embedded devise.
ser = serial.Serial(PORT, BAUD, timeout = TOUT)
ser.write(CMD)
z = ser.readline(eol='\n')
So we send CMD to the device and it replies with an string of varing length ending in a '\n'
if the devise cant replay then readline() times-out and z=''
if the devise is interrupted or crashes will it's sending the data then readline() times-out
and z will be a string without a '\n' at the end.
Is there a nice way to check if readline() has timed-out other than checking the state of z.
A:
I think what you might like to do is..
import re
import time
import serial
def doRead(ser,term):
matcher = re.compile(term) #gives you the ability to search for anything
tic = time.time()
buff = ser.read(128)
# you can use if not ('\n' in buff) too if you don't like re
while ((time.time() - tic) < tout) and (not matcher.search(buff)):
buff += ser.read(128)
return buff
if __name__ == "__main__":
ser = serial.Serial(PORT, BAUD, timeout = TOUT)
ser.write(CMD)
print doRead(ser,term='\n')
| Python PySerial read-line timeout | I'm using pyserial to communicate with a embedded devise.
ser = serial.Serial(PORT, BAUD, timeout = TOUT)
ser.write(CMD)
z = ser.readline(eol='\n')
So we send CMD to the device and it replies with an string of varing length ending in a '\n'
if the devise cant replay then readline() times-out and z=''
if the devise is interrupted or crashes will it's sending the data then readline() times-out
and z will be a string without a '\n' at the end.
Is there a nice way to check if readline() has timed-out other than checking the state of z.
| [
"I think what you might like to do is..\nimport re\nimport time\nimport serial\n\ndef doRead(ser,term):\n matcher = re.compile(term) #gives you the ability to search for anything\n tic = time.time()\n buff = ser.read(128)\n # you can use if not ('\\n' in buff) too if you don't like re\n whi... | [
5
] | [] | [] | [
"pyserial",
"python"
] | stackoverflow_0003437303_pyserial_python.txt |
Q:
How to Pass variables to python script?
I know it can be achieved by command line but I need to pass at least 10 variables and command line will mean too much of programming since these variables may or may not be passed.
Actually I have build A application half in vB( for GUI ) and Half in python( for script ). I need to pass variables to python, similar, to its keywords arguments, i.e, x = val1, y = val2. Is there any way to achieve this?
A:
If you are using Python <2.7 I would suggest optparse.
optparse is deprecated though, and in 2.7 you should use argparse
It makes passing named parameters a breeze.
A:
you can do something fun like call it as
thepyscript.py "x = 12,y = 'hello world', z = 'jam'"
and inside your script,
parse do:
stuff = arg[1].split(',')
for item in stuff:
exec(item) #or eval(item) depending on how complex you get
#Exec can be a lot of fun :) In fact with this approach you could potentially
#send functions to your script.
#If this is more than you need, then i'd stick w/ arg/optparse
A:
Since you're working on windows with VB, it's worth mentioning that IronPython might be one option. Since both VB and IronPython can interact through .NET, you could wrap up your script in an assembly and expose a function which you call with the required arguments.
A:
Have you taken a look at the getopt module? It's designed to make working with command line options easier. See also the examples at Dive Into Python.
If you are working with Python 2.7 (and not lower), than you can also have a look at the argparse module which should make it even easier.
A:
If your script is not called too often, you can use a configuration file.
The .ini style is easily readable by ConfigParser:
[Section_1]
foo1=1
foo2=2
foo3=5
...
[Section_2]
bar1=1
bar2=2
bar3=3
...
If you have a serious amount of variables, it might be the right way to go.
A:
What do you think about creating a python script setting these variables from the gui side? When starting the python app you just start this script and you have your vars.
Execfile
| How to Pass variables to python script? | I know it can be achieved by command line but I need to pass at least 10 variables and command line will mean too much of programming since these variables may or may not be passed.
Actually I have build A application half in vB( for GUI ) and Half in python( for script ). I need to pass variables to python, similar, to its keywords arguments, i.e, x = val1, y = val2. Is there any way to achieve this?
| [
"If you are using Python <2.7 I would suggest optparse.\noptparse is deprecated though, and in 2.7 you should use argparse\nIt makes passing named parameters a breeze.\n",
"you can do something fun like call it as\nthepyscript.py \"x = 12,y = 'hello world', z = 'jam'\"\n\nand inside your script,\nparse do:\nstuff... | [
9,
6,
3,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0003434048_python.txt |
Q:
How do I disable a button after it's clicked in wxpython?
There are two buttons in my little program, start and stop. And what I want is to disable the start button after I click it, and when I hit the stop button it should return to normal. How can I do this? I googled for a while and couldn't find the answer, hope you guys can help me out.
Thanks!
A:
Use the button's Enable and Disable methods in the appropriate event handlers. There's a sample available at the link below:
wxPython Button Demo
In this snippet we are playing around with wxPython's buttons, showing you how to bind the mouse click event, enable and disable, show and hide the buttons. Each button also has a tool-tip (hint) associated with itself.
| How do I disable a button after it's clicked in wxpython? | There are two buttons in my little program, start and stop. And what I want is to disable the start button after I click it, and when I hit the stop button it should return to normal. How can I do this? I googled for a while and couldn't find the answer, hope you guys can help me out.
Thanks!
| [
"Use the button's Enable and Disable methods in the appropriate event handlers. There's a sample available at the link below:\n\nwxPython Button Demo\nIn this snippet we are playing around with wxPython's buttons, showing you how to bind the mouse click event, enable and disable, show and hide the buttons. Each bu... | [
3
] | [] | [] | [
"event_handling",
"python",
"wxpython"
] | stackoverflow_0003437438_event_handling_python_wxpython.txt |
Q:
How do you have python scripts display how much time it takes to execute each process?
It was something like cMessage I think? I can't remember, could someone help me?
A:
cProfile ?
To time a function, you can also use a decorator like this one:
from functools import wraps
import time
def timed(f):
"""Time a function."""
@wraps(f)
def wrapper(*args, **kwds):
start = time.clock()
result = f(*args)
end = 1000 * (time.clock() - start)
print '%s: %.3f ms' % (f.func_name, end)
return result
return wrapper
And "mark" your fonction by "@timed" like that:
@timed
def toBeTimed():
pass
| How do you have python scripts display how much time it takes to execute each process? | It was something like cMessage I think? I can't remember, could someone help me?
| [
"cProfile ?\nTo time a function, you can also use a decorator like this one:\nfrom functools import wraps\nimport time\n\ndef timed(f):\n \"\"\"Time a function.\"\"\"\n @wraps(f)\n def wrapper(*args, **kwds):\n start = time.clock()\n result = f(*args)\n end = 1000 * (time.clock() - sta... | [
2
] | [] | [] | [
"python",
"runtime",
"time"
] | stackoverflow_0003437465_python_runtime_time.txt |
Q:
Detect English verb tenses using NLTK
I am looking for a way given an English text count verb phrases in it in past, present and future tenses. For now I am using NLTK, do a POS (Part-Of-Speech) tagging, and then count say 'VBD' to get past tenses. This is not accurate enough though, so I guess I need to go further and use chunking, then analyze VP-chunks for specific tense patterns. Is there anything existing that does that? Any further reading that might be helpful? The NLTK book is focused mostly on NP-chunks, and I can find quite few info on VP-chunks.
A:
Thee exact answer depends on which chunker you intend to use, but list comprehensions will take you a long way. This gets you the number of verb phrases using a non-existent chunker.
len([phrase for phrase in nltk.Chunker(sentence) if phrase[1] == 'VP'])
You can take a more fine-grained approach to detect numbers of tenses.
A:
You can do this with either the Berkeley Parser or Stanford Parser. But I don't know if there's a Python interface available for either.
| Detect English verb tenses using NLTK | I am looking for a way given an English text count verb phrases in it in past, present and future tenses. For now I am using NLTK, do a POS (Part-Of-Speech) tagging, and then count say 'VBD' to get past tenses. This is not accurate enough though, so I guess I need to go further and use chunking, then analyze VP-chunks for specific tense patterns. Is there anything existing that does that? Any further reading that might be helpful? The NLTK book is focused mostly on NP-chunks, and I can find quite few info on VP-chunks.
| [
"Thee exact answer depends on which chunker you intend to use, but list comprehensions will take you a long way. This gets you the number of verb phrases using a non-existent chunker.\nlen([phrase for phrase in nltk.Chunker(sentence) if phrase[1] == 'VP'])\n\nYou can take a more fine-grained approach to detect numb... | [
10,
1
] | [] | [] | [
"nlp",
"nltk",
"python"
] | stackoverflow_0003434144_nlp_nltk_python.txt |
Q:
Creating a Key Command in Python
I'm writing my own simple key logger based on a script I found online. However, I'm trying to write a key command so that the logger program will close when this command is typed. How should I go about this? (Also I know it's not secure at all, however that's not a concern with this program)
For example Ctrl + 'exit' would close the program.
Also It sometimes won't print certain character properly in the .log file it creates, what could be causing this? (I think the character encouding type may be causeing this problem)
#Key Logger
#By: K.B. Carte
#Version 1.0
################
import pythoncom, pyHook, sys, logging, time
LOG_FILENAME = 'C:\KeyLog\log.out'
def OnKeyboardEvent(event):
keytime = time.strftime('%I:%M %S %p %A %B %d, %Y ')
logging.basicConfig(filename=LOG_FILENAME,
level=logging.DEBUG,
format='%(message)s')
logging.log(10, keytime + "Key: '" + chr(event.Ascii) + "'")
return True
hm = pyHook.HookManager()
hm.KeyDown = OnKeyboardEvent
hm.HookKeyboard()
pythoncom.PumpMessages()
This is in Windows 7, BTW.
A:
To get it to close via a certain command, say "quit" ... you'd want to create a buffer .... if you keep everything you log in a buffer, you can easily do
buff += newkeypress
if "quit" in buff[-4:]:
logfile.close()
sys.exit(0)
or you can do something like append/pop with a list .. or some other type of circular buffer
for funky characters, you may wind up wanting to just print the whole thing as hex .. or ignoring events less than ascii 0 (such as \b and other funky characters)
Or .. make an ascii table (dictionary) and log the match for the key, so if you get \b you log '' and if you get '0' you log '0'
| Creating a Key Command in Python | I'm writing my own simple key logger based on a script I found online. However, I'm trying to write a key command so that the logger program will close when this command is typed. How should I go about this? (Also I know it's not secure at all, however that's not a concern with this program)
For example Ctrl + 'exit' would close the program.
Also It sometimes won't print certain character properly in the .log file it creates, what could be causing this? (I think the character encouding type may be causeing this problem)
#Key Logger
#By: K.B. Carte
#Version 1.0
################
import pythoncom, pyHook, sys, logging, time
LOG_FILENAME = 'C:\KeyLog\log.out'
def OnKeyboardEvent(event):
keytime = time.strftime('%I:%M %S %p %A %B %d, %Y ')
logging.basicConfig(filename=LOG_FILENAME,
level=logging.DEBUG,
format='%(message)s')
logging.log(10, keytime + "Key: '" + chr(event.Ascii) + "'")
return True
hm = pyHook.HookManager()
hm.KeyDown = OnKeyboardEvent
hm.HookKeyboard()
pythoncom.PumpMessages()
This is in Windows 7, BTW.
| [
"To get it to close via a certain command, say \"quit\" ... you'd want to create a buffer .... if you keep everything you log in a buffer, you can easily do\nbuff += newkeypress\nif \"quit\" in buff[-4:]:\n logfile.close()\n sys.exit(0)\n\nor you can do something like append/pop with a list .. or some other t... | [
0
] | [] | [] | [
"keylogger",
"python",
"windows"
] | stackoverflow_0003437545_keylogger_python_windows.txt |
Q:
Text mining: when to use parser, tagger, NER tool?
I'm doing a project on mining blog contents and I need help differentiating on which tool to uses. When do I use a parser, when do I use a tagger, and when do I need to use a NER tool?
For instance, I want to find out the most talked about topics/subjects between several blogs; do I use a part-of-speech tagger to grab the nouns and do a frequency count? That would probably be insufficient because very generic terms can pop up right? Or do I have a list of categories and these synonyms that I can match on?
BTW, I'm using nltk, but am looking at stanford tagger or parser since a couple of dudes said that it was good.
A:
Instead of trying to reinvent the wheel, you might want to read up on Topic Models, which basically creates clusters of words that frequently occur together. Mallet has a readily available toolkit for doing such a task: http://mallet.cs.umass.edu/topics.php .
To answer your original question, POS tagger, parsers, and NER tools are not typically used for topic identification, but are more heavily used for tasks like information extraction where the goal is to identify within a document the specific actors, events, locations, times, etc... For example if you had a simple sentence like "John gave the apple to Mary." you might use a dependency parser to figure out that John is the subject, the apple is the object, and Mary is the prepositional object; thus you know John is the giver and Mary is the receiver and not vice-versa.
| Text mining: when to use parser, tagger, NER tool? | I'm doing a project on mining blog contents and I need help differentiating on which tool to uses. When do I use a parser, when do I use a tagger, and when do I need to use a NER tool?
For instance, I want to find out the most talked about topics/subjects between several blogs; do I use a part-of-speech tagger to grab the nouns and do a frequency count? That would probably be insufficient because very generic terms can pop up right? Or do I have a list of categories and these synonyms that I can match on?
BTW, I'm using nltk, but am looking at stanford tagger or parser since a couple of dudes said that it was good.
| [
"Instead of trying to reinvent the wheel, you might want to read up on Topic Models, which basically creates clusters of words that frequently occur together. Mallet has a readily available toolkit for doing such a task: http://mallet.cs.umass.edu/topics.php .\nTo answer your original question, POS tagger, parsers... | [
3
] | [] | [] | [
"nlp",
"nltk",
"python"
] | stackoverflow_0003108602_nlp_nltk_python.txt |
Q:
How to create the union of many sets using a generator expression?
Suppose I have a list of sets and I want to get the union over all sets in that list. Is there any way to do this using a generator expression? In other words, how can I create the union over all sets in that list directly as a frozenset?
A:
Just use the .union() method.
>>> l = [set([1,2,3]), set([4,5,6]), set([1,4,9])]
>>> frozenset().union(*l)
frozenset([1, 2, 3, 4, 5, 6, 9])
This works for any iterable of iterables.
A:
I assume that what you're trying to avoid is the intermediate creations of frozenset objects as you're building up the union?
Here's one way to do it. NOTE: this originally used itertools.chain() but, as Kenny's comment notes, the version below is slightly better:
import itertools
def mkunion(*args):
return frozenset(itertools.chain.from_iterable(args))
Invoke like this:
a = set(['a','b','c'])
b = set(['a','e','f'])
c = mkunion(a,b) # => frozenset(['a', 'c', 'b', 'e', 'f'])
A:
Nested generator expression. But I think they are a bit cryptic, so the way KennyTM suggested may be clearer.
frozenset(some_item for some_set in some_sets for some_item in some_set)
| How to create the union of many sets using a generator expression? | Suppose I have a list of sets and I want to get the union over all sets in that list. Is there any way to do this using a generator expression? In other words, how can I create the union over all sets in that list directly as a frozenset?
| [
"Just use the .union() method.\n>>> l = [set([1,2,3]), set([4,5,6]), set([1,4,9])]\n>>> frozenset().union(*l)\nfrozenset([1, 2, 3, 4, 5, 6, 9])\n\nThis works for any iterable of iterables.\n",
"I assume that what you're trying to avoid is the intermediate creations of frozenset objects as you're building up the u... | [
64,
6,
4
] | [] | [] | [
"generator",
"python",
"set"
] | stackoverflow_0003438140_generator_python_set.txt |
Q:
Python: date formatted with %x (locale) is not as expected
I have a datetime object, for which I want to create a date string according to the OS locale settings (as specified e.g. in Windows'7 region and language settings).
Following Python's datetime formatting documentation, I used the %x format code which is supposed to output "Locale’s appropriate date representation.". I expect this "representation" to be either Windows "short date" or "Long date" format, but it isn't either one.
(I have the short date format set to d/MM/yyyy and the long date format to dddd d MMMM yyyy, but the output is dd/MM/yy)
What's wrong here: the Python documentation, the Python implementation, or my expectation ?
(and how to fix?)
A:
After reading the setlocale() documentation, I understood that the default OS locale is not used by Python as the default locale. To use it, I had to start my module with:
import locale
locale.setlocale(locale.LC_ALL, '')
Alternatively, if you intend to only reset the locale's time settings, use just LC_TIME as it breaks many fewer things:
import locale
locale.setlocale(locale.LC_TIME, '')
Surely there will be a valid reason for this, but at least this could have been mentioned as a remark in the Python documentation for the %x directive.
A:
Is your locale set in your script? If you call locale.getlocale(), is the result expected? Compare below:
>>> import locale
>>> locale.getlocale()
(None, None)
>>> import datetime
>>> today = datetime.date.today()
>>> today
datetime.date(2010, 8, 9)
>>> today.strftime('%x')
'08/09/10'
>>> locale.setlocale(locale.LC_ALL, "de_DE.UTF-8")
'de_DE.UTF-8'
>>> locale.getlocale()
('de_DE', 'UTF8')
>>> today.strftime('%x')
'09.08.2010'
Note that there are bugs in the datetime module, mostly because of bugs in the underlying C libraries. On my installation (latest OS X), for example, the formatting string %z is completely unavailable.
On Windows, the syntax of locale strings available to setlocale() follows a different syntax than on *nix platforms. A list is here on MSDN.
And if you just wish to set your script to whatever default locale your users have installed (in mine: UK English), you just do this at the beginning of the main script. Don't do it in modules, as it overrides a global variable:
>>> locale.setlocale(locale.LC_ALL, "")
'en_GB.UTF-8'
| Python: date formatted with %x (locale) is not as expected | I have a datetime object, for which I want to create a date string according to the OS locale settings (as specified e.g. in Windows'7 region and language settings).
Following Python's datetime formatting documentation, I used the %x format code which is supposed to output "Locale’s appropriate date representation.". I expect this "representation" to be either Windows "short date" or "Long date" format, but it isn't either one.
(I have the short date format set to d/MM/yyyy and the long date format to dddd d MMMM yyyy, but the output is dd/MM/yy)
What's wrong here: the Python documentation, the Python implementation, or my expectation ?
(and how to fix?)
| [
"After reading the setlocale() documentation, I understood that the default OS locale is not used by Python as the default locale. To use it, I had to start my module with:\nimport locale\nlocale.setlocale(locale.LC_ALL, '')\n\nAlternatively, if you intend to only reset the locale's time settings, use just LC_TIME... | [
8,
5
] | [] | [] | [
"datetime",
"internationalization",
"locale",
"python"
] | stackoverflow_0003438120_datetime_internationalization_locale_python.txt |
Q:
Reading file using python and and see if a particular string is there inthe file
I have a file in the following format
Summary;None;Description;Emails\nDarlene\nGregory Murphy\nDr. Ingram\n;DateStart;20100615T111500;DateEnd;20100615T121500;Time;20100805T084547Z
Summary;Presence tech in smart energy management;Description;;DateStart;20100628T130000;DateEnd;20100628T133000;Time;20100628T055408Z
Summary;meeting;Description;None;DateStart;20100629T110000;DateEnd;20100629T120000;Time;20100805T084547Z
Summary;meeting;Description;None;DateStart;20100630T090000;DateEnd;20100630T100000;Time;20100805T084547Z
Summary;Balaji Viswanath: Meeting;Description;None;DateStart;20100712T140000;DateEnd;20100712T143000;Time;20100805T084547Z
Summary;Government Industry Training: How Smart is Your City - The Smarter City Assessment Tool\nUS Call-In Information: 1-866-803-2143\, International Number: 1-210-795-1098\, International Toll-free Numbers: See below\, Passcode: 6785765\nPresentation Link - Copy and paste URL into web browser: http://w3.tap.ibm.com/medialibrary/media_view?id=87408;Description;International Toll-free Numbers link - Copy and paste this URL into your web browser:\n\nhttps://w3-03.sso.ibm.com/sales/support/ShowDoc.wss?docid=NS010BBUN-7P4TZU&infotype=SK&infosubtype=N0&node=clientset\,IA%7Cindustries\,Y&ftext=&sort=date&showDetails=false&hitsize=25&offset=0&campaign=#International_Call-in_Numbers;DateStart;20100811T203000;DateEnd;20100811T213000;Time;20100805T084547Z
Now I need to create a function that does the following:
The function argument would specify which line to read, and let say i have already done line.split(;)
See if there is "meeting" or "call in number" anywhere in line[1], and see if there is "meeting" or "call in number" anywhere in line[2]. If either of both of these are true, the function should return "call-in meeting". Else it should return "None Inferred".
Thanks in advance
A:
use the in operator to see if there is a match
for line in open("file"):
if "string" in line :
....
A:
A build on ghostdog74's answer:
def finder(line):
'''Takes line number as argument. First line is number 0.'''
with open('/home/vlad/Desktop/file.txt') as f:
lines = f.read().split('Summary')[1:]
searchLine = lines[line]
if 'meeting' in searchLine.lower() or 'call in number' in searchLine.lower():
return 'call-in meeting'
else:
return 'None Inferred'
I don't quite understand what you meant by line[1] and line[2] so this is the best I could do.
EDIT: Fixed the problem with the \n's. I figure since you're searching for the meeting and call in number you don't need the Summary so I used it to split the lines.
A:
vlad003 is right: if you have newline characters in the lines; they will be new lines! In this case, I would split on "Summary" instead:
import itertools
def chunks( filePath ):
"Since you have newline characters in each section,\
you can't read each line in turn. This function reads\
lines of the file and splits them into chunks, restarting\
each time 'Summary' starts a line."
with open( filePath ) as theFile:
chunk = [ ]
for line in theFile:
if line.startswith( "Summary" ):
if chunk: yield chunk
chunk = [ line ]
else:
chunk.append( line )
yield chunk
def nth(iterable, n, default=None):
"Gets the nth element of an iterator."
return next(islice(iterable, n, None), default)
def getStatus( chunkNum ):
"Get the nth chunk of the file, split it by ";", and return the result."
chunk = nth( chunks, chunkNum, "" ).split( ";" )
if not chunk[ 0 ]:
raise SomeError # could not get the right chunk
if "meeting" in chunk[ 1 ].lower() or "call in number" in chunk[ 1 ].lower():
return "call-in meeting"
else:
return "None Inferred"
Note that this is silly if you plan to read all the chunks of the file, since it opens the file and reads through it once per query. If you plan to do this often, it would be worth parsing it into a better data format (e.g. an array of statuses). This would require one pass through the file, and give you much better lookups.
| Reading file using python and and see if a particular string is there inthe file | I have a file in the following format
Summary;None;Description;Emails\nDarlene\nGregory Murphy\nDr. Ingram\n;DateStart;20100615T111500;DateEnd;20100615T121500;Time;20100805T084547Z
Summary;Presence tech in smart energy management;Description;;DateStart;20100628T130000;DateEnd;20100628T133000;Time;20100628T055408Z
Summary;meeting;Description;None;DateStart;20100629T110000;DateEnd;20100629T120000;Time;20100805T084547Z
Summary;meeting;Description;None;DateStart;20100630T090000;DateEnd;20100630T100000;Time;20100805T084547Z
Summary;Balaji Viswanath: Meeting;Description;None;DateStart;20100712T140000;DateEnd;20100712T143000;Time;20100805T084547Z
Summary;Government Industry Training: How Smart is Your City - The Smarter City Assessment Tool\nUS Call-In Information: 1-866-803-2143\, International Number: 1-210-795-1098\, International Toll-free Numbers: See below\, Passcode: 6785765\nPresentation Link - Copy and paste URL into web browser: http://w3.tap.ibm.com/medialibrary/media_view?id=87408;Description;International Toll-free Numbers link - Copy and paste this URL into your web browser:\n\nhttps://w3-03.sso.ibm.com/sales/support/ShowDoc.wss?docid=NS010BBUN-7P4TZU&infotype=SK&infosubtype=N0&node=clientset\,IA%7Cindustries\,Y&ftext=&sort=date&showDetails=false&hitsize=25&offset=0&campaign=#International_Call-in_Numbers;DateStart;20100811T203000;DateEnd;20100811T213000;Time;20100805T084547Z
Now I need to create a function that does the following:
The function argument would specify which line to read, and let say i have already done line.split(;)
See if there is "meeting" or "call in number" anywhere in line[1], and see if there is "meeting" or "call in number" anywhere in line[2]. If either of both of these are true, the function should return "call-in meeting". Else it should return "None Inferred".
Thanks in advance
| [
"use the in operator to see if there is a match\nfor line in open(\"file\"):\n if \"string\" in line :\n ....\n\n",
"A build on ghostdog74's answer:\ndef finder(line):\n '''Takes line number as argument. First line is number 0.'''\n with open('/home/vlad/Desktop/file.txt') as f:\n lines = f... | [
1,
1,
1
] | [] | [] | [
"compare",
"file",
"python"
] | stackoverflow_0003437530_compare_file_python.txt |
Q:
Create name of path files from list
I want to create path of files from list.
pathList = [['~/workspace'], ['test'], ['*'], ['*A', '*2'], ['*Z?', '*1??'], ['*'], ['*'], ['*'], ['*.*']]
and I want
[['', '~/workspace', 'test', '*', '*A', '*Z?', '*', '*', '*', '*.*']]
[['', '~/workspace', 'test', '*', '*A', '*1??', '*', '*', '*', '*.*']]
[['', '~/workspace', 'test', '*', '*2', '*Z?', '*', '*', '*', '*.*']]
[['', '~/workspace', 'test', '*', '*2', '*1??', '*', '*', '*', '*.*']]
I try to create it from for loop but I get
[['', '~/workspace', 'test', '*', '*A', '*Z?', '*', '*', '*', '*.*', '*1??', '*', '*', '*', '*.*', '*2', '*Z?', '*', '*', '*', '*.*', '*1??', '*', '*', '*', '*.*']]
How can I do? Please help me.
Thank you.
A:
Anticipating the next step - you can create paths like this
>>> import os, itertools
>>> [os.path.join(*x) for x in itertools.product(*pathList)]
['~/workspace/test/*/*A/*Z?/*/*/*/*.*',
'~/workspace/test/*/*A/*1??/*/*/*/*.*',
'~/workspace/test/*/*2/*Z?/*/*/*/*.*',
'~/workspace/test/*/*2/*1??/*/*/*/*.*']
and here is a version using itertools.starmap
>>> from itertools import starmap
>>> starmap(os.path.join, itertools.product(*pathList))
<itertools.starmap object at 0xb77d948c>
>>> list(_)
['~/workspace/test/*/*A/*Z?/*/*/*/*.*',
'~/workspace/test/*/*A/*1??/*/*/*/*.*',
'~/workspace/test/*/*2/*Z?/*/*/*/*.*',
'~/workspace/test/*/*2/*1??/*/*/*/*.*']
A:
In Python 2.6 or newer you can use itertools.product:
import itertools
for x in itertools.product(*pathList):
print x
A:
I'm not sure I understand the question, but I think you want itertools.product:
print( list( itertools.product( *pathList ) ) )
>>> [('~/workspace', 'test', '*', '*A', '*Z?', '*', '*', '*', '*.*'),
('~/workspace', 'test', '*', '*A', '*1??', '*', '*', '*', '*.*'),
('~/workspace', 'test', '*', '*2', '*Z?', '*', '*', '*', '*.*'),
('~/workspace', 'test', '*', '*2', '*1??', '*', '*', '*', '*.*')]
This yield all possible paths, taking one element from each nested list.
| Create name of path files from list | I want to create path of files from list.
pathList = [['~/workspace'], ['test'], ['*'], ['*A', '*2'], ['*Z?', '*1??'], ['*'], ['*'], ['*'], ['*.*']]
and I want
[['', '~/workspace', 'test', '*', '*A', '*Z?', '*', '*', '*', '*.*']]
[['', '~/workspace', 'test', '*', '*A', '*1??', '*', '*', '*', '*.*']]
[['', '~/workspace', 'test', '*', '*2', '*Z?', '*', '*', '*', '*.*']]
[['', '~/workspace', 'test', '*', '*2', '*1??', '*', '*', '*', '*.*']]
I try to create it from for loop but I get
[['', '~/workspace', 'test', '*', '*A', '*Z?', '*', '*', '*', '*.*', '*1??', '*', '*', '*', '*.*', '*2', '*Z?', '*', '*', '*', '*.*', '*1??', '*', '*', '*', '*.*']]
How can I do? Please help me.
Thank you.
| [
"Anticipating the next step - you can create paths like this\n>>> import os, itertools\n>>> [os.path.join(*x) for x in itertools.product(*pathList)]\n['~/workspace/test/*/*A/*Z?/*/*/*/*.*',\n '~/workspace/test/*/*A/*1??/*/*/*/*.*',\n '~/workspace/test/*/*2/*Z?/*/*/*/*.*',\n '~/workspace/test/*/*2/*1??/*/*/*/*.*']\... | [
2,
1,
1
] | [] | [] | [
"list",
"loops",
"python"
] | stackoverflow_0003438736_list_loops_python.txt |
Q:
Is there a better error reporting via e-mail for Django?
Quite often the error reports coming via e-mail are less than useful in tracking bugs. Most often this is due to missing session data and username of the user triggering the error. Is there a project or a library I could use to get more complete error reports?
A:
You could write your own exception middleware, as suggested here (bottom of page).
There is a base snippets here and an example of how to extract the traceback here
| Is there a better error reporting via e-mail for Django? | Quite often the error reports coming via e-mail are less than useful in tracking bugs. Most often this is due to missing session data and username of the user triggering the error. Is there a project or a library I could use to get more complete error reports?
| [
"You could write your own exception middleware, as suggested here (bottom of page).\nThere is a base snippets here and an example of how to extract the traceback here\n"
] | [
3
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003438618_django_python.txt |
Q:
Tasks queue process in python
Task is:
I have task queue stored in db. It grows. I need to solve tasks by python script when I have resources for it. I see two ways:
python script working all the time. But i don't like it (reason posible memory leak).
python script called by cron and do a little part of task. But i need to solve the problem of one working active script in memory (To prevent active scripts count grow). What is the best solution to implement it in python?
Any ideas to solve this problem at all?
A:
This is a bit of a vague question. One thing you should remember is that it is very difficult to leak memory in Python, because of the automatic garbage collection. croning a Python script to handle the queue isn't very nice, although it would work fine.
I would use method 1; if you need more power you could make a small Python process that monitors the DB queue and starts new processes to handle the tasks.
A:
You can use a lockfile to prevent multiple scripts from running out of cron. See the answers to an earlier question, "Python: module for creating PID-based lockfile". This is really just good practice in general for anything that you need to make sure won't have multiple instances running, actually, so you should look into it even if you do have the script running constantly, which I do suggest.
For most things, it shouldn't be too hard to avoid memory leaks, but if you're having a lot of trouble with it (I sometimes do with complex third-party web frameworks, for example), I would suggest instead writing the script with a small, carefully-designed main loop that monitors the database for new jobs, and then uses the multiprocessing module to fork off new processes to complete each task.
When a task is complete, the child process can exit, immediately freeing any memory that isn't properly garbage collected, and the main loop should be simple enough that you can avoid any memory leaks.
This also offers the advantage that you can run multiple tasks in parallel if your system has more than one CPU core, or if your tasks spend a lot of time waiting for I/O.
A:
I'd suggest using Celery, an asynchronous task queuing system which I use myself.
It may seem a bit heavy for your use case, but it makes it easy to expand later by adding more worker resources if/when needed.
| Tasks queue process in python | Task is:
I have task queue stored in db. It grows. I need to solve tasks by python script when I have resources for it. I see two ways:
python script working all the time. But i don't like it (reason posible memory leak).
python script called by cron and do a little part of task. But i need to solve the problem of one working active script in memory (To prevent active scripts count grow). What is the best solution to implement it in python?
Any ideas to solve this problem at all?
| [
"This is a bit of a vague question. One thing you should remember is that it is very difficult to leak memory in Python, because of the automatic garbage collection. croning a Python script to handle the queue isn't very nice, although it would work fine.\nI would use method 1; if you need more power you could make... | [
1,
1,
1
] | [] | [] | [
"python",
"queue",
"task"
] | stackoverflow_0003439020_python_queue_task.txt |
Q:
when i easy_install greenlet i got "error: Setup script exited with error: command 'gcc' failed with exit status 1 "
when i easy_install greenlet(also eventlet) as the documents says in ubuntu 10.04 i got the error above.
is there anyone know why?
Expect your help!
And I have install build-essential
As I canot take the format right here, so I paste the message printed out there http://sugelawa.appspot.com/?p=35001
Thank u very much!
A:
(Warning: Ubuntu specific answer. Somewhat applicable to Debian, to but I don't have the details in my head right now) To use easy_install to install modules that contain C extensions (like greenlet), you need a complete development stack installed on your system. For a basic install, the means build-essential for the C part and python-all-dev for the Python part (that's where Python.h lives).
Add an 'ubuntu' tag to the question for clarity (don't have sufficient reputation myself as of now)
| when i easy_install greenlet i got "error: Setup script exited with error: command 'gcc' failed with exit status 1 " | when i easy_install greenlet(also eventlet) as the documents says in ubuntu 10.04 i got the error above.
is there anyone know why?
Expect your help!
And I have install build-essential
As I canot take the format right here, so I paste the message printed out there http://sugelawa.appspot.com/?p=35001
Thank u very much!
| [
"(Warning: Ubuntu specific answer. Somewhat applicable to Debian, to but I don't have the details in my head right now) To use easy_install to install modules that contain C extensions (like greenlet), you need a complete development stack installed on your system. For a basic install, the means build-essential for... | [
8
] | [] | [] | [
"easy_install",
"linux",
"python",
"ubuntu"
] | stackoverflow_0003438624_easy_install_linux_python_ubuntu.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.