title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags listlengths 1 5 |
|---|---|---|---|---|---|---|---|---|---|
Proper way to use **kwargs in Python | 1,098,549 | <p>What is the proper way to use <code>**kwargs</code> in Python when it comes to default values?</p>
<p><code>kwargs</code> returns a dictionary, but what is the best way to set default values, or is there one? Should I just access it as a dictionary? Use get function? </p>
<pre><code>class ExampleClass:
def __init__(self, **kwargs):
self.val = kwargs['val']
self.val2 = kwargs.get('val2')
</code></pre>
<p>A simple question, but one that I can't find good resources on. People do it different ways in code that I've seen and it's hard to know what to use.</p>
| 247 | 2009-07-08T14:45:53Z | 15,769,548 | <p>I think the proper way to use **kwargs in Python when it comes to default values is to use the dictionary method setdefault, as given below:</p>
<pre><code>class ExampleClass:
def __init__(self, **kwargs):
kwargs.setdefault('val', value1)
kwargs.setdefault('val2', value2)
</code></pre>
<p>In this way, if a user passes 'val' or 'val2' in the keyword args, they will be used; otherwise, the default values that have been set will be used.</p>
| 5 | 2013-04-02T16:39:14Z | [
"python",
"kwargs"
] |
Proper way to use **kwargs in Python | 1,098,549 | <p>What is the proper way to use <code>**kwargs</code> in Python when it comes to default values?</p>
<p><code>kwargs</code> returns a dictionary, but what is the best way to set default values, or is there one? Should I just access it as a dictionary? Use get function? </p>
<pre><code>class ExampleClass:
def __init__(self, **kwargs):
self.val = kwargs['val']
self.val2 = kwargs.get('val2')
</code></pre>
<p>A simple question, but one that I can't find good resources on. People do it different ways in code that I've seen and it's hard to know what to use.</p>
| 247 | 2009-07-08T14:45:53Z | 36,336,431 | <p>Following up on <a href="http://stackoverflow.com/questions/1098549/proper-way-to-use-kwargs-in-python/13629607#13629607">@srhegde</a> suggestion of using <a href="https://docs.python.org/2/reference/datamodel.html#object.__setattr__"><strong>setattr</strong></a>:</p>
<pre><code>class ExampleClass(object):
__acceptable_keys_list = ['foo', 'bar']
def __init__(self, **kwargs):
[self.__setattr__(key, kwargs.get(key)) for key in self.__acceptable_keys_list]
</code></pre>
<p>This variant is useful when the class is expected to have all of the items in our <code>acceptable</code> list.</p>
| 5 | 2016-03-31T14:34:37Z | [
"python",
"kwargs"
] |
Proper way to use **kwargs in Python | 1,098,549 | <p>What is the proper way to use <code>**kwargs</code> in Python when it comes to default values?</p>
<p><code>kwargs</code> returns a dictionary, but what is the best way to set default values, or is there one? Should I just access it as a dictionary? Use get function? </p>
<pre><code>class ExampleClass:
def __init__(self, **kwargs):
self.val = kwargs['val']
self.val2 = kwargs.get('val2')
</code></pre>
<p>A simple question, but one that I can't find good resources on. People do it different ways in code that I've seen and it's hard to know what to use.</p>
| 247 | 2009-07-08T14:45:53Z | 37,369,859 | <p>@AbhinavGupta and @Steef suggested using <code>update()</code>, which I found very helpful for processing large argument lists:</p>
<pre><code>args.update(kwargs)
</code></pre>
<p>What if we want to check that the user hasn't passed any spurious/unsupported arguments? @VinaySajip pointed out that <code>pop()</code> can be used to iteratively process the list of arguments. Then, any leftover arguments are spurious. Nice.</p>
<p>Here's another possible way to do this, which keeps the simple syntax of using <code>update()</code>:</p>
<pre><code># kwargs = dictionary of user-supplied arguments
# args = dictionary containing default arguments
# Check that user hasn't given spurious arguments
unknown_args = user_args.keys() - default_args.keys()
if unknown_args:
raise TypeError('Unknown arguments: {}'.format(unknown_args))
# Update args to contain user-supplied arguments
args.update(kwargs)
</code></pre>
<p><code>unknown_args</code> is a <code>set</code> containing the names of arguments that don't occur in the defaults.</p>
| 1 | 2016-05-22T02:08:18Z | [
"python",
"kwargs"
] |
Extract only numbers from data in Jython | 1,098,613 | <p>Here is my problem. I'm working on a Jython program and I have to extract numbers from a PyJavaInstance:</p>
<p>[{string1="foo", xxx1, xxx2, ..., xxxN, string2="bar"}]</p>
<p>(where xxx are the floating point numbers).</p>
<p>My question is how can I extract the numbers and put them in a more simple structure like a python list.</p>
<p>Thank you in advance.</p>
| 0 | 2009-07-08T14:56:48Z | 1,098,642 | <p>can you iterate and check whether an item is float? The method you're looking for is <a href="http://docs.python.org/library/functions.html?highlight=isinstance#isinstance" rel="nofollow"><code>isinstance</code></a>. I hope it's implemented in Jython.</p>
| 1 | 2009-07-08T15:03:43Z | [
"python",
"list",
"jython",
"extract"
] |
Extract only numbers from data in Jython | 1,098,613 | <p>Here is my problem. I'm working on a Jython program and I have to extract numbers from a PyJavaInstance:</p>
<p>[{string1="foo", xxx1, xxx2, ..., xxxN, string2="bar"}]</p>
<p>(where xxx are the floating point numbers).</p>
<p>My question is how can I extract the numbers and put them in a more simple structure like a python list.</p>
<p>Thank you in advance.</p>
| 0 | 2009-07-08T14:56:48Z | 1,098,657 | <p>A <code>PyJavaInstance</code> is a Jython wrapper around a Java instance; how you extract numbers from it depends on what it is. If you need to get a bunch of stuff - some of which are strings and some of which are floats, then:</p>
<pre><code>float_list = []
for item in instance_properties:
try:
float_list.append(float(item))
except ValueError:
pass
</code></pre>
| 2 | 2009-07-08T15:06:37Z | [
"python",
"list",
"jython",
"extract"
] |
Extract only numbers from data in Jython | 1,098,613 | <p>Here is my problem. I'm working on a Jython program and I have to extract numbers from a PyJavaInstance:</p>
<p>[{string1="foo", xxx1, xxx2, ..., xxxN, string2="bar"}]</p>
<p>(where xxx are the floating point numbers).</p>
<p>My question is how can I extract the numbers and put them in a more simple structure like a python list.</p>
<p>Thank you in advance.</p>
| 0 | 2009-07-08T14:56:48Z | 1,098,769 | <p>Thank you Vinay. It's also the kind of solution I've just found:</p>
<pre><code> new_inst=[]
for element in instance:
try:
float(element)
new_inst.append(float(element))
except ValueError:
del(element)
</code></pre>
<p>@SilentGhost: Good suggestion. The issue was to find what method could determine if each element I iterate is a float number. </p>
| 0 | 2009-07-08T15:20:49Z | [
"python",
"list",
"jython",
"extract"
] |
IndexError: list index out of range and python | 1,098,643 | <p>I'm telling my program to print out line 53 of an output. Is this error telling me that there aren't that many lines and therefore can not print it out?</p>
| 8 | 2009-07-08T15:03:55Z | 1,098,658 | <p>yes. sequence doesn't have the 54th item.</p>
| 3 | 2009-07-08T15:07:00Z | [
"python",
"indexoutofboundsexception"
] |
IndexError: list index out of range and python | 1,098,643 | <p>I'm telling my program to print out line 53 of an output. Is this error telling me that there aren't that many lines and therefore can not print it out?</p>
| 8 | 2009-07-08T15:03:55Z | 1,098,660 | <p>If you have a list with 53 items, the last one is <code>thelist[52]</code> because indexing start at 0.</p>
| 16 | 2009-07-08T15:07:15Z | [
"python",
"indexoutofboundsexception"
] |
IndexError: list index out of range and python | 1,098,643 | <p>I'm telling my program to print out line 53 of an output. Is this error telling me that there aren't that many lines and therefore can not print it out?</p>
| 8 | 2009-07-08T15:03:55Z | 1,098,670 | <p>That's right. 'list index out of range' most likely means you are referring to <code>n-th</code> element of the list, while the length of the list is smaller than <code>n</code>.</p>
| 1 | 2009-07-08T15:08:10Z | [
"python",
"indexoutofboundsexception"
] |
IndexError: list index out of range and python | 1,098,643 | <p>I'm telling my program to print out line 53 of an output. Is this error telling me that there aren't that many lines and therefore can not print it out?</p>
| 8 | 2009-07-08T15:03:55Z | 1,098,675 | <p>Yes,</p>
<p>You are trying to access an element of the list that does not exist.</p>
<pre><code>MyList = ["item1", "item2"]
print MyList[0] # Will work
print MyList[1] # Will Work
print MyList[2] # Will crash.
</code></pre>
<p>Have you got an off-by-one error?</p>
| 10 | 2009-07-08T15:08:32Z | [
"python",
"indexoutofboundsexception"
] |
IndexError: list index out of range and python | 1,098,643 | <p>I'm telling my program to print out line 53 of an output. Is this error telling me that there aren't that many lines and therefore can not print it out?</p>
| 8 | 2009-07-08T15:03:55Z | 37,785,115 | <p>Always keep in mind when you want to overcome this error, the default value of indexing and range starts from 0, so if total items is 100 then l[99] and range(99) will give you access up to the last element.</p>
<p>whenever you get this type of error please cross check with items that comes between/middle in range, and insure that their index is not last if you get output then you have made perfect error that mentioned above.</p>
<p>keep coding...</p>
| 0 | 2016-06-13T08:34:53Z | [
"python",
"indexoutofboundsexception"
] |
Help me lambda-nize this | 1,098,841 | <p>To help me better understand lambda I wrote this short snippet that rotates and transforms a quad (I hope I got the math right). Now, I want to replace the three steps below with one liner lambdas, possibly in conjunction with map().</p>
<p>Im using a <a href="http://www.pygame.org/wiki/2DVectorClass?parent=CookBook" rel="nofollow">vector class</a> but hopefully, the functions are clear as to what they do.</p>
<pre><code>self.orientation = vector(1,0)
self.orientation.rotate(90.0)
#the four corners of a quad
points = (vector(-1,-1),vector(1,-1),vector(1,1),vector(-1,1))
print points
#apply rotation to points according to orientation
rot_points = []
for i in points:
rot_points.append(i.rotated(self.orientation.get_angle()))
print rot_points
#transform the point according to world position and scale
real_points = []
for i in rot_points:
real_points.append(self.pos+i*self.scale)
print real_points
return real_points
</code></pre>
| 3 | 2009-07-08T15:31:04Z | 1,098,882 | <p>You could use <code>map</code>, <code>reduce</code>, et al, but nowadays list comprehensions are the preferred way to do things in Python:</p>
<pre><code>rot_points = (i.rotated(self.orientation.get_angle()) for i in points)
real_points = [self.pos+i*self.scale for i in rot_points]
</code></pre>
<p>Notice how I used <code>(parentheses)</code> instead of <code>[brackets]</code> in the first line. That is called a <a href="http://www.python.org/doc/2.5.2/ref/genexpr.html" rel="nofollow">generator expression</a>. It allows <code>rot_points</code> to be constructed on the fly as the points are used in the second line rather than constructing all of the <code>rot_points</code> in memory first and <em>then</em> iterating through them. It could save some unnecessary memory usage, basically, if that's a concern.</p>
| 8 | 2009-07-08T15:37:39Z | [
"python",
"lambda"
] |
Help me lambda-nize this | 1,098,841 | <p>To help me better understand lambda I wrote this short snippet that rotates and transforms a quad (I hope I got the math right). Now, I want to replace the three steps below with one liner lambdas, possibly in conjunction with map().</p>
<p>Im using a <a href="http://www.pygame.org/wiki/2DVectorClass?parent=CookBook" rel="nofollow">vector class</a> but hopefully, the functions are clear as to what they do.</p>
<pre><code>self.orientation = vector(1,0)
self.orientation.rotate(90.0)
#the four corners of a quad
points = (vector(-1,-1),vector(1,-1),vector(1,1),vector(-1,1))
print points
#apply rotation to points according to orientation
rot_points = []
for i in points:
rot_points.append(i.rotated(self.orientation.get_angle()))
print rot_points
#transform the point according to world position and scale
real_points = []
for i in rot_points:
real_points.append(self.pos+i*self.scale)
print real_points
return real_points
</code></pre>
| 3 | 2009-07-08T15:31:04Z | 1,098,984 | <p>Note that you're unnecessarily calling <code>get_angle()</code> for each point, when really it's constant over the life of the loop. </p>
<p>I'd try this:</p>
<pre><code>angle = self.orientation.get_angle()
real_points = [self.pos+point.rotated(angle)*self.scale for point in points]
</code></pre>
<p>I don't think it's a bad idea to create a helper function in this case either, since you're doing quite a bit to each point. A new function is more readable:</p>
<pre><code>angle = self.orientation.get_angle()
def adjust_point(point):
point = point.rotated(angle)
point *= self.scale
point += self.pos
return point
real_points = [adjust_point(p) for p in point]
</code></pre>
| 0 | 2009-07-08T15:56:08Z | [
"python",
"lambda"
] |
for statement and i.find in list | 1,098,970 | <pre><code>for a in ('90','52.6', '26.5'):
if a == '90':
z = (' 0',)
elif a == '52.6':
z = ('0', '5')
else:
z = ('25')
for b in z:
cmd = exepath + ' -a ' + str(a) + ' -b ' + str(b)
process = Popen(cmd, shell=True, stderr=STDOUT, stdout=PIPE)
outputstring = process.communicate()[0]
outputlist = outputstring.splitlines()
for i in outputlist:
if i.find('The student says') != -1:
print i
</code></pre>
<p>Working on an assignment and this a snippet of my code. There is a portion above this code but all it's doing is defining exepath and just printing exepath to the screen. When I run this, I don't get an error or anything but the program just ends when put into the command prompt. Why? and how do I fix it?</p>
<p><strong>EDIT:</strong> Sorry for the quotes but the problem. I updated the code to fix that, but it still gives me nothing back it just exits... What could the problem be?</p>
| -2 | 2009-07-08T15:53:59Z | 1,098,985 | <p>you are missing quotes around you first for statement try</p>
<pre><code>for a in ('90','52.6', '26.5'):
</code></pre>
| 6 | 2009-07-08T15:56:14Z | [
"python"
] |
for statement and i.find in list | 1,098,970 | <pre><code>for a in ('90','52.6', '26.5'):
if a == '90':
z = (' 0',)
elif a == '52.6':
z = ('0', '5')
else:
z = ('25')
for b in z:
cmd = exepath + ' -a ' + str(a) + ' -b ' + str(b)
process = Popen(cmd, shell=True, stderr=STDOUT, stdout=PIPE)
outputstring = process.communicate()[0]
outputlist = outputstring.splitlines()
for i in outputlist:
if i.find('The student says') != -1:
print i
</code></pre>
<p>Working on an assignment and this a snippet of my code. There is a portion above this code but all it's doing is defining exepath and just printing exepath to the screen. When I run this, I don't get an error or anything but the program just ends when put into the command prompt. Why? and how do I fix it?</p>
<p><strong>EDIT:</strong> Sorry for the quotes but the problem. I updated the code to fix that, but it still gives me nothing back it just exits... What could the problem be?</p>
| -2 | 2009-07-08T15:53:59Z | 1,099,481 | <p>Once you've fixed the missing quote, you'll get weird behavior from this part:</p>
<pre><code>else:
z = ('25')
for b in z:
</code></pre>
<p>the parentheses here do nothing at all, and b in the loop will be '2' then '5'. You probably mean to use, instead:</p>
<pre><code> z = ('25',)
</code></pre>
<p>which makes z a tuple with just one item (the trailing comma here is what tells the Python compiler that it's a tuple -- would work just as well w/o the parentheses), so b in the loop will be '25'.</p>
| 1 | 2009-07-08T17:32:57Z | [
"python"
] |
for statement and i.find in list | 1,098,970 | <pre><code>for a in ('90','52.6', '26.5'):
if a == '90':
z = (' 0',)
elif a == '52.6':
z = ('0', '5')
else:
z = ('25')
for b in z:
cmd = exepath + ' -a ' + str(a) + ' -b ' + str(b)
process = Popen(cmd, shell=True, stderr=STDOUT, stdout=PIPE)
outputstring = process.communicate()[0]
outputlist = outputstring.splitlines()
for i in outputlist:
if i.find('The student says') != -1:
print i
</code></pre>
<p>Working on an assignment and this a snippet of my code. There is a portion above this code but all it's doing is defining exepath and just printing exepath to the screen. When I run this, I don't get an error or anything but the program just ends when put into the command prompt. Why? and how do I fix it?</p>
<p><strong>EDIT:</strong> Sorry for the quotes but the problem. I updated the code to fix that, but it still gives me nothing back it just exits... What could the problem be?</p>
| -2 | 2009-07-08T15:53:59Z | 1,100,578 | <p>Looking at your code it will only actually output something if the <code>i.find('The student says')</code> successfully matches so you could either run this in a debugger or add some print statements to see what is in <code>outputstring</code> for each time round the loop.</p>
| 1 | 2009-07-08T21:17:10Z | [
"python"
] |
Matching Nested Structures With Regular Expressions in Python | 1,099,178 | <p>I seem to remember that Regular Expressions in DotNet have a special mechanism that allows for the correct matching of nested structures, like the grouping in "<code>( (a ( ( c ) b ) ) ( d ) e )</code>". </p>
<p>What is the python equivalent of this feature? Can this be achieved using regular expressions with some workaround? (Though it seems to be the sort of problem that current implementations of regex aren't designed for)</p>
| 14 | 2009-07-08T16:30:38Z | 1,099,197 | <p>I'd recommend removing the nesting from the regex itself, looping through the results and performing regexes on that.</p>
| 1 | 2009-07-08T16:34:13Z | [
"python",
"regex",
"recursive-regex"
] |
Matching Nested Structures With Regular Expressions in Python | 1,099,178 | <p>I seem to remember that Regular Expressions in DotNet have a special mechanism that allows for the correct matching of nested structures, like the grouping in "<code>( (a ( ( c ) b ) ) ( d ) e )</code>". </p>
<p>What is the python equivalent of this feature? Can this be achieved using regular expressions with some workaround? (Though it seems to be the sort of problem that current implementations of regex aren't designed for)</p>
| 14 | 2009-07-08T16:30:38Z | 1,099,215 | <p>Python doesn't support recursion in regular expressions. So equivalents to .NET's balancing groups or PCRE regex in Perl are not immediately possible in Python.</p>
<p>Like you said yourself: this is NOT a problem you should really be solving with a single regex.</p>
| 2 | 2009-07-08T16:38:07Z | [
"python",
"regex",
"recursive-regex"
] |
Matching Nested Structures With Regular Expressions in Python | 1,099,178 | <p>I seem to remember that Regular Expressions in DotNet have a special mechanism that allows for the correct matching of nested structures, like the grouping in "<code>( (a ( ( c ) b ) ) ( d ) e )</code>". </p>
<p>What is the python equivalent of this feature? Can this be achieved using regular expressions with some workaround? (Though it seems to be the sort of problem that current implementations of regex aren't designed for)</p>
| 14 | 2009-07-08T16:30:38Z | 1,099,316 | <p>Are you talking about recursion? It's not clear from your question. An example:</p>
<pre><code>ActivePython 2.6.1.1 (ActiveState Software Inc.) based on
Python 2.6.1 (r261:67515, Dec 5 2008, 13:58:38) [MSC v.1500 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import re
>>> p = re.compile(r"((\w+((\d+)[.;]))(\s+)\d)")
>>> m = p.match("Fred99. \t9")
>>> m
<_sre.SRE_Match object at 0x00454F80>
>>> m.groups()
('Fred99. \t9', 'Fred99.', '9.', '9', ' \t')
</code></pre>
<p>This shows matching of nested groups. The numbering of groups depends on the order in which their opening parenthesis occurs in the pattern.</p>
| 0 | 2009-07-08T16:57:31Z | [
"python",
"regex",
"recursive-regex"
] |
Matching Nested Structures With Regular Expressions in Python | 1,099,178 | <p>I seem to remember that Regular Expressions in DotNet have a special mechanism that allows for the correct matching of nested structures, like the grouping in "<code>( (a ( ( c ) b ) ) ( d ) e )</code>". </p>
<p>What is the python equivalent of this feature? Can this be achieved using regular expressions with some workaround? (Though it seems to be the sort of problem that current implementations of regex aren't designed for)</p>
| 14 | 2009-07-08T16:30:38Z | 1,101,030 | <p>Regular expressions <em>cannot</em> parse nested structures. Nested structures are not regular, by definition. They cannot be constructed by a regular grammar, and they cannot be parsed by a finite state automaton (a regular expression can be seen as a shorthand notation for an FSA).</p>
<p>Today's "regex" engines sometimes support some limited "nesting" constructs, but from a technical standpoint, they shouldn't be called "regular" anymore.</p>
| 20 | 2009-07-08T23:10:34Z | [
"python",
"regex",
"recursive-regex"
] |
Matching Nested Structures With Regular Expressions in Python | 1,099,178 | <p>I seem to remember that Regular Expressions in DotNet have a special mechanism that allows for the correct matching of nested structures, like the grouping in "<code>( (a ( ( c ) b ) ) ( d ) e )</code>". </p>
<p>What is the python equivalent of this feature? Can this be achieved using regular expressions with some workaround? (Though it seems to be the sort of problem that current implementations of regex aren't designed for)</p>
| 14 | 2009-07-08T16:30:38Z | 1,101,046 | <p>You can't do this generally using Python regular expressions. (.NET regular expressions have been extended with "balancing groups" which is what allows nested matches.)</p>
<p>However, PyParsing is a very nice package for this type of thing:</p>
<pre><code>from pyparsing import nestedExpr
data = "( (a ( ( c ) b ) ) ( d ) e )"
print nestedExpr().parseString(data).asList()
</code></pre>
<p>The output is:</p>
<pre><code>[[['a', [['c'], 'b']], ['d'], 'e']]
</code></pre>
<p>More on PyParsing:</p>
<ul>
<li><a href="http://pyparsing.wikispaces.com/Documentation">http://pyparsing.wikispaces.com/Documentation</a></li>
</ul>
| 15 | 2009-07-08T23:14:09Z | [
"python",
"regex",
"recursive-regex"
] |
Matching Nested Structures With Regular Expressions in Python | 1,099,178 | <p>I seem to remember that Regular Expressions in DotNet have a special mechanism that allows for the correct matching of nested structures, like the grouping in "<code>( (a ( ( c ) b ) ) ( d ) e )</code>". </p>
<p>What is the python equivalent of this feature? Can this be achieved using regular expressions with some workaround? (Though it seems to be the sort of problem that current implementations of regex aren't designed for)</p>
| 14 | 2009-07-08T16:30:38Z | 14,715,850 | <p><strong>Edit:</strong> <a href="http://stackoverflow.com/a/17141899/190597">falsetru's nested parser</a>, which I've slightly modified to accept arbitrary regex patterns to specify delimiters and item separators, is faster and simpler than my original <code>re.Scanner</code> solution:</p>
<pre><code>import re
def parse_nested(text, left=r'[(]', right=r'[)]', sep=r','):
""" http://stackoverflow.com/a/17141899/190597 (falsetru) """
pat = r'({}|{}|{})'.format(left, right, sep)
tokens = re.split(pat, text)
stack = [[]]
for x in tokens:
if not x or re.match(sep, x):
continue
if re.match(left, x):
# Nest a new list inside the current list
current = []
stack[-1].append(current)
stack.append(current)
elif re.match(right, x):
stack.pop()
if not stack:
raise ValueError('error: opening bracket is missing')
else:
stack[-1].append(x)
if len(stack) > 1:
print(stack)
raise ValueError('error: closing bracket is missing')
return stack.pop()
text = "a {{c1::group {{c2::containing::HINT}} a few}} {{c3::words}} or three"
print(parse_nested(text, r'\s*{{', r'}}\s*'))
</code></pre>
<p>yields</p>
<pre><code>['a', ['c1::group', ['c2::containing::HINT'], 'a few'], ['c3::words'], 'or three']
</code></pre>
<hr>
<p>Nested structures can not be matched with Python regex <em>alone</em>, but it is remarkably easy to build a basic parser (which can handle nested structures) using <a href="http://mail.python.org/pipermail/python-dev/2003-April/035075.html" rel="nofollow">re.Scanner</a>:</p>
<pre><code>import re
class Node(list):
def __init__(self, parent=None):
self.parent = parent
class NestedParser(object):
def __init__(self, left='\(', right='\)'):
self.scanner = re.Scanner([
(left, self.left),
(right, self.right),
(r"\s+", None),
(".+?(?=(%s|%s|$))" % (right, left), self.other),
])
self.result = Node()
self.current = self.result
def parse(self, content):
self.scanner.scan(content)
return self.result
def left(self, scanner, token):
new = Node(self.current)
self.current.append(new)
self.current = new
def right(self, scanner, token):
self.current = self.current.parent
def other(self, scanner, token):
self.current.append(token.strip())
</code></pre>
<p>It can be used like this:</p>
<pre><code>p = NestedParser()
print(p.parse("((a+b)*(c-d))"))
# [[['a+b'], '*', ['c-d']]]
p = NestedParser()
print(p.parse("( (a ( ( c ) b ) ) ( d ) e )"))
# [[['a', [['c'], 'b']], ['d'], 'e']]
</code></pre>
<p>By default <code>NestedParser</code> matches nested parentheses. You can pass other regex to match other nested patterns, such as brackets, <code>[]</code>. <a href="http://stackoverflow.com/questions/14712046/regex-to-extract-nested-patterns#14712046">For example</a>,</p>
<pre><code>p = NestedParser('\[', '\]')
result = (p.parse("Lorem ipsum dolor sit amet [@a xxx yyy [@b xxx yyy [@c xxx yyy]]] lorem ipsum sit amet"))
# ['Lorem ipsum dolor sit amet', ['@a xxx yyy', ['@b xxx yyy', ['@c xxx yyy']]],
# 'lorem ipsum sit amet']
p = NestedParser('<foo>', '</foo>')
print(p.parse("<foo>BAR<foo>BAZ</foo></foo>"))
# [['BAR', ['BAZ']]]
</code></pre>
<hr>
<p>Of course, <code>pyparsing</code> can do a whole lot more than the above code can. But for this single purpose, the above <code>NestedParser</code> is about 5x faster for small strings:</p>
<pre><code>In [27]: import pyparsing as pp
In [28]: data = "( (a ( ( c ) b ) ) ( d ) e )"
In [32]: %timeit pp.nestedExpr().parseString(data).asList()
1000 loops, best of 3: 1.09 ms per loop
In [33]: %timeit NestedParser().parse(data)
1000 loops, best of 3: 234 us per loop
</code></pre>
<p>and around 28x faster for larger strings:</p>
<pre><code>In [44]: %timeit pp.nestedExpr().parseString('({})'.format(data*10000)).asList()
1 loops, best of 3: 8.27 s per loop
In [45]: %timeit NestedParser().parse('({})'.format(data*10000))
1 loops, best of 3: 297 ms per loop
</code></pre>
| 13 | 2013-02-05T19:56:12Z | [
"python",
"regex",
"recursive-regex"
] |
Replacing variable with function/class indicating dynamic value | 1,099,328 | <p>In my program, I draw some quads. I want to add the functionality for them to scale up, then down, then go back to being static (to draw attention). In the quads I have:</p>
<pre><code>self.scale = 10
</code></pre>
<p>Making scale change according to sin would be nice. But adding frequency, amplitude and logic to my already bloated quad class is something I take as a challenge to avoid.</p>
<p>Something like this:</p>
<pre><code>class mysin:
def __init__(self):
self.tick = 0.0
self.freq = 1.0
self.ampl = 1.0
def update(self, amount):
self.tick += amount
def value(self):
return math.sin(self.tick)
</code></pre>
<p>That class would also add itself to the logic system (getting update calls every frame). I would then do:</p>
<pre><code>quad.scale = 10 # for static quad
quad.scale = mysin() # for cool scaling quad
</code></pre>
<p>The problem is that some calculations expect scale to hold a value. I could of course add another class where value() returns a (previously saved) constant value and adapt all the calculations.</p>
<p>What I want to know now is... does this have a name, is it a valid technique? I read the wiki article on functional programming and this idea sprung to mind as a wacky implementation (although Im not sure it qualifies as FP). I could very well have been driven mad by that article. Put me back in line fellow coders.</p>
| 2 | 2009-07-08T17:00:06Z | 1,099,347 | <p>It's sort of like <a href="http://en.wikipedia.org/wiki/Lazy%5Fevaluation" rel="nofollow">lazy-evaluation</a>. It is definitely a valid tecnique when used properly, but I don't think this is the right place to use it. It makes the code kind of confusing.</p>
| 0 | 2009-07-08T17:04:43Z | [
"python"
] |
Replacing variable with function/class indicating dynamic value | 1,099,328 | <p>In my program, I draw some quads. I want to add the functionality for them to scale up, then down, then go back to being static (to draw attention). In the quads I have:</p>
<pre><code>self.scale = 10
</code></pre>
<p>Making scale change according to sin would be nice. But adding frequency, amplitude and logic to my already bloated quad class is something I take as a challenge to avoid.</p>
<p>Something like this:</p>
<pre><code>class mysin:
def __init__(self):
self.tick = 0.0
self.freq = 1.0
self.ampl = 1.0
def update(self, amount):
self.tick += amount
def value(self):
return math.sin(self.tick)
</code></pre>
<p>That class would also add itself to the logic system (getting update calls every frame). I would then do:</p>
<pre><code>quad.scale = 10 # for static quad
quad.scale = mysin() # for cool scaling quad
</code></pre>
<p>The problem is that some calculations expect scale to hold a value. I could of course add another class where value() returns a (previously saved) constant value and adapt all the calculations.</p>
<p>What I want to know now is... does this have a name, is it a valid technique? I read the wiki article on functional programming and this idea sprung to mind as a wacky implementation (although Im not sure it qualifies as FP). I could very well have been driven mad by that article. Put me back in line fellow coders.</p>
| 2 | 2009-07-08T17:00:06Z | 1,099,382 | <p>It sure is a valid technique, but a name? Having an object.value() instead of an int? Uhm. Object orientation? :)</p>
<p>If the methods that use this value requires an integer, and won't call any method on it, you could in fact create your own integer class, that behaves exactly like an integer, but changes the value.</p>
| 0 | 2009-07-08T17:13:42Z | [
"python"
] |
Replacing variable with function/class indicating dynamic value | 1,099,328 | <p>In my program, I draw some quads. I want to add the functionality for them to scale up, then down, then go back to being static (to draw attention). In the quads I have:</p>
<pre><code>self.scale = 10
</code></pre>
<p>Making scale change according to sin would be nice. But adding frequency, amplitude and logic to my already bloated quad class is something I take as a challenge to avoid.</p>
<p>Something like this:</p>
<pre><code>class mysin:
def __init__(self):
self.tick = 0.0
self.freq = 1.0
self.ampl = 1.0
def update(self, amount):
self.tick += amount
def value(self):
return math.sin(self.tick)
</code></pre>
<p>That class would also add itself to the logic system (getting update calls every frame). I would then do:</p>
<pre><code>quad.scale = 10 # for static quad
quad.scale = mysin() # for cool scaling quad
</code></pre>
<p>The problem is that some calculations expect scale to hold a value. I could of course add another class where value() returns a (previously saved) constant value and adapt all the calculations.</p>
<p>What I want to know now is... does this have a name, is it a valid technique? I read the wiki article on functional programming and this idea sprung to mind as a wacky implementation (although Im not sure it qualifies as FP). I could very well have been driven mad by that article. Put me back in line fellow coders.</p>
| 2 | 2009-07-08T17:00:06Z | 1,099,392 | <p>The distinction between</p>
<pre><code>quad.scale= 10
</code></pre>
<p>and</p>
<pre><code>quad.scale= MySin()
</code></pre>
<p>Is minor. Within the <code>Quad</code> class definition the "scale" attribute can be a property with proper getter and setter functions.</p>
<pre><code>class Quad( object ):
@property
def scale( self ):
return self._scale
@scale.setter
def set_scale( self, value ):
# handle numeric and MySin() values appropriately.
</code></pre>
<p>Alternate version with the explicit <code>property</code> function (which I prefer).</p>
<pre><code>class Quad( object ):
def get_scale( self ):
return self._scale
def set_scale( self, value )
# Handle numeric and MySin() values
scale = property( get_scale, set_scale )
</code></pre>
<p>Any other class should NOT know or care what type of value <code>scale</code> has. If some client does this</p>
<pre><code>quad.scale * 2
</code></pre>
<p>Then you have design issues. You haven't properly encapsulated your design and Quad's client classes are too friendly with Quad. </p>
<p>If you absolutely must do this -- because you can't write a method function of Quad to encapsulate this -- then you have to make <code>MySin</code> a proper numeric class so it can respond to <code>quad.scale * 2</code> requests properly.</p>
| 4 | 2009-07-08T17:15:04Z | [
"python"
] |
Replacing variable with function/class indicating dynamic value | 1,099,328 | <p>In my program, I draw some quads. I want to add the functionality for them to scale up, then down, then go back to being static (to draw attention). In the quads I have:</p>
<pre><code>self.scale = 10
</code></pre>
<p>Making scale change according to sin would be nice. But adding frequency, amplitude and logic to my already bloated quad class is something I take as a challenge to avoid.</p>
<p>Something like this:</p>
<pre><code>class mysin:
def __init__(self):
self.tick = 0.0
self.freq = 1.0
self.ampl = 1.0
def update(self, amount):
self.tick += amount
def value(self):
return math.sin(self.tick)
</code></pre>
<p>That class would also add itself to the logic system (getting update calls every frame). I would then do:</p>
<pre><code>quad.scale = 10 # for static quad
quad.scale = mysin() # for cool scaling quad
</code></pre>
<p>The problem is that some calculations expect scale to hold a value. I could of course add another class where value() returns a (previously saved) constant value and adapt all the calculations.</p>
<p>What I want to know now is... does this have a name, is it a valid technique? I read the wiki article on functional programming and this idea sprung to mind as a wacky implementation (although Im not sure it qualifies as FP). I could very well have been driven mad by that article. Put me back in line fellow coders.</p>
| 2 | 2009-07-08T17:00:06Z | 1,099,414 | <p>It sounds like you want your quads to be dumb, and to have an animator class which is smart. So,here are some suggestions:</p>
<ol>
<li>Give the quads an attribute which indicates how to animate them (in addition to the <code>scale</code> and whatever else).</li>
<li>In an <code>Animator</code> class, on a frame update, iterate over your quads and decide how to treat each one, based on that attribute.</li>
<li>In the treatment of a quad, update the scale property of each dynamically changing quad to the appropriate float value. For static quads it never changes, for dynamic ones it changes based on any algorithm you like.</li>
</ol>
<p>One advantage this approach is that it allows you to vary different attributes (scale, opacity, fill colour ... you name it) while keeping the logic in the animator.</p>
| 1 | 2009-07-08T17:18:41Z | [
"python"
] |
Why can't Python find shared objects that are in directories in sys.path? | 1,099,981 | <p>I'm trying to import pycurl:</p>
<pre><code>$ python -c "import pycurl"
Traceback (most recent call last):
File "<string>", line 1, in <module>
ImportError: libcurl.so.4: cannot open shared object file: No such file or directory
</code></pre>
<p>Now, libcurl.so.4 is in /usr/local/lib. As you can see, this is in sys.path:</p>
<pre><code>$ python -c "import sys; print sys.path"
['', '/usr/local/lib/python2.5/site-packages/setuptools-0.6c9-py2.5.egg',
'/usr/local/lib/python25.zip', '/usr/local/lib/python2.5',
'/usr/local/lib/python2.5/plat-linux2', '/usr/local/lib/python2.5/lib-tk',
'/usr/local/lib/python2.5/lib-dynload',
'/usr/local/lib/python2.5/sitepackages', '/usr/local/lib',
'/usr/local/lib/python2.5/site-packages']
</code></pre>
<p>Any help will be greatly appreciated.</p>
| 72 | 2009-07-08T19:06:17Z | 1,100,016 | <p><code>sys.path</code> is only searched for Python modules. For dynamic linked libraries, the paths searched must be in <code>LD_LIBRARY_PATH</code>. Check if your <code>LD_LIBRARY_PATH</code> includes <code>/usr/local/lib</code>, and if it doesn't, add it and try again.</p>
<p>Some more information (<a href="http://tldp.org/HOWTO/Program-Library-HOWTO/shared-libraries.html">source</a>):</p>
<blockquote>
<p>In Linux, the environment variable
LD_LIBRARY_PATH is a colon-separated
set of directories where libraries
should be searched for first, before
the standard set of directories; this
is useful when debugging a new library
or using a nonstandard library for
special purposes. The environment
variable LD_PRELOAD lists shared
libraries with functions that override
the standard set, just as
/etc/ld.so.preload does. These are
implemented by the loader
/lib/ld-linux.so. I should note that,
while LD_LIBRARY_PATH works on many
Unix-like systems, it doesn't work on
all; for example, this functionality
is available on HP-UX but as the
environment variable SHLIB_PATH, and
on AIX this functionality is through
the variable LIBPATH (with the same
syntax, a colon-separated list).</p>
</blockquote>
<p><strong>Update:</strong> to set <code>LD_LIBRARY_PATH</code>, use one of the following, ideally in your <code>~/.bashrc</code>
or equivalent file:</p>
<pre><code>export LD_LIBRARY_PATH=/usr/local/lib
</code></pre>
<p>or</p>
<pre><code>export LD_LIBRARY_PATH=/usr/local/lib:$LD_LIBRARY_PATH
</code></pre>
<p>Use the first form if it's empty (equivalent to the empty string, or not present at all), and the second form if it isn't. Note the use of <em>export</em>.</p>
| 97 | 2009-07-08T19:12:33Z | [
"python",
"shared-libraries",
"libcurl",
"pycurl"
] |
Why can't Python find shared objects that are in directories in sys.path? | 1,099,981 | <p>I'm trying to import pycurl:</p>
<pre><code>$ python -c "import pycurl"
Traceback (most recent call last):
File "<string>", line 1, in <module>
ImportError: libcurl.so.4: cannot open shared object file: No such file or directory
</code></pre>
<p>Now, libcurl.so.4 is in /usr/local/lib. As you can see, this is in sys.path:</p>
<pre><code>$ python -c "import sys; print sys.path"
['', '/usr/local/lib/python2.5/site-packages/setuptools-0.6c9-py2.5.egg',
'/usr/local/lib/python25.zip', '/usr/local/lib/python2.5',
'/usr/local/lib/python2.5/plat-linux2', '/usr/local/lib/python2.5/lib-tk',
'/usr/local/lib/python2.5/lib-dynload',
'/usr/local/lib/python2.5/sitepackages', '/usr/local/lib',
'/usr/local/lib/python2.5/site-packages']
</code></pre>
<p>Any help will be greatly appreciated.</p>
| 72 | 2009-07-08T19:06:17Z | 1,100,297 | <p>Ensure your libcurl.so module is in the system library path, which is distinct and separate from the python library path.</p>
<p>A "quick fix" is to add this path to a LD_LIBRARY_PATH variable. However, setting that system wide (or even account wide) is a BAD IDEA, as it is possible to set it in such a way that some programs will find a library it shouldn't, or even worse, open up security holes.</p>
<p>If your "locally installed libraries" are installed in, for example, /usr/local/lib, add this directory to /etc/ld.so.conf (it's a text file) and run "ldconfig"</p>
<p>The command will run a caching utility, but will also create all the necessary "symbolic links" required for the loader system to function. It is surprising that the "make install" for libcurl did not do this already, but it's possible it could not if /usr/local/lib is not in /etc/ld.so.conf already.</p>
<p>PS: it's possible that your /etc/ld.so.conf contains nothing but "include ld.so.conf.d/*.conf". You can still add a directory path after it, or just create a new file inside the directory it's being included from. Dont forget to run "ldconfig" after it.</p>
<p>Be careful. Getting this wrong can screw up your system. </p>
<p>Additionally: make sure your python module is compiled against THAT version of libcurl. If you just copied some files over from another system, this wont always work. If in doubt, compile your modules on the system you intend to run them on.</p>
| 41 | 2009-07-08T20:13:10Z | [
"python",
"shared-libraries",
"libcurl",
"pycurl"
] |
Why can't Python find shared objects that are in directories in sys.path? | 1,099,981 | <p>I'm trying to import pycurl:</p>
<pre><code>$ python -c "import pycurl"
Traceback (most recent call last):
File "<string>", line 1, in <module>
ImportError: libcurl.so.4: cannot open shared object file: No such file or directory
</code></pre>
<p>Now, libcurl.so.4 is in /usr/local/lib. As you can see, this is in sys.path:</p>
<pre><code>$ python -c "import sys; print sys.path"
['', '/usr/local/lib/python2.5/site-packages/setuptools-0.6c9-py2.5.egg',
'/usr/local/lib/python25.zip', '/usr/local/lib/python2.5',
'/usr/local/lib/python2.5/plat-linux2', '/usr/local/lib/python2.5/lib-tk',
'/usr/local/lib/python2.5/lib-dynload',
'/usr/local/lib/python2.5/sitepackages', '/usr/local/lib',
'/usr/local/lib/python2.5/site-packages']
</code></pre>
<p>Any help will be greatly appreciated.</p>
| 72 | 2009-07-08T19:06:17Z | 1,109,196 | <p>You can also set LD_RUN_PATH to /usr/local/lib in your user environment when you compile pycurl in the first place. This will embed /usr/local/lib in the RPATH attribute of the C extension module .so so that it automatically knows where to find the library at run time without having to have LD_LIBRARY_PATH set at run time.</p>
| 19 | 2009-07-10T12:17:02Z | [
"python",
"shared-libraries",
"libcurl",
"pycurl"
] |
Why can't Python find shared objects that are in directories in sys.path? | 1,099,981 | <p>I'm trying to import pycurl:</p>
<pre><code>$ python -c "import pycurl"
Traceback (most recent call last):
File "<string>", line 1, in <module>
ImportError: libcurl.so.4: cannot open shared object file: No such file or directory
</code></pre>
<p>Now, libcurl.so.4 is in /usr/local/lib. As you can see, this is in sys.path:</p>
<pre><code>$ python -c "import sys; print sys.path"
['', '/usr/local/lib/python2.5/site-packages/setuptools-0.6c9-py2.5.egg',
'/usr/local/lib/python25.zip', '/usr/local/lib/python2.5',
'/usr/local/lib/python2.5/plat-linux2', '/usr/local/lib/python2.5/lib-tk',
'/usr/local/lib/python2.5/lib-dynload',
'/usr/local/lib/python2.5/sitepackages', '/usr/local/lib',
'/usr/local/lib/python2.5/site-packages']
</code></pre>
<p>Any help will be greatly appreciated.</p>
| 72 | 2009-07-08T19:06:17Z | 2,384,146 | <p>Had the exact same issue. I installed curl 7.19 to /opt/curl/ to make sure that I would not affect current curl on our production servers.
Once I linked libcurl.so.4 to /usr/lib:</p>
<p>sudo ln -s /opt/curl/lib/libcurl.so /usr/lib/libcurl.so.4</p>
<p>I still got the same error! Durf.</p>
<p>But running ldconfig make the linkage for me and that worked. No need to set the LD_RUN_PATH or LD_LIBRARY_PATH at all. Just needed to run ldconfig.</p>
| 8 | 2010-03-05T02:18:08Z | [
"python",
"shared-libraries",
"libcurl",
"pycurl"
] |
Why can't Python find shared objects that are in directories in sys.path? | 1,099,981 | <p>I'm trying to import pycurl:</p>
<pre><code>$ python -c "import pycurl"
Traceback (most recent call last):
File "<string>", line 1, in <module>
ImportError: libcurl.so.4: cannot open shared object file: No such file or directory
</code></pre>
<p>Now, libcurl.so.4 is in /usr/local/lib. As you can see, this is in sys.path:</p>
<pre><code>$ python -c "import sys; print sys.path"
['', '/usr/local/lib/python2.5/site-packages/setuptools-0.6c9-py2.5.egg',
'/usr/local/lib/python25.zip', '/usr/local/lib/python2.5',
'/usr/local/lib/python2.5/plat-linux2', '/usr/local/lib/python2.5/lib-tk',
'/usr/local/lib/python2.5/lib-dynload',
'/usr/local/lib/python2.5/sitepackages', '/usr/local/lib',
'/usr/local/lib/python2.5/site-packages']
</code></pre>
<p>Any help will be greatly appreciated.</p>
| 72 | 2009-07-08T19:06:17Z | 10,986,298 | <p>As a supplement to above answers - I'm just bumping into a similar problem, and working completely of the default installed python. </p>
<p>When I call the example of the shared object library I'm looking for with <code>LD_LIBRARY_PATH</code>, I get something like this: </p>
<pre><code>$ LD_LIBRARY_PATH=/path/to/mysodir:$LD_LIBRARY_PATH python example-so-user.py
python: can't open file 'example-so-user.py': [Errno 2] No such file or directory
</code></pre>
<p>Notably, it doesn't even complain about the import - it complains about the source file!</p>
<p>But if I force loading of the object using <code>LD_PRELOAD</code>:</p>
<pre><code>$ LD_PRELOAD=/path/to/mysodir/mypyobj.so python example-so-user.py
python: error while loading shared libraries: libtiff.so.5: cannot open shared object file: No such file or directory
</code></pre>
<p>... I immediately get a more meaningful error message - about a missing dependency!</p>
<p>Just thought I'd jot this down here - cheers!</p>
| 6 | 2012-06-11T19:26:55Z | [
"python",
"shared-libraries",
"libcurl",
"pycurl"
] |
Why can't Python find shared objects that are in directories in sys.path? | 1,099,981 | <p>I'm trying to import pycurl:</p>
<pre><code>$ python -c "import pycurl"
Traceback (most recent call last):
File "<string>", line 1, in <module>
ImportError: libcurl.so.4: cannot open shared object file: No such file or directory
</code></pre>
<p>Now, libcurl.so.4 is in /usr/local/lib. As you can see, this is in sys.path:</p>
<pre><code>$ python -c "import sys; print sys.path"
['', '/usr/local/lib/python2.5/site-packages/setuptools-0.6c9-py2.5.egg',
'/usr/local/lib/python25.zip', '/usr/local/lib/python2.5',
'/usr/local/lib/python2.5/plat-linux2', '/usr/local/lib/python2.5/lib-tk',
'/usr/local/lib/python2.5/lib-dynload',
'/usr/local/lib/python2.5/sitepackages', '/usr/local/lib',
'/usr/local/lib/python2.5/site-packages']
</code></pre>
<p>Any help will be greatly appreciated.</p>
| 72 | 2009-07-08T19:06:17Z | 36,791,034 | <p>I use <code>python setup.py build_ext -R/usr/local/lib -I/usr/local/include/libcalg-1.0</code> and the compiled .so file is under the build folder.
you can type <code>python setup.py --help build_ext</code> to see the explanations of -R and -I</p>
| 0 | 2016-04-22T10:16:21Z | [
"python",
"shared-libraries",
"libcurl",
"pycurl"
] |
how to fix or make an exception for this error | 1,100,029 | <p>I'm creating a code that gets image's urls from any web pages, the code are in python and use BeutifulSoup and httplib2.
When I run the code, I get the next error:</p>
<pre><code>Look me http://movies.nytimes.com (this line is printed by the code)
Traceback (most recent call last):
File "main.py", line 103, in <module>
visit(initialList,profundidad)
File "main.py", line 98, in visit
visit(dodo[indice], bottom -1)
File "main.py", line 94, in visit
getImages(w)
File "main.py", line 34, in getImages
iSoupList = BeautifulSoup(response, parseOnlyThese=SoupStrainer('img'))
File "/usr/local/lib/python2.6/dist-packages/BeautifulSoup.py", line 1499, in __init__
BeautifulStoneSoup.__init__(self, *args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/BeautifulSoup.py", line 1230, in __init__
self._feed(isHTML=isHTML)
File "/usr/local/lib/python2.6/dist-packages/BeautifulSoup.py", line 1263, in _feed
self.builder.feed(markup)
File "/usr/lib/python2.6/HTMLParser.py", line 108, in feed
self.goahead(0)
File "/usr/lib/python2.6/HTMLParser.py", line 148, in goahead
k = self.parse_starttag(i)
File "/usr/lib/python2.6/HTMLParser.py", line 226, in parse_starttag
endpos = self.check_for_whole_start_tag(i)
File "/usr/lib/python2.6/HTMLParser.py", line 301, in check_for_whole_start_tag
self.error("malformed start tag")
File "/usr/lib/python2.6/HTMLParser.py", line 115, in error
raise HTMLParseError(message, self.getpos())
HTMLParser.HTMLParseError: malformed start tag, at line 942, column 118
</code></pre>
<p>Someone can explain me how to fix or make an exeption for the error</p>
| 1 | 2009-07-08T19:15:58Z | 1,100,047 | <p>To catch that error specifically, change your code to look like this:</p>
<pre><code>try:
iSoupList = BeautifulSoup(response, parseOnlyThese=SoupStrainer('img'))
except HTMLParseError:
#Do something intelligent here
</code></pre>
<p>Here's some more reading on Python's try except blocks:
<a href="http://docs.python.org/tutorial/errors.html" rel="nofollow">http://docs.python.org/tutorial/errors.html</a></p>
| 2 | 2009-07-08T19:20:53Z | [
"python",
"beautifulsoup",
"httplib2"
] |
how to fix or make an exception for this error | 1,100,029 | <p>I'm creating a code that gets image's urls from any web pages, the code are in python and use BeutifulSoup and httplib2.
When I run the code, I get the next error:</p>
<pre><code>Look me http://movies.nytimes.com (this line is printed by the code)
Traceback (most recent call last):
File "main.py", line 103, in <module>
visit(initialList,profundidad)
File "main.py", line 98, in visit
visit(dodo[indice], bottom -1)
File "main.py", line 94, in visit
getImages(w)
File "main.py", line 34, in getImages
iSoupList = BeautifulSoup(response, parseOnlyThese=SoupStrainer('img'))
File "/usr/local/lib/python2.6/dist-packages/BeautifulSoup.py", line 1499, in __init__
BeautifulStoneSoup.__init__(self, *args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/BeautifulSoup.py", line 1230, in __init__
self._feed(isHTML=isHTML)
File "/usr/local/lib/python2.6/dist-packages/BeautifulSoup.py", line 1263, in _feed
self.builder.feed(markup)
File "/usr/lib/python2.6/HTMLParser.py", line 108, in feed
self.goahead(0)
File "/usr/lib/python2.6/HTMLParser.py", line 148, in goahead
k = self.parse_starttag(i)
File "/usr/lib/python2.6/HTMLParser.py", line 226, in parse_starttag
endpos = self.check_for_whole_start_tag(i)
File "/usr/lib/python2.6/HTMLParser.py", line 301, in check_for_whole_start_tag
self.error("malformed start tag")
File "/usr/lib/python2.6/HTMLParser.py", line 115, in error
raise HTMLParseError(message, self.getpos())
HTMLParser.HTMLParseError: malformed start tag, at line 942, column 118
</code></pre>
<p>Someone can explain me how to fix or make an exeption for the error</p>
| 1 | 2009-07-08T19:15:58Z | 1,100,462 | <p>Are you using latest version of BeautifulSoup?<br />
This seems a known issue of version 3.1.x, because it started using a new parser (HTMLParser, instead of SGMLParser) that is much worse at processing malformed HTML. You can find more information about this on <a href="http://www.crummy.com/software/BeautifulSoup/3.1-problems.html" rel="nofollow">BeautifulSoup website</a>.<br />
As a quick solution, you can simply use an older version (<a href="http://www.crummy.com/software/BeautifulSoup/download/3.x/BeautifulSoup-3.0.7a.tar.gz" rel="nofollow">3.0.7a</a>).</p>
| 4 | 2009-07-08T20:46:06Z | [
"python",
"beautifulsoup",
"httplib2"
] |
how to fix or make an exception for this error | 1,100,029 | <p>I'm creating a code that gets image's urls from any web pages, the code are in python and use BeutifulSoup and httplib2.
When I run the code, I get the next error:</p>
<pre><code>Look me http://movies.nytimes.com (this line is printed by the code)
Traceback (most recent call last):
File "main.py", line 103, in <module>
visit(initialList,profundidad)
File "main.py", line 98, in visit
visit(dodo[indice], bottom -1)
File "main.py", line 94, in visit
getImages(w)
File "main.py", line 34, in getImages
iSoupList = BeautifulSoup(response, parseOnlyThese=SoupStrainer('img'))
File "/usr/local/lib/python2.6/dist-packages/BeautifulSoup.py", line 1499, in __init__
BeautifulStoneSoup.__init__(self, *args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/BeautifulSoup.py", line 1230, in __init__
self._feed(isHTML=isHTML)
File "/usr/local/lib/python2.6/dist-packages/BeautifulSoup.py", line 1263, in _feed
self.builder.feed(markup)
File "/usr/lib/python2.6/HTMLParser.py", line 108, in feed
self.goahead(0)
File "/usr/lib/python2.6/HTMLParser.py", line 148, in goahead
k = self.parse_starttag(i)
File "/usr/lib/python2.6/HTMLParser.py", line 226, in parse_starttag
endpos = self.check_for_whole_start_tag(i)
File "/usr/lib/python2.6/HTMLParser.py", line 301, in check_for_whole_start_tag
self.error("malformed start tag")
File "/usr/lib/python2.6/HTMLParser.py", line 115, in error
raise HTMLParseError(message, self.getpos())
HTMLParser.HTMLParseError: malformed start tag, at line 942, column 118
</code></pre>
<p>Someone can explain me how to fix or make an exeption for the error</p>
| 1 | 2009-07-08T19:15:58Z | 1,843,482 | <p>I got that error when I had the string <strong>=&</strong> in my HTML document. When I replaced that string (in my case with <strong>=and</strong>) then I no longer received that parsing error.</p>
| 0 | 2009-12-03T22:34:07Z | [
"python",
"beautifulsoup",
"httplib2"
] |
FFT-based 2D convolution and correlation in Python | 1,100,100 | <p>Is there a FFT-based 2D cross-correlation or convolution function built into scipy (or another popular library)?</p>
<p>There are functions like these:</p>
<ul>
<li><code>scipy.signal.correlate2d</code> - "the direct method implemented by <code>convolveND</code> will be
slow for large data"</li>
<li><code>scipy.ndimage.correlate</code> - "The array is correlated with the given kernel using
exact calculation (i.e. not FFT)."</li>
<li><code>scipy.fftpack.convolve.convolve</code>, which I don't really understand, but seems wrong</li>
</ul>
<p>numarray had a <a href="http://structure.usc.edu/numarray/node61.html" rel="nofollow"><code>correlate2d()</code> function with an <code>fft=True</code> switch</a>, but I guess numarray was folded
into numpy, and I can't find if this function was included.</p>
| 19 | 2009-07-08T19:32:19Z | 1,100,281 | <p>I think you want the scipy.stsci package:</p>
<p><a href="http://docs.scipy.org/doc/scipy/reference/stsci.html" rel="nofollow">http://docs.scipy.org/doc/scipy/reference/stsci.html</a></p>
<pre><code>In [30]: scipy.__version__
Out[30]: '0.7.0'
In [31]: from scipy.stsci.convolve import convolve2d, correlate2d
</code></pre>
| 4 | 2009-07-08T20:07:59Z | [
"python",
"image",
"numpy",
"signal-processing",
"fft"
] |
FFT-based 2D convolution and correlation in Python | 1,100,100 | <p>Is there a FFT-based 2D cross-correlation or convolution function built into scipy (or another popular library)?</p>
<p>There are functions like these:</p>
<ul>
<li><code>scipy.signal.correlate2d</code> - "the direct method implemented by <code>convolveND</code> will be
slow for large data"</li>
<li><code>scipy.ndimage.correlate</code> - "The array is correlated with the given kernel using
exact calculation (i.e. not FFT)."</li>
<li><code>scipy.fftpack.convolve.convolve</code>, which I don't really understand, but seems wrong</li>
</ul>
<p>numarray had a <a href="http://structure.usc.edu/numarray/node61.html" rel="nofollow"><code>correlate2d()</code> function with an <code>fft=True</code> switch</a>, but I guess numarray was folded
into numpy, and I can't find if this function was included.</p>
| 19 | 2009-07-08T19:32:19Z | 1,101,764 | <p>I've lost track of the status of this package in scipy, but I know we include ndimage as part of the stsci_python release package as a convenience for our users:</p>
<p><a href="http://www.stsci.edu/resources/software_hardware/pyraf/stsci_python/current/download" rel="nofollow">http://www.stsci.edu/resources/software_hardware/pyraf/stsci_python/current/download</a></p>
<p>or you should be able pull it from the repository if you prefer:</p>
<p><a href="https://www.stsci.edu/svn/ssb/stsci_python/stsci_python/trunk/ndimage/" rel="nofollow">https://www.stsci.edu/svn/ssb/stsci_python/stsci_python/trunk/ndimage/</a></p>
| 2 | 2009-07-09T03:53:20Z | [
"python",
"image",
"numpy",
"signal-processing",
"fft"
] |
FFT-based 2D convolution and correlation in Python | 1,100,100 | <p>Is there a FFT-based 2D cross-correlation or convolution function built into scipy (or another popular library)?</p>
<p>There are functions like these:</p>
<ul>
<li><code>scipy.signal.correlate2d</code> - "the direct method implemented by <code>convolveND</code> will be
slow for large data"</li>
<li><code>scipy.ndimage.correlate</code> - "The array is correlated with the given kernel using
exact calculation (i.e. not FFT)."</li>
<li><code>scipy.fftpack.convolve.convolve</code>, which I don't really understand, but seems wrong</li>
</ul>
<p>numarray had a <a href="http://structure.usc.edu/numarray/node61.html" rel="nofollow"><code>correlate2d()</code> function with an <code>fft=True</code> switch</a>, but I guess numarray was folded
into numpy, and I can't find if this function was included.</p>
| 19 | 2009-07-08T19:32:19Z | 1,477,259 | <p>look at scipy.signal.fftconvolve, signal.convolve and signal.correlate (there is a signal.correlate2d but it seems to return an shifted array, not centered).</p>
| 6 | 2009-09-25T13:22:24Z | [
"python",
"image",
"numpy",
"signal-processing",
"fft"
] |
FFT-based 2D convolution and correlation in Python | 1,100,100 | <p>Is there a FFT-based 2D cross-correlation or convolution function built into scipy (or another popular library)?</p>
<p>There are functions like these:</p>
<ul>
<li><code>scipy.signal.correlate2d</code> - "the direct method implemented by <code>convolveND</code> will be
slow for large data"</li>
<li><code>scipy.ndimage.correlate</code> - "The array is correlated with the given kernel using
exact calculation (i.e. not FFT)."</li>
<li><code>scipy.fftpack.convolve.convolve</code>, which I don't really understand, but seems wrong</li>
</ul>
<p>numarray had a <a href="http://structure.usc.edu/numarray/node61.html" rel="nofollow"><code>correlate2d()</code> function with an <code>fft=True</code> switch</a>, but I guess numarray was folded
into numpy, and I can't find if this function was included.</p>
| 19 | 2009-07-08T19:32:19Z | 1,768,140 | <p>I found <code>scipy.signal.fftconvolve</code>, <a href="http://stackoverflow.com/a/1477259/125507">as also pointed out by magnus</a>, but didn't realize at the time that it's <em>n</em>-dimensional. Since it's built-in and produces the right values, it seems like the ideal solution.</p>
<p>From <a href="http://www.songho.ca/dsp/convolution/convolution2d_example.html">Example of 2D Convolution</a>:</p>
<pre><code>In [1]: a = asarray([[ 1, 2, 3],
...: [ 4, 5, 6],
...: [ 7, 8, 9]])
In [2]: b = asarray([[-1,-2,-1],
...: [ 0, 0, 0],
...: [ 1, 2, 1]])
In [3]: scipy.signal.fftconvolve(a, b, mode = 'same')
Out[3]:
array([[-13., -20., -17.],
[-18., -24., -18.],
[ 13., 20., 17.]])
</code></pre>
<p>Correct! The STSCI version, on the other hand, requires some extra work to make the boundaries correct?</p>
<pre><code>In [4]: stsci.convolve2d(a, b, fft = True)
Out[4]:
array([[-12., -12., -12.],
[-24., -24., -24.],
[-12., -12., -12.]])
</code></pre>
<p>(The STSCI method also requires compiling, which I was unsuccessful with (I just commented out the non-python parts), has some bugs like <a href="http://projects.scipy.org/scipy/ticket/973">this</a> and modifying the inputs ([1, 2] becomes [[1, 2]]), etc. So I changed my accepted answer to the built-in <code>fftconvolve()</code> function.)</p>
<p>Correlation, of course, is the same thing as convolution, but with one input reversed:</p>
<pre><code>In [5]: a
Out[5]:
array([[3, 0, 0],
[2, 0, 0],
[1, 0, 0]])
In [6]: b
Out[6]:
array([[3, 2, 1],
[0, 0, 0],
[0, 0, 0]])
In [7]: scipy.signal.fftconvolve(a, b[::-1, ::-1])
Out[7]:
array([[ 0., -0., 0., 0., 0.],
[ 0., -0., 0., 0., 0.],
[ 3., 6., 9., 0., 0.],
[ 2., 4., 6., 0., 0.],
[ 1., 2., 3., 0., 0.]])
In [8]: scipy.signal.correlate2d(a, b)
Out[8]:
array([[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[3, 6, 9, 0, 0],
[2, 4, 6, 0, 0],
[1, 2, 3, 0, 0]])
</code></pre>
<p>and <a href="http://projects.scipy.org/scipy/browser/trunk/scipy/signal/signaltools.py?rev=5968">the latest revision</a> has been sped up by using power-of-two sizes internally (and then I sped it up more by <a href="https://github.com/scipy/scipy/pull/337">using real FFT for real input</a> and <a href="https://github.com/scipy/scipy/pull/3144">using 5-smooth lengths instead of powers of 2</a> :D ).</p>
| 15 | 2009-11-20T03:22:54Z | [
"python",
"image",
"numpy",
"signal-processing",
"fft"
] |
FFT-based 2D convolution and correlation in Python | 1,100,100 | <p>Is there a FFT-based 2D cross-correlation or convolution function built into scipy (or another popular library)?</p>
<p>There are functions like these:</p>
<ul>
<li><code>scipy.signal.correlate2d</code> - "the direct method implemented by <code>convolveND</code> will be
slow for large data"</li>
<li><code>scipy.ndimage.correlate</code> - "The array is correlated with the given kernel using
exact calculation (i.e. not FFT)."</li>
<li><code>scipy.fftpack.convolve.convolve</code>, which I don't really understand, but seems wrong</li>
</ul>
<p>numarray had a <a href="http://structure.usc.edu/numarray/node61.html" rel="nofollow"><code>correlate2d()</code> function with an <code>fft=True</code> switch</a>, but I guess numarray was folded
into numpy, and I can't find if this function was included.</p>
| 19 | 2009-07-08T19:32:19Z | 8,454,010 | <p>I wrote a cross-correlation/convolution wrapper that takes care of padding & nans and includes a simple smooth wrapper <a href="http://code.google.com/p/agpy/source/browse/trunk/AG_fft_tools/convolve_nd.py" rel="nofollow">here</a>. It's not a popular package, but it also has no dependencies besides numpy (or fftw for faster ffts).</p>
<p>I've also implemented an FFT speed testing code <a href="http://code.google.com/p/agpy/source/browse/trunk/tests/test_ffts.py" rel="nofollow">here</a> in case anyone's interested. It shows - surprisingly - that numpy's fft is faster than scipy's, at least on my machine.</p>
<p>EDIT: moved code to N-dimensional version <a href="http://code.google.com/p/agpy/source/browse/trunk/AG_fft_tools/convolve_nd.py" rel="nofollow">here</a></p>
| 2 | 2011-12-10T02:45:41Z | [
"python",
"image",
"numpy",
"signal-processing",
"fft"
] |
How to properly do one-to-many joins on an (Python) Google App Engine datasource? | 1,100,472 | <p>I have some models set up like:</p>
<pre><code>class Apps(db.Model):
name = db.StringProperty(multiline=False)
description = db.TextProperty()
class AppScreenshots(db.Model):
image_file = db.StringProperty(multiline=False)
description = db.StringProperty(multiline=False)
app = db.ReferenceProperty(Apps)
</code></pre>
<p>I'm trying to reference a "parent" app in a screenshot like so:</p>
<pre><code>a = Apps.get(app_key)
ss = AppScreenshots(
image_file = 'foo',
description = 'bar',
app = a
)
ss.put()
</code></pre>
<p>But it complains to me saying:</p>
<pre><code>BadArgumentError('_app should be a string; received ag1raWxsZXItcm9ib3RzcgoLEgRBcHBzGAkM (a Key):',)
</code></pre>
<p>I've tried going over a few examples on the internet and they all seem to work JUST like the above. One <a href="http://code.google.com/appengine/docs/python/datastore/entitiesandmodels.html#References" rel="nofollow">set of documentation</a> Google has up suggests doing it a little differently, like this:</p>
<pre><code>a = Apps.get(app_key)
ss = AppScreenshots(
image_file = 'foo',
description = 'bar',
app = a.key()
)
ss.put()
</code></pre>
<p>But that gives me the exact same error.</p>
<p>What am I doing wrong? </p>
| 2 | 2009-07-08T20:48:13Z | 1,101,289 | <p>The problem I found when trying to run your code was that apparently you need to change the name of 'app' in AppScreenshots to something else such as 'apps'. The word 'app' must be reserved in this context.</p>
<p>Try this Query instead. You could do .filter() too on this if you don't want the first entity.</p>
<pre><code>class AppScreenshots(db.Model):
image_file = db.StringProperty()
description = db.StringProperty()
apps = db.ReferenceProperty(Apps)
appsObject = db.Query(Apps).get()
ss = AppScreenshots(image_file = 'foo', description = 'bar',apps = appsObject)
</code></pre>
<p>Here is a helpful article on modeling relationships <a href="http://code.google.com/appengine/articles/modeling.html" rel="nofollow">link</a>.</p>
<p>Also a related question <a href="http://stackoverflow.com/questions/1088678/app-engine-db-model-reference-question/1089470#1089470">here on SO</a></p>
| 5 | 2009-07-09T00:49:44Z | [
"python",
"google-app-engine",
"gql"
] |
Create PyQt menu from a list of strings | 1,100,775 | <p>I have a list of strings and want to create a menu entry for each of those strings. When the user clicks on one of the entries, always the same function shall be called with the string as an argument. After some trying and research I came up with something like this:</p>
<pre><code>import sys
from PyQt4 import QtGui, QtCore
class MainWindow(QtGui.QMainWindow):
def __init__(self):
QtGui.QMainWindow.__init__(self)
self.menubar = self.menuBar()
menuitems = ["Item 1","Item 2","Item 3"]
menu = self.menubar.addMenu('&Stuff')
for item in menuitems:
entry = menu.addAction(item)
self.connect(entry,QtCore.SIGNAL('triggered()'), lambda: self.doStuff(item))
menu.addAction(entry)
print "init done"
def doStuff(self, item):
print item
app = QtGui.QApplication(sys.argv)
main = MainWindow()
main.show()
sys.exit(app.exec_())
</code></pre>
<p>Now the problem is that each of the menu items will print the same output: "Item 3" instead of the corresponding one. I'm thankful for any ideas about how I can get this right. Thanks.</p>
| 10 | 2009-07-08T22:01:56Z | 1,100,828 | <p>This should work, but I'm pretty sure there was a better way that I can't recall right now.</p>
<pre><code>def do_stuff_caller(self, item):
return lambda: self.doStuff(item)
...
self.connect(entry, QtCore.SIGNAL('triggered()'), self.do_stuff_caller(item))
</code></pre>
<p><strong>Edit</strong>:
Shorter version, that still isn't what I'm thinking about... or maybe it was in another language? :)</p>
<pre><code>(lambda x: lambda self.do_stuff(x))(item)</code></pre>
| 2 | 2009-07-08T22:13:07Z | [
"python",
"qt",
"pyqt",
"signals-slots"
] |
Create PyQt menu from a list of strings | 1,100,775 | <p>I have a list of strings and want to create a menu entry for each of those strings. When the user clicks on one of the entries, always the same function shall be called with the string as an argument. After some trying and research I came up with something like this:</p>
<pre><code>import sys
from PyQt4 import QtGui, QtCore
class MainWindow(QtGui.QMainWindow):
def __init__(self):
QtGui.QMainWindow.__init__(self)
self.menubar = self.menuBar()
menuitems = ["Item 1","Item 2","Item 3"]
menu = self.menubar.addMenu('&Stuff')
for item in menuitems:
entry = menu.addAction(item)
self.connect(entry,QtCore.SIGNAL('triggered()'), lambda: self.doStuff(item))
menu.addAction(entry)
print "init done"
def doStuff(self, item):
print item
app = QtGui.QApplication(sys.argv)
main = MainWindow()
main.show()
sys.exit(app.exec_())
</code></pre>
<p>Now the problem is that each of the menu items will print the same output: "Item 3" instead of the corresponding one. I'm thankful for any ideas about how I can get this right. Thanks.</p>
| 10 | 2009-07-08T22:01:56Z | 1,102,089 | <p>You're meeting what's been often referred to (maybe not entirely pedantically-correctly;-) as the "scoping problem" in Python -- the binding is late (lexical lookup at call-time) while you'd like it early (at def-time). So where you now have:</p>
<pre><code> for item in menuitems:
entry = menu.addAction(item)
self.connect(entry,QtCore.SIGNAL('triggered()'), lambda: self.doStuff(item))
</code></pre>
<p>try instead:</p>
<pre><code> for item in menuitems:
entry = menu.addAction(item)
self.connect(entry,QtCore.SIGNAL('triggered()'), lambda item=item: self.doStuff(item))
</code></pre>
<p>This "anticipates" the binding, since default values (as the <code>item</code> one here) get computed once an for all at def-time. Adding one level of function nesting (e.g. a double lambda) works too, but it's a bit of an overkill here!-)</p>
<p>You could alternatively use <code>functools.partial(self.doStuff, item)</code> (with an <code>import functools</code> at the top of course) which is another fine solution, but I think I'd go for the simplest (and most common) "fake default-value for argument" idiom.</p>
| 23 | 2009-07-09T06:10:54Z | [
"python",
"qt",
"pyqt",
"signals-slots"
] |
Why would Django's cache work with locmem but fail with memcached? | 1,101,049 | <p>Using Django's cache with locmem (with simple Python classes as values stored in lists/tuples/maps) works perfectly but does not work with memcached.</p>
<p>Only a fraction of the keys (despite ample memory allocated and large timeouts) make their way into memcached, and none of them appear to have any associated value.</p>
<p>When they are retrieved, no value is returned and they are removed from the cache.</p>
<p>Forcing a value of "hi" makes those that appear in the cache retrievable, but does not account for why most of the keys are simply not there.</p>
<p>Questions:</p>
<ol>
<li>Why do only certain keys end up in memcached and others not, even when all values are set to "hi"?</li>
<li>Is there any way to enable more logging or error reporting? (everything seems to fail silently)</li>
<li>Why do the Python classes serialize correctly to locmem but do not end up in Memcached?</li>
</ol>
| 4 | 2009-07-08T23:14:32Z | 1,101,991 | <p>To find out what's going on, run <code>memcached -vv 2>/tmp/mc_debug_log</code> (I'm assuming you're on some sort of Unixy system) and run it for a <em>short</em> time -- you'll find detailed information in that logfile when you're done.</p>
<p>Depending on what Python interface to memcached you're using, it may be that only strings are supported as values (as in the StringClient module in <a href="http://gijsbert.org/cmemcache/index.html" rel="nofollow">cmemcache</a>) or that all pickleable objects are (with the overhead of pickling and unpickling of course), as in the more general Client module in the same cmemcache, GAE's <a href="http://code.google.com/appengine/docs/python/memcache/" rel="nofollow">memcache</a>, and <a href="http://www.tummy.com/Community/software/python-memcached/" rel="nofollow">python-memcached</a>; if you're only able to use strings as values, presumably you're using an interface of the former type?</p>
| 3 | 2009-07-09T05:36:16Z | [
"python",
"django",
"caching",
"memcached"
] |
Why would Django's cache work with locmem but fail with memcached? | 1,101,049 | <p>Using Django's cache with locmem (with simple Python classes as values stored in lists/tuples/maps) works perfectly but does not work with memcached.</p>
<p>Only a fraction of the keys (despite ample memory allocated and large timeouts) make their way into memcached, and none of them appear to have any associated value.</p>
<p>When they are retrieved, no value is returned and they are removed from the cache.</p>
<p>Forcing a value of "hi" makes those that appear in the cache retrievable, but does not account for why most of the keys are simply not there.</p>
<p>Questions:</p>
<ol>
<li>Why do only certain keys end up in memcached and others not, even when all values are set to "hi"?</li>
<li>Is there any way to enable more logging or error reporting? (everything seems to fail silently)</li>
<li>Why do the Python classes serialize correctly to locmem but do not end up in Memcached?</li>
</ol>
| 4 | 2009-07-08T23:14:32Z | 1,105,858 | <p>Apparently, keys can not have spaces in them:</p>
<p><a href="http://code.djangoproject.com/ticket/6447" rel="nofollow">http://code.djangoproject.com/ticket/6447</a><br/>
<a href="http://blog.pos.thum.us/2009/05/22/memcached-keys-cant-have-spaces-in-them/" rel="nofollow">http://blog.pos.thum.us/2009/05/22/memcached-keys-cant-have-spaces-in-them/</a></p>
<p>As soon as I used a key with a space in it, everything became unpredictable.</p>
| 3 | 2009-07-09T19:01:31Z | [
"python",
"django",
"caching",
"memcached"
] |
Library to read ELF file DWARF debug information | 1,101,272 | <p>Any recommendations for a good cross-platform library for reading ELF file debug information in DWARF format? I'd like to read the DWARF debug info in a Python program.</p>
| 19 | 2009-07-09T00:37:14Z | 1,101,352 | <p>The concept of "ELF debug info" doesn't really exist: the ELF specification leaves the content of the .debug section deliberately unspecified.</p>
<p>Common debug formats are STAB and <a href="http://dwarfstd.org/" rel="nofollow">DWARF</a>. A library to read DWARF is <a href="http://www.prevanders.net/dwarf.html" rel="nofollow">libdwarf</a>.</p>
| 9 | 2009-07-09T01:11:00Z | [
"python",
"debugging",
"elf",
"dwarf"
] |
Library to read ELF file DWARF debug information | 1,101,272 | <p>Any recommendations for a good cross-platform library for reading ELF file debug information in DWARF format? I'd like to read the DWARF debug info in a Python program.</p>
| 19 | 2009-07-09T00:37:14Z | 1,101,356 | <p>You might find useful informations here:</p>
<ul>
<li><a href="http://reality.sgiweb.org/davea/dwarf.html">David A's DWARF Page</a></li>
<li><a href="http://stackoverflow.com/questions/45954/python-libdwarf-module">SO question</a></li>
</ul>
| 5 | 2009-07-09T01:12:11Z | [
"python",
"debugging",
"elf",
"dwarf"
] |
Library to read ELF file DWARF debug information | 1,101,272 | <p>Any recommendations for a good cross-platform library for reading ELF file debug information in DWARF format? I'd like to read the DWARF debug info in a Python program.</p>
| 19 | 2009-07-09T00:37:14Z | 1,128,586 | <p>Your options for reading the DWARF debugging information are unfortunately quite limited.</p>
<p>As far as I know there is only one general purpose library for parsing DWARF debugging information and that is <a href="http://reality.sgiweb.org/davea/dwarf.html" rel="nofollow" title="libdwarf">libdwarf</a>. Unfortunately no one has written Python bindings for libdwarf (maybe you could take it up upon yourself and share it with everyone else :) ) You could certainly attempt to access the library's functions using <a href="http://docs.python.org/library/ctypes.html" rel="nofollow" title="ctypes">ctypes</a> or the <a href="http://docs.python.org/c-api/" rel="nofollow" title="Python C/C++ API">Python C API</a>.</p>
<p>A much less elegant solution, however, is to use an existing DWARF parser and parse the textual information it outputs. Your options for this (on Linux) are</p>
<pre><code>objdump -W
readelf --debug-dump=[OPTIONS]
</code></pre>
<p>I currently use a project that builds off of readelf and it's support for the DWARF debugging information is very full featured. You could simply use Python to execute either command in the shell and then parse the information as you need. Certainly not as ideal as a library, but should do the trick.</p>
<p>EDIT: I noticed in a previous comment you mentioned Windows. Both of these programs(objdump and readelf) are part of GNU-binutils, so they should be available with Cygwin or mingw.</p>
| 4 | 2009-07-14T23:11:17Z | [
"python",
"debugging",
"elf",
"dwarf"
] |
Library to read ELF file DWARF debug information | 1,101,272 | <p>Any recommendations for a good cross-platform library for reading ELF file debug information in DWARF format? I'd like to read the DWARF debug info in a Python program.</p>
| 19 | 2009-07-09T00:37:14Z | 3,647,042 | <p>You might be interested in the DWARF library from <a href="http://code.google.com/p/pydevtools/">pydevtools</a>:</p>
<pre><code>>>> from devtools.dwarf import DWARF
>>> dwarf = DWARF('test/test')
>>> dwarf.get_loc_by_addr(0x8048475)
('/home/emilmont/Workspace/dbg/test/main.c', 36, 0)
>>> print dwarf
.debug_info
COMPILE_UNIT<header overall offset = 0>
<0><11> compile_unit
producer: GNU C 4.4.3
language: C89
name: a/test.c
comp_dir: /home/emilmont/Workspace/dbg/test
low_pc: 0x080483e4
high_pc: 0x08048410
stmt_list: 0
[...]
</code></pre>
| 7 | 2010-09-05T17:40:47Z | [
"python",
"debugging",
"elf",
"dwarf"
] |
Library to read ELF file DWARF debug information | 1,101,272 | <p>Any recommendations for a good cross-platform library for reading ELF file debug information in DWARF format? I'd like to read the DWARF debug info in a Python program.</p>
| 19 | 2009-07-09T00:37:14Z | 8,754,544 | <p>There's a new kid on the block - <a href="https://github.com/eliben/pyelftools">pyelftools</a> - a pure Python library for parsing the ELF and DWARF formats. Give it a try.</p>
<p>It aims to be feature-complete and is currently in active development, so any problems should be handled quickly and enthusiastically :-)</p>
| 19 | 2012-01-06T07:09:00Z | [
"python",
"debugging",
"elf",
"dwarf"
] |
Are there any class diagram generating tools for python source code? | 1,101,301 | <p>Are there any reverse-egineering UML tools for Python?</p>
| 7 | 2009-07-09T00:56:30Z | 1,101,333 | <p><a href="http://sourceforge.net/projects/eclipse-pyuml/" rel="nofollow">pyUML</a> may be what you are looking for. Although it is an Eclipse plugin for PyDev.</p>
| 2 | 2009-07-09T01:05:51Z | [
"python",
"uml"
] |
Are there any class diagram generating tools for python source code? | 1,101,301 | <p>Are there any reverse-egineering UML tools for Python?</p>
| 7 | 2009-07-09T00:56:30Z | 1,101,342 | <p><a href="http://www.sparxsystems.com/" rel="nofollow">Sparx Enterprise Architect</a> can reverse engineer Python code, at least according to the documentation. I've never tried it, so I don't know for certain.</p>
| 2 | 2009-07-09T01:07:45Z | [
"python",
"uml"
] |
Are there any class diagram generating tools for python source code? | 1,101,301 | <p>Are there any reverse-egineering UML tools for Python?</p>
| 7 | 2009-07-09T00:56:30Z | 1,101,417 | <p>This looks good: <a href="http://www.andypatterns.com/index.php?cID=65">http://www.andypatterns.com/index.php?cID=65</a></p>
<p>How about this? <a href="http://www.greenteapress.com/thinkpython/swampy/lumpy.html">http://www.greenteapress.com/thinkpython/swampy/lumpy.html</a></p>
| 5 | 2009-07-09T01:36:04Z | [
"python",
"uml"
] |
How to parse dates with -0400 timezone string in python? | 1,101,508 | <p>I have a date string of the form '2009/05/13 19:19:30 -0400'. It seems that previous versions of python may have supported a %z format tag in strptime for the trailing timezone specification, but 2.6.x seems to have removed that.</p>
<p>What's the right way to parse this string into a datetime object?</p>
| 47 | 2009-07-09T02:19:03Z | 1,101,597 | <p>You can use the parse function from dateutil:</p>
<pre><code>>>> from dateutil.parser import parse
>>> d = parse('2009/05/13 19:19:30 -0400')
>>> d
datetime.datetime(2009, 5, 13, 19, 19, 30, tzinfo=tzoffset(None, -14400))
</code></pre>
<p>This way you obtain a datetime object you can then use.</p>
<p><strong>UPDATE:</strong> As <a href="http://stackoverflow.com/questions/7804505/dateutil-parser-parse-gives-error-initial-value-must-be-unicode-or-none-not/7804999#7804999">answered</a> dateutil2.0 is written for python3.0 and does not work with python2.x. For python2.x dateutil1.5 needs to be used.</p>
| 72 | 2009-07-09T02:47:14Z | [
"python",
"datetime",
"timezone"
] |
How to parse dates with -0400 timezone string in python? | 1,101,508 | <p>I have a date string of the form '2009/05/13 19:19:30 -0400'. It seems that previous versions of python may have supported a %z format tag in strptime for the trailing timezone specification, but 2.6.x seems to have removed that.</p>
<p>What's the right way to parse this string into a datetime object?</p>
| 47 | 2009-07-09T02:19:03Z | 1,101,688 | <p>If you are on linux, then you can use the external <code>date</code> command to dwim :</p>
<pre><code>import commands, datetime
def parsedate(text):
output=commands.getoutput('date -d "%s" +%%s' % text )
try:
stamp=eval(output)
except:
print output
raise
return datetime.datetime.frometimestamp(stamp)
</code></pre>
<p>This is of course less portable that dateutil, but slightly more flexible, because <code>date</code> will also accept inputs like "yesterday" or "last year" :-)</p>
| -4 | 2009-07-09T03:21:44Z | [
"python",
"datetime",
"timezone"
] |
How to parse dates with -0400 timezone string in python? | 1,101,508 | <p>I have a date string of the form '2009/05/13 19:19:30 -0400'. It seems that previous versions of python may have supported a %z format tag in strptime for the trailing timezone specification, but 2.6.x seems to have removed that.</p>
<p>What's the right way to parse this string into a datetime object?</p>
| 47 | 2009-07-09T02:19:03Z | 15,516,170 | <p>The problem with using dateutil is that you can't have the same format string for both serialization and deserialization, as dateutil has limited formatting options (only <code>dayfirst</code> and <code>yearfirst</code>).</p>
<p>In my application, I store the format string in .INI file, and each deployment can have its own format. Thus, I really don't like the dateutil approach.</p>
<p>Here's an alternative method that uses pytz instead:</p>
<pre><code>from datetime import datetime, timedelta
from pytz import timezone, utc
from pytz.tzinfo import StaticTzInfo
class OffsetTime(StaticTzInfo):
def __init__(self, offset):
"""A dumb timezone based on offset such as +0530, -0600, etc.
"""
hours = int(offset[:3])
minutes = int(offset[0] + offset[3:])
self._utcoffset = timedelta(hours=hours, minutes=minutes)
def load_datetime(value, format):
if format.endswith('%z'):
format = format[:-2]
offset = value[-5:]
value = value[:-5]
return OffsetTime(offset).localize(datetime.strptime(value, format))
return datetime.strptime(value, format)
def dump_datetime(value, format):
return value.strftime(format)
value = '2009/05/13 19:19:30 -0400'
format = '%Y/%m/%d %H:%M:%S %z'
assert dump_datetime(load_datetime(value, format), format) == value
assert datetime(2009, 5, 13, 23, 19, 30, tzinfo=utc) \
.astimezone(timezone('US/Eastern')) == load_datetime(value, format)
</code></pre>
| 7 | 2013-03-20T05:41:41Z | [
"python",
"datetime",
"timezone"
] |
How to parse dates with -0400 timezone string in python? | 1,101,508 | <p>I have a date string of the form '2009/05/13 19:19:30 -0400'. It seems that previous versions of python may have supported a %z format tag in strptime for the trailing timezone specification, but 2.6.x seems to have removed that.</p>
<p>What's the right way to parse this string into a datetime object?</p>
| 47 | 2009-07-09T02:19:03Z | 23,122,493 | <p><code>%z</code> is supported in Python 3.2+:</p>
<pre><code>>>> from datetime import datetime
>>> datetime.strptime('2009/05/13 19:19:30 -0400', '%Y/%m/%d %H:%M:%S %z')
datetime.datetime(2009, 5, 13, 19, 19, 30,
tzinfo=datetime.timezone(datetime.timedelta(-1, 72000)))
</code></pre>
<p>On earlier versions:</p>
<pre><code>from datetime import datetime
date_str = '2009/05/13 19:19:30 -0400'
naive_date_str, _, offset_str = date_str.rpartition(' ')
naive_dt = datetime.strptime(naive_date_str, '%Y/%m/%d %H:%M:%S')
offset = int(offset_str[-4:-2])*60 + int(offset_str[-2:])
if offset_str[0] == "-":
offset = -offset
dt = naive_dt.replace(tzinfo=FixedOffset(offset))
print(repr(dt))
# -> datetime.datetime(2009, 5, 13, 19, 19, 30, tzinfo=FixedOffset(-240))
print(dt)
# -> 2009-05-13 19:19:30-04:00
</code></pre>
<p>where <code>FixedOffset</code> is a class based on <a href="https://docs.python.org/2/library/datetime.html#datetime.tzinfo.fromutc">the code example from the docs</a>:</p>
<pre><code>from datetime import timedelta, tzinfo
class FixedOffset(tzinfo):
"""Fixed offset in minutes: `time = utc_time + utc_offset`."""
def __init__(self, offset):
self.__offset = timedelta(minutes=offset)
hours, minutes = divmod(offset, 60)
#NOTE: the last part is to remind about deprecated POSIX GMT+h timezones
# that have the opposite sign in the name;
# the corresponding numeric value is not used e.g., no minutes
self.__name = '<%+03d%02d>%+d' % (hours, minutes, -hours)
def utcoffset(self, dt=None):
return self.__offset
def tzname(self, dt=None):
return self.__name
def dst(self, dt=None):
return timedelta(0)
def __repr__(self):
return 'FixedOffset(%d)' % (self.utcoffset().total_seconds() / 60)
</code></pre>
| 25 | 2014-04-17T00:21:33Z | [
"python",
"datetime",
"timezone"
] |
How to parse dates with -0400 timezone string in python? | 1,101,508 | <p>I have a date string of the form '2009/05/13 19:19:30 -0400'. It seems that previous versions of python may have supported a %z format tag in strptime for the trailing timezone specification, but 2.6.x seems to have removed that.</p>
<p>What's the right way to parse this string into a datetime object?</p>
| 47 | 2009-07-09T02:19:03Z | 38,992,733 | <p>Here is a fix of the <code>"%z"</code> issue for python 2.7</p>
<p>Instead of using:</p>
<pre><code>datetime.strptime(t,'%Y-%m-%dT%H:%M %z')
</code></pre>
<p>use the <code>timedelta</code> to account for the timezone, like this:</p>
<pre><code>from datetime import datetime,timedelta
def dt_parse(t):
ret = datetime.strptime(t[0:16],'%Y-%m-%dT%H:%M')
if t[18]=='+':
ret+=timedelta(hours=int(t[19:22]),minutes=int(t[23:]))
elif t[18]=='-':
ret-=timedelta(hours=int(t[19:22]),minutes=int(t[23:]))
return ret
</code></pre>
| 3 | 2016-08-17T09:25:32Z | [
"python",
"datetime",
"timezone"
] |
python calendar.HTMLCalendar | 1,101,524 | <p>I think I want to use pythons built in calendar module to create an HTML calendar with data. I say I think because I'll probably think of a better way, but right now it's a little personal. I don't know if this was intended to be used this way but it seems like it is a little pointless if you can't at least making the days into a <code><a hrefs></code>.</p>
<p>This sets up a calendar for this month with Sunday as the first day.</p>
<pre><code>import calendar
myCal = calendar.HTMLCalendar(calendar.SUNDAY)
print myCal.formatmonth(2009, 7)
</code></pre>
<p>it prints</p>
<pre><code><table border="0" cellpadding="0" cellspacing="0" class="month">\n<tr>
<th colspan="7" class="month">July 2009</th></tr>\n<tr><th class="sun">Sun</th>
<th class="mon">Mon</th><th class="tue">Tue</th><th class="wed">Wed</th>
<th class="thu">Thu</th><th class="fri">Fri</th><th class="sat">Sat</th></tr>\n
<tr><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td>
<td class="noday">&nbsp;</td><td class="wed">1</td><td class="thu">2</td><td class="fri">3</td>
<td class="sat">4</td></tr>\n<tr><td class="sun">5</td><td class="mon">6</td><td class="tue">7</td>
<td class="wed">8</td><td class="thu">9</td><td class="fri">10</td>
<td class="sat">11</td></tr>\n<tr><td class="sun">12</td><td class="mon">13</td>
<td class="tue">14</td><td class="wed">15</td><td class="thu">16</td><td class="fri">17</td>
<td class="sat">18</td></tr>\n<tr><td class="sun">19</td><td class="mon">20</td>
<td class="tue">21</td><td class="wed">22</td><td class="thu">23</td><td class="fri">24</td>
<td class="sat">25</td></tr>\n<tr><td class="sun">26</td><td class="mon">27</td>
<td class="tue">28</td><td class="wed">29</td><td class="thu">30</td><td class="fri">31</td>
<td class="noday">&nbsp;</td></tr>\n</table>\n
</code></pre>
<p>I would like to insert some data into the HTMLCalendar object before it renders the html string. I just can't figure out how. </p>
<p>For example</p>
<pre><code><td class="tue">28<br />[my data]</td>
</code></pre>
| 3 | 2009-07-09T02:23:48Z | 1,101,566 | <p>It's hard to say without knowing exactly what you're trying to accomplish, but here's one idea.</p>
<p>Instead of printing myCal.formatmonth(2009, 7), why don't you assign it to a string. Then you could manipulate it, perhaps with a regex.</p>
<p>Here's a really bad example:</p>
<pre><code>import calendar
import re
myCal = calendar.HTMLCalendar(calendar.SUNDAY)
myStr = myCal.formatmonth(2009, 7)
re.sub('28', '28<br/>[My Data]', myStr)
print myStr
</code></pre>
<p>It does what you want, but it's pretty ugly.</p>
| 0 | 2009-07-09T02:34:52Z | [
"python",
"html",
"calendar"
] |
python calendar.HTMLCalendar | 1,101,524 | <p>I think I want to use pythons built in calendar module to create an HTML calendar with data. I say I think because I'll probably think of a better way, but right now it's a little personal. I don't know if this was intended to be used this way but it seems like it is a little pointless if you can't at least making the days into a <code><a hrefs></code>.</p>
<p>This sets up a calendar for this month with Sunday as the first day.</p>
<pre><code>import calendar
myCal = calendar.HTMLCalendar(calendar.SUNDAY)
print myCal.formatmonth(2009, 7)
</code></pre>
<p>it prints</p>
<pre><code><table border="0" cellpadding="0" cellspacing="0" class="month">\n<tr>
<th colspan="7" class="month">July 2009</th></tr>\n<tr><th class="sun">Sun</th>
<th class="mon">Mon</th><th class="tue">Tue</th><th class="wed">Wed</th>
<th class="thu">Thu</th><th class="fri">Fri</th><th class="sat">Sat</th></tr>\n
<tr><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td>
<td class="noday">&nbsp;</td><td class="wed">1</td><td class="thu">2</td><td class="fri">3</td>
<td class="sat">4</td></tr>\n<tr><td class="sun">5</td><td class="mon">6</td><td class="tue">7</td>
<td class="wed">8</td><td class="thu">9</td><td class="fri">10</td>
<td class="sat">11</td></tr>\n<tr><td class="sun">12</td><td class="mon">13</td>
<td class="tue">14</td><td class="wed">15</td><td class="thu">16</td><td class="fri">17</td>
<td class="sat">18</td></tr>\n<tr><td class="sun">19</td><td class="mon">20</td>
<td class="tue">21</td><td class="wed">22</td><td class="thu">23</td><td class="fri">24</td>
<td class="sat">25</td></tr>\n<tr><td class="sun">26</td><td class="mon">27</td>
<td class="tue">28</td><td class="wed">29</td><td class="thu">30</td><td class="fri">31</td>
<td class="noday">&nbsp;</td></tr>\n</table>\n
</code></pre>
<p>I would like to insert some data into the HTMLCalendar object before it renders the html string. I just can't figure out how. </p>
<p>For example</p>
<pre><code><td class="tue">28<br />[my data]</td>
</code></pre>
| 3 | 2009-07-09T02:23:48Z | 1,101,743 | <p>You may load html, which seems to be valid XMl into a XML tree, modify it and again output it.
e.g. this adds <code><br/> cool</code> to each Tue td node.</p>
<pre><code>import calendar
import xml.etree.ElementTree as etree
myCal = calendar.HTMLCalendar(calendar.SUNDAY)
htmlStr = myCal.formatmonth(2009, 7)
htmlStr = htmlStr.replace("&nbsp;"," ")
root = etree.fromstring(htmlStr)
for elem in root.findall("*//td"):
if elem.get("class") != "tue":
continue
elem.text += "!"
br = etree.SubElement(elem, "br")
br.tail = "cool!"
print etree.tostring(root)
</code></pre>
<p>I do not yet know why you need to generate a HTML calendar, but there are better ways of doing that depending on needs and framework you are using.</p>
| 0 | 2009-07-09T03:47:44Z | [
"python",
"html",
"calendar"
] |
python calendar.HTMLCalendar | 1,101,524 | <p>I think I want to use pythons built in calendar module to create an HTML calendar with data. I say I think because I'll probably think of a better way, but right now it's a little personal. I don't know if this was intended to be used this way but it seems like it is a little pointless if you can't at least making the days into a <code><a hrefs></code>.</p>
<p>This sets up a calendar for this month with Sunday as the first day.</p>
<pre><code>import calendar
myCal = calendar.HTMLCalendar(calendar.SUNDAY)
print myCal.formatmonth(2009, 7)
</code></pre>
<p>it prints</p>
<pre><code><table border="0" cellpadding="0" cellspacing="0" class="month">\n<tr>
<th colspan="7" class="month">July 2009</th></tr>\n<tr><th class="sun">Sun</th>
<th class="mon">Mon</th><th class="tue">Tue</th><th class="wed">Wed</th>
<th class="thu">Thu</th><th class="fri">Fri</th><th class="sat">Sat</th></tr>\n
<tr><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td>
<td class="noday">&nbsp;</td><td class="wed">1</td><td class="thu">2</td><td class="fri">3</td>
<td class="sat">4</td></tr>\n<tr><td class="sun">5</td><td class="mon">6</td><td class="tue">7</td>
<td class="wed">8</td><td class="thu">9</td><td class="fri">10</td>
<td class="sat">11</td></tr>\n<tr><td class="sun">12</td><td class="mon">13</td>
<td class="tue">14</td><td class="wed">15</td><td class="thu">16</td><td class="fri">17</td>
<td class="sat">18</td></tr>\n<tr><td class="sun">19</td><td class="mon">20</td>
<td class="tue">21</td><td class="wed">22</td><td class="thu">23</td><td class="fri">24</td>
<td class="sat">25</td></tr>\n<tr><td class="sun">26</td><td class="mon">27</td>
<td class="tue">28</td><td class="wed">29</td><td class="thu">30</td><td class="fri">31</td>
<td class="noday">&nbsp;</td></tr>\n</table>\n
</code></pre>
<p>I would like to insert some data into the HTMLCalendar object before it renders the html string. I just can't figure out how. </p>
<p>For example</p>
<pre><code><td class="tue">28<br />[my data]</td>
</code></pre>
| 3 | 2009-07-09T02:23:48Z | 1,102,014 | <p>The calendar module has usually been pretty useless, but in 2.5 it introduced the Calendar object. This won't render an HTML calendar for you, but it has loads of methods that will help you render a calendar.</p>
<p>For example, monthdatescalendar(year, month) will give you a list of all weeks in the month given, where each week in turn is a list of the seven days. So monthdatescalendar(2009,7) will start with <code>[[datetime.date(2009, 6, 29), datetime.date(2009, 6, 30),</code> and end with <code>datetime.date(2009, 8, 1), datetime.date(2009, 8, 2)]]</code></p>
<p>With this, it then becomes a trivial exercise to generate the HTML you want.</p>
| 16 | 2009-07-09T05:42:33Z | [
"python",
"html",
"calendar"
] |
python calendar.HTMLCalendar | 1,101,524 | <p>I think I want to use pythons built in calendar module to create an HTML calendar with data. I say I think because I'll probably think of a better way, but right now it's a little personal. I don't know if this was intended to be used this way but it seems like it is a little pointless if you can't at least making the days into a <code><a hrefs></code>.</p>
<p>This sets up a calendar for this month with Sunday as the first day.</p>
<pre><code>import calendar
myCal = calendar.HTMLCalendar(calendar.SUNDAY)
print myCal.formatmonth(2009, 7)
</code></pre>
<p>it prints</p>
<pre><code><table border="0" cellpadding="0" cellspacing="0" class="month">\n<tr>
<th colspan="7" class="month">July 2009</th></tr>\n<tr><th class="sun">Sun</th>
<th class="mon">Mon</th><th class="tue">Tue</th><th class="wed">Wed</th>
<th class="thu">Thu</th><th class="fri">Fri</th><th class="sat">Sat</th></tr>\n
<tr><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td>
<td class="noday">&nbsp;</td><td class="wed">1</td><td class="thu">2</td><td class="fri">3</td>
<td class="sat">4</td></tr>\n<tr><td class="sun">5</td><td class="mon">6</td><td class="tue">7</td>
<td class="wed">8</td><td class="thu">9</td><td class="fri">10</td>
<td class="sat">11</td></tr>\n<tr><td class="sun">12</td><td class="mon">13</td>
<td class="tue">14</td><td class="wed">15</td><td class="thu">16</td><td class="fri">17</td>
<td class="sat">18</td></tr>\n<tr><td class="sun">19</td><td class="mon">20</td>
<td class="tue">21</td><td class="wed">22</td><td class="thu">23</td><td class="fri">24</td>
<td class="sat">25</td></tr>\n<tr><td class="sun">26</td><td class="mon">27</td>
<td class="tue">28</td><td class="wed">29</td><td class="thu">30</td><td class="fri">31</td>
<td class="noday">&nbsp;</td></tr>\n</table>\n
</code></pre>
<p>I would like to insert some data into the HTMLCalendar object before it renders the html string. I just can't figure out how. </p>
<p>For example</p>
<pre><code><td class="tue">28<br />[my data]</td>
</code></pre>
| 3 | 2009-07-09T02:23:48Z | 1,458,077 | <p>Create a new class inheriting from HTMLCalendar.
Override the formatday method.</p>
<p>Whoever makes comments like "this library is useless" obviously doesn't understand Python.</p>
<pre><code>class EmployeeScheduleCalendar(HTMLCalendar):
def formatday(self, day, weekday):
"""
Return a day as a table cell.
"""
if day == 0:
return '<td class="noday">&nbsp;</td>' # day outside month
else:
return '<td class="%s"><a href="%s">%d</a></td>' % (self.cssclasses[weekday], weekday, day)
</code></pre>
| 33 | 2009-09-22T04:17:47Z | [
"python",
"html",
"calendar"
] |
python calendar.HTMLCalendar | 1,101,524 | <p>I think I want to use pythons built in calendar module to create an HTML calendar with data. I say I think because I'll probably think of a better way, but right now it's a little personal. I don't know if this was intended to be used this way but it seems like it is a little pointless if you can't at least making the days into a <code><a hrefs></code>.</p>
<p>This sets up a calendar for this month with Sunday as the first day.</p>
<pre><code>import calendar
myCal = calendar.HTMLCalendar(calendar.SUNDAY)
print myCal.formatmonth(2009, 7)
</code></pre>
<p>it prints</p>
<pre><code><table border="0" cellpadding="0" cellspacing="0" class="month">\n<tr>
<th colspan="7" class="month">July 2009</th></tr>\n<tr><th class="sun">Sun</th>
<th class="mon">Mon</th><th class="tue">Tue</th><th class="wed">Wed</th>
<th class="thu">Thu</th><th class="fri">Fri</th><th class="sat">Sat</th></tr>\n
<tr><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td>
<td class="noday">&nbsp;</td><td class="wed">1</td><td class="thu">2</td><td class="fri">3</td>
<td class="sat">4</td></tr>\n<tr><td class="sun">5</td><td class="mon">6</td><td class="tue">7</td>
<td class="wed">8</td><td class="thu">9</td><td class="fri">10</td>
<td class="sat">11</td></tr>\n<tr><td class="sun">12</td><td class="mon">13</td>
<td class="tue">14</td><td class="wed">15</td><td class="thu">16</td><td class="fri">17</td>
<td class="sat">18</td></tr>\n<tr><td class="sun">19</td><td class="mon">20</td>
<td class="tue">21</td><td class="wed">22</td><td class="thu">23</td><td class="fri">24</td>
<td class="sat">25</td></tr>\n<tr><td class="sun">26</td><td class="mon">27</td>
<td class="tue">28</td><td class="wed">29</td><td class="thu">30</td><td class="fri">31</td>
<td class="noday">&nbsp;</td></tr>\n</table>\n
</code></pre>
<p>I would like to insert some data into the HTMLCalendar object before it renders the html string. I just can't figure out how. </p>
<p>For example</p>
<pre><code><td class="tue">28<br />[my data]</td>
</code></pre>
| 3 | 2009-07-09T02:23:48Z | 5,561,014 | <p>You can subclass HTMLCalendar and override its methods in order to do whatever you want, like so: <a href="http://journal.uggedal.com/creating-a-flexible-monthly-calendar-in-django/" rel="nofollow">http://journal.uggedal.com/creating-a-flexible-monthly-calendar-in-django/</a></p>
<p>If you refer to the documentation for HTMLCalendar (http://svn.python.org/view/python/branches/release27-maint/Lib/calendar.py?view=markup), you'll see that the formatday() method is very straightforward. Simply override it, as in the example linked above, to do whatever you'd like. So HTMLCalendar isn't so pointless after all. ;)</p>
| 3 | 2011-04-06T03:07:04Z | [
"python",
"html",
"calendar"
] |
Why my Python test generator simply doesn't work? | 1,101,550 | <p>This is a sample script to test the use of yield... am I doing it wrong? It always returns '1'...</p>
<pre><code>#!/usr/bin/python
def testGen():
for a in [1,2,3,4,5,6,7,8,9,10]:
yield a
w = 0
while w < 10:
print testGen().next()
w += 1
</code></pre>
| 1 | 2009-07-09T02:30:01Z | 1,101,579 | <p>You're creating a new generator each time. You should only call <code>testGen()</code> once and then use the object returned. Try:</p>
<pre><code>w = 0
g = testGen()
while w < 10:
print g.next()
w += 1
</code></pre>
<p>Then of course there's the normal, idiomatic generator usage:</p>
<pre><code>for n in testGen():
print n
</code></pre>
<p>Note that this will only call <code>testGen()</code> once at the start of the loop, not once per iteration.</p>
| 10 | 2009-07-09T02:37:06Z | [
"python",
"testing",
"generator",
"yield"
] |
Help needed improving Python code using List Comprehensions | 1,101,611 | <p>I've been writing little Python programs at home to learn more about the language. The most recent feature I've tried to understand are List Comprehensions. I created a little script that estimates when my car needs its next oil change based on how frequently I've gotten the oil changed in the past. In the code snippet below, <code>oil_changes</code> is a list of the mileages at which I got the oil changed.</p>
<pre><code># Compute a list of the mileage differences between each oil change.
diffs = [j - i for i, j in zip(oil_changes[:-1], oil_changes[1:])]
# Use the average difference between oil changes to estimate the next change.
next_oil = oil_changes[-1] + sum(diffs) / len(diffs)
</code></pre>
<p>The code produces the right answer (did the math by hand to check) but it doesn't feel quite Pythonic yet. Am I doing a lot of needless copying of the original list in the first line? I feel like there's a much better way to do this but I don't know what it is.</p>
| 3 | 2009-07-09T02:51:36Z | 1,101,622 | <p>It seems fine, really. Not everything is simple (you've got several steps in an otherwise simple calculation, no matter how you frame it). There are options to reduce the copies, like using itertools.islice and itertools.izip, but (aside from izip) the extra steps in the code would just complicate it further. Not everything needs to be a list comprehension, but it is a judgement call sometimes. What looks cleaner to you? What will the next guy that reads it understand best? What will you understand when you come back to fix that bug in three months?</p>
| 2 | 2009-07-09T02:56:11Z | [
"python",
"list-comprehension"
] |
Help needed improving Python code using List Comprehensions | 1,101,611 | <p>I've been writing little Python programs at home to learn more about the language. The most recent feature I've tried to understand are List Comprehensions. I created a little script that estimates when my car needs its next oil change based on how frequently I've gotten the oil changed in the past. In the code snippet below, <code>oil_changes</code> is a list of the mileages at which I got the oil changed.</p>
<pre><code># Compute a list of the mileage differences between each oil change.
diffs = [j - i for i, j in zip(oil_changes[:-1], oil_changes[1:])]
# Use the average difference between oil changes to estimate the next change.
next_oil = oil_changes[-1] + sum(diffs) / len(diffs)
</code></pre>
<p>The code produces the right answer (did the math by hand to check) but it doesn't feel quite Pythonic yet. Am I doing a lot of needless copying of the original list in the first line? I feel like there's a much better way to do this but I don't know what it is.</p>
| 3 | 2009-07-09T02:51:36Z | 1,101,640 | <p>The <a href="http://docs.python.org/library/itertools.html" rel="nofollow"><code>itertools</code></a> package provides additional generator-style functions. For instance, you can use <code>izip</code> in place of <code>zip</code> to save on some memory.</p>
<p>You could also perhaps write an <code>average</code> function so you can turn <code>diffs</code> into a generator instead of a list comprehension:</p>
<pre><code>from itertools import izip
def average(items):
sum, count = 0, 0
for item in items:
sum += item
count += 1
return sum / count
diffs = (j - i for i, j in izip(oil_changes[:-1], oil_changes[1:])
next_oil = oil_changes[-1] + average(diffs)
</code></pre>
<p>Alternatively, you could change your definition of <code>diffs</code> to:</p>
<pre><code>diffs = [oil_changes[i] - oil_changes[i-1] for i in xrange(1, len(oil_changes))]
</code></pre>
<p>I dunno, it's not really a huge improvement. Your code is pretty good as is.</p>
| 3 | 2009-07-09T03:01:17Z | [
"python",
"list-comprehension"
] |
Help needed improving Python code using List Comprehensions | 1,101,611 | <p>I've been writing little Python programs at home to learn more about the language. The most recent feature I've tried to understand are List Comprehensions. I created a little script that estimates when my car needs its next oil change based on how frequently I've gotten the oil changed in the past. In the code snippet below, <code>oil_changes</code> is a list of the mileages at which I got the oil changed.</p>
<pre><code># Compute a list of the mileage differences between each oil change.
diffs = [j - i for i, j in zip(oil_changes[:-1], oil_changes[1:])]
# Use the average difference between oil changes to estimate the next change.
next_oil = oil_changes[-1] + sum(diffs) / len(diffs)
</code></pre>
<p>The code produces the right answer (did the math by hand to check) but it doesn't feel quite Pythonic yet. Am I doing a lot of needless copying of the original list in the first line? I feel like there's a much better way to do this but I don't know what it is.</p>
| 3 | 2009-07-09T02:51:36Z | 1,101,656 | <p>Try this: </p>
<pre><code>assert len(oil_changes) >= 2
sum_of_diffs = oil_changes[-1] - oil_changes[0]
number_of_diffs = len(oil_changes) - 1
average_diff = sum_of_diffs / float(number_of_diffs)
</code></pre>
| 9 | 2009-07-09T03:07:40Z | [
"python",
"list-comprehension"
] |
Help needed improving Python code using List Comprehensions | 1,101,611 | <p>I've been writing little Python programs at home to learn more about the language. The most recent feature I've tried to understand are List Comprehensions. I created a little script that estimates when my car needs its next oil change based on how frequently I've gotten the oil changed in the past. In the code snippet below, <code>oil_changes</code> is a list of the mileages at which I got the oil changed.</p>
<pre><code># Compute a list of the mileage differences between each oil change.
diffs = [j - i for i, j in zip(oil_changes[:-1], oil_changes[1:])]
# Use the average difference between oil changes to estimate the next change.
next_oil = oil_changes[-1] + sum(diffs) / len(diffs)
</code></pre>
<p>The code produces the right answer (did the math by hand to check) but it doesn't feel quite Pythonic yet. Am I doing a lot of needless copying of the original list in the first line? I feel like there's a much better way to do this but I don't know what it is.</p>
| 3 | 2009-07-09T02:51:36Z | 1,101,804 | <blockquote>
<p>Am I doing a lot of needless copying
of the original list in the first
line?</p>
</blockquote>
<p>Technically, yes. Realistically, no. Unless you've changed your oil literally millions of times, the speed penalty is unlikely to be significant. You could change <code>zip</code> to <code>izip</code>, but it hardly seems worth it (and in python 3.0, <code>zip</code> effectively <em>is</em> <code>izip</code>).</p>
<p>Insert that <a href="http://en.wikipedia.org/wiki/Premature%5Foptimization#When%5Fto%5Foptimize" rel="nofollow">old quote by Knuth</a> here.</p>
<p>(you could also replace <code>oil_changes[:-1]</code> with just <code>oil_changes</code>, since <code>zip()</code> truncates to the length of the shortest input sequence anyway)</p>
| 2 | 2009-07-09T04:11:17Z | [
"python",
"list-comprehension"
] |
Help needed improving Python code using List Comprehensions | 1,101,611 | <p>I've been writing little Python programs at home to learn more about the language. The most recent feature I've tried to understand are List Comprehensions. I created a little script that estimates when my car needs its next oil change based on how frequently I've gotten the oil changed in the past. In the code snippet below, <code>oil_changes</code> is a list of the mileages at which I got the oil changed.</p>
<pre><code># Compute a list of the mileage differences between each oil change.
diffs = [j - i for i, j in zip(oil_changes[:-1], oil_changes[1:])]
# Use the average difference between oil changes to estimate the next change.
next_oil = oil_changes[-1] + sum(diffs) / len(diffs)
</code></pre>
<p>The code produces the right answer (did the math by hand to check) but it doesn't feel quite Pythonic yet. Am I doing a lot of needless copying of the original list in the first line? I feel like there's a much better way to do this but I don't know what it is.</p>
| 3 | 2009-07-09T02:51:36Z | 1,101,939 | <p>As other answers pointed out, you don't really need to worry unless your <code>oil_changes</code> list is extremely long. However, as a fan of "stream-based" computing, I think it's interesting to point out that <code>itertools</code> offers all the tools you need to compute your <code>next_oil</code> value in O(1) space (and O(N) time of course!-) no matter how big N, that is, <code>len(next_oil)</code>, gets. </p>
<p><code>izip</code> per se is insufficient, because it only reduces a bit the multiplicative constant but leaves your space demands as O(N). The key idea to bring those demands down to O(1) is to pair <code>izip</code> with <code>tee</code> -- and avoiding the list comprehension, which would be O(N) in space anyway, in favor of a good simple old-fashioned loop!-). Here comes:</p>
<pre><code> it = iter(oil_changes)
a, b = itertools.tee(it)
b.next()
thesum = 0
for thelen, (i, j) in enumerate(itertools.izip(a, b)):
thesum += j - i
last_one = j
next_oil = last_one + thesum / (thelen + 1)
</code></pre>
<p>Instead of taking slices from the list, we take an iterator on it, tee it (making two independently advanceable clones thereof), and advance, once, one of the clones, <code>b</code>. <code>tee</code> takes space O(x) where x is the maximum absolute difference between the advancement of the various clones; here, the two clones' advancement only differs by 1 at most, so the space requirement is clearly O(1).</p>
<p><code>izip</code> makes a one-at-a-time "zipping" of the two slightly-askew clone iterators, and we dress it up in <code>enumerate</code> so we can track how many times we go through the loop, i.e. the length of the iterable we're iterating on (we need the +1 in the final expression, because <code>enumerate</code> starts from 0!-). We compute the sum with a simple <code>+=</code>, which is fine for numbers (<code>sum</code> is even better, but it wouldn't track the length!-).</p>
<p>It's tempting after the loop to use <code>last_one = a.next()</code>, but that would not work because <code>a</code> is actually exhausted -- <code>izip</code> advances its argument iterables left to right, so it has advanced <code>a</code> one last time before it realizes <code>b</code> is over!-). That's OK, because Python loop variables are NOT limited in scope to the loop itself -- after the loop, <code>j</code> still has the value that was last extracted by advancing <code>b</code> before <code>izip</code> gave up (just like <code>thelen</code> still has the last count value returned by <code>enumerate</code>). I'm still naming the value <code>last_one</code> rather than using <code>j</code> directly in the final expression, because I think it's clearer and more readable.</p>
<p>So there it is -- I hope it was instructive!-) -- although for the solution of the specific problem that you posed this time, it's almost certain to be overkill. We Italians have an ancient proverb -- "Impara l'Arte, e mettila da parte!"... "Learn the Art, and then set it aside" -- which I think is quite applicable here: it's a good thing to learn advanced and sophisticated ways to solve very hard problems, in case you ever meet them, but for all that you need to go for simplicity and directness in the vastly more common case of simple, ordinary problems -- not apply advanced solutions that most likely won't be needed!-)</p>
| 9 | 2009-07-09T05:15:57Z | [
"python",
"list-comprehension"
] |
Unicode problem Django-Python-URLLIB-MySQL | 1,101,715 | <p>I am fetching a webpage (<a href="http://autoweek.com" rel="nofollow">http://autoweek.com</a>) and trying to process it but getting encoding error. Autoweek declares "iso-8859-1" encoding and has the word "Nürburgring" (u with umlaut)</p>
<p>I do: </p>
<pre><code># -*- encoding: utf-8 -*-
import urllib
webpage = urllib.urlopen(feed.crawl_url).read()
webpage.decode("utf-8")
</code></pre>
<p>it gives me the following error:</p>
<pre><code>'utf8' codec can't decode bytes in position 7768-7773: unsupported Unicode code range"
</code></pre>
<p>if I bypass .decode step and do some parsing with lxml library, it raises an error when I am saving parsed title to database:</p>
<pre><code>'utf8' codec can't decode bytes in position 45-50: unsupported Unicode code range
</code></pre>
<p>My database has character set utf8 and collation utf-general-ci</p>
<p>My settings:<br />
Django<br />
Python 2.4.3<br />
MySQL 5.0.22<br />
MySQL-python 1.2.1<br />
mod_python 3.2.8 </p>
| 0 | 2009-07-09T03:34:42Z | 1,101,745 | <p>If the <code>webpage</code> declares encoding <code>iso-8859-1</code>, can't you just do <code>webpage.decode("iso-8859-1")</code>?</p>
<p>At that point, <code>webpage</code> is decoded for your app. When it is written into the database, the mapping there should handle the char-to-utf8 encoding.</p>
<p>To get the correct encoding, either tell the webserver that you only accept, say, UTF-8 and then that's what you'll (hopefully) always get, since just about everyone reads UTF-8 (or you could try it with ISO-8859-1); or use .info to inspect the encoding name of the stream returned.</p>
<p>See <a href="http://www.voidspace.org.uk/python/articles/urllib2.shtml" rel="nofollow">urllib2 - The Missing Manual</a> and <a href="http://www.cs.tut.fi/~jkorpela/http.html" rel="nofollow">Quick reference to HTTP headers</a> for details.</p>
| 3 | 2009-07-09T03:48:02Z | [
"python",
"unicode",
"encoding",
"utf-8",
"urllib"
] |
Unicode problem Django-Python-URLLIB-MySQL | 1,101,715 | <p>I am fetching a webpage (<a href="http://autoweek.com" rel="nofollow">http://autoweek.com</a>) and trying to process it but getting encoding error. Autoweek declares "iso-8859-1" encoding and has the word "Nürburgring" (u with umlaut)</p>
<p>I do: </p>
<pre><code># -*- encoding: utf-8 -*-
import urllib
webpage = urllib.urlopen(feed.crawl_url).read()
webpage.decode("utf-8")
</code></pre>
<p>it gives me the following error:</p>
<pre><code>'utf8' codec can't decode bytes in position 7768-7773: unsupported Unicode code range"
</code></pre>
<p>if I bypass .decode step and do some parsing with lxml library, it raises an error when I am saving parsed title to database:</p>
<pre><code>'utf8' codec can't decode bytes in position 45-50: unsupported Unicode code range
</code></pre>
<p>My database has character set utf8 and collation utf-general-ci</p>
<p>My settings:<br />
Django<br />
Python 2.4.3<br />
MySQL 5.0.22<br />
MySQL-python 1.2.1<br />
mod_python 3.2.8 </p>
| 0 | 2009-07-09T03:34:42Z | 1,102,213 | <p><a href="http://autoweek.com" rel="nofollow">autoweek.com</a> seems confused about it's own encoding. It declares conflicting charset definitions:</p>
<pre><code><meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</code></pre>
<p>and later...</p>
<pre><code><meta charset=iso-8859-1"/>.
</code></pre>
<p>iso-8859-1 is the correct one since this is returned in the header from the web server and by the <code>.info()</code> method (and it actually decodes), but this demonstrates that you can't necessarily rely on the Content-Type declaration in web pages. You should follow the method described by lavinio.</p>
| 0 | 2009-07-09T06:50:44Z | [
"python",
"unicode",
"encoding",
"utf-8",
"urllib"
] |
Tkinter: AttributeError: NoneType object has no attribute get | 1,101,750 | <p>I have seen a couple of other posts on similar error message but couldn't find a solution which would fix it in my case.</p>
<p>I dabbled a bit with TkInter and created a very simple UI. The code follows-</p>
<pre><code>from string import *
from Tkinter import *
import tkMessageBox
root=Tk()
vid = IntVar()
def grabText(event):
if entryBox.get().strip()=="":
tkMessageBox.showerror("Error", "Please enter text")
else:
print entryBox.get().strip()
root.title("My Sample")
root.maxsize(width=550, height=200)
root.minsize(width=550, height=200)
root.resizable(width=NO, height=NO)
label=Label(root, text = "Enter text:").grid(row=2,column=0,sticky=W)
entryBox=Entry(root,width=60).grid(row=2, column=1,sticky=W)
grabBtn=Button(root, text="Grab")
grabBtn.grid(row=8, column=1)
grabBtn.bind('<Button-1>', grabText)
root.mainloop()
</code></pre>
<p>I get the UI up and running. When I click on the <code>Grab</code> button, I get the following error on the console:</p>
<pre><code>C:\Python25>python.exe myFiles\testBed.py
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python25\lib\lib-tk\Tkinter.py", line 1403, in __call__
return self.func(*args)
File "myFiles\testBed.py", line 10, in grabText
if entryBox.get().strip()=="":
AttributeError: 'NoneType' object has no attribute 'get'
</code></pre>
<p>The error traces back to <code>Tkinter.py</code>.</p>
<p>I'm sure some one might have dealt with this before. Any help is appreciated.</p>
| 14 | 2009-07-09T03:48:56Z | 1,101,765 | <p>The <code>grid</code> (and <code>pack</code>, and <code>place</code>) function of the <code>Entry</code> object (and of all other widgets) returns <code>None</code>. In python when you do <code>a().b()</code>, the result of the expression is whatever <code>b()</code> returns, therefore <code>Entry(...).grid(...)</code> will return <code>None</code>. </p>
<p>You should split that onto two lines, like this:</p>
<pre><code>entryBox = Entry(root, width=60)
entryBox.grid(row=2, column=1, sticky=W)
</code></pre>
<p>That way, you get your <code>Entry</code> reference stored in <code>entryBox</code>, and it's laid out like you expect. This has a bonus side effect of making your layout easier to understand and maintain, if you collect all of your <code>grid</code> and/or <code>pack</code> statements in blocks. </p>
| 39 | 2009-07-09T03:53:34Z | [
"python",
"user-interface",
"tkinter"
] |
Tkinter: AttributeError: NoneType object has no attribute get | 1,101,750 | <p>I have seen a couple of other posts on similar error message but couldn't find a solution which would fix it in my case.</p>
<p>I dabbled a bit with TkInter and created a very simple UI. The code follows-</p>
<pre><code>from string import *
from Tkinter import *
import tkMessageBox
root=Tk()
vid = IntVar()
def grabText(event):
if entryBox.get().strip()=="":
tkMessageBox.showerror("Error", "Please enter text")
else:
print entryBox.get().strip()
root.title("My Sample")
root.maxsize(width=550, height=200)
root.minsize(width=550, height=200)
root.resizable(width=NO, height=NO)
label=Label(root, text = "Enter text:").grid(row=2,column=0,sticky=W)
entryBox=Entry(root,width=60).grid(row=2, column=1,sticky=W)
grabBtn=Button(root, text="Grab")
grabBtn.grid(row=8, column=1)
grabBtn.bind('<Button-1>', grabText)
root.mainloop()
</code></pre>
<p>I get the UI up and running. When I click on the <code>Grab</code> button, I get the following error on the console:</p>
<pre><code>C:\Python25>python.exe myFiles\testBed.py
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python25\lib\lib-tk\Tkinter.py", line 1403, in __call__
return self.func(*args)
File "myFiles\testBed.py", line 10, in grabText
if entryBox.get().strip()=="":
AttributeError: 'NoneType' object has no attribute 'get'
</code></pre>
<p>The error traces back to <code>Tkinter.py</code>.</p>
<p>I'm sure some one might have dealt with this before. Any help is appreciated.</p>
| 14 | 2009-07-09T03:48:56Z | 1,102,053 | <p>Change this line:</p>
<pre><code>entryBox=Entry(root,width=60).grid(row=2, column=1,sticky=W)
</code></pre>
<p>into these two lines:</p>
<pre><code>entryBox=Entry(root,width=60)
entryBox.grid(row=2, column=1,sticky=W)
</code></pre>
<p>The same goes for <code>label</code> by the way - just as you already correctly do for <code>grabBtn</code>!</p>
| 3 | 2009-07-09T05:55:49Z | [
"python",
"user-interface",
"tkinter"
] |
Is there a way to plan and diagram an architecture for dynamic scripting languages like groovy or python? | 1,102,134 | <p>Say I want to write a large application in groovy, and take advantage of closures, categories and other concepts (that I regularly use to separate concerns). Is there a way to diagram or otherwise communicate in a simple way the architecture of some of this stuff? How do you detail (without verbose documentation) the things that a map of closures might do, for example? I understand that dynamic language features aren't usually recommended on a larger scale because they are seen as complex but does that have to be the case?</p>
| 1 | 2009-07-09T06:23:17Z | 1,102,164 | <p>If you don't want to generate verbose documentation, a picture is worth a thousand words. I've found tools like <a href="http://freemind.sourceforge.net/wiki/index.php/Main_Page" rel="nofollow">FreeMind</a> useful, both for clarifying my ideas and for communicating them to others. And if you are willing to invest in a medium (or at least higher) level of documentation, I would recommend <a href="http://sphinx.pocoo.org/index.html" rel="nofollow">Sphinx</a>. It is pretty easy to use, and although it's oriented towards documentation of Python modules, it can generate completely generic documentation which looks professional and easy on the eye. Your documentation can contain diagrams such as are created using <a href="http://graphviz.org/" rel="nofollow">Graphviz</a>.</p>
| 1 | 2009-07-09T06:34:21Z | [
"python",
"architecture",
"groovy",
"uml",
"dynamic-languages"
] |
Is there a way to plan and diagram an architecture for dynamic scripting languages like groovy or python? | 1,102,134 | <p>Say I want to write a large application in groovy, and take advantage of closures, categories and other concepts (that I regularly use to separate concerns). Is there a way to diagram or otherwise communicate in a simple way the architecture of some of this stuff? How do you detail (without verbose documentation) the things that a map of closures might do, for example? I understand that dynamic language features aren't usually recommended on a larger scale because they are seen as complex but does that have to be the case?</p>
| 1 | 2009-07-09T06:23:17Z | 1,102,219 | <p>UML isn't too well equipped to handle such things, but you can still use it to communicate your design if you are willing to do some mental mapping. You can find an isomorphism between most dynamic concepts and UMLs static object-model.</p>
<p>For example you can think of a closure as an object implementing a one method interface. It's probably useful to model such interfaces as something a bit more specific than <em>interface Callable { call(args[0..</em>]: Object) : Object }_.</p>
<p>Duck typing can similarly though of as an interface. If you have a method that takes something that can quack, model it as taking an object that is a specialization of the interface _interface Quackable { quack() }.</p>
<p>You can use your imagination for other concepts. Keep in mind that the purpose of design diagrams is to communicate ideas. So don't get overly pedantic about modeling everything 100%, think what do you want your diagrams to say, make sure that they say that and eliminate any extraneous detail that would dilute the message. And if you use some concepts that aren't obvious to your target audience, explain them.</p>
<p>Also, if UML really can't handle what you want to say, try other ways to visualize your message. UML is only a good choice because it gives you a common vocabulary so you don't have to explain every concept on your diagram.</p>
| 3 | 2009-07-09T06:52:39Z | [
"python",
"architecture",
"groovy",
"uml",
"dynamic-languages"
] |
Should I use Celery or Carrot for a Django project? | 1,102,254 | <p>I'm a little confused as to which one I should use. I think either will work, but is one better or more appropriate than the other?</p>
<p><a href="http://github.com/ask/carrot/tree/master">http://github.com/ask/carrot/tree/master</a></p>
<p><a href="http://github.com/ask/celery/tree/master">http://github.com/ask/celery/tree/master</a></p>
| 19 | 2009-07-09T07:05:44Z | 1,102,290 | <p>If you need to send/receive messages to/from AMQP message queues, use <code>carrot</code>.</p>
<p>If you want to run scheduled tasks on a number of machines, use <code>celery</code>.</p>
<p>If you're making soup, use both ;-)</p>
| 69 | 2009-07-09T07:15:14Z | [
"python",
"django",
"message-queue",
"rabbitmq",
"amqp"
] |
Should I use Celery or Carrot for a Django project? | 1,102,254 | <p>I'm a little confused as to which one I should use. I think either will work, but is one better or more appropriate than the other?</p>
<p><a href="http://github.com/ask/carrot/tree/master">http://github.com/ask/carrot/tree/master</a></p>
<p><a href="http://github.com/ask/celery/tree/master">http://github.com/ask/celery/tree/master</a></p>
| 19 | 2009-07-09T07:05:44Z | 1,970,813 | <p>May you should see this <a href="http://www.slideshare.net/idangazit/an-introduction-to-celery">http://www.slideshare.net/idangazit/an-introduction-to-celery</a></p>
| 6 | 2009-12-28T18:22:08Z | [
"python",
"django",
"message-queue",
"rabbitmq",
"amqp"
] |
python - Problem storing Unicode character to MySQL with Django | 1,102,465 | <p>I have the string </p>
<pre><code> u"Played Mirror's Edge\u2122"
</code></pre>
<p>Which should be shown as </p>
<pre><code> Played Mirror's Edgeâ¢
</code></pre>
<p>But that is another issue. My problem at hand is that I'm putting it in a model and then trying to save it to a database. AKA:</p>
<pre><code>a = models.Achievement(name=u"Played Mirror's Edge\u2122")
a.save()
</code></pre>
<p>And I'm getting :</p>
<pre><code>'ascii' codec can't encode character u'\u2122' in position 13: ordinal not in range(128)
</code></pre>
<p>full stack trace (as requested) :</p>
<pre><code>Traceback:
File "/var/home/ptarjan/django/mysite/django/core/handlers/base.py" in get_response
86. response = callback(request, *callback_args, **callback_kwargs)
File "/var/home/ptarjan/django/mysite/yourock/views/alias.py" in import_all
161. types.import_all(type, alias)
File "/var/home/ptarjan/django/mysite/yourock/types/types.py" in import_all
52. return modules[type].import_all(siteAlias, alias)
File "/var/home/ptarjan/django/mysite/yourock/types/xbox.py" in import_all
117. achiever = self.add_achievement(dict, siteAlias, alias)
File "/var/home/ptarjan/django/mysite/yourock/types/base_profile.py" in add_achievement
130. owner = siteAlias,
File "/var/home/ptarjan/django/mysite/django/db/models/query.py" in get
304. num = len(clone)
File "/var/home/ptarjan/django/mysite/django/db/models/query.py" in __len__
160. self._result_cache = list(self.iterator())
File "/var/home/ptarjan/django/mysite/django/db/models/query.py" in iterator
275. for row in self.query.results_iter():
File "/var/home/ptarjan/django/mysite/django/db/models/sql/query.py" in results_iter
206. for rows in self.execute_sql(MULTI):
File "/var/home/ptarjan/django/mysite/django/db/models/sql/query.py" in execute_sql
1734. cursor.execute(sql, params)
File "/var/home/ptarjan/django/mysite/django/db/backends/util.py" in execute
19. return self.cursor.execute(sql, params)
File "/var/home/ptarjan/django/mysite/django/db/backends/mysql/base.py" in execute
83. return self.cursor.execute(query, args)
File "/usr/lib/pymodules/python2.5/MySQLdb/cursors.py" in execute
151. query = query % db.literal(args)
File "/usr/lib/pymodules/python2.5/MySQLdb/connections.py" in literal
247. return self.escape(o, self.encoders)
File "/usr/lib/pymodules/python2.5/MySQLdb/connections.py" in string_literal
180. return db.string_literal(obj)
Exception Type: UnicodeEncodeError at /import/xbox:bob
Exception Value: 'ascii' codec can't encode character u'\u2122' in position 13: ordinal not in range(128)
</code></pre>
<p>And the pertinant part of the model :</p>
<pre><code>class Achievement(MyBaseModel):
name = models.CharField(max_length=100, help_text="A human readable achievement name")
</code></pre>
<p>I'm using a MySQL backend with this in my settings.py</p>
<pre><code>DEFAULT_CHARSET = 'utf-8'
</code></pre>
<p>So basically, how the heck should I deal with all this unicode stuff? I was hoping it would all "just work" if I stayed away from funny character sets and stuck to UTF8. Alas, it seems to not be just that easy.</p>
| 6 | 2009-07-09T08:04:19Z | 1,102,488 | <p>I was working on this yesterday, and I found that adding "charset=utf8" and "use_unicode=1" to the connection string made it work (using SQLAlchemy, guess it's the same problem).</p>
<p>So my string looks like:
"mysql://user:pass@host:3306/database?use_unicode=1&charset=utf8"</p>
| 1 | 2009-07-09T08:11:43Z | [
"python",
"mysql",
"django",
"unicode",
"django-models"
] |
python - Problem storing Unicode character to MySQL with Django | 1,102,465 | <p>I have the string </p>
<pre><code> u"Played Mirror's Edge\u2122"
</code></pre>
<p>Which should be shown as </p>
<pre><code> Played Mirror's Edgeâ¢
</code></pre>
<p>But that is another issue. My problem at hand is that I'm putting it in a model and then trying to save it to a database. AKA:</p>
<pre><code>a = models.Achievement(name=u"Played Mirror's Edge\u2122")
a.save()
</code></pre>
<p>And I'm getting :</p>
<pre><code>'ascii' codec can't encode character u'\u2122' in position 13: ordinal not in range(128)
</code></pre>
<p>full stack trace (as requested) :</p>
<pre><code>Traceback:
File "/var/home/ptarjan/django/mysite/django/core/handlers/base.py" in get_response
86. response = callback(request, *callback_args, **callback_kwargs)
File "/var/home/ptarjan/django/mysite/yourock/views/alias.py" in import_all
161. types.import_all(type, alias)
File "/var/home/ptarjan/django/mysite/yourock/types/types.py" in import_all
52. return modules[type].import_all(siteAlias, alias)
File "/var/home/ptarjan/django/mysite/yourock/types/xbox.py" in import_all
117. achiever = self.add_achievement(dict, siteAlias, alias)
File "/var/home/ptarjan/django/mysite/yourock/types/base_profile.py" in add_achievement
130. owner = siteAlias,
File "/var/home/ptarjan/django/mysite/django/db/models/query.py" in get
304. num = len(clone)
File "/var/home/ptarjan/django/mysite/django/db/models/query.py" in __len__
160. self._result_cache = list(self.iterator())
File "/var/home/ptarjan/django/mysite/django/db/models/query.py" in iterator
275. for row in self.query.results_iter():
File "/var/home/ptarjan/django/mysite/django/db/models/sql/query.py" in results_iter
206. for rows in self.execute_sql(MULTI):
File "/var/home/ptarjan/django/mysite/django/db/models/sql/query.py" in execute_sql
1734. cursor.execute(sql, params)
File "/var/home/ptarjan/django/mysite/django/db/backends/util.py" in execute
19. return self.cursor.execute(sql, params)
File "/var/home/ptarjan/django/mysite/django/db/backends/mysql/base.py" in execute
83. return self.cursor.execute(query, args)
File "/usr/lib/pymodules/python2.5/MySQLdb/cursors.py" in execute
151. query = query % db.literal(args)
File "/usr/lib/pymodules/python2.5/MySQLdb/connections.py" in literal
247. return self.escape(o, self.encoders)
File "/usr/lib/pymodules/python2.5/MySQLdb/connections.py" in string_literal
180. return db.string_literal(obj)
Exception Type: UnicodeEncodeError at /import/xbox:bob
Exception Value: 'ascii' codec can't encode character u'\u2122' in position 13: ordinal not in range(128)
</code></pre>
<p>And the pertinant part of the model :</p>
<pre><code>class Achievement(MyBaseModel):
name = models.CharField(max_length=100, help_text="A human readable achievement name")
</code></pre>
<p>I'm using a MySQL backend with this in my settings.py</p>
<pre><code>DEFAULT_CHARSET = 'utf-8'
</code></pre>
<p>So basically, how the heck should I deal with all this unicode stuff? I was hoping it would all "just work" if I stayed away from funny character sets and stuck to UTF8. Alas, it seems to not be just that easy.</p>
| 6 | 2009-07-09T08:04:19Z | 1,102,490 | <p>You are using strings of type 'unicode'. If your model or SQL backend does not support them or does not know how to convert to UTF-8, simply do the conversion yourself. Stick with simple strings (python type str) and convert like in</p>
<pre><code>a = models.Achievement(name=u"Played Mirror's Edge\u2122".encode("UTF-8"))
</code></pre>
| 3 | 2009-07-09T08:11:52Z | [
"python",
"mysql",
"django",
"unicode",
"django-models"
] |
python - Problem storing Unicode character to MySQL with Django | 1,102,465 | <p>I have the string </p>
<pre><code> u"Played Mirror's Edge\u2122"
</code></pre>
<p>Which should be shown as </p>
<pre><code> Played Mirror's Edgeâ¢
</code></pre>
<p>But that is another issue. My problem at hand is that I'm putting it in a model and then trying to save it to a database. AKA:</p>
<pre><code>a = models.Achievement(name=u"Played Mirror's Edge\u2122")
a.save()
</code></pre>
<p>And I'm getting :</p>
<pre><code>'ascii' codec can't encode character u'\u2122' in position 13: ordinal not in range(128)
</code></pre>
<p>full stack trace (as requested) :</p>
<pre><code>Traceback:
File "/var/home/ptarjan/django/mysite/django/core/handlers/base.py" in get_response
86. response = callback(request, *callback_args, **callback_kwargs)
File "/var/home/ptarjan/django/mysite/yourock/views/alias.py" in import_all
161. types.import_all(type, alias)
File "/var/home/ptarjan/django/mysite/yourock/types/types.py" in import_all
52. return modules[type].import_all(siteAlias, alias)
File "/var/home/ptarjan/django/mysite/yourock/types/xbox.py" in import_all
117. achiever = self.add_achievement(dict, siteAlias, alias)
File "/var/home/ptarjan/django/mysite/yourock/types/base_profile.py" in add_achievement
130. owner = siteAlias,
File "/var/home/ptarjan/django/mysite/django/db/models/query.py" in get
304. num = len(clone)
File "/var/home/ptarjan/django/mysite/django/db/models/query.py" in __len__
160. self._result_cache = list(self.iterator())
File "/var/home/ptarjan/django/mysite/django/db/models/query.py" in iterator
275. for row in self.query.results_iter():
File "/var/home/ptarjan/django/mysite/django/db/models/sql/query.py" in results_iter
206. for rows in self.execute_sql(MULTI):
File "/var/home/ptarjan/django/mysite/django/db/models/sql/query.py" in execute_sql
1734. cursor.execute(sql, params)
File "/var/home/ptarjan/django/mysite/django/db/backends/util.py" in execute
19. return self.cursor.execute(sql, params)
File "/var/home/ptarjan/django/mysite/django/db/backends/mysql/base.py" in execute
83. return self.cursor.execute(query, args)
File "/usr/lib/pymodules/python2.5/MySQLdb/cursors.py" in execute
151. query = query % db.literal(args)
File "/usr/lib/pymodules/python2.5/MySQLdb/connections.py" in literal
247. return self.escape(o, self.encoders)
File "/usr/lib/pymodules/python2.5/MySQLdb/connections.py" in string_literal
180. return db.string_literal(obj)
Exception Type: UnicodeEncodeError at /import/xbox:bob
Exception Value: 'ascii' codec can't encode character u'\u2122' in position 13: ordinal not in range(128)
</code></pre>
<p>And the pertinant part of the model :</p>
<pre><code>class Achievement(MyBaseModel):
name = models.CharField(max_length=100, help_text="A human readable achievement name")
</code></pre>
<p>I'm using a MySQL backend with this in my settings.py</p>
<pre><code>DEFAULT_CHARSET = 'utf-8'
</code></pre>
<p>So basically, how the heck should I deal with all this unicode stuff? I was hoping it would all "just work" if I stayed away from funny character sets and stuck to UTF8. Alas, it seems to not be just that easy.</p>
| 6 | 2009-07-09T08:04:19Z | 1,102,518 | <p><del>To me the apostrophe looks strange, should it not be escapded like so:</del></p>
<pre><code>u"Played Mirror\'s Edge\u2122"
</code></pre>
| -1 | 2009-07-09T08:25:41Z | [
"python",
"mysql",
"django",
"unicode",
"django-models"
] |
python - Problem storing Unicode character to MySQL with Django | 1,102,465 | <p>I have the string </p>
<pre><code> u"Played Mirror's Edge\u2122"
</code></pre>
<p>Which should be shown as </p>
<pre><code> Played Mirror's Edgeâ¢
</code></pre>
<p>But that is another issue. My problem at hand is that I'm putting it in a model and then trying to save it to a database. AKA:</p>
<pre><code>a = models.Achievement(name=u"Played Mirror's Edge\u2122")
a.save()
</code></pre>
<p>And I'm getting :</p>
<pre><code>'ascii' codec can't encode character u'\u2122' in position 13: ordinal not in range(128)
</code></pre>
<p>full stack trace (as requested) :</p>
<pre><code>Traceback:
File "/var/home/ptarjan/django/mysite/django/core/handlers/base.py" in get_response
86. response = callback(request, *callback_args, **callback_kwargs)
File "/var/home/ptarjan/django/mysite/yourock/views/alias.py" in import_all
161. types.import_all(type, alias)
File "/var/home/ptarjan/django/mysite/yourock/types/types.py" in import_all
52. return modules[type].import_all(siteAlias, alias)
File "/var/home/ptarjan/django/mysite/yourock/types/xbox.py" in import_all
117. achiever = self.add_achievement(dict, siteAlias, alias)
File "/var/home/ptarjan/django/mysite/yourock/types/base_profile.py" in add_achievement
130. owner = siteAlias,
File "/var/home/ptarjan/django/mysite/django/db/models/query.py" in get
304. num = len(clone)
File "/var/home/ptarjan/django/mysite/django/db/models/query.py" in __len__
160. self._result_cache = list(self.iterator())
File "/var/home/ptarjan/django/mysite/django/db/models/query.py" in iterator
275. for row in self.query.results_iter():
File "/var/home/ptarjan/django/mysite/django/db/models/sql/query.py" in results_iter
206. for rows in self.execute_sql(MULTI):
File "/var/home/ptarjan/django/mysite/django/db/models/sql/query.py" in execute_sql
1734. cursor.execute(sql, params)
File "/var/home/ptarjan/django/mysite/django/db/backends/util.py" in execute
19. return self.cursor.execute(sql, params)
File "/var/home/ptarjan/django/mysite/django/db/backends/mysql/base.py" in execute
83. return self.cursor.execute(query, args)
File "/usr/lib/pymodules/python2.5/MySQLdb/cursors.py" in execute
151. query = query % db.literal(args)
File "/usr/lib/pymodules/python2.5/MySQLdb/connections.py" in literal
247. return self.escape(o, self.encoders)
File "/usr/lib/pymodules/python2.5/MySQLdb/connections.py" in string_literal
180. return db.string_literal(obj)
Exception Type: UnicodeEncodeError at /import/xbox:bob
Exception Value: 'ascii' codec can't encode character u'\u2122' in position 13: ordinal not in range(128)
</code></pre>
<p>And the pertinant part of the model :</p>
<pre><code>class Achievement(MyBaseModel):
name = models.CharField(max_length=100, help_text="A human readable achievement name")
</code></pre>
<p>I'm using a MySQL backend with this in my settings.py</p>
<pre><code>DEFAULT_CHARSET = 'utf-8'
</code></pre>
<p>So basically, how the heck should I deal with all this unicode stuff? I was hoping it would all "just work" if I stayed away from funny character sets and stuck to UTF8. Alas, it seems to not be just that easy.</p>
| 6 | 2009-07-09T08:04:19Z | 1,102,567 | <p>I agree with Nikolai. I already encountered problem to use UTF-8, even in pure Python (2.5).</p>
<p>I finally used the unicode function(?): </p>
<pre><code>entry = unicode(sys.stdin, ENCODING)
</code></pre>
<p>ENCODING was depending on the locale, if I remember well:</p>
<pre><code>import sys, locale
ENCODING = locale.getdefaultlocale()[1]
DEFAULT_ENCODING = sys.getdefaultencoding()
</code></pre>
<p>Maybe take a look at the <a href="http://www.amk.ca/python/howto/unicode" rel="nofollow">Python Unicode HOWTO</a> ?</p>
| 0 | 2009-07-09T08:33:52Z | [
"python",
"mysql",
"django",
"unicode",
"django-models"
] |
python - Problem storing Unicode character to MySQL with Django | 1,102,465 | <p>I have the string </p>
<pre><code> u"Played Mirror's Edge\u2122"
</code></pre>
<p>Which should be shown as </p>
<pre><code> Played Mirror's Edgeâ¢
</code></pre>
<p>But that is another issue. My problem at hand is that I'm putting it in a model and then trying to save it to a database. AKA:</p>
<pre><code>a = models.Achievement(name=u"Played Mirror's Edge\u2122")
a.save()
</code></pre>
<p>And I'm getting :</p>
<pre><code>'ascii' codec can't encode character u'\u2122' in position 13: ordinal not in range(128)
</code></pre>
<p>full stack trace (as requested) :</p>
<pre><code>Traceback:
File "/var/home/ptarjan/django/mysite/django/core/handlers/base.py" in get_response
86. response = callback(request, *callback_args, **callback_kwargs)
File "/var/home/ptarjan/django/mysite/yourock/views/alias.py" in import_all
161. types.import_all(type, alias)
File "/var/home/ptarjan/django/mysite/yourock/types/types.py" in import_all
52. return modules[type].import_all(siteAlias, alias)
File "/var/home/ptarjan/django/mysite/yourock/types/xbox.py" in import_all
117. achiever = self.add_achievement(dict, siteAlias, alias)
File "/var/home/ptarjan/django/mysite/yourock/types/base_profile.py" in add_achievement
130. owner = siteAlias,
File "/var/home/ptarjan/django/mysite/django/db/models/query.py" in get
304. num = len(clone)
File "/var/home/ptarjan/django/mysite/django/db/models/query.py" in __len__
160. self._result_cache = list(self.iterator())
File "/var/home/ptarjan/django/mysite/django/db/models/query.py" in iterator
275. for row in self.query.results_iter():
File "/var/home/ptarjan/django/mysite/django/db/models/sql/query.py" in results_iter
206. for rows in self.execute_sql(MULTI):
File "/var/home/ptarjan/django/mysite/django/db/models/sql/query.py" in execute_sql
1734. cursor.execute(sql, params)
File "/var/home/ptarjan/django/mysite/django/db/backends/util.py" in execute
19. return self.cursor.execute(sql, params)
File "/var/home/ptarjan/django/mysite/django/db/backends/mysql/base.py" in execute
83. return self.cursor.execute(query, args)
File "/usr/lib/pymodules/python2.5/MySQLdb/cursors.py" in execute
151. query = query % db.literal(args)
File "/usr/lib/pymodules/python2.5/MySQLdb/connections.py" in literal
247. return self.escape(o, self.encoders)
File "/usr/lib/pymodules/python2.5/MySQLdb/connections.py" in string_literal
180. return db.string_literal(obj)
Exception Type: UnicodeEncodeError at /import/xbox:bob
Exception Value: 'ascii' codec can't encode character u'\u2122' in position 13: ordinal not in range(128)
</code></pre>
<p>And the pertinant part of the model :</p>
<pre><code>class Achievement(MyBaseModel):
name = models.CharField(max_length=100, help_text="A human readable achievement name")
</code></pre>
<p>I'm using a MySQL backend with this in my settings.py</p>
<pre><code>DEFAULT_CHARSET = 'utf-8'
</code></pre>
<p>So basically, how the heck should I deal with all this unicode stuff? I was hoping it would all "just work" if I stayed away from funny character sets and stuck to UTF8. Alas, it seems to not be just that easy.</p>
| 6 | 2009-07-09T08:04:19Z | 1,104,201 | <p>A few remarks: </p>
<ul>
<li><p>Python 2.x has two string types</p>
<ul>
<li>"str", which is basically a byte array (so you can store anything you like in it)</li>
<li>"unicode" , which is UCS2/UCS4 encoded unicode internally</li>
</ul></li>
<li><p>Instances of these types are considered "decoded" data. The internal representation is the reference, so you "decode" external data into it, and "encode" into some external format.</p></li>
<li><p>A good strategy is to decode as early as possible when data enters the system, and encode as late as possible. Try to use unicode for the strings in your system as much as possible. (I disagree with Nikolai in this regard).</p></li>
<li><p>This encoding aspect applies to Nicolai's answer. He takes the original unicode string, and encodes it into utf-8. But this <strong>doesn't solve</strong> the problem (at least not generally), because the resulting byte buffer can <strong>still</strong> contain bytes outside the range(127) (I haven't checked for \u2122), which means you will hit the same exception again.</p></li>
<li><p>Still Nicolai's analysis holds that you are passing a unicode string, but somewhere down in the system this is regarded a str instance. It suffices if somewhere the str() function is applied to your unicode argument.</p></li>
<li><p>In that case Python uses the so called default encoding which is ascii if you don't change it. There is a function sys.setdefaultencoding which you can use to switch to e.g. utf-8, but the function is only available in a limited context, so you cannot easily use it in application code.</p></li>
<li><p>My feeling is the problem is somewhere deeper in the layers you are calling. Unfortunately, I cannot comment on Django or MySQL/SQLalchemy, but I wonder if you could specify a unicode type when declaring the 'name' attribute in your model. It would be good DB practice to handle type information on the field level. Maybe there is an alternative to CharField?!</p></li>
<li><p>And yes, you can safely embed a single quote (') in a double quoted (") string, and vice versa.</p></li>
</ul>
| 4 | 2009-07-09T14:22:19Z | [
"python",
"mysql",
"django",
"unicode",
"django-models"
] |
python - Problem storing Unicode character to MySQL with Django | 1,102,465 | <p>I have the string </p>
<pre><code> u"Played Mirror's Edge\u2122"
</code></pre>
<p>Which should be shown as </p>
<pre><code> Played Mirror's Edgeâ¢
</code></pre>
<p>But that is another issue. My problem at hand is that I'm putting it in a model and then trying to save it to a database. AKA:</p>
<pre><code>a = models.Achievement(name=u"Played Mirror's Edge\u2122")
a.save()
</code></pre>
<p>And I'm getting :</p>
<pre><code>'ascii' codec can't encode character u'\u2122' in position 13: ordinal not in range(128)
</code></pre>
<p>full stack trace (as requested) :</p>
<pre><code>Traceback:
File "/var/home/ptarjan/django/mysite/django/core/handlers/base.py" in get_response
86. response = callback(request, *callback_args, **callback_kwargs)
File "/var/home/ptarjan/django/mysite/yourock/views/alias.py" in import_all
161. types.import_all(type, alias)
File "/var/home/ptarjan/django/mysite/yourock/types/types.py" in import_all
52. return modules[type].import_all(siteAlias, alias)
File "/var/home/ptarjan/django/mysite/yourock/types/xbox.py" in import_all
117. achiever = self.add_achievement(dict, siteAlias, alias)
File "/var/home/ptarjan/django/mysite/yourock/types/base_profile.py" in add_achievement
130. owner = siteAlias,
File "/var/home/ptarjan/django/mysite/django/db/models/query.py" in get
304. num = len(clone)
File "/var/home/ptarjan/django/mysite/django/db/models/query.py" in __len__
160. self._result_cache = list(self.iterator())
File "/var/home/ptarjan/django/mysite/django/db/models/query.py" in iterator
275. for row in self.query.results_iter():
File "/var/home/ptarjan/django/mysite/django/db/models/sql/query.py" in results_iter
206. for rows in self.execute_sql(MULTI):
File "/var/home/ptarjan/django/mysite/django/db/models/sql/query.py" in execute_sql
1734. cursor.execute(sql, params)
File "/var/home/ptarjan/django/mysite/django/db/backends/util.py" in execute
19. return self.cursor.execute(sql, params)
File "/var/home/ptarjan/django/mysite/django/db/backends/mysql/base.py" in execute
83. return self.cursor.execute(query, args)
File "/usr/lib/pymodules/python2.5/MySQLdb/cursors.py" in execute
151. query = query % db.literal(args)
File "/usr/lib/pymodules/python2.5/MySQLdb/connections.py" in literal
247. return self.escape(o, self.encoders)
File "/usr/lib/pymodules/python2.5/MySQLdb/connections.py" in string_literal
180. return db.string_literal(obj)
Exception Type: UnicodeEncodeError at /import/xbox:bob
Exception Value: 'ascii' codec can't encode character u'\u2122' in position 13: ordinal not in range(128)
</code></pre>
<p>And the pertinant part of the model :</p>
<pre><code>class Achievement(MyBaseModel):
name = models.CharField(max_length=100, help_text="A human readable achievement name")
</code></pre>
<p>I'm using a MySQL backend with this in my settings.py</p>
<pre><code>DEFAULT_CHARSET = 'utf-8'
</code></pre>
<p>So basically, how the heck should I deal with all this unicode stuff? I was hoping it would all "just work" if I stayed away from funny character sets and stuck to UTF8. Alas, it seems to not be just that easy.</p>
| 6 | 2009-07-09T08:04:19Z | 1,104,322 | <p>I was having similar problems with mysql and postgres but no problems with sqllite.</p>
<p>This is how i solved the problem with postgres (didnt test this trick with mysql but id asume it would solve it as well)</p>
<p>in the file where u are dealing with the unicode string do a </p>
<pre><code>from django.utils.safestring import SafeUnicode
</code></pre>
<p>and assume unistr is the variable containing the string, do a </p>
<pre><code>unistr = SafeUnicode(unistr)
</code></pre>
<p>in my case i was scraping from a website</p>
<p>original code which was giving problems (ht is beautifulsoup object):- </p>
<pre><code>keyword = ht.a.string
</code></pre>
<p>the fix:-</p>
<pre><code>keyword = SafeUnicode(ht.a.string)
</code></pre>
<p>I dont know why or what SafeUnicode is doing, all i know is it solved my problems.</p>
| 0 | 2009-07-09T14:42:11Z | [
"python",
"mysql",
"django",
"unicode",
"django-models"
] |
python - Problem storing Unicode character to MySQL with Django | 1,102,465 | <p>I have the string </p>
<pre><code> u"Played Mirror's Edge\u2122"
</code></pre>
<p>Which should be shown as </p>
<pre><code> Played Mirror's Edgeâ¢
</code></pre>
<p>But that is another issue. My problem at hand is that I'm putting it in a model and then trying to save it to a database. AKA:</p>
<pre><code>a = models.Achievement(name=u"Played Mirror's Edge\u2122")
a.save()
</code></pre>
<p>And I'm getting :</p>
<pre><code>'ascii' codec can't encode character u'\u2122' in position 13: ordinal not in range(128)
</code></pre>
<p>full stack trace (as requested) :</p>
<pre><code>Traceback:
File "/var/home/ptarjan/django/mysite/django/core/handlers/base.py" in get_response
86. response = callback(request, *callback_args, **callback_kwargs)
File "/var/home/ptarjan/django/mysite/yourock/views/alias.py" in import_all
161. types.import_all(type, alias)
File "/var/home/ptarjan/django/mysite/yourock/types/types.py" in import_all
52. return modules[type].import_all(siteAlias, alias)
File "/var/home/ptarjan/django/mysite/yourock/types/xbox.py" in import_all
117. achiever = self.add_achievement(dict, siteAlias, alias)
File "/var/home/ptarjan/django/mysite/yourock/types/base_profile.py" in add_achievement
130. owner = siteAlias,
File "/var/home/ptarjan/django/mysite/django/db/models/query.py" in get
304. num = len(clone)
File "/var/home/ptarjan/django/mysite/django/db/models/query.py" in __len__
160. self._result_cache = list(self.iterator())
File "/var/home/ptarjan/django/mysite/django/db/models/query.py" in iterator
275. for row in self.query.results_iter():
File "/var/home/ptarjan/django/mysite/django/db/models/sql/query.py" in results_iter
206. for rows in self.execute_sql(MULTI):
File "/var/home/ptarjan/django/mysite/django/db/models/sql/query.py" in execute_sql
1734. cursor.execute(sql, params)
File "/var/home/ptarjan/django/mysite/django/db/backends/util.py" in execute
19. return self.cursor.execute(sql, params)
File "/var/home/ptarjan/django/mysite/django/db/backends/mysql/base.py" in execute
83. return self.cursor.execute(query, args)
File "/usr/lib/pymodules/python2.5/MySQLdb/cursors.py" in execute
151. query = query % db.literal(args)
File "/usr/lib/pymodules/python2.5/MySQLdb/connections.py" in literal
247. return self.escape(o, self.encoders)
File "/usr/lib/pymodules/python2.5/MySQLdb/connections.py" in string_literal
180. return db.string_literal(obj)
Exception Type: UnicodeEncodeError at /import/xbox:bob
Exception Value: 'ascii' codec can't encode character u'\u2122' in position 13: ordinal not in range(128)
</code></pre>
<p>And the pertinant part of the model :</p>
<pre><code>class Achievement(MyBaseModel):
name = models.CharField(max_length=100, help_text="A human readable achievement name")
</code></pre>
<p>I'm using a MySQL backend with this in my settings.py</p>
<pre><code>DEFAULT_CHARSET = 'utf-8'
</code></pre>
<p>So basically, how the heck should I deal with all this unicode stuff? I was hoping it would all "just work" if I stayed away from funny character sets and stuck to UTF8. Alas, it seems to not be just that easy.</p>
| 6 | 2009-07-09T08:04:19Z | 1,106,383 | <p>Thank you to everyone who was posting here. It really helps my unicode knowledge (and hoepfully other people learned something).</p>
<p>We seemed to be all barking up the wrong tree since I tried to simplify my problem and didn't give ALL information. It seems that I wasn't using "REAL" unicode strings, but rather BeautifulSoup.NavigableString which repr themselves as unicode strings. So all the printouts looked like unicode, but they weren't.</p>
<p>Somewhere deep in the MySQLDB library they couldn't deal with these strings. </p>
<p>This worked :</p>
<pre><code>>>> Achievement.objects.get(name = u"Mirror's Edge\u2122")
<Achievement: Mirror's Edgeâ¢>
</code></pre>
<p>On the other hand :</p>
<pre><code>>>> b = BeautifulSoup(u"<span>Mirror's Edge\u2122</span>").span.string
>>> Achievement.objects.get(name = b)
... Exceptoins ...
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2122' in position 13: ordinal not in range(128)
</code></pre>
<p>But this works :</p>
<pre><code>>>> Achievement.objects.get(name = unicode(b))
<Achievement: Mirror's Edgeâ¢>
</code></pre>
<p>So, thanks again for all the unicode help, I'm sure it will come in handy. But for now ...</p>
<p><strong>WARNING</strong> : BeautifulSoup doesn't return <strong>REAL</strong> unicode strings and should be coerced with unicode() before doing anything meaningful with them.</p>
| 11 | 2009-07-09T20:52:28Z | [
"python",
"mysql",
"django",
"unicode",
"django-models"
] |
python how to create different instances of the same class into an iteration | 1,102,822 | <p>My problem is:</p>
<p>I would like to add to a Composite class Leaf objects created at runtime inside
a Composite routine like this:</p>
<pre><code>def update(self, tp, msg, stt):
"""It updates composite objects
"""
d = Leaf()
d.setDict(tp, msg, stt)
self.append_child(d)
return self.status()
</code></pre>
<p>Inside main:</p>
<pre><code>import lib.composite
c = Composite()
for i in range(0,10):
c.update(str(i), msg, stt)
</code></pre>
<p>and the Composite is:</p>
<pre><code>class Composite(Component):
def __init__(self, *args, **kw):
super(Composite, self).__init__()
self.children = []
def append_child(self, child):
self.children.append(child)
def update(self, tp, msg, stt):
d = Leaf()
d.setDict(tp, msg, stt)
self.append_child(d)
return self.status()
def status(self):
for child in self.children:
ret = child.status()
if type(child) == Leaf:
p_out("Leaf: %s has value %s" % (child, ret))
class Component(object):
def __init__(self, *args, **kw):
if type(self) == Component:
raise NotImplementedError("Component couldn't be "
"instantiated directly")
def status(self, *args, **kw):
raise NotImplementedError("Status method "
"must be implemented")
class Leaf(Component):
def __init__(self):
super(Leaf, self).__init__()
self._dict = {}
def setDict(self, type, key, value)
self._dict = { type : { key : value } }
def status(self):
return self._dict
</code></pre>
<p>But in this way I found always that my composite has just one leaf ("d") added even if
update was called many times.</p>
<p>How can I code such a routine such to be able to fill composite at runtime?</p>
| 0 | 2009-07-09T09:35:44Z | 1,102,937 | <p>What is doing the append_child? I think it should store the leafs in a list. Does it?</p>
<p>Update: you shouldn't pass self as first argument in the main function. I think that it raises an exception.</p>
<p>See code below that seems to work ok</p>
<pre>
class Component(object):
def __init__(self, *args, **kw):
pass
def setDict(self, *args, **kw):
pass
class Leaf(Component):
def __init__(self, *args, **kw):
Component.__init__(self, *args, **kw)
class Composite(Component):
def __init__(self, *args, **kw):
Component.__init__(self, *args, **kw)
self.children = []
def update(self, tp, msg, stt):
"""It updates composite objects
"""
d = Leaf()
d.setDict(tp, msg, stt)
self.append_child(d)
return 0
def append_child(self, child):
self.children.append(child)
def remove_child(self, child):
self.children.remove(child)
c =Composite()
for i in range(0,10):
c.update(str(i), "", 0)
print len(c.children)
</pre>
| 0 | 2009-07-09T09:58:12Z | [
"python",
"design-patterns",
"composite"
] |
python how to create different instances of the same class into an iteration | 1,102,822 | <p>My problem is:</p>
<p>I would like to add to a Composite class Leaf objects created at runtime inside
a Composite routine like this:</p>
<pre><code>def update(self, tp, msg, stt):
"""It updates composite objects
"""
d = Leaf()
d.setDict(tp, msg, stt)
self.append_child(d)
return self.status()
</code></pre>
<p>Inside main:</p>
<pre><code>import lib.composite
c = Composite()
for i in range(0,10):
c.update(str(i), msg, stt)
</code></pre>
<p>and the Composite is:</p>
<pre><code>class Composite(Component):
def __init__(self, *args, **kw):
super(Composite, self).__init__()
self.children = []
def append_child(self, child):
self.children.append(child)
def update(self, tp, msg, stt):
d = Leaf()
d.setDict(tp, msg, stt)
self.append_child(d)
return self.status()
def status(self):
for child in self.children:
ret = child.status()
if type(child) == Leaf:
p_out("Leaf: %s has value %s" % (child, ret))
class Component(object):
def __init__(self, *args, **kw):
if type(self) == Component:
raise NotImplementedError("Component couldn't be "
"instantiated directly")
def status(self, *args, **kw):
raise NotImplementedError("Status method "
"must be implemented")
class Leaf(Component):
def __init__(self):
super(Leaf, self).__init__()
self._dict = {}
def setDict(self, type, key, value)
self._dict = { type : { key : value } }
def status(self):
return self._dict
</code></pre>
<p>But in this way I found always that my composite has just one leaf ("d") added even if
update was called many times.</p>
<p>How can I code such a routine such to be able to fill composite at runtime?</p>
| 0 | 2009-07-09T09:35:44Z | 1,103,288 | <p>"But in this way I found always that my composite has just one leaf ("d") added even if update was called many times."</p>
<p>No, that code makes Composite having ten children.</p>
<pre><code>>>> c.children
[<__main__.Leaf object at 0xb7da77ec>, <__main__.Leaf object at 0xb7da780c>,
<__main__.Leaf object at 0xb7da788c>, <__main__.Leaf object at 0xb7da78ac>,
<__main__.Leaf object at 0xb7da78cc>, <__main__.Leaf object at 0xb7da792c>,
<__main__.Leaf object at 0xb7da794c>, <__main__.Leaf object at 0xb7da798c>,
<__main__.Leaf object at 0xb7da79ac>, <__main__.Leaf object at 0xb7da79cc>]
</code></pre>
<p>So why you think it only has one is strange.</p>
| 3 | 2009-07-09T11:27:46Z | [
"python",
"design-patterns",
"composite"
] |
Moving files under python | 1,102,825 | <p>I'm confused with file moving under python.
Under windows commandline, if i have directory c:\a and a directory c:\b, i can do</p>
<pre><code>move c:\a c:\b
</code></pre>
<p>which moves a to b result is directory structure c:\b\a</p>
<p>If I try this with os.rename or shutil.move:</p>
<pre><code>os.rename("c:/a", "c:/b")
</code></pre>
<p>I get </p>
<pre><code>WindowsError: [Error 17] Cannot create a file when that file already exists
</code></pre>
<p>If I move a single file under c:\a, it works.</p>
<p>In python how do i move a directory to another existing directory?</p>
| 8 | 2009-07-09T09:36:13Z | 1,102,857 | <p>You will need to state the full path it's being moved to:</p>
<pre><code>src = 'C:\a'
dst_dir = 'C:\b'
last_part = os.path.split(src)[1]
os.rename(src, os.path.join(dst_dir, last_part))
</code></pre>
<p>Actually, it looks like <code>shutil.move</code> will do what you want by looking at its documentation:</p>
<blockquote>
<p>If the destination is a directory or a symlink to a directory, the
source
is moved inside the directory.</p>
</blockquote>
<p>(And its <a href="http://svn.python.org/view/python/trunk/Lib/shutil.py?view=markup" rel="nofollow">source</a>.)</p>
| 0 | 2009-07-09T09:43:11Z | [
"python",
"windows",
"move"
] |
Moving files under python | 1,102,825 | <p>I'm confused with file moving under python.
Under windows commandline, if i have directory c:\a and a directory c:\b, i can do</p>
<pre><code>move c:\a c:\b
</code></pre>
<p>which moves a to b result is directory structure c:\b\a</p>
<p>If I try this with os.rename or shutil.move:</p>
<pre><code>os.rename("c:/a", "c:/b")
</code></pre>
<p>I get </p>
<pre><code>WindowsError: [Error 17] Cannot create a file when that file already exists
</code></pre>
<p>If I move a single file under c:\a, it works.</p>
<p>In python how do i move a directory to another existing directory?</p>
| 8 | 2009-07-09T09:36:13Z | 1,102,860 | <p>You can try using the <a href="http://docs.python.org/library/shutil.html#module-shutil">Shutil</a> module.</p>
| 8 | 2009-07-09T09:43:43Z | [
"python",
"windows",
"move"
] |
Moving files under python | 1,102,825 | <p>I'm confused with file moving under python.
Under windows commandline, if i have directory c:\a and a directory c:\b, i can do</p>
<pre><code>move c:\a c:\b
</code></pre>
<p>which moves a to b result is directory structure c:\b\a</p>
<p>If I try this with os.rename or shutil.move:</p>
<pre><code>os.rename("c:/a", "c:/b")
</code></pre>
<p>I get </p>
<pre><code>WindowsError: [Error 17] Cannot create a file when that file already exists
</code></pre>
<p>If I move a single file under c:\a, it works.</p>
<p>In python how do i move a directory to another existing directory?</p>
| 8 | 2009-07-09T09:36:13Z | 1,102,872 | <pre><code>os.rename("c:/a", "c:/b/a")
</code></pre>
<p>is equivalent to </p>
<pre><code>move c:\a c:\b
</code></pre>
<p>under windows commandline</p>
| 16 | 2009-07-09T09:46:37Z | [
"python",
"windows",
"move"
] |
Moving files under python | 1,102,825 | <p>I'm confused with file moving under python.
Under windows commandline, if i have directory c:\a and a directory c:\b, i can do</p>
<pre><code>move c:\a c:\b
</code></pre>
<p>which moves a to b result is directory structure c:\b\a</p>
<p>If I try this with os.rename or shutil.move:</p>
<pre><code>os.rename("c:/a", "c:/b")
</code></pre>
<p>I get </p>
<pre><code>WindowsError: [Error 17] Cannot create a file when that file already exists
</code></pre>
<p>If I move a single file under c:\a, it works.</p>
<p>In python how do i move a directory to another existing directory?</p>
| 8 | 2009-07-09T09:36:13Z | 1,102,971 | <p>When i need many file system operations I prefer using 'path' module:<br>
<strong><a href="http://pypi.python.org/pypi/path.py/2.2" rel="nofollow">http://pypi.python.org/pypi/path.py/2.2</a></strong><br></p>
<p>It's quite a good and lightweight wrapper around built-in 'os.path' module.</p>
<p>Also code:</p>
<pre><code>last_part = os.path.split(src)[1]
</code></pre>
<p>is a bit strange, cause there is special function for this:</p>
<pre><code>last_part = os.path.basename(src)
</code></pre>
| 1 | 2009-07-09T10:04:44Z | [
"python",
"windows",
"move"
] |
Moving files under python | 1,102,825 | <p>I'm confused with file moving under python.
Under windows commandline, if i have directory c:\a and a directory c:\b, i can do</p>
<pre><code>move c:\a c:\b
</code></pre>
<p>which moves a to b result is directory structure c:\b\a</p>
<p>If I try this with os.rename or shutil.move:</p>
<pre><code>os.rename("c:/a", "c:/b")
</code></pre>
<p>I get </p>
<pre><code>WindowsError: [Error 17] Cannot create a file when that file already exists
</code></pre>
<p>If I move a single file under c:\a, it works.</p>
<p>In python how do i move a directory to another existing directory?</p>
| 8 | 2009-07-09T09:36:13Z | 1,102,992 | <p>os.rename("c:/a/", "c:/b"/) --> Changes the name of folder a in folder b</p>
<p>os.rename("c:/a/", "c:/b/a") --> Put folder b into folder a</p>
| 2 | 2009-07-09T10:09:12Z | [
"python",
"windows",
"move"
] |
Moving files under python | 1,102,825 | <p>I'm confused with file moving under python.
Under windows commandline, if i have directory c:\a and a directory c:\b, i can do</p>
<pre><code>move c:\a c:\b
</code></pre>
<p>which moves a to b result is directory structure c:\b\a</p>
<p>If I try this with os.rename or shutil.move:</p>
<pre><code>os.rename("c:/a", "c:/b")
</code></pre>
<p>I get </p>
<pre><code>WindowsError: [Error 17] Cannot create a file when that file already exists
</code></pre>
<p>If I move a single file under c:\a, it works.</p>
<p>In python how do i move a directory to another existing directory?</p>
| 8 | 2009-07-09T09:36:13Z | 1,103,106 | <p>Using Twisted's <a href="http://twistedmatrix.com/documents/8.2.0/api/twisted.python.filepath.FilePath.html" rel="nofollow">FilePath</a>:</p>
<pre><code>from twisted.python.filepath import FilePath
FilePath("c:/a").moveTo(FilePath("c:/b/a"))
</code></pre>
<p>or, more generally:</p>
<pre><code>from twisted.python.filepath import FilePath
def moveToExistingDir(fileOrDir, existingDir):
fileOrDir.moveTo(existingDir.child(fileOrDir.basename()))
moveToExistingDir(FilePath("c:/a"), FilePath("c:/b"))
</code></pre>
| 0 | 2009-07-09T10:34:00Z | [
"python",
"windows",
"move"
] |
Python data/file Crc | 1,103,104 | <p>I am wanting to generate and store a CRC (or similar) value for a given list of files which can be used as a comparison at a later point. Writing a function to do this is simple enough, but is there a more standard way to do it within the Python libs?</p>
<p>The value generated does not need to be of any particular standard.</p>
| 1 | 2009-07-09T10:33:02Z | 1,103,116 | <p>recommend <a href="http://docs.python.org/library/hashlib.html" rel="nofollow">hashlib</a>, it implements a common interface to many different secure hash and message digest algorithms. Included are the FIPS secure hash algorithms SHA1 and MD5.
a demo code:</p>
<pre><code>import hashlib
m = hashlib.md5()
for line in open('data.txt', 'rb'):
m.update(line)
print m.hexdigest()
##ouput
1ab8ad413648c44aa9b90ce5abe50eea
</code></pre>
| 5 | 2009-07-09T10:36:24Z | [
"python",
"file",
"md5",
"crc",
"hashlib"
] |
Python data/file Crc | 1,103,104 | <p>I am wanting to generate and store a CRC (or similar) value for a given list of files which can be used as a comparison at a later point. Writing a function to do this is simple enough, but is there a more standard way to do it within the Python libs?</p>
<p>The value generated does not need to be of any particular standard.</p>
| 1 | 2009-07-09T10:33:02Z | 1,103,137 | <p>If you don't need one-way security you could also use <code>zlib.crc32</code> or <code>zlib.adler32</code>, as documented <a href="http://docs.python.org/library/zlib.html" rel="nofollow">here</a>.</p>
| 1 | 2009-07-09T10:43:38Z | [
"python",
"file",
"md5",
"crc",
"hashlib"
] |
Can I detect if my code is running on cPython or Jython? | 1,103,487 | <p>I'm working on a small django project that will be deployed in a servlet container later. But development is much faster if I work with cPython instead of Jython. So what I want to do is test if my code is running on cPython or Jython in my settiings.py so I can tell it to use the appropriate db driver (postgresql_psycopg2 or doj.backends.zxjdbc.postgresql). Is there a simple way to do this?</p>
| 8 | 2009-07-09T12:19:34Z | 1,103,497 | <p>if you're running Jython </p>
<pre><code>import platform
platform.system()
</code></pre>
<p>return 'Java'<br />
<a href="http://stackoverflow.com/questions/1086000/">here has some discussion</a>, hope this helps.</p>
| 13 | 2009-07-09T12:22:41Z | [
"python",
"django",
"jython"
] |
Can I detect if my code is running on cPython or Jython? | 1,103,487 | <p>I'm working on a small django project that will be deployed in a servlet container later. But development is much faster if I work with cPython instead of Jython. So what I want to do is test if my code is running on cPython or Jython in my settiings.py so I can tell it to use the appropriate db driver (postgresql_psycopg2 or doj.backends.zxjdbc.postgresql). Is there a simple way to do this?</p>
| 8 | 2009-07-09T12:19:34Z | 1,103,680 | <p>You'll have unique settings.py for every different environment.</p>
<p>Your development settings.py should not be your QA/Test or production settings.py.</p>
<p>What we do is this.</p>
<p>We have a "master" settings.py that contains the installed apps and other items which don't change much.</p>
<p>We have environment-specific files with names like <code>settings_dev_win32.py</code> and <code>settings_qa_linux2.py</code> and
'settings_co_linux2.py`, etc. </p>
<p>Each of these environment-specific settings imports the "master" settings, and then overrides things like the DB driver. Since each settings file is unique to an environment, there are no if-statements and no detecting which environment we're running in.</p>
<p>Production (in Apache, using mod_wsgi and mysql) uses the <code>settings_prod_linux2.py</code> file and no other.</p>
<p>Development (in Windows using sqlite) uses the <code>settings_dev_win32.py</code> file. </p>
| 3 | 2009-07-09T12:53:18Z | [
"python",
"django",
"jython"
] |
Can I detect if my code is running on cPython or Jython? | 1,103,487 | <p>I'm working on a small django project that will be deployed in a servlet container later. But development is much faster if I work with cPython instead of Jython. So what I want to do is test if my code is running on cPython or Jython in my settiings.py so I can tell it to use the appropriate db driver (postgresql_psycopg2 or doj.backends.zxjdbc.postgresql). Is there a simple way to do this?</p>
| 8 | 2009-07-09T12:19:34Z | 1,147,610 | <p>As sunqiang pointed out</p>
<pre><code>import platform
platform.system()
</code></pre>
<p>works for Jython 2.5, but this doesn't work on Jython 2.2 (the previous Jython release). Also, there has been some discussion about returning more operating system specific details for calls like these in Jython 3.x. Nothing has been decided there, but to be safely backwards and forwards compatible, I would suggest using:</p>
<pre><code>import sys
sys.platform.startswith('java')
</code></pre>
<p>Which will return True for Jython and False everywhere else (actually in Jython 2.2 or older it returns 1 for Jython and 0 everywhere else, but this will still work fine in if statements and other checks). This call works in Jython at least as far back as 2.1, and will work for the foreseeable future.</p>
<p>In Python versions 2.6 or above (note Jython 2.6 has not yet been released) another option is:</p>
<pre><code>import platform
platform.python_implementation
</code></pre>
<p>Which returns 'CPython' for the C implementation of Python, 'IronPython' for IronPython and will return 'Jython' for Jython. Obviously this one isn't backwards compatible below 2.6, but will be forwards compatible.</p>
| 19 | 2009-07-18T14:01:38Z | [
"python",
"django",
"jython"
] |
Can I detect if my code is running on cPython or Jython? | 1,103,487 | <p>I'm working on a small django project that will be deployed in a servlet container later. But development is much faster if I work with cPython instead of Jython. So what I want to do is test if my code is running on cPython or Jython in my settiings.py so I can tell it to use the appropriate db driver (postgresql_psycopg2 or doj.backends.zxjdbc.postgresql). Is there a simple way to do this?</p>
| 8 | 2009-07-09T12:19:34Z | 13,682,964 | <p>The most clear-cut way is:</p>
<blockquote>
<blockquote>
<blockquote>
<p>import platform</p>
<p>platform.python_implementation()</p>
</blockquote>
</blockquote>
</blockquote>
<p>'CPython'</p>
<p>By default, most of the time the underlying interpreter is CPython only which is also arguably the most efficient one :)</p>
| 12 | 2012-12-03T12:10:53Z | [
"python",
"django",
"jython"
] |
How to match search strings to content in python | 1,103,685 | <p>Usually when we search, we have a list of stories, we provide a search string, and expect back a list of results where the given search strings matches the story.</p>
<p>What I am looking to do, is the opposite. Give a list of search strings, and one story and find out which search strings match to that story.</p>
<p>Now this could be done with re but the case here is i wanna use complex search queries as supported by solr. Full details of the <a href="http://lucene.apache.org/java/2_4_0/queryparsersyntax.html" rel="nofollow">query syntax here</a>. Note: i wont use boost.</p>
<p>Basically i want to get some pointers for the doesitmatch function in the sample code below.</p>
<pre><code>def doesitmatch(contents, searchstring):
"""
returns result of searching contents for searchstring (True or False)
"""
???????
???????
story = "big chunk of story 200 to 1000 words long"
searchstrings = ['sajal' , 'sajal AND "is a jerk"' , 'sajal kayan' , 'sajal AND (kayan OR bangkok OR Thailand OR ( webmaster AND python))' , 'bangkok']
matches = [[searchstr] for searchstr in searchstrings if doesitmatch(story, searchstr) ]
</code></pre>
<p><strong>Edit:</strong> Additionally would also be interested to know if any module exists to convert lucene query like below into regex:</p>
<pre><code>sajal AND (kayan OR bangkok OR Thailand OR ( webmaster AND python) OR "is a jerk")
</code></pre>
| 0 | 2009-07-09T12:54:23Z | 1,103,884 | <p>Probably slow, but easy solution:</p>
<p>Make a query on the story plus each string to the search engine. If it returns anything, then it matches.</p>
<p>Otherwise you need to implement the search syntax yourself. If that includes things like "title:" and stuff this can be rather complex. If it's only the AND and OR from your example, then it's a recursive function that isn't too hairy.</p>
| 0 | 2009-07-09T13:25:06Z | [
"python",
"search",
"lucene",
"solr"
] |
How to match search strings to content in python | 1,103,685 | <p>Usually when we search, we have a list of stories, we provide a search string, and expect back a list of results where the given search strings matches the story.</p>
<p>What I am looking to do, is the opposite. Give a list of search strings, and one story and find out which search strings match to that story.</p>
<p>Now this could be done with re but the case here is i wanna use complex search queries as supported by solr. Full details of the <a href="http://lucene.apache.org/java/2_4_0/queryparsersyntax.html" rel="nofollow">query syntax here</a>. Note: i wont use boost.</p>
<p>Basically i want to get some pointers for the doesitmatch function in the sample code below.</p>
<pre><code>def doesitmatch(contents, searchstring):
"""
returns result of searching contents for searchstring (True or False)
"""
???????
???????
story = "big chunk of story 200 to 1000 words long"
searchstrings = ['sajal' , 'sajal AND "is a jerk"' , 'sajal kayan' , 'sajal AND (kayan OR bangkok OR Thailand OR ( webmaster AND python))' , 'bangkok']
matches = [[searchstr] for searchstr in searchstrings if doesitmatch(story, searchstr) ]
</code></pre>
<p><strong>Edit:</strong> Additionally would also be interested to know if any module exists to convert lucene query like below into regex:</p>
<pre><code>sajal AND (kayan OR bangkok OR Thailand OR ( webmaster AND python) OR "is a jerk")
</code></pre>
| 0 | 2009-07-09T12:54:23Z | 1,103,974 | <p>Some time ago I looked for a python implementaion of lucene and I came accross of <a href="http://whoosh.ca/" rel="nofollow">Woosh</a> which is a pure python text-based research engine. Maybe it will statisfy your needs.</p>
<p>You can also try <a href="http://lucene.apache.org/pylucene/" rel="nofollow">pyLucene</a>, but i did'nt investigate this one.</p>
| 0 | 2009-07-09T13:42:29Z | [
"python",
"search",
"lucene",
"solr"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.