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:
Role of C,C++,python,perl in Web development
Please bear with me experts i'm a newbie in web dev.
With html,css can take care of webpages..
javascript,ajax for some dynamic content..
php for server side scripting,accessing databases,sending emails,doing all other stuf...
What role do these programming languages play?
Can they do any other important task which cannot be done by PHP?
A:
All languages can all do basically any task any other one of them can do, as they are all Turing complete.
PHP works as a server-side scripting language, but you can also use Perl, Python, Ruby, Haskell, Lisp, Java, C, C++, assembly, or pretty much any other language that can access standard input and standard output for CGI communication with web content.
PHP is widely used because a) it's easy to learn a little and go, and b) the rather tedious CGI protocols are skipped, as the language handles them for you, so you can just plug your PHP script into an HTML page and not have to know how your program reads the information at all. This makes web programming easier for PHP, but the PHP interpreter is written in C, which does all the heavy lifting, so logically if PHP can do server-side scripting, so can C. Since most other languages are written in C, they too can do server-side scripting. (And since C compiles down to assembly, assembly can do it too, and so can any language that compiles down to assembly. Which is all of them not already covered.)
A:
The language is where the actual logic of your application resides.
Perl, Python, Ruby etc. are all server side scripting languages (although their implementations and deployment methods are quite different).
As for "Can they do any other important task which cannot be done by PHP?", not really. All the languages are equal 'power' wise but the language design and capabilities make the development experience quite different.
Here's a relevant link about some of the things PHP gets right by a rather prolific Pythonista http://blog.ianbicking.org/2008/01/12/what-php-deployment-gets-right/
A:
Another difference between your language choice is speed. An app written in C is going to run faster and require less system resources in general then a higher level scripting language. In a small scale app, you'd never notice. If your site is the next facebook, you will.
Here's a good example of a choice of languages having a very real effect:
http://developers.slashdot.org/story/09/12/20/1433257/The-Environmental-Impact-of-PHP-Compared-To-C-On-Facebook?art_pos=9
A:
If you'd like to understand how all of these different programming languages can be used for server-side scripting, read up on CGI.
|
Role of C,C++,python,perl in Web development
|
Please bear with me experts i'm a newbie in web dev.
With html,css can take care of webpages..
javascript,ajax for some dynamic content..
php for server side scripting,accessing databases,sending emails,doing all other stuf...
What role do these programming languages play?
Can they do any other important task which cannot be done by PHP?
|
[
"All languages can all do basically any task any other one of them can do, as they are all Turing complete.\nPHP works as a server-side scripting language, but you can also use Perl, Python, Ruby, Haskell, Lisp, Java, C, C++, assembly, or pretty much any other language that can access standard input and standard output for CGI communication with web content.\nPHP is widely used because a) it's easy to learn a little and go, and b) the rather tedious CGI protocols are skipped, as the language handles them for you, so you can just plug your PHP script into an HTML page and not have to know how your program reads the information at all. This makes web programming easier for PHP, but the PHP interpreter is written in C, which does all the heavy lifting, so logically if PHP can do server-side scripting, so can C. Since most other languages are written in C, they too can do server-side scripting. (And since C compiles down to assembly, assembly can do it too, and so can any language that compiles down to assembly. Which is all of them not already covered.)\n",
"The language is where the actual logic of your application resides. \nPerl, Python, Ruby etc. are all server side scripting languages (although their implementations and deployment methods are quite different). \nAs for \"Can they do any other important task which cannot be done by PHP?\", not really. All the languages are equal 'power' wise but the language design and capabilities make the development experience quite different.\nHere's a relevant link about some of the things PHP gets right by a rather prolific Pythonista http://blog.ianbicking.org/2008/01/12/what-php-deployment-gets-right/\n",
"Another difference between your language choice is speed. An app written in C is going to run faster and require less system resources in general then a higher level scripting language. In a small scale app, you'd never notice. If your site is the next facebook, you will.\nHere's a good example of a choice of languages having a very real effect:\nhttp://developers.slashdot.org/story/09/12/20/1433257/The-Environmental-Impact-of-PHP-Compared-To-C-On-Facebook?art_pos=9\n",
"If you'd like to understand how all of these different programming languages can be used for server-side scripting, read up on CGI.\n"
] |
[
10,
5,
4,
3
] |
[] |
[] |
[
"c",
"c++",
"perl",
"python"
] |
stackoverflow_0001991065_c_c++_perl_python.txt
|
Q:
In Python, what does dict.pop(a,b) mean?
class a(object):
data={'a':'aaa','b':'bbb','c':'ccc'}
def pop(self, key, *args):
return self.data.pop(key, *args)#what is this mean.
b=a()
print b.pop('a',{'b':'bbb'})
print b.data
self.data.pop(key, *args) ←------ why is there a second argument?
A:
The pop method of dicts (like self.data, i.e. {'a':'aaa','b':'bbb','c':'ccc'}, here) takes two arguments -- see the docs
The second argument, default, is what pop returns if the first argument, key, is absent.
(If you call pop with just one argument, key, it raises an exception if that key's absent).
In your example, print b.pop('a',{'b':'bbb'}), this is irrelevant because 'a' is a key in b.data. But if you repeat that line...:
b=a()
print b.pop('a',{'b':'bbb'})
print b.pop('a',{'b':'bbb'})
print b.data
you'll see it makes a difference: the first pop removes the 'a' key, so in the second pop the default argument is actually returned (since 'a' is now absent from b.data).
A:
So many questions here. I see at least two, maybe three:
What does pop(a,b) do?/Why are there a second argument?
What is *args being used for?
The first question is trivially answered in the Python Standard Library reference:
pop(key[, default])
If key is in the dictionary, remove it and return its value, else return default.
If default is not given and key is not in the dictionary, a KeyError is raised.
The second question is covered in the Python Language Reference:
If the form “*identifier” is present,
it is initialized to a tuple receiving
any excess positional parameters,
defaulting to the empty tuple. If the
form “**identifier” is present, it is
initialized to a new dictionary
receiving any excess keyword
arguments, defaulting to a new empty
dictionary.
In other words, the pop function takes at least two arguments. The first two get assigned the names self and key; and the rest are stuffed into a tuple called args.
What's happening on the next line when *args is passed along in the call to self.data.pop is the inverse of this - the tuple *args is expanded to of positional parameters which get passed along. This is explained in the Python Language Reference:
If the syntax *expression appears in
the function call, expression must
evaluate to a sequence. Elements from
this sequence are treated as if they
were additional positional arguments
In short, a.pop() wants to be flexible and accept any number of positional parameters, so that it can pass this unknown number of positional parameters on to self.data.pop().
This gives you flexibility; data happens to be a dict right now, and so self.data.pop() takes either one or two parameters; but if you changed data to be a type which took 19 parameters for a call to self.data.pop() you wouldn't have to change class a at all. You'd still have to change any code that called a.pop() to pass the required 19 parameters though.
A:
def func(*args):
pass
When you define a function this way, *args will be array of arguments passed to the function. This allows your function to work without knowing ahead of time how many arguments are going to be passed to it.
You do this with keyword arguments too, using **kwargs:
def func2(**kwargs):
pass
See: Arbitrary argument lists
In your case, you've defined a class which is acting like a dictionary. The dict.pop method is defined as pop(key[, default]).
Your method doesn't use the default parameter. But, by defining your method with *args and passing *args to dict.pop(), you are allowing the caller to use the default parameter.
In other words, you should be able to use your class's pop method like dict.pop:
my_a = a()
value1 = my_a.pop('key1') # throw an exception if key1 isn't in the dict
value2 = my_a.pop('key2', None) # return None if key2 isn't in the dict
A:
>>> def func(a, *args, **kwargs):
... print 'a %s, args %s, kwargs %s' % (a, args, kwargs)
...
>>> func('one', 'two', 'three', four='four', five='five')
a one, args ('two', 'three'), kwargs {'four': 'four', 'five': 'five'}
>>> def anotherfunct(beta, *args):
... print 'beta %s, args %s' % (beta, args)
...
>>> def func(a, *args, **kwargs):
... anotherfunct(a, *args)
...
>>> func('one', 'two', 'three', four='four', five='five')
beta one, args ('two', 'three')
>>>
|
In Python, what does dict.pop(a,b) mean?
|
class a(object):
data={'a':'aaa','b':'bbb','c':'ccc'}
def pop(self, key, *args):
return self.data.pop(key, *args)#what is this mean.
b=a()
print b.pop('a',{'b':'bbb'})
print b.data
self.data.pop(key, *args) ←------ why is there a second argument?
|
[
"The pop method of dicts (like self.data, i.e. {'a':'aaa','b':'bbb','c':'ccc'}, here) takes two arguments -- see the docs\nThe second argument, default, is what pop returns if the first argument, key, is absent.\n(If you call pop with just one argument, key, it raises an exception if that key's absent).\nIn your example, print b.pop('a',{'b':'bbb'}), this is irrelevant because 'a' is a key in b.data. But if you repeat that line...:\nb=a()\nprint b.pop('a',{'b':'bbb'})\nprint b.pop('a',{'b':'bbb'})\nprint b.data\n\nyou'll see it makes a difference: the first pop removes the 'a' key, so in the second pop the default argument is actually returned (since 'a' is now absent from b.data).\n",
"So many questions here. I see at least two, maybe three:\n\nWhat does pop(a,b) do?/Why are there a second argument?\nWhat is *args being used for?\n\n\nThe first question is trivially answered in the Python Standard Library reference:\n\npop(key[, default])\nIf key is in the dictionary, remove it and return its value, else return default.\n If default is not given and key is not in the dictionary, a KeyError is raised.\n\n\nThe second question is covered in the Python Language Reference:\n\nIf the form “*identifier” is present,\n it is initialized to a tuple receiving\n any excess positional parameters,\n defaulting to the empty tuple. If the\n form “**identifier” is present, it is\n initialized to a new dictionary\n receiving any excess keyword\n arguments, defaulting to a new empty\n dictionary.\n\nIn other words, the pop function takes at least two arguments. The first two get assigned the names self and key; and the rest are stuffed into a tuple called args.\nWhat's happening on the next line when *args is passed along in the call to self.data.pop is the inverse of this - the tuple *args is expanded to of positional parameters which get passed along. This is explained in the Python Language Reference:\n\nIf the syntax *expression appears in\n the function call, expression must\n evaluate to a sequence. Elements from\n this sequence are treated as if they\n were additional positional arguments\n\nIn short, a.pop() wants to be flexible and accept any number of positional parameters, so that it can pass this unknown number of positional parameters on to self.data.pop().\nThis gives you flexibility; data happens to be a dict right now, and so self.data.pop() takes either one or two parameters; but if you changed data to be a type which took 19 parameters for a call to self.data.pop() you wouldn't have to change class a at all. You'd still have to change any code that called a.pop() to pass the required 19 parameters though.\n",
"def func(*args): \n pass\n\nWhen you define a function this way, *args will be array of arguments passed to the function. This allows your function to work without knowing ahead of time how many arguments are going to be passed to it. \nYou do this with keyword arguments too, using **kwargs:\ndef func2(**kwargs): \n pass\n\nSee: Arbitrary argument lists\n\nIn your case, you've defined a class which is acting like a dictionary. The dict.pop method is defined as pop(key[, default]). \nYour method doesn't use the default parameter. But, by defining your method with *args and passing *args to dict.pop(), you are allowing the caller to use the default parameter.\nIn other words, you should be able to use your class's pop method like dict.pop: \nmy_a = a()\nvalue1 = my_a.pop('key1') # throw an exception if key1 isn't in the dict\nvalue2 = my_a.pop('key2', None) # return None if key2 isn't in the dict\n\n",
">>> def func(a, *args, **kwargs):\n... print 'a %s, args %s, kwargs %s' % (a, args, kwargs)\n... \n>>> func('one', 'two', 'three', four='four', five='five')\na one, args ('two', 'three'), kwargs {'four': 'four', 'five': 'five'}\n\n\n>>> def anotherfunct(beta, *args):\n... print 'beta %s, args %s' % (beta, args)\n... \n>>> def func(a, *args, **kwargs):\n... anotherfunct(a, *args)\n... \n>>> func('one', 'two', 'three', four='four', five='five')\nbeta one, args ('two', 'three')\n>>> \n\n"
] |
[
127,
28,
7,
7
] |
[] |
[] |
[
"dictionary",
"python"
] |
stackoverflow_0001990802_dictionary_python.txt
|
Q:
A Python script I've written for correcting table names of the SQL dumps from Windows. Any comments?
as a newbie in Python I've thought about writing a quick and dirty script for correcting the table anme caps of a MySQL dump file (by phpMyAdmin).
The idea is since the correct capitalization of the table names are in the comments, I'm going to use it.
e.g.:
-- --------------------------------------------------------
--
-- Table structure for table `Address`
--
The reason I'm asking here is that I don't have a mentor on Python programming and I was hoping you guys could steer me to the right direction. It feels like there's a lot of stuff I'm doing wrong (maybe it's not pythonic) I'd really appreciate your help, thanks in advance!
Here's what I've written (and it works):
#!/usr/bin/env python
import re
filename = 'dump.sql'
def get_text_blocks(filename):
text_blocks = []
text_block = ''
separator = '-- -+'
for line in open(filename, 'r'):
text_block += line
if re.match(separator, line):
if text_block:
text_blocks.append(text_block)
text_block = ''
return text_blocks
def fix_text_blocks(text_blocks):
f = open(filename + '-fixed', 'w')
for block in text_blocks:
table_pattern = re.compile(r'Table structure for table `(.+)`')
correct_table_name = table_pattern.search(block)
if correct_table_name:
replacement = 'CREATE TABLE IF NOT EXISTS `' + correct_table_name.groups(0)[0] + '`'
block = re.sub(r'CREATE TABLE IF NOT EXISTS `(.+)`', replacement, block)
f.write(block)
if __name__ == '__main__':
fix_text_blocks(get_text_blocks(filename))
A:
Looks fairly good, so the following are relatively minor:
get_text_blocks basically splits the entire text by the separator, correct? If so, I think this can be done with a single regex with a re.MULTILINE flag. Something like r'(.*?)\n-- -+' (warning: untested).
If you don't want to use a single regex but prefer to parse the file in a loop, you can ditch the regex for str.straswith. You should also not concatenate strings the way you do with text_block, since every concatenation creates a new string. You can use either the StringIO class, or have a list of lines, and then join them with '\n'.join.
The nested 'if' can be dropped: use the 'and' operator instead.
In any case, working with files (and other objects which have a 'finally' logic) is now done with the 'with [object] as [name]:' clause. Look it up, it's nifty.
If you don't do that - always close your files when you finish working with them, preferably in a 'finally' clause.
I prefer opening files with the 'b' flag as well. Prevents '\r\n' magic in Windows.
In fix_text_blocks, the pattern should be compiled outside the for loop.
|
A Python script I've written for correcting table names of the SQL dumps from Windows. Any comments?
|
as a newbie in Python I've thought about writing a quick and dirty script for correcting the table anme caps of a MySQL dump file (by phpMyAdmin).
The idea is since the correct capitalization of the table names are in the comments, I'm going to use it.
e.g.:
-- --------------------------------------------------------
--
-- Table structure for table `Address`
--
The reason I'm asking here is that I don't have a mentor on Python programming and I was hoping you guys could steer me to the right direction. It feels like there's a lot of stuff I'm doing wrong (maybe it's not pythonic) I'd really appreciate your help, thanks in advance!
Here's what I've written (and it works):
#!/usr/bin/env python
import re
filename = 'dump.sql'
def get_text_blocks(filename):
text_blocks = []
text_block = ''
separator = '-- -+'
for line in open(filename, 'r'):
text_block += line
if re.match(separator, line):
if text_block:
text_blocks.append(text_block)
text_block = ''
return text_blocks
def fix_text_blocks(text_blocks):
f = open(filename + '-fixed', 'w')
for block in text_blocks:
table_pattern = re.compile(r'Table structure for table `(.+)`')
correct_table_name = table_pattern.search(block)
if correct_table_name:
replacement = 'CREATE TABLE IF NOT EXISTS `' + correct_table_name.groups(0)[0] + '`'
block = re.sub(r'CREATE TABLE IF NOT EXISTS `(.+)`', replacement, block)
f.write(block)
if __name__ == '__main__':
fix_text_blocks(get_text_blocks(filename))
|
[
"Looks fairly good, so the following are relatively minor:\n\nget_text_blocks basically splits the entire text by the separator, correct? If so, I think this can be done with a single regex with a re.MULTILINE flag. Something like r'(.*?)\\n-- -+' (warning: untested).\nIf you don't want to use a single regex but prefer to parse the file in a loop, you can ditch the regex for str.straswith. You should also not concatenate strings the way you do with text_block, since every concatenation creates a new string. You can use either the StringIO class, or have a list of lines, and then join them with '\\n'.join.\nThe nested 'if' can be dropped: use the 'and' operator instead.\nIn any case, working with files (and other objects which have a 'finally' logic) is now done with the 'with [object] as [name]:' clause. Look it up, it's nifty.\nIf you don't do that - always close your files when you finish working with them, preferably in a 'finally' clause.\nI prefer opening files with the 'b' flag as well. Prevents '\\r\\n' magic in Windows.\nIn fix_text_blocks, the pattern should be compiled outside the for loop.\n\n"
] |
[
1
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001991117_python.txt
|
Q:
Remove html formatting ">" from text file using Python csv.reader
I have a text file with ; used as the delimiter. The problem is that it has some html text formatting in it such as > Obviously the ; in this causes problems.
The text file is large and I don't have a list of these html strings, that is there are many different examples such as $amp;. How can I remove all of them using python.
The file is a list of names, addresses, phone number and a few more fields. I am looking for the crap.html.remove(textfile) module
A:
The quickest way is probably to use the undocumented but so far stable unescape method in HTMLParser:
import HTMLParser
s= HTMLParser.HTMLParser().unescape(s)
Note this will necessarily output a Unicode string, so if you have any non-ASCII bytes in there you will need to s.decode(encoding) first.
A:
Take a look at the code from here:
import re, htmlentitydefs
##
# Removes HTML or XML character references and entities from a text string.
#
# @param text The HTML (or XML) source text.
# @return The plain text, as a Unicode string, if necessary.
def unescape(text):
def fixup(m):
text = m.group(0)
if text[:2] == "&#":
# character reference
try:
if text[:3] == "&#x":
return unichr(int(text[3:-1], 16))
else:
return unichr(int(text[2:-1]))
except (ValueError, OverflowError):
pass
else:
# named entity
try:
text = unichr(htmlentitydefs.name2codepoint[text[1:-1]])
except KeyError:
pass
return text # leave as is
return re.sub("&#?\w+;", fixup, text)
Of course, this only takes care of HTML entities. You may have other semicolons in the text that mess with your CSV parser. But I guess you already know that...
UPDATE: added catch for possible OverflowError.
A:
On most Unix systems (including your Mac OS X), you can recode the input text file with:
recode html.. file_with_html.txt
This replaces > by ">", etc.
You can call this through Python's subprocess module, for instance.
|
Remove html formatting ">" from text file using Python csv.reader
|
I have a text file with ; used as the delimiter. The problem is that it has some html text formatting in it such as > Obviously the ; in this causes problems.
The text file is large and I don't have a list of these html strings, that is there are many different examples such as $amp;. How can I remove all of them using python.
The file is a list of names, addresses, phone number and a few more fields. I am looking for the crap.html.remove(textfile) module
|
[
"The quickest way is probably to use the undocumented but so far stable unescape method in HTMLParser:\nimport HTMLParser\ns= HTMLParser.HTMLParser().unescape(s)\n\nNote this will necessarily output a Unicode string, so if you have any non-ASCII bytes in there you will need to s.decode(encoding) first.\n",
"Take a look at the code from here:\nimport re, htmlentitydefs\n\n##\n# Removes HTML or XML character references and entities from a text string.\n#\n# @param text The HTML (or XML) source text.\n# @return The plain text, as a Unicode string, if necessary.\n\ndef unescape(text):\n def fixup(m):\n text = m.group(0)\n if text[:2] == \"&#\":\n # character reference\n try:\n if text[:3] == \"&#x\":\n return unichr(int(text[3:-1], 16))\n else:\n return unichr(int(text[2:-1]))\n except (ValueError, OverflowError):\n pass\n else:\n # named entity\n try:\n text = unichr(htmlentitydefs.name2codepoint[text[1:-1]])\n except KeyError:\n pass\n return text # leave as is\n return re.sub(\"&#?\\w+;\", fixup, text)\n\nOf course, this only takes care of HTML entities. You may have other semicolons in the text that mess with your CSV parser. But I guess you already know that...\nUPDATE: added catch for possible OverflowError.\n",
"On most Unix systems (including your Mac OS X), you can recode the input text file with:\nrecode html.. file_with_html.txt\n\nThis replaces > by \">\", etc.\nYou can call this through Python's subprocess module, for instance.\n"
] |
[
6,
3,
1
] |
[] |
[] |
[
"csv",
"file",
"html",
"python",
"regex"
] |
stackoverflow_0001637253_csv_file_html_python_regex.txt
|
Q:
How does Django + mod_wsgi affect the python path?
I have a simple setup with my python libraries in /domains/somedomain.com/libs/ and all my tests run fine. I start WSGI with DJANGO_SETTINGS_MODULE to "somedomain.settings" where somedomain is a package in libs/
Suddenly, when adding pywapi.py into libs/ I can't import it when hitting the site. But, if I add 'import pywapi' to my wsgi script, it fails when hit by Apache, but succeeds if I just write it. the WSGI itself is actually adding libs/ to the path, so I know it should be there when running. The path is absolute, too, so any change in CWD shouldn't be causing this.
I can't think of anything else and I've been tinkering with it half of my otherwise productive morning.
A:
I think the problem is related with the permissions of that file. Check that the user running wsgi (apache user, usually) is capable of reading and writing the everything in the libs folder and specially capable of reading the file pywapi.py.
|
How does Django + mod_wsgi affect the python path?
|
I have a simple setup with my python libraries in /domains/somedomain.com/libs/ and all my tests run fine. I start WSGI with DJANGO_SETTINGS_MODULE to "somedomain.settings" where somedomain is a package in libs/
Suddenly, when adding pywapi.py into libs/ I can't import it when hitting the site. But, if I add 'import pywapi' to my wsgi script, it fails when hit by Apache, but succeeds if I just write it. the WSGI itself is actually adding libs/ to the path, so I know it should be there when running. The path is absolute, too, so any change in CWD shouldn't be causing this.
I can't think of anything else and I've been tinkering with it half of my otherwise productive morning.
|
[
"I think the problem is related with the permissions of that file. Check that the user running wsgi (apache user, usually) is capable of reading and writing the everything in the libs folder and specially capable of reading the file pywapi.py.\n"
] |
[
2
] |
[] |
[] |
[
"apache",
"django",
"mod_wsgi",
"python"
] |
stackoverflow_0001991743_apache_django_mod_wsgi_python.txt
|
Q:
Parse xml file while a tag is missing
I try to parse an xml file. The text which is in tags is parsed successfully (or it seems so) but I want to output as the text which is not contained in some tags and the following program just ignores it.
from xml.etree.ElementTree import XMLTreeBuilder
class HtmlLatex: # The target object of the parser
out = ''
var = ''
def start(self, tag, attrib): # Called for each opening tag.
pass
def end(self, tag): # Called for each closing tag.
if tag == 'i':
self.out += self.var
elif tag == 'sub':
self.out += '_{' + self.var + '}'
elif tag == 'sup':
self.out += '^{' + self.var + '}'
else:
self.out += self.var
def data(self, data):
self.var = data
def close(self):
print(self.out)
if __name__ == '__main__':
target = HtmlLatex()
parser = XMLTreeBuilder(target=target)
text = ''
with open('input.txt') as f1:
text = f1.read()
print(text)
parser.feed(text)
parser.close()
A part of the input I want to parse:
<p><i>p</i><sub>0</sub> = (<i>m</i><sup>3</sup>+(2<i>l</i><sub>2</sub>+<i>l</i><sub>1</sub>) <i>m</i><sup>2</sup>+(<i>l</i><sub>2</sub><sup>2</sup>+2<i>l</i><sub>1</sub> <i>l</i><sub>2</sub>+<i>l</i><sub>1</sub><sup>2</sup>) <i>m</i>) /(<i>m</i><sup>3</sup>+(3<i>l</i><sub>2</sub>+2<i>l</i><sub>1</sub>) ) }.</p>
A:
Have a look at BeautifulSoup, a python library for parsing, navigating and manipulating html and xml. It has a handy interface and might solve your problem ...
A:
Here's a pyparsing version - I hope the comments are sufficiently explanatory.
src = """<p><i>p</i><sub>0</sub> = (<i>m</i><sup>3</sup>+(2<i>l</i><sub>2</sub>+<i>l</i><sub>1</sub>) """ \
"""<i>m</i><sup>2</sup>+(<i>l</i><sub>2</sub><sup>2</sup>+2<i>l</i><sub>1</sub> <i>l</i><sub>2</sub>+""" \
"""<i>l</i><sub>1</sub><sup>2</sup>) <i>m</i>) /(<i>m</i><sup>3</sup>+(3<i>l</i><sub>2</sub>+""" \
"""2<i>l</i><sub>1</sub>) ) }.</p>"""
from pyparsing import makeHTMLTags, anyOpenTag, anyCloseTag, Suppress, replaceWith
# set up tag matching for <sub> and <sup> tags
SUB,endSUB = makeHTMLTags("sub")
SUP,endSUP = makeHTMLTags("sup")
# all other tags will be suppressed from the output
ANY,endANY = map(Suppress,(anyOpenTag,anyCloseTag))
SUB.setParseAction(replaceWith("_{"))
SUP.setParseAction(replaceWith("^{"))
endSUB.setParseAction(replaceWith("}"))
endSUP.setParseAction(replaceWith("}"))
transformer = (SUB | endSUB | SUP | endSUP | ANY | endANY)
# now use the transformer to apply these transforms to the input string
print transformer.transformString(src)
Gives
p_{0} = (m^{3}+(2l_{2}+l_{1}) m^{2}+(l_{2}^{2}+2l_{1} l_{2}+l_{1}^{2}) m) /(m^{3}+(3l_{2}+2l_{1}) ) }.
|
Parse xml file while a tag is missing
|
I try to parse an xml file. The text which is in tags is parsed successfully (or it seems so) but I want to output as the text which is not contained in some tags and the following program just ignores it.
from xml.etree.ElementTree import XMLTreeBuilder
class HtmlLatex: # The target object of the parser
out = ''
var = ''
def start(self, tag, attrib): # Called for each opening tag.
pass
def end(self, tag): # Called for each closing tag.
if tag == 'i':
self.out += self.var
elif tag == 'sub':
self.out += '_{' + self.var + '}'
elif tag == 'sup':
self.out += '^{' + self.var + '}'
else:
self.out += self.var
def data(self, data):
self.var = data
def close(self):
print(self.out)
if __name__ == '__main__':
target = HtmlLatex()
parser = XMLTreeBuilder(target=target)
text = ''
with open('input.txt') as f1:
text = f1.read()
print(text)
parser.feed(text)
parser.close()
A part of the input I want to parse:
<p><i>p</i><sub>0</sub> = (<i>m</i><sup>3</sup>+(2<i>l</i><sub>2</sub>+<i>l</i><sub>1</sub>) <i>m</i><sup>2</sup>+(<i>l</i><sub>2</sub><sup>2</sup>+2<i>l</i><sub>1</sub> <i>l</i><sub>2</sub>+<i>l</i><sub>1</sub><sup>2</sup>) <i>m</i>) /(<i>m</i><sup>3</sup>+(3<i>l</i><sub>2</sub>+2<i>l</i><sub>1</sub>) ) }.</p>
|
[
"Have a look at BeautifulSoup, a python library for parsing, navigating and manipulating html and xml. It has a handy interface and might solve your problem ...\n",
"Here's a pyparsing version - I hope the comments are sufficiently explanatory.\nsrc = \"\"\"<p><i>p</i><sub>0</sub> = (<i>m</i><sup>3</sup>+(2<i>l</i><sub>2</sub>+<i>l</i><sub>1</sub>) \"\"\" \\\n \"\"\"<i>m</i><sup>2</sup>+(<i>l</i><sub>2</sub><sup>2</sup>+2<i>l</i><sub>1</sub> <i>l</i><sub>2</sub>+\"\"\" \\\n \"\"\"<i>l</i><sub>1</sub><sup>2</sup>) <i>m</i>) /(<i>m</i><sup>3</sup>+(3<i>l</i><sub>2</sub>+\"\"\" \\\n \"\"\"2<i>l</i><sub>1</sub>) ) }.</p>\"\"\"\n\nfrom pyparsing import makeHTMLTags, anyOpenTag, anyCloseTag, Suppress, replaceWith\n\n# set up tag matching for <sub> and <sup> tags\nSUB,endSUB = makeHTMLTags(\"sub\")\nSUP,endSUP = makeHTMLTags(\"sup\")\n\n# all other tags will be suppressed from the output\nANY,endANY = map(Suppress,(anyOpenTag,anyCloseTag))\n\nSUB.setParseAction(replaceWith(\"_{\"))\nSUP.setParseAction(replaceWith(\"^{\"))\nendSUB.setParseAction(replaceWith(\"}\"))\nendSUP.setParseAction(replaceWith(\"}\"))\n\ntransformer = (SUB | endSUB | SUP | endSUP | ANY | endANY)\n\n# now use the transformer to apply these transforms to the input string\nprint transformer.transformString(src)\n\nGives\np_{0} = (m^{3}+(2l_{2}+l_{1}) m^{2}+(l_{2}^{2}+2l_{1} l_{2}+l_{1}^{2}) m) /(m^{3}+(3l_{2}+2l_{1}) ) }.\n\n"
] |
[
3,
2
] |
[] |
[] |
[
"html",
"parsing",
"python",
"xml"
] |
stackoverflow_0001991840_html_parsing_python_xml.txt
|
Q:
File writing does not happen when it is supposed to happen in the program flow
This is not a new problem for me. From C to PERL to Python on Windows Mobile, Windows XP and other Windows versions this problem persists and f**ks my nerves.
Now in my latest script it again happens.
To be more concrete: I have coded in Python a trivial script. Now the script writes correctly to the file when run from the debugger, but out of the debugger it does not work correctly.
It does not write to file when it should.
I am using python 2.6 with eclipse and pydev.
This is the code
import httplib2
import thread
ht = httplib2.Http();
list = []
k = 0
def check(proxy, port):
global list
global k
try:
head = ht.request(proxy, 'HEAD')
except:
return
k = k + 1
list.append(proxy)
list.append(port)
def OnListCaller(ProxyList, OutFile, NListLen):
global list
global k
filei = open(ProxyList, 'r')
fileo = open(OutFile, 'a')
while 1:
proxy = filei.readline()
if not proxy: continue
port = filei.readline()
proxy = proxy.rstrip()
port = port.rstrip()
thread.start_new(check, (proxy, port,))
if k >= NListLen:
for t in list:
fileo.write(t + "\n")
list = []
fileo.close()
fileo = open(OutFile, 'a')
k = 0
OnListCaller('C:\proxy\input.txt', 'C:\proxy\checked.txt', 1)
The problem is in the OnListCaller at the if k>=NListLen.
The file should be updated when k is >= then a given value.
Thanks to everyone.
A:
Remember what your mom taught you:
always flush()
(in python, file_object.flush() followed by os.fsync(file_object.fileno()))
A:
Regarding the code:
It looks like the actual problem is one relating to threads, not to files:
Whilst you are executing this code:
for t in list:
fileo.write(t + "\n")
list = []
fileo.close()
fileo = open(OutFile, 'a')
k = 0
list is being modified by the threads you have spawned. I don't know the details of how 'for x in y' works with threads, but I imagine it is missing out the elements added to the list after the body for loop has been executed the first time.
To solve this you need a mutex for list which you lock for the entirety of this for loop (until you have cleared the list), and which you lock whenever you are adding an item to the list.
A:
import httplib2
import thread
import os
import sys
ht = httplib2.Http();
def check(proxy, port, OutFile):
global list
try:
head = ht.request(proxy, 'HEAD')
except:
return
fileo = open(OutFile, 'a')
fileo.write(proxy+"\n")
fileo.write(port+"\n")
sys.stdout.flush()
os.fsync(fileo.fileno())
fileo.close()
def OnListCaller(ProxyList, OutFile, NListLen):
global list
filei = open(ProxyList, 'r')
while 1:
proxy = filei.readline()
if not proxy: continue
port = filei.readline()
proxy = proxy.rstrip()
port = port.rstrip()
#TODO: regleaza pentru unix cand o sa fie nevoie
thread.start_new(check, (proxy, port, OutFile,))
OnListCaller('C:\proxy\input.txt', 'C:\proxy\checked.txt', 1)
This is the fixed code.
A:
If you have opened the file with a file handle in Python, remember to close it when finished.
eg
f=open("file")
....
f.write(....)
f.close()
A:
Obviously, you forget to close the file upon finishing working with it. If you want to check the contents of the file before closing it, call the flush() method. Example:
file = open("hello.txt", "a")
file.write(...)
file.flush() // force write on the disk
file.close() // finished using the file, close it
Check you code, not all open files are closed in it.
|
File writing does not happen when it is supposed to happen in the program flow
|
This is not a new problem for me. From C to PERL to Python on Windows Mobile, Windows XP and other Windows versions this problem persists and f**ks my nerves.
Now in my latest script it again happens.
To be more concrete: I have coded in Python a trivial script. Now the script writes correctly to the file when run from the debugger, but out of the debugger it does not work correctly.
It does not write to file when it should.
I am using python 2.6 with eclipse and pydev.
This is the code
import httplib2
import thread
ht = httplib2.Http();
list = []
k = 0
def check(proxy, port):
global list
global k
try:
head = ht.request(proxy, 'HEAD')
except:
return
k = k + 1
list.append(proxy)
list.append(port)
def OnListCaller(ProxyList, OutFile, NListLen):
global list
global k
filei = open(ProxyList, 'r')
fileo = open(OutFile, 'a')
while 1:
proxy = filei.readline()
if not proxy: continue
port = filei.readline()
proxy = proxy.rstrip()
port = port.rstrip()
thread.start_new(check, (proxy, port,))
if k >= NListLen:
for t in list:
fileo.write(t + "\n")
list = []
fileo.close()
fileo = open(OutFile, 'a')
k = 0
OnListCaller('C:\proxy\input.txt', 'C:\proxy\checked.txt', 1)
The problem is in the OnListCaller at the if k>=NListLen.
The file should be updated when k is >= then a given value.
Thanks to everyone.
|
[
"Remember what your mom taught you:\nalways flush()\n(in python, file_object.flush() followed by os.fsync(file_object.fileno()))\n",
"Regarding the code:\nIt looks like the actual problem is one relating to threads, not to files:\nWhilst you are executing this code:\n for t in list:\n fileo.write(t + \"\\n\")\n list = []\n fileo.close()\n fileo = open(OutFile, 'a')\n k = 0\n\nlist is being modified by the threads you have spawned. I don't know the details of how 'for x in y' works with threads, but I imagine it is missing out the elements added to the list after the body for loop has been executed the first time.\nTo solve this you need a mutex for list which you lock for the entirety of this for loop (until you have cleared the list), and which you lock whenever you are adding an item to the list.\n",
"\nimport httplib2\nimport thread\nimport os\nimport sys\nht = httplib2.Http();\ndef check(proxy, port, OutFile):\n global list\n try:\n head = ht.request(proxy, 'HEAD')\n except:\n return\n fileo = open(OutFile, 'a')\n fileo.write(proxy+\"\\n\")\n fileo.write(port+\"\\n\")\n sys.stdout.flush()\n os.fsync(fileo.fileno())\n fileo.close()\ndef OnListCaller(ProxyList, OutFile, NListLen):\n global list\n filei = open(ProxyList, 'r') \n while 1:\n proxy = filei.readline()\n if not proxy: continue\n port = filei.readline()\n proxy = proxy.rstrip()\n port = port.rstrip()\n\n #TODO: regleaza pentru unix cand o sa fie nevoie\n\n thread.start_new(check, (proxy, port, OutFile,))\n\nOnListCaller('C:\\proxy\\input.txt', 'C:\\proxy\\checked.txt', 1)\n\nThis is the fixed code.\n",
"If you have opened the file with a file handle in Python, remember to close it when finished.\neg\nf=open(\"file\")\n....\nf.write(....)\nf.close()\n\n",
"Obviously, you forget to close the file upon finishing working with it. If you want to check the contents of the file before closing it, call the flush() method. Example:\nfile = open(\"hello.txt\", \"a\")\nfile.write(...)\nfile.flush() // force write on the disk\nfile.close() // finished using the file, close it\n\nCheck you code, not all open files are closed in it.\n"
] |
[
8,
2,
1,
0,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001991815_python.txt
|
Q:
python import module to work globally
I've got a problem trying to get python to accept an import 'globally'
In a module it needs to import another module depending on another variable but it doesn't seem to import it into all of the module functions if i have it in the start function; for example:
def start():
selected = "web"
exec("from gui import " + selected + " as ui")
log("going to start gui " + selected)
ui.start()
this works but in the same module:
def close():
ui.stop()
doesn't work. i don't know what's going on here
Joe
A:
import gui
ui = None
def start():
selected = "web"
log("going to start gui " + selected)
global ui
__import__("gui.%s" % selected) # if you're importing a submodule that
# may not have been imported yet
ui = getattr(gui, selected)
ui.start()
A:
Why do you want to do it this way? Why not use the __import__ builtin? Also, your binding to gui is local to the function start.
A:
You can provide scope of exec with in. Try this:
exec("from gui import " + selected + " as ui") in globals()
A:
You are importing the ui module to the start() function scope only. You should import the module to global scope. To do this you could import the module before the two functions (start and close) or provide global scope to exec() function.
Example: To provide global scope to the exec method.
exec("from gui import " + selected + " as ui") in globals()
|
python import module to work globally
|
I've got a problem trying to get python to accept an import 'globally'
In a module it needs to import another module depending on another variable but it doesn't seem to import it into all of the module functions if i have it in the start function; for example:
def start():
selected = "web"
exec("from gui import " + selected + " as ui")
log("going to start gui " + selected)
ui.start()
this works but in the same module:
def close():
ui.stop()
doesn't work. i don't know what's going on here
Joe
|
[
"import gui\nui = None\n\ndef start():\n selected = \"web\"\n log(\"going to start gui \" + selected)\n global ui\n __import__(\"gui.%s\" % selected) # if you're importing a submodule that\n # may not have been imported yet\n ui = getattr(gui, selected)\n ui.start()\n\n",
"Why do you want to do it this way? Why not use the __import__ builtin? Also, your binding to gui is local to the function start.\n",
"You can provide scope of exec with in. Try this:\nexec(\"from gui import \" + selected + \" as ui\") in globals()\n\n",
"You are importing the ui module to the start() function scope only. You should import the module to global scope. To do this you could import the module before the two functions (start and close) or provide global scope to exec() function.\nExample: To provide global scope to the exec method.\nexec(\"from gui import \" + selected + \" as ui\") in globals()\n\n"
] |
[
8,
2,
0,
0
] |
[] |
[] |
[
"import",
"module",
"python"
] |
stackoverflow_0001991784_import_module_python.txt
|
Q:
Sorting problem with the Google App Engine
I am using the following class to store some data:
class NewsArticle(db.Model):
score = db.FloatProperty(default=0.0)
date_scored = db.DateTimeProperty()
...
What I need to do is to get those NewsArticle entities that have the top score in some time frame (e.g. get the top scored data entities of today or of last week).
I tried the following:
query = db.GqlQuery('SELECT * FROM NewsArticle WHERE date_created > DATETIME(:year, :month, :day, 0, 0, 0) ORDER BY score DESC', year=date.selected_year, month=date.selected_month, day=date.selected_day)
But that doesn't work since the datastore requires that the
first ordering property must be the
same as inequality filter property
I thought about getting all NewsArticle entities for a specific timeframe and then doing the score-sorting in my application, but I am expecting a really large number of results so in-memory-sorting won't be efficient.
What other solutions are possible for my problem?
A:
You could either:
filter only by the timeframe and sort by score in memory or,
if you can limit the timeframes to whole days and weeks, include additional properties in your model to save the the week as a integer and the day as a DateProperty and do a simple equality check on that.
EDIT: To learn more, have a look at Restrictions on Queries
A:
I am expecting a really large number
of results so in-memory-sorting won't
be efficient.
You can get at most 1000 results from a query, so sorting them every which way will be extremely efficient -- e.g., consider, on my Macbook Air (first-day, slowest model):
$ python -mtimeit -s'import random; x=range(1000); random.shuffle(x)' 'y=sorted(x)'
1000 loops, best of 3: 714 usec per loop
AppEngine's CPUs are substantially faster than the Air, so 700 microseconds to sort 1000 results would be a very pessimistic estimate; this compares with tens of msec for fetching the data -- so, don't worry at all about sorting: as long as you can fetch the results you want, you'll be just fine.
BTW, to assess likely App Engine performance on a task, see Guido van Rossum's presentation here -- he claims 10-50 msec for a "typical db.get()" (50-100 for put, etc).
If you expect more than 1000 results from a query, that typically means you need to denormalize the table to trim the query's results to under 1000. For example, in your case, say that you expect about 500-700 entries a day -- in which case getting all results for today would be no problem, but a week is definitely a problem: you need to trim the query down to 20% or less of what it would "normally" be.
For example, say your scores are in the range 0-100, about uniformly distributed. In this case, you might add to the entity a boolean field "topcandidate": when you save the entity, you set that field to True iff the score is in the range 85-100 (as you see, this means the table gets denormalized, since the field represents logically redundant information).
When you fetch weekly top results, you add the equality condition to have topcandidate True. Instead of 3500-4900 results, this should get you down to 500-900 -- the top-scoring 15% or so, after which you can sort them in memory and pick, say, the top 100.
Of course the exact numbers depend on the distribution of your score field (more likely to be a bell curve than a flat uniform distribution) and how many "top score candidates" you need, but this is one generally useful approach to work around the 1000-results limit.
A:
Try this:
import datetime
...
query = Data.gql('SELECT * FROM NewsArticle WHERE date_created >= :today ORDER BY score DESC', today=datetime.date.today())
|
Sorting problem with the Google App Engine
|
I am using the following class to store some data:
class NewsArticle(db.Model):
score = db.FloatProperty(default=0.0)
date_scored = db.DateTimeProperty()
...
What I need to do is to get those NewsArticle entities that have the top score in some time frame (e.g. get the top scored data entities of today or of last week).
I tried the following:
query = db.GqlQuery('SELECT * FROM NewsArticle WHERE date_created > DATETIME(:year, :month, :day, 0, 0, 0) ORDER BY score DESC', year=date.selected_year, month=date.selected_month, day=date.selected_day)
But that doesn't work since the datastore requires that the
first ordering property must be the
same as inequality filter property
I thought about getting all NewsArticle entities for a specific timeframe and then doing the score-sorting in my application, but I am expecting a really large number of results so in-memory-sorting won't be efficient.
What other solutions are possible for my problem?
|
[
"You could either:\n\nfilter only by the timeframe and sort by score in memory or, \nif you can limit the timeframes to whole days and weeks, include additional properties in your model to save the the week as a integer and the day as a DateProperty and do a simple equality check on that.\n\nEDIT: To learn more, have a look at Restrictions on Queries\n",
"\nI am expecting a really large number\n of results so in-memory-sorting won't\n be efficient.\n\nYou can get at most 1000 results from a query, so sorting them every which way will be extremely efficient -- e.g., consider, on my Macbook Air (first-day, slowest model):\n$ python -mtimeit -s'import random; x=range(1000); random.shuffle(x)' 'y=sorted(x)'\n1000 loops, best of 3: 714 usec per loop\n\nAppEngine's CPUs are substantially faster than the Air, so 700 microseconds to sort 1000 results would be a very pessimistic estimate; this compares with tens of msec for fetching the data -- so, don't worry at all about sorting: as long as you can fetch the results you want, you'll be just fine.\nBTW, to assess likely App Engine performance on a task, see Guido van Rossum's presentation here -- he claims 10-50 msec for a \"typical db.get()\" (50-100 for put, etc).\nIf you expect more than 1000 results from a query, that typically means you need to denormalize the table to trim the query's results to under 1000. For example, in your case, say that you expect about 500-700 entries a day -- in which case getting all results for today would be no problem, but a week is definitely a problem: you need to trim the query down to 20% or less of what it would \"normally\" be.\nFor example, say your scores are in the range 0-100, about uniformly distributed. In this case, you might add to the entity a boolean field \"topcandidate\": when you save the entity, you set that field to True iff the score is in the range 85-100 (as you see, this means the table gets denormalized, since the field represents logically redundant information).\nWhen you fetch weekly top results, you add the equality condition to have topcandidate True. Instead of 3500-4900 results, this should get you down to 500-900 -- the top-scoring 15% or so, after which you can sort them in memory and pick, say, the top 100.\nOf course the exact numbers depend on the distribution of your score field (more likely to be a bell curve than a flat uniform distribution) and how many \"top score candidates\" you need, but this is one generally useful approach to work around the 1000-results limit.\n",
"Try this:\nimport datetime\n...\nquery = Data.gql('SELECT * FROM NewsArticle WHERE date_created >= :today ORDER BY score DESC', today=datetime.date.today())\n\n"
] |
[
5,
1,
0
] |
[
"I think ordering by multiple properties might work. Simply use the first inequality property as the first ordering property.\nquery = db.GqlQuery('SELECT * FROM NewsArticle WHERE date_created > DATETIME(:year, :month, :day, 0, 0, 0) ORDER BY date_created, score DESC', year=date.selected_year, month=date.selected_month, day=date.selected_day)\n\n"
] |
[
-1
] |
[
"google_app_engine",
"google_cloud_datastore",
"python"
] |
stackoverflow_0001991022_google_app_engine_google_cloud_datastore_python.txt
|
Q:
python appengine form-posted utf8 file issue
i am trying to form-post a sql file that consists on many INSERTS, eg.
INSERT INTO `TABLE` VALUES ('abcdé', 2759);
then i use re.search to parse it and extract the fields to put into my own datastore. The problem is that, although the file contains accented characters (see the e is a é), once uploaded it loses it and either errors or stores a bytestring representation of it.
Heres what i am currently using (and I have tried loads of alternatives):
form = cgi.FieldStorage()
uFile = form['sql']
uSql = uFile.file.read()
lineX = uSql.split("\n") # to get each line
and so on.
has anyone got a robust way of making this work? remember i am on appengine so access to some libraries is restricted/forbidden
A:
You mention utf8 in the Q's title but then never again: what are you doing (in terms of setting headers and checking them) to verify what encoding is in use? There should be headers of the form
Content-Type: text/plain; charset=utf-8
and the charset= part is where the encoding is specified. So what are the values upon sending and receiving this? If charset is erroneous, you may have to manually perform some encoding and decoding. To help us gauge what the encoding seems to be, besides the headers, what's the ord value of that accented-e? E.g., if the encoding was actually iso-8859-1, that ord value would be 233 (in decimal; 0xE9 in hex).
|
python appengine form-posted utf8 file issue
|
i am trying to form-post a sql file that consists on many INSERTS, eg.
INSERT INTO `TABLE` VALUES ('abcdé', 2759);
then i use re.search to parse it and extract the fields to put into my own datastore. The problem is that, although the file contains accented characters (see the e is a é), once uploaded it loses it and either errors or stores a bytestring representation of it.
Heres what i am currently using (and I have tried loads of alternatives):
form = cgi.FieldStorage()
uFile = form['sql']
uSql = uFile.file.read()
lineX = uSql.split("\n") # to get each line
and so on.
has anyone got a robust way of making this work? remember i am on appengine so access to some libraries is restricted/forbidden
|
[
"You mention utf8 in the Q's title but then never again: what are you doing (in terms of setting headers and checking them) to verify what encoding is in use? There should be headers of the form\nContent-Type: text/plain; charset=utf-8\n\nand the charset= part is where the encoding is specified. So what are the values upon sending and receiving this? If charset is erroneous, you may have to manually perform some encoding and decoding. To help us gauge what the encoding seems to be, besides the headers, what's the ord value of that accented-e? E.g., if the encoding was actually iso-8859-1, that ord value would be 233 (in decimal; 0xE9 in hex).\n"
] |
[
1
] |
[] |
[] |
[
"forms",
"google_app_engine",
"python",
"utf_8"
] |
stackoverflow_0001991658_forms_google_app_engine_python_utf_8.txt
|
Q:
How to install mysqlDb for MySQL and Python on Windows
I am a .NET developer trying to install mysqldb for python I keep having this error message
raise improperlyconfigured("error loading mysqldb module: %s" % e)
django.core.exceptions.improperlyconfigured: error loading mysqldb
module: no module named mysqldb>
I am following this instruction from this site
I do not understand these lines
windows .......
c:...> python setup.py install c:...> python setup.py
bdist_wininst
the latter example should build a windows installer package, if you
have the correct tools. in any event, you must have a c compiler.
additionally, you have to set an environment variable (mysqlroot)
which is the path to your mysql installation. in theory, it would be
possible to get this information out of the registry, but like i said,
i don't do windows, but i'll accept a patch that does this.
I have been searching for answer all day please do anybody really know how to do this
or at least point me in the right direction?
And what is the c compiler for?
A:
I have downloaded and installed MySQL from here and it solved my problem.
|
How to install mysqlDb for MySQL and Python on Windows
|
I am a .NET developer trying to install mysqldb for python I keep having this error message
raise improperlyconfigured("error loading mysqldb module: %s" % e)
django.core.exceptions.improperlyconfigured: error loading mysqldb
module: no module named mysqldb>
I am following this instruction from this site
I do not understand these lines
windows .......
c:...> python setup.py install c:...> python setup.py
bdist_wininst
the latter example should build a windows installer package, if you
have the correct tools. in any event, you must have a c compiler.
additionally, you have to set an environment variable (mysqlroot)
which is the path to your mysql installation. in theory, it would be
possible to get this information out of the registry, but like i said,
i don't do windows, but i'll accept a patch that does this.
I have been searching for answer all day please do anybody really know how to do this
or at least point me in the right direction?
And what is the c compiler for?
|
[
"I have downloaded and installed MySQL from here and it solved my problem.\n"
] |
[
19
] |
[] |
[] |
[
"mysql",
"python"
] |
stackoverflow_0001992103_mysql_python.txt
|
Q:
Why does my Python class claim that I have 2 arguments instead of 1?
#! /usr/bin/env python
import os
import stat
import sys
class chkup:
def set(file):
filepermission = os.stat(file)
user_read()
user_write()
user_exec()
def user_read():
"""Return True if 'file' is readable by user
"""
# Extract the permissions bits from the file's (or
# directory's) stat info.
b = bool(filepermission.st_mode & stat.S_IRUSR)
print b
return b
def user_write():
"""Return True if 'file' is readable by user
"""
# Extract the permissions bits from the file's (or
# directory's) stat info.
b = bool(filepermission.st_mode & stat.S_WRUSR)
print b
return b
def user_exec():
"""Return True if 'file' is readable by user
"""
# Extract the permissions bits from the file's (or
# directory's) stat info.
b = bool(filepermission.st_mode & stat.S_IXUSR)
print b
return b
def main():
i = chkup()
place = '/net/home/f08/itsrsw1/ScriptingWork/quotacheck'
i.set(place)
if __name__ == '__main__':
main()
With that code I receive
> Traceback (most recent call last):
File "chkup.py", line 46, in <module>
main()
File "chkup.py", line 43, in main
i.set(place)
TypeError: set() takes exactly 1 argument (2 given)
Any thoughts?
A:
The first argument for a python class method is the self variable. If you call classInstance.method(parameter), the method is invoked as method(self, parameter).
So, when you're defining your class, do something like this:
class MyClass(Object):
def my_method(self, parameter):
print parameter
You might want to read through the Python tutorial.
A:
Because you're not passing the object (generally referred to as self) as the first parameter to your methods. In Python, a call like this:
my_obj.do_something(my_other_obj)
is essentially desugared into a call like this:
MyClass.do_something(my_obj, my_other_obj)
Thus, Python is looking for a method signature like this:
class MyClass(object):
def do_something(self, my_other_obj):
self.my_var = my_other_obj
So you should pass the object (generally called self) as the first parameter to a method.
A:
You need to explicitly pass self variable, which represents an instance of a class, e.g.:
def set(self, file):
filepermission = os.stat(file)
self.user_read()
self.user_write()
self.user_exec()
It doesn't have to be called self but it's a good convention to follow, and your code will be understood by other programmers.
A:
self is an implicit first argument to all class member functions. So the i.set(place) call actually calls set(i, place). You need to take this into account when defining your class, and write def set(self, file) instead.
A:
set() is a method of class chkup. When you call i.set(place), python keeps track of the instance i using the first argument to the method. Generally, every instance method will receive at least one argument, called self, and subsequent arguments follow. You should redefine your class:
class chkup:
def set(self, file):
"etc..."
You might look up "self" and python on stackoverflow:
Python __init__ and self what do they do?
etc.
A:
In a class, you need to take into account the self parameter for method members.
A:
Since you're treating set as a bound (instance) method of a class, you must explicitly receive the instance as your first argument. It's called "self" by convention.
def set(self, file):
filepermission = os.stat(file)
user_read()
user_write()
user_exec()
A:
in order to define a non-static method you must provide "self" as a first argument like this
class chkup:
def set(self,file):
filepermission = os.stat(file)
#this is done to make non static methods,
#the call of set() here done by
chk=chkup()
chk.set(fileName) # note that you dont provide "self" when calling
A:
Thats because python automatically passes the current object as an argument to all the methods in the class,so when you pass 2 arguments to a function,python appends the third argument which is the current object,the method prototype should consider this
|
Why does my Python class claim that I have 2 arguments instead of 1?
|
#! /usr/bin/env python
import os
import stat
import sys
class chkup:
def set(file):
filepermission = os.stat(file)
user_read()
user_write()
user_exec()
def user_read():
"""Return True if 'file' is readable by user
"""
# Extract the permissions bits from the file's (or
# directory's) stat info.
b = bool(filepermission.st_mode & stat.S_IRUSR)
print b
return b
def user_write():
"""Return True if 'file' is readable by user
"""
# Extract the permissions bits from the file's (or
# directory's) stat info.
b = bool(filepermission.st_mode & stat.S_WRUSR)
print b
return b
def user_exec():
"""Return True if 'file' is readable by user
"""
# Extract the permissions bits from the file's (or
# directory's) stat info.
b = bool(filepermission.st_mode & stat.S_IXUSR)
print b
return b
def main():
i = chkup()
place = '/net/home/f08/itsrsw1/ScriptingWork/quotacheck'
i.set(place)
if __name__ == '__main__':
main()
With that code I receive
> Traceback (most recent call last):
File "chkup.py", line 46, in <module>
main()
File "chkup.py", line 43, in main
i.set(place)
TypeError: set() takes exactly 1 argument (2 given)
Any thoughts?
|
[
"The first argument for a python class method is the self variable. If you call classInstance.method(parameter), the method is invoked as method(self, parameter).\nSo, when you're defining your class, do something like this: \nclass MyClass(Object): \n def my_method(self, parameter): \n print parameter\n\nYou might want to read through the Python tutorial.\n",
"Because you're not passing the object (generally referred to as self) as the first parameter to your methods. In Python, a call like this:\nmy_obj.do_something(my_other_obj)\n\nis essentially desugared into a call like this:\nMyClass.do_something(my_obj, my_other_obj)\n\nThus, Python is looking for a method signature like this:\nclass MyClass(object):\n def do_something(self, my_other_obj):\n self.my_var = my_other_obj\n\nSo you should pass the object (generally called self) as the first parameter to a method.\n",
"You need to explicitly pass self variable, which represents an instance of a class, e.g.:\ndef set(self, file):\n filepermission = os.stat(file)\n self.user_read()\n self.user_write()\n self.user_exec()\n\nIt doesn't have to be called self but it's a good convention to follow, and your code will be understood by other programmers.\n",
"self is an implicit first argument to all class member functions. So the i.set(place) call actually calls set(i, place). You need to take this into account when defining your class, and write def set(self, file) instead.\n",
"set() is a method of class chkup. When you call i.set(place), python keeps track of the instance i using the first argument to the method. Generally, every instance method will receive at least one argument, called self, and subsequent arguments follow. You should redefine your class:\nclass chkup:\n def set(self, file):\n \"etc...\"\n\nYou might look up \"self\" and python on stackoverflow:\nPython __init__ and self what do they do?\netc. \n",
"In a class, you need to take into account the self parameter for method members.\n",
"Since you're treating set as a bound (instance) method of a class, you must explicitly receive the instance as your first argument. It's called \"self\" by convention.\ndef set(self, file):\n filepermission = os.stat(file)\n user_read()\n user_write()\n user_exec()\n\n",
"in order to define a non-static method you must provide \"self\" as a first argument like this\nclass chkup:\n def set(self,file):\n filepermission = os.stat(file)\n\n#this is done to make non static methods,\n#the call of set() here done by\nchk=chkup()\nchk.set(fileName) # note that you dont provide \"self\" when calling\n",
"Thats because python automatically passes the current object as an argument to all the methods in the class,so when you pass 2 arguments to a function,python appends the third argument which is the current object,the method prototype should consider this\n"
] |
[
16,
4,
2,
1,
1,
0,
0,
0,
0
] |
[] |
[] |
[
"class_method",
"python"
] |
stackoverflow_0001868685_class_method_python.txt
|
Q:
Python Hierarchical QcomboBox: clean-up list
I have a hierarchical two combo-box. The first combo-box displays a list of customerNames, i.e. different companies from a MySQL db. Each customer has branches in different cities.
Then, when a customer name is chosen from combo-box1 option list, e.g. {Aldi, Meyer, Carrefour, WalMart}, for that particular customer, a list of cities/branches is automatically displayed in the combo-box2. Something like that, e.g.:
combo1: chosen_customer [Aldi] --> cities:{NY, Boston, Berlin, Tokyo, London} then..
combo2: options {NY, Boston, Berlin, Tokyo, London}
The problem comes when we chose again another customer, that eventually has a smaller number of branches - e.g.
combo1: chosen_customer [Meyer] --> {LA, San Francisco}, then.. we got
combo2: options {LA, San Francisco, Berlin, Tokyo, London}
intead of combo2: options {LA, San Francisco}
Here is the function that runs the combo2, which is called every time a customerName is chosen from the list combo1:
def loadComboCity(self,customerName):
"""query results cityList into self.mydb.matrix"""
queryName="citylist_thisCustomer"
self.mysqlAPI(queryName,customerName)
id=0
for row in self.mydb.matrix:
cityname=self.mydb.matrix[id][0]
self.addcomboCity(id,cityname)
id=id+1
del self.mydb.matrix[:]
and the function that adds each name of the list city that belongs to that customer:
def addcomboCity(self,id,cityname):
self.comboCity.addItem(QtCore.QString())
self.comboCity.setItemText(id, QtGui.QApplication.translate("MainWindow", cityname, None, QtGui.QApplication.UnicodeUTF8))
We tried to use del to clean the previous content of the list, but it still gets the same behavior.
This is a Qt or a Python related problem? Or there is some bit that we are missing here?
All comments and suggestions are highly appreciated.
A:
I think you are missing a QComboBox.clear() call , before the 'for loop'. Try the following code (Notice the new line just before id=0)
def loadComboCity(self,customerName):
"""query results cityList into self.mydb.matrix"""
queryName="citylist_thisCustomer"
self.mysqlAPI(queryName,customerName)
# Clear the previous items in the combobox (if any)
self.comboCity.clear()
id=0
for row in self.mydb.matrix:
cityname=self.mydb.matrix[id][0]
self.addcomboCity(id,cityname)
id=id+1
del self.mydb.matrix[:]
|
Python Hierarchical QcomboBox: clean-up list
|
I have a hierarchical two combo-box. The first combo-box displays a list of customerNames, i.e. different companies from a MySQL db. Each customer has branches in different cities.
Then, when a customer name is chosen from combo-box1 option list, e.g. {Aldi, Meyer, Carrefour, WalMart}, for that particular customer, a list of cities/branches is automatically displayed in the combo-box2. Something like that, e.g.:
combo1: chosen_customer [Aldi] --> cities:{NY, Boston, Berlin, Tokyo, London} then..
combo2: options {NY, Boston, Berlin, Tokyo, London}
The problem comes when we chose again another customer, that eventually has a smaller number of branches - e.g.
combo1: chosen_customer [Meyer] --> {LA, San Francisco}, then.. we got
combo2: options {LA, San Francisco, Berlin, Tokyo, London}
intead of combo2: options {LA, San Francisco}
Here is the function that runs the combo2, which is called every time a customerName is chosen from the list combo1:
def loadComboCity(self,customerName):
"""query results cityList into self.mydb.matrix"""
queryName="citylist_thisCustomer"
self.mysqlAPI(queryName,customerName)
id=0
for row in self.mydb.matrix:
cityname=self.mydb.matrix[id][0]
self.addcomboCity(id,cityname)
id=id+1
del self.mydb.matrix[:]
and the function that adds each name of the list city that belongs to that customer:
def addcomboCity(self,id,cityname):
self.comboCity.addItem(QtCore.QString())
self.comboCity.setItemText(id, QtGui.QApplication.translate("MainWindow", cityname, None, QtGui.QApplication.UnicodeUTF8))
We tried to use del to clean the previous content of the list, but it still gets the same behavior.
This is a Qt or a Python related problem? Or there is some bit that we are missing here?
All comments and suggestions are highly appreciated.
|
[
"I think you are missing a QComboBox.clear() call , before the 'for loop'. Try the following code (Notice the new line just before id=0)\ndef loadComboCity(self,customerName):\n \"\"\"query results cityList into self.mydb.matrix\"\"\"\n queryName=\"citylist_thisCustomer\"\n self.mysqlAPI(queryName,customerName)\n\n # Clear the previous items in the combobox (if any)\n self.comboCity.clear()\n\n id=0\n for row in self.mydb.matrix:\n cityname=self.mydb.matrix[id][0]\n self.addcomboCity(id,cityname) \n id=id+1\n del self.mydb.matrix[:]\n\n"
] |
[
1
] |
[] |
[] |
[
"combobox",
"hierarchical_data",
"python",
"qt"
] |
stackoverflow_0001990782_combobox_hierarchical_data_python_qt.txt
|
Q:
Self-contained egg installs: turbogears and pythonpath
I have a TG 1.0 application (not 1.1 -- I'm not sure I can convince the admin to upgrade) running. I have my own checkout of the project from cvs that I'm developing with, and it's come time to integrate xlwt (http://www.python-excel.org/) into the web app.
However, I don't have administrator access and it's not easy to get python packages installed by the administrator. What's more is that the app might be run on different servers, so I'd love to get a self-contained solution. I looked at:
http://peak.telecommunity.com/DevCenter/EasyInstall#custom-installation-locations
To see if I could figure out how to easy_install my troubles away, but I'm stuck with not really knowing how python is installed on the system. I do know that my user has a blank PYTHONPATH, that python is being run from /usr/local/python, and that the application is running just fine at the moment. I'd love to just have a PYTHONPATH="." so I can drop the egg files into the project directory, but I don't know how to make the actual configuration of the app honour this PYTHONPATH.
Any clues? Thanks!
A:
Why don't you use just Virtualenv, create a Python installation which you (as a user own) and install the TG egg inside that? This would make it convenient for you to install non-standard packages as well. I did this since I couldn't get my admin to install the stuff I needed.
A:
So, if anyone wants an easy answer for this: I inspected sys.path at run-time of my program and it turns out the root of the project (not the directory with templates/ and controllers in it, but its parent) is on it. So I added the directories to there and... voila! So I would suggest this as opposed to mucking about with python paths and such.
|
Self-contained egg installs: turbogears and pythonpath
|
I have a TG 1.0 application (not 1.1 -- I'm not sure I can convince the admin to upgrade) running. I have my own checkout of the project from cvs that I'm developing with, and it's come time to integrate xlwt (http://www.python-excel.org/) into the web app.
However, I don't have administrator access and it's not easy to get python packages installed by the administrator. What's more is that the app might be run on different servers, so I'd love to get a self-contained solution. I looked at:
http://peak.telecommunity.com/DevCenter/EasyInstall#custom-installation-locations
To see if I could figure out how to easy_install my troubles away, but I'm stuck with not really knowing how python is installed on the system. I do know that my user has a blank PYTHONPATH, that python is being run from /usr/local/python, and that the application is running just fine at the moment. I'd love to just have a PYTHONPATH="." so I can drop the egg files into the project directory, but I don't know how to make the actual configuration of the app honour this PYTHONPATH.
Any clues? Thanks!
|
[
"Why don't you use just Virtualenv, create a Python installation which you (as a user own) and install the TG egg inside that? This would make it convenient for you to install non-standard packages as well. I did this since I couldn't get my admin to install the stuff I needed. \n",
"So, if anyone wants an easy answer for this: I inspected sys.path at run-time of my program and it turns out the root of the project (not the directory with templates/ and controllers in it, but its parent) is on it. So I added the directories to there and... voila! So I would suggest this as opposed to mucking about with python paths and such.\n"
] |
[
1,
0
] |
[] |
[] |
[
"easy_install",
"egg",
"path",
"python",
"pythonpath"
] |
stackoverflow_0001959286_easy_install_egg_path_python_pythonpath.txt
|
Q:
Help needed--Is class necessary in Python scripting?
I am creating an interface for Python scripting.
Later I will be dong Python scripting also for automated testing.
Is it necessary the at i must use class in my code.Now I have created the code
with dictionaries,lists,functions,global and local variables.
Is class necessary?
Help me in this.
A:
No, of course class is not a must. As Python is a scripting language, you can simply code your scripts without defining your own classes.
Classes are useful if you implement a more complex program which needs a structured approach and OOP benfits (encapsulation, polimorphism) help you in doing it.
A:
It's not needed to make it work, but I would argue that it will become messy to maintain if you do not encapsulate certain things in classes. Classes are something that schould help the programmer to organizes his/her code, not just nice to have fluff.
A:
No you don't need to use classes for scripting.
However, when you start using the unit testing framework unittest, that will involve classes so you need to understand at least how to sub-class the TestCase class, eg:
import unittest
import os
class TestLint(unittest.TestCase):
def testLintCreatesLog(self):
# stuff that does things to create the file lint.log removed...
assert os.path.exists('lint.log') # this should be here after lint
assert os.path.getsize('lint.log') == 0 # nothing in the log - assume happy
if __name__ == '__main__':
# When this module is executed from the command-line, run all its tests
unittest.main()
A:
not necessary since python is not a purely object oriented language but certain things are better written in classes (encapsulation).it becomes easier to build a large project using classes
|
Help needed--Is class necessary in Python scripting?
|
I am creating an interface for Python scripting.
Later I will be dong Python scripting also for automated testing.
Is it necessary the at i must use class in my code.Now I have created the code
with dictionaries,lists,functions,global and local variables.
Is class necessary?
Help me in this.
|
[
"No, of course class is not a must. As Python is a scripting language, you can simply code your scripts without defining your own classes.\nClasses are useful if you implement a more complex program which needs a structured approach and OOP benfits (encapsulation, polimorphism) help you in doing it.\n",
"It's not needed to make it work, but I would argue that it will become messy to maintain if you do not encapsulate certain things in classes. Classes are something that schould help the programmer to organizes his/her code, not just nice to have fluff.\n",
"No you don't need to use classes for scripting.\nHowever, when you start using the unit testing framework unittest, that will involve classes so you need to understand at least how to sub-class the TestCase class, eg:\nimport unittest\nimport os\n\nclass TestLint(unittest.TestCase):\n\n def testLintCreatesLog(self):\n # stuff that does things to create the file lint.log removed...\n assert os.path.exists('lint.log') # this should be here after lint \n assert os.path.getsize('lint.log') == 0 # nothing in the log - assume happy\n\nif __name__ == '__main__':\n # When this module is executed from the command-line, run all its tests\n unittest.main()\n\n",
"not necessary since python is not a purely object oriented language but certain things are better written in classes (encapsulation).it becomes easier to build a large project using classes\n"
] |
[
10,
1,
1,
0
] |
[] |
[] |
[
"class",
"python",
"scripting"
] |
stackoverflow_0000438149_class_python_scripting.txt
|
Q:
SQL to calculate the Tanimoto Coefficient of several vectors
I think it's easier to explain my problem with an example.
I have one table with ingredients for recipes and I have implemented a function to calculate the Tanimoto coefficient between ingredients. It's fast enough to calculate the coefficient between two ingredients (3 sql queries needed), but it does not scale well. To calculate the coefficient betweeen all possible ingredient's combination it needs N + (N*(N-1))/2 queries or 500500 queries for just 1k ingredients. Is there a faster way to do that? Here's what I got so far:
class Filtering():
def __init__(self):
self._connection=sqlite.connect('database.db')
def n_recipes(self, ingredient_id):
cursor = self._connection.cursor()
cursor.execute('''select count(recipe_id) from recipe_ingredient
where ingredient_id = ? ''', (ingredient_id, ))
return cursor.fetchone()[0]
def n_recipes_intersection(self, ingredient_a, ingredient_b):
cursor = self._connection.cursor()
cursor.execute('''select count(drink_id) from recipe_ingredient where
ingredient_id = ? and recipe_id in (
select recipe_id from recipe_ingredient
where ingredient_id = ?) ''', (ingredient_a, ingredient_b))
return cursor.fetchone()[0]
def tanimoto(self, ingredient_a, ingredient_b):
n_a, n_b = map(self.n_recipes, (ingredient_a, ingredient_b))
n_ab = self.n_recipes_intersection(ingredient_a, ingredient_b)
return float(n_ab) / (n_a + n_b - n_ab)
A:
Why aren't you simply fetching all recipes into memory and then computing Tanimoto coefficients in memory?
It's simpler and it's much, much faster.
A:
If anybody is interested, this is the code that I came up with after Alex's and S.Lotts's suggestions. Thank you guys.
def __init__(self):
self._connection=sqlite.connect('database.db')
self._counts = None
self._intersections = {}
def inc_intersections(self, ingredients):
ingredients.sort()
lenght = len(ingredients)
for i in xrange(1, lenght):
a = ingredients[i]
for j in xrange(0, i):
b = ingredients[j]
if a not in self._intersections:
self._intersections[a] = {b: 1}
elif b not in self._intersections[a]:
self._intersections[a][b] = 1
else:
self._intersections[a][b] += 1
def precompute_tanimoto(self):
counts = {}
self._intersections = {}
cursor = self._connection.cursor()
cursor.execute('''select recipe_id, ingredient_id
from recipe_ingredient
order by recipe_id, ingredient_id''')
rows = cursor.fetchall()
print len(rows)
last_recipe = None
for recipe, ingredient in rows:
if recipe != last_recipe:
if last_recipe != None:
self.inc_intersections(ingredients)
last_recipe = recipe
ingredients = [ingredient]
else:
ingredients.append(ingredient)
if ingredient not in counts:
counts[ingredient] = 1
else:
counts[ingredient] += 1
self.inc_intersections(ingredients)
self._counts = counts
def tanimoto(self, ingredient_a, ingredient_b):
if self._counts == None:
self.precompute_tanimoto()
if ingredient_b > ingredient_a:
ingredient_b, ingredient_a = ingredient_a, ingredient_b
n_a, n_b = self._counts[ingredient_a], self._counts[ingredient_b]
n_ab = self._intersections[ingredient_a][ingredient_b]
print n_a, n_b, n_ab
return float(n_ab) / (n_a + n_b - n_ab)
A:
If you have 1000 ingredients, 1000 queries will suffice to map each ingredient to a set of recipes in memory. If (say) an ingredient is typically part of about 100 recipes, each set will take a few KB, so the whole dictionary will take just a few MB -- absolutely no problem to hold the whole thing in memory (and still not a serious memory problem if the average number of recipes per ingredient grows by an order of magnitude).
result = dict()
for ing_id in all_ingredient_ids:
cursor.execute('''select recipe_id from recipe_ingredient
where ingredient_id = ?''', (ing_id,))
result[ing_id] = set(r[0] for r in cursor.fetchall())
return result
After those 1000 queries, every one of the needed 500,000 computations of pairwise Tanimoto coefficients is then obviously done in-memory -- you can precompute the squares of the lengths of the various sets as a further speedup (and park them in another dict), and the key "A dotproduct B" component for each pair is of course the length of the sets' intersection.
A:
I think this will cut you down to 2 selects per pair for the intersection, and 4 queries per pair total. You can't get away from O(N^2) since you are trying all pairs -- N*(N-1)/2 is simply how many pairs there are.
def n_recipes_intersection(self, ingredient_a, ingredient_b):
cursor = self._cur
cursor.execute('''
select count(recipe_id)
from recipe_ingredient as A
join recipe_ingredient as B using (recipe_id)
where A.ingredient_id = ?
and B.ingredient_id = ?;
''', (ingredient_a, ingredient_b))
return cursor.fetchone()[0]
|
SQL to calculate the Tanimoto Coefficient of several vectors
|
I think it's easier to explain my problem with an example.
I have one table with ingredients for recipes and I have implemented a function to calculate the Tanimoto coefficient between ingredients. It's fast enough to calculate the coefficient between two ingredients (3 sql queries needed), but it does not scale well. To calculate the coefficient betweeen all possible ingredient's combination it needs N + (N*(N-1))/2 queries or 500500 queries for just 1k ingredients. Is there a faster way to do that? Here's what I got so far:
class Filtering():
def __init__(self):
self._connection=sqlite.connect('database.db')
def n_recipes(self, ingredient_id):
cursor = self._connection.cursor()
cursor.execute('''select count(recipe_id) from recipe_ingredient
where ingredient_id = ? ''', (ingredient_id, ))
return cursor.fetchone()[0]
def n_recipes_intersection(self, ingredient_a, ingredient_b):
cursor = self._connection.cursor()
cursor.execute('''select count(drink_id) from recipe_ingredient where
ingredient_id = ? and recipe_id in (
select recipe_id from recipe_ingredient
where ingredient_id = ?) ''', (ingredient_a, ingredient_b))
return cursor.fetchone()[0]
def tanimoto(self, ingredient_a, ingredient_b):
n_a, n_b = map(self.n_recipes, (ingredient_a, ingredient_b))
n_ab = self.n_recipes_intersection(ingredient_a, ingredient_b)
return float(n_ab) / (n_a + n_b - n_ab)
|
[
"Why aren't you simply fetching all recipes into memory and then computing Tanimoto coefficients in memory? \nIt's simpler and it's much, much faster.\n",
"If anybody is interested, this is the code that I came up with after Alex's and S.Lotts's suggestions. Thank you guys.\ndef __init__(self):\n self._connection=sqlite.connect('database.db')\n self._counts = None\n self._intersections = {}\n\ndef inc_intersections(self, ingredients):\n ingredients.sort()\n lenght = len(ingredients)\n for i in xrange(1, lenght):\n a = ingredients[i]\n for j in xrange(0, i):\n b = ingredients[j]\n if a not in self._intersections:\n self._intersections[a] = {b: 1}\n elif b not in self._intersections[a]:\n self._intersections[a][b] = 1\n else:\n self._intersections[a][b] += 1\n\n\ndef precompute_tanimoto(self):\n counts = {}\n self._intersections = {}\n\n cursor = self._connection.cursor()\n cursor.execute('''select recipe_id, ingredient_id\n from recipe_ingredient\n order by recipe_id, ingredient_id''')\n rows = cursor.fetchall() \n\n print len(rows)\n\n last_recipe = None\n for recipe, ingredient in rows:\n if recipe != last_recipe:\n if last_recipe != None:\n self.inc_intersections(ingredients)\n last_recipe = recipe\n ingredients = [ingredient]\n else:\n ingredients.append(ingredient)\n\n if ingredient not in counts:\n counts[ingredient] = 1\n else:\n counts[ingredient] += 1\n\n self.inc_intersections(ingredients)\n\n self._counts = counts\n\ndef tanimoto(self, ingredient_a, ingredient_b):\n if self._counts == None:\n self.precompute_tanimoto()\n\n if ingredient_b > ingredient_a:\n ingredient_b, ingredient_a = ingredient_a, ingredient_b\n\n n_a, n_b = self._counts[ingredient_a], self._counts[ingredient_b]\n n_ab = self._intersections[ingredient_a][ingredient_b]\n\n print n_a, n_b, n_ab\n\n return float(n_ab) / (n_a + n_b - n_ab)\n\n",
"If you have 1000 ingredients, 1000 queries will suffice to map each ingredient to a set of recipes in memory. If (say) an ingredient is typically part of about 100 recipes, each set will take a few KB, so the whole dictionary will take just a few MB -- absolutely no problem to hold the whole thing in memory (and still not a serious memory problem if the average number of recipes per ingredient grows by an order of magnitude).\nresult = dict()\nfor ing_id in all_ingredient_ids:\n cursor.execute('''select recipe_id from recipe_ingredient\n where ingredient_id = ?''', (ing_id,))\n result[ing_id] = set(r[0] for r in cursor.fetchall())\nreturn result\n\nAfter those 1000 queries, every one of the needed 500,000 computations of pairwise Tanimoto coefficients is then obviously done in-memory -- you can precompute the squares of the lengths of the various sets as a further speedup (and park them in another dict), and the key \"A dotproduct B\" component for each pair is of course the length of the sets' intersection.\n",
"I think this will cut you down to 2 selects per pair for the intersection, and 4 queries per pair total. You can't get away from O(N^2) since you are trying all pairs -- N*(N-1)/2 is simply how many pairs there are.\ndef n_recipes_intersection(self, ingredient_a, ingredient_b):\n cursor = self._cur\n cursor.execute('''\n select count(recipe_id)\n from recipe_ingredient as A \n join recipe_ingredient as B using (recipe_id)\n where A.ingredient_id = ? \n and B.ingredient_id = ?;\n ''', (ingredient_a, ingredient_b))\n return cursor.fetchone()[0]\n\n"
] |
[
4,
3,
1,
0
] |
[] |
[] |
[
"collaborative_filtering",
"python",
"sql"
] |
stackoverflow_0001992158_collaborative_filtering_python_sql.txt
|
Q:
python: Should I use ValueError or create my own subclass to handle invalid strings?
Possible Duplicate:
Which exception should I raise on bad/illegal argument combinations in Python?
I've looked through python's built in exceptions and the only thing that seems close is ValueError.
from python documentation:
exception ValueError:
Raised when a built-in operation or function receives an argument that has the right type but an inappropriate value, and the situation is not described by a more precise exception such as IndexError.
Should I create a subclass of ValueError, like InvalidFormatException?
(My particular case is if a roman numeral string is improperly formatted, but there are many other applicable cases.)
EDIT: it seems like ValueError is the right choice, now the issue is whether to use ValueError directly or to subclass it.
A:
ValueError is a good match for the case you have. Just go with that and remember that you can specify a useful message as an argument, letting you distinguish this from other types of ValueError.
I would not make the code more complicated by defining a subclass, however, unless I had a good reason to want to catch just that particular error but avoid catching any other ValueErrors. Many applications have dozens of "special" error conditions, but if they also defined per-case subclasses the code would quickly get unmaintainable and anyone trying to use the routines would be constantly surprised by the unexpected new exceptions.
A:
ValueError seems logical:
In [1]: int('abc')
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython console> in <module>()
ValueError: invalid literal for int() with base 10: 'abc'
A:
I vote for creating a unique subclass, InvalidFormatException.
ValueError, while true, is vague.
InvalidFormatException is more specific and tied directly to your problem.
A user could wind up with situations where they're doing something that could produce either error. They could be converting roman numerals and then doing some math. They might need to distinguish between the ValueError and the InvalidFormatException.
A:
Well really it depends whether you want (or need) that particular exception to be catchable independently of other ValueErrors that may occur during invocation of your code. It also depends whether you are the sole consumer of your code or it's intended for other people to use; in the latter case it may be helpful to these people if you define some high-level library-specific exceptions that they can check for.
|
python: Should I use ValueError or create my own subclass to handle invalid strings?
|
Possible Duplicate:
Which exception should I raise on bad/illegal argument combinations in Python?
I've looked through python's built in exceptions and the only thing that seems close is ValueError.
from python documentation:
exception ValueError:
Raised when a built-in operation or function receives an argument that has the right type but an inappropriate value, and the situation is not described by a more precise exception such as IndexError.
Should I create a subclass of ValueError, like InvalidFormatException?
(My particular case is if a roman numeral string is improperly formatted, but there are many other applicable cases.)
EDIT: it seems like ValueError is the right choice, now the issue is whether to use ValueError directly or to subclass it.
|
[
"ValueError is a good match for the case you have. Just go with that and remember that you can specify a useful message as an argument, letting you distinguish this from other types of ValueError.\nI would not make the code more complicated by defining a subclass, however, unless I had a good reason to want to catch just that particular error but avoid catching any other ValueErrors. Many applications have dozens of \"special\" error conditions, but if they also defined per-case subclasses the code would quickly get unmaintainable and anyone trying to use the routines would be constantly surprised by the unexpected new exceptions.\n",
"ValueError seems logical:\nIn [1]: int('abc')\n---------------------------------------------------------------------------\nValueError Traceback (most recent call last)\n\n<ipython console> in <module>()\n\nValueError: invalid literal for int() with base 10: 'abc'\n\n",
"I vote for creating a unique subclass, InvalidFormatException.\nValueError, while true, is vague.\nInvalidFormatException is more specific and tied directly to your problem.\nA user could wind up with situations where they're doing something that could produce either error. They could be converting roman numerals and then doing some math. They might need to distinguish between the ValueError and the InvalidFormatException. \n",
"Well really it depends whether you want (or need) that particular exception to be catchable independently of other ValueErrors that may occur during invocation of your code. It also depends whether you are the sole consumer of your code or it's intended for other people to use; in the latter case it may be helpful to these people if you define some high-level library-specific exceptions that they can check for.\n"
] |
[
11,
4,
4,
3
] |
[
"Yes. ;-) ValueError does sound like the most applicable of the built-in ones, and with a subclass of that you seem to be doing the best possible. It's also what f.i. '%q' % 1 would raise.\n",
"I also support ValueError for this case. My 2 cents.\n"
] |
[
-1,
-1
] |
[
"exception",
"python"
] |
stackoverflow_0001992006_exception_python.txt
|
Q:
Recompile Vim for pythoncomplete#Complete on modules *other* than standard library?
I like using pythoncomplete#Complete for Vim omnicompletion, but it doesn't work for Python modules other than the standard library.
Is there a way to re-compile Vim so that this will work on non-standard library modules?
I have tried pysmell, et. al., but they just don't work as well as pythoncomplete#Complete. This is for a Windows machine.
A:
Have you tried setting PYTHONPATH prior to starting Vim?
You can also modify the path from inside Vim, by doing:
:python import sys
:python print sys.path
:python sys.path.append(...)
... etc
|
Recompile Vim for pythoncomplete#Complete on modules *other* than standard library?
|
I like using pythoncomplete#Complete for Vim omnicompletion, but it doesn't work for Python modules other than the standard library.
Is there a way to re-compile Vim so that this will work on non-standard library modules?
I have tried pysmell, et. al., but they just don't work as well as pythoncomplete#Complete. This is for a Windows machine.
|
[
"Have you tried setting PYTHONPATH prior to starting Vim?\nYou can also modify the path from inside Vim, by doing:\n:python import sys\n:python print sys.path\n:python sys.path.append(...)\n... etc\n\n"
] |
[
1
] |
[] |
[] |
[
"python",
"vim"
] |
stackoverflow_0001991865_python_vim.txt
|
Q:
python qt raise syntax error
I have a top level widget that is producing a syntax error in python. raise() on line 15. This is using the python Qt bindings. I know that raise is a python reserved word. I am looking for how to call the Qt "raise()" function with the python bindings.
#!/usr/bin/python
# simple.py
import sys
from PyQt4 import QtGui
app = QtGui.QApplication(sys.argv)
widget = QtGui.QWidget()
widget.resize(250, 150)
widget.setWindowTitle('simple')
widget.show()
widget.activateWindow ()
widget.raise()
sys.exit(app.exec_())
A:
"raise" is a keyword (reserved word) in Python. So, you can't use it. And PyQt4 certainly doesn't use it as you think, because, well, it's a keyword, so no extension can. It's like you can't use "from" for a variable name (pet peeve: Python doesn't have variables, but I digress...)
As a hint, it's also highlighted by the syntax highlighter of SO.
Just a bit of interactive pythoneering... and it's raise_. Yep, with an underscore tacked on at the end. Pretty standard method when you have a keyword as a method/function.
|
python qt raise syntax error
|
I have a top level widget that is producing a syntax error in python. raise() on line 15. This is using the python Qt bindings. I know that raise is a python reserved word. I am looking for how to call the Qt "raise()" function with the python bindings.
#!/usr/bin/python
# simple.py
import sys
from PyQt4 import QtGui
app = QtGui.QApplication(sys.argv)
widget = QtGui.QWidget()
widget.resize(250, 150)
widget.setWindowTitle('simple')
widget.show()
widget.activateWindow ()
widget.raise()
sys.exit(app.exec_())
|
[
"\"raise\" is a keyword (reserved word) in Python. So, you can't use it. And PyQt4 certainly doesn't use it as you think, because, well, it's a keyword, so no extension can. It's like you can't use \"from\" for a variable name (pet peeve: Python doesn't have variables, but I digress...)\nAs a hint, it's also highlighted by the syntax highlighter of SO.\nJust a bit of interactive pythoneering... and it's raise_. Yep, with an underscore tacked on at the end. Pretty standard method when you have a keyword as a method/function.\n"
] |
[
15
] |
[] |
[] |
[
"pyqt4",
"python",
"qt",
"qt4"
] |
stackoverflow_0001992739_pyqt4_python_qt_qt4.txt
|
Q:
Python Working with lists based on indexes
I have data in a CSV file. One of the column lists a persons name and all the rows that follow in that column provide some descriptive attributes about that person until the next persons name shows up. I can tell when the row has a name or an attribute by the LTYPE column, N in that column indicates that in that row the NAME value is actually a name, an A in that column indicates that the data in the NAME column is an attribute. The attributes are coded and I have 600K lines of the data. Here is a sample. The data is grouped and the befinning of each grouping is indicated by RID resetting to 1.
{'LTYPE': 'N', 'RID': '1', 'NAME': 'Jason Smith'}
{'LTYPE': 'A', 'RID': '2', 'NAME': 'DA'}
{'LTYPE': 'A', 'RID': '3', 'NAME': 'B'}
{'LTYPE': 'N', 'RID': '4', 'NAME': 'John Smith'}
{'LTYPE': 'A', 'RID': '5', 'NAME': 'BC'}
{'LTYPE': 'A', 'RID': '6', 'NAME': 'CB'}
{'LTYPE': 'A', 'RID': '7', 'NAME': 'DB'}
{'LTYPE': 'A', 'RID': '8', 'NAME': 'DA'}
{'LTYPE': 'N', 'RID': '9', 'NAME': 'Robert Smith'}
{'LTYPE': 'A', 'RID': '10', 'NAME': 'BC'}
{'LTYPE': 'A', 'RID': '11', 'NAME': 'DB'}
{'LTYPE': 'A', 'RID': '12', 'NAME': 'CB'}
{'LTYPE': 'A', 'RID': '13', 'NAME': 'RB'}
{'LTYPE': 'A', 'RID': '14', 'NAME': 'VC'}
{'LTYPE': 'N', 'RID': '15', 'NAME': 'Harvey Smith'}
{'LTYPE': 'A', 'RID': '16', 'NAME': 'SA'}
{'LTYPE': 'A', 'RID': '17', 'NAME': 'AS'}
{'LTYPE': 'N', 'RID': '18', 'NAME': 'Lukas Smith'}
{'LTYPE': 'A', 'RID': '19', 'NAME': 'BC'}
{'LTYPE': 'A', 'RID': '20', 'NAME': 'AS'}
I want to create the following:
{'PERSON_ATTRIBUTES': 'DA B ', 'LTYPE': 'N', 'RID': '1', 'PERSON_NAME': 'Jason Smith', 'NAME': 'Jason Smith'}
{'PERSON_ATTRIBUTES': 'DA B ', 'LTYPE': 'A', 'RID': '2', 'PERSON_NAME': 'Jason Smith', 'NAME': 'DA'}
{'PERSON_ATTRIBUTES': 'DA B ', 'LTYPE': 'A', 'RID': '3', 'PERSON_NAME': 'Jason Smith', 'NAME': 'B'}
{'PERSON_ATTRIBUTES': 'BC CB DB DA ', 'LTYPE': 'N', 'RID': '4', 'PERSON_NAME': 'John Smith', 'NAME': 'John Smith'}
{'PERSON_ATTRIBUTES': 'BC CB DB DA ', 'LTYPE': 'A', 'RID': '5', 'PERSON_NAME': 'John Smith', 'NAME': 'BC'}
{'PERSON_ATTRIBUTES': 'BC CB DB DA ', 'LTYPE': 'A', 'RID': '6', 'PERSON_NAME': 'John Smith', 'NAME': 'CB'}
{'PERSON_ATTRIBUTES': 'BC CB DB DA ', 'LTYPE': 'A', 'RID': '7', 'PERSON_NAME': 'John Smith', 'NAME': 'DB'}
{'PERSON_ATTRIBUTES': 'BC CB DB DA ', 'LTYPE': 'A', 'RID': '8', 'PERSON_NAME': 'John Smith', 'NAME': 'DA'}
{'PERSON_ATTRIBUTES': 'BC DB CB RB VC ', 'LTYPE': 'N', 'RID': '9', 'PERSON_NAME': 'Robert Smith', 'NAME': 'Robert Smith'}
{'PERSON_ATTRIBUTES': 'BC DB CB RB VC ', 'LTYPE': 'A', 'RID': '10', 'PERSON_NAME': 'Robert Smith', 'NAME': 'BC'}
{'PERSON_ATTRIBUTES': 'BC DB CB RB VC ', 'LTYPE': 'A', 'RID': '11', 'PERSON_NAME': 'Robert Smith', 'NAME': 'DB'}
{'PERSON_ATTRIBUTES': 'BC DB CB RB VC ', 'LTYPE': 'A', 'RID': '12', 'PERSON_NAME': 'Robert Smith', 'NAME': 'CB'}
{'PERSON_ATTRIBUTES': 'BC DB CB RB VC ', 'LTYPE': 'A', 'RID': '13', 'PERSON_NAME': 'Robert Smith', 'NAME': 'RB'}
{'PERSON_ATTRIBUTES': 'BC DB CB RB VC ', 'LTYPE': 'A', 'RID': '14', 'PERSON_NAME': 'Robert Smith', 'NAME': 'VC'}
{'PERSON_ATTRIBUTES': 'SA AS ', 'LTYPE': 'N', 'RID': '15', 'PERSON_NAME': 'Harvey Smith', 'NAME': 'Harvey Smith'}
{'PERSON_ATTRIBUTES': 'SA AS ', 'LTYPE': 'A', 'RID': '16', 'PERSON_NAME': 'Harvey Smith', 'NAME': 'SA'}
{'PERSON_ATTRIBUTES': 'SA AS ', 'LTYPE': 'A', 'RID': '17', 'PERSON_NAME': 'Harvey Smith', 'NAME': 'AS'}
{'PERSON_ATTRIBUTES': 'BC AS ', 'LTYPE': 'N', 'RID': '18', 'PERSON_NAME': 'Lukas Smith', 'NAME': 'Lukas Smith'}
{'PERSON_ATTRIBUTES': 'BC AS ', 'LTYPE': 'A', 'RID': '19', 'PERSON_NAME': 'Lukas Smith', 'NAME': 'BC'}
{'PERSON_ATTRIBUTES': 'BC AS ', 'LTYPE': 'A', 'RID': '20', 'PERSON_NAME': 'Lukas Smith', 'NAME': 'AS'}
I started off by getting the index positions of LTYPE
nameIndex=[]
attributeIndex=[]
for line in thedata:
if line['LTYPE']=='N':
nameIndex.append(int(line["RID"])-1)
if line['LTYPE']=='A':
attributeIndex.append(int(line["RID"])-1)
So I have the list index of each of the rows classified as a name in one list and the list index of each of the rows classified as an attribute in another list. It is then easy to attach the name to each observation as follows
for counter, row in enumerate(thedata):
if counter in nameIndex:
row['PERSON_NAME']=row['NAME']
person_NAME=row['NAME']
if counter not in nameIndex:
row['PERSON_NAME']=person_NAME
I am struggling to determine and assign the list of attributes to each person.
First I need to combine the attributes that belong together so I did this:
newAttribute=[]
for counter, row in enumerate(thedata):
if counter in attributeIndex:
tempAttribute=tempAttribute+' '+row['NAME']
if counter not in attributeIndex:
if counter==0:
tempAttribute=""
pass
if counter!=0:
newAttribute.append(tempAttribute.lstrip())
tempAttribute=""
one problem with my approach is that I still have to add the last group to the newAttribute list since the loop finishes before it is added. So to get the list of grouped attributes I have to run
newAttribute.append(tempAttribute)
But even then I can't seem to find a clean way to add the attributes I have to do it in two steps. First, I create a dictionary with the nameIndex positions as the key and the attributes as the values
tempDict={}
for each in range(len(nameIndex)):
tempdict[nameIndex[each]]=newAttribute[each]
I cycle through the list once putting in the attribute on the name line
for counter,row in enumerate(thedata):
if counter in tempDict:
thedata[counter]['TA']=tempDict[counter]
and then I go through it again checking if the key 'TA' exists and using the existence to set the PERSON_ATTRIBUTE key
for each in thedata:
if each.has_key('TA'):
each['PERSON_ATTRIBUTES']=each['TA']
holdAttribute=each['TA']
else:
each['PERSON_ATTRIBUTES']=holdAttribute
There has got to be a cleaner way to think about this and so I was wondering if anyone would like to point me in the direction of some functions that I could read about that would let me clean up this code. I know I still have to drop the 'TA' key but I figured that I have taken enough space.
A:
I suggest a different, index-free approach based on itertools.groupby:
import itertools, operator
data = [
{'LTYPE': 'N', 'RID': '1', 'NAME': 'Jason Smith'},
{'LTYPE': 'A', 'RID': '2', 'NAME': 'DA'},
{'LTYPE': 'A', 'RID': '3', 'NAME': 'B'},
{'LTYPE': 'N', 'RID': '4', 'NAME': 'John Smith'},
{'LTYPE': 'A', 'RID': '5', 'NAME': 'BC'},
{'LTYPE': 'A', 'RID': '6', 'NAME': 'CB'},
{'LTYPE': 'A', 'RID': '7', 'NAME': 'DB'},
{'LTYPE': 'A', 'RID': '8', 'NAME': 'DA'},
]
for k, g in itertools.groupby(data, operator.itemgetter('LTYPE')):
if k=='N':
person_name_record = next(g)
else:
attribute_records = list(g)
person_attributes = ' '.join(r['NAME'] for r in attribute_records)
addfields = dict(PERSON_ATTRIBUTES=person_attributes,
PERSON_NAME=person_name_record['NAME'])
person_name_record.update(addfields)
for r in attribute_records: r.update(addfields)
for r in data: print r
This prints your desired results for the first couple people (and each person is treated separately, so it should work just the same for a few hundred thousand people;-).
A:
I would split this into two tasks.
First, divide thedata into groups of LTYPE=N rows and the LTYPE=A rows that follow it.
def group_name_and_attributes(thedata):
group = []
for row in thedata:
if row['LTYPE'] == 'N':
if group:
yield group
group = [row]
else:
group.append(row)
if group:
yield group
Next, take each group in isolation and collect the total attributes for each; it's easy to then add the sum attributes to each row as desired.
def join_person_attributes(thedata):
for group in group_name_and_attributes(thedata):
attributes = ' '.join(row['NAME'] for row in group if row['LTYPE'] == 'A')
for row in group:
new_row = row.copy()
new_row['PERSON_ATTRIBUTES'] = attributes
yield new_row
new_data = list(join_person_attributes(thedata))
Of course you could make this modify the rows in-place, or only return one row per group, or ...
|
Python Working with lists based on indexes
|
I have data in a CSV file. One of the column lists a persons name and all the rows that follow in that column provide some descriptive attributes about that person until the next persons name shows up. I can tell when the row has a name or an attribute by the LTYPE column, N in that column indicates that in that row the NAME value is actually a name, an A in that column indicates that the data in the NAME column is an attribute. The attributes are coded and I have 600K lines of the data. Here is a sample. The data is grouped and the befinning of each grouping is indicated by RID resetting to 1.
{'LTYPE': 'N', 'RID': '1', 'NAME': 'Jason Smith'}
{'LTYPE': 'A', 'RID': '2', 'NAME': 'DA'}
{'LTYPE': 'A', 'RID': '3', 'NAME': 'B'}
{'LTYPE': 'N', 'RID': '4', 'NAME': 'John Smith'}
{'LTYPE': 'A', 'RID': '5', 'NAME': 'BC'}
{'LTYPE': 'A', 'RID': '6', 'NAME': 'CB'}
{'LTYPE': 'A', 'RID': '7', 'NAME': 'DB'}
{'LTYPE': 'A', 'RID': '8', 'NAME': 'DA'}
{'LTYPE': 'N', 'RID': '9', 'NAME': 'Robert Smith'}
{'LTYPE': 'A', 'RID': '10', 'NAME': 'BC'}
{'LTYPE': 'A', 'RID': '11', 'NAME': 'DB'}
{'LTYPE': 'A', 'RID': '12', 'NAME': 'CB'}
{'LTYPE': 'A', 'RID': '13', 'NAME': 'RB'}
{'LTYPE': 'A', 'RID': '14', 'NAME': 'VC'}
{'LTYPE': 'N', 'RID': '15', 'NAME': 'Harvey Smith'}
{'LTYPE': 'A', 'RID': '16', 'NAME': 'SA'}
{'LTYPE': 'A', 'RID': '17', 'NAME': 'AS'}
{'LTYPE': 'N', 'RID': '18', 'NAME': 'Lukas Smith'}
{'LTYPE': 'A', 'RID': '19', 'NAME': 'BC'}
{'LTYPE': 'A', 'RID': '20', 'NAME': 'AS'}
I want to create the following:
{'PERSON_ATTRIBUTES': 'DA B ', 'LTYPE': 'N', 'RID': '1', 'PERSON_NAME': 'Jason Smith', 'NAME': 'Jason Smith'}
{'PERSON_ATTRIBUTES': 'DA B ', 'LTYPE': 'A', 'RID': '2', 'PERSON_NAME': 'Jason Smith', 'NAME': 'DA'}
{'PERSON_ATTRIBUTES': 'DA B ', 'LTYPE': 'A', 'RID': '3', 'PERSON_NAME': 'Jason Smith', 'NAME': 'B'}
{'PERSON_ATTRIBUTES': 'BC CB DB DA ', 'LTYPE': 'N', 'RID': '4', 'PERSON_NAME': 'John Smith', 'NAME': 'John Smith'}
{'PERSON_ATTRIBUTES': 'BC CB DB DA ', 'LTYPE': 'A', 'RID': '5', 'PERSON_NAME': 'John Smith', 'NAME': 'BC'}
{'PERSON_ATTRIBUTES': 'BC CB DB DA ', 'LTYPE': 'A', 'RID': '6', 'PERSON_NAME': 'John Smith', 'NAME': 'CB'}
{'PERSON_ATTRIBUTES': 'BC CB DB DA ', 'LTYPE': 'A', 'RID': '7', 'PERSON_NAME': 'John Smith', 'NAME': 'DB'}
{'PERSON_ATTRIBUTES': 'BC CB DB DA ', 'LTYPE': 'A', 'RID': '8', 'PERSON_NAME': 'John Smith', 'NAME': 'DA'}
{'PERSON_ATTRIBUTES': 'BC DB CB RB VC ', 'LTYPE': 'N', 'RID': '9', 'PERSON_NAME': 'Robert Smith', 'NAME': 'Robert Smith'}
{'PERSON_ATTRIBUTES': 'BC DB CB RB VC ', 'LTYPE': 'A', 'RID': '10', 'PERSON_NAME': 'Robert Smith', 'NAME': 'BC'}
{'PERSON_ATTRIBUTES': 'BC DB CB RB VC ', 'LTYPE': 'A', 'RID': '11', 'PERSON_NAME': 'Robert Smith', 'NAME': 'DB'}
{'PERSON_ATTRIBUTES': 'BC DB CB RB VC ', 'LTYPE': 'A', 'RID': '12', 'PERSON_NAME': 'Robert Smith', 'NAME': 'CB'}
{'PERSON_ATTRIBUTES': 'BC DB CB RB VC ', 'LTYPE': 'A', 'RID': '13', 'PERSON_NAME': 'Robert Smith', 'NAME': 'RB'}
{'PERSON_ATTRIBUTES': 'BC DB CB RB VC ', 'LTYPE': 'A', 'RID': '14', 'PERSON_NAME': 'Robert Smith', 'NAME': 'VC'}
{'PERSON_ATTRIBUTES': 'SA AS ', 'LTYPE': 'N', 'RID': '15', 'PERSON_NAME': 'Harvey Smith', 'NAME': 'Harvey Smith'}
{'PERSON_ATTRIBUTES': 'SA AS ', 'LTYPE': 'A', 'RID': '16', 'PERSON_NAME': 'Harvey Smith', 'NAME': 'SA'}
{'PERSON_ATTRIBUTES': 'SA AS ', 'LTYPE': 'A', 'RID': '17', 'PERSON_NAME': 'Harvey Smith', 'NAME': 'AS'}
{'PERSON_ATTRIBUTES': 'BC AS ', 'LTYPE': 'N', 'RID': '18', 'PERSON_NAME': 'Lukas Smith', 'NAME': 'Lukas Smith'}
{'PERSON_ATTRIBUTES': 'BC AS ', 'LTYPE': 'A', 'RID': '19', 'PERSON_NAME': 'Lukas Smith', 'NAME': 'BC'}
{'PERSON_ATTRIBUTES': 'BC AS ', 'LTYPE': 'A', 'RID': '20', 'PERSON_NAME': 'Lukas Smith', 'NAME': 'AS'}
I started off by getting the index positions of LTYPE
nameIndex=[]
attributeIndex=[]
for line in thedata:
if line['LTYPE']=='N':
nameIndex.append(int(line["RID"])-1)
if line['LTYPE']=='A':
attributeIndex.append(int(line["RID"])-1)
So I have the list index of each of the rows classified as a name in one list and the list index of each of the rows classified as an attribute in another list. It is then easy to attach the name to each observation as follows
for counter, row in enumerate(thedata):
if counter in nameIndex:
row['PERSON_NAME']=row['NAME']
person_NAME=row['NAME']
if counter not in nameIndex:
row['PERSON_NAME']=person_NAME
I am struggling to determine and assign the list of attributes to each person.
First I need to combine the attributes that belong together so I did this:
newAttribute=[]
for counter, row in enumerate(thedata):
if counter in attributeIndex:
tempAttribute=tempAttribute+' '+row['NAME']
if counter not in attributeIndex:
if counter==0:
tempAttribute=""
pass
if counter!=0:
newAttribute.append(tempAttribute.lstrip())
tempAttribute=""
one problem with my approach is that I still have to add the last group to the newAttribute list since the loop finishes before it is added. So to get the list of grouped attributes I have to run
newAttribute.append(tempAttribute)
But even then I can't seem to find a clean way to add the attributes I have to do it in two steps. First, I create a dictionary with the nameIndex positions as the key and the attributes as the values
tempDict={}
for each in range(len(nameIndex)):
tempdict[nameIndex[each]]=newAttribute[each]
I cycle through the list once putting in the attribute on the name line
for counter,row in enumerate(thedata):
if counter in tempDict:
thedata[counter]['TA']=tempDict[counter]
and then I go through it again checking if the key 'TA' exists and using the existence to set the PERSON_ATTRIBUTE key
for each in thedata:
if each.has_key('TA'):
each['PERSON_ATTRIBUTES']=each['TA']
holdAttribute=each['TA']
else:
each['PERSON_ATTRIBUTES']=holdAttribute
There has got to be a cleaner way to think about this and so I was wondering if anyone would like to point me in the direction of some functions that I could read about that would let me clean up this code. I know I still have to drop the 'TA' key but I figured that I have taken enough space.
|
[
"I suggest a different, index-free approach based on itertools.groupby:\nimport itertools, operator\n\ndata = [\n{'LTYPE': 'N', 'RID': '1', 'NAME': 'Jason Smith'},\n{'LTYPE': 'A', 'RID': '2', 'NAME': 'DA'},\n{'LTYPE': 'A', 'RID': '3', 'NAME': 'B'},\n{'LTYPE': 'N', 'RID': '4', 'NAME': 'John Smith'},\n{'LTYPE': 'A', 'RID': '5', 'NAME': 'BC'},\n{'LTYPE': 'A', 'RID': '6', 'NAME': 'CB'},\n{'LTYPE': 'A', 'RID': '7', 'NAME': 'DB'},\n{'LTYPE': 'A', 'RID': '8', 'NAME': 'DA'},\n]\n\nfor k, g in itertools.groupby(data, operator.itemgetter('LTYPE')):\n if k=='N':\n person_name_record = next(g)\n else:\n attribute_records = list(g)\n person_attributes = ' '.join(r['NAME'] for r in attribute_records)\n addfields = dict(PERSON_ATTRIBUTES=person_attributes,\n PERSON_NAME=person_name_record['NAME'])\n person_name_record.update(addfields)\n for r in attribute_records: r.update(addfields)\n\nfor r in data: print r\n\nThis prints your desired results for the first couple people (and each person is treated separately, so it should work just the same for a few hundred thousand people;-).\n",
"I would split this into two tasks.\nFirst, divide thedata into groups of LTYPE=N rows and the LTYPE=A rows that follow it.\ndef group_name_and_attributes(thedata):\n group = []\n for row in thedata:\n if row['LTYPE'] == 'N':\n if group:\n yield group\n group = [row]\n else:\n group.append(row)\n if group:\n yield group\n\nNext, take each group in isolation and collect the total attributes for each; it's easy to then add the sum attributes to each row as desired.\ndef join_person_attributes(thedata):\n for group in group_name_and_attributes(thedata):\n attributes = ' '.join(row['NAME'] for row in group if row['LTYPE'] == 'A')\n for row in group:\n new_row = row.copy()\n new_row['PERSON_ATTRIBUTES'] = attributes\n yield new_row\n\nnew_data = list(join_person_attributes(thedata))\n\nOf course you could make this modify the rows in-place, or only return one row per group, or ...\n"
] |
[
2,
1
] |
[] |
[] |
[
"list",
"python",
"variable_assignment"
] |
stackoverflow_0001992659_list_python_variable_assignment.txt
|
Q:
how can i escape '\xff\xfe' to a readable string
i see a string in this code:
data[:2] == '\xff\xfe'
i don't know what '\xff\xfe' is,
so i want to escape it ,but not successful
import cgi
print cgi.escape('\xff\xfe')#print \xff\xfe
how can i get it.
thanks
A:
'\xFF' means the byte with the hex value FF. '\xff\xfe' is a byte-order mark: http://en.wikipedia.org/wiki/Byte_order_mark
You could also represent it as two separate characters but that probably won't tell you anything useful.
A:
>>> print '\xff\xfe'.encode('string-escape')
\xff\xfe
A:
What is the connection between "i don't know what '\xff\xfe' is" and "so i want to escape it"? What is the purpose of "escaping" it?
It would help enormously if you gave a little more context than data[:2] == '\xff\xfe' (say a few line before and after) ... however it looks like it is testing whether the first two bytes of data could possibly represent an UTF-16 littleendian byte order mark. In that case you could do something like:
UTF16_LE_BOM = "\xff\xfe"
# much later
if data[:2] == UTF16_LE_BOM:
do_something()
A:
You cannot escape or encode an invalid string.
You should understand that you are working with strings and not byte streams and there are some characters you cannot accept in them, first of them being 0x00 - and also your example that is happening to be a BOM sequence.
So if you need to include non-valid strings characters (unicode or ascii) you will have to stop using strings for this.
Take a look at PEP-0358
|
how can i escape '\xff\xfe' to a readable string
|
i see a string in this code:
data[:2] == '\xff\xfe'
i don't know what '\xff\xfe' is,
so i want to escape it ,but not successful
import cgi
print cgi.escape('\xff\xfe')#print \xff\xfe
how can i get it.
thanks
|
[
"'\\xFF' means the byte with the hex value FF. '\\xff\\xfe' is a byte-order mark: http://en.wikipedia.org/wiki/Byte_order_mark\nYou could also represent it as two separate characters but that probably won't tell you anything useful.\n",
">>> print '\\xff\\xfe'.encode('string-escape')\n\\xff\\xfe\n\n",
"What is the connection between \"i don't know what '\\xff\\xfe' is\" and \"so i want to escape it\"? What is the purpose of \"escaping\" it?\nIt would help enormously if you gave a little more context than data[:2] == '\\xff\\xfe' (say a few line before and after) ... however it looks like it is testing whether the first two bytes of data could possibly represent an UTF-16 littleendian byte order mark. In that case you could do something like:\nUTF16_LE_BOM = \"\\xff\\xfe\"\n\n# much later\nif data[:2] == UTF16_LE_BOM:\n do_something()\n\n",
"You cannot escape or encode an invalid string.\nYou should understand that you are working with strings and not byte streams and there are some characters you cannot accept in them, first of them being 0x00 - and also your example that is happening to be a BOM sequence.\nSo if you need to include non-valid strings characters (unicode or ascii) you will have to stop using strings for this.\nTake a look at PEP-0358\n"
] |
[
11,
2,
2,
-1
] |
[] |
[] |
[
"encoding",
"escaping",
"python",
"unicode"
] |
stackoverflow_0001979171_encoding_escaping_python_unicode.txt
|
Q:
Upload file to a website via Python script
I want to upload a file from my computer to a file hoster like hotfile.com via a Python script. Because Hotfile is only offering a web-based upload service (no ftp).
I need Python first to login with my username and password and after that to upload the file. When the file transfer is over, I need the Download and Delete-link (which is generated right after the Upload has finished).
Is this even possible? If so, can anybody tell me how the script looks like or even give my hints how to build it?
Thanks
A:
For a similar task, I've previously used mechanize, with some quite success.
Note: although I was not uploading files, its documentation says that it is capable to handle also file uploads.
A:
Okay, you want to use Python to upload a file using HTTP "put". You will need to use a Python library that lets you do HTML stuff; a good choice might be httplib which is included with Python.
A Google search for "Python HTTP put" found me this:
http://inamidst.com/proj/put/put.py
This appears to be complete working code that solves your problem.
A:
You mention they do not offer FTP, but I went to their site and found the following:
How to upload with FTP?
ftp.hotfile.com user: your hotfile
username pass: your hotfile password
You can upload and make folders, but
cant rename,move files
Try it. If it works, using FTP from within Python will be a very simple task.
|
Upload file to a website via Python script
|
I want to upload a file from my computer to a file hoster like hotfile.com via a Python script. Because Hotfile is only offering a web-based upload service (no ftp).
I need Python first to login with my username and password and after that to upload the file. When the file transfer is over, I need the Download and Delete-link (which is generated right after the Upload has finished).
Is this even possible? If so, can anybody tell me how the script looks like or even give my hints how to build it?
Thanks
|
[
"For a similar task, I've previously used mechanize, with some quite success.\nNote: although I was not uploading files, its documentation says that it is capable to handle also file uploads.\n",
"Okay, you want to use Python to upload a file using HTTP \"put\". You will need to use a Python library that lets you do HTML stuff; a good choice might be httplib which is included with Python.\nA Google search for \"Python HTTP put\" found me this:\nhttp://inamidst.com/proj/put/put.py\nThis appears to be complete working code that solves your problem.\n",
"You mention they do not offer FTP, but I went to their site and found the following:\n\nHow to upload with FTP?\n ftp.hotfile.com user: your hotfile\n username pass: your hotfile password\n You can upload and make folders, but\n cant rename,move files\n\nTry it. If it works, using FTP from within Python will be a very simple task.\n"
] |
[
1,
1,
0
] |
[] |
[] |
[
"authentication",
"automation",
"file_upload",
"python"
] |
stackoverflow_0001993060_authentication_automation_file_upload_python.txt
|
Q:
How do I open all files of a certain type in Python and process them?
I'm trying to figure out how to make python go through a directory full of csv files, process each of the files and spit out a text file with a trimmed list of values.
In this example, I'm iterating through a CSV with lots of different types of columns but all I really want are the first name, last name, and keyword. I have a folder full of these csvs with different columns (except they all share first name, last name, and keyword somewhere in the csv). What's the best way to open that folder, go through each csv file, and then spit it all out as either its own csv file for just a text list as I have in the example below.
import csv
reader = csv.reader(open("keywords.csv"))
rownum = 0
headnum = 0
F = open('compiled.txt','w')
for row in reader:
if rownum == 0:
header = row;
for col in row:
if header[headnum]=='Keyword':
keywordnum=headnum;
elif header[headnum]=='First Name':
firstnamenum=headnum;
elif header[headnum]=='Last Name':
lastnamenum=headnum;
headnum +=1
else:
currentrow=row
print(currentrow[keywordnum] + '\n' + currentrow[firstnamenum] + '\n' + currentrow[lastnamenum])
F.write(currentrow[keywordnum] + '\n')
rownum +=1
A:
The best way is probably to use the shell's globbing ability, or alternatively the glob module of Python.
Shell (Linux, Unix)
Shell:
python myapp.py folder/*.csv
myapp.py:
import sys
for filename in sys.argv[1:]:
with open(filename) as f:
# do something with f
Windows (Or no shell available.)
import glob
for filename in glob.glob("folder/*.csv"):
with open(filename) as f:
# do something with f
Note: Python 2.5 needs from __future__ import with_statement
A:
The "get all the CSV files" part of the question has been answered several times (including by the OP), but the "get the right named columns" hasn't yet: csv.DictReader makes it trivial -- the "process one CSV file" loop becomes just:
reader = csv.DictReader(open(thecsvfilename))
for row in reader:
print('\n'.join(row['Keyword'], row['First Name'], row['Last Name']))
F.write(row['Keyword'] + '\n')
A:
A few suggestions:
You could keep the header indices for Keyword, First Name, and Last Name in a map instead of using separate variables. This would make it easier to modify the script later on.
You could use the list index() function instead of looping over the headers, e.g.:
if rownum == 0:
for header in ('Keyword', 'First Name', 'Last Name'):
header_index[header] = row.index(header)
You could use the glob module to grab the filenames, but gs is probably right that shell globbing is a better way to do it.
It might be better to use the csv module for writing the file as well; I think it handles escaping, so it would probably be more robust.
A:
I think the best way to process a bunch of files in a directory is with os.walk (documented in the Python os module docs here.
Here is an answer I wrote to another Python question, which includes working tested Python code to use os.walk to open a bunch of files. This version visits all subdirectories too, but it would be easy to modify it to just stay in the one directory.
Replace strings in files by Python
A:
And I've answered my own question again... I imported the os and glob modules to nab a path.
|
How do I open all files of a certain type in Python and process them?
|
I'm trying to figure out how to make python go through a directory full of csv files, process each of the files and spit out a text file with a trimmed list of values.
In this example, I'm iterating through a CSV with lots of different types of columns but all I really want are the first name, last name, and keyword. I have a folder full of these csvs with different columns (except they all share first name, last name, and keyword somewhere in the csv). What's the best way to open that folder, go through each csv file, and then spit it all out as either its own csv file for just a text list as I have in the example below.
import csv
reader = csv.reader(open("keywords.csv"))
rownum = 0
headnum = 0
F = open('compiled.txt','w')
for row in reader:
if rownum == 0:
header = row;
for col in row:
if header[headnum]=='Keyword':
keywordnum=headnum;
elif header[headnum]=='First Name':
firstnamenum=headnum;
elif header[headnum]=='Last Name':
lastnamenum=headnum;
headnum +=1
else:
currentrow=row
print(currentrow[keywordnum] + '\n' + currentrow[firstnamenum] + '\n' + currentrow[lastnamenum])
F.write(currentrow[keywordnum] + '\n')
rownum +=1
|
[
"The best way is probably to use the shell's globbing ability, or alternatively the glob module of Python.\nShell (Linux, Unix)\nShell:\n\npython myapp.py folder/*.csv\n\nmyapp.py:\nimport sys\nfor filename in sys.argv[1:]:\n with open(filename) as f:\n # do something with f\n\nWindows (Or no shell available.)\nimport glob\nfor filename in glob.glob(\"folder/*.csv\"):\n with open(filename) as f:\n # do something with f\n\nNote: Python 2.5 needs from __future__ import with_statement\n",
"The \"get all the CSV files\" part of the question has been answered several times (including by the OP), but the \"get the right named columns\" hasn't yet: csv.DictReader makes it trivial -- the \"process one CSV file\" loop becomes just:\nreader = csv.DictReader(open(thecsvfilename))\nfor row in reader:\n print('\\n'.join(row['Keyword'], row['First Name'], row['Last Name'])) \n F.write(row['Keyword'] + '\\n')\n\n",
"A few suggestions:\n\nYou could keep the header indices for Keyword, First Name, and Last Name in a map instead of using separate variables. This would make it easier to modify the script later on.\nYou could use the list index() function instead of looping over the headers, e.g.:\nif rownum == 0:\n for header in ('Keyword', 'First Name', 'Last Name'):\n header_index[header] = row.index(header)\n\nYou could use the glob module to grab the filenames, but gs is probably right that shell globbing is a better way to do it.\nIt might be better to use the csv module for writing the file as well; I think it handles escaping, so it would probably be more robust.\n\n",
"I think the best way to process a bunch of files in a directory is with os.walk (documented in the Python os module docs here.\nHere is an answer I wrote to another Python question, which includes working tested Python code to use os.walk to open a bunch of files. This version visits all subdirectories too, but it would be easy to modify it to just stay in the one directory.\nReplace strings in files by Python\n",
"And I've answered my own question again... I imported the os and glob modules to nab a path. \n"
] |
[
8,
4,
1,
1,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001992657_python.txt
|
Q:
A programming strategy to bypass the os thread limit?
The scenario: We have a python script that checks thousands of proxys simultaneously.
The program uses threads, 1 per proxy, to speed the process. When it reaches the 1007 thread, the script crashes because of the thread limit.
My solution is: A global variable that gets incremented when a thread spawns and decrements when a thread finishes. The function which spawns the threads monitors the variable so that the limit is not reached.
What will your solution be, friends?
Thanks for the answers.
A:
You want to do non-blocking I/O with the select module.
There are a couple of different specific techniques. select.select should work for every major platform. There are other variations that are more efficient (and could matter if you are checking tens of thousands of connections simultaneously) but you will then need to write the code for you specific platform.
A:
I've run into this situation before. Just make a pool of Tasks, and spawn a fixed number of threads that run an endless loop which grabs a Task from the pool, run it, and repeat. Essentially you're implementing your own thread abstraction and using the OS threads to implement it.
This does have drawbacks, the major one being that if your Tasks block for long periods of time they can prevent the execution of other Tasks. But it does let you create an unbounded number of Tasks, limited only by memory.
A:
Does Python have any sort of asynchronous IO functionality? That would be the preferred answer IMO - spawning an extra thread for each outbound connection isn't as neat as having a single thread which is effectively event-driven.
A:
Using different processes, and pipes to transfer data. Using threads in python is pretty lame. From what I heard, they don't actually run in parallel, even if you have a multi-core processor... But maybe it was fixed in python3.
A:
My solution is: A global variable that gets incremented when a thread spawns and decrements when a thread finishes. The function which spawns the threads monitors the variable so that the limit is not reached.
The standard way is to have each thread get next tasks in a loop instead of dying after processing just one. This way you don't have to keep track of the number of threads, since you just fire a fixed number of them. As a bonus, you save on thread creation/destruction.
A:
A counting semaphore should do the trick.
from socket import *
from threading import *
maxthreads = 1000
threads_sem = Semaphore(maxthreads)
class MyThread(Thread):
def __init__(self, conn, addr):
Thread.__init__(self)
self.conn = conn
self.addr = addr
def run(self):
try:
read = conn.recv(4096)
if read == 'go away\n':
global running
running = False
conn.close()
finally:
threads_sem.release()
sock = socket()
sock.bind(('0.0.0.0', 2323))
sock.listen(1)
running = True
while running:
conn, addr = sock.accept()
threads_sem.acquire()
MyThread(conn, addr).start()
A:
Make sure your threads get destroyed properly after they've been used or use a threadpool, although per what I see they're not that effective in Python
see here:
http://code.activestate.com/recipes/203871/
A:
Using the select module or a similar library would most probably be a more efficient solution, but that would require bigger architectural changes.
If you just want to limit the number of threads, a global counter should be fine, as long as you access it in a thread safe way.
A:
Be careful to minimize the default thread stack size. At least on Linux, the default limit puts severe restrictions on the number of created threads. Linux allocates a chunk of the process virtual address space to the stack (usually 10MB). 300 threads x 10MB stack allocation = 3GB of virtual address space dedicated to stack, and on a 32 bit system you have a 3GB limit. You can probably get away with much less.
A:
Twisted is a perfect fit for this problem. See http://twistedmatrix.com/documents/current/core/howto/clients.html for a tutorial on writing a client.
If you don't mind using alternate Python implmentations, Stackless has light-weight (non-native) threads. The only company I know doing much with it though is CCP--they use it for tasklets in their game on both the client and server. You still need to do async I/O with Stackless because if a thread blocks, the process blocks.
A:
As mentioned in another thread, why do you spawn off a new thread for each single operation? This is a classical producer - consumer problem, isn't it? Depending a bit on how you look at it, the proxy checkers might be comsumers or producers.
Anyway, the solution is to make a "queue" of "tasks" to process, and make the threads in a loop check if there are any more tasks to perform in the queue, and if there isn't, wait a predefined interval, and check again.
You should protect your queue with some locking mechanisms, i.e. semaphores, to prevent race conditions.
It's really not that difficult. But it requires a bit of thinking getting it right. Good luck!
|
A programming strategy to bypass the os thread limit?
|
The scenario: We have a python script that checks thousands of proxys simultaneously.
The program uses threads, 1 per proxy, to speed the process. When it reaches the 1007 thread, the script crashes because of the thread limit.
My solution is: A global variable that gets incremented when a thread spawns and decrements when a thread finishes. The function which spawns the threads monitors the variable so that the limit is not reached.
What will your solution be, friends?
Thanks for the answers.
|
[
"You want to do non-blocking I/O with the select module.\nThere are a couple of different specific techniques. select.select should work for every major platform. There are other variations that are more efficient (and could matter if you are checking tens of thousands of connections simultaneously) but you will then need to write the code for you specific platform.\n",
"I've run into this situation before. Just make a pool of Tasks, and spawn a fixed number of threads that run an endless loop which grabs a Task from the pool, run it, and repeat. Essentially you're implementing your own thread abstraction and using the OS threads to implement it.\nThis does have drawbacks, the major one being that if your Tasks block for long periods of time they can prevent the execution of other Tasks. But it does let you create an unbounded number of Tasks, limited only by memory.\n",
"Does Python have any sort of asynchronous IO functionality? That would be the preferred answer IMO - spawning an extra thread for each outbound connection isn't as neat as having a single thread which is effectively event-driven.\n",
"Using different processes, and pipes to transfer data. Using threads in python is pretty lame. From what I heard, they don't actually run in parallel, even if you have a multi-core processor... But maybe it was fixed in python3.\n",
"\nMy solution is: A global variable that gets incremented when a thread spawns and decrements when a thread finishes. The function which spawns the threads monitors the variable so that the limit is not reached. \n\nThe standard way is to have each thread get next tasks in a loop instead of dying after processing just one. This way you don't have to keep track of the number of threads, since you just fire a fixed number of them. As a bonus, you save on thread creation/destruction.\n",
"A counting semaphore should do the trick.\nfrom socket import *\nfrom threading import *\n\nmaxthreads = 1000\nthreads_sem = Semaphore(maxthreads)\n\nclass MyThread(Thread):\n def __init__(self, conn, addr):\n Thread.__init__(self)\n self.conn = conn\n self.addr = addr\n def run(self):\n try:\n read = conn.recv(4096)\n if read == 'go away\\n':\n global running\n running = False\n conn.close()\n finally:\n threads_sem.release()\n\nsock = socket()\nsock.bind(('0.0.0.0', 2323))\nsock.listen(1)\nrunning = True\nwhile running:\n conn, addr = sock.accept()\n threads_sem.acquire()\n MyThread(conn, addr).start()\n\n",
"Make sure your threads get destroyed properly after they've been used or use a threadpool, although per what I see they're not that effective in Python\nsee here:\nhttp://code.activestate.com/recipes/203871/\n",
"Using the select module or a similar library would most probably be a more efficient solution, but that would require bigger architectural changes.\nIf you just want to limit the number of threads, a global counter should be fine, as long as you access it in a thread safe way.\n",
"Be careful to minimize the default thread stack size. At least on Linux, the default limit puts severe restrictions on the number of created threads. Linux allocates a chunk of the process virtual address space to the stack (usually 10MB). 300 threads x 10MB stack allocation = 3GB of virtual address space dedicated to stack, and on a 32 bit system you have a 3GB limit. You can probably get away with much less.\n",
"Twisted is a perfect fit for this problem. See http://twistedmatrix.com/documents/current/core/howto/clients.html for a tutorial on writing a client.\nIf you don't mind using alternate Python implmentations, Stackless has light-weight (non-native) threads. The only company I know doing much with it though is CCP--they use it for tasklets in their game on both the client and server. You still need to do async I/O with Stackless because if a thread blocks, the process blocks.\n",
"As mentioned in another thread, why do you spawn off a new thread for each single operation? This is a classical producer - consumer problem, isn't it? Depending a bit on how you look at it, the proxy checkers might be comsumers or producers.\nAnyway, the solution is to make a \"queue\" of \"tasks\" to process, and make the threads in a loop check if there are any more tasks to perform in the queue, and if there isn't, wait a predefined interval, and check again.\nYou should protect your queue with some locking mechanisms, i.e. semaphores, to prevent race conditions.\nIt's really not that difficult. But it requires a bit of thinking getting it right. Good luck!\n"
] |
[
5,
4,
3,
2,
2,
2,
1,
1,
1,
1,
1
] |
[] |
[] |
[
"multithreading",
"python"
] |
stackoverflow_0001993079_multithreading_python.txt
|
Q:
SocketServer client side socket error during third send() on winXP
I'm struggling with following error:
"socket.error: [10053] 'Software
caused connection abort'"
Traceback (most recent call last): ...
self.send(json.dumps([0x02, subItems])+"\n") ...
sent = self.handler.send(data) socket.error: [Errno 10053]
I established server properely, I can connect to it, send "hello" message, then I can send one more 0x1 type message. Next client actions are not being seen by server side. Client program throws above socket.error .
import SocketServer
class ThreadedTCPRequestHandler(SocketServer.StreamRequestHandler):
def handle(self):
#data = json.loads(self.request.recv(1024))
if(self.request in subengine.sub.get_all_sub()):
pass
else:
#login = json.loads(self.request.recv(1024))
login = json.loads(self.rfile.readline().strip())
logging.debug("User : %s connected" % login )
data = json.loads(self.rfile.readline().strip())
if(data[0]==0x1): # subscribe
logging.info("subscribe message received, from %d" % self.request.fileno())
logging.info("symbols to subscribe: %s" % data[1])
elif (data[0] == 0x2): # unsubscribe
logging.info("unsubscribe message received")
else:
pass
# def finish(self):
# logging.info("terminating connection")
class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
pass
server = ThreadedTCPServer(('localhost',5555), ThreadedTCPRequestHandler)
server_thread = threading.Thread(target=server.serve_forever)
server_thread.setDaemon(True)
server_thread.start()
client side code example:
class Client:
handler = None
def __init__(self, uname = '', host = 'localhost', port = 0, sock = None):
if sock is None:
self.handler = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.host = host
self.port = port
self.uname = uname
def feed_conection(self):
self.handler.connect((self.host, self.port))
if(self.handler != 0):
self.handler.send(json.dumps(self.uname)+"\n")
else:
print ("Nie udalo sie polaczyc")
def sub(self, subItems):
self.send(json.dumps([0x01, subItems])+"\n")
def unsub(self, subItems):
self.send(json.dumps([0x02, subItems])+"\n")
def send(self, data):
data_len = len(data)
total_sent = 0
while(total_sent < data_len):
sent = self.handler.send(data)
if not sent:
break
data = data[sent:]
total_sent += sent
A:
If this, as you report, is really how your main server code ends...:
server_thread.setDaemon(True)
server_thread.start()
then your code is saying: let server_thread just die when the main thread dies, let server_thread start, and now let the main thread die -- i.e., are you really "falling off the end" right after starting a daemonized thread? That's just wrong -- as soon as the OS switches back to your main thread, boom, everything on the server side just dies, exactly as you programmed it to (so of course client code trying to continue a conversation with that server will see problems!-). Why are you making server_thread a daemon and yet letting the main thread just end? Maybe you're not really posting the actual code you're using...?
|
SocketServer client side socket error during third send() on winXP
|
I'm struggling with following error:
"socket.error: [10053] 'Software
caused connection abort'"
Traceback (most recent call last): ...
self.send(json.dumps([0x02, subItems])+"\n") ...
sent = self.handler.send(data) socket.error: [Errno 10053]
I established server properely, I can connect to it, send "hello" message, then I can send one more 0x1 type message. Next client actions are not being seen by server side. Client program throws above socket.error .
import SocketServer
class ThreadedTCPRequestHandler(SocketServer.StreamRequestHandler):
def handle(self):
#data = json.loads(self.request.recv(1024))
if(self.request in subengine.sub.get_all_sub()):
pass
else:
#login = json.loads(self.request.recv(1024))
login = json.loads(self.rfile.readline().strip())
logging.debug("User : %s connected" % login )
data = json.loads(self.rfile.readline().strip())
if(data[0]==0x1): # subscribe
logging.info("subscribe message received, from %d" % self.request.fileno())
logging.info("symbols to subscribe: %s" % data[1])
elif (data[0] == 0x2): # unsubscribe
logging.info("unsubscribe message received")
else:
pass
# def finish(self):
# logging.info("terminating connection")
class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
pass
server = ThreadedTCPServer(('localhost',5555), ThreadedTCPRequestHandler)
server_thread = threading.Thread(target=server.serve_forever)
server_thread.setDaemon(True)
server_thread.start()
client side code example:
class Client:
handler = None
def __init__(self, uname = '', host = 'localhost', port = 0, sock = None):
if sock is None:
self.handler = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.host = host
self.port = port
self.uname = uname
def feed_conection(self):
self.handler.connect((self.host, self.port))
if(self.handler != 0):
self.handler.send(json.dumps(self.uname)+"\n")
else:
print ("Nie udalo sie polaczyc")
def sub(self, subItems):
self.send(json.dumps([0x01, subItems])+"\n")
def unsub(self, subItems):
self.send(json.dumps([0x02, subItems])+"\n")
def send(self, data):
data_len = len(data)
total_sent = 0
while(total_sent < data_len):
sent = self.handler.send(data)
if not sent:
break
data = data[sent:]
total_sent += sent
|
[
"If this, as you report, is really how your main server code ends...:\nserver_thread.setDaemon(True)\nserver_thread.start()\n\nthen your code is saying: let server_thread just die when the main thread dies, let server_thread start, and now let the main thread die -- i.e., are you really \"falling off the end\" right after starting a daemonized thread? That's just wrong -- as soon as the OS switches back to your main thread, boom, everything on the server side just dies, exactly as you programmed it to (so of course client code trying to continue a conversation with that server will see problems!-). Why are you making server_thread a daemon and yet letting the main thread just end? Maybe you're not really posting the actual code you're using...?\n"
] |
[
0
] |
[] |
[] |
[
"python",
"sockets"
] |
stackoverflow_0001993243_python_sockets.txt
|
Q:
Python web framework with low barrier to entry
I am looking for a LAMPish/WAMPish experience.
Something very transparent. Write the script, hit F5 and see the results. Very little, if any abstraction.
SQLAlchemy and (maybe) some simple templating engine will be used.
I need simple access to the environment - similar to the PHP way. Something like the COOKIE, SESSION, POST, GET objects.
I don't want to write a middleware layer just to get some web serving up and running. And I do not want to deal with specifics of CGI.
This is not meant for a very complex project and it is for beginning programmers and/or beginning Python programmers.
An MVC framework is not out of the question. ASP.NET MVC is nicely done IMO. One thing I liked is that POSTed data is automatically cast to data model objects if so desired.
Can you help me out here?
Thanks!
PS: I did not really find anything matching these criteria in older posts.
A:
CherryPy might be what you need. It transparently maps URLs onto Python functions, and handles all the cookie and session stuff (and of course the POST / GET parameters for you).
It's not a full-stack solution like Django or Rails. On the other hand, that means that it doesn't lump you with a template engine or ORM you don't like; you're free to use whatever you like.
It includes a WSGI compliant web server, so you don't even need Apache.
A:
What you're describing most resembles Pylons, it seems to me. However, the number of web frameworks in/for Python is huge -- see this page for an attempt to list and VERY briefly characterize each and every one of them!-)
A:
For low barrier to entry, web.py is very very light and simple.
Features:
easy (dev) deploy... copy web.py folder into your app directory, then start the server
regex-based url mapping
very simple class mappings
built-in server (most frameworks have this of course)
very thin (as measured by lines of code, at least) layer over python application code.
Here is its hello world:
import web
urls = (
'/(.*)', 'hello'
)
app = web.application(urls, globals())
class hello:
def GET(self, name):
if not name:
name = 'world'
return 'Hello, ' + name + '!'
if __name__ == "__main__":
app.run()
As much as I like Werkzeug conceptually, writing wsgi plumbing in the Hello, World! is deeply unpleasant, and totally gets in the way of actually demoing an app.
That said, web.py isn't perfect, and for big jobs, it's probably not the right tool, since:
routes style systems are (imho) better than pure regex ones
integrating web.py with other middlewares might be adventurous
A:
Look at:
WSGI, the standard Python API for HTTP servers to call Python code.
Django, a popular, feature-rich, well documented Python web framework
web.py, a minimal Python web framework
A:
Have you looked into the Django web framework? Its an MVC framework written in python, and is relatively simple to set up and get started. You can run it with nothing but python, as it can use SQLite and its own development server, or you can set it up to use MySQL and Apache if you'd like.
Pylons is another framework that supports SQLAlchemy for models. I've never used it but it seems promising.
A:
Don't forget Bottle. It is a single-file micro web framework with no dependencies and very easy to use. Here is an "Hello world" example:
from bottle import route, run
@route('/')
def index():
return 'Hello World!'
run(host='localhost', port=8080)
And here an example for accessing POST variables (cookies and GET vars are similar)
from bottle import route, request
@route('/submit', method='POST')
def submit():
name = request.POST.get('name', 'World')
return 'Hello %s!' % name
A:
Check out web2py. It runs out of the box with no configuration - even from a USB stick. The template language is pure Python and you can develop your entire app through the browser editor (although I find vim faster ;)
|
Python web framework with low barrier to entry
|
I am looking for a LAMPish/WAMPish experience.
Something very transparent. Write the script, hit F5 and see the results. Very little, if any abstraction.
SQLAlchemy and (maybe) some simple templating engine will be used.
I need simple access to the environment - similar to the PHP way. Something like the COOKIE, SESSION, POST, GET objects.
I don't want to write a middleware layer just to get some web serving up and running. And I do not want to deal with specifics of CGI.
This is not meant for a very complex project and it is for beginning programmers and/or beginning Python programmers.
An MVC framework is not out of the question. ASP.NET MVC is nicely done IMO. One thing I liked is that POSTed data is automatically cast to data model objects if so desired.
Can you help me out here?
Thanks!
PS: I did not really find anything matching these criteria in older posts.
|
[
"CherryPy might be what you need. It transparently maps URLs onto Python functions, and handles all the cookie and session stuff (and of course the POST / GET parameters for you).\nIt's not a full-stack solution like Django or Rails. On the other hand, that means that it doesn't lump you with a template engine or ORM you don't like; you're free to use whatever you like.\nIt includes a WSGI compliant web server, so you don't even need Apache.\n",
"What you're describing most resembles Pylons, it seems to me. However, the number of web frameworks in/for Python is huge -- see this page for an attempt to list and VERY briefly characterize each and every one of them!-)\n",
"For low barrier to entry, web.py is very very light and simple. \nFeatures:\n\neasy (dev) deploy... copy web.py folder into your app directory, then start the server\nregex-based url mapping\nvery simple class mappings\nbuilt-in server (most frameworks have this of course)\nvery thin (as measured by lines of code, at least) layer over python application code. \n\nHere is its hello world:\nimport web\n\nurls = (\n '/(.*)', 'hello'\n)\napp = web.application(urls, globals())\n\nclass hello: \n def GET(self, name):\n if not name: \n name = 'world'\n return 'Hello, ' + name + '!'\n\nif __name__ == \"__main__\":\n app.run()\n\nAs much as I like Werkzeug conceptually, writing wsgi plumbing in the Hello, World! is deeply unpleasant, and totally gets in the way of actually demoing an app. \nThat said, web.py isn't perfect, and for big jobs, it's probably not the right tool, since:\n\nroutes style systems are (imho) better than pure regex ones\nintegrating web.py with other middlewares might be adventurous\n\n",
"Look at:\n\nWSGI, the standard Python API for HTTP servers to call Python code.\nDjango, a popular, feature-rich, well documented Python web framework\nweb.py, a minimal Python web framework\n\n",
"Have you looked into the Django web framework? Its an MVC framework written in python, and is relatively simple to set up and get started. You can run it with nothing but python, as it can use SQLite and its own development server, or you can set it up to use MySQL and Apache if you'd like.\nPylons is another framework that supports SQLAlchemy for models. I've never used it but it seems promising.\n",
"Don't forget Bottle. It is a single-file micro web framework with no dependencies and very easy to use. Here is an \"Hello world\" example:\nfrom bottle import route, run\n@route('/')\ndef index():\n return 'Hello World!'\nrun(host='localhost', port=8080)\n\nAnd here an example for accessing POST variables (cookies and GET vars are similar)\nfrom bottle import route, request\n@route('/submit', method='POST')\ndef submit():\n name = request.POST.get('name', 'World')\n return 'Hello %s!' % name\n\n",
"Check out web2py. It runs out of the box with no configuration - even from a USB stick. The template language is pure Python and you can develop your entire app through the browser editor (although I find vim faster ;)\n"
] |
[
7,
5,
5,
1,
1,
1,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0000948815_python.txt
|
Q:
Possible to send variables to the index page in CherryPy?
For instance I want to visit http://localhost:8080/?var=val or similar with POST, but I get a 500 server error:
500 Internal Server Error
The server encountered an unexpected condition which prevented it from fulfilling the request.
Traceback (most recent call last):
File "c:\python26\lib\site-packages\cherrypy\_cprequest.py", line 606, in respond
cherrypy.response.body = self.handler()
File "c:\python26\lib\site-packages\cherrypy\_cpdispatch.py", line 25, in __call__
return self.callable(*self.args, **self.kwargs)
TypeError: index() takes no arguments (1 given)
Powered by CherryPy 3.1.2
A:
It is definitely possible.
Here is an example (adapted from the CherryPy tutorial):
<form action="indexPostHandler" method="post">
<p>Enter a value:</p>
<input type="text" name="val" value=""/>
<p><input type="submit" value="Login"/></p>
</form>
And, in your index, you can use something like the following to process the request:
class Root:
# create form here
def indexPostHandler(self, val=None):
# do something with val here
...
|
Possible to send variables to the index page in CherryPy?
|
For instance I want to visit http://localhost:8080/?var=val or similar with POST, but I get a 500 server error:
500 Internal Server Error
The server encountered an unexpected condition which prevented it from fulfilling the request.
Traceback (most recent call last):
File "c:\python26\lib\site-packages\cherrypy\_cprequest.py", line 606, in respond
cherrypy.response.body = self.handler()
File "c:\python26\lib\site-packages\cherrypy\_cpdispatch.py", line 25, in __call__
return self.callable(*self.args, **self.kwargs)
TypeError: index() takes no arguments (1 given)
Powered by CherryPy 3.1.2
|
[
"It is definitely possible.\nHere is an example (adapted from the CherryPy tutorial):\n<form action=\"indexPostHandler\" method=\"post\">\n <p>Enter a value:</p>\n <input type=\"text\" name=\"val\" value=\"\"/>\n <p><input type=\"submit\" value=\"Login\"/></p>\n</form>\n\nAnd, in your index, you can use something like the following to process the request:\nclass Root:\n # create form here\n def indexPostHandler(self, val=None):\n # do something with val here\n ...\n\n"
] |
[
1
] |
[] |
[] |
[
"cherrypy",
"python"
] |
stackoverflow_0001993565_cherrypy_python.txt
|
Q:
Pass XML fragments as stylesheet paramters with lxml?
I'm starting to use lxml in Python for processing XML/XSL documents, and in general it seems very straight forward. However, I'm not able to find a way to pass an XML fragment as a stylesheet parameter when doing a translation.
For example, in PHP it is possible to pass DOMDocument XML fragments as stylesheet parameters, so that one can have complex params available within the stylesheet:
$xml = new DOMDocument();
$xml->loadXML('<root><node/></root>');
$xsl = new DOMDocument();
$xsl->loadXML('<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" omit-xml-declaration="yes"
indent="yes" media-type="text/html" />
<xsl:param name="a" />
<xsl:template match="/">
<html>
<body>
<xsl:value-of select="$a/foo/bar/text()" />
</body>
</html>
</xsl:template>
</xsl:stylesheet>');
$fragment = new DOMDocument();
$fragment->loadXML('<foo><bar>baz</bar></foo>');
$proc = new XSLTProcessor;
$proc->registerPHPFunctions();
$proc->importStyleSheet($xsl);
$param_ns = '';
$param_name = 'a';
$proc->setParameter($param_ns, $param_name, $fragment->documentElement);
Which will result in:
<html>
<body>
baz
</body>
</html>
How does one accomplish this using lxml?
A:
As far as I know, you can only use xpath expressions (or result of the etree.XSLT.strparam() method for strings with quotes) in lxml (at the moment anyway).
However, because you can use xpath expressions, that means you could "work around" by using a custom xpath extension function that returns the Element in question. Another way could be to make use of the standard xpath document() function, and use a custom resolver
A:
You can use a python extension function to return an etree.XML document to xslt. Here's the bare minimum example. It registers a global namespace (uri:params), associations a function with the "params" method in that namespace. That's used by the stylesheet to reach the extension function. Don't forget the xmlns:ptest declaration in the stylesheet.
hmm, looks like I'm going to have to put in html entities to represent < symbol in this code. I have also put it in http://bkc.pastebin.com/f67461ccc
from lxml import etree
stylesheet = etree.XML("""
<xsl:stylesheet version="1.0"
xmlns:ptest="uri:params"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:variable name="params" select="ptest:params()" />
<xsl:template match="/">
<name_is><xsl:value-of select="$params/name" /></name_is>
</xsl:template>
</xsl:stylesheet>
""")
def params(context):
# this is the extension function, it returns
# a etree.XML document
return etree.XML(
"""<params>
<name>fred
</params>"""
)
def test():
"""test passing document to xslt via python extension function
>>> test()
<?xml version="1.0"?>
<name_is xmlns:ptest="uri:params">fred
<BLANKLINE>
"""
ns = etree.FunctionNamespace('uri:params') # register global namespace
ns['params'] = params # define function in new global namespace
transform = etree.XSLT(stylesheet)
print str(transform(etree.XML("""<source />""")))
if __name__ == "__main__":
import doctest
doctest.testmod()
A:
I believe what you're looking for can be performed using lxml.etree.XSLT. Good examples can be found in the XSLT section on the page documenting XPath and XSLT with lxml.
|
Pass XML fragments as stylesheet paramters with lxml?
|
I'm starting to use lxml in Python for processing XML/XSL documents, and in general it seems very straight forward. However, I'm not able to find a way to pass an XML fragment as a stylesheet parameter when doing a translation.
For example, in PHP it is possible to pass DOMDocument XML fragments as stylesheet parameters, so that one can have complex params available within the stylesheet:
$xml = new DOMDocument();
$xml->loadXML('<root><node/></root>');
$xsl = new DOMDocument();
$xsl->loadXML('<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" omit-xml-declaration="yes"
indent="yes" media-type="text/html" />
<xsl:param name="a" />
<xsl:template match="/">
<html>
<body>
<xsl:value-of select="$a/foo/bar/text()" />
</body>
</html>
</xsl:template>
</xsl:stylesheet>');
$fragment = new DOMDocument();
$fragment->loadXML('<foo><bar>baz</bar></foo>');
$proc = new XSLTProcessor;
$proc->registerPHPFunctions();
$proc->importStyleSheet($xsl);
$param_ns = '';
$param_name = 'a';
$proc->setParameter($param_ns, $param_name, $fragment->documentElement);
Which will result in:
<html>
<body>
baz
</body>
</html>
How does one accomplish this using lxml?
|
[
"As far as I know, you can only use xpath expressions (or result of the etree.XSLT.strparam() method for strings with quotes) in lxml (at the moment anyway).\nHowever, because you can use xpath expressions, that means you could \"work around\" by using a custom xpath extension function that returns the Element in question. Another way could be to make use of the standard xpath document() function, and use a custom resolver\n",
"You can use a python extension function to return an etree.XML document to xslt. Here's the bare minimum example. It registers a global namespace (uri:params), associations a function with the \"params\" method in that namespace. That's used by the stylesheet to reach the extension function. Don't forget the xmlns:ptest declaration in the stylesheet.\nhmm, looks like I'm going to have to put in html entities to represent < symbol in this code. I have also put it in http://bkc.pastebin.com/f67461ccc\n\nfrom lxml import etree\n\nstylesheet = etree.XML(\"\"\"\n <xsl:stylesheet version=\"1.0\"\n xmlns:ptest=\"uri:params\"\n xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\n <xsl:variable name=\"params\" select=\"ptest:params()\" />\n <xsl:template match=\"/\">\n <name_is><xsl:value-of select=\"$params/name\" /></name_is>\n </xsl:template>\n </xsl:stylesheet>\n\"\"\")\n\ndef params(context):\n # this is the extension function, it returns\n # a etree.XML document\n return etree.XML(\n \"\"\"<params>\n <name>fred\n </params>\"\"\"\n )\n\n\ndef test():\n \"\"\"test passing document to xslt via python extension function\n\n >>> test()\n <?xml version=\"1.0\"?>\n <name_is xmlns:ptest=\"uri:params\">fred\n <BLANKLINE>\n \"\"\" \n ns = etree.FunctionNamespace('uri:params') # register global namespace\n ns['params'] = params # define function in new global namespace\n transform = etree.XSLT(stylesheet)\n print str(transform(etree.XML(\"\"\"<source />\"\"\")))\n\nif __name__ == \"__main__\":\n import doctest\n doctest.testmod()\n\n",
"I believe what you're looking for can be performed using lxml.etree.XSLT. Good examples can be found in the XSLT section on the page documenting XPath and XSLT with lxml.\n"
] |
[
1,
1,
0
] |
[] |
[] |
[
"lxml",
"python",
"xml",
"xslt"
] |
stackoverflow_0001756559_lxml_python_xml_xslt.txt
|
Q:
if my condition false how to do a statement one time only in python
is there any way to make this logic:
I need to make a statement one time only if the condition is false as below:
while 1:
statement1
statement2
if condition: --condition is true here
statement3
else --condition is false here
statement3 --I need to do this "statement3" one time only
if another condition:
break
what I mean that I need to send my data if speed > 3 else send my data only one time.
any help, please
I solved it. I just need to add extra "neverdone = True" to the solution of "Alex Martelli"
neverdone = True
while 1:
statement1
statement2
if condition:
statement3
neverdone = True
elif neverdone:
neverdone = False
statement3
if anothercondition:
break
many thanks to Alex Martelli.
A:
add a boolean variable:
neverdone = True
while 1:
statement1
statement2
if condition:
statement3
elif neverdone:
neverdone = False
statement3
if anothercondition:
break
A:
Couldn't you just put a break statement after statement3? That would mean that it would run once and then the while loop would exit.
A:
you can use a flag, or write something like:
while 1:
state1()
state2()
state3()
if not condition:
state3 = lambda : None
if another_condition:
break
Thise will destroy the state3 when the condition is false.
A:
If you want to do something once don't put it in a infinite loop (duh)
def dostuff():
statement1
statement2
if condition:
statement3
dostuff()
if not contition:
statement3
while True:
dostuff()
if another condition:
break
|
if my condition false how to do a statement one time only in python
|
is there any way to make this logic:
I need to make a statement one time only if the condition is false as below:
while 1:
statement1
statement2
if condition: --condition is true here
statement3
else --condition is false here
statement3 --I need to do this "statement3" one time only
if another condition:
break
what I mean that I need to send my data if speed > 3 else send my data only one time.
any help, please
I solved it. I just need to add extra "neverdone = True" to the solution of "Alex Martelli"
neverdone = True
while 1:
statement1
statement2
if condition:
statement3
neverdone = True
elif neverdone:
neverdone = False
statement3
if anothercondition:
break
many thanks to Alex Martelli.
|
[
"add a boolean variable:\nneverdone = True\nwhile 1:\n statement1\n statement2\n if condition:\n statement3\n elif neverdone:\n neverdone = False\n statement3\n if anothercondition:\n break\n\n",
"Couldn't you just put a break statement after statement3? That would mean that it would run once and then the while loop would exit.\n",
"you can use a flag, or write something like:\nwhile 1:\n state1()\n state2()\n state3()\n if not condition:\n state3 = lambda : None\n if another_condition:\n break\n\nThise will destroy the state3 when the condition is false.\n",
"If you want to do something once don't put it in a infinite loop (duh)\ndef dostuff():\n statement1\n statement2\n if condition:\n statement3\n\ndostuff()\n\nif not contition:\n statement3\n\nwhile True:\n dostuff()\n if another condition:\n break\n\n"
] |
[
3,
0,
0,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001993637_python.txt
|
Q:
translate this block of C physics code to python
I have only learnt python for for few months and totally a newb in C, I got a C code from the web, and I am dying to study it. But i only understand python language, so would someone can help to translate the following code to python would be great. Thanks in advance!
for(i=0; i<n; i++) { /* Foreach particle "i" ... */
ax=0.0;
ay=0.0;
az=0.0;
for(j=0; j<n; j++) { /* Loop over all particles "j" */
dx=x[j]-x[i];
dy=y[j]-y[i];
dz=yz[j]-z[i];
invr = 1.0/sqrt(dx*dx + dy*dy + dz*dz + eps);
invr3 = invr*invr*invr;
f=m[j]*invr3;
ax += f*dx; /* accumulate the acceleration from gravitational attraction */
ay += f*dy;
az += f*dx;
}
xnew[i] = x[i] + dt*vx[i] + 0.5*dt*dt*ax; /* update position of particle "i" */
ynew[i] = y[i] + dt*vy[i] + 0.5*dt*dt*ay;
znew[i] = z[i] + dt*vz[i] + 0.5*dt*dt*az;
vx[i] += dt*ax; /* update velocity of particle "i" */
vy[i] += dt*ay;
vz[i] += dt*az;
}
Thanks again!
A:
Treat this as an ideal opportunity to learn some C, the syntax is not so unlike Python.
It will serve you well
A:
Here's a literal translation
(Edit: was a literal translation but there are some anomalies in the original C code which @hughdbrown pointed out in comments -- looks like you're trying to study this subject from code so utterly broken it wouldn't even compile, which seems very unwise on your part, so, anyway, I'm taking the liberty of fixing the apparent errors and absurdities of the original C code in this Python "almost"-literal translation...):
import math
for i in range(n):
ax = ay = az = 0.0
for j in range(n):
dx=x[j]-x[i]
dy=y[j]-y[i]
dz=z[j]-z[i]
invr = 1.0/math.sqrt(dx*dx + dy*dy + dz*dz + eps)
f=m[j]*invr**3
ax += f*dx # accumulate the acceleration from gravitational attraction
ay += f*dy
az += f*dz
xnew[i] = x[i] + dt*vx[i] + 0.5*dt*dt*ax
ynew[i] = y[i] + dt*vy[i] + 0.5*dt*dt*ay
znew[i] = z[i] + dt*vz[i] + 0.5*dt*dt*az
vx[i] += dt*ax # update velocity of particle "i"
vy[i] += dt*ay
vz[i] += dt*az
Of course it assumes lists x, y, z, ... vx, vy, vz are all pre-existing and of the same length n, just like the C code snippet assumes for the same-named arrays.
A:
Honestly, except for the loops this is already very close to python .. for(j=0; j < n; ++j) simply maintains the loop counter j, which is incremented after each loop iteration. The loop runs for all 0 <= j < n. Good luck.
A:
Incidentally this code is extremely buggy, assuming the intent is to numerically integrate the n-body problem.
The loop to calculate the force doesn't correctly handle the case i == j, resulting in a very large (depending on the size of eps) spurious error being added to each force.
Speaking of eps, for well-posed problems it serves no purpose except to add error to your force calculation.
The update rules for position and velocity are a strange mix of Velocity Verlet and Forward Euler, and the resulting integrator likely has all of the bad properties of the latter, at best. Velocity Verlet, being second-order, explicit, and symplectic, will give much better results for negligible cost and should be used here instead.
|
translate this block of C physics code to python
|
I have only learnt python for for few months and totally a newb in C, I got a C code from the web, and I am dying to study it. But i only understand python language, so would someone can help to translate the following code to python would be great. Thanks in advance!
for(i=0; i<n; i++) { /* Foreach particle "i" ... */
ax=0.0;
ay=0.0;
az=0.0;
for(j=0; j<n; j++) { /* Loop over all particles "j" */
dx=x[j]-x[i];
dy=y[j]-y[i];
dz=yz[j]-z[i];
invr = 1.0/sqrt(dx*dx + dy*dy + dz*dz + eps);
invr3 = invr*invr*invr;
f=m[j]*invr3;
ax += f*dx; /* accumulate the acceleration from gravitational attraction */
ay += f*dy;
az += f*dx;
}
xnew[i] = x[i] + dt*vx[i] + 0.5*dt*dt*ax; /* update position of particle "i" */
ynew[i] = y[i] + dt*vy[i] + 0.5*dt*dt*ay;
znew[i] = z[i] + dt*vz[i] + 0.5*dt*dt*az;
vx[i] += dt*ax; /* update velocity of particle "i" */
vy[i] += dt*ay;
vz[i] += dt*az;
}
Thanks again!
|
[
"Treat this as an ideal opportunity to learn some C, the syntax is not so unlike Python.\nIt will serve you well\n",
"Here's a literal translation\n(Edit: was a literal translation but there are some anomalies in the original C code which @hughdbrown pointed out in comments -- looks like you're trying to study this subject from code so utterly broken it wouldn't even compile, which seems very unwise on your part, so, anyway, I'm taking the liberty of fixing the apparent errors and absurdities of the original C code in this Python \"almost\"-literal translation...):\nimport math\n\nfor i in range(n):\n ax = ay = az = 0.0\n for j in range(n):\n dx=x[j]-x[i]\n dy=y[j]-y[i]\n dz=z[j]-z[i]\n invr = 1.0/math.sqrt(dx*dx + dy*dy + dz*dz + eps)\n f=m[j]*invr**3\n ax += f*dx # accumulate the acceleration from gravitational attraction\n ay += f*dy\n az += f*dz\n xnew[i] = x[i] + dt*vx[i] + 0.5*dt*dt*ax\n ynew[i] = y[i] + dt*vy[i] + 0.5*dt*dt*ay\n znew[i] = z[i] + dt*vz[i] + 0.5*dt*dt*az\n vx[i] += dt*ax # update velocity of particle \"i\"\n vy[i] += dt*ay\n vz[i] += dt*az\n\nOf course it assumes lists x, y, z, ... vx, vy, vz are all pre-existing and of the same length n, just like the C code snippet assumes for the same-named arrays.\n",
"Honestly, except for the loops this is already very close to python .. for(j=0; j < n; ++j) simply maintains the loop counter j, which is incremented after each loop iteration. The loop runs for all 0 <= j < n. Good luck.\n",
"Incidentally this code is extremely buggy, assuming the intent is to numerically integrate the n-body problem.\n\nThe loop to calculate the force doesn't correctly handle the case i == j, resulting in a very large (depending on the size of eps) spurious error being added to each force.\nSpeaking of eps, for well-posed problems it serves no purpose except to add error to your force calculation.\nThe update rules for position and velocity are a strange mix of Velocity Verlet and Forward Euler, and the resulting integrator likely has all of the bad properties of the latter, at best. Velocity Verlet, being second-order, explicit, and symplectic, will give much better results for negligible cost and should be used here instead.\n\n"
] |
[
7,
2,
1,
1
] |
[] |
[] |
[
"c",
"python"
] |
stackoverflow_0001993580_c_python.txt
|
Q:
How do I trust the order of a Python dictionary?
I'm trying to make a dictionary in Python that I can sort through but it seems to change order when I add new things. Is there a way around this?
A:
A standard Dictionary does not impose an ordering, it's simply a lookup.
You want an Ordered Dictionary or Ordered Dictionary.
A:
Python dicts are built as hash tables -- great performance, but ordering is essentially arbitrary and unpredictable. If your need for predictably-ordered walks are occasional, and based on keys or values, the sorted built-in is very handy:
# print all entries in sorted key order
for k in sorted(d): print k, d[k]
# print all entries in reverse-sorted value order
for k in sorted(d, key=d.get, reverse=True): print k, d[k]
# given all keys are strings, print in case-insensitive sorted order
for k in sorted(d, key=str.lower): print k, d[k]
and so forth. If you needs are different (e.g., keep track of the respective times at which keys are inserted, or their values altered, and so forth), the "ordered dictionaries" suggested in other answers will serve you better (but never with the awesome raw performance of a true dict!-).
|
How do I trust the order of a Python dictionary?
|
I'm trying to make a dictionary in Python that I can sort through but it seems to change order when I add new things. Is there a way around this?
|
[
"A standard Dictionary does not impose an ordering, it's simply a lookup.\nYou want an Ordered Dictionary or Ordered Dictionary.\n",
"Python dicts are built as hash tables -- great performance, but ordering is essentially arbitrary and unpredictable. If your need for predictably-ordered walks are occasional, and based on keys or values, the sorted built-in is very handy:\n# print all entries in sorted key order\nfor k in sorted(d): print k, d[k]\n\n# print all entries in reverse-sorted value order\nfor k in sorted(d, key=d.get, reverse=True): print k, d[k]\n\n# given all keys are strings, print in case-insensitive sorted order\nfor k in sorted(d, key=str.lower): print k, d[k]\n\nand so forth. If you needs are different (e.g., keep track of the respective times at which keys are inserted, or their values altered, and so forth), the \"ordered dictionaries\" suggested in other answers will serve you better (but never with the awesome raw performance of a true dict!-).\n"
] |
[
9,
5
] |
[] |
[] |
[
"dictionary",
"python"
] |
stackoverflow_0001993747_dictionary_python.txt
|
Q:
Unit testing for D-Bus and HAL?
How does one test a method that does some interactions with the local D-Bus (accessing a HAL object)?
Results of tests will differ depending on the system that the test is run on, so I don't know how to provide the method reliable input.
I'm working in Python, by the way.
A:
If you can not mock the environment then it's probably impossible for you to write the test.
If your access to HAL/D-Bus is via an object and you provide a mock instance to your test then it should be possible to emulate the necessary inputs to your test from the mock implementation.
A:
It's also possible to create a temporary D-Bus buses for tests, and emulate any services your program uses in your test code. You can use this approach for programs which are D-Bus services, D-Bus clients, or both. The downside is that the bus setup is a bit hairy. There's code for doing this in e.g. Telepathy Gabble.
|
Unit testing for D-Bus and HAL?
|
How does one test a method that does some interactions with the local D-Bus (accessing a HAL object)?
Results of tests will differ depending on the system that the test is run on, so I don't know how to provide the method reliable input.
I'm working in Python, by the way.
|
[
"If you can not mock the environment then it's probably impossible for you to write the test.\nIf your access to HAL/D-Bus is via an object and you provide a mock instance to your test then it should be possible to emulate the necessary inputs to your test from the mock implementation.\n",
"It's also possible to create a temporary D-Bus buses for tests, and emulate any services your program uses in your test code. You can use this approach for programs which are D-Bus services, D-Bus clients, or both. The downside is that the bus setup is a bit hairy. There's code for doing this in e.g. Telepathy Gabble.\n"
] |
[
2,
0
] |
[] |
[] |
[
"dbus",
"hal",
"python",
"unit_testing"
] |
stackoverflow_0000827295_dbus_hal_python_unit_testing.txt
|
Q:
How can I force cherrypy to accept a variable number of GET parameters?
for instance, say I have my cherrypy index module set up like this
>>> import cherrypy
>>> class test:
def index(self, var = None):
if var:
print var
else:
print "nothing"
index.exposed = True
>>> cherrypy.quickstart(test())
If I send more than one GET parameter I get this error
404 Not Found
Unexpected query string parameters:
var2
Traceback (most recent call last):
File
"C:\Python26\lib\site-packages\cherrypy_cprequest.py",
line 606, in respond
cherrypy.response.body = self.handler() File
"C:\Python26\lib\site-packages\cherrypy_cpdispatch.py",
line 27, in call
test_callable_spec(self.callable, self.args, self.kwargs) File
"C:\Python26\lib\site-packages\cherrypy_cpdispatch.py",
line 130, in test_callable_spec
"parameters: %s" % ", ".join(extra_qs_params)) HTTPError:
(404, 'Unexpected query string
parameters: var2')
Powered by CherryPy 3.1.2
A:
def index(self, var=None, **params):
or
def index(self, **params):
'var2' will be a key in the params dict. In the second example, so will 'var'.
Note the other answers which reference the *args syntax won't work in this case, because CherryPy passes query params as keyword arguments, not positional arguments. Hence you need the ** syntax.
A:
For complete generality, change
def index(self, var = None):
to
def index(self, *vars):
vars will be bound to a tuple, which is empty if no arguments were passed, has one item if one argument was passed, two if two, and so forth. It's then up to your code to deal with various such cases sensibly and appropriately, of course.
|
How can I force cherrypy to accept a variable number of GET parameters?
|
for instance, say I have my cherrypy index module set up like this
>>> import cherrypy
>>> class test:
def index(self, var = None):
if var:
print var
else:
print "nothing"
index.exposed = True
>>> cherrypy.quickstart(test())
If I send more than one GET parameter I get this error
404 Not Found
Unexpected query string parameters:
var2
Traceback (most recent call last):
File
"C:\Python26\lib\site-packages\cherrypy_cprequest.py",
line 606, in respond
cherrypy.response.body = self.handler() File
"C:\Python26\lib\site-packages\cherrypy_cpdispatch.py",
line 27, in call
test_callable_spec(self.callable, self.args, self.kwargs) File
"C:\Python26\lib\site-packages\cherrypy_cpdispatch.py",
line 130, in test_callable_spec
"parameters: %s" % ", ".join(extra_qs_params)) HTTPError:
(404, 'Unexpected query string
parameters: var2')
Powered by CherryPy 3.1.2
|
[
"def index(self, var=None, **params):\n\nor\ndef index(self, **params):\n\n'var2' will be a key in the params dict. In the second example, so will 'var'.\nNote the other answers which reference the *args syntax won't work in this case, because CherryPy passes query params as keyword arguments, not positional arguments. Hence you need the ** syntax.\n",
"For complete generality, change\n def index(self, var = None):\n\nto\n def index(self, *vars):\n\nvars will be bound to a tuple, which is empty if no arguments were passed, has one item if one argument was passed, two if two, and so forth. It's then up to your code to deal with various such cases sensibly and appropriately, of course.\n"
] |
[
36,
1
] |
[] |
[] |
[
"cherrypy",
"python"
] |
stackoverflow_0001993604_cherrypy_python.txt
|
Q:
Where is os.environ initialized?
Using this code, many keys are output, but I expected no output:
import os
for i in os.environ:
print i
This is the code from os.py:
try:
environ
except NameError:
environ = {}
Where does os.environ get its values from? Where is it initialized?
A:
The os module starts by importing all names from a platform-specific submodule (such as _nt or _posix) then does a little normalization. Clearly the environ name (standing for the system environment) was defined by the platform-specific submodule (as it's normally expected to be!!!), so the except clause in os.py didn't trigger and os.environ is just the rich dictionary it's normally supposed to be.
A:
The quoted code from os.py is a backstop. It's saying, if no-one has yet defined an environ variable, create one, with an empty dictionary as a value.
But environ does exist, because it has been imported by this further up on line 58:
from nt import *
if you're running Windows, and similar platform-specific imports for other platforms. So in practice environ will always exist and the empty dict backstop will never be used.
Why bother provide a backstop then? Well, it's of dubious usefulness in the real world since as far as I can see all the platforms currently supported by the core Python distribution do implement a proper environ lookup. However there may be, or have been, unusual platforms where Python runs that do not have environment variables, and it may be of use when developing a new platform not to have a lot of programs fail to run when system interfaces like environment variables are not written yet.
|
Where is os.environ initialized?
|
Using this code, many keys are output, but I expected no output:
import os
for i in os.environ:
print i
This is the code from os.py:
try:
environ
except NameError:
environ = {}
Where does os.environ get its values from? Where is it initialized?
|
[
"The os module starts by importing all names from a platform-specific submodule (such as _nt or _posix) then does a little normalization. Clearly the environ name (standing for the system environment) was defined by the platform-specific submodule (as it's normally expected to be!!!), so the except clause in os.py didn't trigger and os.environ is just the rich dictionary it's normally supposed to be.\n",
"The quoted code from os.py is a backstop. It's saying, if no-one has yet defined an environ variable, create one, with an empty dictionary as a value.\nBut environ does exist, because it has been imported by this further up on line 58:\nfrom nt import *\n\nif you're running Windows, and similar platform-specific imports for other platforms. So in practice environ will always exist and the empty dict backstop will never be used.\nWhy bother provide a backstop then? Well, it's of dubious usefulness in the real world since as far as I can see all the platforms currently supported by the core Python distribution do implement a proper environ lookup. However there may be, or have been, unusual platforms where Python runs that do not have environment variables, and it may be of use when developing a new platform not to have a lot of programs fail to run when system interfaces like environment variables are not written yet.\n"
] |
[
7,
3
] |
[] |
[] |
[
"initialization",
"python",
"std"
] |
stackoverflow_0001993643_initialization_python_std.txt
|
Q:
My own OCR-program in Python
I am still a beginner but I want to write a character-recognition-program. This program isn't ready yet. And I edited a lot, therefor the comments may not match exactly. I will use the 8-connectivity for the connected component labeling.
from PIL import Image
import numpy as np
im = Image.open("D:\\Python26\\PYTHON-PROGRAMME\\bild_schrift.jpg")
w,h = im.size
w = int(w)
h = int(h)
#2D-Array for area
area = []
for x in range(w):
area.append([])
for y in range(h):
area[x].append(2) #number 0 is white, number 1 is black
#2D-Array for letter
letter = []
for x in range(50):
letter.append([])
for y in range(50):
letter[x].append(0)
#2D-Array for label
label = []
for x in range(50):
label.append([])
for y in range(50):
label[x].append(0)
#image to number conversion
pix = im.load()
threshold = 200
for x in range(w):
for y in range(h):
aaa = pix[x, y]
bbb = aaa[0] + aaa[1] + aaa[2] #total value
if bbb<=threshold:
area[x][y] = 1
if bbb>threshold:
area[x][y] = 0
np.set_printoptions(threshold='nan', linewidth=10)
#matrix transponation
ccc = np.array(area)
area = ccc.T #better solution?
#find all black pixel and set temporary label numbers
i=1
for x in range(40): # width (later)
for y in range(40): # heigth (later)
if area[x][y]==1:
letter[x][y]=1
label[x][y]=i
i += 1
#connected components labeling
for x in range(40): # width (later)
for y in range(40): # heigth (later)
if area[x][y]==1:
label[x][y]=i
#if pixel has neighbour:
if area[x][y+1]==1:
#pixel and neighbour get the lowest label
pass # tomorrows work
if area[x+1][y]==1:
#pixel and neighbour get the lowest label
pass # tomorrows work
#should i also compare pixel and left neighbour?
#find width of the letter
#find height of the letter
#find the middle of the letter
#middle = [width/2][height/2] #?
#divide letter into 30 parts --> 5 x 6 array
#model letter
#letter A-Z, a-z, 0-9 (maybe more)
#compare each of the 30 parts of the letter with all model letters
#make a weighting
#print(letter)
im.save("D:\\Python26\\PYTHON-PROGRAMME\\bild2.jpg")
print('done')
A:
OCR is not an easy task indeed. That's why text CAPTCHAs still work :)
To talk only about the letter extraction and not the pattern recognition, the technique you are using to separate the letters is called Connected Component Labeling. Since you are asking for a more efficient way to do this, try to implement the two-pass algorithm that's described in this article. Another description can be found in the article Blob extraction.
EDIT: Here's the implementation for the algorithm that I have suggested:
import sys
from PIL import Image, ImageDraw
class Region():
def __init__(self, x, y):
self._pixels = [(x, y)]
self._min_x = x
self._max_x = x
self._min_y = y
self._max_y = y
def add(self, x, y):
self._pixels.append((x, y))
self._min_x = min(self._min_x, x)
self._max_x = max(self._max_x, x)
self._min_y = min(self._min_y, y)
self._max_y = max(self._max_y, y)
def box(self):
return [(self._min_x, self._min_y), (self._max_x, self._max_y)]
def find_regions(im):
width, height = im.size
regions = {}
pixel_region = [[0 for y in range(height)] for x in range(width)]
equivalences = {}
n_regions = 0
#first pass. find regions.
for x in xrange(width):
for y in xrange(height):
#look for a black pixel
if im.getpixel((x, y)) == (0, 0, 0, 255): #BLACK
# get the region number from north or west
# or create new region
region_n = pixel_region[x-1][y] if x > 0 else 0
region_w = pixel_region[x][y-1] if y > 0 else 0
max_region = max(region_n, region_w)
if max_region > 0:
#a neighbour already has a region
#new region is the smallest > 0
new_region = min(filter(lambda i: i > 0, (region_n, region_w)))
#update equivalences
if max_region > new_region:
if max_region in equivalences:
equivalences[max_region].add(new_region)
else:
equivalences[max_region] = set((new_region, ))
else:
n_regions += 1
new_region = n_regions
pixel_region[x][y] = new_region
#Scan image again, assigning all equivalent regions the same region value.
for x in xrange(width):
for y in xrange(height):
r = pixel_region[x][y]
if r > 0:
while r in equivalences:
r = min(equivalences[r])
if not r in regions:
regions[r] = Region(x, y)
else:
regions[r].add(x, y)
return list(regions.itervalues())
def main():
im = Image.open(r"c:\users\personal\py\ocr\test.png")
regions = find_regions(im)
draw = ImageDraw.Draw(im)
for r in regions:
draw.rectangle(r.box(), outline=(255, 0, 0))
del draw
#im.show()
output = file("output.png", "wb")
im.save(output)
output.close()
if __name__ == "__main__":
main()
It's not 100% perfect, but since you are doing this only for learning purposes, it may be a good starting point. With the bounding box of each character you can now use a neural network as others have suggested here.
A:
OCR is very, very hard. Even with computer-generated characters, it's quite challenging if you don't know the font and font size in advance. Even if you're matching characters exactly, I would not call it a "beginning" programming project; it's quite subtle.
If you want to recognize scanned, or handwritten characters, that's even harder - you'll need to use advanced math, algorithms, and machine learning. There are quite a few books and thousands of articles written about this topic, so you don't need to reinvent the wheel.
I admire your effort, but I don't think you've gotten far enough to hit any of the actual difficulties yet. So far you're just randomly exploring pixels and copying them from one array to another. You haven't actually done any comparison yet, and I'm not sure the purpose of your "random walk".
Why random? Writing correct randomized algorithms is quite difficult. I would recommend starting with a deterministic algorithm first.
Why are you copying from one array to another? Why not just compare directly?
When you get the comparison, you'll have to deal with the fact that the image is not exactly the same as the "prototype", and it's not clear how you'll deal with that.
Based on the code you've written so far, though, I have an idea for you: try writing a program that finds its way through a "maze" in an image. The input would be the image, plus the start pixel and the goal pixel. The output is a path through the maze from the start to the goal. This is a much easier problem than OCR - solving mazes is something that computers are great for - but it's still fun and challenging.
A:
Most OCR algorithms these days are based on neural network algorithms. Hopfield networks are a good place to start. Based on the Hopfield Model available here in C, I built a very basic image recognition algorithm in python similar to what you describe. I've posted the full source here. It's a toy project and not suitable for real OCR, but can get you started in the right direction.
The Hopfield model is used as an autoassociative memory to store and recall a set of bitmap images. Images are stored by calculating a corresponding weight matrix. Thereafter, starting from an arbitrary configuration, the memory will settle on exactly that stored image, which is nearest to the starting configuration in terms of Hamming distance. Thus given an incomplete or corrupted version of a stored image, the network is able to recall the corresponding original image.
A Java applet to toy with an example can be found here; the network is trained with example inputs for the digits 0-9. Draw in the box on the right, click test and see the results from the network.
Don't let the mathematical notation intimidate you, the algorithms are straightforward once you get to source code.
A:
OCR is very, very difficult! What approach to use to attempt OCR will be based on what you are trying to accomplish (hand writing recongnition, computer generated text reading, etc.)
However, to get you started, read up on Neural Networks and OCR. Here are a few jump-right-in articles on the subject:
http://www.codeproject.com/KB/cs/neural_network_ocr.aspx
http://www.codeproject.com/KB/dotnet/simple_ocr.aspx
Use your favorite search engine to find information.
Have fun!
|
My own OCR-program in Python
|
I am still a beginner but I want to write a character-recognition-program. This program isn't ready yet. And I edited a lot, therefor the comments may not match exactly. I will use the 8-connectivity for the connected component labeling.
from PIL import Image
import numpy as np
im = Image.open("D:\\Python26\\PYTHON-PROGRAMME\\bild_schrift.jpg")
w,h = im.size
w = int(w)
h = int(h)
#2D-Array for area
area = []
for x in range(w):
area.append([])
for y in range(h):
area[x].append(2) #number 0 is white, number 1 is black
#2D-Array for letter
letter = []
for x in range(50):
letter.append([])
for y in range(50):
letter[x].append(0)
#2D-Array for label
label = []
for x in range(50):
label.append([])
for y in range(50):
label[x].append(0)
#image to number conversion
pix = im.load()
threshold = 200
for x in range(w):
for y in range(h):
aaa = pix[x, y]
bbb = aaa[0] + aaa[1] + aaa[2] #total value
if bbb<=threshold:
area[x][y] = 1
if bbb>threshold:
area[x][y] = 0
np.set_printoptions(threshold='nan', linewidth=10)
#matrix transponation
ccc = np.array(area)
area = ccc.T #better solution?
#find all black pixel and set temporary label numbers
i=1
for x in range(40): # width (later)
for y in range(40): # heigth (later)
if area[x][y]==1:
letter[x][y]=1
label[x][y]=i
i += 1
#connected components labeling
for x in range(40): # width (later)
for y in range(40): # heigth (later)
if area[x][y]==1:
label[x][y]=i
#if pixel has neighbour:
if area[x][y+1]==1:
#pixel and neighbour get the lowest label
pass # tomorrows work
if area[x+1][y]==1:
#pixel and neighbour get the lowest label
pass # tomorrows work
#should i also compare pixel and left neighbour?
#find width of the letter
#find height of the letter
#find the middle of the letter
#middle = [width/2][height/2] #?
#divide letter into 30 parts --> 5 x 6 array
#model letter
#letter A-Z, a-z, 0-9 (maybe more)
#compare each of the 30 parts of the letter with all model letters
#make a weighting
#print(letter)
im.save("D:\\Python26\\PYTHON-PROGRAMME\\bild2.jpg")
print('done')
|
[
"OCR is not an easy task indeed. That's why text CAPTCHAs still work :)\nTo talk only about the letter extraction and not the pattern recognition, the technique you are using to separate the letters is called Connected Component Labeling. Since you are asking for a more efficient way to do this, try to implement the two-pass algorithm that's described in this article. Another description can be found in the article Blob extraction.\nEDIT: Here's the implementation for the algorithm that I have suggested:\nimport sys\nfrom PIL import Image, ImageDraw\n\nclass Region():\n def __init__(self, x, y):\n self._pixels = [(x, y)]\n self._min_x = x\n self._max_x = x\n self._min_y = y\n self._max_y = y\n\n def add(self, x, y):\n self._pixels.append((x, y))\n self._min_x = min(self._min_x, x)\n self._max_x = max(self._max_x, x)\n self._min_y = min(self._min_y, y)\n self._max_y = max(self._max_y, y)\n\n def box(self):\n return [(self._min_x, self._min_y), (self._max_x, self._max_y)]\n\ndef find_regions(im):\n width, height = im.size\n regions = {}\n pixel_region = [[0 for y in range(height)] for x in range(width)]\n equivalences = {}\n n_regions = 0\n #first pass. find regions.\n for x in xrange(width):\n for y in xrange(height):\n #look for a black pixel\n if im.getpixel((x, y)) == (0, 0, 0, 255): #BLACK\n # get the region number from north or west\n # or create new region\n region_n = pixel_region[x-1][y] if x > 0 else 0\n region_w = pixel_region[x][y-1] if y > 0 else 0\n\n max_region = max(region_n, region_w)\n\n if max_region > 0:\n #a neighbour already has a region\n #new region is the smallest > 0\n new_region = min(filter(lambda i: i > 0, (region_n, region_w)))\n #update equivalences\n if max_region > new_region:\n if max_region in equivalences:\n equivalences[max_region].add(new_region)\n else:\n equivalences[max_region] = set((new_region, ))\n else:\n n_regions += 1\n new_region = n_regions\n\n pixel_region[x][y] = new_region\n\n #Scan image again, assigning all equivalent regions the same region value.\n for x in xrange(width):\n for y in xrange(height):\n r = pixel_region[x][y]\n if r > 0:\n while r in equivalences:\n r = min(equivalences[r])\n\n if not r in regions:\n regions[r] = Region(x, y)\n else:\n regions[r].add(x, y)\n\n return list(regions.itervalues())\n\ndef main():\n im = Image.open(r\"c:\\users\\personal\\py\\ocr\\test.png\")\n regions = find_regions(im)\n draw = ImageDraw.Draw(im)\n for r in regions:\n draw.rectangle(r.box(), outline=(255, 0, 0))\n del draw \n #im.show()\n output = file(\"output.png\", \"wb\")\n im.save(output)\n output.close()\n\nif __name__ == \"__main__\":\n main()\n\nIt's not 100% perfect, but since you are doing this only for learning purposes, it may be a good starting point. With the bounding box of each character you can now use a neural network as others have suggested here.\n",
"OCR is very, very hard. Even with computer-generated characters, it's quite challenging if you don't know the font and font size in advance. Even if you're matching characters exactly, I would not call it a \"beginning\" programming project; it's quite subtle.\nIf you want to recognize scanned, or handwritten characters, that's even harder - you'll need to use advanced math, algorithms, and machine learning. There are quite a few books and thousands of articles written about this topic, so you don't need to reinvent the wheel.\nI admire your effort, but I don't think you've gotten far enough to hit any of the actual difficulties yet. So far you're just randomly exploring pixels and copying them from one array to another. You haven't actually done any comparison yet, and I'm not sure the purpose of your \"random walk\".\n\nWhy random? Writing correct randomized algorithms is quite difficult. I would recommend starting with a deterministic algorithm first.\nWhy are you copying from one array to another? Why not just compare directly?\n\nWhen you get the comparison, you'll have to deal with the fact that the image is not exactly the same as the \"prototype\", and it's not clear how you'll deal with that.\nBased on the code you've written so far, though, I have an idea for you: try writing a program that finds its way through a \"maze\" in an image. The input would be the image, plus the start pixel and the goal pixel. The output is a path through the maze from the start to the goal. This is a much easier problem than OCR - solving mazes is something that computers are great for - but it's still fun and challenging.\n",
"Most OCR algorithms these days are based on neural network algorithms. Hopfield networks are a good place to start. Based on the Hopfield Model available here in C, I built a very basic image recognition algorithm in python similar to what you describe. I've posted the full source here. It's a toy project and not suitable for real OCR, but can get you started in the right direction. \n\nThe Hopfield model is used as an autoassociative memory to store and recall a set of bitmap images. Images are stored by calculating a corresponding weight matrix. Thereafter, starting from an arbitrary configuration, the memory will settle on exactly that stored image, which is nearest to the starting configuration in terms of Hamming distance. Thus given an incomplete or corrupted version of a stored image, the network is able to recall the corresponding original image.\n\nA Java applet to toy with an example can be found here; the network is trained with example inputs for the digits 0-9. Draw in the box on the right, click test and see the results from the network. \nDon't let the mathematical notation intimidate you, the algorithms are straightforward once you get to source code. \n",
"OCR is very, very difficult! What approach to use to attempt OCR will be based on what you are trying to accomplish (hand writing recongnition, computer generated text reading, etc.)\nHowever, to get you started, read up on Neural Networks and OCR. Here are a few jump-right-in articles on the subject:\nhttp://www.codeproject.com/KB/cs/neural_network_ocr.aspx\nhttp://www.codeproject.com/KB/dotnet/simple_ocr.aspx\nUse your favorite search engine to find information.\nHave fun!\n"
] |
[
34,
7,
5,
4
] |
[] |
[] |
[
"arrays",
"artificial_intelligence",
"ocr",
"python"
] |
stackoverflow_0001989987_arrays_artificial_intelligence_ocr_python.txt
|
Q:
how change int to binary. on python 2.5
print 077777#how can i get binary
i use python2.5
A:
Make a map of hexadecimal characters to binary sequences, then run the number through (note: only works for non-negative numbers):
def bin(value):
binmap = {'0': '0000', '1': '0001', ..., 'f': '1111'}
return ''.join(binmap[x] for x in ('%x' % (value,))).lstrip('0') or '0'
A:
Here are some recipes from ActiveState Code you might find helpful: Format integer as binary string
My initial answer only works in Python 2.6 and up as Alex correctly pointed out.
Like this:
print '{0:b}'.format(077777)
A:
Simplest (not fastest!) way to get a binary string for an int in Python 2.5:
def dobin(n):
digs = []
s = ''
if n<0:
s = '-'
n = -n
while True:
digs.append(str(n % 2))
n /= 2
if not n: break
if s: digs.append(s)
digs.reverse()
return ''.join(digs)
Are you looking for speed, or for clarity?
A:
n = 1234
"".join([["0", "1"][(n >> i) & 1] for i in reversed(range(n.__sizeof__()))])
although not sure if sizeof its correct.you could also calculate the highest bit set and only print those.
"".join([["0", "1"][(n>>i)&1] for i in range(log(n,2)+1)])
|
how change int to binary. on python 2.5
|
print 077777#how can i get binary
i use python2.5
|
[
"Make a map of hexadecimal characters to binary sequences, then run the number through (note: only works for non-negative numbers):\ndef bin(value):\n binmap = {'0': '0000', '1': '0001', ..., 'f': '1111'}\n return ''.join(binmap[x] for x in ('%x' % (value,))).lstrip('0') or '0'\n\n",
"Here are some recipes from ActiveState Code you might find helpful: Format integer as binary string\n\nMy initial answer only works in Python 2.6 and up as Alex correctly pointed out.\n\nLike this:\nprint '{0:b}'.format(077777)\n\n",
"Simplest (not fastest!) way to get a binary string for an int in Python 2.5:\ndef dobin(n):\n digs = []\n s = ''\n if n<0:\n s = '-'\n n = -n\n while True:\n digs.append(str(n % 2))\n n /= 2\n if not n: break\n if s: digs.append(s)\n digs.reverse()\n return ''.join(digs)\n\nAre you looking for speed, or for clarity?\n",
"n = 1234\n\n\"\".join([[\"0\", \"1\"][(n >> i) & 1] for i in reversed(range(n.__sizeof__()))])\n\nalthough not sure if sizeof its correct.you could also calculate the highest bit set and only print those.\n\"\".join([[\"0\", \"1\"][(n>>i)&1] for i in range(log(n,2)+1)])\n\n"
] |
[
6,
1,
1,
1
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001993834_python.txt
|
Q:
insert tags in ElementTree text
I am using the Python ElementTree module to manipulate HTML.
I want to emphasize certain words, and my current solution is:
for e in tree.getiterator():
for attr in 'text', 'tail':
words = (getattr(e, attr) or '').split()
change = False
for i, word in enumerate(words):
word = clean_word.sub('', word)
if word.lower() in glossary:
change = True
words[i] = word.replace(word, '<b>' + word + '</b>')
if change:
setattr(e, attr, ' '.join(words))
The above examines the text of each element and emphasizes the important words it finds.
However it does this by embedding HTML tags in the text attributes, which is escaped when rendering so that I need to counter with:
html = etree.tostring(tree).replace('>', '>').replace('<', '<')
This makes me uncomfortable so I want to do it properly.
However to embed a new Element I would need to shift around the 'text' and 'tail' attributes so that the emphasized text appeared at the same position. And this would be really tricky when iterating as above.
Any advice how to do this properly would be appreciated. I am sure there is something I have missed in the API!
A:
You can also use xslt and a custom xpath function to do this.
Shown below is an example. It still needs some work, for example cleaning up extra whitespace at the end of elements and handling mixed-text, but it's another idea.
given this input:
<html>
<head>
</head>
<body>
<p>here is some text to bold</p>
<p>and some more</p>
</body>
</html>
and glossary contains the two words: some, bold
then example output is :
<?xml version="1.0"?>
<html>
<head/>
<body>
<p>here is <b>some</b> text to <b>bold</b> </p>
<p>and <b>some</b> more </p>
</body>
</html>
Here's the code, I have also posted it at http://bkc.pastebin.com/f545a8e1d
from lxml import etree
stylesheet = etree.XML("""
<xsl:stylesheet version="1.0"
xmlns:btest="uri:bolder"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="@*">
<xsl:copy />
</xsl:template>
<xsl:template match="*">
<xsl:element name="{name(.)}">
<xsl:copy-of select="@*" />
<xsl:apply-templates select="text()" />
<xsl:apply-templates select="./*" />
</xsl:element>
</xsl:template>
<xsl:template match="text()">
<xsl:copy-of select="btest:bolder(.)/node()" />
</xsl:template>
</xsl:stylesheet>
""")
glossary = ['some', 'bold']
def bolder(context, s):
results = []
r = None
for word in s[0].split():
if word in glossary:
if r is not None:
results.append(r)
r = etree.Element('r')
b = etree.SubElement(r, 'b')
b.text = word
b.tail = ' '
results.append(r)
r = None
else:
if r is None:
r = etree.Element('r')
r.text = '%s%s ' % (r.text or '', word)
if r is not None:
results.append(r)
return results
def test():
ns = etree.FunctionNamespace('uri:bolder') # register global namespace
ns['bolder'] = bolder # define function in new global namespace
transform = etree.XSLT(stylesheet)
print str(transform(etree.XML("""<html><head></head><body><p>here is some text to bold</p><p>and some more</p></body></html>""")))
if __name__ == "__main__":
test()
A:
Although ElementTree is very easy to use for most XML processing tasks, it's also inconvenient for mixed content. I suggest using DOM parser:
from xml.dom import minidom
import re
ws_split = re.compile(r'\s+', re.U).split
def processNode(parent):
doc = parent.ownerDocument
for node in parent.childNodes[:]:
if node.nodeType==node.TEXT_NODE:
words = ws_split(node.nodeValue)
new_words = []
changed = False
for word in words:
if word in glossary:
text = ' '.join(new_words+[''])
parent.insertBefore(doc.createTextNode(text), node)
b = doc.createElement('b')
b.appendChild(doc.createTextNode(word))
parent.insertBefore(b, node)
new_words = ['']
changed = True
else:
new_words.append(word)
if changed:
text = ' '.join(new_words)
print text
parent.replaceChild(doc.createTextNode(text), node)
else:
processNode(node)
Also I used regexp to split words to avoid them sticking together:
>>> ' '.join(ws_split('a b '))
'a b '
>>> ' '.join('a b '.split())
'a b'
|
insert tags in ElementTree text
|
I am using the Python ElementTree module to manipulate HTML.
I want to emphasize certain words, and my current solution is:
for e in tree.getiterator():
for attr in 'text', 'tail':
words = (getattr(e, attr) or '').split()
change = False
for i, word in enumerate(words):
word = clean_word.sub('', word)
if word.lower() in glossary:
change = True
words[i] = word.replace(word, '<b>' + word + '</b>')
if change:
setattr(e, attr, ' '.join(words))
The above examines the text of each element and emphasizes the important words it finds.
However it does this by embedding HTML tags in the text attributes, which is escaped when rendering so that I need to counter with:
html = etree.tostring(tree).replace('>', '>').replace('<', '<')
This makes me uncomfortable so I want to do it properly.
However to embed a new Element I would need to shift around the 'text' and 'tail' attributes so that the emphasized text appeared at the same position. And this would be really tricky when iterating as above.
Any advice how to do this properly would be appreciated. I am sure there is something I have missed in the API!
|
[
"You can also use xslt and a custom xpath function to do this. \nShown below is an example. It still needs some work, for example cleaning up extra whitespace at the end of elements and handling mixed-text, but it's another idea.\ngiven this input:\n\n<html>\n<head>\n</head>\n<body>\n<p>here is some text to bold</p>\n<p>and some more</p>\n</body>\n</html>\n\nand glossary contains the two words: some, bold\nthen example output is :\n\n<?xml version=\"1.0\"?>\n<html>\n<head/>\n<body>\n<p>here is <b>some</b> text to <b>bold</b> </p>\n<p>and <b>some</b> more </p>\n</body>\n</html>\n\nHere's the code, I have also posted it at http://bkc.pastebin.com/f545a8e1d\n\n\nfrom lxml import etree\n\nstylesheet = etree.XML(\"\"\"\n <xsl:stylesheet version=\"1.0\"\n xmlns:btest=\"uri:bolder\"\n xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\n\n <xsl:template match=\"@*\">\n <xsl:copy />\n </xsl:template>\n\n <xsl:template match=\"*\">\n <xsl:element name=\"{name(.)}\">\n <xsl:copy-of select=\"@*\" />\n <xsl:apply-templates select=\"text()\" />\n <xsl:apply-templates select=\"./*\" />\n </xsl:element>\n </xsl:template>\n\n <xsl:template match=\"text()\">\n <xsl:copy-of select=\"btest:bolder(.)/node()\" />\n </xsl:template> \n </xsl:stylesheet>\n\"\"\")\n\nglossary = ['some', 'bold']\n\ndef bolder(context, s):\n results = []\n r = None\n for word in s[0].split():\n if word in glossary:\n if r is not None:\n results.append(r)\n r = etree.Element('r')\n b = etree.SubElement(r, 'b')\n b.text = word\n b.tail = ' '\n results.append(r)\n r = None\n else:\n if r is None:\n r = etree.Element('r')\n r.text = '%s%s ' % (r.text or '', word)\n\n if r is not None:\n results.append(r)\n return results\n\ndef test():\n ns = etree.FunctionNamespace('uri:bolder') # register global namespace\n ns['bolder'] = bolder # define function in new global namespace\n transform = etree.XSLT(stylesheet)\n print str(transform(etree.XML(\"\"\"<html><head></head><body><p>here is some text to bold</p><p>and some more</p></body></html>\"\"\")))\n\nif __name__ == \"__main__\":\n test()\n\n\n\n",
"Although ElementTree is very easy to use for most XML processing tasks, it's also inconvenient for mixed content. I suggest using DOM parser:\nfrom xml.dom import minidom\nimport re\n\nws_split = re.compile(r'\\s+', re.U).split\n\ndef processNode(parent):\n doc = parent.ownerDocument\n for node in parent.childNodes[:]:\n if node.nodeType==node.TEXT_NODE:\n words = ws_split(node.nodeValue)\n new_words = []\n changed = False\n for word in words:\n if word in glossary:\n text = ' '.join(new_words+[''])\n parent.insertBefore(doc.createTextNode(text), node)\n b = doc.createElement('b')\n b.appendChild(doc.createTextNode(word))\n parent.insertBefore(b, node)\n new_words = ['']\n changed = True\n else:\n new_words.append(word)\n if changed:\n text = ' '.join(new_words)\n print text\n parent.replaceChild(doc.createTextNode(text), node)\n else:\n processNode(node)\n\nAlso I used regexp to split words to avoid them sticking together:\n>>> ' '.join(ws_split('a b '))\n'a b '\n>>> ' '.join('a b '.split())\n'a b'\n\n"
] |
[
4,
1
] |
[] |
[] |
[
"elementtree",
"html",
"lxml",
"python"
] |
stackoverflow_0001973026_elementtree_html_lxml_python.txt
|
Q:
What is python's 'restricted execution mode'?
When __builtins__ is set and I try to access function globals, I get this error
>>> def f(): pass
...
>>> f.func_globals
{'f': <function f at 0x00B83270>, '__builtins__': <module '__builtin__' (built-in)>}
>>> __builtins__ = {}
>>> f.func_globals
Traceback (most recent call last):
File "<string>", line 1, in <string>
RuntimeError: restricted attribute
>>>
Why is that, where I can read more about it? Can I use it to safeguard expression evaluation?
See Question: How safe is expression evaluation using eval?
A:
Alas, a long-obsolete concept, see the docs -- the original idea was to provide a safe / sandboxed mode, but it just didn't pan out and was abandoned and deprecated since 2.3.
|
What is python's 'restricted execution mode'?
|
When __builtins__ is set and I try to access function globals, I get this error
>>> def f(): pass
...
>>> f.func_globals
{'f': <function f at 0x00B83270>, '__builtins__': <module '__builtin__' (built-in)>}
>>> __builtins__ = {}
>>> f.func_globals
Traceback (most recent call last):
File "<string>", line 1, in <string>
RuntimeError: restricted attribute
>>>
Why is that, where I can read more about it? Can I use it to safeguard expression evaluation?
See Question: How safe is expression evaluation using eval?
|
[
"Alas, a long-obsolete concept, see the docs -- the original idea was to provide a safe / sandboxed mode, but it just didn't pan out and was abandoned and deprecated since 2.3.\n"
] |
[
3
] |
[] |
[] |
[
"python",
"security"
] |
stackoverflow_0001994117_python_security.txt
|
Q:
Learning Python and using dictionaries
I'm working through exercises in Building Skills in Python, which to my knowledge don't have any published solutions.
In any case, I'm attempting to have a dictionary count the number of occurrences of a certain number in the original list, before duplicates are removed. For some reason, despite a number of variations on the theme below, I cant seem to increment the value for each of the 'keys' in the dictionary.
How could I code this with dictionaries?
dv = list()
# arbitrary sequence of numbers
seq = [2,4,5,2,4,6,3,8,9,3,7,2,47,2]
# dictionary counting number of occurances
seqDic = { }
for v in seq:
i = 1
dv.append(v)
for i in range(len(dv)-1):
if dv[i] == v:
del dv[-1]
seqDic.setdefault(v)
currentCount = seqDic[v]
currentCount += 1
print currentCount # debug
seqDic[v]=currentCount
print "orig:", seq
print "new: ", dv
print seqDic
A:
defaultdict makes this easy:
>>> from collections import defaultdict
>>> seq = [2,4,5,2,4,6,3,8,9,3,7,2,47,2]
>>> seqDic = defaultdict(int)
>>> for v in seq:
... seqDic[v] += 1
>>> print seqDic
defaultdict(<type 'int'>, {2: 4, 3: 2, 4: 2, 5: 1, 6: 1, 7: 1, 8: 1, 9: 1, 47: 1})
A:
I'm not really sure what you try to do .. count how often each number appears?
#arbitrary sequence of numbers
seq = [2,4,5,2,4,6,3,8,9,3,7,2,47,2]
#dictionary counting number of occurances
seqDic = {}
### what you want to do, spelled out
for number in seq:
if number in seqDic: # we had the number before
seqDic[number] += 1
else: # first time we see it
seqDic[number] = 1
#### or:
for number in seq:
current = seqDic.get(number, 0) # current count in the dict, or 0
seqDic[number] = current + 1
### or, to show you how setdefault works
for number in seq:
seqDic.setdefault(number, 0) # set to 0 if it doesnt exist
seqDic[number] += 1 # increase by one
print "orig:", seq
print seqDic
A:
defaultdict is not dict (it's a subclass, and may do too much of the work for you to help you learn via this exercise), so here's a simple way to do it with plain dict:
dv = list()
# arbitrary sequence of numbers
seq = [2,4,5,2,4,6,3,8,9,3,7,2,47,2]
# dictionary counting number of occurances
seqDic = { }
for i in seq:
if i in seqDic:
seqDic[i] += 1
else:
dv.append(i)
seqDic[i] = 1
this simple approach works particularly well here because you need the if i in seqDic test anyway for the purpose of building dv as well as seqDic. Otherwise, simpler would be:
for i in seq:
seqDic[i] = 1 + seqDic.get(i, 0)
using the handy method get of dict, which returns the second argument if the first is not a key in the dictionary. If you like this idea, here's a solution that also builds dv:
for i in seq:
seqDic[i] = 1 + seqDic.get(i, 0)
if seqDic[i] == 1: dv.append(i)
Edit: If you don't case about the order of items in dv (rather than wanting dv to be in the same order as the first occurrence of item in seq), then just using (after the simple version of the loop)
dv = seqDic.keys()
also works (in Python 2, where .keys returns a list), and so does
dv = list(seqDic)
which is fine in both Python 2 and Python 3. Under the same hypothesis (that you don't care about the order of items in dv) there are also other good solutions, such as
seqDic = dict.fromkeys(seq, 0)
for i in seq: seqDic[i] += 1
dv = list(seqDic)
here, we first use the fromkeys class method of dictionaries to build a new dict which already has 0 as the value corresponding to each key, so we can then just increment each entry without such precautions as .get or membership checks.
A:
How about this:
#arbitrary sequence of numbers
seq = [2,4,5,2,4,6,3,8,9,3,7,2,47,2]
#dictionary counting number of occurances
seqDic = { }
for v in seq:
if v in seqDic:
seqDic[v] += 1
else:
seqDic[v] = 1
dv = seqDic.keys()
print "orig:", seq
print "new: ", dv
print seqDic
It's clean and I think it demonstrates what you are trying to learn how to do in a simple manner. It is possible to do this using defaultdict as others have pointed out, but knowing how to do it this way is instructive too.
A:
Or, if you use Python3, you can use collections.Counter, which is essentially a dict, albeit subclassed.
>>> from collections import Counter
>>> seq = [2,4,5,2,4,6,3,8,9,3,7,2,47,2]
>>> Counter(seq)
Counter({2: 4, 3: 2, 4: 2, 5: 1, 6: 1, 7: 1, 8: 1, 9: 1, 47: 1}
A:
for v in seq:
try:
seqDic[v] += 1
except KeyError:
seqDic[v] = 1
That's the way I've always done the inner loop of things like this.
Apart from anything else, it's significantly faster than testing membership before working on the element, so if you have a few hundred thousand elements it saves a lot of time.
|
Learning Python and using dictionaries
|
I'm working through exercises in Building Skills in Python, which to my knowledge don't have any published solutions.
In any case, I'm attempting to have a dictionary count the number of occurrences of a certain number in the original list, before duplicates are removed. For some reason, despite a number of variations on the theme below, I cant seem to increment the value for each of the 'keys' in the dictionary.
How could I code this with dictionaries?
dv = list()
# arbitrary sequence of numbers
seq = [2,4,5,2,4,6,3,8,9,3,7,2,47,2]
# dictionary counting number of occurances
seqDic = { }
for v in seq:
i = 1
dv.append(v)
for i in range(len(dv)-1):
if dv[i] == v:
del dv[-1]
seqDic.setdefault(v)
currentCount = seqDic[v]
currentCount += 1
print currentCount # debug
seqDic[v]=currentCount
print "orig:", seq
print "new: ", dv
print seqDic
|
[
"defaultdict makes this easy:\n>>> from collections import defaultdict\n\n>>> seq = [2,4,5,2,4,6,3,8,9,3,7,2,47,2]\n\n>>> seqDic = defaultdict(int)\n\n>>> for v in seq:\n... seqDic[v] += 1\n\n>>> print seqDic\ndefaultdict(<type 'int'>, {2: 4, 3: 2, 4: 2, 5: 1, 6: 1, 7: 1, 8: 1, 9: 1, 47: 1})\n\n",
"I'm not really sure what you try to do .. count how often each number appears?\n#arbitrary sequence of numbers\nseq = [2,4,5,2,4,6,3,8,9,3,7,2,47,2]\n\n#dictionary counting number of occurances\nseqDic = {}\n\n### what you want to do, spelled out\nfor number in seq:\n if number in seqDic: # we had the number before\n seqDic[number] += 1\n else: # first time we see it\n seqDic[number] = 1\n\n#### or:\nfor number in seq:\n current = seqDic.get(number, 0) # current count in the dict, or 0\n seqDic[number] = current + 1\n\n### or, to show you how setdefault works\nfor number in seq:\n seqDic.setdefault(number, 0) # set to 0 if it doesnt exist\n seqDic[number] += 1 # increase by one\n\nprint \"orig:\", seq\nprint seqDic\n\n",
"defaultdict is not dict (it's a subclass, and may do too much of the work for you to help you learn via this exercise), so here's a simple way to do it with plain dict:\ndv = list()\n# arbitrary sequence of numbers\nseq = [2,4,5,2,4,6,3,8,9,3,7,2,47,2]\n\n# dictionary counting number of occurances\nseqDic = { }\n\nfor i in seq:\n if i in seqDic:\n seqDic[i] += 1\n else:\n dv.append(i)\n seqDic[i] = 1\n\nthis simple approach works particularly well here because you need the if i in seqDic test anyway for the purpose of building dv as well as seqDic. Otherwise, simpler would be:\nfor i in seq:\n seqDic[i] = 1 + seqDic.get(i, 0)\n\nusing the handy method get of dict, which returns the second argument if the first is not a key in the dictionary. If you like this idea, here's a solution that also builds dv:\nfor i in seq:\n seqDic[i] = 1 + seqDic.get(i, 0)\n if seqDic[i] == 1: dv.append(i)\n\nEdit: If you don't case about the order of items in dv (rather than wanting dv to be in the same order as the first occurrence of item in seq), then just using (after the simple version of the loop)\ndv = seqDic.keys()\n\nalso works (in Python 2, where .keys returns a list), and so does\ndv = list(seqDic)\n\nwhich is fine in both Python 2 and Python 3. Under the same hypothesis (that you don't care about the order of items in dv) there are also other good solutions, such as\nseqDic = dict.fromkeys(seq, 0)\nfor i in seq: seqDic[i] += 1\ndv = list(seqDic)\n\nhere, we first use the fromkeys class method of dictionaries to build a new dict which already has 0 as the value corresponding to each key, so we can then just increment each entry without such precautions as .get or membership checks.\n",
"How about this:\n#arbitrary sequence of numbers\nseq = [2,4,5,2,4,6,3,8,9,3,7,2,47,2]\n\n#dictionary counting number of occurances\nseqDic = { }\n\nfor v in seq:\n if v in seqDic:\n seqDic[v] += 1\n else:\n seqDic[v] = 1\n\ndv = seqDic.keys()\n\nprint \"orig:\", seq\nprint \"new: \", dv\nprint seqDic\n\nIt's clean and I think it demonstrates what you are trying to learn how to do in a simple manner. It is possible to do this using defaultdict as others have pointed out, but knowing how to do it this way is instructive too.\n",
"Or, if you use Python3, you can use collections.Counter, which is essentially a dict, albeit subclassed.\n>>> from collections import Counter\n>>> seq = [2,4,5,2,4,6,3,8,9,3,7,2,47,2]\n>>> Counter(seq)\nCounter({2: 4, 3: 2, 4: 2, 5: 1, 6: 1, 7: 1, 8: 1, 9: 1, 47: 1}\n\n",
"for v in seq:\n try:\n seqDic[v] += 1\n except KeyError:\n seqDic[v] = 1\n\nThat's the way I've always done the inner loop of things like this.\nApart from anything else, it's significantly faster than testing membership before working on the element, so if you have a few hundred thousand elements it saves a lot of time.\n"
] |
[
2,
2,
2,
1,
0,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001993689_python.txt
|
Q:
Use raw SQL to create tables in SQLAlchemy, after which use ORM
Is it possible to use raw SQL rather than the TABLE construct for creating tables in SQL Alchemy? I would still like to use the rest of SQLAlchemy though, such as the object mapper and session module. I'm just not fond of the SQLAlchemy syntax used to create tables (I've spent too long mired in SAS and SQL to learn another!).
Many thanks, Rich
A:
Yes.
connection.execute("""
CREATE TABLE ...
""")
You can then reflect all tables: MetaData(dsn, reflect=True) or metadata_instance.reflect().
A:
You can use the autoload paramater to the Table constructor to have it automatically load up the table definitions. There are some examples here.
|
Use raw SQL to create tables in SQLAlchemy, after which use ORM
|
Is it possible to use raw SQL rather than the TABLE construct for creating tables in SQL Alchemy? I would still like to use the rest of SQLAlchemy though, such as the object mapper and session module. I'm just not fond of the SQLAlchemy syntax used to create tables (I've spent too long mired in SAS and SQL to learn another!).
Many thanks, Rich
|
[
"Yes.\nconnection.execute(\"\"\"\nCREATE TABLE ...\n\"\"\")\n\nYou can then reflect all tables: MetaData(dsn, reflect=True) or metadata_instance.reflect().\n",
"You can use the autoload paramater to the Table constructor to have it automatically load up the table definitions. There are some examples here.\n"
] |
[
3,
1
] |
[] |
[] |
[
"database_design",
"python",
"sqlalchemy"
] |
stackoverflow_0001992815_database_design_python_sqlalchemy.txt
|
Q:
PyWin32: Windows Classic theme
In the PyWin32 demos folder, the win32gui_dialog.py sample uses the classic windows controls.
Can the Windows Vista themed buttons also be displayed using PyWin32, and if so, how? I'm using ActivePython 3.1, if that makes any difference.
Sample:
PyWin32 http://imagespark.net/files/old.png
A:
Short answer: a resounding YES.
I know that this is possible because I have seen it being done before. but I am not entirely certain as to how it is done.
At the very least, you can use IronPython and use Windows' builtin .NET framework by wielding clr.
If you are not interested in IronPython, then might you consider something along the lines of easyGUI or TkInter?
A:
You'll need to add a side-by-side manifest specifying a correct version of ComCtl32.dll to the Python interpreter. Fortunately there is no need to change the interpreter executable itself.
Create a file named python.exe.manifest in the directory containing python.exe.
Put the following contents in that file:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly
xmlns="urn:schemas-microsoft-com:asm.v1"
manifestVersion="1.0">
<assemblyIdentity
processorArchitecture="x86"
version="5.1.0.0"
type="win32"
name="python.exe"/>
<description>Python</description>
<dependency>
<dependentAssembly>
<assemblyIdentity
type="win32"
name="Microsoft.Windows.Common-Controls"
version="6.0.0.0"
publicKeyToken="6595b64144ccf1df"
language="*"
processorArchitecture="x86"/>
</dependentAssembly>
</dependency>
</assembly>
You may want to copy python.exe.manifest to pythonw.exe.manifest too.
A:
Have you tried using 'winxpgui' module instead of 'win32gui' module?
I'm not sure if there's a 'winvistagui' or 'win7gui' module, but 'winxpgui' does exist and may work, as it has a manifest included.
|
PyWin32: Windows Classic theme
|
In the PyWin32 demos folder, the win32gui_dialog.py sample uses the classic windows controls.
Can the Windows Vista themed buttons also be displayed using PyWin32, and if so, how? I'm using ActivePython 3.1, if that makes any difference.
Sample:
PyWin32 http://imagespark.net/files/old.png
|
[
"Short answer: a resounding YES.\nI know that this is possible because I have seen it being done before. but I am not entirely certain as to how it is done.\nAt the very least, you can use IronPython and use Windows' builtin .NET framework by wielding clr.\nIf you are not interested in IronPython, then might you consider something along the lines of easyGUI or TkInter?\n",
"You'll need to add a side-by-side manifest specifying a correct version of ComCtl32.dll to the Python interpreter. Fortunately there is no need to change the interpreter executable itself.\n\nCreate a file named python.exe.manifest in the directory containing python.exe.\nPut the following contents in that file:\n\n\n<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?> \n<assembly \n xmlns=\"urn:schemas-microsoft-com:asm.v1\" \n manifestVersion=\"1.0\">\n <assemblyIdentity \n processorArchitecture=\"x86\" \n version=\"5.1.0.0\"\n type=\"win32\"\n name=\"python.exe\"/>\n <description>Python</description>\n <dependency>\n <dependentAssembly>\n <assemblyIdentity\n type=\"win32\"\n name=\"Microsoft.Windows.Common-Controls\"\n version=\"6.0.0.0\"\n publicKeyToken=\"6595b64144ccf1df\"\n language=\"*\"\n processorArchitecture=\"x86\"/>\n </dependentAssembly>\n </dependency>\n</assembly>\n\n\nYou may want to copy python.exe.manifest to pythonw.exe.manifest too.\n",
"Have you tried using 'winxpgui' module instead of 'win32gui' module? \nI'm not sure if there's a 'winvistagui' or 'win7gui' module, but 'winxpgui' does exist and may work, as it has a manifest included.\n"
] |
[
2,
2,
0
] |
[] |
[] |
[
"python",
"python_3.x",
"pywin32",
"windows",
"windows_vista"
] |
stackoverflow_0001969041_python_python_3.x_pywin32_windows_windows_vista.txt
|
Q:
assistance troubleshooting a python/cherrypy error
import cherrypy
import os
PORT = 8080
class intelServ:
def index(self, botkey = None, userkey = None, network = None, user = None, channel = None, msg = None, step = None, **args):
# If any necessary parameters are missing, the bot should fail silently.
#if not botkey or not userkey or not network or not user or not channel or not msg:
# return 'failing'
chatLog = Chat()
chatLog.genLogfile(botkey, userkey)
return "You said: " + msg
index.exposed = True
class Chat:
def genLogfile(self, botkey, userkey):
botHome = os.path.join(os.curdir, botkey)
chatLog = os.path.join(botHome, userkey)
print botHome
print chatLog
# check if bot has a home, if not make one
if not os.path.exists(botHome):
os.mkdir(botHome)
# check if communication is already in progress, if not start it.
if not os.path.exists(chatLog):
FILE = open(chatLog, "w")
FILE.close()
FILE = open(chatLog+".step","w")
FILE.close()
# configure and start our cherrypy server
cherrypy.config.update({'server.socket_port': PORT, 'server.socket_host': '0.0.0.0'})
cherrypy.quickstart(intelServ())
This code returns the following traceback and I cannot figure out why:
> 500 Internal Server Error
>
> The server encountered an unexpected
> condition which prevented it from
> fulfilling the request.
>
> Traceback (most recent call last):
> File
> "c:\python26\lib\site-packages\cherrypy\_cprequest.py",
> line 606, in respond
> cherrypy.response.body = self.handler() File
> "c:\python26\lib\site-packages\cherrypy\_cpdispatch.py",
> line 25, in __call__
> return self.callable(*self.args, **self.kwargs) File "D:\code\pycode\spam\chatbot.py",
> line 14, in index
> chatLog.genLogfile(botkey, userkey) File
> "D:\code\pycode\spampy\chatbot.py",
> line 22, in genLogfile
> botHome = os.path.join(os.curdir, botkey) File
> "c:\python26\lib\ntpath.py", line 73,
> in join
> elif isabs(b): File "c:\python26\lib\ntpath.py", line 57,
> in isabs
> s = splitdrive(s)[1] File "c:\python26\lib\ntpath.py", line 125,
> in splitdrive
> if p[1:2] == ':': TypeError: 'NoneType' object is unsubscriptable
>
> Powered by CherryPy 3.1.2
A:
It looks like the parameter botkey as supplied to intelServ.index() is None (hence the 'NoneType'). You should uncomment your input validation code.
|
assistance troubleshooting a python/cherrypy error
|
import cherrypy
import os
PORT = 8080
class intelServ:
def index(self, botkey = None, userkey = None, network = None, user = None, channel = None, msg = None, step = None, **args):
# If any necessary parameters are missing, the bot should fail silently.
#if not botkey or not userkey or not network or not user or not channel or not msg:
# return 'failing'
chatLog = Chat()
chatLog.genLogfile(botkey, userkey)
return "You said: " + msg
index.exposed = True
class Chat:
def genLogfile(self, botkey, userkey):
botHome = os.path.join(os.curdir, botkey)
chatLog = os.path.join(botHome, userkey)
print botHome
print chatLog
# check if bot has a home, if not make one
if not os.path.exists(botHome):
os.mkdir(botHome)
# check if communication is already in progress, if not start it.
if not os.path.exists(chatLog):
FILE = open(chatLog, "w")
FILE.close()
FILE = open(chatLog+".step","w")
FILE.close()
# configure and start our cherrypy server
cherrypy.config.update({'server.socket_port': PORT, 'server.socket_host': '0.0.0.0'})
cherrypy.quickstart(intelServ())
This code returns the following traceback and I cannot figure out why:
> 500 Internal Server Error
>
> The server encountered an unexpected
> condition which prevented it from
> fulfilling the request.
>
> Traceback (most recent call last):
> File
> "c:\python26\lib\site-packages\cherrypy\_cprequest.py",
> line 606, in respond
> cherrypy.response.body = self.handler() File
> "c:\python26\lib\site-packages\cherrypy\_cpdispatch.py",
> line 25, in __call__
> return self.callable(*self.args, **self.kwargs) File "D:\code\pycode\spam\chatbot.py",
> line 14, in index
> chatLog.genLogfile(botkey, userkey) File
> "D:\code\pycode\spampy\chatbot.py",
> line 22, in genLogfile
> botHome = os.path.join(os.curdir, botkey) File
> "c:\python26\lib\ntpath.py", line 73,
> in join
> elif isabs(b): File "c:\python26\lib\ntpath.py", line 57,
> in isabs
> s = splitdrive(s)[1] File "c:\python26\lib\ntpath.py", line 125,
> in splitdrive
> if p[1:2] == ':': TypeError: 'NoneType' object is unsubscriptable
>
> Powered by CherryPy 3.1.2
|
[
"It looks like the parameter botkey as supplied to intelServ.index() is None (hence the 'NoneType'). You should uncomment your input validation code.\n"
] |
[
1
] |
[] |
[] |
[
"cherrypy",
"python"
] |
stackoverflow_0001994107_cherrypy_python.txt
|
Q:
Why can't I find '__path__' in django.db.__init__.py?
backend_dir = os.path.join(__path__[0], 'backends')
Why can't I find it?
A:
Set settings.DATABASE_ENGINE in settings.py.
The execution reaches the line you mentioned only if the back-end is not standard.
|
Why can't I find '__path__' in django.db.__init__.py?
|
backend_dir = os.path.join(__path__[0], 'backends')
Why can't I find it?
|
[
"Set settings.DATABASE_ENGINE in settings.py.\nThe execution reaches the line you mentioned only if the back-end is not standard.\n"
] |
[
0
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0001994294_django_python.txt
|
Q:
Is Google App Engine right for me?
I am thinking about using Google App Engine.It is going to be a huge website. In that case, what is your piece of advice using Google App Engine. I heard GAE has restrictions like we cannot store images or files more than 1MB limit(they are going to change this from what I read in the GAE roadmap),query is limited to 1000 results, and I am also going to se web2py with GAE. So I would like to know your comments.
Thanks
A:
Having developed a smallish site with GAE, I have some thoughts
If you mean "huge" like "the next YouTube", then GAE might be a great fit, because of the previously mentioned scaling.
If you mean "huge" like "massively complex, with a whole slew of screens, models, and features", then GAE might not be a good fit. Things like unit testing are hard on GAE, and there's not a built-in structure for your app that you'd get with something like (famously) (Ruby on) Rails, or (Python powered) Turbogears.
ie: there is no staging environment: just your development copy of the system and production. This may or may not be a bad thing, depending on your situation.
Additionally, it depends on the other Python modules you intend to pull in: some Python modules just don't run on GAE (because you can't talk to hardware, or because there are just too many files in the package).
Hope this helps
A:
using web2py on Google App Engine is a great strategy. It lets you get up and running fast, and if you do outgrow the restrictions of GAE then you can move your web2py application elsewhere.
However, keeping this portability means you should stay away from the advanced parts of GAE (Task Queues, Transactions, ListProperty, etc).
A:
The AppEngine uses BigTable as it's datastore backend. Don't try to write a traditional relational-database driven application. BigTable is much more well suited for use as a highly-scalable key-value store. Avoid joins if at all possible.
A:
I wouldn't worry about any of this. After having played with Google App Engine for a while now, I've found that it scales quite well for large data sets. If your data elements are large (i.e. photos), then you'll need to integrate with another service to handle them, but that's probably going to be true no matter what with data of that size. Also, I've found BigTable relatively easy to work with having come from a background entirely in relational databases. Finally, Django is a somewhat hidden, but awesome, "feature" of Google App Engine. If you've never used it, it's a really nice, elegant web framework that makes a lot of common tasks trivial (forms come to mind here).
A:
Google has just released version 1.3.0 of the SDK with support with a new Blobstore API for storage of files up to 50MB. See the post "App Engine SDK 1.3.0 Released Including Support for Larger User Uploads".
A:
What about Google Wave? It's being built on appengine, and once live, real-time translatable chat reaches the corporate sector... I could see it hitting top 1000th... But then again, that's an internal project that gets to do special stuff other appengine apps can't.... Like hanging threads; I think... And whatever else Wave has under the hood...
|
Is Google App Engine right for me?
|
I am thinking about using Google App Engine.It is going to be a huge website. In that case, what is your piece of advice using Google App Engine. I heard GAE has restrictions like we cannot store images or files more than 1MB limit(they are going to change this from what I read in the GAE roadmap),query is limited to 1000 results, and I am also going to se web2py with GAE. So I would like to know your comments.
Thanks
|
[
"Having developed a smallish site with GAE, I have some thoughts\n\nIf you mean \"huge\" like \"the next YouTube\", then GAE might be a great fit, because of the previously mentioned scaling.\nIf you mean \"huge\" like \"massively complex, with a whole slew of screens, models, and features\", then GAE might not be a good fit. Things like unit testing are hard on GAE, and there's not a built-in structure for your app that you'd get with something like (famously) (Ruby on) Rails, or (Python powered) Turbogears.\n\nie: there is no staging environment: just your development copy of the system and production. This may or may not be a bad thing, depending on your situation.\nAdditionally, it depends on the other Python modules you intend to pull in: some Python modules just don't run on GAE (because you can't talk to hardware, or because there are just too many files in the package).\nHope this helps\n",
"using web2py on Google App Engine is a great strategy. It lets you get up and running fast, and if you do outgrow the restrictions of GAE then you can move your web2py application elsewhere. \nHowever, keeping this portability means you should stay away from the advanced parts of GAE (Task Queues, Transactions, ListProperty, etc).\n",
"The AppEngine uses BigTable as it's datastore backend. Don't try to write a traditional relational-database driven application. BigTable is much more well suited for use as a highly-scalable key-value store. Avoid joins if at all possible.\n",
"I wouldn't worry about any of this. After having played with Google App Engine for a while now, I've found that it scales quite well for large data sets. If your data elements are large (i.e. photos), then you'll need to integrate with another service to handle them, but that's probably going to be true no matter what with data of that size. Also, I've found BigTable relatively easy to work with having come from a background entirely in relational databases. Finally, Django is a somewhat hidden, but awesome, \"feature\" of Google App Engine. If you've never used it, it's a really nice, elegant web framework that makes a lot of common tasks trivial (forms come to mind here).\n",
"Google has just released version 1.3.0 of the SDK with support with a new Blobstore API for storage of files up to 50MB. See the post \"App Engine SDK 1.3.0 Released Including Support for Larger User Uploads\".\n",
"What about Google Wave? It's being built on appengine, and once live, real-time translatable chat reaches the corporate sector... I could see it hitting top 1000th... But then again, that's an internal project that gets to do special stuff other appengine apps can't.... Like hanging threads; I think... And whatever else Wave has under the hood...\n"
] |
[
8,
5,
3,
2,
1,
0
] |
[
"If you are planning on a 'huge' website, then don't use App Engine. Simple as that. The App Engine is not built to deliver the next top 1000th website. \nAllow me to also ask what do you mean by 'huge', how many simultaneous users? Queries per second? DB load?\n"
] |
[
-11
] |
[
"google_app_engine",
"python",
"web2py"
] |
stackoverflow_0001903065_google_app_engine_python_web2py.txt
|
Q:
How to get (and use) extended permissions in Facebook with Python/Django
I'm trying to write a simple app that lets a user grant my code permission to write to her page's Facebook stream. As I understand it, it should be as easy as:
Have the user click on a button that launches a popup containing the a page in my Facebook app.
In that page, they click on something that grants stream_publish to my app and assigns that permission to their page.
Window closes, I now have all the info I need to run a script in cron to push stuff to that page's stream.
I've been reading the wiki for days. Notes on pyfacebook are at least a year out of date, and people have pointed me to the socialauth app for Django which appears to be equally out of date and focused on targeting users as opposed to their pages. I can't even do #1 up there, let along #2 and 3.
If someone could show me how to use Django/Python to request/receive permission to write to a Facebook stream, that would be a great start.
Any help would be greatly appreciated.
A:
Have you looked at minifb? Their examples page shows basically everything you need to know to request authorization and receive a session key. (Also, the github page for pyfacebook shows that the library is still alive)
So, for your scenario you'd need:
Request the "stream_publish" permission. There are some ways to do it, but I'd actually go for the easiest: submitting a form (note I've never done an app for facebook, I'm probably wrong assuming this approach is the easiest :-)
Use your application normally: call the API methods using the user_id of the user that authorized your application (you'll have to store it) and, since you were authorized, it shouldn't fail.
For this, basically, add this form on your template:
<form promptpermission="publish_stream">
<input type="submit" value="Allow Publish Stream">
</form>
Kudos to the Facebook developers, by the way. Very nice official documentation.
EDIT: I'm not allowed to comment yet so: Should you face problems getting the uid, check this question and the references.
A:
After a lot of tinkering, I appear to have solved all of my problems in Facebookland:
Turns out that having a user click on a button to grant permissions is as easy as Caio Romão said it was. For my part though, I found that directing them to the Facebook Desktop App link was way easier and more dependable.
Using this link method, Facebook allows you to specify enable_profile_selector=1 which will make sure that a list of pages is generated from which the user can select which pages (if any) will grant these permissions.
For this one though, Facebook is totally broken. While in #2 they allow the user to select a page to grant permissions, they don't pass this information onto the application either by way of a POST or in the headers. It's just not there. Instead, you have to do an ugly trick with FQL and some additional questions to the user to make it work.
Anyway, I detailed it all on my blog if anyone is interested. Thanks for your help!
|
How to get (and use) extended permissions in Facebook with Python/Django
|
I'm trying to write a simple app that lets a user grant my code permission to write to her page's Facebook stream. As I understand it, it should be as easy as:
Have the user click on a button that launches a popup containing the a page in my Facebook app.
In that page, they click on something that grants stream_publish to my app and assigns that permission to their page.
Window closes, I now have all the info I need to run a script in cron to push stuff to that page's stream.
I've been reading the wiki for days. Notes on pyfacebook are at least a year out of date, and people have pointed me to the socialauth app for Django which appears to be equally out of date and focused on targeting users as opposed to their pages. I can't even do #1 up there, let along #2 and 3.
If someone could show me how to use Django/Python to request/receive permission to write to a Facebook stream, that would be a great start.
Any help would be greatly appreciated.
|
[
"Have you looked at minifb? Their examples page shows basically everything you need to know to request authorization and receive a session key. (Also, the github page for pyfacebook shows that the library is still alive)\nSo, for your scenario you'd need:\n\nRequest the \"stream_publish\" permission. There are some ways to do it, but I'd actually go for the easiest: submitting a form (note I've never done an app for facebook, I'm probably wrong assuming this approach is the easiest :-)\nUse your application normally: call the API methods using the user_id of the user that authorized your application (you'll have to store it) and, since you were authorized, it shouldn't fail.\n\nFor this, basically, add this form on your template:\n<form promptpermission=\"publish_stream\">\n<input type=\"submit\" value=\"Allow Publish Stream\">\n</form>\n\nKudos to the Facebook developers, by the way. Very nice official documentation.\nEDIT: I'm not allowed to comment yet so: Should you face problems getting the uid, check this question and the references.\n",
"After a lot of tinkering, I appear to have solved all of my problems in Facebookland:\n\nTurns out that having a user click on a button to grant permissions is as easy as Caio Romão said it was. For my part though, I found that directing them to the Facebook Desktop App link was way easier and more dependable.\nUsing this link method, Facebook allows you to specify enable_profile_selector=1 which will make sure that a list of pages is generated from which the user can select which pages (if any) will grant these permissions.\nFor this one though, Facebook is totally broken. While in #2 they allow the user to select a page to grant permissions, they don't pass this information onto the application either by way of a POST or in the headers. It's just not there. Instead, you have to do an ugly trick with FQL and some additional questions to the user to make it work.\n\nAnyway, I detailed it all on my blog if anyone is interested. Thanks for your help!\n"
] |
[
3,
1
] |
[] |
[] |
[
"django",
"facebook",
"pyfacebook",
"python"
] |
stackoverflow_0001967438_django_facebook_pyfacebook_python.txt
|
Q:
How can I open '_mysql.pyd' in 'D:\Python25\Lib\site-packages'?
My IDE is 'ulipad', and when I open the file, it can't be shown. How can I get it?
A:
.pyd files are DLLs. You can't usefully open them in text editors.
|
How can I open '_mysql.pyd' in 'D:\Python25\Lib\site-packages'?
|
My IDE is 'ulipad', and when I open the file, it can't be shown. How can I get it?
|
[
".pyd files are DLLs. You can't usefully open them in text editors.\n"
] |
[
1
] |
[] |
[] |
[
"mysql",
"python"
] |
stackoverflow_0001994403_mysql_python.txt
|
Q:
Problem with for loop iterations over data from a queue
I'm having a problem reading and processing data from my server. I've spent hours debugging this and it seems as though the problem has nothing to do with the server but is really just an issue with one of my for loops. Its difficult to explain this without actually seeing the data from the server, but I'll do my best to explain this.
Basically I have a server that when I send a command, it returns to me 5 different XML strings sequentially. My program parses this data into Python dictionaries and stores them in different class attributes. As TCP is a stream, I usually don't receive each string separately. What usually happens is I'll receive the first string, then the next 4 strings in groups of 2. So theres normally 3 different iterations of the for loop. However, the last string fails to get processed and stored in an attribute. Here's the logic containing the for loop in question:
def xmlParser(self, newData):
print newData
for string in newData:
if 'a' in string:
print 'string1 being processed'
xmlToDictionary(string, 'string1')
elif 'b' in string:
print 'string2 being processed'
xmlToDictionary(string, 'string2')
elif 'c' in string:
print 'string3 being processed'
xmlToDictionary(string, 'string3')
elif 'd' in string:
print 'string4 being processed'
xmlToDictionary(string, 'string4')
elif 'e' in string:
print 'string5 being processed'
xmlToDictionary(string, 'string5')
The print statements are solely for debugging purposes. My first reaction to the last string not being processed was that it simply wasn't being received. However, by printing newData I can verify that all the strings are received and sent to this function. The newData is a list containing the strings to be processed. For the 3 different iterations, newData looks like this
newData = ['string1']
newData = ['string2', 'string3']
newData = ['string4', 'string5']
Its 'string5' that isn't processed, and I don't believe its because of an exception being raised in xmlToDictionary() because the string 'string5 being processed' isn't printed. And if I include an else statement in the function, that isn't executed either. Its as if the for loop just refuses to perform a second iteration on the last group of data. To test things further, I modified the server script to send 'string5' before 'string4' and, to my surprise, completely fixed the issue and caused 'string5' to be processed and stored as a dictionary. In this situation, newData looked like this
newData = ['string1']
newData = ['string2', 'string3', 'string5']
newData = ['string4']
I also tried modifying the server script to stop sending 'string4' altogether. This also was successful in allowing 'string5' to be processed. The for loop only performed two iterations and newData looked like this
newData = ['string1']
newData = ['string2', 'string3', 'string5']
I tried to put all this together into determining what the problem is, but I'm totally confused. I've never encountered something like this before. If I can't come up with a solution, I'll either leave the script to send 'string5' before 'string4' or I may simply combine all the strings on the server and have it sent as one big string. Regardless, I would still like to determine what is going on here since it may indicate a deeper problem with my program.
A:
"As TCP is a stream, I usually don't receive each string separately "
You can't reliably and predictably receive them separately. TCP makes things into a single stream of data. That's what TCP/IP must do. It must buffer to create a "stream" of data, not matter what you try to do at each end to send or receive things "separately". Separately has no meaning when you use TCP/IP.
You must break up the strings at your end using some feature of the string. Syntax. Punctuation. Something.
Usually, what we do is combine the 5 XML strings into a single XML message.
<message>
<string1>...</string1>
<string2>...</string2>
<string3>...</string3>
<string4>...</string4>
<string5>...</string5>
</message>
Parse the one message, find your five strings. It's much simpler. And it fits with the way TCP/IP actually works.
A:
I just tried your code with the following result:
def xmlParser(newData):
for string in newData:
print string
if 'a' in string:
print 'string1 being processed'
elif 'b' in string:
print 'string2 being processed'
# ...
elif 'e' in string:
print 'string5 being processed'
newData = ['string1']
xmlParser(newData)
newData = ['string2', 'string3']
xmlParser(newData)
newData = ['string4', 'string5']
xmlParser(newData)
And here is the output:
$ python test.py
string1
string2
string3
string4
string5
The loop will process exactly all the element if there is no exception throw inside xmlToDictionary. If you want to verify if throw an exception, try this code:
def xmlParser(self, newData):
print newData
for string in newData:
try:
if 'a' in string:
print 'string1 being processed'
xmlToDictionary(string, 'string1')
# ...
elif 'e' in string:
print 'string5 being processed'
xmlToDictionary(string, 'string5')
except:
print "excetion error"
Maybe the test condition is not exactly what you want:
if 'a' in string:
Hope I helped you
A:
Well, this is a stumper. Especially since you have not posted the real code, but your own concept of how the code should be working. Since there is nothing wrong with this concept, there is nothing wrong with your example.
Still, I copied out your code, and then tried to perturb it to get your results. I think the most likely culprit is that you have some undesirable side effect occurring in your code that processes string4's. Your description sounds very much like what happens when a list is modified while it is being iterated over. Here's one example that would cause the exact behavior you describe:
elif 'd' in string:
print 'string4 being processed'
# undesirable side effect occurs here
newData.remove(string)
xmlToDictionary(string, 'string4')
Try sending a sequence like [string4, string1] and see if string1 gets through. If not, there is a strong chance that some kind of side-effect is coming from this chunk of code.
|
Problem with for loop iterations over data from a queue
|
I'm having a problem reading and processing data from my server. I've spent hours debugging this and it seems as though the problem has nothing to do with the server but is really just an issue with one of my for loops. Its difficult to explain this without actually seeing the data from the server, but I'll do my best to explain this.
Basically I have a server that when I send a command, it returns to me 5 different XML strings sequentially. My program parses this data into Python dictionaries and stores them in different class attributes. As TCP is a stream, I usually don't receive each string separately. What usually happens is I'll receive the first string, then the next 4 strings in groups of 2. So theres normally 3 different iterations of the for loop. However, the last string fails to get processed and stored in an attribute. Here's the logic containing the for loop in question:
def xmlParser(self, newData):
print newData
for string in newData:
if 'a' in string:
print 'string1 being processed'
xmlToDictionary(string, 'string1')
elif 'b' in string:
print 'string2 being processed'
xmlToDictionary(string, 'string2')
elif 'c' in string:
print 'string3 being processed'
xmlToDictionary(string, 'string3')
elif 'd' in string:
print 'string4 being processed'
xmlToDictionary(string, 'string4')
elif 'e' in string:
print 'string5 being processed'
xmlToDictionary(string, 'string5')
The print statements are solely for debugging purposes. My first reaction to the last string not being processed was that it simply wasn't being received. However, by printing newData I can verify that all the strings are received and sent to this function. The newData is a list containing the strings to be processed. For the 3 different iterations, newData looks like this
newData = ['string1']
newData = ['string2', 'string3']
newData = ['string4', 'string5']
Its 'string5' that isn't processed, and I don't believe its because of an exception being raised in xmlToDictionary() because the string 'string5 being processed' isn't printed. And if I include an else statement in the function, that isn't executed either. Its as if the for loop just refuses to perform a second iteration on the last group of data. To test things further, I modified the server script to send 'string5' before 'string4' and, to my surprise, completely fixed the issue and caused 'string5' to be processed and stored as a dictionary. In this situation, newData looked like this
newData = ['string1']
newData = ['string2', 'string3', 'string5']
newData = ['string4']
I also tried modifying the server script to stop sending 'string4' altogether. This also was successful in allowing 'string5' to be processed. The for loop only performed two iterations and newData looked like this
newData = ['string1']
newData = ['string2', 'string3', 'string5']
I tried to put all this together into determining what the problem is, but I'm totally confused. I've never encountered something like this before. If I can't come up with a solution, I'll either leave the script to send 'string5' before 'string4' or I may simply combine all the strings on the server and have it sent as one big string. Regardless, I would still like to determine what is going on here since it may indicate a deeper problem with my program.
|
[
"\"As TCP is a stream, I usually don't receive each string separately \"\nYou can't reliably and predictably receive them separately. TCP makes things into a single stream of data. That's what TCP/IP must do. It must buffer to create a \"stream\" of data, not matter what you try to do at each end to send or receive things \"separately\". Separately has no meaning when you use TCP/IP.\nYou must break up the strings at your end using some feature of the string. Syntax. Punctuation. Something.\nUsually, what we do is combine the 5 XML strings into a single XML message.\n<message>\n <string1>...</string1>\n <string2>...</string2>\n <string3>...</string3>\n <string4>...</string4>\n <string5>...</string5>\n</message> \n\nParse the one message, find your five strings. It's much simpler. And it fits with the way TCP/IP actually works.\n",
"I just tried your code with the following result:\ndef xmlParser(newData):\n for string in newData:\n print string\n if 'a' in string:\n print 'string1 being processed'\n elif 'b' in string:\n print 'string2 being processed'\n # ...\n elif 'e' in string:\n print 'string5 being processed'\n\nnewData = ['string1']\nxmlParser(newData)\nnewData = ['string2', 'string3']\nxmlParser(newData)\nnewData = ['string4', 'string5']\nxmlParser(newData)\n\nAnd here is the output:\n$ python test.py\nstring1\nstring2\nstring3\nstring4\nstring5\n\nThe loop will process exactly all the element if there is no exception throw inside xmlToDictionary. If you want to verify if throw an exception, try this code:\ndef xmlParser(self, newData):\n print newData\n for string in newData:\n try:\n if 'a' in string:\n print 'string1 being processed'\n xmlToDictionary(string, 'string1')\n # ...\n elif 'e' in string:\n print 'string5 being processed'\n xmlToDictionary(string, 'string5')\n except:\n print \"excetion error\"\n\nMaybe the test condition is not exactly what you want:\n\nif 'a' in string:\n\nHope I helped you\n",
"Well, this is a stumper. Especially since you have not posted the real code, but your own concept of how the code should be working. Since there is nothing wrong with this concept, there is nothing wrong with your example.\nStill, I copied out your code, and then tried to perturb it to get your results. I think the most likely culprit is that you have some undesirable side effect occurring in your code that processes string4's. Your description sounds very much like what happens when a list is modified while it is being iterated over. Here's one example that would cause the exact behavior you describe:\nelif 'd' in string: \n print 'string4 being processed' \n # undesirable side effect occurs here\n newData.remove(string)\n xmlToDictionary(string, 'string4') \n\nTry sending a sequence like [string4, string1] and see if string1 gets through. If not, there is a strong chance that some kind of side-effect is coming from this chunk of code.\n"
] |
[
3,
1,
1
] |
[] |
[] |
[
"for_loop",
"loops",
"python"
] |
stackoverflow_0001994904_for_loop_loops_python.txt
|
Q:
Creating an FTP client with Python
I've always thought about creating my own ftp client ever since I've started using the Internet. And now that I'm studying Python, I'm thinking about creating one as an exercises/personal project.
I'm wondering,
What libraries do you guys suggest? Will ftplib suffice? Or would you suggest another library(preferably one that has good docs)?
I'm thinking about using wxPython. Is it a good idea? Should I learn it first?
I'm coming from a Web Development background. What tips/suggestions would you guys give to me?
I'd appreciate any guidance/help. Thanks in advance! :)
A:
It sounds like you want to make a program that has a GUI. May I recommend using PyQt for that part of your application? ftplib should be fine for your FTP support, and you can find documentation right here.
Alternatively for FTP support, you can use the QFtp class from the QtNetwork module from PyQt framework. The following is an example FTP client that comes with PyQt. The images come with it.
#!/usr/bin/env python
"""PyQt4 port of the network/ftp example from Qt v4.x"""
# This is only needed for Python v2 but is harmless for Python v3.
import sip
sip.setapi('QString', 2)
from PyQt4 import QtCore, QtGui, QtNetwork
import ftp_rc
class FtpWindow(QtGui.QDialog):
def __init__(self, parent=None):
super(FtpWindow, self).__init__(parent)
self.isDirectory = {}
self.currentPath = ''
self.ftp = None
self.outFile = None
ftpServerLabel = QtGui.QLabel("Ftp &server:")
self.ftpServerLineEdit = QtGui.QLineEdit('ftp.trolltech.com')
ftpServerLabel.setBuddy(self.ftpServerLineEdit)
self.statusLabel = QtGui.QLabel("Please enter the name of an FTP server.")
self.fileList = QtGui.QTreeWidget()
self.fileList.setEnabled(False)
self.fileList.setRootIsDecorated(False)
self.fileList.setHeaderLabels(("Name", "Size", "Owner", "Group", "Time"))
self.fileList.header().setStretchLastSection(False)
self.connectButton = QtGui.QPushButton("Connect")
self.connectButton.setDefault(True)
self.cdToParentButton = QtGui.QPushButton()
self.cdToParentButton.setIcon(QtGui.QIcon(':/images/cdtoparent.png'))
self.cdToParentButton.setEnabled(False)
self.downloadButton = QtGui.QPushButton("Download")
self.downloadButton.setEnabled(False)
self.quitButton = QtGui.QPushButton("Quit")
buttonBox = QtGui.QDialogButtonBox()
buttonBox.addButton(self.downloadButton,
QtGui.QDialogButtonBox.ActionRole)
buttonBox.addButton(self.quitButton, QtGui.QDialogButtonBox.RejectRole)
self.progressDialog = QtGui.QProgressDialog(self)
self.fileList.itemActivated.connect(self.processItem)
self.fileList.currentItemChanged.connect(self.enableDownloadButton)
self.progressDialog.canceled.connect(self.cancelDownload)
self.connectButton.clicked.connect(self.connectOrDisconnect)
self.cdToParentButton.clicked.connect(self.cdToParent)
self.downloadButton.clicked.connect(self.downloadFile)
self.quitButton.clicked.connect(self.close)
topLayout = QtGui.QHBoxLayout()
topLayout.addWidget(ftpServerLabel)
topLayout.addWidget(self.ftpServerLineEdit)
topLayout.addWidget(self.cdToParentButton)
topLayout.addWidget(self.connectButton)
mainLayout = QtGui.QVBoxLayout()
mainLayout.addLayout(topLayout)
mainLayout.addWidget(self.fileList)
mainLayout.addWidget(self.statusLabel)
mainLayout.addWidget(buttonBox)
self.setLayout(mainLayout)
self.setWindowTitle("FTP")
def sizeHint(self):
return QtCore.QSize(500, 300)
def connectOrDisconnect(self):
if self.ftp:
self.ftp.abort()
self.ftp.deleteLater()
self.ftp = None
self.fileList.setEnabled(False)
self.cdToParentButton.setEnabled(False)
self.downloadButton.setEnabled(False)
self.connectButton.setEnabled(True)
self.connectButton.setText("Connect")
self.setCursor(QtCore.Qt.ArrowCursor)
return
self.setCursor(QtCore.Qt.WaitCursor)
self.ftp = QtNetwork.QFtp(self)
self.ftp.commandFinished.connect(self.ftpCommandFinished)
self.ftp.listInfo.connect(self.addToList)
self.ftp.dataTransferProgress.connect(self.updateDataTransferProgress)
self.fileList.clear()
self.currentPath = ''
self.isDirectory.clear()
url = QtCore.QUrl(self.ftpServerLineEdit.text())
if not url.isValid() or url.scheme().lower() != 'ftp':
self.ftp.connectToHost(self.ftpServerLineEdit.text(), 21)
self.ftp.login()
else:
self.ftp.connectToHost(url.host(), url.port(21))
user_name = url.userName()
if user_name:
try:
# Python v3.
user_name = bytes(user_name, encoding='latin1')
except:
# Python v2.
pass
self.ftp.login(QtCore.QUrl.fromPercentEncoding(user_name), url.password())
else:
self.ftp.login()
if url.path():
self.ftp.cd(url.path())
self.fileList.setEnabled(True)
self.connectButton.setEnabled(False)
self.connectButton.setText("Disconnect")
self.statusLabel.setText("Connecting to FTP server %s..." % self.ftpServerLineEdit.text())
def downloadFile(self):
fileName = self.fileList.currentItem().text(0)
if QtCore.QFile.exists(fileName):
QtGui.QMessageBox.information(self, "FTP",
"There already exists a file called %s in the current "
"directory." % fileName)
return
self.outFile = QtCore.QFile(fileName)
if not self.outFile.open(QtCore.QIODevice.WriteOnly):
QtGui.QMessageBox.information(self, "FTP",
"Unable to save the file %s: %s." % (fileName, self.outFile.errorString()))
self.outFile = None
return
self.ftp.get(self.fileList.currentItem().text(0), self.outFile)
self.progressDialog.setLabelText("Downloading %s..." % fileName)
self.downloadButton.setEnabled(False)
self.progressDialog.exec_()
def cancelDownload(self):
self.ftp.abort()
def ftpCommandFinished(self, _, error):
self.setCursor(QtCore.Qt.ArrowCursor)
if self.ftp.currentCommand() == QtNetwork.QFtp.ConnectToHost:
if error:
QtGui.QMessageBox.information(self, "FTP",
"Unable to connect to the FTP server at %s. Please "
"check that the host name is correct." % self.ftpServerLineEdit.text())
self.connectOrDisconnect()
return
self.statusLabel.setText("Logged onto %s." % self.ftpServerLineEdit.text())
self.fileList.setFocus()
self.downloadButton.setDefault(True)
self.connectButton.setEnabled(True)
return
if self.ftp.currentCommand() == QtNetwork.QFtp.Login:
self.ftp.list()
if self.ftp.currentCommand() == QtNetwork.QFtp.Get:
if error:
self.statusLabel.setText("Canceled download of %s." % self.outFile.fileName())
self.outFile.close()
self.outFile.remove()
else:
self.statusLabel.setText("Downloaded %s to current directory." % self.outFile.fileName())
self.outFile.close()
self.outFile = None
self.enableDownloadButton()
self.progressDialog.hide()
elif self.ftp.currentCommand() == QtNetwork.QFtp.List:
if not self.isDirectory:
self.fileList.addTopLevelItem(QtGui.QTreeWidgetItem(["<empty>"]))
self.fileList.setEnabled(False)
def addToList(self, urlInfo):
item = QtGui.QTreeWidgetItem()
item.setText(0, urlInfo.name())
item.setText(1, str(urlInfo.size()))
item.setText(2, urlInfo.owner())
item.setText(3, urlInfo.group())
item.setText(4, urlInfo.lastModified().toString('MMM dd yyyy'))
if urlInfo.isDir():
icon = QtGui.QIcon(':/images/dir.png')
else:
icon = QtGui.QIcon(':/images/file.png')
item.setIcon(0, icon)
self.isDirectory[urlInfo.name()] = urlInfo.isDir()
self.fileList.addTopLevelItem(item)
if not self.fileList.currentItem():
self.fileList.setCurrentItem(self.fileList.topLevelItem(0))
self.fileList.setEnabled(True)
def processItem(self, item):
name = item.text(0)
if self.isDirectory.get(name):
self.fileList.clear()
self.isDirectory.clear()
self.currentPath += '/' + name
self.ftp.cd(name)
self.ftp.list()
self.cdToParentButton.setEnabled(True)
self.setCursor(QtCore.Qt.WaitCursor)
def cdToParent(self):
self.setCursor(QtCore.Qt.WaitCursor)
self.fileList.clear()
self.isDirectory.clear()
dirs = self.currentPath.split('/')
if len(dirs) > 1:
self.currentPath = ''
self.cdToParentButton.setEnabled(False)
self.ftp.cd('/')
else:
self.currentPath = '/'.join(dirs[:-1])
self.ftp.cd(self.currentPath)
self.ftp.list()
def updateDataTransferProgress(self, readBytes, totalBytes):
self.progressDialog.setMaximum(totalBytes)
self.progressDialog.setValue(readBytes)
def enableDownloadButton(self):
current = self.fileList.currentItem()
if current:
currentFile = current.text(0)
self.downloadButton.setEnabled(not self.isDirectory.get(currentFile))
else:
self.downloadButton.setEnabled(False)
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
ftpWin = FtpWindow()
ftpWin.show()
sys.exit(ftpWin.exec_())
A:
Python's standard library is just a great place to start: http://docs.python.org/library/ftplib.html
Note: And if for some reason you want to write your own client, you can simple read the source, which is a good training exercise in itself ...
|
Creating an FTP client with Python
|
I've always thought about creating my own ftp client ever since I've started using the Internet. And now that I'm studying Python, I'm thinking about creating one as an exercises/personal project.
I'm wondering,
What libraries do you guys suggest? Will ftplib suffice? Or would you suggest another library(preferably one that has good docs)?
I'm thinking about using wxPython. Is it a good idea? Should I learn it first?
I'm coming from a Web Development background. What tips/suggestions would you guys give to me?
I'd appreciate any guidance/help. Thanks in advance! :)
|
[
"It sounds like you want to make a program that has a GUI. May I recommend using PyQt for that part of your application? ftplib should be fine for your FTP support, and you can find documentation right here.\nAlternatively for FTP support, you can use the QFtp class from the QtNetwork module from PyQt framework. The following is an example FTP client that comes with PyQt. The images come with it.\n#!/usr/bin/env python\n\n\"\"\"PyQt4 port of the network/ftp example from Qt v4.x\"\"\"\n\n# This is only needed for Python v2 but is harmless for Python v3.\nimport sip\nsip.setapi('QString', 2)\n\nfrom PyQt4 import QtCore, QtGui, QtNetwork\n\nimport ftp_rc\n\n\nclass FtpWindow(QtGui.QDialog):\n def __init__(self, parent=None):\n super(FtpWindow, self).__init__(parent)\n\n self.isDirectory = {}\n self.currentPath = ''\n self.ftp = None\n self.outFile = None\n\n ftpServerLabel = QtGui.QLabel(\"Ftp &server:\")\n self.ftpServerLineEdit = QtGui.QLineEdit('ftp.trolltech.com')\n ftpServerLabel.setBuddy(self.ftpServerLineEdit)\n\n self.statusLabel = QtGui.QLabel(\"Please enter the name of an FTP server.\")\n\n self.fileList = QtGui.QTreeWidget()\n self.fileList.setEnabled(False)\n self.fileList.setRootIsDecorated(False)\n self.fileList.setHeaderLabels((\"Name\", \"Size\", \"Owner\", \"Group\", \"Time\"))\n self.fileList.header().setStretchLastSection(False)\n\n self.connectButton = QtGui.QPushButton(\"Connect\")\n self.connectButton.setDefault(True)\n\n self.cdToParentButton = QtGui.QPushButton()\n self.cdToParentButton.setIcon(QtGui.QIcon(':/images/cdtoparent.png'))\n self.cdToParentButton.setEnabled(False)\n\n self.downloadButton = QtGui.QPushButton(\"Download\")\n self.downloadButton.setEnabled(False)\n\n self.quitButton = QtGui.QPushButton(\"Quit\")\n\n buttonBox = QtGui.QDialogButtonBox()\n buttonBox.addButton(self.downloadButton,\n QtGui.QDialogButtonBox.ActionRole)\n buttonBox.addButton(self.quitButton, QtGui.QDialogButtonBox.RejectRole)\n\n self.progressDialog = QtGui.QProgressDialog(self)\n\n self.fileList.itemActivated.connect(self.processItem)\n self.fileList.currentItemChanged.connect(self.enableDownloadButton)\n self.progressDialog.canceled.connect(self.cancelDownload)\n self.connectButton.clicked.connect(self.connectOrDisconnect)\n self.cdToParentButton.clicked.connect(self.cdToParent)\n self.downloadButton.clicked.connect(self.downloadFile)\n self.quitButton.clicked.connect(self.close)\n\n topLayout = QtGui.QHBoxLayout()\n topLayout.addWidget(ftpServerLabel)\n topLayout.addWidget(self.ftpServerLineEdit)\n topLayout.addWidget(self.cdToParentButton)\n topLayout.addWidget(self.connectButton)\n\n mainLayout = QtGui.QVBoxLayout()\n mainLayout.addLayout(topLayout)\n mainLayout.addWidget(self.fileList)\n mainLayout.addWidget(self.statusLabel)\n mainLayout.addWidget(buttonBox)\n self.setLayout(mainLayout)\n\n self.setWindowTitle(\"FTP\")\n\n def sizeHint(self):\n return QtCore.QSize(500, 300)\n\n def connectOrDisconnect(self):\n if self.ftp:\n self.ftp.abort()\n self.ftp.deleteLater()\n self.ftp = None\n\n self.fileList.setEnabled(False)\n self.cdToParentButton.setEnabled(False)\n self.downloadButton.setEnabled(False)\n self.connectButton.setEnabled(True)\n self.connectButton.setText(\"Connect\")\n self.setCursor(QtCore.Qt.ArrowCursor)\n\n return\n\n self.setCursor(QtCore.Qt.WaitCursor)\n\n self.ftp = QtNetwork.QFtp(self)\n self.ftp.commandFinished.connect(self.ftpCommandFinished)\n self.ftp.listInfo.connect(self.addToList)\n self.ftp.dataTransferProgress.connect(self.updateDataTransferProgress)\n\n self.fileList.clear()\n self.currentPath = ''\n self.isDirectory.clear()\n\n url = QtCore.QUrl(self.ftpServerLineEdit.text())\n if not url.isValid() or url.scheme().lower() != 'ftp':\n self.ftp.connectToHost(self.ftpServerLineEdit.text(), 21)\n self.ftp.login()\n else:\n self.ftp.connectToHost(url.host(), url.port(21))\n\n user_name = url.userName()\n if user_name:\n try:\n # Python v3.\n user_name = bytes(user_name, encoding='latin1')\n except:\n # Python v2.\n pass\n\n self.ftp.login(QtCore.QUrl.fromPercentEncoding(user_name), url.password())\n else:\n self.ftp.login()\n\n if url.path():\n self.ftp.cd(url.path())\n\n self.fileList.setEnabled(True)\n self.connectButton.setEnabled(False)\n self.connectButton.setText(\"Disconnect\")\n self.statusLabel.setText(\"Connecting to FTP server %s...\" % self.ftpServerLineEdit.text())\n\n def downloadFile(self):\n fileName = self.fileList.currentItem().text(0)\n\n if QtCore.QFile.exists(fileName):\n QtGui.QMessageBox.information(self, \"FTP\",\n \"There already exists a file called %s in the current \"\n \"directory.\" % fileName)\n return\n\n self.outFile = QtCore.QFile(fileName)\n if not self.outFile.open(QtCore.QIODevice.WriteOnly):\n QtGui.QMessageBox.information(self, \"FTP\",\n \"Unable to save the file %s: %s.\" % (fileName, self.outFile.errorString()))\n self.outFile = None\n return\n\n self.ftp.get(self.fileList.currentItem().text(0), self.outFile)\n\n self.progressDialog.setLabelText(\"Downloading %s...\" % fileName)\n self.downloadButton.setEnabled(False)\n self.progressDialog.exec_()\n\n def cancelDownload(self):\n self.ftp.abort()\n\n def ftpCommandFinished(self, _, error):\n self.setCursor(QtCore.Qt.ArrowCursor)\n\n if self.ftp.currentCommand() == QtNetwork.QFtp.ConnectToHost:\n if error:\n QtGui.QMessageBox.information(self, \"FTP\",\n \"Unable to connect to the FTP server at %s. Please \"\n \"check that the host name is correct.\" % self.ftpServerLineEdit.text())\n self.connectOrDisconnect()\n return\n\n self.statusLabel.setText(\"Logged onto %s.\" % self.ftpServerLineEdit.text())\n self.fileList.setFocus()\n self.downloadButton.setDefault(True)\n self.connectButton.setEnabled(True)\n return\n\n if self.ftp.currentCommand() == QtNetwork.QFtp.Login:\n self.ftp.list()\n\n if self.ftp.currentCommand() == QtNetwork.QFtp.Get:\n if error:\n self.statusLabel.setText(\"Canceled download of %s.\" % self.outFile.fileName())\n self.outFile.close()\n self.outFile.remove()\n else:\n self.statusLabel.setText(\"Downloaded %s to current directory.\" % self.outFile.fileName())\n self.outFile.close()\n\n self.outFile = None\n self.enableDownloadButton()\n self.progressDialog.hide()\n elif self.ftp.currentCommand() == QtNetwork.QFtp.List:\n if not self.isDirectory:\n self.fileList.addTopLevelItem(QtGui.QTreeWidgetItem([\"<empty>\"]))\n self.fileList.setEnabled(False)\n\n def addToList(self, urlInfo):\n item = QtGui.QTreeWidgetItem()\n item.setText(0, urlInfo.name())\n item.setText(1, str(urlInfo.size()))\n item.setText(2, urlInfo.owner())\n item.setText(3, urlInfo.group())\n item.setText(4, urlInfo.lastModified().toString('MMM dd yyyy'))\n\n if urlInfo.isDir():\n icon = QtGui.QIcon(':/images/dir.png')\n else:\n icon = QtGui.QIcon(':/images/file.png')\n item.setIcon(0, icon)\n\n self.isDirectory[urlInfo.name()] = urlInfo.isDir()\n self.fileList.addTopLevelItem(item)\n if not self.fileList.currentItem():\n self.fileList.setCurrentItem(self.fileList.topLevelItem(0))\n self.fileList.setEnabled(True)\n\n def processItem(self, item):\n name = item.text(0)\n if self.isDirectory.get(name):\n self.fileList.clear()\n self.isDirectory.clear()\n self.currentPath += '/' + name\n self.ftp.cd(name)\n self.ftp.list()\n self.cdToParentButton.setEnabled(True)\n self.setCursor(QtCore.Qt.WaitCursor)\n\n def cdToParent(self):\n self.setCursor(QtCore.Qt.WaitCursor)\n self.fileList.clear()\n self.isDirectory.clear()\n\n dirs = self.currentPath.split('/')\n if len(dirs) > 1:\n self.currentPath = ''\n self.cdToParentButton.setEnabled(False)\n self.ftp.cd('/')\n else:\n self.currentPath = '/'.join(dirs[:-1])\n self.ftp.cd(self.currentPath)\n\n self.ftp.list()\n\n def updateDataTransferProgress(self, readBytes, totalBytes):\n self.progressDialog.setMaximum(totalBytes)\n self.progressDialog.setValue(readBytes)\n\n def enableDownloadButton(self):\n current = self.fileList.currentItem()\n if current:\n currentFile = current.text(0)\n self.downloadButton.setEnabled(not self.isDirectory.get(currentFile))\n else:\n self.downloadButton.setEnabled(False)\n\n\nif __name__ == '__main__':\n\n import sys\n\n app = QtGui.QApplication(sys.argv)\n ftpWin = FtpWindow()\n ftpWin.show()\n sys.exit(ftpWin.exec_())\n\n",
"Python's standard library is just a great place to start: http://docs.python.org/library/ftplib.html\nNote: And if for some reason you want to write your own client, you can simple read the source, which is a good training exercise in itself ...\n"
] |
[
10,
4
] |
[] |
[] |
[
"ftp",
"python"
] |
stackoverflow_0001995046_ftp_python.txt
|
Q:
Why am I getting an error using 'set' in Python?
s = set('ABC')
s.add('z')
s.update('BCD')
s.remove('DEF') # error here
s -= set('DEFG')
A:
As others pointed out, 'DEF', the set member you're trying to remove, is not a member of the set, and remove, per the docs, is specified as "Raises KeyError if elem is not contained in the set.".
If you want "missing element" to mean a silent no=op instead, just use discard instead of remove: that's the crucial difference between the discard and remove methods of sets, and the very reason they both need to exist!
A:
The argument to set.remove() must be a set member.
'DEF' is not a member of your set. 'D' is.
A:
From http://docs.python.org/library/stdtypes.html :
remove(elem)
Remove element elem from the set. Raises KeyError if elem is not contained in the set.
'DEF' is not in the set
A:
Do you expect 'DEF' to be treated as an element or a set?
In the latter case use s.difference_update('DEF').
|
Why am I getting an error using 'set' in Python?
|
s = set('ABC')
s.add('z')
s.update('BCD')
s.remove('DEF') # error here
s -= set('DEFG')
|
[
"As others pointed out, 'DEF', the set member you're trying to remove, is not a member of the set, and remove, per the docs, is specified as \"Raises KeyError if elem is not contained in the set.\".\nIf you want \"missing element\" to mean a silent no=op instead, just use discard instead of remove: that's the crucial difference between the discard and remove methods of sets, and the very reason they both need to exist!\n",
"The argument to set.remove() must be a set member.\n'DEF' is not a member of your set. 'D' is.\n",
"From http://docs.python.org/library/stdtypes.html :\n\nremove(elem)\nRemove element elem from the set. Raises KeyError if elem is not contained in the set.\n\n'DEF' is not in the set\n",
"Do you expect 'DEF' to be treated as an element or a set?\nIn the latter case use s.difference_update('DEF').\n"
] |
[
16,
2,
0,
0
] |
[] |
[] |
[
"python",
"set"
] |
stackoverflow_0001994163_python_set.txt
|
Q:
Removing specific items from Django's cache?
I'm using site wide caching with memcached as the backend. I would like to invalidate pages in the cache when the underlying database object changes.
If the page name changes then I would invalidate the whole cache (as it affects navigation on every page. Clumsy but sufficient for my needs.
If just the page content changes then I'd like to invalidate the cache of just that page.
Is there an easy way to do this?
A:
I haven't done a lot of caching with Django, but I think what you want here are signals.
You can set up a post_save signal on the underlying object, and have the callback function invalidate that page in the cache.
from django.core.signals import post_save
from django.core.cache import cache
def invalidate_cache(sender, **kwargs):
# invalidate cache
cache.delete(sender.get_absolute_url()) # or any other pertinent keys
post_save.connect(invalidate_cache, sender=UnderlyingModel)
This should properly remove the item from the cache when it is updated.
A:
tghw's solution does not actually work, because the cache key is NOT the absolute path. The key is calculated from the absolute path and the HTTP headers. See this question for an example.
|
Removing specific items from Django's cache?
|
I'm using site wide caching with memcached as the backend. I would like to invalidate pages in the cache when the underlying database object changes.
If the page name changes then I would invalidate the whole cache (as it affects navigation on every page. Clumsy but sufficient for my needs.
If just the page content changes then I'd like to invalidate the cache of just that page.
Is there an easy way to do this?
|
[
"I haven't done a lot of caching with Django, but I think what you want here are signals.\nYou can set up a post_save signal on the underlying object, and have the callback function invalidate that page in the cache.\nfrom django.core.signals import post_save\nfrom django.core.cache import cache\n\ndef invalidate_cache(sender, **kwargs):\n # invalidate cache\n cache.delete(sender.get_absolute_url()) # or any other pertinent keys\n\npost_save.connect(invalidate_cache, sender=UnderlyingModel)\n\nThis should properly remove the item from the cache when it is updated.\n",
"tghw's solution does not actually work, because the cache key is NOT the absolute path. The key is calculated from the absolute path and the HTTP headers. See this question for an example.\n"
] |
[
6,
4
] |
[] |
[] |
[
"caching",
"django",
"memcached",
"python"
] |
stackoverflow_0000720800_caching_django_memcached_python.txt
|
Q:
i *must* store third party credentials in my database. best way?
My app must read an SSL url from a third party. How do I best store the third party credentials in my own database, which protects the third party credentials from being compromised? Consider both absolute security and practicality. One-way hashing the credentials is not useful as I must restore credentials to plaintext for the SSL call. I'm using python on google app engine, and my app authenticates with google credentials.
encrypt credentials using e.g. AES and save the encryption key somewhere else (just moves the problem), or derive it from the credentials and keep the algorithm secret (just moves the problem)
encrypt credentials using a synchronous stream cipher, derive the (not)entropy from the credentials and keep the algorithm secret (just moves the problem)
on a separate web app dedicated to storing third party credentials, provide a SSL url to receive the third party credentials, this url is accessed with google credentials (same as my app) and can use authsub or something to transfer authorization to the other web app. this sounds more secure because its harder to hack a trivially simple webapp, and if my complex main app gets compromised the third party credentials aren't exposed.
what do you think about all approaches?
A:
How are the credentials being used? If their use is only triggered by the original owner (eg. you're storing a bank card number and they're making their 2nd purchase) then they can provide a password at that point which is used as your encryption key. You would then never need to store that key locally and the database content alone is useless to an attacker.
A:
It's a difficult task, and no approach will save you the trouble to make sure that there is no weak link. For starters, I wouldn't know if hosting on Google is the best way to go, because you will be forfeiting control (I really don't know if App Engine is designed with the required level of security in mind, you should find that out) and probably cannot do penetration testing (which you should.)
Having a separate small application is probably a good idea, but that doesn't save you from having to encrypt one way or the other the credentials themselves in this smaller app. It just buys you simplicity, which in turn makes things easier to analyze.
I personally would try to design the app so the key changes randomly after each use, having a kind of one time pad approach. You don't specify the app in enough detail to see if this is feasible.
A:
If you need to reversably store credentials there simply is no solution. Use AES and keep the secret key under well paid armed guard.
If your using windows I would check out the Cred* Win32 API (advapi32.dll) it would at least allow you to punt key management to windows syskey where TPM and or bootup passphrase can provide protection against low level compromise (stolen disk drives)
Obviously if your application or the security context within which it runs is compromised none of the above would be of much help.
A:
A decent book that covers this sort of situation is Cryptography In The Database.
|
i *must* store third party credentials in my database. best way?
|
My app must read an SSL url from a third party. How do I best store the third party credentials in my own database, which protects the third party credentials from being compromised? Consider both absolute security and practicality. One-way hashing the credentials is not useful as I must restore credentials to plaintext for the SSL call. I'm using python on google app engine, and my app authenticates with google credentials.
encrypt credentials using e.g. AES and save the encryption key somewhere else (just moves the problem), or derive it from the credentials and keep the algorithm secret (just moves the problem)
encrypt credentials using a synchronous stream cipher, derive the (not)entropy from the credentials and keep the algorithm secret (just moves the problem)
on a separate web app dedicated to storing third party credentials, provide a SSL url to receive the third party credentials, this url is accessed with google credentials (same as my app) and can use authsub or something to transfer authorization to the other web app. this sounds more secure because its harder to hack a trivially simple webapp, and if my complex main app gets compromised the third party credentials aren't exposed.
what do you think about all approaches?
|
[
"How are the credentials being used? If their use is only triggered by the original owner (eg. you're storing a bank card number and they're making their 2nd purchase) then they can provide a password at that point which is used as your encryption key. You would then never need to store that key locally and the database content alone is useless to an attacker.\n",
"It's a difficult task, and no approach will save you the trouble to make sure that there is no weak link. For starters, I wouldn't know if hosting on Google is the best way to go, because you will be forfeiting control (I really don't know if App Engine is designed with the required level of security in mind, you should find that out) and probably cannot do penetration testing (which you should.) \nHaving a separate small application is probably a good idea, but that doesn't save you from having to encrypt one way or the other the credentials themselves in this smaller app. It just buys you simplicity, which in turn makes things easier to analyze.\nI personally would try to design the app so the key changes randomly after each use, having a kind of one time pad approach. You don't specify the app in enough detail to see if this is feasible.\n",
"If you need to reversably store credentials there simply is no solution. Use AES and keep the secret key under well paid armed guard.\nIf your using windows I would check out the Cred* Win32 API (advapi32.dll) it would at least allow you to punt key management to windows syskey where TPM and or bootup passphrase can provide protection against low level compromise (stolen disk drives)\nObviously if your application or the security context within which it runs is compromised none of the above would be of much help.\n",
"A decent book that covers this sort of situation is Cryptography In The Database.\n"
] |
[
3,
2,
2,
2
] |
[] |
[] |
[
"authentication",
"google_app_engine",
"passwords",
"python",
"security"
] |
stackoverflow_0001994112_authentication_google_app_engine_passwords_python_security.txt
|
Q:
Python vs. Java -- Which would you pick to do concurrent programming and why?
Also, if not python or java, then would you more generally pick a statically-typed language or a dynamic-type language?
A:
I would choose the JVM over python, primarily because multi-threading in Python is impeded by the Global Interpreter Lock. However, Java is unlikely to be your best when running on the JVM. Clojure or Scala (using actors) are both likely to be better suited to multi-threaded problems.
If you do choose Java you should consider making use of the java.util.concurrent libraries and avoid multi-threading primitives such as synchronized.
A:
For concurrency, I would use Java. By use Java, I actually mean Scala, which borrows a lot from Erlang's concurrency constructs, but is (probably) more accessible to a Java developer who has never used either before.
Python threads suffer from having to wait for the Global Interpreter Lock, making true concurrency (within a single process) unachievable for CPU-bound programs. As I understand, Stackless Python solves some (though not all) of CPython's concurrency deficiencies, but as I have not used it, I can't really advise on it.
A:
Definetely Stackless Python! That a Python variant especially made for concurrency.
But in the end it depends on your target platform and what you are trying to achieve.
A:
If not Java/Python I would go for a functional language since taking side effects into account is one of the complexities of writing concurrent software. (As far as your question goes : this one happens to be statical typed, but compiler infered most of the time)
Personally I would pick F#, since I've seen lots of nice examples of writing concurrent software with ease using it.
As an introduction : this man is equally fun as inspiring, even a must have seen if you are not interested in F# what so ever.
A:
I don't think the argument is about language choice or static or dynamic typing - it's between two models of concurrency - shared memory and message passing. Which model makes more sense in your situation & does your chosen language allow you to make a choice or are you forced to adopt one model over the other?
Why not have a look at Erlang (which has dynamic typing) and message passing, the Actor model, and read why Joe Armstrong doesn't like shared memory. There's also a interesting discussion about java concurrency using locks and threads here on SO.
I don't know about Python, but Java, along with the inbuilt locks and threads model, has a mesasge passing framework called Kilim.
A:
I would use Java, via Jython. Java has strong thread capabilities, and it can be written using the Python syntax with Jython, so you got the best of the two worlds.
Python itself is not really good with concurrency, and is slower than Java anyway.
But if you have concurrency issues and free hands, I'd have a look at Erlang because it has been design for such problems. Of course, you must consider Erlang only if you have:
time to master a (very) new technology
control on a reasonable part of the production chain, since Erland need some adaptations in your toolbox to fit
A:
Neither. Concurrent programming is notoriously hard to get correct. There is the option of using a process oriented programming language like occam-pi which is based of the idea of communicating sequential processes and the pi calculus. This allows compile time checking for deadlock and many other problems that arise during concurrent systems development. If you do not like occam-pi, which I cant blame you if you dont, you could try Go the new language from google which also implements a version of CSP.
A:
For some tasks, Python is too slow. Your single thread Java program could be faster than the concurrent version of Python on a multi-core computer...
I'd like to use Java or Scala, F# or simply go to C++(MPI and OpenMPI).
A:
The Java environment (JVM + libraries) is better for concurrency than (C)Python, but Java the language sucks. I would probably go with another language on the JVM - Jython has already been mentioned, and Clojure and Scala both have excellent support for concurrency.
Clojure is particularly good - it has support for high performance persistent data structures, agents and software transactional memory. It is a dynamic language but you can give it type hints to get performance as good as Java.
Watch this video on InfoQ by Richard Hickey (creator of Clojure) on the problems with traditional approaches to concurrency, and how Clojure handles it.
A:
I'd look at Objective-C and the Foundation Framework. Asynchronous, concurrent programming is well provided for.
This of course depends on your access to Apple's Developer Tools or GnuStep, but if you have access to either one it's a good route to take with concurrent programming.
A:
The answer is that it depends. For example are you trying to take advantage of multiple cores or cpus on a single machine or are you wanting to distribute your task across many machines? How important is speed vs. ease of implementation?
As mentioned before, Python has the Global Interpreter Lock but you could use the multiprocessing module. Note that while Stackless is very cool, it won't utilise multiple cores on its own. Python is usually considered easier to work with than Java. If speed is a priority Java is usually faster.
The java.util.concurrent library in Java makes writing concurrent applications on a single machine simpler but you'll still need to synchronise around any shared state. While Java isn't necessarily the best language for concurrency, there are a lot of tools, libraries, documentation and best practices out there to help.
Using message passing and immutability instead of threads and shared state is considered the better approach to programming concurrent applications. Functional languages that discourage mutability and side effects are often preferred as a result. If distributing your concurrent applications across multiple machines is a requirement, it is worth looking at runtimes designed for this e.g. Erlang or Scala Actors.
|
Python vs. Java -- Which would you pick to do concurrent programming and why?
|
Also, if not python or java, then would you more generally pick a statically-typed language or a dynamic-type language?
|
[
"I would choose the JVM over python, primarily because multi-threading in Python is impeded by the Global Interpreter Lock. However, Java is unlikely to be your best when running on the JVM. Clojure or Scala (using actors) are both likely to be better suited to multi-threaded problems.\nIf you do choose Java you should consider making use of the java.util.concurrent libraries and avoid multi-threading primitives such as synchronized.\n",
"For concurrency, I would use Java. By use Java, I actually mean Scala, which borrows a lot from Erlang's concurrency constructs, but is (probably) more accessible to a Java developer who has never used either before.\nPython threads suffer from having to wait for the Global Interpreter Lock, making true concurrency (within a single process) unachievable for CPU-bound programs. As I understand, Stackless Python solves some (though not all) of CPython's concurrency deficiencies, but as I have not used it, I can't really advise on it.\n",
"Definetely Stackless Python! That a Python variant especially made for concurrency. \nBut in the end it depends on your target platform and what you are trying to achieve. \n",
"If not Java/Python I would go for a functional language since taking side effects into account is one of the complexities of writing concurrent software. (As far as your question goes : this one happens to be statical typed, but compiler infered most of the time)\nPersonally I would pick F#, since I've seen lots of nice examples of writing concurrent software with ease using it.\nAs an introduction : this man is equally fun as inspiring, even a must have seen if you are not interested in F# what so ever. \n",
"I don't think the argument is about language choice or static or dynamic typing - it's between two models of concurrency - shared memory and message passing. Which model makes more sense in your situation & does your chosen language allow you to make a choice or are you forced to adopt one model over the other?\nWhy not have a look at Erlang (which has dynamic typing) and message passing, the Actor model, and read why Joe Armstrong doesn't like shared memory. There's also a interesting discussion about java concurrency using locks and threads here on SO.\nI don't know about Python, but Java, along with the inbuilt locks and threads model, has a mesasge passing framework called Kilim.\n",
"I would use Java, via Jython. Java has strong thread capabilities, and it can be written using the Python syntax with Jython, so you got the best of the two worlds.\nPython itself is not really good with concurrency, and is slower than Java anyway.\nBut if you have concurrency issues and free hands, I'd have a look at Erlang because it has been design for such problems. Of course, you must consider Erlang only if you have:\n\ntime to master a (very) new technology\ncontrol on a reasonable part of the production chain, since Erland need some adaptations in your toolbox to fit\n\n",
"Neither. Concurrent programming is notoriously hard to get correct. There is the option of using a process oriented programming language like occam-pi which is based of the idea of communicating sequential processes and the pi calculus. This allows compile time checking for deadlock and many other problems that arise during concurrent systems development. If you do not like occam-pi, which I cant blame you if you dont, you could try Go the new language from google which also implements a version of CSP.\n",
"For some tasks, Python is too slow. Your single thread Java program could be faster than the concurrent version of Python on a multi-core computer...\nI'd like to use Java or Scala, F# or simply go to C++(MPI and OpenMPI).\n",
"The Java environment (JVM + libraries) is better for concurrency than (C)Python, but Java the language sucks. I would probably go with another language on the JVM - Jython has already been mentioned, and Clojure and Scala both have excellent support for concurrency. \nClojure is particularly good - it has support for high performance persistent data structures, agents and software transactional memory. It is a dynamic language but you can give it type hints to get performance as good as Java.\nWatch this video on InfoQ by Richard Hickey (creator of Clojure) on the problems with traditional approaches to concurrency, and how Clojure handles it.\n",
"I'd look at Objective-C and the Foundation Framework. Asynchronous, concurrent programming is well provided for.\nThis of course depends on your access to Apple's Developer Tools or GnuStep, but if you have access to either one it's a good route to take with concurrent programming.\n",
"The answer is that it depends. For example are you trying to take advantage of multiple cores or cpus on a single machine or are you wanting to distribute your task across many machines? How important is speed vs. ease of implementation?\nAs mentioned before, Python has the Global Interpreter Lock but you could use the multiprocessing module. Note that while Stackless is very cool, it won't utilise multiple cores on its own. Python is usually considered easier to work with than Java. If speed is a priority Java is usually faster.\nThe java.util.concurrent library in Java makes writing concurrent applications on a single machine simpler but you'll still need to synchronise around any shared state. While Java isn't necessarily the best language for concurrency, there are a lot of tools, libraries, documentation and best practices out there to help.\nUsing message passing and immutability instead of threads and shared state is considered the better approach to programming concurrent applications. Functional languages that discourage mutability and side effects are often preferred as a result. If distributing your concurrent applications across multiple machines is a requirement, it is worth looking at runtimes designed for this e.g. Erlang or Scala Actors.\n"
] |
[
31,
12,
11,
6,
5,
2,
2,
1,
1,
1,
1
] |
[] |
[] |
[
"concurrency",
"java",
"python",
"python_stackless"
] |
stackoverflow_0001861457_concurrency_java_python_python_stackless.txt
|
Q:
How can I turn 000000000001 into 1?
I need to turn a formatted integer into a regular integer:
000000000001 needs to be turned into 1
000000000053 needs to be turned into 53
000000965948 needs to be turned into 965948
And so on.
It seems that a simple int(000000000015) results in the number 13. I understand there is some weird stuff behind the scenes. What is the best way to do this accurately every time?
A:
Numbers starting with 0 are considered octal.
>>> 07
7
>>> 08
File "<stdin>", line 1
08
^
SyntaxError: invalid token
You can wrap your zero-padded number into a string, then it should work.
>>> int("08")
8
int() takes an optional argument, which is the base, so the above would be the equivalent of:
>>> int("08", 10)
8
A:
The leading zeroes are considered octal. I am assuming that you are converting the string "000000013", not literal 000000013, so you should be able to convert these to base 10 integer by int("000000013",10)
If the "harm has already been done", and they are literals, that have already been converted to octal literals, you can use the following (beware, this is harmful and heresy:)
int(("%o" % 00000013),10)
A:
Try this:
>>> int('00000000053', 10)
53
|
How can I turn 000000000001 into 1?
|
I need to turn a formatted integer into a regular integer:
000000000001 needs to be turned into 1
000000000053 needs to be turned into 53
000000965948 needs to be turned into 965948
And so on.
It seems that a simple int(000000000015) results in the number 13. I understand there is some weird stuff behind the scenes. What is the best way to do this accurately every time?
|
[
"Numbers starting with 0 are considered octal.\n>>> 07\n7\n>>> 08\n File \"<stdin>\", line 1\n 08\n ^\nSyntaxError: invalid token\n\nYou can wrap your zero-padded number into a string, then it should work.\n>>> int(\"08\")\n8\n\nint() takes an optional argument, which is the base, so the above would be the equivalent of:\n>>> int(\"08\", 10)\n8\n\n",
"The leading zeroes are considered octal. I am assuming that you are converting the string \"000000013\", not literal 000000013, so you should be able to convert these to base 10 integer by int(\"000000013\",10)\nIf the \"harm has already been done\", and they are literals, that have already been converted to octal literals, you can use the following (beware, this is harmful and heresy:)\nint((\"%o\" % 00000013),10)\n\n",
"Try this:\n>>> int('00000000053', 10)\n53\n\n"
] |
[
11,
8,
3
] |
[
"if x = \"0000000000000001\":\n x = 1\n\n"
] |
[
-8
] |
[
"integer",
"parsing",
"python"
] |
stackoverflow_0001995602_integer_parsing_python.txt
|
Q:
Django/Python: How can I make the following number increment (not in database)
I would like to create a number like:
000000000001
to save to the database. I obviously cannot increment in this fashion (I don't think) in a database, so I'm looking for the most efficient method for pulling the previous number from the database and incrementing it by 1 to create the next record:
000000000002
and so on...
If I store the first number manually, can I do some sort of manual typing to make it hold its number of zeros? I don't even know where to start.
A:
All the leading zeroes are just formatting.
>>> "%012d" % ( 1, )
'000000000001'
>>> "%012d" % ( 2, )
'000000000002'
Use an ordinary integer and format it to have lots of leading zeroes.
A:
There's actually a super tricky way to do this using the itertools library and a generator function.
from itertools import product, imap
def stringdigit(num_digits=10, start = None):
"""A generator function which returns string versions of a large iterated number with
leading zeros. start allows you to define a place to begin the iteration"""
treatfun = lambda x: ''.join(x)
for n in imap(treatfun, product('0123456789', repeat = num_digits)):
if start == None or n > start:
yield n
This creates an iterator which will return the "zero-padded string form" that you need. It works using the product function which iteratively returns repeated combinations from an iterable in "sorted order". The num_digits argument specifies how many total digits you would like returned. start specifies a place to begin the iteration from (say if you wanted to start from 1111111).
product comes with the python 2.6 release. If your using something before that for some reason then use this as the product definition. Taken from the docs here.
def product(*args, **kwds):
# product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
# product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
pools = map(tuple, args) * kwds.get('repeat', 1)
result = [[]]
for pool in pools:
result = [x+[y] for x in result for y in pool]
for prod in result:
yield tuple(prod)
You can use this function in in a for-loop as an interator:
for num in stringdigit(num_digits = 7):
#do stuff with num
Hope that helps.
-Will
|
Django/Python: How can I make the following number increment (not in database)
|
I would like to create a number like:
000000000001
to save to the database. I obviously cannot increment in this fashion (I don't think) in a database, so I'm looking for the most efficient method for pulling the previous number from the database and incrementing it by 1 to create the next record:
000000000002
and so on...
If I store the first number manually, can I do some sort of manual typing to make it hold its number of zeros? I don't even know where to start.
|
[
"All the leading zeroes are just formatting.\n>>> \"%012d\" % ( 1, )\n'000000000001'\n>>> \"%012d\" % ( 2, )\n'000000000002'\n\nUse an ordinary integer and format it to have lots of leading zeroes.\n",
"There's actually a super tricky way to do this using the itertools library and a generator function.\nfrom itertools import product, imap\n\ndef stringdigit(num_digits=10, start = None):\n \"\"\"A generator function which returns string versions of a large iterated number with\n leading zeros. start allows you to define a place to begin the iteration\"\"\"\n treatfun = lambda x: ''.join(x)\n for n in imap(treatfun, product('0123456789', repeat = num_digits)):\n if start == None or n > start:\n yield n\n\nThis creates an iterator which will return the \"zero-padded string form\" that you need. It works using the product function which iteratively returns repeated combinations from an iterable in \"sorted order\". The num_digits argument specifies how many total digits you would like returned. start specifies a place to begin the iteration from (say if you wanted to start from 1111111).\nproduct comes with the python 2.6 release. If your using something before that for some reason then use this as the product definition. Taken from the docs here.\ndef product(*args, **kwds):\n # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy\n # product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111\n pools = map(tuple, args) * kwds.get('repeat', 1)\n result = [[]]\n for pool in pools:\n result = [x+[y] for x in result for y in pool]\n for prod in result:\n yield tuple(prod)\n\nYou can use this function in in a for-loop as an interator:\nfor num in stringdigit(num_digits = 7):\n #do stuff with num\n\nHope that helps.\n-Will\n"
] |
[
7,
1
] |
[] |
[] |
[
"auto_increment",
"django",
"python"
] |
stackoverflow_0001995561_auto_increment_django_python.txt
|
Q:
Optimization of Google App Engine Code
Google app engine tells me to optimize this code. Anybody any ideas what I could do?
def index(request):
user = users.get_current_user()
return base.views.render('XXX.html',
dict(profiles=Profile.gql("").fetch(limit=100), user=user))
And later in the template I do:
{% for profile in profiles %}
<a href="/profile/{{profile.user.email}}/"><img src="{{profile.gravatarUrl}}"></a>
<a href="/profile/{{profile.user.email}}/">{{ profile.user.nickname }}</a>
<br/>{{ profile.shortDisplay }}
Where the methods used are:
def shortDisplay(self):
return "%s/day; %s/week; %s days" % (self.maxPerDay, self.maxPerWeek, self.days)
def gravatarUrl(self):
email = self.user.email().lower()
default = "..."
gravatar_url = "http://www.gravatar.com/avatar.php?"
gravatar_url += urllib.urlencode({'gravatar_id':hashlib.md5(email).hexdigest(),
'default':default, 'size':"64"})
return gravatar_url
A:
The high CPU usage will be due to fetching 100 entities per request. You have several options here:
Using Profile.all().fetch(100) will be ever so slightly faster, and easier to read besides.
Remove any extraneous properties from the Profile model. There's significant per-property overhead deserializing entities.
Display fewer users per page.
Store the output of this page in memcache, and render from memcache whenever you can. That way, you don't need to generate the page often, so it doesn't matter so much if it's high CPU.
A:
I would guess that performing an md5 hash on every item every time is pretty costly. Better store the gravatar email hash somewhere.
A:
I had an issue with a lot of CPU being used for seemingly little work, which turned out ot be queries running multiple times. Eg. In my Django template, I did post.comments.count and then looped through post.comments. This resulted in two executions - one getting the count, and one getting the entities. Oops!
I'd also say grab a copy of Guido's Appstats. It won't help with the Python, but it's very useful to see the time spent in API calls (and the time between them - which often gives an indication of where you've got slow Python).
You can get the library here: https://sites.google.com/site/appengineappstats/
I wrote an article about it on my blog (with some screenshots): http://blog.dantup.com/2010/01/profiling-google-app-engine-with-appstats
Appstats http://blog.dantup.com/pi/appstats_4_thumb.png
A:
It depends where you get the warning of too much CPU.
Is it in the dashboard, it probably is a lot of datastore CPU, no need for optimization.
If the request takes more then 10 sec you need to optimize.
If you get regular Log warnings that a certain request is x.xx over CPU limit it means your application code is taking too long. And needs optimization.
I have found that a lot of Django template stuff does not take a lot of application CPU (50-100 Mcycle). If all the fields for the template are precomputed.
|
Optimization of Google App Engine Code
|
Google app engine tells me to optimize this code. Anybody any ideas what I could do?
def index(request):
user = users.get_current_user()
return base.views.render('XXX.html',
dict(profiles=Profile.gql("").fetch(limit=100), user=user))
And later in the template I do:
{% for profile in profiles %}
<a href="/profile/{{profile.user.email}}/"><img src="{{profile.gravatarUrl}}"></a>
<a href="/profile/{{profile.user.email}}/">{{ profile.user.nickname }}</a>
<br/>{{ profile.shortDisplay }}
Where the methods used are:
def shortDisplay(self):
return "%s/day; %s/week; %s days" % (self.maxPerDay, self.maxPerWeek, self.days)
def gravatarUrl(self):
email = self.user.email().lower()
default = "..."
gravatar_url = "http://www.gravatar.com/avatar.php?"
gravatar_url += urllib.urlencode({'gravatar_id':hashlib.md5(email).hexdigest(),
'default':default, 'size':"64"})
return gravatar_url
|
[
"The high CPU usage will be due to fetching 100 entities per request. You have several options here:\n\nUsing Profile.all().fetch(100) will be ever so slightly faster, and easier to read besides.\nRemove any extraneous properties from the Profile model. There's significant per-property overhead deserializing entities.\nDisplay fewer users per page.\nStore the output of this page in memcache, and render from memcache whenever you can. That way, you don't need to generate the page often, so it doesn't matter so much if it's high CPU.\n\n",
"I would guess that performing an md5 hash on every item every time is pretty costly. Better store the gravatar email hash somewhere.\n",
"I had an issue with a lot of CPU being used for seemingly little work, which turned out ot be queries running multiple times. Eg. In my Django template, I did post.comments.count and then looped through post.comments. This resulted in two executions - one getting the count, and one getting the entities. Oops!\nI'd also say grab a copy of Guido's Appstats. It won't help with the Python, but it's very useful to see the time spent in API calls (and the time between them - which often gives an indication of where you've got slow Python).\nYou can get the library here: https://sites.google.com/site/appengineappstats/\nI wrote an article about it on my blog (with some screenshots): http://blog.dantup.com/2010/01/profiling-google-app-engine-with-appstats\nAppstats http://blog.dantup.com/pi/appstats_4_thumb.png\n",
"It depends where you get the warning of too much CPU.\nIs it in the dashboard, it probably is a lot of datastore CPU, no need for optimization.\nIf the request takes more then 10 sec you need to optimize.\nIf you get regular Log warnings that a certain request is x.xx over CPU limit it means your application code is taking too long. And needs optimization.\nI have found that a lot of Django template stuff does not take a lot of application CPU (50-100 Mcycle). If all the fields for the template are precomputed.\n"
] |
[
6,
3,
1,
0
] |
[] |
[] |
[
"google_app_engine",
"optimization",
"python"
] |
stackoverflow_0000298185_google_app_engine_optimization_python.txt
|
Q:
Polymorphism in Django
I have the following models. How do I get access to the unicode of the inheriting tables (Team and Athete) from the Entity table? I'm trying to display a list of all the Entities that displays 'name' if Team and 'firstname' and 'lastname' if Athlete.
class Entity(models.Model):
entity_type_list = (('T', 'Team'), ('A', 'Athlete'))
type = models.CharField(max_length=2, choices=entity_type_list,default='P')
pictureurl = models.URLField('Picture Url', verify_exists=False, max_length=255, null=True, blank=True)
class Team(Entity):
name = models.CharField(max_length=100)
def __unicode__(self):
return self.name
class Athlete(Entity):
firstname = models.CharField(max_length=100)
lastname = models.CharField(max_length=100)
def __unicode__(self):
return '%s %s' % (self.firstname, self.lastname)
A:
This answer from Carl Meyer to the question mentioned earlier by Paul McMillan might be what your looking for. A subtlety to this problem not captured in some of the answers is how to get at derived class instances from a QuerySet on Entity.
The Problem
for entity in Entity.objects.all()
print unicode(entity) # Calls the Entity class unicode, which is not what you want.
A Solution
Use the InheritanceCastModel mixin in the answer linked above as a base class for Entity. You can then cast from Entity instances to the actual derived class instances. This is particularly handy when you want to use querysets on your parent class (Entity) but access the derived class instances.
class Entity(InheritanceCastModel):
# your model definition. You can get rid of the entity_type_list and type, as the
# real_type provided by InheritanceCastModel provides this info
class Athlete(Entity):
# unchanged
class Team(Entity):
# unchanged
for entity in Entity.objects.all():
actual_entity = entity.cast()
print unicode(actual_entity) # actual entity is a a Team or Athlete
A:
From pure Python, you can use the isinstance function:
class Entity:
def __init__(self):
if isinstance(self, Team):
print 'is team'
elif isinstance(self, Athlete):
print 'is athlete'
class Team(Entity):
def __unicode__(self):
return 'Team'
class Athlete(Entity):
def __unicode__(self):
return 'Athlete'
A:
Loop over all the entities... if entity.class == 'Athlete' and entity.firstname and entity.lastname: blah
Hope this helps.
Edit: hmmm looks like I forgot about actually getting the combined list of both entities. Not sure I know of a slick way to do that.
A:
I answered a similar question a while ago. Have a look, I think one of the answers probably solves your problem as well.
How do I access the child classes of an object in django without knowing the name of the child class?
My answer from there was to add this to the parent class:
def get_children(self):
rel_objs = self._meta.get_all_related_objects()
return [getattr(self, x.get_accessor_name()) for x in rel_objs if x.model != type(self)]
Then you can call that function to get the children objects (in your case you will only have one) and then call the unicode function from that object.
A:
I am not very clear what you want to do, but in any case you can add a criteria in dervied class instead of checking unicode method of derived classes
e.g. you can ask the class isTypeA ? or why don't you check the type?
A:
This is a little ugly, but I think it should work:
entities = Entity.objects.all()
for entity in entities:
try:
print entity.team
except:
print entity.athlete
Check out http://docs.djangoproject.com/en/1.0/topics/db/models/#id7 for more on multi-table inheritance. Just be careful, because the Django ORM is inevitably a leaky abstraction and things you might normally do with objects can get you in trouble, or do unexpected things.
A:
If I undestand correctly, you are simply asking how to call the __unicode__ method of a given object.
Use unicode(instance) and depending on the type of entity, the appropriate implementation will be called polymorphically.
A:
I don't believe you have to do anything. If Entity is never instantiated directly, you will never call the non-existent Entity.__unicode__ method. However, if you'd like to play it save, you could add a stub method in your Entity class:
class Entity(models.Model):
def __unicode__(self):
pass
class Team(Entity):
def __unicode__(self):
return self.name
class Athlete(Entity):
def __unicode__(self):
return '%s %s' % (self.firstname, self.lastname)
You are now assured that any class which inherits from Entity will have a __unicode__ method, and you can simply traverse them:
for thing in [TeamA(), AthleteA(), TeamB(), AthleteB()]:
print unicode(thing)
|
Polymorphism in Django
|
I have the following models. How do I get access to the unicode of the inheriting tables (Team and Athete) from the Entity table? I'm trying to display a list of all the Entities that displays 'name' if Team and 'firstname' and 'lastname' if Athlete.
class Entity(models.Model):
entity_type_list = (('T', 'Team'), ('A', 'Athlete'))
type = models.CharField(max_length=2, choices=entity_type_list,default='P')
pictureurl = models.URLField('Picture Url', verify_exists=False, max_length=255, null=True, blank=True)
class Team(Entity):
name = models.CharField(max_length=100)
def __unicode__(self):
return self.name
class Athlete(Entity):
firstname = models.CharField(max_length=100)
lastname = models.CharField(max_length=100)
def __unicode__(self):
return '%s %s' % (self.firstname, self.lastname)
|
[
"This answer from Carl Meyer to the question mentioned earlier by Paul McMillan might be what your looking for. A subtlety to this problem not captured in some of the answers is how to get at derived class instances from a QuerySet on Entity.\nThe Problem\nfor entity in Entity.objects.all()\n print unicode(entity) # Calls the Entity class unicode, which is not what you want.\n\nA Solution\nUse the InheritanceCastModel mixin in the answer linked above as a base class for Entity. You can then cast from Entity instances to the actual derived class instances. This is particularly handy when you want to use querysets on your parent class (Entity) but access the derived class instances. \nclass Entity(InheritanceCastModel):\n # your model definition. You can get rid of the entity_type_list and type, as the\n # real_type provided by InheritanceCastModel provides this info\n\nclass Athlete(Entity):\n # unchanged\n\nclass Team(Entity):\n # unchanged\n\nfor entity in Entity.objects.all():\n actual_entity = entity.cast()\n print unicode(actual_entity) # actual entity is a a Team or Athlete\n\n",
"From pure Python, you can use the isinstance function:\nclass Entity:\n def __init__(self):\n if isinstance(self, Team):\n print 'is team'\n elif isinstance(self, Athlete):\n print 'is athlete'\n\nclass Team(Entity):\n def __unicode__(self):\n return 'Team'\n\nclass Athlete(Entity):\n def __unicode__(self):\n return 'Athlete'\n\n",
"Loop over all the entities... if entity.class == 'Athlete' and entity.firstname and entity.lastname: blah\nHope this helps.\nEdit: hmmm looks like I forgot about actually getting the combined list of both entities. Not sure I know of a slick way to do that.\n",
"I answered a similar question a while ago. Have a look, I think one of the answers probably solves your problem as well.\nHow do I access the child classes of an object in django without knowing the name of the child class?\nMy answer from there was to add this to the parent class:\ndef get_children(self):\n rel_objs = self._meta.get_all_related_objects()\n return [getattr(self, x.get_accessor_name()) for x in rel_objs if x.model != type(self)]\n\nThen you can call that function to get the children objects (in your case you will only have one) and then call the unicode function from that object.\n",
"I am not very clear what you want to do, but in any case you can add a criteria in dervied class instead of checking unicode method of derived classes\ne.g. you can ask the class isTypeA ? or why don't you check the type?\n",
"This is a little ugly, but I think it should work:\nentities = Entity.objects.all()\nfor entity in entities:\n try:\n print entity.team\n except:\n print entity.athlete\n\nCheck out http://docs.djangoproject.com/en/1.0/topics/db/models/#id7 for more on multi-table inheritance. Just be careful, because the Django ORM is inevitably a leaky abstraction and things you might normally do with objects can get you in trouble, or do unexpected things.\n",
"If I undestand correctly, you are simply asking how to call the __unicode__ method of a given object. \nUse unicode(instance) and depending on the type of entity, the appropriate implementation will be called polymorphically.\n",
"I don't believe you have to do anything. If Entity is never instantiated directly, you will never call the non-existent Entity.__unicode__ method. However, if you'd like to play it save, you could add a stub method in your Entity class:\nclass Entity(models.Model):\n\n def __unicode__(self):\n pass\n\nclass Team(Entity):\n\n def __unicode__(self):\n return self.name\n\nclass Athlete(Entity):\n\n def __unicode__(self):\n return '%s %s' % (self.firstname, self.lastname)\n\nYou are now assured that any class which inherits from Entity will have a __unicode__ method, and you can simply traverse them:\nfor thing in [TeamA(), AthleteA(), TeamB(), AthleteB()]:\n print unicode(thing)\n\n"
] |
[
6,
1,
0,
0,
0,
0,
0,
0
] |
[] |
[] |
[
"django",
"inheritance",
"python"
] |
stackoverflow_0001397537_django_inheritance_python.txt
|
Q:
How to reset Python interpreter to a 'safe' state?
I have a C++ app that embeds the Python interpreter. There are points in the code where the interpreter may get interrupted and I need to make sure the interpreter is in a 'safe' state to execute new code. I would just call Py_Finalize and re-initialize everything except I have a bunch of PyObject * references that I need to stay valid. Is there a function to do this or is it even necessary? When I mentioned the interpreter being interrupted above, I meant by a seg. fault or access violation which my app tries to recover from.
A:
Er, trying to "recover" from a segfault or access violation is quite dangerous. There is a reason you get these in the first place, and it's that your program has tried to do something which it shouldn't have tried to do; therefore it has hit a bug or an unforeseen condition.
There is no provision in the Python interpreter to roll back to a "safe point" in cases such as those mentioned. Even finalizing and reinitializing the interpreter might still leave some static data in a inconsistent state.
If you told us why you are trying to do this we might be able to suggest an alternative.
|
How to reset Python interpreter to a 'safe' state?
|
I have a C++ app that embeds the Python interpreter. There are points in the code where the interpreter may get interrupted and I need to make sure the interpreter is in a 'safe' state to execute new code. I would just call Py_Finalize and re-initialize everything except I have a bunch of PyObject * references that I need to stay valid. Is there a function to do this or is it even necessary? When I mentioned the interpreter being interrupted above, I meant by a seg. fault or access violation which my app tries to recover from.
|
[
"Er, trying to \"recover\" from a segfault or access violation is quite dangerous. There is a reason you get these in the first place, and it's that your program has tried to do something which it shouldn't have tried to do; therefore it has hit a bug or an unforeseen condition.\nThere is no provision in the Python interpreter to roll back to a \"safe point\" in cases such as those mentioned. Even finalizing and reinitializing the interpreter might still leave some static data in a inconsistent state.\nIf you told us why you are trying to do this we might be able to suggest an alternative.\n"
] |
[
2
] |
[] |
[] |
[
"function",
"python",
"recover"
] |
stackoverflow_0001993238_function_python_recover.txt
|
Q:
How do I implement 'Parameter Object' refactor in Python?
Right now I use the parameter object's class to be inherited like so
class A():
def __init__(self,p1,p2):
self.p1, self.p2 = p1, p2
class B(A):
def __init__(self,b):
self.p1, self.p2 = b.p1, b.p2
This trims up the absurdity of using the code but not the class code itself. So, I'd like to do the C++ thing and pass the parameter object to the initialization list like so
class A {
int p1,p2;
}
class B : public A {
B(const A& a) : A(a) {}
}
Can I do this in Python? Specifically, can I set the attributes of a parent class by somehow calling it's __init__ within the child's? - from reading "Dive into Python" I'd guess I can do this since the object is already constructed by the time __init__ is called.
Or, perhaps is there some different method of implementing the parameter object refactor in Python (and I'm just trying to force a C++ technique)?
A:
Generally speaking, you likely don't need the parameter object refactor technique. Python has several collections in the standard library that already have the core benefits that a parameter object refactor would provide.
Additionally, the cost/benefit analysis for a refactor like the parameter object design pattern is notably different than C++. For instance, without static compilation, object creation and member lookups are much more expensive. The base case of the parameter object pattern is to provide a namespace for related fields, something that can be accomplished simply enough in Python with a dictionary.
The pattern has more value in Python if you need some kind of model manipulation in the form of methods that are related to the grouped data, but even then mechanisms as simple and inexpensive as "properties" can solve manipulation needs on member attributes.
With a slightly more detailed description of the problem space, we can probably help evaluate whether this sort of refactor is a benefit, but most likely you'd be better not using that design pattern when working in Python.
A:
The translation of the C++ code into python would be something like:
class A():
def __init__(self,p1,p2):
self.p1, self.p2 = p1, p2
class B(A):
def __init__(self,b):
A.__init__(self, b.p1, b.p2)
A:
class B(A):
def __init__(self, *args, **kwargs):
super(B, self).__init__(*args, **kwargs)
Read more about super() for details.
|
How do I implement 'Parameter Object' refactor in Python?
|
Right now I use the parameter object's class to be inherited like so
class A():
def __init__(self,p1,p2):
self.p1, self.p2 = p1, p2
class B(A):
def __init__(self,b):
self.p1, self.p2 = b.p1, b.p2
This trims up the absurdity of using the code but not the class code itself. So, I'd like to do the C++ thing and pass the parameter object to the initialization list like so
class A {
int p1,p2;
}
class B : public A {
B(const A& a) : A(a) {}
}
Can I do this in Python? Specifically, can I set the attributes of a parent class by somehow calling it's __init__ within the child's? - from reading "Dive into Python" I'd guess I can do this since the object is already constructed by the time __init__ is called.
Or, perhaps is there some different method of implementing the parameter object refactor in Python (and I'm just trying to force a C++ technique)?
|
[
"Generally speaking, you likely don't need the parameter object refactor technique. Python has several collections in the standard library that already have the core benefits that a parameter object refactor would provide.\nAdditionally, the cost/benefit analysis for a refactor like the parameter object design pattern is notably different than C++. For instance, without static compilation, object creation and member lookups are much more expensive. The base case of the parameter object pattern is to provide a namespace for related fields, something that can be accomplished simply enough in Python with a dictionary.\nThe pattern has more value in Python if you need some kind of model manipulation in the form of methods that are related to the grouped data, but even then mechanisms as simple and inexpensive as \"properties\" can solve manipulation needs on member attributes.\nWith a slightly more detailed description of the problem space, we can probably help evaluate whether this sort of refactor is a benefit, but most likely you'd be better not using that design pattern when working in Python.\n",
"The translation of the C++ code into python would be something like:\nclass A():\n def __init__(self,p1,p2):\n self.p1, self.p2 = p1, p2\n\nclass B(A):\n def __init__(self,b):\n A.__init__(self, b.p1, b.p2)\n\n",
"class B(A):\n def __init__(self, *args, **kwargs):\n super(B, self).__init__(*args, **kwargs)\n\nRead more about super() for details.\n"
] |
[
3,
2,
1
] |
[] |
[] |
[
"inheritance",
"parameter_object",
"python",
"refactoring"
] |
stackoverflow_0001995622_inheritance_parameter_object_python_refactoring.txt
|
Q:
applying image decoration (border) in Python (programmatically)
I am looking for a way to create a border in python.Is there any library in Python which we can import to create a border.
Note that I do not want to use any image masks to create this effect (e.g. I don't want to use any image editing package like GIMP to create a border image mask) .
Here is what I am looking for:
import fooImageBorders
import Image
foo = Image.open("someImage.jpg")
foo2 = fooImageBorders.bevel(foo, color = black)
...I can write my own methods to add borders .. but if there is already something like this out there with a comprehensive set of border options, I would like to make use of it.
I looked at PIL documentation and couldn't find a way to do this. I have windows xp and there doesn't seem to be a way to install PythonMagick either for Python 2.6 if you don't have cygwin.
A:
Look at the ImageOps module within the PIL.
import Image
import ImageOps
x = Image.open('test.png')
y = ImageOps.expand(x,border=5,fill='red')
y.save('test2.png')
A:
You can use the PythonMagick module. the documentation for this module is here (Magic ++ documentation)
Example: To add a red 2 pixel border to an image, you need following code.
from PythonMagick import Image
i = Image('example.jpg') # reades image and creates an image instance
i.borderColor("#ff0000") # sets border paint color to red
i.border("2x2") # paints a 2 pixel border
i.write("out.jpg")
# writes the image to a file
A:
foo2 = foo.copy()
draw = ImageDraw.Draw(foo2)
for i in range(width):
draw.rectangle([i, i, foo2.size[0]-i-1, foo2.size[1]-i-1], outline = color)
foo2 will have a width-pixel border of color.
If you want different colored borders on each side, you can replace .rectangle with repeated .line calls.
If you want the border not to cover any part of the existing image, use this instead of foo.copy().
foo2 = Image.new(foo.mode, (foo.size[0] + 2*width, foo.size[1] + 2*width))
foo2.paste(foo, (width, width))
|
applying image decoration (border) in Python (programmatically)
|
I am looking for a way to create a border in python.Is there any library in Python which we can import to create a border.
Note that I do not want to use any image masks to create this effect (e.g. I don't want to use any image editing package like GIMP to create a border image mask) .
Here is what I am looking for:
import fooImageBorders
import Image
foo = Image.open("someImage.jpg")
foo2 = fooImageBorders.bevel(foo, color = black)
...I can write my own methods to add borders .. but if there is already something like this out there with a comprehensive set of border options, I would like to make use of it.
I looked at PIL documentation and couldn't find a way to do this. I have windows xp and there doesn't seem to be a way to install PythonMagick either for Python 2.6 if you don't have cygwin.
|
[
"Look at the ImageOps module within the PIL.\nimport Image\nimport ImageOps\n\nx = Image.open('test.png')\ny = ImageOps.expand(x,border=5,fill='red')\ny.save('test2.png')\n\n",
"You can use the PythonMagick module. the documentation for this module is here (Magic ++ documentation)\nExample: To add a red 2 pixel border to an image, you need following code.\nfrom PythonMagick import Image\ni = Image('example.jpg') # reades image and creates an image instance\ni.borderColor(\"#ff0000\") # sets border paint color to red\ni.border(\"2x2\") # paints a 2 pixel border\ni.write(\"out.jpg\")\n# writes the image to a file \n\n",
"foo2 = foo.copy()\ndraw = ImageDraw.Draw(foo2)\nfor i in range(width):\n draw.rectangle([i, i, foo2.size[0]-i-1, foo2.size[1]-i-1], outline = color)\n\nfoo2 will have a width-pixel border of color.\nIf you want different colored borders on each side, you can replace .rectangle with repeated .line calls.\nIf you want the border not to cover any part of the existing image, use this instead of foo.copy().\nfoo2 = Image.new(foo.mode, (foo.size[0] + 2*width, foo.size[1] + 2*width))\nfoo2.paste(foo, (width, width))\n\n"
] |
[
11,
2,
1
] |
[] |
[] |
[
"image",
"image_processing",
"python"
] |
stackoverflow_0001995772_image_image_processing_python.txt
|
Q:
Python execution
Is it possible for a python script to execute at a low run level?
Edit:
To clarify, is it possible for a python script to run in the background, kind of like a daemon.
A:
I put this file nice.py in my site-packages directory (on Windows):
import win32api,win32process,win32con
pid = win32api.GetCurrentProcessId()
handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, True, pid)
win32process.SetPriorityClass(handle, win32process.BELOW_NORMAL_PRIORITY_CLASS)
Then I just import nice on any script I want to run at reduced priority.
A:
Yes. The scripts that control daemons are (normally) plain old bash scripts and can run whatever a bash script can run. The only difference is that in a low runlevel, lots of other system services will not be running, so if the program tries to do something that depends on another daemon, that may fail.
|
Python execution
|
Is it possible for a python script to execute at a low run level?
Edit:
To clarify, is it possible for a python script to run in the background, kind of like a daemon.
|
[
"I put this file nice.py in my site-packages directory (on Windows):\nimport win32api,win32process,win32con\npid = win32api.GetCurrentProcessId()\nhandle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, True, pid)\nwin32process.SetPriorityClass(handle, win32process.BELOW_NORMAL_PRIORITY_CLASS)\n\nThen I just import nice on any script I want to run at reduced priority.\n",
"Yes. The scripts that control daemons are (normally) plain old bash scripts and can run whatever a bash script can run. The only difference is that in a low runlevel, lots of other system services will not be running, so if the program tries to do something that depends on another daemon, that may fail.\n"
] |
[
5,
0
] |
[] |
[] |
[
"python",
"runlevel"
] |
stackoverflow_0001995102_python_runlevel.txt
|
Q:
is my google app engine deployed source code secure?
I'm thinking about good ways to store third party credentials, which basically means there needs to be a secret somewhere, either in code or data. I'm deploying on google app engine.
If the 'secret' was something like
pw_passphrase = sha2(username + 'global-password')
pw_plaintext = aes_decrypt(pw_passphrase, pw_ciphertext)
can I depend on this code never being seen by a non appengine administrator?
...what if the credentials protect something supersensitive like personal financial data, do we still trust it?
(The sha2 bit is exchangable with any other secret pseudo-random function.)
A:
Yes: your source code is secure (as secure as Google can make it), and there's no way for unauthorized third parties to peek.
A:
Also remember to handle exceptions in your code with an error page, or else an exception thrown might uncover your source code to an unsigned user.
|
is my google app engine deployed source code secure?
|
I'm thinking about good ways to store third party credentials, which basically means there needs to be a secret somewhere, either in code or data. I'm deploying on google app engine.
If the 'secret' was something like
pw_passphrase = sha2(username + 'global-password')
pw_plaintext = aes_decrypt(pw_passphrase, pw_ciphertext)
can I depend on this code never being seen by a non appengine administrator?
...what if the credentials protect something supersensitive like personal financial data, do we still trust it?
(The sha2 bit is exchangable with any other secret pseudo-random function.)
|
[
"Yes: your source code is secure (as secure as Google can make it), and there's no way for unauthorized third parties to peek.\n",
"Also remember to handle exceptions in your code with an error page, or else an exception thrown might uncover your source code to an unsigned user.\n"
] |
[
4,
2
] |
[] |
[] |
[
"credentials",
"google_app_engine",
"passwords",
"python",
"security"
] |
stackoverflow_0001994182_credentials_google_app_engine_passwords_python_security.txt
|
Q:
Upgrade Python to 2.6 on Mac
I'd like to upgrade the default python installation (2.5.1) supplied with OS X Leopard to the latest version. Please let me know how I can achieve this.
Thanks
A:
When an OS is distributed with some specific Python release and uses it for some OS functionality (as is the case with Mac OS X, as well as many Linux distros &c), you should not tamper in any way with the system-supplied Python (as in, "upgrading" it and the like): while Python strives for backwards compatibility within any major release (such as 2.* or 3.*, this can never be 100% guaranted; your OS supplied tested all functionality thoroughly with the specific Python version they distribute; if you manage to alter that version, "on your head be it" -- neither your OS supplier nor the PSF accepts any responsibility for whatever damage that might perhaps do to your system.
Rather, as other answers already suggested, install any other release you wish "besides" the system one -- why tamper with that crucial one, and risk breaking things, when installing others is so easy anyway?! On typical Mac OS X 10.5 machines (haven't upgraded any of my several macs to 10.6 yet), I have the Apple-supplied 2.5, a 2.4 on the side to support some old projects not worth the bother to upgrate, the latest 2.6 for new stuff, 3.1 as well to get the very newest -- they all live together in peace and quiet, I just type the release number explicitly, i.e. using python2.6 at the prompt, when I want a specific release. What release gets used when at the shell prompt you just say python is up to you (I personally prefer that to mean "the system-supplied Python", but it's a matter of taste: by setting paths, or shell aliases, &c, you can make it mean whatever you wish).
A:
Don't upgrade.
Install ActivePython (which co-exists with others).
Open Terminal
Type python2.6
A:
May I suggest you leave the "Default" be, and install Python in /usr/local/bin.
Download python
Unzip it
./configure
make
sudo make install
done.
Since /usr/local/bin comes before /usr/bin in the $PATH, you will invoke 2.6 when you type python, but the OS will remain stable...
A:
You have a number of options
Install with MacPorts or Fink, e.g.:
sudo port install python2.6
Install from the disc image from python.org
Install from source:
tar xzvf Python-2.6.3.tgz
cd Python-2.6.3
./configure && make && sudo make install
A:
The best is to use macports (just like Adam Rosenfield stated on this thread).
You can easily switch between Python versions using macports select mechanism:
$ sudo port select --set python pythonXY
To view the list of available Python versions you can use above and/or confirm which one you're using:
$ sudo port select --list python
To install a new Python version:
$ sudo port install pythonXY
A:
The standard http://python.org install for Mac OSX will happily coexist with the "system python". If you let the installer change your paths, when you run python from a prompt in terminal, it will find the version at
/Library/Frameworks/Python.framework/Versions/2.6/bin/python
However, this won't interfere with anything that OSX itself does with python, which correctly hardwires the path to the version that it installs.
A:
I believe there are a few options. The one I like is to install alternative UNIX software on my Macs using MacPorts, http://www.macports.org/ -- this way the new software is installed in a different directory and won't mess up anything depending on the apple-installed version, and macports also has a nice way of keeping their installed software up to date. I believe MacPorts helps take care of dependencies as well.
|
Upgrade Python to 2.6 on Mac
|
I'd like to upgrade the default python installation (2.5.1) supplied with OS X Leopard to the latest version. Please let me know how I can achieve this.
Thanks
|
[
"When an OS is distributed with some specific Python release and uses it for some OS functionality (as is the case with Mac OS X, as well as many Linux distros &c), you should not tamper in any way with the system-supplied Python (as in, \"upgrading\" it and the like): while Python strives for backwards compatibility within any major release (such as 2.* or 3.*, this can never be 100% guaranted; your OS supplied tested all functionality thoroughly with the specific Python version they distribute; if you manage to alter that version, \"on your head be it\" -- neither your OS supplier nor the PSF accepts any responsibility for whatever damage that might perhaps do to your system.\nRather, as other answers already suggested, install any other release you wish \"besides\" the system one -- why tamper with that crucial one, and risk breaking things, when installing others is so easy anyway?! On typical Mac OS X 10.5 machines (haven't upgraded any of my several macs to 10.6 yet), I have the Apple-supplied 2.5, a 2.4 on the side to support some old projects not worth the bother to upgrate, the latest 2.6 for new stuff, 3.1 as well to get the very newest -- they all live together in peace and quiet, I just type the release number explicitly, i.e. using python2.6 at the prompt, when I want a specific release. What release gets used when at the shell prompt you just say python is up to you (I personally prefer that to mean \"the system-supplied Python\", but it's a matter of taste: by setting paths, or shell aliases, &c, you can make it mean whatever you wish).\n",
"Don't upgrade.\n\nInstall ActivePython (which co-exists with others). \nOpen Terminal\nType python2.6\n\n",
"May I suggest you leave the \"Default\" be, and install Python in /usr/local/bin.\n\nDownload python\nUnzip it\n./configure\nmake\nsudo make install\n\ndone.\nSince /usr/local/bin comes before /usr/bin in the $PATH, you will invoke 2.6 when you type python, but the OS will remain stable...\n",
"You have a number of options\n\nInstall with MacPorts or Fink, e.g.:\nsudo port install python2.6\n\nInstall from the disc image from python.org\nInstall from source:\ntar xzvf Python-2.6.3.tgz\ncd Python-2.6.3\n./configure && make && sudo make install\n\n\n",
"The best is to use macports (just like Adam Rosenfield stated on this thread).\nYou can easily switch between Python versions using macports select mechanism:\n$ sudo port select --set python pythonXY\nTo view the list of available Python versions you can use above and/or confirm which one you're using:\n$ sudo port select --list python\nTo install a new Python version:\n$ sudo port install pythonXY\n",
"The standard http://python.org install for Mac OSX will happily coexist with the \"system python\". If you let the installer change your paths, when you run python from a prompt in terminal, it will find the version at \n /Library/Frameworks/Python.framework/Versions/2.6/bin/python\n\nHowever, this won't interfere with anything that OSX itself does with python, which correctly hardwires the path to the version that it installs.\n",
"I believe there are a few options. The one I like is to install alternative UNIX software on my Macs using MacPorts, http://www.macports.org/ -- this way the new software is installed in a different directory and won't mess up anything depending on the apple-installed version, and macports also has a nice way of keeping their installed software up to date. I believe MacPorts helps take care of dependencies as well. \n"
] |
[
20,
8,
6,
5,
4,
1,
0
] |
[] |
[] |
[
"installation",
"macos",
"python",
"upgrade"
] |
stackoverflow_0001541776_installation_macos_python_upgrade.txt
|
Q:
django unprintable templatesyntaxerror object caused by urlconf?
I'm trying to get a django project set up, and I seem to be having trouble with my urlconf. I'm not sure what the deal is, and the error below isn't entirely helpful to me. I don't think it really has anything to do with template rendering, actually, because I stepped through the execution path until just before the render_to_response function completes (which is where the urlconf seems to be causing an error) and the template objects are parsed correctly.
Traceback (most recent call last):
File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 2978, in _HandleRequest
base_env_dict=env_dict)
File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 411, in Dispatch
base_env_dict=base_env_dict)
File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 2244, in Dispatch
self._module_dict)
File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 2162, in ExecuteCGI
reset_modules = exec_script(handler_path, cgi_path, hook)
File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 2058, in ExecuteOrImportScript
exec module_code in script_module.__dict__
File "C:\Users\Ben\Development\workspace\ringbot\src\main.py", line 52, in <module>
main()
File "C:\Users\Ben\Development\workspace\ringbot\src\main.py", line 49, in main
util.run_wsgi_app(application)
File "C:\Program Files\Google\google_appengine\google\appengine\ext\webapp\util.py", line 97, in run_wsgi_app
run_bare_wsgi_app(add_wsgi_middleware(application))
File "C:\Program Files\Google\google_appengine\google\appengine\ext\webapp\util.py", line 115, in run_bare_wsgi_app
result = application(env, _start_response)
File "C:\Python25\lib\site-packages\django\core\handlers\wsgi.py", line 241, in __call__
response = self.get_response(request)
File "C:\Python25\lib\site-packages\django\core\handlers\base.py", line 134, in get_response
return self.handle_uncaught_exception(request, resolver, exc_info)
File "C:\Python25\lib\site-packages\django\core\handlers\base.py", line 154, in handle_uncaught_exception
return debug.technical_500_response(request, *exc_info)
File "C:\Python25\lib\site-packages\django\views\debug.py", line 40, in technical_500_response
html = reporter.get_traceback_html()
File "C:\Python25\lib\site-packages\django\views\debug.py", line 114, in get_traceback_html
return t.render(c)
File "C:\Python25\lib\site-packages\django\template\__init__.py", line 178, in render
return self.nodelist.render(context)
File "C:\Python25\lib\site-packages\django\template\__init__.py", line 779, in render
bits.append(self.render_node(node, context))
File "C:\Python25\lib\site-packages\django\template\debug.py", line 81, in render_node
raise wrapped
TemplateSyntaxError: <unprintable TemplateSyntaxError object>
Here is my top-level urlconf:
from django.conf.urls.defaults import *
urlpatterns = patterns('',
(r'', include('pub.urls')),
)
And pub.urls:
from django.conf.urls.defaults import *
import pub
urlpatterns = patterns('pub.views',
(r'^$', 'index')
)
and pub.views.index:
# Create your views here.
from django.shortcuts import render_to_response
from django.http import HttpResponse
import openidgae
# this needs to be moved somewhere else, but for now it can live here
def index(request):
lip = openidgae.get_current_person(request, HttpResponse())
resp = render_to_response('pub/index.html', {'lip': lip}) # exception thrown here
return resp
A:
Make sure each of your .py files is syntactically correct. Run python manage.py shell and then import each of your modules and make sure it loads with no errors. Since syntax errors are runtime errors in python, mistakes sometimes show up at odd times and in odd places.
A:
Here's another suggestion which could come in handy in the future.
The stack trace printed in the web interface isn't always optimal for a number of possible reasons. However, you can also get a stack trace out to the console which might give you information that was omitted on the web page.
The easiest way to do that is to run django using the built-in webserver (i.e. python manage.py runserver 0.0.0.0:8000), and visit THAT page with your browser. You should see a stack trace appear inline with the web server logging output on the console, which may include otherwise "unprintable" error content.
A:
looks like the problem is because of a NoReverseMatch exception being thrown because my templates contain a {% url ... %} block that doesn't resolve. From the django site: Note that if the URL you're reversing doesn't exist, you'll get an NoReverseMatch exception raised, which will cause your site to display an error page.
|
django unprintable templatesyntaxerror object caused by urlconf?
|
I'm trying to get a django project set up, and I seem to be having trouble with my urlconf. I'm not sure what the deal is, and the error below isn't entirely helpful to me. I don't think it really has anything to do with template rendering, actually, because I stepped through the execution path until just before the render_to_response function completes (which is where the urlconf seems to be causing an error) and the template objects are parsed correctly.
Traceback (most recent call last):
File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 2978, in _HandleRequest
base_env_dict=env_dict)
File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 411, in Dispatch
base_env_dict=base_env_dict)
File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 2244, in Dispatch
self._module_dict)
File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 2162, in ExecuteCGI
reset_modules = exec_script(handler_path, cgi_path, hook)
File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 2058, in ExecuteOrImportScript
exec module_code in script_module.__dict__
File "C:\Users\Ben\Development\workspace\ringbot\src\main.py", line 52, in <module>
main()
File "C:\Users\Ben\Development\workspace\ringbot\src\main.py", line 49, in main
util.run_wsgi_app(application)
File "C:\Program Files\Google\google_appengine\google\appengine\ext\webapp\util.py", line 97, in run_wsgi_app
run_bare_wsgi_app(add_wsgi_middleware(application))
File "C:\Program Files\Google\google_appengine\google\appengine\ext\webapp\util.py", line 115, in run_bare_wsgi_app
result = application(env, _start_response)
File "C:\Python25\lib\site-packages\django\core\handlers\wsgi.py", line 241, in __call__
response = self.get_response(request)
File "C:\Python25\lib\site-packages\django\core\handlers\base.py", line 134, in get_response
return self.handle_uncaught_exception(request, resolver, exc_info)
File "C:\Python25\lib\site-packages\django\core\handlers\base.py", line 154, in handle_uncaught_exception
return debug.technical_500_response(request, *exc_info)
File "C:\Python25\lib\site-packages\django\views\debug.py", line 40, in technical_500_response
html = reporter.get_traceback_html()
File "C:\Python25\lib\site-packages\django\views\debug.py", line 114, in get_traceback_html
return t.render(c)
File "C:\Python25\lib\site-packages\django\template\__init__.py", line 178, in render
return self.nodelist.render(context)
File "C:\Python25\lib\site-packages\django\template\__init__.py", line 779, in render
bits.append(self.render_node(node, context))
File "C:\Python25\lib\site-packages\django\template\debug.py", line 81, in render_node
raise wrapped
TemplateSyntaxError: <unprintable TemplateSyntaxError object>
Here is my top-level urlconf:
from django.conf.urls.defaults import *
urlpatterns = patterns('',
(r'', include('pub.urls')),
)
And pub.urls:
from django.conf.urls.defaults import *
import pub
urlpatterns = patterns('pub.views',
(r'^$', 'index')
)
and pub.views.index:
# Create your views here.
from django.shortcuts import render_to_response
from django.http import HttpResponse
import openidgae
# this needs to be moved somewhere else, but for now it can live here
def index(request):
lip = openidgae.get_current_person(request, HttpResponse())
resp = render_to_response('pub/index.html', {'lip': lip}) # exception thrown here
return resp
|
[
"Make sure each of your .py files is syntactically correct. Run python manage.py shell and then import each of your modules and make sure it loads with no errors. Since syntax errors are runtime errors in python, mistakes sometimes show up at odd times and in odd places.\n",
"Here's another suggestion which could come in handy in the future.\nThe stack trace printed in the web interface isn't always optimal for a number of possible reasons. However, you can also get a stack trace out to the console which might give you information that was omitted on the web page.\nThe easiest way to do that is to run django using the built-in webserver (i.e. python manage.py runserver 0.0.0.0:8000), and visit THAT page with your browser. You should see a stack trace appear inline with the web server logging output on the console, which may include otherwise \"unprintable\" error content.\n",
"looks like the problem is because of a NoReverseMatch exception being thrown because my templates contain a {% url ... %} block that doesn't resolve. From the django site: Note that if the URL you're reversing doesn't exist, you'll get an NoReverseMatch exception raised, which will cause your site to display an error page.\n"
] |
[
1,
0,
0
] |
[] |
[] |
[
"django",
"google_app_engine",
"python"
] |
stackoverflow_0001788245_django_google_app_engine_python.txt
|
Q:
How can I get the depth of a jpg file?
I want to retrieve the bit depth for a jpeg file using Python.
Using the Python Imaging Library:
import Image
data = Image.open('file.jpg')
print data.depth
However, this gives me a depth of 8 for an obviously 24-bit image. Am I doing something wrong? Is there some way to do it with pure Python code?
Thanks in advance.
Edit: It's data.bits not data.depth.
A:
I don't see the depth attribute documented anywhere in the Python Imaging Library handbook. However, it looks like only a limited number of modes are supported. You could use something like this:
mode_to_bpp = {'1':1, 'L':8, 'P':8, 'RGB':24, 'RGBA':32, 'CMYK':32, 'YCbCr':24, 'I':32, 'F':32}
data = Image.open('file.jpg')
bpp = mode_to_bpp[data.mode]
A:
Jpeg files don't have bit depth in the same manner as GIF or PNG files. The transform used to create the Jpeg data renders a continuous color spectrum on decompression.
A:
PIL is reporting bit depth per "band". I don't actually see depth as a documented property in the PIL docs, however, I think you want this:
data.depth * len(data.getbands())
Or better yet:
data.mode
See here for more info.
A:
I was going to say that JPG images are 24 bit by definition. They normally consist of three 8 bit colour channels, one for each of red, green and blue making 24 bits per pixel. However, I've just found this page which states:
If you use a more modern version of Photoshop, you'll notice it will also let you work in 16-bits per channel, which gives you 48 bits per pixel.
But I can't find a reference for how you'd tell the two apart.
|
How can I get the depth of a jpg file?
|
I want to retrieve the bit depth for a jpeg file using Python.
Using the Python Imaging Library:
import Image
data = Image.open('file.jpg')
print data.depth
However, this gives me a depth of 8 for an obviously 24-bit image. Am I doing something wrong? Is there some way to do it with pure Python code?
Thanks in advance.
Edit: It's data.bits not data.depth.
|
[
"I don't see the depth attribute documented anywhere in the Python Imaging Library handbook. However, it looks like only a limited number of modes are supported. You could use something like this:\nmode_to_bpp = {'1':1, 'L':8, 'P':8, 'RGB':24, 'RGBA':32, 'CMYK':32, 'YCbCr':24, 'I':32, 'F':32}\n\ndata = Image.open('file.jpg')\nbpp = mode_to_bpp[data.mode]\n\n",
"Jpeg files don't have bit depth in the same manner as GIF or PNG files. The transform used to create the Jpeg data renders a continuous color spectrum on decompression.\n",
"PIL is reporting bit depth per \"band\". I don't actually see depth as a documented property in the PIL docs, however, I think you want this:\ndata.depth * len(data.getbands())\n\nOr better yet:\ndata.mode\n\nSee here for more info.\n",
"I was going to say that JPG images are 24 bit by definition. They normally consist of three 8 bit colour channels, one for each of red, green and blue making 24 bits per pixel. However, I've just found this page which states:\n\nIf you use a more modern version of Photoshop, you'll notice it will also let you work in 16-bits per channel, which gives you 48 bits per pixel.\n\nBut I can't find a reference for how you'd tell the two apart.\n"
] |
[
14,
8,
4,
2
] |
[] |
[] |
[
"imaging",
"jpeg",
"python"
] |
stackoverflow_0001996577_imaging_jpeg_python.txt
|
Q:
All Possible combination for an HEX Value from a given set of chars
I am new to python and programming,
I am looking for a code, or a sample code that can have a predefined set of hex values
and that can find the 3 used values within to generate a certain value.
lets say I have a value of : 0x50158A51
this is a 4 byte (32 bit) hex value
now i need to find the values which when added or subtracted (from the provided set) will end with this result.
for example:
0x75612171 + 0x75612171 + 0x6553476F = 0x50158A51
notice that the values added are all from the allowed set
Just to be clear i have a limited chars set
which is :
\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13
\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f\x20\x21\x22\x23\x24\x25\x26
\x27\x28\x29\x2a\x2b\x2c\x2d\x2e\x2f\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39
\x3a\x3b\x3c\x3d\x3e\x3f\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4a\x4b\x4c
\x4d\x4e\x4f\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5a\x5b\x5c\x5d\x5e\x5f
\x60\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6a\x6b\x6c\x6d\x6e\x6f\x70\x71\x72
\x73\x74\x75\x76\x77\x78\x79\x7a\x7b\x7c\x7d\x7e\x7f\x80\x81\x82\x83\x84\x85
\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95\x96\x97\x98
\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab
\xac\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe
\xbf\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1
\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4
\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7
\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff
i used a simple code to calculate 3 values:
#!/usr/bin/python
hex1 = 0x55555521
hex2 = 0x55555421
hex3 = 0x6D556F49
calc = hex1 + hex2 + hex3
print hex(calc)
which will give a result of:
root@linux:~# ./calc2.py
0x150158a51
i need to some how reverse the process of the answer by placing variations from my allowed set into the variables
for example:
placing 4 byte hex values from the set into the variables
try:
hex1 = placing 4bytes from allowed set
hex2 = placing 4bytes from allowed set
hex3 = placing 4bytes from allowed set
if result (hex1+hex2+hex3) = 0x150158a51
then
print "values used for this results are: hex1 hex2 hex3"
Thank you in advance.
A:
What you're asking for isn't possible. There will be infinite sequences of numbers that when added together will continue to produce the same result, modulo 2^32.
As a trivial example, say that your target number is 0x10000000 and the only hex values you allow are zero and one. Then the following sequences of numbers will result in 0x10000000:
0x1 + 0x1 + ... + 0x1 (0x10000000 times) = 0x10000000
0x1 + 0x1 + ... + 0x1 (0x110000000 times) = 0x10000000
0x1 + 0x1 + ... + 0x1 (0x210000000 times) = 0x10000000
and so on. Since you can continue adding 0x1's indefinitely, the algorithm can never terminate.
A:
The following program for 0x50158A51 generates:
0x50157f51 + 0x00000b00 + 0x00000000 = 0x50158A51
for 0x1090F0FF it generates:
0x107f7f7f + 0x000011717f + 0x00000001 = 0x1090f0ff
where all "characters" in summands are from allowed set and not from disallowed set.
The program:
a=0x1090F0FF
a0=0
a1=0
a2=0
for n in range(3,-1,-1):
a0<<=8;
a1<<=8;
a2<<=8;
mask = 0xff<<(n*8)
b=(a&mask)>>(n*8)
if b > 2*0x7f:
a0 += 0x7f
a1 += 0x7f
a2 += b - 2*0x7f
elif b > 0x7f:
a0 += 0x7f
a1 += b - 0x7f
else:
a0 += b
print '%08x + %08x + %08x = %08x' % (a0, a1, a2, a0+a1+a2)
A:
From what I understood, but I may be wrong, you are talking about variation of a Subset Sum Problem, which is NP-Complete. So you may look for some more info about that.
|
All Possible combination for an HEX Value from a given set of chars
|
I am new to python and programming,
I am looking for a code, or a sample code that can have a predefined set of hex values
and that can find the 3 used values within to generate a certain value.
lets say I have a value of : 0x50158A51
this is a 4 byte (32 bit) hex value
now i need to find the values which when added or subtracted (from the provided set) will end with this result.
for example:
0x75612171 + 0x75612171 + 0x6553476F = 0x50158A51
notice that the values added are all from the allowed set
Just to be clear i have a limited chars set
which is :
\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13
\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f\x20\x21\x22\x23\x24\x25\x26
\x27\x28\x29\x2a\x2b\x2c\x2d\x2e\x2f\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39
\x3a\x3b\x3c\x3d\x3e\x3f\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4a\x4b\x4c
\x4d\x4e\x4f\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5a\x5b\x5c\x5d\x5e\x5f
\x60\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6a\x6b\x6c\x6d\x6e\x6f\x70\x71\x72
\x73\x74\x75\x76\x77\x78\x79\x7a\x7b\x7c\x7d\x7e\x7f\x80\x81\x82\x83\x84\x85
\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95\x96\x97\x98
\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab
\xac\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe
\xbf\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1
\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4
\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7
\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff
i used a simple code to calculate 3 values:
#!/usr/bin/python
hex1 = 0x55555521
hex2 = 0x55555421
hex3 = 0x6D556F49
calc = hex1 + hex2 + hex3
print hex(calc)
which will give a result of:
root@linux:~# ./calc2.py
0x150158a51
i need to some how reverse the process of the answer by placing variations from my allowed set into the variables
for example:
placing 4 byte hex values from the set into the variables
try:
hex1 = placing 4bytes from allowed set
hex2 = placing 4bytes from allowed set
hex3 = placing 4bytes from allowed set
if result (hex1+hex2+hex3) = 0x150158a51
then
print "values used for this results are: hex1 hex2 hex3"
Thank you in advance.
|
[
"What you're asking for isn't possible. There will be infinite sequences of numbers that when added together will continue to produce the same result, modulo 2^32.\nAs a trivial example, say that your target number is 0x10000000 and the only hex values you allow are zero and one. Then the following sequences of numbers will result in 0x10000000:\n0x1 + 0x1 + ... + 0x1 (0x10000000 times) = 0x10000000 \n0x1 + 0x1 + ... + 0x1 (0x110000000 times) = 0x10000000\n0x1 + 0x1 + ... + 0x1 (0x210000000 times) = 0x10000000\n\nand so on. Since you can continue adding 0x1's indefinitely, the algorithm can never terminate.\n",
"The following program for 0x50158A51 generates: \n0x50157f51 + 0x00000b00 + 0x00000000 = 0x50158A51\n\nfor 0x1090F0FF it generates:\n0x107f7f7f + 0x000011717f + 0x00000001 = 0x1090f0ff\n\nwhere all \"characters\" in summands are from allowed set and not from disallowed set.\nThe program:\na=0x1090F0FF\n\na0=0\na1=0\na2=0\nfor n in range(3,-1,-1):\n a0<<=8;\n a1<<=8;\n a2<<=8;\n mask = 0xff<<(n*8)\n b=(a&mask)>>(n*8)\n if b > 2*0x7f:\n a0 += 0x7f\n a1 += 0x7f\n a2 += b - 2*0x7f\n elif b > 0x7f:\n a0 += 0x7f\n a1 += b - 0x7f\n else:\n a0 += b\n\nprint '%08x + %08x + %08x = %08x' % (a0, a1, a2, a0+a1+a2)\n\n",
"From what I understood, but I may be wrong, you are talking about variation of a Subset Sum Problem, which is NP-Complete. So you may look for some more info about that.\n"
] |
[
1,
1,
0
] |
[] |
[] |
[
"dataset",
"hex",
"python",
"subtraction"
] |
stackoverflow_0001996184_dataset_hex_python_subtraction.txt
|
Q:
Reference function or create a new function that only calls another?
def a(something):
return something*something
#Case I - referencing
b = a
#Case II - creating a new function to call the first
def b(something):
return a(something)
Which is better style? Are there drawbacks to either?
A:
Depends on what you need.
def a(something):
return something*something
b = a
def a(something):
return something+something
>>> b(3)
9
>>> a(3)
7
Whereas if you did:
b = lambda x:a(x)
b and a will always returns the same
If you want to optimize an extra function call out the first way is better, if you want b and a to always return the same thing the second way is better.
A:
b = a means calls to b will be faster (no overhead), but introspection (e.g. help(b)) will show the name a, and a's docstring. Unless the latter issues are a killer for your specific application (some kind of tutorial, for example), the speed advantage normally wins the case.
Consider, e.g. in ref.py:
def a(something):
return something*something
#Case I - referencing
b1 = a
#Case II - creating a new function to call the first
def b2(something):
return a(something)
Now:
$ python -mtimeit -s'import ref' 'ref.a(23)'
1000000 loops, best of 3: 0.716 usec per loop
$ python -mtimeit -s'import ref' 'ref.b1(23)'
1000000 loops, best of 3: 0.702 usec per loop
$ python -mtimeit -s'import ref' 'ref.b2(23)'
1000000 loops, best of 3: 0.958 usec per loop
I.e., calls to b1 (pure referencing) are just as fast as calls to a (actually appear 2% faster in this run, but that's well within "the noise" of measurement;-), calls to b2 (entirely new function which internally calls a) incur a 20% overhead -- not a killer, but normally something to avoid unless that performance sacrifice buys you something specific that's quite important for your use case.
A:
First doesn't generate a new function, should be better.
A:
Function call creates overhead. Case I is faster. Case II creates new function unrelated function.
Why would you need Case II?
|
Reference function or create a new function that only calls another?
|
def a(something):
return something*something
#Case I - referencing
b = a
#Case II - creating a new function to call the first
def b(something):
return a(something)
Which is better style? Are there drawbacks to either?
|
[
"Depends on what you need.\ndef a(something):\n return something*something\n\nb = a\n\ndef a(something):\n return something+something\n\n>>> b(3)\n9\n>>> a(3)\n7\n\nWhereas if you did:\nb = lambda x:a(x)\n\nb and a will always returns the same\nIf you want to optimize an extra function call out the first way is better, if you want b and a to always return the same thing the second way is better.\n",
"b = a means calls to b will be faster (no overhead), but introspection (e.g. help(b)) will show the name a, and a's docstring. Unless the latter issues are a killer for your specific application (some kind of tutorial, for example), the speed advantage normally wins the case.\nConsider, e.g. in ref.py:\ndef a(something):\n return something*something\n\n#Case I - referencing\nb1 = a\n#Case II - creating a new function to call the first\ndef b2(something):\n return a(something)\n\nNow:\n$ python -mtimeit -s'import ref' 'ref.a(23)'\n1000000 loops, best of 3: 0.716 usec per loop\n$ python -mtimeit -s'import ref' 'ref.b1(23)'\n1000000 loops, best of 3: 0.702 usec per loop\n$ python -mtimeit -s'import ref' 'ref.b2(23)'\n1000000 loops, best of 3: 0.958 usec per loop\n\nI.e., calls to b1 (pure referencing) are just as fast as calls to a (actually appear 2% faster in this run, but that's well within \"the noise\" of measurement;-), calls to b2 (entirely new function which internally calls a) incur a 20% overhead -- not a killer, but normally something to avoid unless that performance sacrifice buys you something specific that's quite important for your use case.\n",
"First doesn't generate a new function, should be better.\n",
"Function call creates overhead. Case I is faster. Case II creates new function unrelated function.\nWhy would you need Case II?\n"
] |
[
5,
2,
0,
0
] |
[] |
[] |
[
"coding_style",
"function",
"python"
] |
stackoverflow_0001996680_coding_style_function_python.txt
|
Q:
How to get a Blob size? (Python Google App Engine)
http://code.google.com/appengine/docs/python/datastore/typesandpropertyclasses.html#Blob
A:
{{ theblob|length }} if you're using a Django template (as you seem to indicate in a comment, although you give absolutely no indication of this in your question -- I suggest editing the question to add that crucial bit of info!-).
|
How to get a Blob size? (Python Google App Engine)
|
http://code.google.com/appengine/docs/python/datastore/typesandpropertyclasses.html#Blob
|
[
"{{ theblob|length }} if you're using a Django template (as you seem to indicate in a comment, although you give absolutely no indication of this in your question -- I suggest editing the question to add that crucial bit of info!-).\n"
] |
[
3
] |
[
"Try blob.getSize()\n"
] |
[
-1
] |
[
"blob",
"google_app_engine",
"python"
] |
stackoverflow_0001996591_blob_google_app_engine_python.txt
|
Q:
Wildcard matching a string in Python regex search
I thought I would write some quick code to download the number of "fans" a Facebook page has.
For some reason, despite a fair number of iterations I've tried, I can't get the following code to pick out the number of fans in the HTML. None of the other solutions I found on the web correctly match the regex in this case either. Surely it is possible to have some wildcard between the two matching bits?
The text I'd like to match against is "6 of X fans", where X is an arbitrary number of fans a page has - I would like to get this number.
I was thinking of polling this data intermittently and writing to a file but I haven't gotten around to that yet. I'm also wondering if this is headed in the right direction, as the code seems pretty clunky. :)
import urllib
import re
fbhandle = urllib.urlopen('http://www.facebook.com/Microsoft')
pattern = "6 of(.*)fans" #this wild card doesnt appear to work?
compiled = re.compile(pattern)
for lines in fbhandle.readlines():
ms = compiled.match(lines)
print ms #debugging
if ms: break
#ms.group()
print ms
fbhandle.close()
A:
Evan Fosmark already gave a good answer. This is just more info.
You have this line:
pattern = "6 of(.*)fans"
In general, this isn't a good regular expression. If the input text was:
"6 of 99 fans in the whole galaxy of fans"
Then the match group (the stuff inside the parentheses) would be:
" 99 fans in the whole galaxy of "
So, we want a pattern that will just grab what you want, even with a silly input text like the above.
In this case, it doesn't really matter if you match the white space, because when you convert a string to an integer, white space is ignored. But let's write the pattern to ignore white space.
With the * wildcard, it is possible to match a string of length zero. In this case I think you always want a non-empty match, so you want to use + to match one or more characters.
Python has non-greedy matching available, so you could rewrite with that. Older programs with regular expressions may not have non-greedy matching, so I'll also give a pattern that doesn't require non-greedy.
So, the non-greedy pattern:
pattern = "6 of\s+(.+?)\s+fans"
The other one:
pattern = "6 of\s+(\S+)\s+fans"
\s means "any white space" and will match a space, a tab, and a few other characters (such as "form feed"). \S means "any non-white-space" and matches anything that \s would not match.
The first pattern does better than your first pattern with the silly input text:
"6 of 99 fans in the whole galaxy of fans"
It would return a match group of just 99.
But try this other silly input text:
"6 of 99 crazed fans"
It would return a match group of 99 crazed.
The second pattern would not match at all, because the word "crazed" isn't the word "fans".
Hmm. Here's one last pattern that should always do the right thing even with silly input texts:
pattern = "6 of\D*?(\d+)\D*?fans"
\d matches any digit ('0' to '9'). \D matches any non-digit.
This will successfully match anything that is remotely non-ambiguous:
"6 of 99 fans in the whole galaxy of fans"
The match group will be 99.
"6 of 99 crazed fans"
The match group will be 99.
"6 of 99 41 fans"
It will not match, because there was a second number in there.
To learn more about Python regular expressions, you can read various web pages. For a quick reminder, inside the Python interpreter, do:
>>> import re
>>> help(re)
When you are "scraping" text from a web page, you might sometimes run afoul of HTML codes. In general, regular expressions are not a good tool for disregarding HTML or XML markup (see here); you would probably do better to use Beautiful Soup to parse the HTML and extract the text, followed by a regular expression to grab the text you really wanted.
I hope this was interesting and/or educational.
A:
import urllib
import re
fbhandle = urllib.urlopen('http://www.facebook.com/Microsoft')
pattern = "6 of(.*)fans" #this wild card doesnt appear to work?
compiled = re.compile(pattern)
ms = compiled.search(fbhandle.read())
print ms.group(1).strip()
fbhandle.close()
You needed to use re.search() instead. Using re.match() tries to match the pattern against the whole document, but really you're just trying to match a piece inside the document. The code above prints: 79,110. Of course, this will probably be a different number by the time it gets run by someone else.
A:
don't need regex
import urllib
fbhandle = urllib.urlopen('http://www.facebook.com/Microsoft')
for line in fbhandle.readlines():
line=line.rstrip().split("</span>")
for item in line:
if ">Fans<" in item:
rind=item.rindex("<span>")
print "-->",item[rind:].split()[2]
output
$ ./python.py
--> 79,133
|
Wildcard matching a string in Python regex search
|
I thought I would write some quick code to download the number of "fans" a Facebook page has.
For some reason, despite a fair number of iterations I've tried, I can't get the following code to pick out the number of fans in the HTML. None of the other solutions I found on the web correctly match the regex in this case either. Surely it is possible to have some wildcard between the two matching bits?
The text I'd like to match against is "6 of X fans", where X is an arbitrary number of fans a page has - I would like to get this number.
I was thinking of polling this data intermittently and writing to a file but I haven't gotten around to that yet. I'm also wondering if this is headed in the right direction, as the code seems pretty clunky. :)
import urllib
import re
fbhandle = urllib.urlopen('http://www.facebook.com/Microsoft')
pattern = "6 of(.*)fans" #this wild card doesnt appear to work?
compiled = re.compile(pattern)
for lines in fbhandle.readlines():
ms = compiled.match(lines)
print ms #debugging
if ms: break
#ms.group()
print ms
fbhandle.close()
|
[
"Evan Fosmark already gave a good answer. This is just more info.\nYou have this line:\npattern = \"6 of(.*)fans\"\n\nIn general, this isn't a good regular expression. If the input text was:\n\"6 of 99 fans in the whole galaxy of fans\"\nThen the match group (the stuff inside the parentheses) would be:\n\" 99 fans in the whole galaxy of \"\nSo, we want a pattern that will just grab what you want, even with a silly input text like the above.\nIn this case, it doesn't really matter if you match the white space, because when you convert a string to an integer, white space is ignored. But let's write the pattern to ignore white space.\nWith the * wildcard, it is possible to match a string of length zero. In this case I think you always want a non-empty match, so you want to use + to match one or more characters.\nPython has non-greedy matching available, so you could rewrite with that. Older programs with regular expressions may not have non-greedy matching, so I'll also give a pattern that doesn't require non-greedy.\nSo, the non-greedy pattern:\npattern = \"6 of\\s+(.+?)\\s+fans\"\n\nThe other one:\npattern = \"6 of\\s+(\\S+)\\s+fans\"\n\n\\s means \"any white space\" and will match a space, a tab, and a few other characters (such as \"form feed\"). \\S means \"any non-white-space\" and matches anything that \\s would not match.\nThe first pattern does better than your first pattern with the silly input text:\n\"6 of 99 fans in the whole galaxy of fans\"\nIt would return a match group of just 99.\nBut try this other silly input text:\n\"6 of 99 crazed fans\"\nIt would return a match group of 99 crazed.\nThe second pattern would not match at all, because the word \"crazed\" isn't the word \"fans\".\nHmm. Here's one last pattern that should always do the right thing even with silly input texts:\npattern = \"6 of\\D*?(\\d+)\\D*?fans\"\n\n\\d matches any digit ('0' to '9'). \\D matches any non-digit.\nThis will successfully match anything that is remotely non-ambiguous:\n\"6 of 99 fans in the whole galaxy of fans\"\nThe match group will be 99.\n\"6 of 99 crazed fans\"\nThe match group will be 99.\n\"6 of 99 41 fans\"\nIt will not match, because there was a second number in there.\nTo learn more about Python regular expressions, you can read various web pages. For a quick reminder, inside the Python interpreter, do:\n>>> import re\n>>> help(re)\n\nWhen you are \"scraping\" text from a web page, you might sometimes run afoul of HTML codes. In general, regular expressions are not a good tool for disregarding HTML or XML markup (see here); you would probably do better to use Beautiful Soup to parse the HTML and extract the text, followed by a regular expression to grab the text you really wanted.\nI hope this was interesting and/or educational.\n",
"import urllib\nimport re\n\nfbhandle = urllib.urlopen('http://www.facebook.com/Microsoft')\npattern = \"6 of(.*)fans\" #this wild card doesnt appear to work?\ncompiled = re.compile(pattern)\n\nms = compiled.search(fbhandle.read())\nprint ms.group(1).strip()\nfbhandle.close()\n\nYou needed to use re.search() instead. Using re.match() tries to match the pattern against the whole document, but really you're just trying to match a piece inside the document. The code above prints: 79,110. Of course, this will probably be a different number by the time it gets run by someone else.\n",
"don't need regex\nimport urllib\nfbhandle = urllib.urlopen('http://www.facebook.com/Microsoft')\nfor line in fbhandle.readlines():\n line=line.rstrip().split(\"</span>\")\n for item in line:\n if \">Fans<\" in item:\n rind=item.rindex(\"<span>\")\n print \"-->\",item[rind:].split()[2]\n\noutput\n$ ./python.py\n--> 79,133\n\n"
] |
[
15,
14,
0
] |
[] |
[] |
[
"python",
"regex"
] |
stackoverflow_0001996482_python_regex.txt
|
Q:
Reading from an SSL Socket in Twisted
I'm trying to implement an SSL client in Twisted that simply must connect to a socket and read binary data (specifically, tuples of data). I've gotten the code to a point where it seems to connect and disconnect successfully but no data is ever read from the socket.
class FeedbackHandler(LineReceiver):
MAX_LENGTH = 1024*1024
def connectionMade(self):
log.debug('feedbackHandler connectionMade')
def rawDataReceived(self, data):
log.debug('feedbackHandler rawDataReceived %s' % binascii.hexlify(data))
self.io.write(data)
def lineReceived(self, data):
log.debug('feedbackHandler lineReceived %s' % binascii.hexlify(data))
self.io.write(data)
def connectionLost(self, reason):
log.debug('feedbackHandler connectionLost %s' % reason)
self.deferred.callback(self.io.getValue())
io.close()
And the code that kicks it off:
factory = self.clientProtocolFactory() # a ClientFactory instance
context = self.getContextFactory(CERT_FILE) # a ClientContextFactory
reactor.connectSSL(server, port, factory, context)
However when it runs none of the received methods are called, regardless of setRawMode. Is there just nothing to read from the server? connectionMade and connectionLost are called immediately when connecting and terminates with a ConnectionDone error instance.
A:
Take a look at ssldump or wireshark. Since you're not seeing any data delivered at this level, you should drop down a level to one of these tools. One of them might reveal an SSL negotiation error, or that the server never sends any bytes, or something else that's hard to guess based just on what you've discovered so far. You still might not have the complete answer, but you'll have more pieces of the puzzle.
|
Reading from an SSL Socket in Twisted
|
I'm trying to implement an SSL client in Twisted that simply must connect to a socket and read binary data (specifically, tuples of data). I've gotten the code to a point where it seems to connect and disconnect successfully but no data is ever read from the socket.
class FeedbackHandler(LineReceiver):
MAX_LENGTH = 1024*1024
def connectionMade(self):
log.debug('feedbackHandler connectionMade')
def rawDataReceived(self, data):
log.debug('feedbackHandler rawDataReceived %s' % binascii.hexlify(data))
self.io.write(data)
def lineReceived(self, data):
log.debug('feedbackHandler lineReceived %s' % binascii.hexlify(data))
self.io.write(data)
def connectionLost(self, reason):
log.debug('feedbackHandler connectionLost %s' % reason)
self.deferred.callback(self.io.getValue())
io.close()
And the code that kicks it off:
factory = self.clientProtocolFactory() # a ClientFactory instance
context = self.getContextFactory(CERT_FILE) # a ClientContextFactory
reactor.connectSSL(server, port, factory, context)
However when it runs none of the received methods are called, regardless of setRawMode. Is there just nothing to read from the server? connectionMade and connectionLost are called immediately when connecting and terminates with a ConnectionDone error instance.
|
[
"Take a look at ssldump or wireshark. Since you're not seeing any data delivered at this level, you should drop down a level to one of these tools. One of them might reveal an SSL negotiation error, or that the server never sends any bytes, or something else that's hard to guess based just on what you've discovered so far. You still might not have the complete answer, but you'll have more pieces of the puzzle.\n"
] |
[
2
] |
[] |
[] |
[
"openssl",
"python",
"sockets",
"twisted"
] |
stackoverflow_0001991399_openssl_python_sockets_twisted.txt
|
Q:
Error in imitating memoize() from django.utils.functional.py
def a():
print 'aa'
def b():
print 'bb'
def c(*x):
print x
def d(x,y):
c(*(x+y))
d(a,b)
Traceback (most recent call last):
File "D:\zjm_code\mysite\zjmbooks\a.py", line 15, in <module>
d(a,b)
File "D:\zjm_code\mysite\zjmbooks\a.py", line 13, in d
c(*(x+y))
TypeError: unsupported operand type(s) for +: 'function' and 'function'
the code in django.utils.functional.py:
def curry(_curried_func, *args, **kwargs):
def _curried(*moreargs, **morekwargs):
return _curried_func(*(args+moreargs), **dict(kwargs, **morekwargs))
return _curried
WRAPPER_ASSIGNMENTS = ('__module__', '__name__', '__doc__')
WRAPPER_UPDATES = ('__dict__',)
def update_wrapper(wrapper,
wrapped,
assigned = WRAPPER_ASSIGNMENTS,
updated = WRAPPER_UPDATES):
for attr in assigned:
try:
setattr(wrapper, attr, getattr(wrapped, attr))
except TypeError: # Python 2.3 doesn't allow assigning to __name__.
pass
for attr in updated:
getattr(wrapper, attr).update(getattr(wrapped, attr))
return wrapper
def wraps(wrapped,
assigned = WRAPPER_ASSIGNMENTS,
updated = WRAPPER_UPDATES):
return curry(update_wrapper, wrapped=wrapped,
assigned=assigned, updated=updated)
### End from Python 2.5 functools.py ##########################################
def memoize(func, cache, num_args):
def wrapper(*args):
mem_args = args[:num_args]
if mem_args in cache:
return cache[mem_args]
result = func(*args)
cache[mem_args] = result
return result
return wraps(func)(wrapper)
my Analysis:
def curry(update_wrapper, *args, **kwargs):
def _curried(*wrapper, **morekwargs):
return update_wrapper(wrapper,{wrapped:func})#this is the result
return _curried
def update_wrapper(wrapper,wrapped)
def wraps(func):
return curry(update_wrapper, wrapped=func)
wraps(func)(wrapper)
A:
Your code (in x+y, where x is a and y is b) is trying to sum two functions (instead of calling them and summing their results, for example): function objects cannot be summed, so your code raises an exeption.
The code you quote, in args+moreargs, is summing two tuples: tuples can of course perfectly well be summed, it means concatenating them. Absolutely no relation whatsoever to the absurd "sum of two functions" your code is attempting.
|
Error in imitating memoize() from django.utils.functional.py
|
def a():
print 'aa'
def b():
print 'bb'
def c(*x):
print x
def d(x,y):
c(*(x+y))
d(a,b)
Traceback (most recent call last):
File "D:\zjm_code\mysite\zjmbooks\a.py", line 15, in <module>
d(a,b)
File "D:\zjm_code\mysite\zjmbooks\a.py", line 13, in d
c(*(x+y))
TypeError: unsupported operand type(s) for +: 'function' and 'function'
the code in django.utils.functional.py:
def curry(_curried_func, *args, **kwargs):
def _curried(*moreargs, **morekwargs):
return _curried_func(*(args+moreargs), **dict(kwargs, **morekwargs))
return _curried
WRAPPER_ASSIGNMENTS = ('__module__', '__name__', '__doc__')
WRAPPER_UPDATES = ('__dict__',)
def update_wrapper(wrapper,
wrapped,
assigned = WRAPPER_ASSIGNMENTS,
updated = WRAPPER_UPDATES):
for attr in assigned:
try:
setattr(wrapper, attr, getattr(wrapped, attr))
except TypeError: # Python 2.3 doesn't allow assigning to __name__.
pass
for attr in updated:
getattr(wrapper, attr).update(getattr(wrapped, attr))
return wrapper
def wraps(wrapped,
assigned = WRAPPER_ASSIGNMENTS,
updated = WRAPPER_UPDATES):
return curry(update_wrapper, wrapped=wrapped,
assigned=assigned, updated=updated)
### End from Python 2.5 functools.py ##########################################
def memoize(func, cache, num_args):
def wrapper(*args):
mem_args = args[:num_args]
if mem_args in cache:
return cache[mem_args]
result = func(*args)
cache[mem_args] = result
return result
return wraps(func)(wrapper)
my Analysis:
def curry(update_wrapper, *args, **kwargs):
def _curried(*wrapper, **morekwargs):
return update_wrapper(wrapper,{wrapped:func})#this is the result
return _curried
def update_wrapper(wrapper,wrapped)
def wraps(func):
return curry(update_wrapper, wrapped=func)
wraps(func)(wrapper)
|
[
"Your code (in x+y, where x is a and y is b) is trying to sum two functions (instead of calling them and summing their results, for example): function objects cannot be summed, so your code raises an exeption.\nThe code you quote, in args+moreargs, is summing two tuples: tuples can of course perfectly well be summed, it means concatenating them. Absolutely no relation whatsoever to the absurd \"sum of two functions\" your code is attempting.\n"
] |
[
3
] |
[] |
[] |
[
"caching",
"python"
] |
stackoverflow_0001997094_caching_python.txt
|
Q:
How to connect two state circles with an arrow in tkinter?
I am currently writing a fsm editor with tkinter. But, I stuck on connecting two states. I have two questions:
1) How can make the transition arrow growable according to mouse movement?
2) How can I stick the starting point of the arrow on a state and the end point of the arrow on another state?
PS. Do you think the documentation of tkinter is good enough?
A:
Here's an example that shows the concept. In a nutshell, use tags to associate lines with boxes, and simply adjust the coordinates appropriately when the user moves the mouse.
Run the example, then click and drag from within the beige box.
Of course, for production code you need to make a more general solution, but hopefully this shows you how easy it is to create a box with arrows that adjust as you move the box around.
from Tkinter import *
class CanvasDemo(Frame):
def __init__(self, width=200, height=200):
Frame.__init__(self, root)
self.canvas = Canvas(self)
self.canvas.pack(fill="both", expand="1")
self.canvas.create_rectangle(50, 25, 150, 75, fill="bisque", tags="r1")
self.canvas.create_line(0,0, 50, 25, arrow="last", tags="to_r1")
self.canvas.bind("<B1-Motion>", self.move_box)
self.canvas.bind("<ButtonPress-1>", self.start_move)
def move_box(self, event):
deltax = event.x - self.x
deltay = event.y - self.y
self.canvas.move("r1", deltax, deltay)
coords = self.canvas.coords("to_r1")
coords[2] += deltax
coords[3] += deltay
self.canvas.coords("to_r1", *coords)
self.x = event.x
self.y = event.y
def start_move(self, event):
self.x = event.x
self.y = event.y
root = Tk()
canvas = CanvasDemo(root)
canvas.pack()
mainloop()
A:
Tkinter is perfectly fine for this sort of application. In the past I've worked on tools that were boxes connected with arrows that stayed connected as you move the boxes around (which is what I think you are asking about). Don't let people who don't know much about Tkinter sway you -- it's a perfectly fine toolkit and the canvas is very flexible.
The solution to your problem is simple math. You merely need to compute the coordinates of the edges or corners of boxes to know where to anchor your arrows. To make it "grow" as you say, simply make a binding on mouse movements and update the coordinates appropriately.
To make the line growable all you have to do is adjust the coordinates of the line each time the mouse moves. The easiest thing to do is make liberal use of canvas tags. With the tags you can know which arrows connect to which boxes so that when you move the box you adjust the coordinates of any arrows that point to or from it.
|
How to connect two state circles with an arrow in tkinter?
|
I am currently writing a fsm editor with tkinter. But, I stuck on connecting two states. I have two questions:
1) How can make the transition arrow growable according to mouse movement?
2) How can I stick the starting point of the arrow on a state and the end point of the arrow on another state?
PS. Do you think the documentation of tkinter is good enough?
|
[
"Here's an example that shows the concept. In a nutshell, use tags to associate lines with boxes, and simply adjust the coordinates appropriately when the user moves the mouse.\nRun the example, then click and drag from within the beige box.\nOf course, for production code you need to make a more general solution, but hopefully this shows you how easy it is to create a box with arrows that adjust as you move the box around.\nfrom Tkinter import *\n\nclass CanvasDemo(Frame):\n def __init__(self, width=200, height=200):\n Frame.__init__(self, root)\n self.canvas = Canvas(self)\n self.canvas.pack(fill=\"both\", expand=\"1\")\n self.canvas.create_rectangle(50, 25, 150, 75, fill=\"bisque\", tags=\"r1\")\n self.canvas.create_line(0,0, 50, 25, arrow=\"last\", tags=\"to_r1\")\n self.canvas.bind(\"<B1-Motion>\", self.move_box)\n self.canvas.bind(\"<ButtonPress-1>\", self.start_move)\n\n def move_box(self, event):\n deltax = event.x - self.x\n deltay = event.y - self.y\n self.canvas.move(\"r1\", deltax, deltay)\n coords = self.canvas.coords(\"to_r1\")\n coords[2] += deltax\n coords[3] += deltay\n self.canvas.coords(\"to_r1\", *coords)\n self.x = event.x\n self.y = event.y\n\n def start_move(self, event):\n self.x = event.x\n self.y = event.y\n\nroot = Tk()\ncanvas = CanvasDemo(root)\ncanvas.pack()\nmainloop()\n\n",
"Tkinter is perfectly fine for this sort of application. In the past I've worked on tools that were boxes connected with arrows that stayed connected as you move the boxes around (which is what I think you are asking about). Don't let people who don't know much about Tkinter sway you -- it's a perfectly fine toolkit and the canvas is very flexible. \nThe solution to your problem is simple math. You merely need to compute the coordinates of the edges or corners of boxes to know where to anchor your arrows. To make it \"grow\" as you say, simply make a binding on mouse movements and update the coordinates appropriately.\nTo make the line growable all you have to do is adjust the coordinates of the line each time the mouse moves. The easiest thing to do is make liberal use of canvas tags. With the tags you can know which arrows connect to which boxes so that when you move the box you adjust the coordinates of any arrows that point to or from it.\n"
] |
[
5,
3
] |
[] |
[] |
[
"fsm",
"python",
"tkinter"
] |
stackoverflow_0001996377_fsm_python_tkinter.txt
|
Q:
How to get something to appear on every page in Django?
I'm curious as to the best-practise way to handle having something appear on every page, or on a number of pages without having to assign the data manually to every page like so:
# views.py
def page0(request):
return render_to_response(
"core/index.html",
{
"locality": getCityForm(request.user),
},
context_instance=RequestContext(request)
)
def page1(request):
return render_to_response(
"core/index.html",
{
"locality": getCityForm(request.user),
},
context_instance=RequestContext(request)
)
...
def page9(request):
return render_to_response(
"core/index.html",
{
"locality": getCityForm(request.user),
},
context_instance=RequestContext(request)
)
Now I can think of a few ways to do this, including writing my own Context or maybe some middleware, and of course, copy/pasting this locality assignment on every page... I'm just not sure of the best way to do this. I'm pretty sure that it's not that last one though.
A:
You want a context processor. The data they generate is included in every context created as a RequestContext. They are perfect for this.
Combined with base templates that show common things, you can get rid of lots of need for copying and pasting code.
A:
use inheritance in the templating engine:
have a base.html that includes the common code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<link rel="stylesheet" href="style.css" />
<title>{% block title %}My amazing site{% endblock %}</title>
</head>
<body>
<div id="sidebar">
{% block sidebar %}
<ul>
<li><a href="/">Home</a></li>
<li><a href="/blog/">Blog</a></li>
</ul>
{% endblock %}
</div>
<div id="content">
{% block content %}{% endblock %}
</div>
</body>
</html>
then in each page that needs that common code, simply:
{% extends "base.html" %}
{% block title %}My amazing blog{% endblock %}
{% block content %}
{% for entry in blog_entries %}
<h2>{{ entry.title }}</h2>
<p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
http://docs.djangoproject.com/en/dev/topics/templates/#id1
this combined with context processessing will eliminate a lot of duplicate code.
A:
Middleware is one option or your could write a custom template tag.
A:
To do exactly what you request, I'd simply define a function:
def foobar(req):
return render_to_response(
"core/index.html",
{
"locality": getCityForm(req.user),
},
context_instance=RequestContext(req)
)
put it in some module myfun, and return myfun.foobar(request) wherever needed. You're likely to want a few more arguments, but as long as it stays about this simple, it's simpler that defining middleware, using OOP, &c.
|
How to get something to appear on every page in Django?
|
I'm curious as to the best-practise way to handle having something appear on every page, or on a number of pages without having to assign the data manually to every page like so:
# views.py
def page0(request):
return render_to_response(
"core/index.html",
{
"locality": getCityForm(request.user),
},
context_instance=RequestContext(request)
)
def page1(request):
return render_to_response(
"core/index.html",
{
"locality": getCityForm(request.user),
},
context_instance=RequestContext(request)
)
...
def page9(request):
return render_to_response(
"core/index.html",
{
"locality": getCityForm(request.user),
},
context_instance=RequestContext(request)
)
Now I can think of a few ways to do this, including writing my own Context or maybe some middleware, and of course, copy/pasting this locality assignment on every page... I'm just not sure of the best way to do this. I'm pretty sure that it's not that last one though.
|
[
"You want a context processor. The data they generate is included in every context created as a RequestContext. They are perfect for this.\nCombined with base templates that show common things, you can get rid of lots of need for copying and pasting code.\n",
"use inheritance in the templating engine:\nhave a base.html that includes the common code:\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">\n<head>\n<link rel=\"stylesheet\" href=\"style.css\" />\n<title>{% block title %}My amazing site{% endblock %}</title>\n</head>\n\n<body>\n<div id=\"sidebar\">\n {% block sidebar %}\n <ul>\n <li><a href=\"/\">Home</a></li>\n <li><a href=\"/blog/\">Blog</a></li>\n </ul>\n {% endblock %}\n</div>\n\n<div id=\"content\">\n {% block content %}{% endblock %}\n</div>\n</body>\n</html>\n\nthen in each page that needs that common code, simply:\n{% extends \"base.html\" %}\n{% block title %}My amazing blog{% endblock %}\n{% block content %}\n{% for entry in blog_entries %}\n<h2>{{ entry.title }}</h2>\n<p>{{ entry.body }}</p>\n{% endfor %}\n{% endblock %}\n\nhttp://docs.djangoproject.com/en/dev/topics/templates/#id1\nthis combined with context processessing will eliminate a lot of duplicate code.\n",
"Middleware is one option or your could write a custom template tag.\n",
"To do exactly what you request, I'd simply define a function:\ndef foobar(req):\n return render_to_response(\n \"core/index.html\",\n {\n \"locality\": getCityForm(req.user),\n },\n context_instance=RequestContext(req)\n )\n\nput it in some module myfun, and return myfun.foobar(request) wherever needed. You're likely to want a few more arguments, but as long as it stays about this simple, it's simpler that defining middleware, using OOP, &c.\n"
] |
[
16,
3,
2,
0
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0001997109_django_python.txt
|
Q:
How are exceptions implemented under the hood?
Just about everyone uses them, but many, including me simply take it for granted that they just work.
I am looking for high-quality material. Languages I use are: Java, C, C#, Python, C++, so these are of most interest to me.
Now, C++ is probably a good place to start since you can throw anything in that language.
Also, C is close to assembly. How would one emulate exceptions using pure C constructs and no assembly?
Finally, I heard a rumor that Google employees do not use exceptions for some projects due to speed considerations. Is this just a rumor? How can anything substantial be accomplished without them?
Thank you.
A:
Exceptions are just a specific example of a more general case of advanced non-local flow control constructs. Other examples are:
notifications (a generalization of exceptions, originally from some old Lisp object system, now implemented in e.g. CommonLisp and Ioke),
continuations (a more structured form of GOTO, popular in high-level, higher-order languages),
coroutines (a generalization of subroutines, popular especially in Lua),
generators à la Python (essentially a restricted form of coroutines),
fibers (cooperative light-weight threads) and of course the already mentioned
GOTO.
(I'm sure there's many others I missed.)
An interesting property of these constructs is that they are all roughly equivalent in expressive power: if you have one, you can pretty easily build all the others.
So, how you best implement exceptions depends on what other constructs you have available:
Every CPU has GOTO, therefore you can always fall back to that, if you must.
C has setjmp/longjmp which are basically MacGyver continuations (built out of duct-tape and toothpicks, not quite the real thing, but will at least get you out of the immediate trouble if you don't have something better available).
The JVM and CLI have exceptions of their own, which means that if the exception semantics of your language match Java's/C#'s, you are home free (but if not, then you are screwed).
The Parrot VM as both exceptions and continuations.
Windows has its own framework for exception handling, which language implementors can use to build their own exceptions on top.
A very interesting use case, both of the usage of exceptions and the implementation of exceptions is Microsoft Live Lab's Volta Project. (Now defunct.) The goal of Volta was to provide architectural refactoring for Web applications at the push of a button. So, you could turn your one-tier web application into a two- or three-tier application just by putting some [Browser] or [DB] attributes on your .NET code and the code would then automagically run on the client or in the DB. In order to do that, the .NET code had to be translated to JavaScript source code, obviously.
Now, you could just write an entire VM in JavaScript and run the bytecode unmodified. (Basically, port the CLR from C++ to JavaScript.) There are actually projects that do this (e.g. the HotRuby VM), but this is both inefficient and not very interoperable with other JavaScript code.
So, instead, they wrote a compiler which compiles CIL bytecode to JavaScript sourcecode. However, JavaScript lacks certain features that .NET has (generators, threads, also the two exception models aren't 100% compatible), and more importantly it lacks certain features that compiler writers love (either GOTO or continuations) and that could be used to implement the above-mentioned missing features.
However, JavaScript does have exceptions. So, they used JavaScript Exceptions to implement Volta Continuations and then they used Volta Continuations to implement .NET Exceptions, .NET Generators and even .NET Managed Threads(!!!)
So, to answer your original question:
How are exceptions implemented under the hood?
With Exceptions, ironically! At least in this very specific case, anyway.
Another great example is some of the exception proposals on the Go mailing list, which implement exceptions using Goroutines (something like a mixture of concurrent coroutines ans CSP processes). Yet another example is Haskell, which uses Monads, lazy evaluation, tail call optimization and higher-order functions to implement exceptions. Some modern CPUs also support basic building blocks for exceptions (for example the Vega-3 CPUs that were specifically designed for the Azul Systems Java Compute Accelerators).
A:
Here is a common way C++ exceptions are implemented:
http://www.codesourcery.com/public/cxx-abi/abi-eh.html
It is for the Itanium architecture, but the implementation described here is used in other architectures as well. Note that it is a long document, since C++ exceptions are complicated.
Here is a good description on how LLVM implements exceptions:
http://llvm.org/docs/ExceptionHandling.html
Since LLVM is meant to be a common intermediate representation for many runtimes, the mechanisms described can be applied to many languages.
A:
In his book C Interfaces and Implementations: Techniques for Creating Reusable Software, D. R. Hanson provides a nice implementation of exceptions in pure C using a set of macros and setjmp/longjmp. He provides TRY/RAISE/EXCEPT/FINALLY macros that can emulate pretty much everything C++ exceptions do and more.
The code can be perused here (look at except.h/except.c).
P.S. re your question about Google. Their employees are actually allowed to use exceptions in new code, and the official reason for the ban in old code is because it was already written that way and it doesn't make sense to mix styles.
Personally, I also think that C++ without exceptions isn't the best idea.
A:
C/C++ compilers use the underlying OS facilities for exception handling. Frameworks like .Net or Java also rely, in the VM, on the OS facilities. In Windows for instance, the real heavy lifting is done by SEH, the Structured Exception Handling infrastructure. You should absolutely read the old reference article: A Crash Course on the Depths of Win32™ Structured Exception Handling.
As for the cost of not using exceptions, they are expensive but compared to what? Compared to return error codes? After you factor in the cost of correctness and the quality of code, exceptions will always win for commercial applications. Short of few very critical OS level functions, exceptions are always better overall.
An last but not least there is the anti-pattern of using exceptions for flow control. Exceptions should be exceptional and code that abuses exceptions fro flow control will pay the price in performance.
A:
The best paper ever written on the implementation of exceptions (under the hood) is Exception Handling in CLU by Barbara Liskov and Alan Snyder. I have referred to it every time I've started a new compiler.
For a somewhat higher-level view of an implementation in C using setjmp and longjmp, I recommend Dave Hanson's C Interfaces and Implementations (like Eli Bendersky).
A:
setjmp() and longjmp() usually.
Exception catching does have a non-trivial cost, but for most purposes it's not a big deal.
A:
The key thing an exception implementation needs to handle is how to return to the exception handler once an exception has been thrown. Since you may have made an arbitrary number of nested function calls since the try statement in C++, it must unwind the call stack searching for the handler. However implemented, this must incur the code size cost of maintaining sufficient information in order to perform this operation (and generally means a table of data for calls that can take exceptions). It also means that the dynamic code execution path will be longer than simply returning from functions calls (which is a fairly inexpensive operation on most platforms). There may be other costs as well depending on the implementation.
The relative cost will vary depending on the language used. The higher-level language used, the less likely the code size cost will matter, and the information may be retained regardless of whether exceptions are used.
An application where the use of exceptions (and C++ in general) is often avoided for good reasons is embedded firmware. In typical small bare metal or RTOS platforms, you might have 1MB of code space, or 64K, or even smaller. Some platforms are so small, even C is not practical to use. In this kind of environment, the size impact is relevant because of the cost mentioned above. It also impacts the standard library itself. Embedded toolchain vendors will often produce a library without exception capability, which has a huge impact on code size. Highly optimizing compilers may also analyze the callgraph and optimize away needed call frame information for the unwind operation for considerable space reduction. Exceptions also make it more difficult to analyze hard real-time requirements.
In more typical environments, the code size cost is almost certainly irrelevant and the performance factor is likely key. Whether you use them will depend on your performance requirements and how you want to use them. Using exceptions in non-exceptional cases can make an elegant design, but at a performance cost that may be unacceptable for high performance systems. Implementations and relative cost will vary by platform and compiler, so the best way to truly understand if exceptions are a problem is to analyze your own code's performance.
A:
C++ code at Google (save for some Windows-specific cases) don't use exceptions: cfr the guidelines, short form: "We do not use C++ exceptions". Quoting from the discussion (hit the arrow to expand on the URL):
Our advice against using exceptions is
not predicated on philosophical or
moral grounds, but practical ones.
Because we'd like to use our
open-source projects at Google and
it's difficult to do so if those
projects use exceptions, we need to
advise against exceptions in Google
open-source projects as well. Things
would probably be different if we had
to do it all over again from scratch.
This rule does not apply to Google code in other languages, such as Java and Python.
A:
Regarding performance - sparse use of exceptions will probably have negligible effects, but do not abuse them.
I have personally seen Java code which performed two orders of magnitude worse than it could have (took about x100 the time) because exceptions were used in an important loop instead of more standard if/returns.
A:
Some runtimes like the Objective-C runtime have zero-cost 64-bit exceptions. What that means is that it doesn't cost anything to enter a try block. However, this is quite costly when the exception is thrown. This follows the paradigm of "optimize for the average case" - exceptions are meant to be exceptional, so it is better to make the case when there are no exceptions really fast, even if it comes at the cost of significantly slower exceptions.
|
How are exceptions implemented under the hood?
|
Just about everyone uses them, but many, including me simply take it for granted that they just work.
I am looking for high-quality material. Languages I use are: Java, C, C#, Python, C++, so these are of most interest to me.
Now, C++ is probably a good place to start since you can throw anything in that language.
Also, C is close to assembly. How would one emulate exceptions using pure C constructs and no assembly?
Finally, I heard a rumor that Google employees do not use exceptions for some projects due to speed considerations. Is this just a rumor? How can anything substantial be accomplished without them?
Thank you.
|
[
"Exceptions are just a specific example of a more general case of advanced non-local flow control constructs. Other examples are:\n\nnotifications (a generalization of exceptions, originally from some old Lisp object system, now implemented in e.g. CommonLisp and Ioke), \ncontinuations (a more structured form of GOTO, popular in high-level, higher-order languages), \ncoroutines (a generalization of subroutines, popular especially in Lua), \ngenerators à la Python (essentially a restricted form of coroutines), \nfibers (cooperative light-weight threads) and of course the already mentioned \nGOTO.\n\n(I'm sure there's many others I missed.)\nAn interesting property of these constructs is that they are all roughly equivalent in expressive power: if you have one, you can pretty easily build all the others.\nSo, how you best implement exceptions depends on what other constructs you have available: \n\nEvery CPU has GOTO, therefore you can always fall back to that, if you must.\nC has setjmp/longjmp which are basically MacGyver continuations (built out of duct-tape and toothpicks, not quite the real thing, but will at least get you out of the immediate trouble if you don't have something better available). \nThe JVM and CLI have exceptions of their own, which means that if the exception semantics of your language match Java's/C#'s, you are home free (but if not, then you are screwed). \nThe Parrot VM as both exceptions and continuations. \nWindows has its own framework for exception handling, which language implementors can use to build their own exceptions on top.\n\nA very interesting use case, both of the usage of exceptions and the implementation of exceptions is Microsoft Live Lab's Volta Project. (Now defunct.) The goal of Volta was to provide architectural refactoring for Web applications at the push of a button. So, you could turn your one-tier web application into a two- or three-tier application just by putting some [Browser] or [DB] attributes on your .NET code and the code would then automagically run on the client or in the DB. In order to do that, the .NET code had to be translated to JavaScript source code, obviously.\nNow, you could just write an entire VM in JavaScript and run the bytecode unmodified. (Basically, port the CLR from C++ to JavaScript.) There are actually projects that do this (e.g. the HotRuby VM), but this is both inefficient and not very interoperable with other JavaScript code.\nSo, instead, they wrote a compiler which compiles CIL bytecode to JavaScript sourcecode. However, JavaScript lacks certain features that .NET has (generators, threads, also the two exception models aren't 100% compatible), and more importantly it lacks certain features that compiler writers love (either GOTO or continuations) and that could be used to implement the above-mentioned missing features.\nHowever, JavaScript does have exceptions. So, they used JavaScript Exceptions to implement Volta Continuations and then they used Volta Continuations to implement .NET Exceptions, .NET Generators and even .NET Managed Threads(!!!)\nSo, to answer your original question:\n\nHow are exceptions implemented under the hood?\n\nWith Exceptions, ironically! At least in this very specific case, anyway.\nAnother great example is some of the exception proposals on the Go mailing list, which implement exceptions using Goroutines (something like a mixture of concurrent coroutines ans CSP processes). Yet another example is Haskell, which uses Monads, lazy evaluation, tail call optimization and higher-order functions to implement exceptions. Some modern CPUs also support basic building blocks for exceptions (for example the Vega-3 CPUs that were specifically designed for the Azul Systems Java Compute Accelerators).\n",
"Here is a common way C++ exceptions are implemented:\nhttp://www.codesourcery.com/public/cxx-abi/abi-eh.html\nIt is for the Itanium architecture, but the implementation described here is used in other architectures as well. Note that it is a long document, since C++ exceptions are complicated.\nHere is a good description on how LLVM implements exceptions:\nhttp://llvm.org/docs/ExceptionHandling.html\nSince LLVM is meant to be a common intermediate representation for many runtimes, the mechanisms described can be applied to many languages.\n",
"In his book C Interfaces and Implementations: Techniques for Creating Reusable Software, D. R. Hanson provides a nice implementation of exceptions in pure C using a set of macros and setjmp/longjmp. He provides TRY/RAISE/EXCEPT/FINALLY macros that can emulate pretty much everything C++ exceptions do and more. \nThe code can be perused here (look at except.h/except.c).\nP.S. re your question about Google. Their employees are actually allowed to use exceptions in new code, and the official reason for the ban in old code is because it was already written that way and it doesn't make sense to mix styles.\nPersonally, I also think that C++ without exceptions isn't the best idea.\n",
"C/C++ compilers use the underlying OS facilities for exception handling. Frameworks like .Net or Java also rely, in the VM, on the OS facilities. In Windows for instance, the real heavy lifting is done by SEH, the Structured Exception Handling infrastructure. You should absolutely read the old reference article: A Crash Course on the Depths of Win32™ Structured Exception Handling.\nAs for the cost of not using exceptions, they are expensive but compared to what? Compared to return error codes? After you factor in the cost of correctness and the quality of code, exceptions will always win for commercial applications. Short of few very critical OS level functions, exceptions are always better overall. \nAn last but not least there is the anti-pattern of using exceptions for flow control. Exceptions should be exceptional and code that abuses exceptions fro flow control will pay the price in performance.\n",
"The best paper ever written on the implementation of exceptions (under the hood) is Exception Handling in CLU by Barbara Liskov and Alan Snyder. I have referred to it every time I've started a new compiler.\nFor a somewhat higher-level view of an implementation in C using setjmp and longjmp, I recommend Dave Hanson's C Interfaces and Implementations (like Eli Bendersky).\n",
"setjmp() and longjmp() usually.\nException catching does have a non-trivial cost, but for most purposes it's not a big deal.\n",
"The key thing an exception implementation needs to handle is how to return to the exception handler once an exception has been thrown. Since you may have made an arbitrary number of nested function calls since the try statement in C++, it must unwind the call stack searching for the handler. However implemented, this must incur the code size cost of maintaining sufficient information in order to perform this operation (and generally means a table of data for calls that can take exceptions). It also means that the dynamic code execution path will be longer than simply returning from functions calls (which is a fairly inexpensive operation on most platforms). There may be other costs as well depending on the implementation.\nThe relative cost will vary depending on the language used. The higher-level language used, the less likely the code size cost will matter, and the information may be retained regardless of whether exceptions are used.\nAn application where the use of exceptions (and C++ in general) is often avoided for good reasons is embedded firmware. In typical small bare metal or RTOS platforms, you might have 1MB of code space, or 64K, or even smaller. Some platforms are so small, even C is not practical to use. In this kind of environment, the size impact is relevant because of the cost mentioned above. It also impacts the standard library itself. Embedded toolchain vendors will often produce a library without exception capability, which has a huge impact on code size. Highly optimizing compilers may also analyze the callgraph and optimize away needed call frame information for the unwind operation for considerable space reduction. Exceptions also make it more difficult to analyze hard real-time requirements.\nIn more typical environments, the code size cost is almost certainly irrelevant and the performance factor is likely key. Whether you use them will depend on your performance requirements and how you want to use them. Using exceptions in non-exceptional cases can make an elegant design, but at a performance cost that may be unacceptable for high performance systems. Implementations and relative cost will vary by platform and compiler, so the best way to truly understand if exceptions are a problem is to analyze your own code's performance.\n",
"C++ code at Google (save for some Windows-specific cases) don't use exceptions: cfr the guidelines, short form: \"We do not use C++ exceptions\". Quoting from the discussion (hit the arrow to expand on the URL):\n\nOur advice against using exceptions is\n not predicated on philosophical or\n moral grounds, but practical ones.\n Because we'd like to use our\n open-source projects at Google and\n it's difficult to do so if those\n projects use exceptions, we need to\n advise against exceptions in Google\n open-source projects as well. Things\n would probably be different if we had\n to do it all over again from scratch.\n\nThis rule does not apply to Google code in other languages, such as Java and Python.\n",
"Regarding performance - sparse use of exceptions will probably have negligible effects, but do not abuse them.\nI have personally seen Java code which performed two orders of magnitude worse than it could have (took about x100 the time) because exceptions were used in an important loop instead of more standard if/returns.\n",
"Some runtimes like the Objective-C runtime have zero-cost 64-bit exceptions. What that means is that it doesn't cost anything to enter a try block. However, this is quite costly when the exception is thrown. This follows the paradigm of \"optimize for the average case\" - exceptions are meant to be exceptional, so it is better to make the case when there are no exceptions really fast, even if it comes at the cost of significantly slower exceptions.\n"
] |
[
50,
24,
19,
7,
6,
5,
4,
3,
1,
1
] |
[] |
[] |
[
"c",
"c++",
"exception",
"python"
] |
stackoverflow_0001995734_c_c++_exception_python.txt
|
Q:
Can't find thread.py
What does this code mean?
try:
import thread
except ImportError:
del _sys.modules[__name__]#why
raise
But I can't find thread.py.
why,del _sys.modules[__name__]
A:
That code from Python's threading.py is trying to load the C implementation of the thread module. If it fails (for some reason this hasn't been compiled, as it would be with all Python distributions) then it deletes itself from the list of modules so that threading doesn't show up as having been imported.
If you're looking for the source of the thread module, it's here: http://svn.python.org/projects/python/trunk/Python/thread.c
A:
Must be some custom logic - keeping track of what is imported and where. In regular Python 3.1 this standalone code does not work:
>>> try:
import thread
except:
del _sys.modules[__name__]
raise
Traceback (most recent call last):
File "<pyshell#10>", line 4, in <module>
del _sys.modules[__name__]
NameError: name '_sys' is not defined
>>>
Where did you find this?
|
Can't find thread.py
|
What does this code mean?
try:
import thread
except ImportError:
del _sys.modules[__name__]#why
raise
But I can't find thread.py.
why,del _sys.modules[__name__]
|
[
"That code from Python's threading.py is trying to load the C implementation of the thread module. If it fails (for some reason this hasn't been compiled, as it would be with all Python distributions) then it deletes itself from the list of modules so that threading doesn't show up as having been imported.\nIf you're looking for the source of the thread module, it's here: http://svn.python.org/projects/python/trunk/Python/thread.c\n",
"Must be some custom logic - keeping track of what is imported and where. In regular Python 3.1 this standalone code does not work:\n>>> try:\n import thread\nexcept:\n del _sys.modules[__name__]\n raise\n\nTraceback (most recent call last):\n File \"<pyshell#10>\", line 4, in <module>\n del _sys.modules[__name__]\nNameError: name '_sys' is not defined\n>>> \n\nWhere did you find this?\n"
] |
[
5,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001997244_python.txt
|
Q:
How to install imagingft in OSX and Ubuntu?
I'm using PIL 1.1.6 to render a truetype font on my local Windows machine. I'd like to be able to get the application running in OSX and Ubuntu (server). So far the instructions I've found all deal with specific ports repositories on OSX (Darwinports, Macports, etc.) or very outdated instructions for Linux.
Has anyone recently got imagingft to work in either and what were your specific steps?
A:
Long ago I'd switched my OSX (Snow Leopard) python version from the default 2.6 back to 2.5 for compatibility reasons on a project I had been working on. I switched it back to 2.6 and was then able to compile imagingft normally:
./configure
make
make install
I was able to do the same thing on my Ubuntu server and neither required that I even reinstall PIL, despite some sets of instructions stating that I might have to.
|
How to install imagingft in OSX and Ubuntu?
|
I'm using PIL 1.1.6 to render a truetype font on my local Windows machine. I'd like to be able to get the application running in OSX and Ubuntu (server). So far the instructions I've found all deal with specific ports repositories on OSX (Darwinports, Macports, etc.) or very outdated instructions for Linux.
Has anyone recently got imagingft to work in either and what were your specific steps?
|
[
"Long ago I'd switched my OSX (Snow Leopard) python version from the default 2.6 back to 2.5 for compatibility reasons on a project I had been working on. I switched it back to 2.6 and was then able to compile imagingft normally:\n./configure\nmake\nmake install\n\nI was able to do the same thing on my Ubuntu server and neither required that I even reinstall PIL, despite some sets of instructions stating that I might have to.\n"
] |
[
0
] |
[] |
[] |
[
"macos",
"python",
"python_imaging_library",
"ubuntu"
] |
stackoverflow_0001967674_macos_python_python_imaging_library_ubuntu.txt
|
Q:
How does Gedit expose its api to python for plugins?
I'm starting a medium (academic) project in C++ for which I need users to be able to write small scripts, which interact directly with the main program. My first thought as an aproach to this was to make something like Gedit does with it's plugins (in fact I thought about it because it is something very similar to what I need to do.)
I do have some experience writting plugins for geddit, but zero experience in writting a plugin framework.
Would it be really difficult to me to write one similar to gedit's? (i mean, the way it exposes its API to python, and then loads the python plugin and calls its methods). Can anyone point me in the right directions or teach me a little if you have experience with it?
A:
Fortunately, gedit's plugin framework can be used. You could use Ethos, which is the same plugin framework gedit uses, only without gedit.
|
How does Gedit expose its api to python for plugins?
|
I'm starting a medium (academic) project in C++ for which I need users to be able to write small scripts, which interact directly with the main program. My first thought as an aproach to this was to make something like Gedit does with it's plugins (in fact I thought about it because it is something very similar to what I need to do.)
I do have some experience writting plugins for geddit, but zero experience in writting a plugin framework.
Would it be really difficult to me to write one similar to gedit's? (i mean, the way it exposes its API to python, and then loads the python plugin and calls its methods). Can anyone point me in the right directions or teach me a little if you have experience with it?
|
[
"Fortunately, gedit's plugin framework can be used. You could use Ethos, which is the same plugin framework gedit uses, only without gedit.\n"
] |
[
3
] |
[] |
[] |
[
"c++",
"gedit",
"plugins",
"python"
] |
stackoverflow_0001997427_c++_gedit_plugins_python.txt
|
Q:
Find which python modules are being imported
What's an easy way of finding all the python modules from a particular package that are being used in an application?
A:
sys.modules is a dictionary mapping module names to modules. You can examine its keys to see imported modules.
See: http://docs.python.org/library/sys.html#sys.modules
A:
You could use python -v, which will emit messages about every imported module:
$ echo 'print "hello world"' > helo.py
$ python -v helo.py
# installing zipimport hook
import zipimport # builtin
# installed zipimport hook
# /System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site.py
import site # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site.pyc
# /System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/os.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/os.py
import os # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/os.pyc
import posix # builtin
# /System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/posixpath.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/posixpath.py
import posixpath # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/posixpath.pyc
...and so on, and so forth. Of course you can later grep the modules of interest from among this large list!-)
A:
I think modulefinder is what you're looking for. You can use modulefinder.py directly, running it as a script as is described there, or you can import the module and then create a report using the modulefinder.ModuleFinder class.
A:
A real simple method is to delete all .pyc files from the package or folder, and then run the application. Once you've played a bit, do a directory listing and see which files have .pyc files now. Those are modules which were imported by the application.
(Note: the __main__ module, whichever one you invoke as the "main" script, never gets compiled, so you should not expect to see a .pyc file for it unless something imported it from within the application. This is often a sign of a problem if it does happen.)
|
Find which python modules are being imported
|
What's an easy way of finding all the python modules from a particular package that are being used in an application?
|
[
"sys.modules is a dictionary mapping module names to modules. You can examine its keys to see imported modules.\nSee: http://docs.python.org/library/sys.html#sys.modules\n",
"You could use python -v, which will emit messages about every imported module:\n$ echo 'print \"hello world\"' > helo.py\n$ python -v helo.py\n# installing zipimport hook\nimport zipimport # builtin\n# installed zipimport hook\n# /System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site.py\nimport site # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site.pyc\n# /System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/os.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/os.py\nimport os # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/os.pyc\nimport posix # builtin\n# /System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/posixpath.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/posixpath.py\nimport posixpath # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/posixpath.pyc\n\n...and so on, and so forth. Of course you can later grep the modules of interest from among this large list!-)\n",
"I think modulefinder is what you're looking for. You can use modulefinder.py directly, running it as a script as is described there, or you can import the module and then create a report using the modulefinder.ModuleFinder class.\n",
"A real simple method is to delete all .pyc files from the package or folder, and then run the application. Once you've played a bit, do a directory listing and see which files have .pyc files now. Those are modules which were imported by the application.\n(Note: the __main__ module, whichever one you invoke as the \"main\" script, never gets compiled, so you should not expect to see a .pyc file for it unless something imported it from within the application. This is often a sign of a problem if it does happen.)\n"
] |
[
40,
35,
1,
0
] |
[] |
[] |
[
"package",
"python"
] |
stackoverflow_0001997449_package_python.txt
|
Q:
Django -vs- Grails -vs-?
I'm wondering if there's such a thing as Django-like ease of web app development combined with good deployment, debugging and other tools?
Django is a very productive framework for building content-heavy sites; the best I've tried and a breath of fresh air compared to some of the Java monstrosities out there. However it's written in Python which means there's little real support in the way of deployment/packaging, debugging, profilers and other tools that make building and maintaining applications much easier.
Ruby has similar issues and although I do like Ruby much better than I like Python, I get the impression that Rails is roughly in the same boat at Django when it comes to managing/supporting the app.
Has anyone here tried both Django and Grails (or other web frameworks) for non-trivial projects? How did they compare?
A:
You asked for someone who used both Grails and Django. I've done work on both for big projects. Here's my Thoughts:
IDE's:
Django works really well in Eclipse, Grails works really well in IntelliJ Idea.
Debugging:
Practically the same (assuming you use IntelliJ for Grails, and Eclipse for Python). Step debugging, inspecting variables, etc... never need a print statement for either. Sometimes django error messages can be useless but Grails error messages are usually pretty lengthy and hard to parse through.
Time to run a unit test:
django: 2 seconds.
Grails: 20 seconds (the tests themselves both run in a fraction of a second, it's the part about loading the framework to run them that takes the rest... as you can see, Grails is frustratingly slow to load).
Deployment:
Django: copy & paste one file into an apache config, and to redeploy, just change the code and reload apache.
Grails: create a .war file, deploy it on tomcat, rinse and repeat to redeploy.
Programming languages:
Groovy is TOTALLY awesome. I love it, more so than Python. But I certainly have no complaints.
Plugins:
Grails: lots of broken plugins (and can use every java lib ever).
Django: a few stable plugins, but enough to do most of what you need.
Database:
Django: schema migrations using South, and generally intuitive relations.
Grails: no schema migrations, and by default it deletes the database on startup... WTF
Usage:
Django: startups (especially in the Gov 2.0 space), independent web dev shops.
Grails: enterprise
Hope that helps!
A:
However it's written in Python which
means there's little real support in
the way of deployment/packaging,
debugging, profilers and other tools
that make building and maintaining
applications much easier.
Python has:
a great interactive debugger, which makes very good use of Python REPL.
easy_install anv virtualenv for dependency management, packaging and deployment.
profiling features comparable to other languages
So IMHO you shouldn't worry about this things, use Python and Django and live happily :-)
Lucky for you, newest version of Django runs on Jython, so you don't need to leave your whole Java ecosystem behind.
Speaking of frameworks, I evaluated this year:
Pylons (Python)
webpy (Python)
Symfony (PHP)
CakePHP (PHP)
None of this frameworks comes close to the power of Django or Ruby on Rails. Based on my collegue opinion I could recommend you kohana framework. The downside is, it's written in PHP and, as far as I know, PHP doesn't have superb tools for debugging, profiling and packaging of apps.
Edit: Here is a very good article about packaging and deployment of Python apps (specifically Django apps). It's a hot topic in Django community now.
A:
Grails.
Grails just looks like Rails (Ruby),but it uses groovy which is simpler than java. It uses java technology and you can use any java lib without any trouble.
I also choose Grails over simplicity and there are lots of java lib (such as jasper report, jawr etc) and I am glad that now they join with SpringSource which makes their base solid.
A:
The statement that grails deletes the database on start-up is completely wrong. It's behavior on start-up is completely configurable and easy to configure. I generally use create-drop when running an app in dev mode. I use update when I run in test and production.
I also love the bootstrap processing that lets me pre-configure test users, data, etc by environment in Grails.
I'd love to see someone who has really built and deployed some commercial projects comment on the pros / cons. Be a really interesting read.
A:
I have two friends who originally started writing an application using Ruby on Rails, but ran into a number of issues and limitations. After about 8 weeks of working on it, they decided to investigate other alternatives.
They settled on the Catalyst Framework, and Perl. That was about 4 months ago now, and they've repeatedly talked about how much better the application is going, and how much more flexibility they have.
With Perl, you have all of CPAN available to you, along with the large quantity of tools included. I'd suggest taking a look at it, at least.
A:
The "good deployment" issue -- for Python -- doesn't have the Deep Significance that it has for Java.
Python deployment for Django is basically "move the files". You can run straight out of the subversion trunk directory if you want to.
You can, without breaking much of a sweat, using the Python distutils and build yourself a distribution kit that puts your Django apps into Python's site-packages. I'm not a big fan of it, but it's really easy to do.
Since my stuff runs in Linux, I have simple "install.py" scripts that move stuff out of the Subversion directories into /opt/this and /opt/that directories. I use an explicit path settings in my Apache configuration to name those directories where the applications live.
Patching can be done by editing the files in place. (A bad policy.) I prefer to edit in the SVN location and rerun my little install to be sure I actually have all the files under control.
A:
cakephp.org
Cakephp is really good, really close to ruby on rails (1.2). It is in php, works very well on shared hosts and is easy to implement.
The only downside is that the documentation is somewhat lacking, but you quickly get it and quickly start doing cool stuff.
I totally recommend cakephp.
A:
Personally I made some rather big projects with Django, but I can compare only with said "montrosities" (Spring, EJB) and really low-level stuff like Twisted.
Web frameworks using interpreted languages are mostly in its infancy and all of them (actively maintained, that is) are getting better with every day.
A:
By "good deployment" are you comparing it with Java's EAR files, which allow you to deploy web applications by uploading a single file to a J2EE server? (And, to a lesser extent, WAR files; EAR files can have WAR files for dependent projects)
I don't think Django or Rails have gotten quite to that point yet, but I could be wrong... zuber pointed out an article with more details on the Python side.
Capistrano may help out on the Ruby side.
Unfortunately, I haven't really worked with either Python or Ruby that much, so I can't help out on profilers or debuggers.
|
Django -vs- Grails -vs-?
|
I'm wondering if there's such a thing as Django-like ease of web app development combined with good deployment, debugging and other tools?
Django is a very productive framework for building content-heavy sites; the best I've tried and a breath of fresh air compared to some of the Java monstrosities out there. However it's written in Python which means there's little real support in the way of deployment/packaging, debugging, profilers and other tools that make building and maintaining applications much easier.
Ruby has similar issues and although I do like Ruby much better than I like Python, I get the impression that Rails is roughly in the same boat at Django when it comes to managing/supporting the app.
Has anyone here tried both Django and Grails (or other web frameworks) for non-trivial projects? How did they compare?
|
[
"You asked for someone who used both Grails and Django. I've done work on both for big projects. Here's my Thoughts:\nIDE's:\nDjango works really well in Eclipse, Grails works really well in IntelliJ Idea.\nDebugging:\nPractically the same (assuming you use IntelliJ for Grails, and Eclipse for Python). Step debugging, inspecting variables, etc... never need a print statement for either. Sometimes django error messages can be useless but Grails error messages are usually pretty lengthy and hard to parse through.\nTime to run a unit test:\ndjango: 2 seconds.\nGrails: 20 seconds (the tests themselves both run in a fraction of a second, it's the part about loading the framework to run them that takes the rest... as you can see, Grails is frustratingly slow to load).\nDeployment:\nDjango: copy & paste one file into an apache config, and to redeploy, just change the code and reload apache.\nGrails: create a .war file, deploy it on tomcat, rinse and repeat to redeploy.\nProgramming languages:\nGroovy is TOTALLY awesome. I love it, more so than Python. But I certainly have no complaints. \nPlugins:\nGrails: lots of broken plugins (and can use every java lib ever).\nDjango: a few stable plugins, but enough to do most of what you need.\nDatabase:\nDjango: schema migrations using South, and generally intuitive relations.\nGrails: no schema migrations, and by default it deletes the database on startup... WTF\nUsage:\nDjango: startups (especially in the Gov 2.0 space), independent web dev shops.\nGrails: enterprise\nHope that helps!\n",
"\nHowever it's written in Python which\n means there's little real support in\n the way of deployment/packaging,\n debugging, profilers and other tools\n that make building and maintaining\n applications much easier.\n\nPython has:\n\na great interactive debugger, which makes very good use of Python REPL. \neasy_install anv virtualenv for dependency management, packaging and deployment.\nprofiling features comparable to other languages\n\nSo IMHO you shouldn't worry about this things, use Python and Django and live happily :-)\nLucky for you, newest version of Django runs on Jython, so you don't need to leave your whole Java ecosystem behind.\nSpeaking of frameworks, I evaluated this year:\n\nPylons (Python)\nwebpy (Python)\nSymfony (PHP)\nCakePHP (PHP)\n\nNone of this frameworks comes close to the power of Django or Ruby on Rails. Based on my collegue opinion I could recommend you kohana framework. The downside is, it's written in PHP and, as far as I know, PHP doesn't have superb tools for debugging, profiling and packaging of apps.\nEdit: Here is a very good article about packaging and deployment of Python apps (specifically Django apps). It's a hot topic in Django community now.\n",
"Grails.\nGrails just looks like Rails (Ruby),but it uses groovy which is simpler than java. It uses java technology and you can use any java lib without any trouble.\nI also choose Grails over simplicity and there are lots of java lib (such as jasper report, jawr etc) and I am glad that now they join with SpringSource which makes their base solid.\n",
"The statement that grails deletes the database on start-up is completely wrong. It's behavior on start-up is completely configurable and easy to configure. I generally use create-drop when running an app in dev mode. I use update when I run in test and production.\nI also love the bootstrap processing that lets me pre-configure test users, data, etc by environment in Grails. \nI'd love to see someone who has really built and deployed some commercial projects comment on the pros / cons. Be a really interesting read.\n",
"I have two friends who originally started writing an application using Ruby on Rails, but ran into a number of issues and limitations. After about 8 weeks of working on it, they decided to investigate other alternatives.\nThey settled on the Catalyst Framework, and Perl. That was about 4 months ago now, and they've repeatedly talked about how much better the application is going, and how much more flexibility they have.\nWith Perl, you have all of CPAN available to you, along with the large quantity of tools included. I'd suggest taking a look at it, at least.\n",
"The \"good deployment\" issue -- for Python -- doesn't have the Deep Significance that it has for Java.\nPython deployment for Django is basically \"move the files\". You can run straight out of the subversion trunk directory if you want to.\nYou can, without breaking much of a sweat, using the Python distutils and build yourself a distribution kit that puts your Django apps into Python's site-packages. I'm not a big fan of it, but it's really easy to do. \nSince my stuff runs in Linux, I have simple \"install.py\" scripts that move stuff out of the Subversion directories into /opt/this and /opt/that directories. I use an explicit path settings in my Apache configuration to name those directories where the applications live.\nPatching can be done by editing the files in place. (A bad policy.) I prefer to edit in the SVN location and rerun my little install to be sure I actually have all the files under control.\n",
"cakephp.org\nCakephp is really good, really close to ruby on rails (1.2). It is in php, works very well on shared hosts and is easy to implement. \nThe only downside is that the documentation is somewhat lacking, but you quickly get it and quickly start doing cool stuff.\nI totally recommend cakephp.\n",
"Personally I made some rather big projects with Django, but I can compare only with said \"montrosities\" (Spring, EJB) and really low-level stuff like Twisted.\nWeb frameworks using interpreted languages are mostly in its infancy and all of them (actively maintained, that is) are getting better with every day.\n",
"By \"good deployment\" are you comparing it with Java's EAR files, which allow you to deploy web applications by uploading a single file to a J2EE server? (And, to a lesser extent, WAR files; EAR files can have WAR files for dependent projects)\nI don't think Django or Rails have gotten quite to that point yet, but I could be wrong... zuber pointed out an article with more details on the Python side.\nCapistrano may help out on the Ruby side.\nUnfortunately, I haven't really worked with either Python or Ruby that much, so I can't help out on profilers or debuggers.\n"
] |
[
32,
10,
10,
10,
3,
3,
1,
1,
1
] |
[] |
[] |
[
"django",
"frameworks",
"python"
] |
stackoverflow_0000075798_django_frameworks_python.txt
|
Q:
Determining the number of possible combinations
I'm trying to figure out how many possible ways there are to combine various elements form this string.
"{Hello|Hi|Hey} {world|earth}{!|.|?}"
Where one item (separated by a pipe/|) is selected at random from each group ({}) and combined into a single string.
So the above "template" could produce:
Hello world.
Hi earth?
Hey world.
Hi world?
I'm guessing this is a type of permutation, but I want to make sure I'm getting this right.
It would be really nice if this worked with "n" nested items as well.
"{{Hello|Hi|Hey} {world|earth}|{Goodbye|farewell} {noobs|n3wbz|n00blets}}"
I'd prefer a math/statistics based solution over brute-force looping to get the answer if possible.
Thanks!
A:
Well, there are 3 x 2 x 3 = 18 combinations in your first example.
Your second example is 3 x 4 x 2 x 3 = 72 combinations.
I'm not entirely sure what you mean by {a|b}|{c|d} though, I'm assuming you mean pick one of either (a or b) or (c or d), which is 4 choices.
You might want to read up on combinations here or here.
Update: Yep, it's that simple. Your problem is exactly like counting the number of combinations of digits in a number. For example, if I want to find the number of combinations of an ATM PIN number (4 decimal digits), I have sets {0-9}, {0-9}, {0-9}, {0-9}. There are 10 possibilities for the first choice (= 10). For each of those numbers, there are 10 possibilities for the second choice (= 10 × 10). For each of those, there are 10 for the third (= 10 × 10 × 10) and 10 for the fourth (= 10 × 10 × 10 × 10 = 10,000). It should be intuitively clear that there are 10,000 possibilities for a 4 digit decimal number.
Your example uses sets of words instead of sets of digits, but the principle is the same. The number of combinations is the number of items in set 1 × number of items in set 2 × ... × number of items in set n, etc.
It gets more complicated when you start putting restrictions in, or are picking multiple items from the same set, etc.
A:
The problem breaks down to two simple sub-problems:
count how many combinations are within braces and separated within vbars, for each braces pair
multiply those numbers
So for 1 I'd go with a plain regular expression + looping approach:
import re
def docount(thestring):
x = re.compile(r'{([^}]}')
counts = [mo.group(0).count('|')+1 for mo in x.finditer(thestring)]
result = 1
for c in counts: result *= c
return result
I've embedded 2 as well since that's the most trivial part anyway (if you're keen on using reduce for such purposes, that's OK too in lieu of the last three lines, I guess;-).
|
Determining the number of possible combinations
|
I'm trying to figure out how many possible ways there are to combine various elements form this string.
"{Hello|Hi|Hey} {world|earth}{!|.|?}"
Where one item (separated by a pipe/|) is selected at random from each group ({}) and combined into a single string.
So the above "template" could produce:
Hello world.
Hi earth?
Hey world.
Hi world?
I'm guessing this is a type of permutation, but I want to make sure I'm getting this right.
It would be really nice if this worked with "n" nested items as well.
"{{Hello|Hi|Hey} {world|earth}|{Goodbye|farewell} {noobs|n3wbz|n00blets}}"
I'd prefer a math/statistics based solution over brute-force looping to get the answer if possible.
Thanks!
|
[
"Well, there are 3 x 2 x 3 = 18 combinations in your first example.\nYour second example is 3 x 4 x 2 x 3 = 72 combinations.\nI'm not entirely sure what you mean by {a|b}|{c|d} though, I'm assuming you mean pick one of either (a or b) or (c or d), which is 4 choices.\nYou might want to read up on combinations here or here.\n\nUpdate: Yep, it's that simple. Your problem is exactly like counting the number of combinations of digits in a number. For example, if I want to find the number of combinations of an ATM PIN number (4 decimal digits), I have sets {0-9}, {0-9}, {0-9}, {0-9}. There are 10 possibilities for the first choice (= 10). For each of those numbers, there are 10 possibilities for the second choice (= 10 × 10). For each of those, there are 10 for the third (= 10 × 10 × 10) and 10 for the fourth (= 10 × 10 × 10 × 10 = 10,000). It should be intuitively clear that there are 10,000 possibilities for a 4 digit decimal number.\nYour example uses sets of words instead of sets of digits, but the principle is the same. The number of combinations is the number of items in set 1 × number of items in set 2 × ... × number of items in set n, etc.\nIt gets more complicated when you start putting restrictions in, or are picking multiple items from the same set, etc.\n",
"The problem breaks down to two simple sub-problems:\n\ncount how many combinations are within braces and separated within vbars, for each braces pair\nmultiply those numbers\n\nSo for 1 I'd go with a plain regular expression + looping approach:\nimport re\n\ndef docount(thestring):\n x = re.compile(r'{([^}]}')\n counts = [mo.group(0).count('|')+1 for mo in x.finditer(thestring)]\n result = 1\n for c in counts: result *= c\n return result\n\nI've embedded 2 as well since that's the most trivial part anyway (if you're keen on using reduce for such purposes, that's OK too in lieu of the last three lines, I guess;-).\n"
] |
[
6,
0
] |
[] |
[] |
[
"combinatorics",
"math",
"python",
"statistics"
] |
stackoverflow_0001997614_combinatorics_math_python_statistics.txt
|
Q:
sharing objects between module in GAE
To share a state(e.g. user) between a module in django people sometime use thread local storage, but as google app engine follows CGI standard and keeps state of a request in os.environ , can I share objects between two modules just by setting it e.g.
mod1.my_data = {} and now any other module can get handle to my_data?
without worrying about other threads/requests sharing/overwriting it?
A:
Later requests that happen to be served on the same process (you can't control that) would access just the same mod1.my_data object (unless you take pains to reassign it as a fresh object at the start of each request, of course).
|
sharing objects between module in GAE
|
To share a state(e.g. user) between a module in django people sometime use thread local storage, but as google app engine follows CGI standard and keeps state of a request in os.environ , can I share objects between two modules just by setting it e.g.
mod1.my_data = {} and now any other module can get handle to my_data?
without worrying about other threads/requests sharing/overwriting it?
|
[
"Later requests that happen to be served on the same process (you can't control that) would access just the same mod1.my_data object (unless you take pains to reassign it as a fresh object at the start of each request, of course).\n"
] |
[
0
] |
[] |
[] |
[
"google_app_engine",
"python"
] |
stackoverflow_0001997663_google_app_engine_python.txt
|
Q:
how to start a thread when django runserver?
I want to start a thread when django project runserver successfully.
where can I put the create-thread-and-start code? Is there any hook for the django runserver?
A:
Why would you want to do that? runserver is for development only, it should never be used in production. And if you're running via Apache, it should manage threads/processes for you anyway.
A:
Agree with the above answer, you probably don't want to do this. Runserver should be used for development only. Once you deploy, you'll want to move to Apache/WSGI. On my dev machine (where I do use runserver), I usually throw it in a screen session, so it doesn't get in the way, but I can pull it back up if I need to see a traceback.
|
how to start a thread when django runserver?
|
I want to start a thread when django project runserver successfully.
where can I put the create-thread-and-start code? Is there any hook for the django runserver?
|
[
"Why would you want to do that? runserver is for development only, it should never be used in production. And if you're running via Apache, it should manage threads/processes for you anyway.\n",
"Agree with the above answer, you probably don't want to do this. Runserver should be used for development only. Once you deploy, you'll want to move to Apache/WSGI. On my dev machine (where I do use runserver), I usually throw it in a screen session, so it doesn't get in the way, but I can pull it back up if I need to see a traceback.\n"
] |
[
7,
0
] |
[] |
[] |
[
"django",
"multithreading",
"python"
] |
stackoverflow_0001994507_django_multithreading_python.txt
|
Q:
what is the 'decimal.getcontext().copy()' mean
import decimal # Decimals
a=decimal.getcontext().copy()
print a
what is the useful of a.
A:
I am answering assuming a novice.
"a" is a variable. Variable is a logical unit that keeps a value/string etc on computer's memory while executing a program. As an example if you are going to add 1 and 2 and get the answer, you should create a "variable" in memory say "a" and assign the value of 1 + 2 for "a"
In this code you have imported a library called decimal. It contains set of operations or methods. Then you perform some operations on it and assign the output to a variable called "a". Then you are trying to print it to console.
N.B : You should not use variable names like a,b. It is not a good practice. You should use a meaningful word.
A:
While I agree with many of the other comments here I figured I'd throw a bone.
The decimal module is a utility for doing arithmetic on numbers of arbitrary precision. This is used in some scientific contexts to do calculations on things that suffer from round-off errors. The classical example would be calculting the 9999th digit of pi. You just can't do that with floats.
The decimal library uses the concept of a "context" to decide how much precision you really want. Since the more precision you want the slower the calculations will run. The decimal.getcontext() part returns the default context. But through a crazy "gotcha" (that I've actually fallen prey to) this is actually just a pointer. So if you were to change the context with a decimal.setcontext('foo') you would actually change a as well. Handily the module has a .copy() method.
The original programmer probably did this to save a copy of the context for later use. Perhaps s/he wanted to perform a part of the computation at a lower precision to save time and then wanted to perform the difficult part at a higher precision.
Although in python > 2.5 this is best done with a context manager like 'with'
from decimal import localcontext
with localcontext() as ctx:
ctx.prec -= 5 # Perform a low precision calculation
s = calculate_something()
s = +s # Round the final result back to the default precision
But without the rest of the relevant code my guess is no better than yours.
While I have worked with the decimal module before all of this is easily found in the python docs here. Try to go there and poke around first for questions like this ... if you can figure it out yourself you'll remember it longer. And you'll get that warm feeling in your head that the rest of us feel when we answer questions.
A:
a is the name of a variable, you could just as easily have put
import decimal # Decimals
print decimal.getcontext().copy()
To remove the reference to a
A:
I think the answer is that in this particular case, a serves no purpose
However in the larger scheme of things, if you need to use the value of
a=decimal.getcontext().copy()
again, then you don't want to recompute it, because either the function may change or it may be an expensive operation.
|
what is the 'decimal.getcontext().copy()' mean
|
import decimal # Decimals
a=decimal.getcontext().copy()
print a
what is the useful of a.
|
[
"I am answering assuming a novice.\n\"a\" is a variable. Variable is a logical unit that keeps a value/string etc on computer's memory while executing a program. As an example if you are going to add 1 and 2 and get the answer, you should create a \"variable\" in memory say \"a\" and assign the value of 1 + 2 for \"a\"\nIn this code you have imported a library called decimal. It contains set of operations or methods. Then you perform some operations on it and assign the output to a variable called \"a\". Then you are trying to print it to console.\nN.B : You should not use variable names like a,b. It is not a good practice. You should use a meaningful word.\n",
"While I agree with many of the other comments here I figured I'd throw a bone.\nThe decimal module is a utility for doing arithmetic on numbers of arbitrary precision. This is used in some scientific contexts to do calculations on things that suffer from round-off errors. The classical example would be calculting the 9999th digit of pi. You just can't do that with floats.\nThe decimal library uses the concept of a \"context\" to decide how much precision you really want. Since the more precision you want the slower the calculations will run. The decimal.getcontext() part returns the default context. But through a crazy \"gotcha\" (that I've actually fallen prey to) this is actually just a pointer. So if you were to change the context with a decimal.setcontext('foo') you would actually change a as well. Handily the module has a .copy() method.\nThe original programmer probably did this to save a copy of the context for later use. Perhaps s/he wanted to perform a part of the computation at a lower precision to save time and then wanted to perform the difficult part at a higher precision.\nAlthough in python > 2.5 this is best done with a context manager like 'with'\nfrom decimal import localcontext\n\nwith localcontext() as ctx:\n ctx.prec -= 5 # Perform a low precision calculation\n s = calculate_something()\ns = +s # Round the final result back to the default precision\n\nBut without the rest of the relevant code my guess is no better than yours.\nWhile I have worked with the decimal module before all of this is easily found in the python docs here. Try to go there and poke around first for questions like this ... if you can figure it out yourself you'll remember it longer. And you'll get that warm feeling in your head that the rest of us feel when we answer questions.\n",
"a is the name of a variable, you could just as easily have put \nimport decimal # Decimals\nprint decimal.getcontext().copy()\n\nTo remove the reference to a\n",
"I think the answer is that in this particular case, a serves no purpose\nHowever in the larger scheme of things, if you need to use the value of \na=decimal.getcontext().copy()\n\nagain, then you don't want to recompute it, because either the function may change or it may be an expensive operation.\n"
] |
[
7,
5,
3,
1
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001997795_python.txt
|
Q:
How to query a contact for its PubSub using Python's xmpp?
I'm writing a XMPP bot in Python (using xmpppy). I want (after user's request) check his PubSub status (mood, tune) and do something with it. How do I do that?
I know how to parse a stanza send by user when he changes status but I don't know how to force him to send me such stanza.
A:
Read XEP-163. Essentially, you need to implement the send-side of entity caps (XEP-115), so that you send your presence like this:
<presence from='romeo@example.net/home'>
<c xmlns='http://jabber.org/protocol/caps'
hash='sha-1'
node='http://example.com/MYBOT'
ver='/FpawanrJ31ymsv4ApCMGcyJmUk='/>
</presence>
When you get get a disco#info request like this:
<iq to='romeo@example.net/home'
id='disco1'
from='example.net'
type='get'>
<query xmlns='http://jabber.org/protocol/disco#info'
node='http://example.com/MYBOT#/FpawanrJ31ymsv4ApCMGcyJmUk='/>
</iq>
You respond with the list of features you implement:
<iq from='romeo@example.net/home'
id='disco1'
to='example.net'
type='result'>
<query xmlns='http://jabber.org/protocol/disco#info'
node='http://example.com/MYBOT#/FpawanrJ31ymsv4ApCMGcyJmUk='>
<identity category='client' type='bot' name='MYBOT'/>
<feature var='http://jabber.org/protocol/mood+notify'/>
<feature var='http://jabber.org/protocol/tune+notify'/>
</query>
</iq>
Add a +notify to each node name that you want to implicitly subscribe to, and add the resulting string as a feature, as above. Ensuring that the SHA-1 hash in your outbound presence is correct is the only hard part.
|
How to query a contact for its PubSub using Python's xmpp?
|
I'm writing a XMPP bot in Python (using xmpppy). I want (after user's request) check his PubSub status (mood, tune) and do something with it. How do I do that?
I know how to parse a stanza send by user when he changes status but I don't know how to force him to send me such stanza.
|
[
"Read XEP-163. Essentially, you need to implement the send-side of entity caps (XEP-115), so that you send your presence like this:\n<presence from='romeo@example.net/home'>\n <c xmlns='http://jabber.org/protocol/caps' \n hash='sha-1'\n node='http://example.com/MYBOT'\n ver='/FpawanrJ31ymsv4ApCMGcyJmUk='/>\n</presence>\n\nWhen you get get a disco#info request like this:\n<iq to='romeo@example.net/home'\n id='disco1'\n from='example.net' \n type='get'>\n <query xmlns='http://jabber.org/protocol/disco#info'\n node='http://example.com/MYBOT#/FpawanrJ31ymsv4ApCMGcyJmUk='/>\n</iq>\n\nYou respond with the list of features you implement:\n<iq from='romeo@example.net/home'\n id='disco1'\n to='example.net' \n type='result'>\n <query xmlns='http://jabber.org/protocol/disco#info'\n node='http://example.com/MYBOT#/FpawanrJ31ymsv4ApCMGcyJmUk='>\n <identity category='client' type='bot' name='MYBOT'/>\n <feature var='http://jabber.org/protocol/mood+notify'/>\n <feature var='http://jabber.org/protocol/tune+notify'/>\n </query>\n</iq>\n\nAdd a +notify to each node name that you want to implicitly subscribe to, and add the resulting string as a feature, as above. Ensuring that the SHA-1 hash in your outbound presence is correct is the only hard part. \n"
] |
[
3
] |
[] |
[] |
[
"bots",
"python",
"xmpp"
] |
stackoverflow_0001986169_bots_python_xmpp.txt
|
Q:
Datetime problem at start of month in Python
I have a function that removes a file after a certain amount of time. The problem is that it works at later parts of the month, but when I try and remove 7 days from the start of the month it will not substract into the previous month. Does anyone know how to get this to work? The code is below that works out the date and removes the days.
today = datetime.date.today() # Today's date Binary
todaystr = datetime.date.today().isoformat() # Todays date as a string
minus_seven = today.replace(day=today.day-7).isoformat() # Removes 7 days
Thanks for any help.
A:
minus_seven = today - datetime.timedelta(days = 7)
A:
The reason this breaks is that today is a datetime.date; and as the docs say, that means that today.day is:
Between 1 and the number of days in the given month of the given year.
You can see why this works later in the month; but for the first few days of the month you end up with a negative value.
The docs immediately go on to document the correct way to do what you're trying to do:
date2 = date1 - timedelta Computes date2 such that date2 + timedelta == date1.
|
Datetime problem at start of month in Python
|
I have a function that removes a file after a certain amount of time. The problem is that it works at later parts of the month, but when I try and remove 7 days from the start of the month it will not substract into the previous month. Does anyone know how to get this to work? The code is below that works out the date and removes the days.
today = datetime.date.today() # Today's date Binary
todaystr = datetime.date.today().isoformat() # Todays date as a string
minus_seven = today.replace(day=today.day-7).isoformat() # Removes 7 days
Thanks for any help.
|
[
"minus_seven = today - datetime.timedelta(days = 7)\n\n",
"The reason this breaks is that today is a datetime.date; and as the docs say, that means that today.day is:\n\nBetween 1 and the number of days in the given month of the given year.\n\nYou can see why this works later in the month; but for the first few days of the month you end up with a negative value.\nThe docs immediately go on to document the correct way to do what you're trying to do:\n\ndate2 = date1 - timedelta Computes date2 such that date2 + timedelta == date1.\n\n"
] |
[
7,
3
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001998198_python.txt
|
Q:
Python's Regular Expression Source String Length
In Python Regular Expressions,
re.compile("x"*50000)
gives me OverflowError: regular expression code size limit exceeded
but following one does not get any error, but it hits 100% CPU, and took 1 minute in my PC
>>> re.compile(".*?.*?.*?.*?.*?.*?.*?.*?.*?.*?"*50000)
<_sre.SRE_Pattern object at 0x03FB0020>
Is that normal?
Should I assume, ".*?.*?.*?.*?.*?.*?.*?.*?.*?.*?"*50000 is shorter than "x"*50000?
Tested on Python 2.6, Win32
UPDATE 1:
It Looks like ".*?.*?.*?.*?.*?.*?.*?.*?.*?.*?"*50000 could be reduce to .*?
So, how about this one?
re.compile(".*?x"*50000)
It does compile, and if that one also can reduce to ".*?x", it should match to string "abcx" or "x" alone, but it does not match.
So, Am I missing something?
UPDATE 2:
My Point is not to know max limit of regex source strings, I like to know some reasons/concepts of "x"*50000 caught by overflow handler, but not on ".*?x"*50000.
It does not make sense for me, thats why.
It is something missing on overflow checking or Its just fine or its really overflowing something?
Any Hints/Opinions will be appreciated.
A:
The difference is that ".*?.*?.*?.*?.*?.*?.*?.*?.*?.*?"*50000 can be reduced to ".*?", while "x"*50000 has to generate 50000 nodes in the FSM (or a similar structure used by the regex engine).
EDIT: Ok, I was wrong. It's not that smart. The reason why "x"*50000 fails, but ".*?x"*50000 doesn't is that there is a limit on size of one "code item". "x"*50000 will generate one long item and ".*?x"*50000 will generate many small items. If you could split the string literal somehow without changing the meaning of the regex, it would work, but I can't think of a way to do that.
A:
you want to match 50000 "x"s , correct??? if so, an alternative without regex
if "x"*50000 in mystring:
print "found"
if you want to match 50000 "x"s using regex, you can use range
>>> pat=re.compile("x{50000}")
>>> pat.search(s)
<_sre.SRE_Match object at 0xb8057a30>
on my system it will take in length of 65535 max
>>> pat=re.compile("x{65536}")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.6/re.py", line 188, in compile
return _compile(pattern, flags)
File "/usr/lib/python2.6/re.py", line 241, in _compile
p = sre_compile.compile(pattern, flags)
File "/usr/lib/python2.6/sre_compile.py", line 529, in compile
groupindex, indexgroup
RuntimeError: invalid SRE code
>>> pat=re.compile("x{65535}")
>>>
I don't know if there are tweaks in Python we can use to increase that limit though.
|
Python's Regular Expression Source String Length
|
In Python Regular Expressions,
re.compile("x"*50000)
gives me OverflowError: regular expression code size limit exceeded
but following one does not get any error, but it hits 100% CPU, and took 1 minute in my PC
>>> re.compile(".*?.*?.*?.*?.*?.*?.*?.*?.*?.*?"*50000)
<_sre.SRE_Pattern object at 0x03FB0020>
Is that normal?
Should I assume, ".*?.*?.*?.*?.*?.*?.*?.*?.*?.*?"*50000 is shorter than "x"*50000?
Tested on Python 2.6, Win32
UPDATE 1:
It Looks like ".*?.*?.*?.*?.*?.*?.*?.*?.*?.*?"*50000 could be reduce to .*?
So, how about this one?
re.compile(".*?x"*50000)
It does compile, and if that one also can reduce to ".*?x", it should match to string "abcx" or "x" alone, but it does not match.
So, Am I missing something?
UPDATE 2:
My Point is not to know max limit of regex source strings, I like to know some reasons/concepts of "x"*50000 caught by overflow handler, but not on ".*?x"*50000.
It does not make sense for me, thats why.
It is something missing on overflow checking or Its just fine or its really overflowing something?
Any Hints/Opinions will be appreciated.
|
[
"The difference is that \".*?.*?.*?.*?.*?.*?.*?.*?.*?.*?\"*50000 can be reduced to \".*?\", while \"x\"*50000 has to generate 50000 nodes in the FSM (or a similar structure used by the regex engine).\nEDIT: Ok, I was wrong. It's not that smart. The reason why \"x\"*50000 fails, but \".*?x\"*50000 doesn't is that there is a limit on size of one \"code item\". \"x\"*50000 will generate one long item and \".*?x\"*50000 will generate many small items. If you could split the string literal somehow without changing the meaning of the regex, it would work, but I can't think of a way to do that.\n",
"you want to match 50000 \"x\"s , correct??? if so, an alternative without regex\nif \"x\"*50000 in mystring:\n print \"found\"\n\nif you want to match 50000 \"x\"s using regex, you can use range\n>>> pat=re.compile(\"x{50000}\")\n>>> pat.search(s)\n<_sre.SRE_Match object at 0xb8057a30>\n\non my system it will take in length of 65535 max\n>>> pat=re.compile(\"x{65536}\")\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\n File \"/usr/lib/python2.6/re.py\", line 188, in compile\n return _compile(pattern, flags)\n File \"/usr/lib/python2.6/re.py\", line 241, in _compile\n p = sre_compile.compile(pattern, flags)\n File \"/usr/lib/python2.6/sre_compile.py\", line 529, in compile\n groupindex, indexgroup\nRuntimeError: invalid SRE code\n>>> pat=re.compile(\"x{65535}\")\n>>>\n\nI don't know if there are tweaks in Python we can use to increase that limit though.\n"
] |
[
6,
1
] |
[] |
[] |
[
"python",
"regex"
] |
stackoverflow_0001998261_python_regex.txt
|
Q:
Replace string in a specific line using python
I'm writing a python script to replace strings from a each text file in a directory with a specific extension (.seq). The strings replaced should only be from the second line of each file, and the output is a new subdirectory (call it clean) with the same file names as the original files, but with a *.clean suffix. The output file contains exactly the same text as the original, but with the strings replaced. I need to replace all these strings: 'K','Y','W','M','R','S' with 'N'.
This is what I've come up with after googling. It's very messy (2nd week of programming), and it stops at copying the files into the clean directory without replacing anything. I'd really appreciate any help.
Thanks before!
import os, shutil
os.mkdir('clean')
for file in os.listdir(os.getcwd()):
if file.find('.seq') != -1:
shutil.copy(file, 'clean')
os.chdir('clean')
for subdir, dirs, files in os.walk(os.getcwd()):
for file in files:
f = open(file, 'r')
for line in f.read():
if line.__contains__('>'): #indicator for the first line. the first line always starts with '>'. It's a FASTA file, if you've worked with dna/protein before.
pass
else:
line.replace('M', 'N')
line.replace('K', 'N')
line.replace('Y', 'N')
line.replace('W', 'N')
line.replace('R', 'N')
line.replace('S', 'N')
A:
some notes:
string.replace and re.sub are not in-place so you should be assigning the return value back to your variable.
glob.glob is better for finding files in a directory matching a defined pattern...
maybe you should be checking if the directory already exists before creating it (I just assumed this, this could not be your desired behavior)
the with statement takes care of closing the file in a safe way. if you don't want to use it you have to use try finally.
in your example you where forgetting to put the sufix *.clean ;)
you where not actually writing the files, you could do it like i did in my example or use fileinput module (which until today i did not know)
here's my example:
import re
import os
import glob
source_dir=os.getcwd()
target_dir="clean"
source_files = [fname for fname in glob.glob(os.path.join(source_dir,"*.seq"))]
# check if target directory exists... if not, create it.
if not os.path.exists(target_dir):
os.makedirs(target_dir)
for source_file in source_files:
target_file = os.path.join(target_dir,os.path.basename(source_file)+".clean")
with open(source_file,'r') as sfile:
with open(target_file,'w') as tfile:
lines = sfile.readlines()
# do the replacement in the second line.
# (remember that arrays are zero indexed)
lines[1]=re.sub("K|Y|W|M|R|S",'N',lines[1])
tfile.writelines(lines)
print "DONE"
hope it helps.
A:
You should replace line.replace('M', 'N') with line=line.replace('M', 'N'). replace returns a copy of the original string with the relevant substrings replaced.
An even better way (IMO) is to use re.
import re
line="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
line=re.sub("K|Y|W|M|R|S",'N',line)
print line
A:
Here are some general hints:
Don't use find for checking the file extension (e.g., this would also match "file1.seqdata.xls"). At least use file.endswith('seq'), or, better yet, os.path.splitext(file)[1]
Actually, don't do that altogether. This is what you want:
import glob
seq_files = glob.glob("*.seq")
Don't copy the files, it's much easier to use just one loop:
for filename in seq_files:
in_file = open(filename)
out_file = open(os.path.join("clean", filename), "w")
# now read lines from in_file and write lines to out_file
Don't use line.__contains__('>'). What you mean is
if '>' in line:
(which will call __contains__ internally). But actually, you want to know wether the line starts with a `">", not if there's one somewhere within the line, be it at the beginning or not. So the better way would be this:
if line.startswith(">"):
I'm not familiar with your file type; if the ">" check really is just for determining the first line, there's better ways to do that.
You don't need the if block (you just pass). It's cleaner to write
if not something:
do_things()
other_stuff()
instead of
if something:
pass
else:
do_things()
other_stuff()
Have fun learning Python!
A:
you need to allocate the result of the replacement back to "line" variable
line=line.replace('M', 'N')
you can also use the module fileinput for inplace edit
import os, shutil,fileinput
if not os.path.exists('clean'):
os.mkdir('clean')
for file in os.listdir("."):
if file.endswith(".seq"):
shutil.copy(file, 'clean')
os.chdir('clean')
for subdir, dirs, files in os.walk("."):
for file in files:
f = fileinput.FileInput(file,inplace=0)
for n,line in enumerate(f):
if line.lstrip().startswith('>'):
pass
elif n==1: #replace 2nd line
for repl in ["M","K","Y","W","R","S"]:
line=line.replace(ch, 'N')
print line.rstrip()
f.close()
change inplace=0 to inplace=1 for in place editing of your files.
A:
line.replace is not a mutator, it leaves the original string unchanged and returns a new string with the replacements made. You'll need to change your code to line = line.replace('R', 'N'), etc.
I think you also want to add a break statement at the end of your else clause, so that you don't iterate over the entire file, but stop after having processed line 2.
Lastly, you'll need to actually write the file out containing your changes. So far, you are just reading the file and updating the line in your program variable 'line'. You need to actually create an output file as well, to which you will write the modified lines.
|
Replace string in a specific line using python
|
I'm writing a python script to replace strings from a each text file in a directory with a specific extension (.seq). The strings replaced should only be from the second line of each file, and the output is a new subdirectory (call it clean) with the same file names as the original files, but with a *.clean suffix. The output file contains exactly the same text as the original, but with the strings replaced. I need to replace all these strings: 'K','Y','W','M','R','S' with 'N'.
This is what I've come up with after googling. It's very messy (2nd week of programming), and it stops at copying the files into the clean directory without replacing anything. I'd really appreciate any help.
Thanks before!
import os, shutil
os.mkdir('clean')
for file in os.listdir(os.getcwd()):
if file.find('.seq') != -1:
shutil.copy(file, 'clean')
os.chdir('clean')
for subdir, dirs, files in os.walk(os.getcwd()):
for file in files:
f = open(file, 'r')
for line in f.read():
if line.__contains__('>'): #indicator for the first line. the first line always starts with '>'. It's a FASTA file, if you've worked with dna/protein before.
pass
else:
line.replace('M', 'N')
line.replace('K', 'N')
line.replace('Y', 'N')
line.replace('W', 'N')
line.replace('R', 'N')
line.replace('S', 'N')
|
[
"some notes: \n\nstring.replace and re.sub are not in-place so you should be assigning the return value back to your variable.\nglob.glob is better for finding files in a directory matching a defined pattern...\nmaybe you should be checking if the directory already exists before creating it (I just assumed this, this could not be your desired behavior)\nthe with statement takes care of closing the file in a safe way. if you don't want to use it you have to use try finally.\nin your example you where forgetting to put the sufix *.clean ;)\nyou where not actually writing the files, you could do it like i did in my example or use fileinput module (which until today i did not know)\n\nhere's my example:\nimport re\nimport os\nimport glob\n\nsource_dir=os.getcwd()\ntarget_dir=\"clean\"\nsource_files = [fname for fname in glob.glob(os.path.join(source_dir,\"*.seq\"))]\n\n# check if target directory exists... if not, create it.\nif not os.path.exists(target_dir):\n os.makedirs(target_dir)\n\nfor source_file in source_files:\n target_file = os.path.join(target_dir,os.path.basename(source_file)+\".clean\")\n with open(source_file,'r') as sfile:\n with open(target_file,'w') as tfile:\n lines = sfile.readlines()\n # do the replacement in the second line.\n # (remember that arrays are zero indexed)\n lines[1]=re.sub(\"K|Y|W|M|R|S\",'N',lines[1])\n tfile.writelines(lines)\n\nprint \"DONE\"\n\nhope it helps.\n",
"You should replace line.replace('M', 'N') with line=line.replace('M', 'N'). replace returns a copy of the original string with the relevant substrings replaced.\nAn even better way (IMO) is to use re.\nimport re\n\nline=\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\nline=re.sub(\"K|Y|W|M|R|S\",'N',line)\nprint line \n\n",
"Here are some general hints:\n\nDon't use find for checking the file extension (e.g., this would also match \"file1.seqdata.xls\"). At least use file.endswith('seq'), or, better yet, os.path.splitext(file)[1]\nActually, don't do that altogether. This is what you want:\nimport glob\nseq_files = glob.glob(\"*.seq\")\n\nDon't copy the files, it's much easier to use just one loop:\nfor filename in seq_files:\n in_file = open(filename)\n out_file = open(os.path.join(\"clean\", filename), \"w\")\n # now read lines from in_file and write lines to out_file\n\nDon't use line.__contains__('>'). What you mean is\nif '>' in line:\n\n(which will call __contains__ internally). But actually, you want to know wether the line starts with a `\">\", not if there's one somewhere within the line, be it at the beginning or not. So the better way would be this:\nif line.startswith(\">\"):\n\nI'm not familiar with your file type; if the \">\" check really is just for determining the first line, there's better ways to do that.\nYou don't need the if block (you just pass). It's cleaner to write\nif not something:\n do_things()\nother_stuff()\n\ninstead of \nif something:\n pass\nelse:\n do_things()\nother_stuff()\n\n\nHave fun learning Python!\n",
"you need to allocate the result of the replacement back to \"line\" variable\nline=line.replace('M', 'N')\n\nyou can also use the module fileinput for inplace edit\nimport os, shutil,fileinput\nif not os.path.exists('clean'):\n os.mkdir('clean')\n\nfor file in os.listdir(\".\"):\n if file.endswith(\".seq\"):\n shutil.copy(file, 'clean')\n\nos.chdir('clean')\n\nfor subdir, dirs, files in os.walk(\".\"):\n for file in files:\n f = fileinput.FileInput(file,inplace=0)\n for n,line in enumerate(f):\n if line.lstrip().startswith('>'):\n pass\n elif n==1: #replace 2nd line\n for repl in [\"M\",\"K\",\"Y\",\"W\",\"R\",\"S\"]:\n line=line.replace(ch, 'N')\n print line.rstrip()\n f.close()\n\nchange inplace=0 to inplace=1 for in place editing of your files.\n",
"line.replace is not a mutator, it leaves the original string unchanged and returns a new string with the replacements made. You'll need to change your code to line = line.replace('R', 'N'), etc.\nI think you also want to add a break statement at the end of your else clause, so that you don't iterate over the entire file, but stop after having processed line 2.\nLastly, you'll need to actually write the file out containing your changes. So far, you are just reading the file and updating the line in your program variable 'line'. You need to actually create an output file as well, to which you will write the modified lines.\n"
] |
[
9,
5,
5,
4,
0
] |
[] |
[] |
[
"python",
"replace"
] |
stackoverflow_0001998233_python_replace.txt
|
Q:
Wrong encoding of text, in Django?
"query" = джазовыми
For some reason...when I display it via:
{{ query|safe }}
I get this:
%u0434%u0436%u0430%u0437%u043E%u0432%u044B%u043C%u0438
A:
Would the query be set from the source, this would solve it:
query = u"джазовыми"
(provided that for example your file encoding is utf-8 and you have corresponding line
# -*- coding: UTF-8 -*-
in the beginning)
But I guess the query is entered by user. The error seems to be located in that part of your code. Can you quote how it is done?
|
Wrong encoding of text, in Django?
|
"query" = джазовыми
For some reason...when I display it via:
{{ query|safe }}
I get this:
%u0434%u0436%u0430%u0437%u043E%u0432%u044B%u043C%u0438
|
[
"Would the query be set from the source, this would solve it:\nquery = u\"джазовыми\"\n\n(provided that for example your file encoding is utf-8 and you have corresponding line\n# -*- coding: UTF-8 -*-\n\nin the beginning)\nBut I guess the query is entered by user. The error seems to be located in that part of your code. Can you quote how it is done?\n"
] |
[
2
] |
[] |
[] |
[
"django",
"encoding",
"python",
"templates",
"utf_8"
] |
stackoverflow_0001998362_django_encoding_python_templates_utf_8.txt
|
Q:
Is it safe to use user input for Python's regular expressions?
I would like to let my users use regular expressions for some features. I'm curious what the implications are of passing user input to re.compile(). I assume there is no way for a user to give me a string that could let them execute arbitrary code. The dangers I have thought of are:
The user could pass input that raises an exception.
The user could pass input that causes the regex engine to take a long time, or to use a lot of memory.
The solution to 1. is easy: catch exceptions. I'm not sure if there is a good solution to 2. Perhaps just limiting the length of the regex would work.
Is there anything else I need to worry about?
A:
I have worked on a program that allows users to enter their own regex and you are right - they can (and do) enter regex that can take a long time to finish - sometimes longer than than the lifetime of the universe. What is worse, while processing a regex Python holds the GIL, so it will not only hang the thread that is running the regex, but the entire program.
Limiting the length of the regex will not work, since the problem is backtracking. For example, matching the regex r"(\S+)+x" on a string of length N that does not contain an "x" will backtrack 2**N times. On my system this takes about a second to match against "a"*21 and the time doubles for each additional character, so a string of 100 characters would take approximately 19167393131891000 years to complete (this is an estimate, I have not timed it).
For more information read the O'Reilly book "Mastering Regular Expressions" - this has a couple of chapters on performance.
edit
To get round this we wrote a regex analysing function that tried to catch and reject some of the more obvious degenerate cases, but it is impossible to get all of them.
Another thing we looked at was patching the re module to raise an exception if it backtracks too many times. This is possible, but requires changing the Python C source and recompiling, so is not portable. We also submitted a patch to release the GIL when matching against python strings, but I don't think it was accepted into the core (python only holds the GIL because regex can be run against mutable buffers).
A:
It's much simpler for casual users to give them a subset language. The shell's globbing rules in fnmatch, for example. The SQL LIKE condition rules are another example.
Translate the user's language into a proper regex for execution at runtime.
A:
Compiling the regular expression should be reasonably safe. Although what it compiles into is not strictly an NFA (backreferences mean it's not quite as clean) it should still be sort of straightforward to compile into.
Now as to performance characteristics, this is another problem entirely. Even a small regular expression can have exponential time characteristics because of backtracking. It might be better to define a certain subset of features and only support very limited expressions that you translate yourself.
If you really want to support general regular expressions you either have to trust your users (sometimes an option) or limit the amount of space and time used. I believe that space used is determined only by the length of the regular expression.
edit: As Dave notes, apparently the global interpreter lock is held during regex matching, which would make setting that timeout harder. If that is the case, your only option to set a timeout is to run the match in a separate process. While not exactly ideal it is doable. I completely forgot about multiprocessing. Point of interest is this section on sharing objects. If you really need the hard constraints, separate processes are the way to go here.
A:
It's not necessary to use compile() except when you need to reuse a lot of different regular expressions. The module already caches the last expressions.
The point 2 (at execution) could be a very difficult one if you allow the user to input any regular expression. You can make a complex regexp with few characters, like the famous (x+x+)+y one. I think it's a problem yet to be resolved in a general way.
A workaround could be launching a different thread and monitor it, if it exceeds the allowed time, kill the thread and return with an error.
A:
I really don't think it is possible to execute code simply by passing it into an re.compile. The way I understand it, re.compile (or any regex system in any language) converts the regex string into a finite automaton (DFA or NFA), and despite the ominous name 'compile' it has nothing to do with the execution of any code.
A:
You technically don't need to use re.compile() to perform a regular expression operation on a string. In fact, the compile method can often be slower if you're only executing the operation once since there's overhead associated with the initial compiling.
If you're worried about the word "compile" then avoid it all together and simply pass the raw expression to match, search, etc. You may wind up improving the performance of your code slightly anyways.
|
Is it safe to use user input for Python's regular expressions?
|
I would like to let my users use regular expressions for some features. I'm curious what the implications are of passing user input to re.compile(). I assume there is no way for a user to give me a string that could let them execute arbitrary code. The dangers I have thought of are:
The user could pass input that raises an exception.
The user could pass input that causes the regex engine to take a long time, or to use a lot of memory.
The solution to 1. is easy: catch exceptions. I'm not sure if there is a good solution to 2. Perhaps just limiting the length of the regex would work.
Is there anything else I need to worry about?
|
[
"I have worked on a program that allows users to enter their own regex and you are right - they can (and do) enter regex that can take a long time to finish - sometimes longer than than the lifetime of the universe. What is worse, while processing a regex Python holds the GIL, so it will not only hang the thread that is running the regex, but the entire program.\nLimiting the length of the regex will not work, since the problem is backtracking. For example, matching the regex r\"(\\S+)+x\" on a string of length N that does not contain an \"x\" will backtrack 2**N times. On my system this takes about a second to match against \"a\"*21 and the time doubles for each additional character, so a string of 100 characters would take approximately 19167393131891000 years to complete (this is an estimate, I have not timed it).\nFor more information read the O'Reilly book \"Mastering Regular Expressions\" - this has a couple of chapters on performance.\nedit\nTo get round this we wrote a regex analysing function that tried to catch and reject some of the more obvious degenerate cases, but it is impossible to get all of them. \nAnother thing we looked at was patching the re module to raise an exception if it backtracks too many times. This is possible, but requires changing the Python C source and recompiling, so is not portable. We also submitted a patch to release the GIL when matching against python strings, but I don't think it was accepted into the core (python only holds the GIL because regex can be run against mutable buffers).\n",
"It's much simpler for casual users to give them a subset language. The shell's globbing rules in fnmatch, for example. The SQL LIKE condition rules are another example.\nTranslate the user's language into a proper regex for execution at runtime.\n",
"Compiling the regular expression should be reasonably safe. Although what it compiles into is not strictly an NFA (backreferences mean it's not quite as clean) it should still be sort of straightforward to compile into.\nNow as to performance characteristics, this is another problem entirely. Even a small regular expression can have exponential time characteristics because of backtracking. It might be better to define a certain subset of features and only support very limited expressions that you translate yourself. \nIf you really want to support general regular expressions you either have to trust your users (sometimes an option) or limit the amount of space and time used. I believe that space used is determined only by the length of the regular expression. \nedit: As Dave notes, apparently the global interpreter lock is held during regex matching, which would make setting that timeout harder. If that is the case, your only option to set a timeout is to run the match in a separate process. While not exactly ideal it is doable. I completely forgot about multiprocessing. Point of interest is this section on sharing objects. If you really need the hard constraints, separate processes are the way to go here.\n",
"It's not necessary to use compile() except when you need to reuse a lot of different regular expressions. The module already caches the last expressions.\nThe point 2 (at execution) could be a very difficult one if you allow the user to input any regular expression. You can make a complex regexp with few characters, like the famous (x+x+)+y one. I think it's a problem yet to be resolved in a general way. \nA workaround could be launching a different thread and monitor it, if it exceeds the allowed time, kill the thread and return with an error.\n",
"I really don't think it is possible to execute code simply by passing it into an re.compile. The way I understand it, re.compile (or any regex system in any language) converts the regex string into a finite automaton (DFA or NFA), and despite the ominous name 'compile' it has nothing to do with the execution of any code. \n",
"You technically don't need to use re.compile() to perform a regular expression operation on a string. In fact, the compile method can often be slower if you're only executing the operation once since there's overhead associated with the initial compiling.\nIf you're worried about the word \"compile\" then avoid it all together and simply pass the raw expression to match, search, etc. You may wind up improving the performance of your code slightly anyways.\n"
] |
[
22,
6,
4,
1,
0,
0
] |
[] |
[] |
[
"python",
"regex",
"sanitize",
"user_input"
] |
stackoverflow_0001998104_python_regex_sanitize_user_input.txt
|
Q:
Parsing XML with SAX/Python + no validation
I am new to python and I'm trying to parse a XML file with SAX without validating it.
The head of my xml file is:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE n:document SYSTEM "schema.dtd">
<n:document....
and I've tried to parse it with python 2.5.2:
from xml.sax import make_parser, handler
import sys
parser = make_parser()
parser.setFeature(handler.feature_namespaces,True)
parser.setFeature(handler.feature_validation,False)
parser.setContentHandler(handler.ContentHandler())
parser.parse(sys.argv[1])
but I got an error:
python doc.py document.xml
(...)
File "/usr/lib/python2.5/urllib2.py", line 244, in get_type
raise ValueError, "unknown url type: %s" % self.__original
ValueError: unknown url type: schema.dtd
I don't want the SAX parser to look for a schema. Where am I wrong ?
Thanks !
A:
expatreader considers the DTD external subset as an external general entity. So the feature you want is:
parser.setFeature(handler.feature_external_ges, False)
However, it's a bit dodgy pointing the DTD external subset to a non-existant URL; as this shows, it's not only validating parsers that read it.
|
Parsing XML with SAX/Python + no validation
|
I am new to python and I'm trying to parse a XML file with SAX without validating it.
The head of my xml file is:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE n:document SYSTEM "schema.dtd">
<n:document....
and I've tried to parse it with python 2.5.2:
from xml.sax import make_parser, handler
import sys
parser = make_parser()
parser.setFeature(handler.feature_namespaces,True)
parser.setFeature(handler.feature_validation,False)
parser.setContentHandler(handler.ContentHandler())
parser.parse(sys.argv[1])
but I got an error:
python doc.py document.xml
(...)
File "/usr/lib/python2.5/urllib2.py", line 244, in get_type
raise ValueError, "unknown url type: %s" % self.__original
ValueError: unknown url type: schema.dtd
I don't want the SAX parser to look for a schema. Where am I wrong ?
Thanks !
|
[
"expatreader considers the DTD external subset as an external general entity. So the feature you want is:\nparser.setFeature(handler.feature_external_ges, False)\n\nHowever, it's a bit dodgy pointing the DTD external subset to a non-existant URL; as this shows, it's not only validating parsers that read it.\n"
] |
[
4
] |
[] |
[] |
[
"python",
"sax",
"validation",
"xml"
] |
stackoverflow_0001998425_python_sax_validation_xml.txt
|
Q:
How can I create a static variable in a Python class via the C API?
I want to do the equivalent of
class Foo(object):
bar = 1
using Python's C API. In other words, I want to create a Python class which has a static variable, using C.
How can I do this?
A:
Found it! It's just a matter of setting the tp_dict element of the type object and filling adding entries to it for each of the static variables. The following C code creates the same static variable as the Python code above:
PyTypeObject type;
// ...other initialisation...
type.tp_dict = PyDict_New();
PyDict_SetItemString(type.tp_dict, "bar", PyInt_FromLong(1));
A:
You can pass that source code to Py_CompileString with the appropriate flags.
If you already have the class you could use PyObject_SetAttr.
|
How can I create a static variable in a Python class via the C API?
|
I want to do the equivalent of
class Foo(object):
bar = 1
using Python's C API. In other words, I want to create a Python class which has a static variable, using C.
How can I do this?
|
[
"Found it! It's just a matter of setting the tp_dict element of the type object and filling adding entries to it for each of the static variables. The following C code creates the same static variable as the Python code above:\nPyTypeObject type;\n// ...other initialisation...\ntype.tp_dict = PyDict_New();\nPyDict_SetItemString(type.tp_dict, \"bar\", PyInt_FromLong(1));\n\n",
"You can pass that source code to Py_CompileString with the appropriate flags.\nIf you already have the class you could use PyObject_SetAttr.\n"
] |
[
5,
2
] |
[] |
[] |
[
"c",
"python"
] |
stackoverflow_0001952379_c_python.txt
|
Q:
How do i use Django and UTF-8 content-type for template?
When I do:
return render_to_response()
in Django. How do I set the content-type to UTF-8? So that everything displayed is UTF-8?
A:
django use UTF-8 as default encoding, but this can be modified with settings.DEFAULT_CHARSET.
Be sure, in your HTML template, to set UTF-8 for the HTML page also :
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
|
How do i use Django and UTF-8 content-type for template?
|
When I do:
return render_to_response()
in Django. How do I set the content-type to UTF-8? So that everything displayed is UTF-8?
|
[
"django use UTF-8 as default encoding, but this can be modified with settings.DEFAULT_CHARSET.\nBe sure, in your HTML template, to set UTF-8 for the HTML page also :\n<meta http-equiv=\"Content-type\" content=\"text/html; charset=utf-8\" /> \n\n"
] |
[
5
] |
[] |
[] |
[
"django",
"encoding",
"python",
"unicode",
"utf_8"
] |
stackoverflow_0001998987_django_encoding_python_unicode_utf_8.txt
|
Q:
Understanding while loop
I am a newbie in Python. I can understand what a for loop does, but can't really understand what a while loop does. I knew it does repeat something while the condition is true, easy to say, but it's really hard to use it as far as I think.
Say, an example here:
while 1:
rate(100) #what does this rate(100) do?
try:
'something'
except:
'something else'
I just can't understand it. Help!
A:
The example code you have provided is equivalent to this:
while True:
rate(100) #what does this rate(100) do?
try:
'something'
except:
'something else'
In Python many expressions can be tested for truth (that is evaluate to True or False when used in conditions and logical operations). For example non-empty sequences or non-zero numbers as you have evaluate to True. So this loop will run forever or until some code explicitly breaks out of it. This is because the loop condition is hard-coded to True so will never evaluate to False to exit the loop.
The basic behaviour of the while loop in python is well explained in the Python Tutorial. Unless you have a more specific question I would suggest you start there. Other Python flow control constructs are also described there.
A:
while 1 is a special case of while loop: It's a so-called "infinite loop".
Of course nothing is infinite. What the code is saying is: Run the contents of this loop until something inside causes it to exit. There's no explicit test in the loop, so the exit condition must be inside.
Either that, or the loop is meant to run for the entire duration of the program, and the program will run until killed by the operating system - or you flip the big red switch on your PC.
A:
You have actually defined an infinite loop. while 1: means to run the code-block below infinite times. You can only exit from it using a break statement.
The rate(100) calls the rate method, which must be defined somewhere. Then a try-catch block is executed. First 'something' code is run. If no errors occur, then the execution returns to the top of the loop. In case of an error, 'something else' is run.
A:
Well, while 1 is an infinite loop that will run forever. I'm guessing here a bit but rate(N) looks like the sort of function that would try to do something 100 times a second (or minute or other time period), in which case it's likely to be a simple "sleep for time period divided by rate".
For example, rate(100) would, in that case, be a sleep for 1/100th of a second (or other time unit).
Bottom line, it looks like a loop which continously tries something 100 times per time unit and, upon failure, do something else (the exception).
Without more context, you're probably not going to be able to get much more than that.
A:
The while 1: construction is a infinite loop, ie it never ends.
A:
while 1 is an infinite loop - it will run forever.
The while loop is a statement that allows code to be run on a given boolean value.
You can find more information here, and I've included the example given in the article below - converted to python.
x = 0
while (x < 3):
print "x = %d\n" % x
x++
A:
Read this: http://www.cs.utexas.edu/users/EWD/transcriptions/EWD03xx/EWD316.2.html
|
Understanding while loop
|
I am a newbie in Python. I can understand what a for loop does, but can't really understand what a while loop does. I knew it does repeat something while the condition is true, easy to say, but it's really hard to use it as far as I think.
Say, an example here:
while 1:
rate(100) #what does this rate(100) do?
try:
'something'
except:
'something else'
I just can't understand it. Help!
|
[
"The example code you have provided is equivalent to this:\nwhile True:\n rate(100) #what does this rate(100) do?\n try:\n 'something'\n except:\n 'something else'\n\nIn Python many expressions can be tested for truth (that is evaluate to True or False when used in conditions and logical operations). For example non-empty sequences or non-zero numbers as you have evaluate to True. So this loop will run forever or until some code explicitly breaks out of it. This is because the loop condition is hard-coded to True so will never evaluate to False to exit the loop.\nThe basic behaviour of the while loop in python is well explained in the Python Tutorial. Unless you have a more specific question I would suggest you start there. Other Python flow control constructs are also described there.\n",
"while 1 is a special case of while loop: It's a so-called \"infinite loop\".\nOf course nothing is infinite. What the code is saying is: Run the contents of this loop until something inside causes it to exit. There's no explicit test in the loop, so the exit condition must be inside.\nEither that, or the loop is meant to run for the entire duration of the program, and the program will run until killed by the operating system - or you flip the big red switch on your PC.\n",
"You have actually defined an infinite loop. while 1: means to run the code-block below infinite times. You can only exit from it using a break statement.\nThe rate(100) calls the rate method, which must be defined somewhere. Then a try-catch block is executed. First 'something' code is run. If no errors occur, then the execution returns to the top of the loop. In case of an error, 'something else' is run.\n",
"Well, while 1 is an infinite loop that will run forever. I'm guessing here a bit but rate(N) looks like the sort of function that would try to do something 100 times a second (or minute or other time period), in which case it's likely to be a simple \"sleep for time period divided by rate\".\nFor example, rate(100) would, in that case, be a sleep for 1/100th of a second (or other time unit).\nBottom line, it looks like a loop which continously tries something 100 times per time unit and, upon failure, do something else (the exception).\nWithout more context, you're probably not going to be able to get much more than that.\n",
"The while 1: construction is a infinite loop, ie it never ends.\n",
"while 1 is an infinite loop - it will run forever.\nThe while loop is a statement that allows code to be run on a given boolean value.\nYou can find more information here, and I've included the example given in the article below - converted to python.\nx = 0\nwhile (x < 3):\n print \"x = %d\\n\" % x\n x++\n\n",
"Read this: http://www.cs.utexas.edu/users/EWD/transcriptions/EWD03xx/EWD316.2.html\n"
] |
[
3,
2,
2,
0,
0,
0,
0
] |
[] |
[] |
[
"python",
"while_loop"
] |
stackoverflow_0001999026_python_while_loop.txt
|
Q:
Calling a variable from another function Python
I am trying to call a variable for use in another function. The variable is only in the other function and not declared as a global variable. Does anyone know how to call the other variable. The code below shows the 'retval' variable being used but it is declared in the other function.
def email_results():
if make.retval > 0:
os.system('python email_success.py')
else:
os.system('python email_failure.py')
if __name__ == '__main__': myObject = email_results()
Thanks
The function I declare it in is:
def make():
if os.path.exists(t):
command = "export ROOTDIR="+rootDir+"; "
command += "export PROJECT="+project+"; "
command += "export BUILD_DIR=$ROOTDIR/$PROJECT/basebuild; "
command += "export AD_EXEC_DIR=$BUILD_DIR/output_dev; "
command += "export BLDTARGET=MVArm9; "
command += "export PROFILE=release; "
command += "cd $ROOTDIR/$PROJECT; "
command += "make > "+logFileName+" 2>&1"
print "The command that I will be executing is:"
print command
#executing make command
retval = os.system(command)
print "retval=", retval
return retval
if __name__ == '__main__': myObject = make()
A:
Your make.retval is (I'm guessing from your vague question) the result of another function, make, which for some reason doesn't return retval.
Do this
def make( ):
etc.
return retval
def email_results( retval ):
etc.
if __name__ == "__main__":
retval= make()
email_results( retval )
Please find a good book on programming and read it. You're having problems with fundamental concepts of programming, not Python specifically.
A:
It should be make() not make.retval; the first is a function call, the second is an object member (sometimes called an attribute) reference. Since you defined make as a function, it is callable but does not have a member called retval.
|
Calling a variable from another function Python
|
I am trying to call a variable for use in another function. The variable is only in the other function and not declared as a global variable. Does anyone know how to call the other variable. The code below shows the 'retval' variable being used but it is declared in the other function.
def email_results():
if make.retval > 0:
os.system('python email_success.py')
else:
os.system('python email_failure.py')
if __name__ == '__main__': myObject = email_results()
Thanks
The function I declare it in is:
def make():
if os.path.exists(t):
command = "export ROOTDIR="+rootDir+"; "
command += "export PROJECT="+project+"; "
command += "export BUILD_DIR=$ROOTDIR/$PROJECT/basebuild; "
command += "export AD_EXEC_DIR=$BUILD_DIR/output_dev; "
command += "export BLDTARGET=MVArm9; "
command += "export PROFILE=release; "
command += "cd $ROOTDIR/$PROJECT; "
command += "make > "+logFileName+" 2>&1"
print "The command that I will be executing is:"
print command
#executing make command
retval = os.system(command)
print "retval=", retval
return retval
if __name__ == '__main__': myObject = make()
|
[
"Your make.retval is (I'm guessing from your vague question) the result of another function, make, which for some reason doesn't return retval.\nDo this\ndef make( ):\n etc. \n return retval\n\ndef email_results( retval ):\n etc.\n\nif __name__ == \"__main__\":\n retval= make()\n email_results( retval )\n\nPlease find a good book on programming and read it. You're having problems with fundamental concepts of programming, not Python specifically.\n",
"It should be make() not make.retval; the first is a function call, the second is an object member (sometimes called an attribute) reference. Since you defined make as a function, it is callable but does not have a member called retval.\n"
] |
[
7,
1
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001999144_python.txt
|
Q:
Determine where documents differ with Python
I have been using the Python difflib library to find where 2 documents differ. The Differ().compare() method does this, but it is very slow - atleast 100x slower for large HTML documents compared to the diff command.
How can I efficiently determine where 2 documents differ in Python? (Ideally I am after the positions rather the actual text, which is what SequenceMatcher().get_opcodes() returns.)
A:
a = open("file1.txt").readlines()
b = open("file2.txt").readlines()
count = 0
pos = 0
while 1:
count += 1
try:
al = a.pop(0)
bl = b.pop(0)
if al != bl:
print "files differ on line %d, byte %d" % (count,pos)
pos += len(al)
except IndexError:
break
A:
Google has a diff library for plain text with a python API, which should apply to the html documents you want to work with. I am not sure if it is suited for your particular use case where you are specifically interested in the location of the differences, but it is worth having a look at.
A:
An ugly and stupid solution: If diff is faster, use it; through a call from python via subprocess, parse the command output for the information you need. This won't be as fast as just diff, but maybe faster than difflib.
|
Determine where documents differ with Python
|
I have been using the Python difflib library to find where 2 documents differ. The Differ().compare() method does this, but it is very slow - atleast 100x slower for large HTML documents compared to the diff command.
How can I efficiently determine where 2 documents differ in Python? (Ideally I am after the positions rather the actual text, which is what SequenceMatcher().get_opcodes() returns.)
|
[
"a = open(\"file1.txt\").readlines()\nb = open(\"file2.txt\").readlines()\ncount = 0\npos = 0\n\nwhile 1:\n count += 1\n try:\n al = a.pop(0)\n bl = b.pop(0)\n if al != bl:\n print \"files differ on line %d, byte %d\" % (count,pos)\n pos += len(al)\n except IndexError:\n break\n\n",
"Google has a diff library for plain text with a python API, which should apply to the html documents you want to work with. I am not sure if it is suited for your particular use case where you are specifically interested in the location of the differences, but it is worth having a look at. \n",
"An ugly and stupid solution: If diff is faster, use it; through a call from python via subprocess, parse the command output for the information you need. This won't be as fast as just diff, but maybe faster than difflib.\n"
] |
[
3,
2,
1
] |
[] |
[] |
[
"diff",
"difflib",
"document",
"python",
"sequencematcher"
] |
stackoverflow_0001999019_diff_difflib_document_python_sequencematcher.txt
|
Q:
Is there a Scrum plugin for the Roundup Issue Tracker?
Is there a Scrum plugin for the Roundup Issue Tracker similar to Agilo for Trac? I realize that Roundup is an issue tracking system, whereas Trac is designed to be an integrated project management, SCM, and issue tracker. Therefore, maybe a better question would be—Is anyone aware of a, preferably Python based, Scrum tool to use in conjunction with Roundup? Although, that may be a bit too subjective for this forum.
A:
After researching this some more, it appears that there is not a Scrum plugin for the Roundup Issue Tracker similar to Agilo for Trac. However, I was able to find Ajellito (formerly Agilito). From the Ajellito website:
Simple, web-based Agile / Scrum project management tool built in Django
Ajellito aims to do just enough for you to effectively and efficiently manage projects using an Agile methodology.
Given that Ajellito is written in Django—a Python web framework—this may be a nice complement to Roundup.
Using Ajellito for tracking user stories and tasks/actions and Roundup to track bugs/defects presents a new problem in terms of integration, or lack thereof, between the actions/tasks and bugs/defects.
Agile Database Integration http://img.skitch.com/20100104-t3crikk3hjb1mrmmnuipsk5fj7.jpg
|
Is there a Scrum plugin for the Roundup Issue Tracker?
|
Is there a Scrum plugin for the Roundup Issue Tracker similar to Agilo for Trac? I realize that Roundup is an issue tracking system, whereas Trac is designed to be an integrated project management, SCM, and issue tracker. Therefore, maybe a better question would be—Is anyone aware of a, preferably Python based, Scrum tool to use in conjunction with Roundup? Although, that may be a bit too subjective for this forum.
|
[
"After researching this some more, it appears that there is not a Scrum plugin for the Roundup Issue Tracker similar to Agilo for Trac. However, I was able to find Ajellito (formerly Agilito). From the Ajellito website:\n\nSimple, web-based Agile / Scrum project management tool built in Django\n Ajellito aims to do just enough for you to effectively and efficiently manage projects using an Agile methodology. \n\nGiven that Ajellito is written in Django—a Python web framework—this may be a nice complement to Roundup. \nUsing Ajellito for tracking user stories and tasks/actions and Roundup to track bugs/defects presents a new problem in terms of integration, or lack thereof, between the actions/tasks and bugs/defects.\nAgile Database Integration http://img.skitch.com/20100104-t3crikk3hjb1mrmmnuipsk5fj7.jpg\n"
] |
[
0
] |
[] |
[] |
[
"agile",
"python",
"roundup",
"scrum",
"trac"
] |
stackoverflow_0001977458_agile_python_roundup_scrum_trac.txt
|
Q:
How to use Staticgenerator with Django + Apache + mod_python
I have currently an enviroment with Django + Apache via mod_python. How can I use Staticgenerator without nginx, just with Apache and mod_python? Thank you.
A:
Perhaps this page from the webfaction forum will help:
http://forum.webfaction.com/viewtopic.php?id=1945
A:
Staticgenerator is designed to be used with a front-end http server. The example configuration as shown on the Github Staticgenerator page is using Nginx as the front-end http server and Apache as the back-end http server.
If you want a static website generator that isn't specifically designed to be used with a front-end http server, you might want to look at Hyde. Hyde is Django powered and statically generates the webpages, which are then placed in a deploy directory. Hyde came out of the developer, Lakshmi Vyas, wanting a Django based Jekyll, which is a static website generator written in Ruby. Lakshmi Vyas did look into Staticgenerator prior to developing Hyde but decided to roll his own.
|
How to use Staticgenerator with Django + Apache + mod_python
|
I have currently an enviroment with Django + Apache via mod_python. How can I use Staticgenerator without nginx, just with Apache and mod_python? Thank you.
|
[
"Perhaps this page from the webfaction forum will help:\n\nhttp://forum.webfaction.com/viewtopic.php?id=1945\n\n",
"Staticgenerator is designed to be used with a front-end http server. The example configuration as shown on the Github Staticgenerator page is using Nginx as the front-end http server and Apache as the back-end http server.\nIf you want a static website generator that isn't specifically designed to be used with a front-end http server, you might want to look at Hyde. Hyde is Django powered and statically generates the webpages, which are then placed in a deploy directory. Hyde came out of the developer, Lakshmi Vyas, wanting a Django based Jekyll, which is a static website generator written in Ruby. Lakshmi Vyas did look into Staticgenerator prior to developing Hyde but decided to roll his own.\n"
] |
[
0,
0
] |
[] |
[] |
[
"apache",
"django",
"mod_python",
"python"
] |
stackoverflow_0001275270_apache_django_mod_python_python.txt
|
Q:
Django: Is there a way to have the "through" model in a ManyToManyField in a different app to the model containing the ManyToManyField?
Lets say I have two django apps:
competitions - which will handle competition data
entries - which will handle functionality relating to entering competitors into competitions
In the competitions app I have a model which represents a section of a competition:
class Division(models.Model):
competition = models.ForeignKey(Competition)
discipline = models.CharField(max_length=1, choices=DISCIPLINE_CHOICES)
age_group = models.ForeignKey(AgeGroup)
participants = models.ManyToManyField(Competitor, through='Entry')
I want to put the Entry model in the entries app:
class Entry(models.Model):
division = models.ForeignKey('Division')
competitor = models.ForeignKey(Competitor)
withdrawn = models.BooleanField(default=False)
How do I solve the from ... import ... statements, so that they work? When I put in import statements such as from entries.models import Entry I get the models from these apps ignored by syncdb (because the imports are circular) or when I remove one or both of them I get validation errors:
Error: One or more models did not
validate: entries.entry: 'division'
has a relation with model Division,
which has either not been installed or
is abstract. competitions.division:
'participants' specifies an m2m
relation through model Entry, which
has not been installed
I understand why this happens, but I have no idea how to change this, so that it works (without resorting to moving the Entry model into the competitions app, which I really don't want to do).
A:
It seems like I've found an answer, which works more consistently :)
The Django documentation on the ForeignKey class says:
To refer to models defined in another
application, you can explicitly
specify a model with the full
application label. For example, if the
Manufacturer model above is defined in
another application called production,
you'd need to use:
class Car(models.Model):
manufacturer = models.ForeignKey('production.Manufacturer')
This sort of reference can be useful
when resolving circular import
dependencies between two applications.
A:
sometimes, django.db.models.get_model helps to work around circular imports. In your example, try to import Entry normally and chage the division FK definition in Entry to this:
from django.db.models import get_model
class Entry(models.Model):
division = models.ForeignKey(get_model('competitions', 'Division'))
|
Django: Is there a way to have the "through" model in a ManyToManyField in a different app to the model containing the ManyToManyField?
|
Lets say I have two django apps:
competitions - which will handle competition data
entries - which will handle functionality relating to entering competitors into competitions
In the competitions app I have a model which represents a section of a competition:
class Division(models.Model):
competition = models.ForeignKey(Competition)
discipline = models.CharField(max_length=1, choices=DISCIPLINE_CHOICES)
age_group = models.ForeignKey(AgeGroup)
participants = models.ManyToManyField(Competitor, through='Entry')
I want to put the Entry model in the entries app:
class Entry(models.Model):
division = models.ForeignKey('Division')
competitor = models.ForeignKey(Competitor)
withdrawn = models.BooleanField(default=False)
How do I solve the from ... import ... statements, so that they work? When I put in import statements such as from entries.models import Entry I get the models from these apps ignored by syncdb (because the imports are circular) or when I remove one or both of them I get validation errors:
Error: One or more models did not
validate: entries.entry: 'division'
has a relation with model Division,
which has either not been installed or
is abstract. competitions.division:
'participants' specifies an m2m
relation through model Entry, which
has not been installed
I understand why this happens, but I have no idea how to change this, so that it works (without resorting to moving the Entry model into the competitions app, which I really don't want to do).
|
[
"It seems like I've found an answer, which works more consistently :)\nThe Django documentation on the ForeignKey class says:\n\nTo refer to models defined in another\n application, you can explicitly\n specify a model with the full\n application label. For example, if the\n Manufacturer model above is defined in\n another application called production,\n you'd need to use:\n\nclass Car(models.Model):\n manufacturer = models.ForeignKey('production.Manufacturer')\n\n\nThis sort of reference can be useful\n when resolving circular import\n dependencies between two applications.\n\n",
"sometimes, django.db.models.get_model helps to work around circular imports. In your example, try to import Entry normally and chage the division FK definition in Entry to this:\nfrom django.db.models import get_model\n\nclass Entry(models.Model):\n division = models.ForeignKey(get_model('competitions', 'Division'))\n\n"
] |
[
16,
5
] |
[] |
[] |
[
"django",
"django_apps",
"django_models",
"manytomanyfield",
"python"
] |
stackoverflow_0001970365_django_django_apps_django_models_manytomanyfield_python.txt
|
Q:
"download link " fails in IE
I was trying to implement a "download link" and put it beside one of my report table so that users can download a csv file and open it with applications like Excel.
The records are generated dynamically based on the query made by users.
So somewhere in my controller there's something like:
response.headers['Content-Type'] = 'text/csv'
response.headers['Content-Disposition'] = 'attachment; filename=xxx.csv'
return response.stream(dynamically_generated_csv, request=request)
This works in both FireFox & Chrome, but fails in IE.
When I print out the response headers, I found that several headers were added to my response by web2py:'Expires', 'Cache-Control', etc...
And when I remove the 'Cache-Control' header by doing the following:
del response.headers['Cache-Control']
It works in IE.
So it seems like IE has trouble dealing with a downloadable file with 'Cache-Control' set to certain value.
Now, my question is:
Why does web2py add these response headers, implicitly? and maybe without a way to set it off?
is there any side effect when i delete the 'Cache-Control' header this way?
Thanks in advance.
A:
I'm not sure what Cache control headers are/were being sent but IE has a bug with downloaded files like you are experiencing.
For IE, you MUST enable caching. When IE loads files (e.g. Excel files), in Excel, it loads them from the cache directory, thus if you don't cache it, Excel (or your other app) will fail to load the file.
Eric Law (MSFT) on the topic: http://blogs.msdn.com/ieinternals/archive/2009/10/02/Internet-Explorer-cannot-download-over-HTTPS-when-no-cache.aspx
Update: If however you just want to force the download... e.g. not have IE load the excel file inside the IE window... then be sure to set the full headers for the attachment.
//PHP style
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment; filename="downloaded.pdf"');
A:
Is the download link using https (ssl)? If so, then IE can't handle the downloading if it's set to be cached. This is a known problem with IE.
A:
This doesn't answer your question, but solves, I hope, original problem.
I would just add timestamp (something unique enough) to query string of link to CSV file. It helped for me.
|
"download link " fails in IE
|
I was trying to implement a "download link" and put it beside one of my report table so that users can download a csv file and open it with applications like Excel.
The records are generated dynamically based on the query made by users.
So somewhere in my controller there's something like:
response.headers['Content-Type'] = 'text/csv'
response.headers['Content-Disposition'] = 'attachment; filename=xxx.csv'
return response.stream(dynamically_generated_csv, request=request)
This works in both FireFox & Chrome, but fails in IE.
When I print out the response headers, I found that several headers were added to my response by web2py:'Expires', 'Cache-Control', etc...
And when I remove the 'Cache-Control' header by doing the following:
del response.headers['Cache-Control']
It works in IE.
So it seems like IE has trouble dealing with a downloadable file with 'Cache-Control' set to certain value.
Now, my question is:
Why does web2py add these response headers, implicitly? and maybe without a way to set it off?
is there any side effect when i delete the 'Cache-Control' header this way?
Thanks in advance.
|
[
"I'm not sure what Cache control headers are/were being sent but IE has a bug with downloaded files like you are experiencing.\nFor IE, you MUST enable caching. When IE loads files (e.g. Excel files), in Excel, it loads them from the cache directory, thus if you don't cache it, Excel (or your other app) will fail to load the file.\nEric Law (MSFT) on the topic: http://blogs.msdn.com/ieinternals/archive/2009/10/02/Internet-Explorer-cannot-download-over-HTTPS-when-no-cache.aspx\nUpdate: If however you just want to force the download... e.g. not have IE load the excel file inside the IE window... then be sure to set the full headers for the attachment.\n//PHP style\nheader('Content-Type: application/vnd.ms-excel');\nheader('Content-Disposition: attachment; filename=\"downloaded.pdf\"');\n\n",
"Is the download link using https (ssl)? If so, then IE can't handle the downloading if it's set to be cached. This is a known problem with IE.\n",
"This doesn't answer your question, but solves, I hope, original problem.\nI would just add timestamp (something unique enough) to query string of link to CSV file. It helped for me.\n"
] |
[
5,
2,
0
] |
[] |
[] |
[
"internet_explorer",
"python",
"web2py"
] |
stackoverflow_0001999950_internet_explorer_python_web2py.txt
|
Q:
Python string splitting
If I have a string 'x=10', how can I extract the 10 as an integer using one line of code?
A:
>>> s = "x=10"
>>> int(s.split('=')[-1])
10
A:
s = 'x=10'
i = int(s[2:])
A:
Sure:
a = "x=10"
b = int(a.split('=')[1])
A:
result = int(my_string.rpartition("=")[-1])
Note, however, that if there is anything else after the = sign the function will break.
So x=10, x=560, and x=1010001003010 will all work. However, y=1,341 will break with a ValueError.
ValueError: invalid literal for int() with base 10: '1,341'
Edit:
Actually, pitrou's use of split is even better, since you probably are not guaranteed that there will be only one = sign either.
And also fixed the partition vs. rpartition problem.
A:
Check this one:
answer = int("x=10".partition("=")[2])
|
Python string splitting
|
If I have a string 'x=10', how can I extract the 10 as an integer using one line of code?
|
[
">>> s = \"x=10\"\n>>> int(s.split('=')[-1])\n10\n\n",
"s = 'x=10' \ni = int(s[2:])\n\n",
"Sure:\na = \"x=10\"\nb = int(a.split('=')[1])\n\n",
"result = int(my_string.rpartition(\"=\")[-1])\n\nNote, however, that if there is anything else after the = sign the function will break.\nSo x=10, x=560, and x=1010001003010 will all work. However, y=1,341 will break with a ValueError.\nValueError: invalid literal for int() with base 10: '1,341'\nEdit:\nActually, pitrou's use of split is even better, since you probably are not guaranteed that there will be only one = sign either. \nAnd also fixed the partition vs. rpartition problem.\n",
"Check this one:\nanswer = int(\"x=10\".partition(\"=\")[2])\n\n"
] |
[
7,
3,
3,
3,
0
] |
[] |
[] |
[
"python",
"split",
"string"
] |
stackoverflow_0002000202_python_split_string.txt
|
Q:
sqlalchemy cascade and association objects
My database structure is something like this (I'm using declarative style):
class Character(Base):
__tablename__="characters"
id = Column(Integer, primary_key=True)
name = Column(String)
player = Column(String)
inventory = relation(Inventory)
class Item(Base):
__tablename__="items"
id = Column(Integer, primary_key=True)
name = Column(String)
class Inventory(Base):
__tablename__="inventory"
id = Column(Integer, primary_key=True)
char_id = Column(Integer, ForeignKey("characters.id"))
item_id = Column(Integer, ForeignKey("characters.id"))
quantity = Column(Integer)
item = relation(Item)
My problem is that when I remove an "Inventory" object from "Character.inventory" this isn't updated until the session get committed. For example:
>>> torch_inv=character.inventory[0] # Inventory object referred to a torch
>>> torch_inv.item, torch_inv.quantity
(<Item object, torch>, 3)
>>> session.delete(torch_inv)
>>> character.inventory[0]
<Inventory object, torch>
I've seen that there is a relation option "cascade" but I can't find a way to make it working in this case.
A:
Session.delete() method just marks an instance as "to be deleted", so your relation won't change untill you flush changes to database independent on cascade rules. On other hand you can just remove Inventory instance from character.inventory collection, then having 'delete-orphan' cascade rule will mark removed Inventory instance for deletion.
|
sqlalchemy cascade and association objects
|
My database structure is something like this (I'm using declarative style):
class Character(Base):
__tablename__="characters"
id = Column(Integer, primary_key=True)
name = Column(String)
player = Column(String)
inventory = relation(Inventory)
class Item(Base):
__tablename__="items"
id = Column(Integer, primary_key=True)
name = Column(String)
class Inventory(Base):
__tablename__="inventory"
id = Column(Integer, primary_key=True)
char_id = Column(Integer, ForeignKey("characters.id"))
item_id = Column(Integer, ForeignKey("characters.id"))
quantity = Column(Integer)
item = relation(Item)
My problem is that when I remove an "Inventory" object from "Character.inventory" this isn't updated until the session get committed. For example:
>>> torch_inv=character.inventory[0] # Inventory object referred to a torch
>>> torch_inv.item, torch_inv.quantity
(<Item object, torch>, 3)
>>> session.delete(torch_inv)
>>> character.inventory[0]
<Inventory object, torch>
I've seen that there is a relation option "cascade" but I can't find a way to make it working in this case.
|
[
"Session.delete() method just marks an instance as \"to be deleted\", so your relation won't change untill you flush changes to database independent on cascade rules. On other hand you can just remove Inventory instance from character.inventory collection, then having 'delete-orphan' cascade rule will mark removed Inventory instance for deletion.\n"
] |
[
1
] |
[] |
[] |
[
"python",
"sqlalchemy"
] |
stackoverflow_0001998962_python_sqlalchemy.txt
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.