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 |
|---|---|---|---|---|---|---|---|---|---|
Regex for extraction in Python | 1,528,016 | <p>I have a string like this:</p>
<pre><code>"a word {{bla|123|456}} another {{bli|789|123}} some more text {{blu|789}} and more".
</code></pre>
<p>I would like to get this as an output:</p>
<pre><code>(("bla", 123, 456), ("bli", 789, 123), ("blu", 789))
</code></pre>
<p>I haven't been able to find the proper python regex to achieve that.</p>
| 0 | 2009-10-06T20:45:35Z | 1,528,109 | <p>We might be able to get fancy and do everything in a single complicated regular expression, but that way lies madness. Let's do one regexp that grabs the groups, and then split the groups up. We could use a regexp to split the groups, but we can just use str.split(), so let's do that.</p>
<pre><code>import re
pat_group = re.compile("{{([^}]*)}}")
def mixed_tuple(iterable):
lst = []
for x in iterable:
try:
lst.append(int(x))
except ValueError:
lst.append(x)
return tuple(lst)
s = "a word {{bla|123|456}} another {{bli|789|123}} some more text {{blu|789}} and more"
lst_groups = re.findall(pat_group, s)
lst = [mixed_tuple(x.split("|")) for x in lst_groups]
</code></pre>
<p>In pat_group, "{{" just matches literal "{{". "(" starts a group. "[^}]" is a character class that matches any character except for "}", and '*' allows it to match zero or more such characters. ")" closes out the group and "}}" matches literal characters. Thus, we match the "{{...}}" patterns, and can extract everything between the curly braces as a group.</p>
<p>re.findall() returns a list of groups matched from the pattern.</p>
<p>Finally, a list comprehension splits each string and returns the result as a tuple.</p>
| 0 | 2009-10-06T21:08:03Z | [
"python",
"regex"
] |
Regex for extraction in Python | 1,528,016 | <p>I have a string like this:</p>
<pre><code>"a word {{bla|123|456}} another {{bli|789|123}} some more text {{blu|789}} and more".
</code></pre>
<p>I would like to get this as an output:</p>
<pre><code>(("bla", 123, 456), ("bli", 789, 123), ("blu", 789))
</code></pre>
<p>I haven't been able to find the proper python regex to achieve that.</p>
| 0 | 2009-10-06T20:45:35Z | 1,528,137 | <p>Assuming your actual format is <code>{{[a-z]+|[0-9]+|[0-9]+}}</code>, here's a complete program with conversion to ints.</p>
<pre><code>import re
s = "a word {{bla|123|456}} another {{bli|789|123}} some more text {{blu|789}} and more"
result = []
for match in re.finditer('{{.*?}}', s):
# Split on pipe (|) and filter out non-alphanumerics
parts = [filter(str.isalnum, part) for part in match.group().split('|')]
# Convert to int when possible
for index, part in enumerate(parts):
try:
parts[index] = int(part)
except ValueError:
pass
result.append(tuple(parts))
</code></pre>
| 0 | 2009-10-06T21:14:40Z | [
"python",
"regex"
] |
Regex for extraction in Python | 1,528,016 | <p>I have a string like this:</p>
<pre><code>"a word {{bla|123|456}} another {{bli|789|123}} some more text {{blu|789}} and more".
</code></pre>
<p>I would like to get this as an output:</p>
<pre><code>(("bla", 123, 456), ("bli", 789, 123), ("blu", 789))
</code></pre>
<p>I haven't been able to find the proper python regex to achieve that.</p>
| 0 | 2009-10-06T20:45:35Z | 1,528,581 | <p>Is pyparsing overkill for this? Maybe, but without too much suffering, it <em>does</em> deliver the desired output, without a thicket of backslashes to escape the '{', '|', or '}' characters. Plus, there's no need for post-parse conversions of integers and whatnot - the parse actions take care of this kind of stuff at parse time.</p>
<pre><code>from pyparsing import Word, Suppress, alphas, alphanums, nums, delimitedList
LBRACE,RBRACE,VERT = map(Suppress,"{}|")
word = Word(alphas,alphanums)
integer = Word(nums)
integer.setParseAction(lambda t: int(t[0]))
patt = (LBRACE*2 + delimitedList(word|integer, VERT) + RBRACE*2)
patt.setParseAction(lambda toks:tuple(toks.asList()))
s = "a word {{bla|123|456}} another {{bli|789|123}} some more text {{blu|789}} and more"
print tuple(p[0] for p in patt.searchString(s))
</code></pre>
<p>Prints:</p>
<pre><code>(('bla', 123, 456), ('bli', 789, 123), ('blu', 789))
</code></pre>
| 0 | 2009-10-06T23:09:24Z | [
"python",
"regex"
] |
How can I handle exceptions in a list comprehension in Python? | 1,528,237 | <p>I have some a list comprehension in Python in which each iteration can throw an exception. </p>
<p><strong>For instance</strong>, if I have:</p>
<pre><code>eggs = (1,3,0,3,2)
[1/egg for egg in eggs]
</code></pre>
<p>I'll get a <code>ZeroDivisionError</code> exception in the 3rd element.</p>
<p>How can I handle this exception and continue execution of the list comprehension?</p>
<p>The only way I can think of is to use a helper function:</p>
<pre><code>def spam(egg):
try:
return 1/egg
except ZeroDivisionError:
# handle division by zero error
# leave empty for now
pass
</code></pre>
<p>But this looks a bit cumbersome to me.</p>
<p>Is there a better way to do this in Python?</p>
<p><strong>Note:</strong> This is a simple example (see "<em>for instance</em>" above) that I contrived because my real example requires some context. I'm not interested in avoiding divide by zero errors but in handling exceptions in a list comprehension.</p>
| 35 | 2009-10-06T21:36:06Z | 1,528,244 | <p>You can use</p>
<pre><code>[1/egg for egg in eggs if egg != 0]
</code></pre>
<p>this will simply skip elements that are zero.</p>
| 17 | 2009-10-06T21:38:18Z | [
"python",
"exception-handling",
"list-comprehension"
] |
How can I handle exceptions in a list comprehension in Python? | 1,528,237 | <p>I have some a list comprehension in Python in which each iteration can throw an exception. </p>
<p><strong>For instance</strong>, if I have:</p>
<pre><code>eggs = (1,3,0,3,2)
[1/egg for egg in eggs]
</code></pre>
<p>I'll get a <code>ZeroDivisionError</code> exception in the 3rd element.</p>
<p>How can I handle this exception and continue execution of the list comprehension?</p>
<p>The only way I can think of is to use a helper function:</p>
<pre><code>def spam(egg):
try:
return 1/egg
except ZeroDivisionError:
# handle division by zero error
# leave empty for now
pass
</code></pre>
<p>But this looks a bit cumbersome to me.</p>
<p>Is there a better way to do this in Python?</p>
<p><strong>Note:</strong> This is a simple example (see "<em>for instance</em>" above) that I contrived because my real example requires some context. I'm not interested in avoiding divide by zero errors but in handling exceptions in a list comprehension.</p>
| 35 | 2009-10-06T21:36:06Z | 1,528,286 | <p>No there's not a better way. In a lot of cases you can use avoidance like Peter does</p>
<p>Your other option is to not use comprehensions</p>
<pre><code>eggs = (1,3,0,3,2)
result=[]
for egg in eggs:
try:
result.append(egg/0)
except ZeroDivisionError:
# handle division by zero error
# leave empty for now
pass
</code></pre>
<p>Up to you to decide whether that is more cumbersome or not</p>
| 6 | 2009-10-06T21:50:01Z | [
"python",
"exception-handling",
"list-comprehension"
] |
How can I handle exceptions in a list comprehension in Python? | 1,528,237 | <p>I have some a list comprehension in Python in which each iteration can throw an exception. </p>
<p><strong>For instance</strong>, if I have:</p>
<pre><code>eggs = (1,3,0,3,2)
[1/egg for egg in eggs]
</code></pre>
<p>I'll get a <code>ZeroDivisionError</code> exception in the 3rd element.</p>
<p>How can I handle this exception and continue execution of the list comprehension?</p>
<p>The only way I can think of is to use a helper function:</p>
<pre><code>def spam(egg):
try:
return 1/egg
except ZeroDivisionError:
# handle division by zero error
# leave empty for now
pass
</code></pre>
<p>But this looks a bit cumbersome to me.</p>
<p>Is there a better way to do this in Python?</p>
<p><strong>Note:</strong> This is a simple example (see "<em>for instance</em>" above) that I contrived because my real example requires some context. I'm not interested in avoiding divide by zero errors but in handling exceptions in a list comprehension.</p>
| 35 | 2009-10-06T21:36:06Z | 1,528,375 | <p>There is no built-in expression in Python that lets you ignore an exception (or return alternate values &c in case of exceptions), so it's impossible, literally speaking, to "handle exceptions in a list comprehension" because a list comprehension is an expression containing other expression, nothing more (i.e., <strong>no</strong> statements, and only statements can catch/ignore/handle exceptions).</p>
<p>Function calls are expression, and the function bodies can include all the statements you want, so delegating the evaluation of the exception-prone sub-expression to a function, as you've noticed, is one feasible workaround (others, when feasible, are checks on values that might provoke exceptions, as also suggested in other answers).</p>
<p>The correct responses to the question "how to handle exceptions in a list comprehension" are all expressing part of all of this truth: 1) literally, i.e. lexically IN the comprehension itself, you can't; 2) practically, you delegate the job to a function or check for error prone values when that's feasible. Your repeated claim that this is not an answer is thus unfounded.</p>
| 38 | 2009-10-06T22:10:27Z | [
"python",
"exception-handling",
"list-comprehension"
] |
How can I handle exceptions in a list comprehension in Python? | 1,528,237 | <p>I have some a list comprehension in Python in which each iteration can throw an exception. </p>
<p><strong>For instance</strong>, if I have:</p>
<pre><code>eggs = (1,3,0,3,2)
[1/egg for egg in eggs]
</code></pre>
<p>I'll get a <code>ZeroDivisionError</code> exception in the 3rd element.</p>
<p>How can I handle this exception and continue execution of the list comprehension?</p>
<p>The only way I can think of is to use a helper function:</p>
<pre><code>def spam(egg):
try:
return 1/egg
except ZeroDivisionError:
# handle division by zero error
# leave empty for now
pass
</code></pre>
<p>But this looks a bit cumbersome to me.</p>
<p>Is there a better way to do this in Python?</p>
<p><strong>Note:</strong> This is a simple example (see "<em>for instance</em>" above) that I contrived because my real example requires some context. I'm not interested in avoiding divide by zero errors but in handling exceptions in a list comprehension.</p>
| 35 | 2009-10-06T21:36:06Z | 8,915,613 | <p>I realize this question is quite old, but you can also create a general function to make this kind of thing easier:</p>
<pre><code>def catch(func, handle=lambda e : e, *args, **kwargs):
try:
return func(*args, **kwargs)
except Exception as e:
return handle(e)
</code></pre>
<p>Then, in your comprehension:</p>
<pre><code>eggs = (1,3,0,3,2)
[catch(lambda : 1/egg) for egg in eggs]
[1, 0, ('integer division or modulo by zero'), 0, 0]
</code></pre>
<p>You can of course make the default handle function whatever you want (say you'd rather return 'None' by default).</p>
<p>Hope this helps you or any future viewers of this question!</p>
<p>Note: in python 3, I would make the 'handle' argument keyword only, and put it at the end of the argument list. This would make actually passing arguments and such through catch much more natural.</p>
| 30 | 2012-01-18T18:48:01Z | [
"python",
"exception-handling",
"list-comprehension"
] |
Does Python have a "compile only" switch like Perl's -c? | 1,528,346 | <p>Perl has the <code>-c</code> switch to compile the code without running it. This is convenient for debugging compile errors in Perl.</p>
<p>Does Python have a similar switch?</p>
| 13 | 2009-10-06T22:03:19Z | 1,528,351 | <p>You can say</p>
<pre><code>python -m py_compile script_to_check.py
</code></pre>
<p>However, this will have the side effect of creating a compiled <code>script_to_check.pyc</code> file in the same directory as your script. This feature is designed to speed up later uses of a module rather than to make sure that your syntax is correct, though you could certainly use it for that.</p>
| 15 | 2009-10-06T22:05:11Z | [
"python",
"compiler-construction"
] |
Does Python have a "compile only" switch like Perl's -c? | 1,528,346 | <p>Perl has the <code>-c</code> switch to compile the code without running it. This is convenient for debugging compile errors in Perl.</p>
<p>Does Python have a similar switch?</p>
| 13 | 2009-10-06T22:03:19Z | 1,528,362 | <p>Through 2.6, there's <a href="http://docs.python.org/library/compiler.html" rel="nofollow">the compiler package</a>. That page doesn't say if there is a replacement in 3.0, or if you just can't do that any more.</p>
| 0 | 2009-10-06T22:08:22Z | [
"python",
"compiler-construction"
] |
Does Python have a "compile only" switch like Perl's -c? | 1,528,346 | <p>Perl has the <code>-c</code> switch to compile the code without running it. This is convenient for debugging compile errors in Perl.</p>
<p>Does Python have a similar switch?</p>
| 13 | 2009-10-06T22:03:19Z | 1,528,456 | <p>Even better is to run <a href="http://divmod.org/trac/wiki/DivmodPyflakes">pyflakes</a>, <a href="http://pychecker.sourceforge.net/">pychecker</a> or maybe <a href="http://www.logilab.org/857">pylint</a> at the code. They catch some common errors that compiling won't.</p>
| 8 | 2009-10-06T22:36:35Z | [
"python",
"compiler-construction"
] |
Why can't I save an object in Django? | 1,528,656 | <pre><code>thechan = Score.objects.filter(content=44)[0:1]
thechan[0].custom_score = 2
thechan[0].save()
</code></pre>
<p>I do print statements, and it shows everything fine. However, it's not SAVING!</p>
<p>I go into my database, and I run a simple SELECT statement..and it's not changed!</p>
<pre><code>select custom_score FROM music_score where content_id = 44;
</code></pre>
| 1 | 2009-10-06T23:29:48Z | 1,528,712 | <p>Fixed.</p>
<pre><code>thechan = Score.objects.get(content=44)
thechan.custom_score = 2
thechan.save()
</code></pre>
| 0 | 2009-10-06T23:42:16Z | [
"python",
"django",
"frameworks"
] |
Why can't I save an object in Django? | 1,528,656 | <pre><code>thechan = Score.objects.filter(content=44)[0:1]
thechan[0].custom_score = 2
thechan[0].save()
</code></pre>
<p>I do print statements, and it shows everything fine. However, it's not SAVING!</p>
<p>I go into my database, and I run a simple SELECT statement..and it's not changed!</p>
<pre><code>select custom_score FROM music_score where content_id = 44;
</code></pre>
| 1 | 2009-10-06T23:29:48Z | 1,528,801 | <p>What's going on here is that Score.objects.filter() doesn't return a regular list, but a <a href="http://docs.djangoproject.com/en/dev/ref/models/querysets/">QuerySet</a>. QuerySets behave like lists in some ways, but every time you slice one you get a new QuerySet instance, and everytime you index into one, you get a new instance of your model class.</p>
<p>That means your original code does something like:</p>
<pre><code>thechan = Score.objects.filter(content=44)[0:1]
thechan[0].custom_score = 2
thechan = Score.objects.filter(content=44)[0:1]
thechan[0].save() # saves an unmodified object back to the DB, no effective change
</code></pre>
<p>If for whatever reason you needed to do this on a QuerySet rather than just using get(), you could write:</p>
<pre><code>thechan = Score.objects.filter(content=44)[0]
thechan.custom_score = 2
thechan.save()
</code></pre>
<p>instead. This distinction becomes a bit more important if you are, say, iterating over the elements of a QuerySet instead of dealing with a single record.</p>
| 11 | 2009-10-07T00:05:45Z | [
"python",
"django",
"frameworks"
] |
Idiomatic way to do list/dict in Cython? | 1,528,691 | <p>My problem: I've found that processing large data sets with raw C++ using the STL map and vector can often be considerably faster (and with lower memory footprint) than using Cython. </p>
<p>I figure that part of this speed penalty is due to using Python lists and dicts, and that there might be some tricks to use less encumbered data structures in Cython. For example, this page (<a href="http://wiki.cython.org/tutorials/numpy">http://wiki.cython.org/tutorials/numpy</a>) shows how to make numpy arrays very fast in Cython by predefining the size and types of the ND array. </p>
<p>Question: Is there any way to do something similar with lists/dicts, e.g. by stating roughly how many elements or (key,value) pairs you expect to have in them? <strong>That is, is there an idiomatic way to convert lists/dicts to (fast) data structures in Cython?</strong> </p>
<p>If not I guess I'll just have to write it in C++ and wrap in a Cython import. </p>
| 32 | 2009-10-06T23:37:44Z | 1,547,009 | <p>You can take a look at the standard <a href="http://docs.python.org/library/array.html" rel="nofollow"><code>array</code></a> module for Python if this is appropriate for your Cython setting. I'm not sure since I have never used Cython.</p>
| 2 | 2009-10-10T03:57:11Z | [
"c++",
"python",
"c",
"cython"
] |
Idiomatic way to do list/dict in Cython? | 1,528,691 | <p>My problem: I've found that processing large data sets with raw C++ using the STL map and vector can often be considerably faster (and with lower memory footprint) than using Cython. </p>
<p>I figure that part of this speed penalty is due to using Python lists and dicts, and that there might be some tricks to use less encumbered data structures in Cython. For example, this page (<a href="http://wiki.cython.org/tutorials/numpy">http://wiki.cython.org/tutorials/numpy</a>) shows how to make numpy arrays very fast in Cython by predefining the size and types of the ND array. </p>
<p>Question: Is there any way to do something similar with lists/dicts, e.g. by stating roughly how many elements or (key,value) pairs you expect to have in them? <strong>That is, is there an idiomatic way to convert lists/dicts to (fast) data structures in Cython?</strong> </p>
<p>If not I guess I'll just have to write it in C++ and wrap in a Cython import. </p>
| 32 | 2009-10-06T23:37:44Z | 1,547,069 | <p>There is no way to get native Python lists/dicts up to the speed of a C++ map/vector or even anywhere close. It has nothing to do with allocation or type declaration but rather paying the interpreter overhead. The example you mention (numpy) is a C extension and is written in C for precisely this reason. </p>
| 1 | 2009-10-10T04:38:32Z | [
"c++",
"python",
"c",
"cython"
] |
Idiomatic way to do list/dict in Cython? | 1,528,691 | <p>My problem: I've found that processing large data sets with raw C++ using the STL map and vector can often be considerably faster (and with lower memory footprint) than using Cython. </p>
<p>I figure that part of this speed penalty is due to using Python lists and dicts, and that there might be some tricks to use less encumbered data structures in Cython. For example, this page (<a href="http://wiki.cython.org/tutorials/numpy">http://wiki.cython.org/tutorials/numpy</a>) shows how to make numpy arrays very fast in Cython by predefining the size and types of the ND array. </p>
<p>Question: Is there any way to do something similar with lists/dicts, e.g. by stating roughly how many elements or (key,value) pairs you expect to have in them? <strong>That is, is there an idiomatic way to convert lists/dicts to (fast) data structures in Cython?</strong> </p>
<p>If not I guess I'll just have to write it in C++ and wrap in a Cython import. </p>
| 32 | 2009-10-06T23:37:44Z | 2,699,569 | <p>Doing similar operations in Python as in C++ can often be slower. <code>list</code> and <code>dict</code> are actually implemented very well, but you gain a lot of overhead using Python objects, which are more abstract than C++ objects and require a lot more lookup at runtime.</p>
<p>Incidentally, <code>std::vector</code> is implemented in a pretty similar way to <code>list</code>. <code>std::map</code>, though, is actually implemented in a way that many operations are slower than <code>dict</code> as its size gets large. For suitably large examples of each, <code>dict</code> overcomes the constant factor by which it's slower than <code>std::map</code> and will actually do operations like lookup, insertion, etc. faster.</p>
<p>If you want to use <code>std::map</code> and <code>std::vector</code>, nothing is stopping you. You'll have to wrap them yourself if you want to expose them to Python. Do not be shocked if this wrapping consumes all or much of the time you were hoping to save. I am not aware of any tools that make this automatic for you.</p>
<p>There are C API calls for controlling the creation of objects with some detail. You can say "Make a list with at least this many elements", but this doesn't improve the overall complexity of your list creation-and-filling operation. It certainly doesn't change much later as you try to change your list.</p>
<p>My general advice is</p>
<ul>
<li><p>If you want a fixed-size array (you talk about specifying the size of a list), you may actually want something like a numpy array.</p></li>
<li><p>I doubt you are going to get any speedup you want out of using <code>std::vector</code> over <code>list</code> for a <em>general</em> replacement in your code. If you want to use it behind the scenes, it may give you a satisfying size and space improvement (I of course don't know without measuring, nor do you. ;) ).</p></li>
<li><p><code>dict</code> actually does its job really well. I definitely wouldn't try introducing a new general-purpose type for use in Python based on <code>std::map</code>, which has worse algorithmic complexity in time for many important operations andâin at least some implementationsâleaves some optimisations to the user that <code>dict</code> already has. </p>
<p>If I did want something that worked a little more like <code>std::map</code>, I'd probably use a database. This is generally what I do if stuff I want to store in a <code>dict</code> (or for that matter, stuff I store in a <code>list</code>) gets too big for me to feel comfortable storing in memory. Python has <code>sqlite3</code> in the stdlib and drivers for all other major databases available.</p></li>
</ul>
| 24 | 2010-04-23T14:58:39Z | [
"c++",
"python",
"c",
"cython"
] |
Idiomatic way to do list/dict in Cython? | 1,528,691 | <p>My problem: I've found that processing large data sets with raw C++ using the STL map and vector can often be considerably faster (and with lower memory footprint) than using Cython. </p>
<p>I figure that part of this speed penalty is due to using Python lists and dicts, and that there might be some tricks to use less encumbered data structures in Cython. For example, this page (<a href="http://wiki.cython.org/tutorials/numpy">http://wiki.cython.org/tutorials/numpy</a>) shows how to make numpy arrays very fast in Cython by predefining the size and types of the ND array. </p>
<p>Question: Is there any way to do something similar with lists/dicts, e.g. by stating roughly how many elements or (key,value) pairs you expect to have in them? <strong>That is, is there an idiomatic way to convert lists/dicts to (fast) data structures in Cython?</strong> </p>
<p>If not I guess I'll just have to write it in C++ and wrap in a Cython import. </p>
| 32 | 2009-10-06T23:37:44Z | 6,139,683 | <p>C++ is fast not just because of the static declarations of the vector and the elements that go into it, but crucially because using templates/generics one specifies that the vector will <em>only</em> contain elements of a certain type, e.g. vector with tuples of three elements. Cython can't do this last thing and it sounds nontrivial -- it would have to be enforced at compile time, somehow (typechecking at runtime is what Python already does). So right now when you pop something off a list in Cython there is no way of knowing in advance what type it is , and putting it in a typed variable only adds a typecheck, not speed. This means that there is no way of bypassing the Python interpreter in this regard, and it seems to me it's the most crucial shortcoming of Cython for non-numerical tasks.</p>
<p>The manual way of solving this is to subclass the python list/dict (or perhaps std::vector) with a cdef class for a specific type of element or key-value combination. This would amount to the same thing as the code that templates are generating. As long as you use the resulting class in Cython code it should provide an improvement.</p>
<p>Using databases or arrays just solves a different problem, because this is about putting arbitrary objects (but with a specific type, and preferably a cdef class) in containers.</p>
<p>And std::map shouldn't be compared to dict; std::map maintains keys in sorted order because it is a balanced tree, dict solves a different problem. A better comparison would be dict and Google's hashtable.</p>
| 7 | 2011-05-26T13:55:00Z | [
"c++",
"python",
"c",
"cython"
] |
Idiomatic way to do list/dict in Cython? | 1,528,691 | <p>My problem: I've found that processing large data sets with raw C++ using the STL map and vector can often be considerably faster (and with lower memory footprint) than using Cython. </p>
<p>I figure that part of this speed penalty is due to using Python lists and dicts, and that there might be some tricks to use less encumbered data structures in Cython. For example, this page (<a href="http://wiki.cython.org/tutorials/numpy">http://wiki.cython.org/tutorials/numpy</a>) shows how to make numpy arrays very fast in Cython by predefining the size and types of the ND array. </p>
<p>Question: Is there any way to do something similar with lists/dicts, e.g. by stating roughly how many elements or (key,value) pairs you expect to have in them? <strong>That is, is there an idiomatic way to convert lists/dicts to (fast) data structures in Cython?</strong> </p>
<p>If not I guess I'll just have to write it in C++ and wrap in a Cython import. </p>
| 32 | 2009-10-06T23:37:44Z | 8,508,658 | <p>Cython now has template support, and comes with declarations for some of the STL containers.</p>
<p>See <a href="http://docs.cython.org/src/userguide/wrapping_CPlusPlus.html#standard-library">http://docs.cython.org/src/userguide/wrapping_CPlusPlus.html#standard-library</a></p>
<p>Here's the example they give:</p>
<pre><code>from libcpp.vector cimport vector
cdef vector[int] vect
cdef int i
for i in range(10):
vect.push_back(i)
for i in range(10):
print vect[i]
</code></pre>
| 23 | 2011-12-14T17:09:26Z | [
"c++",
"python",
"c",
"cython"
] |
reading lines 2 at a time | 1,528,711 | <p>Is there a better way to read lines two at a time from a file in python than:</p>
<pre><code>with open(fn) as f:
for line in f:
try:
line2 = f.next()
except StopIteration:
line2 = ''
print line, line2 # or something more interesting
</code></pre>
<p>I'm in 2.5.4. Anything different in newer versions?</p>
<p>EDIT: a deleted answer noted: in py3k you'd need to do next(f) instead of f.next(). Not to mention the print change</p>
| 10 | 2009-10-06T23:42:02Z | 1,528,769 | <pre><code>import itertools
with open(fn) as f:
for line, line2 in itertools.izip_longest(f, f, fillvalue=''):
print line, line2
</code></pre>
<p>Alas, <code>izip_longest</code> requires Python 2.6 or better; 2.5 only has <code>izip</code>, which would truncate the last line if <code>f</code> has an odd number of lines. It's quite easy to supply the equivalent functionality as a generator, of course.</p>
<p>Here's a more general "N at a time" iterator-wrapper:</p>
<pre><code>def natatime(itr, fillvalue=None, n=2):
return itertools.izip_longest(*(iter(itr),)*n, fillvalue=fillvalue)
</code></pre>
<p><code>itertools</code> is generally the best way to go, but, if you insisted on implementing it by yourself, then:</p>
<pre><code>def natatime_no_itertools(itr, fillvalue=None, n=2):
x = iter(itr)
for item in x:
yield (item,) + tuple(next(x, fillvalue) for _ in xrange(n-1))
</code></pre>
<p>In 2.5, I think the best approach is actually not a generator, but another itertools-based solution:</p>
<pre><code>def natatime_25(itr, fillvalue=None, n=2):
x = itertools.chain(iter(itr), (fillvalue,) * (n-1))
return itertools.izip(*(x,)*n)
</code></pre>
<p>(since 2.5 doesn't have the built-in <code>next</code>, as well as missing <code>izip_longest</code>).</p>
| 14 | 2009-10-06T23:57:23Z | [
"python"
] |
reading lines 2 at a time | 1,528,711 | <p>Is there a better way to read lines two at a time from a file in python than:</p>
<pre><code>with open(fn) as f:
for line in f:
try:
line2 = f.next()
except StopIteration:
line2 = ''
print line, line2 # or something more interesting
</code></pre>
<p>I'm in 2.5.4. Anything different in newer versions?</p>
<p>EDIT: a deleted answer noted: in py3k you'd need to do next(f) instead of f.next(). Not to mention the print change</p>
| 10 | 2009-10-06T23:42:02Z | 1,528,846 | <p>for small to medium sized files, </p>
<pre><code>>>> data=open("file").readlines()
>>> for num,line in enumerate(data[::2]):
... print ''.join(data[num:num+2])
</code></pre>
| 1 | 2009-10-07T00:16:27Z | [
"python"
] |
reading lines 2 at a time | 1,528,711 | <p>Is there a better way to read lines two at a time from a file in python than:</p>
<pre><code>with open(fn) as f:
for line in f:
try:
line2 = f.next()
except StopIteration:
line2 = ''
print line, line2 # or something more interesting
</code></pre>
<p>I'm in 2.5.4. Anything different in newer versions?</p>
<p>EDIT: a deleted answer noted: in py3k you'd need to do next(f) instead of f.next(). Not to mention the print change</p>
| 10 | 2009-10-06T23:42:02Z | 1,528,856 | <p>You could possibly make it more clear with a generator:</p>
<pre><code>def read2(f):
for line in f:
try:
line2 = f.next()
except StopIteration:
line2 = ''
yield line, line2
with open(fn) as f:
for line1, line2 in read2(f):
print line1
print line2
</code></pre>
| 2 | 2009-10-07T00:18:53Z | [
"python"
] |
How to write an empty indentation block in Python? | 1,528,903 | <p>The runtime keeps telling me:</p>
<blockquote>
<p>expected an indented block</p>
</blockquote>
<p>But I don't want write nothing inside my except block, I just want it to catch and swallow the exception.</p>
| 24 | 2009-10-07T00:34:09Z | 1,528,905 | <p>Just write</p>
<pre><code>pass
</code></pre>
<p>as in</p>
<pre><code>try:
# Do something illegal.
...
except:
# Pretend nothing happened.
pass
</code></pre>
<p>EDIT: @swillden brings up a good point, viz., this is a terrible idea in general. You should, at the least, say</p>
<pre><code>except TypeError, DivideByZeroError:
</code></pre>
<p>or whatever kinds of errors you want to handle. Otherwise you can mask bigger problems.</p>
| 64 | 2009-10-07T00:34:35Z | [
"python",
"syntax",
"try-catch",
"indentation"
] |
How to write an empty indentation block in Python? | 1,528,903 | <p>The runtime keeps telling me:</p>
<blockquote>
<p>expected an indented block</p>
</blockquote>
<p>But I don't want write nothing inside my except block, I just want it to catch and swallow the exception.</p>
| 24 | 2009-10-07T00:34:09Z | 1,529,193 | <p>I've never done this in more permanent code, but I frequently do it as a placeholder</p>
<pre><code>if some_expression:
True
else:
do_something(blah)
</code></pre>
<p>Just sticking a True in there will stop the error. Not sure if there's anything bad about this.</p>
| 0 | 2009-10-07T02:27:33Z | [
"python",
"syntax",
"try-catch",
"indentation"
] |
Using callback function in pyevent | 1,528,915 | <p>I want to detect pressing the "snapshot" button on the top of a webcam in linux. The button has this entry in /dev:
/dev/input/by-id/usb-PixArt_Imaging_Inc._USB2.0_UVC_VGA-event-if00</p>
<p>I am using the "rel" wrapper, at the moment, because it handles exceptions better. Before the following code executes, self.s.cam_btn is assigned the /dev entry for the button.</p>
<pre><code> rel.override()
rel.init()
rel.read(self.s.cam_btn, self.snap)
rel.dispatch()
</code></pre>
<p>self.snap() is the callback. It captures a screen shot from mplayer and feeds the image to an OCR program. Everything mostly works until the callback returns. Here is the problem:</p>
<p>If self.snap() returns nothing, the program stops and will not service any more button events. If self.snap() returns 1, the program continues servicing the same button event in an infinite loop, rather than waiting for a new event. Documentation for pyevent is a little sparse so any help gratefully received.</p>
<p>Clinton</p>
| 0 | 2009-10-07T00:37:43Z | 1,531,141 | <p>Never used <code>pyevent</code>, but would try rescheduling the event at the end of the handler:</p>
<pre><code>def snap(self):
# ... code ...
rel.read(self.s.cam_btn, self.snap)
return False
</code></pre>
| 0 | 2009-10-07T11:48:56Z | [
"python"
] |
How to create inline objects with properties in Python? | 1,528,932 | <p>In Javascript it would be:</p>
<pre><code>var newObject = { 'propertyName' : 'propertyValue' };
</code></pre>
<p>How to do it in Python?</p>
| 23 | 2009-10-07T00:43:55Z | 1,528,939 | <p>I don't know if there's a built-in way to do it, but you can always define a class like this:</p>
<pre><code>class InlineClass(object):
def __init__(self, dict):
self.__dict__ = dict
obj = InlineClass({'propertyName' : 'propertyValue'})
</code></pre>
| 10 | 2009-10-07T00:47:01Z | [
"python",
"instantiation",
"dynamic-languages"
] |
How to create inline objects with properties in Python? | 1,528,932 | <p>In Javascript it would be:</p>
<pre><code>var newObject = { 'propertyName' : 'propertyValue' };
</code></pre>
<p>How to do it in Python?</p>
| 23 | 2009-10-07T00:43:55Z | 1,528,978 | <p>I like <a href="http://stackoverflow.com/questions/1528932/how-to-create-inline-objects-with-properties-in-python/1528939#1528939">Smashery's</a> idea, but Python seems content to let you modify classes on your own:</p>
<pre><code>>>> class Inline(object):
... pass
...
>>> obj = Inline()
>>> obj.test = 1
>>> obj.test
1
>>>
</code></pre>
<p>Works just fine in Python 2.5 for me. Note that you do have to do this to a class derived from <code>object</code> - it won't work if you change the line to <code>obj = object</code>.</p>
| 4 | 2009-10-07T01:00:48Z | [
"python",
"instantiation",
"dynamic-languages"
] |
How to create inline objects with properties in Python? | 1,528,932 | <p>In Javascript it would be:</p>
<pre><code>var newObject = { 'propertyName' : 'propertyValue' };
</code></pre>
<p>How to do it in Python?</p>
| 23 | 2009-10-07T00:43:55Z | 1,528,993 | <pre><code>obj = type('obj', (object,), {'propertyName' : 'propertyValue'})
</code></pre>
<p>there are <a href="http://docs.python.org//library/functions.html#type">two kinds of <code>type</code> function uses</a>.</p>
| 47 | 2009-10-07T01:04:15Z | [
"python",
"instantiation",
"dynamic-languages"
] |
How to create inline objects with properties in Python? | 1,528,932 | <p>In Javascript it would be:</p>
<pre><code>var newObject = { 'propertyName' : 'propertyValue' };
</code></pre>
<p>How to do it in Python?</p>
| 23 | 2009-10-07T00:43:55Z | 1,529,041 | <p>Peter's answer</p>
<pre><code>obj = lambda: None
obj.propertyName = 'propertyValue'
</code></pre>
| 12 | 2009-10-07T01:23:07Z | [
"python",
"instantiation",
"dynamic-languages"
] |
How to create inline objects with properties in Python? | 1,528,932 | <p>In Javascript it would be:</p>
<pre><code>var newObject = { 'propertyName' : 'propertyValue' };
</code></pre>
<p>How to do it in Python?</p>
| 23 | 2009-10-07T00:43:55Z | 1,529,145 | <pre><code>class test:
def __setattr__(self,key,value):
return value
myObj = test()
myObj.mykey = 'abc' # set your property and value
</code></pre>
| 0 | 2009-10-07T02:04:35Z | [
"python",
"instantiation",
"dynamic-languages"
] |
How to create inline objects with properties in Python? | 1,528,932 | <p>In Javascript it would be:</p>
<pre><code>var newObject = { 'propertyName' : 'propertyValue' };
</code></pre>
<p>How to do it in Python?</p>
| 23 | 2009-10-07T00:43:55Z | 1,529,890 | <p>It is easy in Python to declare a class with an <code>__init__()</code> function that can set up the instance for you, with optional arguments. If you don't specify the arguments you get a blank instance, and if you specify some or all of the arguments you initialize the instance.</p>
<p>I explained it <a href="http://stackoverflow.com/questions/1495666/how-to-define-a-class-in-python/1495740#1495740">here</a> (my highest-rated answer to date) so I won't retype the explanation. But, if you have questions, ask and I'll answer.</p>
<p>If you just want a generic object whose class doesn't really matter, you can do this:</p>
<pre><code>class Generic(object):
pass
x = Generic()
x.foo = 1
x.bar = 2
x.baz = 3
</code></pre>
<p>An obvious extension would be to add an <code>__str__()</code> function that prints something useful.</p>
<p>This trick is nice sometimes when you want a more-convenient dictionary. I find it easier to type <code>x.foo</code> than <code>x["foo"]</code>.</p>
| 2 | 2009-10-07T06:39:34Z | [
"python",
"instantiation",
"dynamic-languages"
] |
How to create inline objects with properties in Python? | 1,528,932 | <p>In Javascript it would be:</p>
<pre><code>var newObject = { 'propertyName' : 'propertyValue' };
</code></pre>
<p>How to do it in Python?</p>
| 23 | 2009-10-07T00:43:55Z | 27,931,360 | <p>Python 3.3 added the <a href="https://docs.python.org/3.3/library/types.html#types.SimpleNamespace" rel="nofollow"><code>SimpleNamespace</code></a> class for that exact purpose:</p>
<pre><code>>>> from types import SimpleNamespace
>>> obj = SimpleNamespace(propertyName='propertyValue')
>>> obj
namespace(propertyName='propertyValue')
>>> obj.propertyName
'propertyValue'
</code></pre>
<p>In addition to the appropriate constructor to build the object, <code>SimpleNamespace</code> defines <code>__repr__</code> and <code>__eq__</code> (<a href="https://docs.python.org/3.4/library/types.html#types.SimpleNamespace" rel="nofollow">documented in 3.4</a>) to behave as expected.</p>
| 2 | 2015-01-13T20:58:16Z | [
"python",
"instantiation",
"dynamic-languages"
] |
How to create inline objects with properties in Python? | 1,528,932 | <p>In Javascript it would be:</p>
<pre><code>var newObject = { 'propertyName' : 'propertyValue' };
</code></pre>
<p>How to do it in Python?</p>
| 23 | 2009-10-07T00:43:55Z | 37,155,671 | <p>Another viable option is to use <a href="https://docs.python.org/2/library/collections.html#collections.namedtuple" rel="nofollow">namedtuple</a>:</p>
<pre><code>from collections import namedtuple
message = namedtuple('Message', ['propertyName'], verbose=True)
messages = [
message('propertyValueOne'),
message('propertyValueTwo')
]
</code></pre>
| 0 | 2016-05-11T07:19:13Z | [
"python",
"instantiation",
"dynamic-languages"
] |
Is there an equivalent of Python's itertools for Java? | 1,528,966 | <p>I'm searching for a library (preferably generic) that generates iterable combinations and permutations of data contained in collections. Cartesian product would also be nice.</p>
<p>The best way of describing what I want would be "itertools for Java".</p>
| 14 | 2009-10-07T00:57:24Z | 1,529,187 | <p><code>itertools</code> does much more than <em>just</em> combinations and permutations, so (while it would surely be nice to have all of <code>itertools</code> when coding Java;-) you can get away with much less.</p>
<p>For example, for permutations, see <a href="https://web.archive.org/web/20120217153017/http://www.merriampark.com/perm.htm" rel="nofollow">here</a>; for combinations, <a href="https://web.archive.org/web/20120213125655/http://www.merriampark.com/comb.htm" rel="nofollow">here</a> (both classes are from the same author).</p>
| 3 | 2009-10-07T02:26:21Z | [
"java",
"python",
"combinatorics",
"itertools"
] |
Is there an equivalent of Python's itertools for Java? | 1,528,966 | <p>I'm searching for a library (preferably generic) that generates iterable combinations and permutations of data contained in collections. Cartesian product would also be nice.</p>
<p>The best way of describing what I want would be "itertools for Java".</p>
| 14 | 2009-10-07T00:57:24Z | 2,044,586 | <p>Cartesian product is available here:
<a href="http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/collect/Sets.html#cartesianProduct%28java.util.Set...%29">http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/collect/Sets.html#cartesianProduct%28java.util.Set...%29</a></p>
| 5 | 2010-01-11T20:09:41Z | [
"java",
"python",
"combinatorics",
"itertools"
] |
Is there an equivalent of Python's itertools for Java? | 1,528,966 | <p>I'm searching for a library (preferably generic) that generates iterable combinations and permutations of data contained in collections. Cartesian product would also be nice.</p>
<p>The best way of describing what I want would be "itertools for Java".</p>
| 14 | 2009-10-07T00:57:24Z | 4,616,789 | <p>Here you find something that might cover your combinatorial needs bundled in a library:</p>
<p><a href="http://code.google.com/p/combinatoricslib/" rel="nofollow">http://code.google.com/p/combinatoricslib/</a></p>
| 2 | 2011-01-06T15:53:08Z | [
"java",
"python",
"combinatorics",
"itertools"
] |
Is there an equivalent of Python's itertools for Java? | 1,528,966 | <p>I'm searching for a library (preferably generic) that generates iterable combinations and permutations of data contained in collections. Cartesian product would also be nice.</p>
<p>The best way of describing what I want would be "itertools for Java".</p>
| 14 | 2009-10-07T00:57:24Z | 5,767,853 | <p>I'm actually making a port of itertools to java: it's called <a href="http://code.google.com/p/neoitertools/">neoitertools</a></p>
<p>Any feedback appreciated as it still in beta. Missing the "product" function yet, and some intensive tests.</p>
| 10 | 2011-04-24T00:22:34Z | [
"java",
"python",
"combinatorics",
"itertools"
] |
Is there an equivalent of Python's itertools for Java? | 1,528,966 | <p>I'm searching for a library (preferably generic) that generates iterable combinations and permutations of data contained in collections. Cartesian product would also be nice.</p>
<p>The best way of describing what I want would be "itertools for Java".</p>
| 14 | 2009-10-07T00:57:24Z | 9,474,013 | <p>I'm just throwing this out there, but shouldn't it be possible to use Python's itertools implementation directly from Java using Jython? Is it a C-based api?</p>
<p>[one Google later]</p>
<p><a href="http://www.jython.org/javadoc/org/python/modules/itertools.html" rel="nofollow">itertools (Jython API documentation)</a></p>
<p>Actually, the <a href="http://code.google.com/p/neoitertools/" rel="nofollow">neoitertools</a> project listed above looks very promising, it appears to be in [very] active development (according to Google code) and looks to be a complete implemetation of the itertools functionality, plus it's available via Maven.</p>
<p>Just my 2 pence.</p>
| 1 | 2012-02-27T23:25:41Z | [
"java",
"python",
"combinatorics",
"itertools"
] |
Is there an equivalent of Python's itertools for Java? | 1,528,966 | <p>I'm searching for a library (preferably generic) that generates iterable combinations and permutations of data contained in collections. Cartesian product would also be nice.</p>
<p>The best way of describing what I want would be "itertools for Java".</p>
| 14 | 2009-10-07T00:57:24Z | 39,439,426 | <p>Few years later, <a href="https://github.com/dpaukov/combinatoricslib" rel="nofollow">combinatorics</a> seems to fit your needs. Taken from the readme:</p>
<pre><code>Simple permutations
Permutations with repetitions
Simple combinations
Combinations with repetitions
Subsets
Integer Partitions
List Partitions
Integer Compositions
</code></pre>
| 0 | 2016-09-11T18:41:27Z | [
"java",
"python",
"combinatorics",
"itertools"
] |
Can't set attributes of object class | 1,529,002 | <p>So, I was playing around with Python while answering <a href="http://stackoverflow.com/questions/1528932/how-to-create-inline-objects-with-properties-in-python/">this question</a>, and I discovered that this is not valid:</p>
<pre><code>o = object()
o.attr = 'hello'
</code></pre>
<p>due to an <code>AttributeError: 'object' object has no attribute 'attr'</code>. However, with any class inherited from object, it is valid:</p>
<pre><code>class Sub(object):
pass
s = Sub()
s.attr = 'hello'
</code></pre>
<p>Printing <code>s.attr</code> displays 'hello' as expected. Why is this the case? What in the Python language specification specifies that you can't assign attributes to vanilla objects?</p>
| 53 | 2009-10-07T01:07:55Z | 1,529,012 | <p>This is (IMO) one of the fundamental limitations with Python - you can't re-open classes. I believe the actual problem, though, is caused by the fact that classes implemented in C can't be modified at runtime... subclasses can, but not the base classes.</p>
| 0 | 2009-10-07T01:12:03Z | [
"python",
"attributes",
"language-design"
] |
Can't set attributes of object class | 1,529,002 | <p>So, I was playing around with Python while answering <a href="http://stackoverflow.com/questions/1528932/how-to-create-inline-objects-with-properties-in-python/">this question</a>, and I discovered that this is not valid:</p>
<pre><code>o = object()
o.attr = 'hello'
</code></pre>
<p>due to an <code>AttributeError: 'object' object has no attribute 'attr'</code>. However, with any class inherited from object, it is valid:</p>
<pre><code>class Sub(object):
pass
s = Sub()
s.attr = 'hello'
</code></pre>
<p>Printing <code>s.attr</code> displays 'hello' as expected. Why is this the case? What in the Python language specification specifies that you can't assign attributes to vanilla objects?</p>
| 53 | 2009-10-07T01:07:55Z | 1,529,027 | <p>It's because object is a "type", not a class. In general, all classes that are defined in C extensions (like all the built in datatypes, and stuff like numpy arrays) do not allow addition of arbitrary attributes.</p>
| 1 | 2009-10-07T01:16:32Z | [
"python",
"attributes",
"language-design"
] |
Can't set attributes of object class | 1,529,002 | <p>So, I was playing around with Python while answering <a href="http://stackoverflow.com/questions/1528932/how-to-create-inline-objects-with-properties-in-python/">this question</a>, and I discovered that this is not valid:</p>
<pre><code>o = object()
o.attr = 'hello'
</code></pre>
<p>due to an <code>AttributeError: 'object' object has no attribute 'attr'</code>. However, with any class inherited from object, it is valid:</p>
<pre><code>class Sub(object):
pass
s = Sub()
s.attr = 'hello'
</code></pre>
<p>Printing <code>s.attr</code> displays 'hello' as expected. Why is this the case? What in the Python language specification specifies that you can't assign attributes to vanilla objects?</p>
| 53 | 2009-10-07T01:07:55Z | 1,529,029 | <p>So, investigating my own question, I discovered this about the Python language: you can inherit from things like int, and you see the same behaviour:</p>
<pre><code>>>> class MyInt(int):
pass
>>> x = MyInt()
>>> print x
0
>>> x.hello = 4
>>> print x.hello
4
>>> x = x + 1
>>> print x
1
>>> print x.hello
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
AttributeError: 'int' object has no attribute 'hello'
</code></pre>
<p>I assume the error at the end is because the add function returns an int, so I'd have to override functions like <code>__add__</code> and such in order to retain my custom attributes. But this all now makes sense to me (I think), when I think of "object" like "int". </p>
| 1 | 2009-10-07T01:16:57Z | [
"python",
"attributes",
"language-design"
] |
Can't set attributes of object class | 1,529,002 | <p>So, I was playing around with Python while answering <a href="http://stackoverflow.com/questions/1528932/how-to-create-inline-objects-with-properties-in-python/">this question</a>, and I discovered that this is not valid:</p>
<pre><code>o = object()
o.attr = 'hello'
</code></pre>
<p>due to an <code>AttributeError: 'object' object has no attribute 'attr'</code>. However, with any class inherited from object, it is valid:</p>
<pre><code>class Sub(object):
pass
s = Sub()
s.attr = 'hello'
</code></pre>
<p>Printing <code>s.attr</code> displays 'hello' as expected. Why is this the case? What in the Python language specification specifies that you can't assign attributes to vanilla objects?</p>
| 53 | 2009-10-07T01:07:55Z | 1,529,099 | <p>An instance of <code>object</code> does <strong>not</strong> carry around a <code>__dict__</code> -- if it did, before the horrible circular dependence problem (since <code>dict</code>, like most everything else, inherits from <code>object</code>;-), this would saddle <em>every</em> object in Python with a dict, which would mean an overhead of <em>many</em> bytes per object that currently doesn't have or need a dict (essentially, all objects that don't have arbitrarily assignable attributes don't have or need a dict).</p>
<p>For example, using the excellent <code>pympler</code> project (you can get it via svn from <a href="http://code.google.com/p/pympler/source/checkout">here</a>), we can do some measurements...:</p>
<pre><code>>>> from pympler import asizeof
>>> asizeof.asizeof({})
144
>>> asizeof.asizeof(23)
16
</code></pre>
<p>You wouldn't want every <code>int</code> to take up 144 bytes instead of just 16, right?-)</p>
<p>Now, when you make a class (inheriting from whatever), things change...:</p>
<pre><code>>>> class dint(int): pass
...
>>> asizeof.asizeof(dint(23))
184
</code></pre>
<p>...the <code>__dict__</code> <em>is</em> now added (plus, a little more overhead) -- so a <code>dint</code> instance can have arbitrary attributes, but you pay quite a space cost for that flexibility.</p>
<p>So what if you wanted <code>int</code>s with just <em>one</em> extra attribute <code>foobar</code>...? It's a rare need, but Python does offer a special mechanism for the purpose...</p>
<pre><code>>>> class fint(int):
... __slots__ = 'foobar',
... def __init__(self, x): self.foobar=x+100
...
>>> asizeof.asizeof(fint(23))
80
</code></pre>
<p>...not <em>quite</em> as tiny as an <code>int</code>, mind you! (or even the two <code>int</code>s, one the <code>self</code> and one the <code>self.foobar</code> -- the second one can be reassigned), but surely much better than a <code>dint</code>.</p>
<p>When the class has the <code>__slots__</code> special attribute (a sequence of strings), then the <code>class</code> statement (more precisely, the default metaclass, <code>type</code>) does <strong>not</strong> equip every instance of that class with a <code>__dict__</code> (and therefore the ability to have arbitrary attributes), just a finite, rigid set of "slots" (basically places which can each hold one reference to some object) with the given names.</p>
<p>In exchange for the lost flexibility, you gain a lot of bytes per instance (probably meaningful only if you have zillions of instances gallivanting around, but, there <em>are</em> use cases for that).</p>
| 88 | 2009-10-07T01:47:26Z | [
"python",
"attributes",
"language-design"
] |
Can't set attributes of object class | 1,529,002 | <p>So, I was playing around with Python while answering <a href="http://stackoverflow.com/questions/1528932/how-to-create-inline-objects-with-properties-in-python/">this question</a>, and I discovered that this is not valid:</p>
<pre><code>o = object()
o.attr = 'hello'
</code></pre>
<p>due to an <code>AttributeError: 'object' object has no attribute 'attr'</code>. However, with any class inherited from object, it is valid:</p>
<pre><code>class Sub(object):
pass
s = Sub()
s.attr = 'hello'
</code></pre>
<p>Printing <code>s.attr</code> displays 'hello' as expected. Why is this the case? What in the Python language specification specifies that you can't assign attributes to vanilla objects?</p>
| 53 | 2009-10-07T01:07:55Z | 1,529,237 | <p>It is simply due to optimization.</p>
<p>Dicts are relatively large.</p>
<pre><code>>>> import sys
>>> sys.getsizeof((lambda:1).__dict__)
140
</code></pre>
<p>Most (maybe all) classes that are defined in C do not have a dict for optimization.</p>
<p>If you look at the <a href="http://svn.python.org/view/python/trunk/Objects/object.c?revision=74457&view=markup">source code</a> you will see that there are many checks to see if the object has a dict or not.</p>
| 5 | 2009-10-07T02:45:56Z | [
"python",
"attributes",
"language-design"
] |
Can't set attributes of object class | 1,529,002 | <p>So, I was playing around with Python while answering <a href="http://stackoverflow.com/questions/1528932/how-to-create-inline-objects-with-properties-in-python/">this question</a>, and I discovered that this is not valid:</p>
<pre><code>o = object()
o.attr = 'hello'
</code></pre>
<p>due to an <code>AttributeError: 'object' object has no attribute 'attr'</code>. However, with any class inherited from object, it is valid:</p>
<pre><code>class Sub(object):
pass
s = Sub()
s.attr = 'hello'
</code></pre>
<p>Printing <code>s.attr</code> displays 'hello' as expected. Why is this the case? What in the Python language specification specifies that you can't assign attributes to vanilla objects?</p>
| 53 | 2009-10-07T01:07:55Z | 22,966,774 | <p>As other answerers have said, an <code>object</code> does not have a <code>__dict__</code>. <code>object</code> is the base class of <strong>all</strong> types, including <code>int</code> or <code>str</code>. Thus whatever is provided by <code>object</code> will be a burden to them as well. Even something as simple as an <em>optional</em> <code>__dict__</code> would need an extra pointer for each value; this would waste additional 4-8 bytes of memory for each object in the system, for a very limited utility.</p>
<hr>
<p>Instead of doing an instance of a dummy class, in Python 3.3+, you can (and should) use <a href="https://docs.python.org/3/library/types.html#types.SimpleNamespace"><code>types.SimpleNamespace</code></a> for this.</p>
| 15 | 2014-04-09T15:09:53Z | [
"python",
"attributes",
"language-design"
] |
Can a WIN32 program authenticate into Django authentication system, using MYSQL? | 1,529,128 | <p>I have a web service with Django Framework.<br />
My friend's project is a WIN32 program and also a MS-sql server.</p>
<p>The Win32 program currently has a login system that talks to a MS-sql for authentication.</p>
<p>However, we would like to INTEGRATE this login system as one.</p>
<p>Please answer the 2 things:</p>
<ol>
<li>I want scrap the MS-SQL to use only the Django authentication system on the linux server. Can the WIN32 client talk to Django using a Django API (login)?</li>
<li>If not, what is the best way of combining the authentication?</li>
</ol>
| 1 | 2009-10-07T01:59:57Z | 1,529,146 | <p>If the only thing the WIN32 app uses the MS-SQL Server for is Authentication/Authorization then you could write a new Authentication/Authorization provider that uses a set of Web Services (that you would have to create) that expose the Django provider.</p>
| 0 | 2009-10-07T02:05:25Z | [
"python",
"windows",
"django",
"authentication",
"frameworks"
] |
Can a WIN32 program authenticate into Django authentication system, using MYSQL? | 1,529,128 | <p>I have a web service with Django Framework.<br />
My friend's project is a WIN32 program and also a MS-sql server.</p>
<p>The Win32 program currently has a login system that talks to a MS-sql for authentication.</p>
<p>However, we would like to INTEGRATE this login system as one.</p>
<p>Please answer the 2 things:</p>
<ol>
<li>I want scrap the MS-SQL to use only the Django authentication system on the linux server. Can the WIN32 client talk to Django using a Django API (login)?</li>
<li>If not, what is the best way of combining the authentication?</li>
</ol>
| 1 | 2009-10-07T01:59:57Z | 1,529,161 | <p>Either provide a view where your win32 client can post to the django server and get a response that means "good login" or "bad login". This will require you to modify the win32 client and create a very simple django view.</p>
<p>Or provide your own <a href="http://docs.djangoproject.com/en/dev/topics/auth/#specifying-authentication-backends" rel="nofollow">Django Authentication backend</a> that authenticates your django logins against the MS-sql server. This alternative will require no modification to your win32 client but probably quite a bit of effort on the authentication backend front. A bit of research might yield someone else's backend that you can re-use. <a href="http://www.mail-archive.com/django-updates@googlegroups.com/msg16966.html" rel="nofollow">This looks like a promising place to start</a> - they claim that "Both Windows Authentication (Integrated Security) and SQL Server
Authentication supported."</p>
| 2 | 2009-10-07T02:17:34Z | [
"python",
"windows",
"django",
"authentication",
"frameworks"
] |
why is urllib2 missing table fields which I can see in the Firefox source? | 1,529,234 | <p>the html that I am receiving from urllib2 is missing dozens of fields of data that I can see when I view the source of the URL in Firefox. Any advice would be much appreciated. Here is what it looks like: </p>
<p>from FireFox view source: </p>
<pre><code># ...<td class=td6>as</td></tr></thead>|ManyFields|<br></div><div id="c1">...
</code></pre>
<p>from urllib2 return html: </p>
<pre><code># ...<td class=td6>as</td></tr></thead>|</table>|<br></div><div id="c1">...
</code></pre>
| 0 | 2009-10-07T02:45:32Z | 1,529,364 | <p>It seems from a cursory check that the page you're getting has a <strong>lot</strong> of Javascript; perhaps that Javascript cooperates in building the information that you see at the end in Firefox (at least some of it is actively altering the page's contents). If you need to scrape JS-rich pages, your best bet is to automate an actual browser via <a href="http://jimmyg.org/blog/2009/getting-started-with-selenium-and-python.html" rel="nofollow">Selenium</a>.</p>
| 2 | 2009-10-07T03:43:09Z | [
"python",
"html",
"field",
"urllib2"
] |
why is urllib2 missing table fields which I can see in the Firefox source? | 1,529,234 | <p>the html that I am receiving from urllib2 is missing dozens of fields of data that I can see when I view the source of the URL in Firefox. Any advice would be much appreciated. Here is what it looks like: </p>
<p>from FireFox view source: </p>
<pre><code># ...<td class=td6>as</td></tr></thead>|ManyFields|<br></div><div id="c1">...
</code></pre>
<p>from urllib2 return html: </p>
<pre><code># ...<td class=td6>as</td></tr></thead>|</table>|<br></div><div id="c1">...
</code></pre>
| 0 | 2009-10-07T02:45:32Z | 1,529,381 | <p>The extra content you're seeing is generated by JavaScript. It is not part of the raw HTML document, and hence won't be present with a plain HTTP fetcher such as urllib2.</p>
| 0 | 2009-10-07T03:48:52Z | [
"python",
"html",
"field",
"urllib2"
] |
Help to solve my problems with python LIST? | 1,529,307 | <pre><code>author_A = [['book_x',1,10],['book_y',2,20],['book_z',3,30]]
author_B = [['book_s',5,10],['book_t',2,20],['book_z',3,30]]
author_A AND author_B = ['book_z',3,30]
author_A = [['book_x',1,10],['book_y',2,20]]
author_B = [['book_s',5,10],['book_t',2,20]]
---------------------------------------------
</code></pre>
<p>I Want present data like this </p>
<pre><code> author quantity Amount($)
A&B 3 30
A 3 30
B 7 30
total 13 90
</code></pre>
<p>I DO NOT Want present data like this !!! in this case it's ADDED duplicate ['book_z',3,30]</p>
<pre><code> author quantity Amount($)
A 6 60
B 10 60
total 16 120
</code></pre>
<p>that is my problems ,Anybody Please help me to sove this problems.
Thanks everybody</p>
| 0 | 2009-10-07T03:15:20Z | 1,529,346 | <p>You can find the intersections and exclusive ones like this...</p>
<pre><code>A_and_B = [a for a in author_A if a in author_B]
only_A = [a for a in author_A if a not in author_B]
only_B = [b for b in author_B if b not in author_A]
</code></pre>
<p>then it is only a matter of printing them...</p>
<pre><code>print '%s %d %d' % tuple(A_and_B)
print '%s %d %d' % tuple(only_A)
print '%s %d %d' % tuple(only_B)
</code></pre>
<p>Hope that helps</p>
| 1 | 2009-10-07T03:36:19Z | [
"python"
] |
Help to solve my problems with python LIST? | 1,529,307 | <pre><code>author_A = [['book_x',1,10],['book_y',2,20],['book_z',3,30]]
author_B = [['book_s',5,10],['book_t',2,20],['book_z',3,30]]
author_A AND author_B = ['book_z',3,30]
author_A = [['book_x',1,10],['book_y',2,20]]
author_B = [['book_s',5,10],['book_t',2,20]]
---------------------------------------------
</code></pre>
<p>I Want present data like this </p>
<pre><code> author quantity Amount($)
A&B 3 30
A 3 30
B 7 30
total 13 90
</code></pre>
<p>I DO NOT Want present data like this !!! in this case it's ADDED duplicate ['book_z',3,30]</p>
<pre><code> author quantity Amount($)
A 6 60
B 10 60
total 16 120
</code></pre>
<p>that is my problems ,Anybody Please help me to sove this problems.
Thanks everybody</p>
| 0 | 2009-10-07T03:15:20Z | 1,529,348 | <pre><code>author_A = [['book_x',1,10],['book_y',2,20],['book_z',3,30]]
author_B = [['book_s',5,10],['book_t',2,20],['book_z',3,30]]
def present(A, B):
Aset = set(tuple(x) for x in A)
Bset = set(tuple(x) for x in B)
both = Aset & Bset
justA = Aset - both
justB = Bset - both
totals = [0, 0]
print "%-12s %-12s %12s" % ('author', 'quantity', 'Amount($)')
for subset, name in zip((both, justA, justB), ('A*B', 'A', 'B')):
tq = sum(x[1] for x in subset)
ta = sum(x[2] for x in subset)
totals[0] += tq
totals[1] += ta
print ' %-11s %-11d %-11d' % (name, tq, ta)
print ' %-11s %-11d %-11d' % ('total', totals[0], totals[1])
present(author_A, author_B)
</code></pre>
<p>I've tried to reproduce your desired weird format with some numbers left-aligned and totally funky spacing, but I'm sure you'll need to tweak the formatting in the various print statements to get the exact (and totally weird) formatting effect of your examples. However, apart from the spacing and left- vs right- alignment of the output, this should otherwise be exactly what you request.</p>
| 6 | 2009-10-07T03:36:42Z | [
"python"
] |
Help to solve my problems with python LIST? | 1,529,307 | <pre><code>author_A = [['book_x',1,10],['book_y',2,20],['book_z',3,30]]
author_B = [['book_s',5,10],['book_t',2,20],['book_z',3,30]]
author_A AND author_B = ['book_z',3,30]
author_A = [['book_x',1,10],['book_y',2,20]]
author_B = [['book_s',5,10],['book_t',2,20]]
---------------------------------------------
</code></pre>
<p>I Want present data like this </p>
<pre><code> author quantity Amount($)
A&B 3 30
A 3 30
B 7 30
total 13 90
</code></pre>
<p>I DO NOT Want present data like this !!! in this case it's ADDED duplicate ['book_z',3,30]</p>
<pre><code> author quantity Amount($)
A 6 60
B 10 60
total 16 120
</code></pre>
<p>that is my problems ,Anybody Please help me to sove this problems.
Thanks everybody</p>
| 0 | 2009-10-07T03:15:20Z | 1,529,531 | <pre><code>books = {
'A':[['book_x',1,10],['book_y',2,20]],
'B':[['book_s',5,10],['book_t',2,20]],
'A & B':[['book_z',3,30]],
}
for key in books:
quantity = []
amount = []
for item in books[key]:
quantity.append(item[1])
amount.append(item[2])
print ("%s\t%s\t%s") % (key,sum(quantity),sum(amount))
</code></pre>
| 0 | 2009-10-07T04:52:22Z | [
"python"
] |
Python sqlite3 "unable to open database file" on windows | 1,529,527 | <p>I am working on a windows vista machine in python 3.1.1. I am trying to insert a large number of rows into a SQLite3 db. The file exists, and my program properly inserts <em>some</em> rows into the db. However, at some point in the insertion process, the program dies with this message:
sqlite3.OperationalError: unable to open database file</p>
<p>However, before it dies, there are several rows that are properly added to the database.</p>
<p>Here is the code which specifically handles the insertion:</p>
<pre><code>idx = 0
lst_to_ins = []
for addl_img in all_jpegs:
lst_to_ins.append((addl_img['col1'], addl_img['col2']))
idx = idx + 1
if idx % 10 == 0:
logging.debug('adding rows [%s]', lst_to_ins)
conn.executemany(ins_sql, lst_to_ins)
conn.commit()
lst_to_ins = []
logging.debug('added 10 rows [%d]', idx)
if len(lst_to_ins) > 0:
conn.executemany(ins_sql, lst_to_ins)
conn.commit()
logging.debug('adding the last few rows to the db')
</code></pre>
<p>This code inserts anywhere from 10 to 400 rows, then dies with the error message </p>
<pre><code>conn.executemany(ins_sql, lst_to_ins)
sqlite3.OperationalError: unable to open database file
</code></pre>
<p>How is it possible that I can insert some rows, but then get this error?</p>
| 6 | 2009-10-07T04:50:37Z | 1,529,642 | <p>SQLite does not have record locking; it uses a simple locking mechanism that locks the entire database file briefly during a write. It sounds like you are running into a lock that hasn't cleared yet.</p>
<p>The author of SQLite recommends that you create a transaction prior to doing your inserts, and then complete the transaction at the end. This causes SQLite to queue the insert requests, and perform them using a single file lock when the transaction is committed.</p>
<p>In the newest version of SQLite, the locking mechanism has been enhanced, so it might not require a full file lock anymore.</p>
| 1 | 2009-10-07T05:26:10Z | [
"python",
"sqlite",
"windows-vista"
] |
Python sqlite3 "unable to open database file" on windows | 1,529,527 | <p>I am working on a windows vista machine in python 3.1.1. I am trying to insert a large number of rows into a SQLite3 db. The file exists, and my program properly inserts <em>some</em> rows into the db. However, at some point in the insertion process, the program dies with this message:
sqlite3.OperationalError: unable to open database file</p>
<p>However, before it dies, there are several rows that are properly added to the database.</p>
<p>Here is the code which specifically handles the insertion:</p>
<pre><code>idx = 0
lst_to_ins = []
for addl_img in all_jpegs:
lst_to_ins.append((addl_img['col1'], addl_img['col2']))
idx = idx + 1
if idx % 10 == 0:
logging.debug('adding rows [%s]', lst_to_ins)
conn.executemany(ins_sql, lst_to_ins)
conn.commit()
lst_to_ins = []
logging.debug('added 10 rows [%d]', idx)
if len(lst_to_ins) > 0:
conn.executemany(ins_sql, lst_to_ins)
conn.commit()
logging.debug('adding the last few rows to the db')
</code></pre>
<p>This code inserts anywhere from 10 to 400 rows, then dies with the error message </p>
<pre><code>conn.executemany(ins_sql, lst_to_ins)
sqlite3.OperationalError: unable to open database file
</code></pre>
<p>How is it possible that I can insert some rows, but then get this error?</p>
| 6 | 2009-10-07T04:50:37Z | 2,127,838 | <p>same error here on windows 7 (python 2.6, django 1.1.1 and sqllite) after some records inserted correctly: sqlite3.OperationalError: unable to open database file</p>
<p>I ran my script from Eclipse different times and always got that error. But as I ran it from the command line (after setting PYTHONPATH and DJANGO_SETTINGS_MODULE) it worked as a charm...</p>
<p>just my 2 cents!</p>
| 0 | 2010-01-24T16:43:24Z | [
"python",
"sqlite",
"windows-vista"
] |
Print extremely large long in scientific notation in python | 1,529,569 | <p>Is there a way to get python to print extremely large longs in scientific notation? I am talking about numbers on the order of 10^1000 or larger, at this size the standard print "%e" % num fails.</p>
<p>For example:</p>
<pre>
Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41)
[GCC 4.3.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> print "%e" % 10**100
1.000000e+100
>>> print "%e" % 10**1000
Traceback (most recent call last):
File "", line 1, in
TypeError: float argument required, not long
</pre>
<p>It appears that python is trying to convert the long to a float and then print it, is it possible to get python to just print the long in scientific notation without converting it to a float?</p>
| 12 | 2009-10-07T05:03:35Z | 1,529,607 | <p><a href="http://code.google.com/p/gmpy/">gmpy</a> to the rescue...:</p>
<pre><code>>>> import gmpy
>>> x = gmpy.mpf(10**1000)
>>> x.digits(10, 0, -1, 1)
'1.e1000'
</code></pre>
<p>I'm biased, of course, as the original author and still a committer of <code>gmpy</code>, but I do think it eases tasks such as this one that can be quite a chore without it (I don't know a simple way to do it without <em>some</em> add-on, and <code>gmpy</code>'s definitely <strong>the</strong> add-on I'd choose here;-).</p>
| 15 | 2009-10-07T05:14:12Z | [
"python"
] |
Print extremely large long in scientific notation in python | 1,529,569 | <p>Is there a way to get python to print extremely large longs in scientific notation? I am talking about numbers on the order of 10^1000 or larger, at this size the standard print "%e" % num fails.</p>
<p>For example:</p>
<pre>
Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41)
[GCC 4.3.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> print "%e" % 10**100
1.000000e+100
>>> print "%e" % 10**1000
Traceback (most recent call last):
File "", line 1, in
TypeError: float argument required, not long
</pre>
<p>It appears that python is trying to convert the long to a float and then print it, is it possible to get python to just print the long in scientific notation without converting it to a float?</p>
| 12 | 2009-10-07T05:03:35Z | 2,330,992 | <p>No need to use a third party library. Here's a solution in Python3, that works for large integers.</p>
<pre><code>def ilog(n, base):
"""
Find the integer log of n with respect to the base.
>>> import math
>>> for base in range(2, 16 + 1):
... for n in range(1, 1000):
... assert ilog(n, base) == int(math.log(n, base) + 1e-10), '%s %s' % (n, base)
"""
count = 0
while n >= base:
count += 1
n //= base
return count
def sci_notation(n, prec=3):
"""
Represent n in scientific notation, with the specified precision.
>>> sci_notation(1234 * 10**1000)
'1.234e+1003'
>>> sci_notation(10**1000 // 2, prec=1)
'5.0e+999'
"""
base = 10
exponent = ilog(n, base)
mantissa = n / base**exponent
return '{0:.{1}f}e{2:+d}'.format(mantissa, prec, exponent)
</code></pre>
| 4 | 2010-02-25T01:37:07Z | [
"python"
] |
how to create new file using python | 1,529,584 | <p>how can i create new file in /var/log directory using python language in OSX leopard? i tried to do it using os.open function but i get "permission denied"</p>
<p>thanks in advance</p>
| 1 | 2009-10-07T05:07:44Z | 1,529,596 | <p>It probably failed because /var/log has user set to root and group set to wheel. Try running your python code as root and it will probably work.</p>
| 1 | 2009-10-07T05:11:17Z | [
"python",
"osx",
"osx-leopard"
] |
how to create new file using python | 1,529,584 | <p>how can i create new file in /var/log directory using python language in OSX leopard? i tried to do it using os.open function but i get "permission denied"</p>
<p>thanks in advance</p>
| 1 | 2009-10-07T05:07:44Z | 1,529,612 | <p>Only root can write in <code>/var/log/</code> on Mac OS X...:</p>
<pre><code>$ ls -ld /var/log
drwxr-xr-x 60 root wheel 2040 Oct 6 17:00 /var/log
</code></pre>
<p>Maybe consider using the <code>syslog</code> module in the standard library...</p>
| 6 | 2009-10-07T05:16:10Z | [
"python",
"osx",
"osx-leopard"
] |
how to create new file using python | 1,529,584 | <p>how can i create new file in /var/log directory using python language in OSX leopard? i tried to do it using os.open function but i get "permission denied"</p>
<p>thanks in advance</p>
| 1 | 2009-10-07T05:07:44Z | 1,529,652 | <p>You can create the log file as root and then change the owner to the user your script is run as</p>
<pre><code># touch /var/log/mylogfile
# chown myuser /var/log/mylogfile
</code></pre>
<p>where mylogfile is your logfile and myuser is the user the script will be run as</p>
<p>also look into logrotate</p>
| 1 | 2009-10-07T05:29:02Z | [
"python",
"osx",
"osx-leopard"
] |
How to change the foreground or background colour of a Tkinter Button on Mac OS X? | 1,529,847 | <p>I've been working through the Tkinter chapters in Programming Python and encountered a problem where the foreground and background colours of a button will not change. I am working on a Mac OS X 10.6 system with Python 2.6.1. The colours of a label will change, but not the colours of a button. For example:</p>
<pre><code>from Tkinter import *
Label(None, text='label', fg='green', bg='black').pack()
Button(None, text='button', fg='green', bg='black').pack()
mainloop()
</code></pre>
<p>On my Mac system the colours of the label change, but the colours of the button do not. On a Windows system with Python 2.6.1 the colours of both the label and button change.</p>
<p>Anyone know what is going wrong?</p>
<p>I've checked Interface Builder and it appears that there is no option to change the foreground or background colour of a button in that tool. There is the ability to edit the foreground and background colours of a label.</p>
<p>The Mac OS X rendering system (Quartz?) may just not support (easily) changing the fg and bg of a button.</p>
| 7 | 2009-10-07T06:28:57Z | 1,530,913 | <p>I think the answer is that the buttons on the mac simply don't support changing the background and foreground colors. As you've seen, this isn't unique to Tk.</p>
| 10 | 2009-10-07T10:58:11Z | [
"python",
"osx",
"tkinter"
] |
How to change the foreground or background colour of a Tkinter Button on Mac OS X? | 1,529,847 | <p>I've been working through the Tkinter chapters in Programming Python and encountered a problem where the foreground and background colours of a button will not change. I am working on a Mac OS X 10.6 system with Python 2.6.1. The colours of a label will change, but not the colours of a button. For example:</p>
<pre><code>from Tkinter import *
Label(None, text='label', fg='green', bg='black').pack()
Button(None, text='button', fg='green', bg='black').pack()
mainloop()
</code></pre>
<p>On my Mac system the colours of the label change, but the colours of the button do not. On a Windows system with Python 2.6.1 the colours of both the label and button change.</p>
<p>Anyone know what is going wrong?</p>
<p>I've checked Interface Builder and it appears that there is no option to change the foreground or background colour of a button in that tool. There is the ability to edit the foreground and background colours of a label.</p>
<p>The Mac OS X rendering system (Quartz?) may just not support (easily) changing the fg and bg of a button.</p>
| 7 | 2009-10-07T06:28:57Z | 9,543,342 | <p>
For anyone else who happens upon this question as I did, the solution is to use the <a href="http://docs.python.org/library/ttk.html" rel="nofollow">ttk</a> module, which is available by default on OS X 10.7. Unfortunately, setting the background color still doesn't work out of the box, but text color does.</p>
<p>It requires a small change to the code:</p>
<p>Original:</p>
<pre class="lang-python prettyprint-override"><code>from Tkinter import *
Label(None, text='label', fg='green', bg='black').pack()
Button(None, text='button', fg='green', bg='black').pack()
mainloop()
</code></pre>
<p>With ttk:</p>
<pre class="lang-python prettyprint-override"><code>import tkinter as tk
from tkinter import ttk
root = tk.Tk()
# background="..." doesn't work...
ttk.Style().configure('green/black.TLabel', foreground='green', background='black')
ttk.Style().configure('green/black.TButton', foreground='green', background='black')
label = ttk.Label(root, text='I am a ttk.Label with text!', style='green/black.TLabel')
label.pack()
button = ttk.Button(root, text='Click Me!', style='green/black.TButton')
button.pack()
root.mainloop()
</code></pre>
| 8 | 2012-03-03T04:04:44Z | [
"python",
"osx",
"tkinter"
] |
How to change the foreground or background colour of a Tkinter Button on Mac OS X? | 1,529,847 | <p>I've been working through the Tkinter chapters in Programming Python and encountered a problem where the foreground and background colours of a button will not change. I am working on a Mac OS X 10.6 system with Python 2.6.1. The colours of a label will change, but not the colours of a button. For example:</p>
<pre><code>from Tkinter import *
Label(None, text='label', fg='green', bg='black').pack()
Button(None, text='button', fg='green', bg='black').pack()
mainloop()
</code></pre>
<p>On my Mac system the colours of the label change, but the colours of the button do not. On a Windows system with Python 2.6.1 the colours of both the label and button change.</p>
<p>Anyone know what is going wrong?</p>
<p>I've checked Interface Builder and it appears that there is no option to change the foreground or background colour of a button in that tool. There is the ability to edit the foreground and background colours of a label.</p>
<p>The Mac OS X rendering system (Quartz?) may just not support (easily) changing the fg and bg of a button.</p>
| 7 | 2009-10-07T06:28:57Z | 34,762,619 | <p>I was looking as to why this doesn't work as well. I found a quick way to try and fix it is to have a label and then bind a click with the label. Then have the label change colors for a short time to mimic clicking. Here is an example.</p>
<pre class="lang-python prettyprint-override"><code>def buttonPress(*args):
searchB.config(state = "active")
searchB.update()
time.sleep(0.2)
searchB.config(state = "normal")
## Whatever command you want
searchB = Label(main, text = "Search", bg = "#fecc14", fg = "Black", activebackground = "Red", highlightbackground="Black")
searchB.bind("<Button-1>", startSearch)
searchB.pack()
</code></pre>
| 0 | 2016-01-13T09:16:49Z | [
"python",
"osx",
"tkinter"
] |
Debugging a scripting language like ruby | 1,529,896 | <p>I am basically from the world of C language programming, now delving into the world of scripting languages like Ruby and Python.</p>
<p>I am wondering how to do debugging.
At present the steps I follow is, </p>
<ul>
<li>I complete a large script,</li>
<li>Comment everything but the portion I
want to check</li>
<li>Execute the script</li>
</ul>
<p>Though it works, I am not able to debug like how I would do in, say, a VC++ environment or something like that.</p>
<p>My question is, is there any better way of debugging?</p>
<p>Note: I guess it may be a repeated question, if so, please point me to the answer.</p>
| 6 | 2009-10-07T06:41:49Z | 1,529,917 | <p>Seems like the problem here is that your environment (Visual Studio) doesn't support these languages, not that these languages don't support debuggers in general.</p>
<p>Perl, Python, and Ruby all have fully-featured debuggers; you can find other IDEs that help you, too. For Ruby, there's <a href="http://www.jetbrains.com/ruby/index.html" rel="nofollow">RubyMine</a>; for Perl, there's <a href="http://www.activestate.com/komodo" rel="nofollow">Komodo</a>. And that's just off the top of my head.</p>
| 4 | 2009-10-07T06:47:28Z | [
"python",
"ruby",
"scripting-language"
] |
Debugging a scripting language like ruby | 1,529,896 | <p>I am basically from the world of C language programming, now delving into the world of scripting languages like Ruby and Python.</p>
<p>I am wondering how to do debugging.
At present the steps I follow is, </p>
<ul>
<li>I complete a large script,</li>
<li>Comment everything but the portion I
want to check</li>
<li>Execute the script</li>
</ul>
<p>Though it works, I am not able to debug like how I would do in, say, a VC++ environment or something like that.</p>
<p>My question is, is there any better way of debugging?</p>
<p>Note: I guess it may be a repeated question, if so, please point me to the answer.</p>
| 6 | 2009-10-07T06:41:49Z | 1,529,918 | <p>Here's a <a href="http://brian.maybeyoureinsane.net/blog/2007/05/07/ruby-debug-basics-screencast/" rel="nofollow">screencast</a> on ruby debugging with ruby-debug.</p>
| 6 | 2009-10-07T06:47:48Z | [
"python",
"ruby",
"scripting-language"
] |
Debugging a scripting language like ruby | 1,529,896 | <p>I am basically from the world of C language programming, now delving into the world of scripting languages like Ruby and Python.</p>
<p>I am wondering how to do debugging.
At present the steps I follow is, </p>
<ul>
<li>I complete a large script,</li>
<li>Comment everything but the portion I
want to check</li>
<li>Execute the script</li>
</ul>
<p>Though it works, I am not able to debug like how I would do in, say, a VC++ environment or something like that.</p>
<p>My question is, is there any better way of debugging?</p>
<p>Note: I guess it may be a repeated question, if so, please point me to the answer.</p>
| 6 | 2009-10-07T06:41:49Z | 1,529,926 | <p>If you're working with Python then you can find a list of debugging tools <a href="http://stackoverflow.com/questions/477193/suggestions-for-python-debugging-tools">here</a> to which I just want to add <a href="http://eclipse.org/" rel="nofollow">Eclipse</a> with the <a href="http://pydev.org/" rel="nofollow">Pydev extension</a>, which makes working with breakpoints etc. also very simple.</p>
| 2 | 2009-10-07T06:49:50Z | [
"python",
"ruby",
"scripting-language"
] |
Debugging a scripting language like ruby | 1,529,896 | <p>I am basically from the world of C language programming, now delving into the world of scripting languages like Ruby and Python.</p>
<p>I am wondering how to do debugging.
At present the steps I follow is, </p>
<ul>
<li>I complete a large script,</li>
<li>Comment everything but the portion I
want to check</li>
<li>Execute the script</li>
</ul>
<p>Though it works, I am not able to debug like how I would do in, say, a VC++ environment or something like that.</p>
<p>My question is, is there any better way of debugging?</p>
<p>Note: I guess it may be a repeated question, if so, please point me to the answer.</p>
| 6 | 2009-10-07T06:41:49Z | 1,529,931 | <p>Script languages have no differences compared with other languages in the sense that you still have to break your problems into manageable pieces -- that is, functions. So, instead of testing the whole script after finishing the whole script, I prefer to test those small functions before integrating them. TDD always helps.</p>
| 2 | 2009-10-07T06:50:14Z | [
"python",
"ruby",
"scripting-language"
] |
Debugging a scripting language like ruby | 1,529,896 | <p>I am basically from the world of C language programming, now delving into the world of scripting languages like Ruby and Python.</p>
<p>I am wondering how to do debugging.
At present the steps I follow is, </p>
<ul>
<li>I complete a large script,</li>
<li>Comment everything but the portion I
want to check</li>
<li>Execute the script</li>
</ul>
<p>Though it works, I am not able to debug like how I would do in, say, a VC++ environment or something like that.</p>
<p>My question is, is there any better way of debugging?</p>
<p>Note: I guess it may be a repeated question, if so, please point me to the answer.</p>
| 6 | 2009-10-07T06:41:49Z | 1,529,953 | <p>There is a nice gentle introduction to the Python debugger <a href="http://pythonconquerstheuniverse.wordpress.com/category/the-python-debugger/" rel="nofollow">here</a></p>
| 3 | 2009-10-07T06:56:44Z | [
"python",
"ruby",
"scripting-language"
] |
Debugging a scripting language like ruby | 1,529,896 | <p>I am basically from the world of C language programming, now delving into the world of scripting languages like Ruby and Python.</p>
<p>I am wondering how to do debugging.
At present the steps I follow is, </p>
<ul>
<li>I complete a large script,</li>
<li>Comment everything but the portion I
want to check</li>
<li>Execute the script</li>
</ul>
<p>Though it works, I am not able to debug like how I would do in, say, a VC++ environment or something like that.</p>
<p>My question is, is there any better way of debugging?</p>
<p>Note: I guess it may be a repeated question, if so, please point me to the answer.</p>
| 6 | 2009-10-07T06:41:49Z | 1,529,996 | <p>Your sequence seems entirely backwards to me. Here's how I do it:</p>
<ol>
<li>I write a test for the functionality I want.</li>
<li>I start writing the script, executing bits and verifying test results.</li>
<li>I review what I'd done to document and publish.</li>
</ol>
<p>Specifically, I execute <em>before</em> I complete. It's way too late by then.</p>
<p>There are debuggers, of course, but with good tests and good design, I've almost never needed one.</p>
| 10 | 2009-10-07T07:09:05Z | [
"python",
"ruby",
"scripting-language"
] |
Debugging a scripting language like ruby | 1,529,896 | <p>I am basically from the world of C language programming, now delving into the world of scripting languages like Ruby and Python.</p>
<p>I am wondering how to do debugging.
At present the steps I follow is, </p>
<ul>
<li>I complete a large script,</li>
<li>Comment everything but the portion I
want to check</li>
<li>Execute the script</li>
</ul>
<p>Though it works, I am not able to debug like how I would do in, say, a VC++ environment or something like that.</p>
<p>My question is, is there any better way of debugging?</p>
<p>Note: I guess it may be a repeated question, if so, please point me to the answer.</p>
| 6 | 2009-10-07T06:41:49Z | 1,530,310 | <p>There's a SO question on Ruby IDEs <a href="http://stackoverflow.com/questions/59968/best-editor-or-ide-for-ruby">here</a> - and searching for "ruby IDE" offers more.</p>
<blockquote>
<p>I complete a large script</p>
</blockquote>
<p>That's what caught my eye: "complete", to me, means "done", "finished", "released". Whether or not you write tests before writing the functions that pass them, or whether or not you write tests at all (and I recommend that you do) you should not be writing code that can't be run (which is a test in itself) until it's become large. Ruby and Python offer a multitude of ways to write small, individually-testable (or executable) pieces of code, so that you don't have to wait for (?) days before you can run the thing.</p>
<p>I'm building a (Ruby) database translation/transformation script at the moment - it's up to about 1000 lines and still not done. I seldom go more than 5 minutes without running it, or at least running the part on which I'm working. When it breaks (I'm not perfect, it breaks a lot ;-p) I know where the problem must be - in the code I wrote in the last 5 minutes. Progress is pretty fast.</p>
<p>I'm not asserting that IDEs/debuggers have no place: some problems don't surface until a large body of code is released: it can be really useful on occasion to drop the whole thing into a debugging environment to find out what is going on. When third-party libraries and frameworks are involved it can be extremely useful to debug into their code to locate problems (which are usually - but not always - related to faulty understanding of the library function).</p>
| 0 | 2009-10-07T08:38:02Z | [
"python",
"ruby",
"scripting-language"
] |
Debugging a scripting language like ruby | 1,529,896 | <p>I am basically from the world of C language programming, now delving into the world of scripting languages like Ruby and Python.</p>
<p>I am wondering how to do debugging.
At present the steps I follow is, </p>
<ul>
<li>I complete a large script,</li>
<li>Comment everything but the portion I
want to check</li>
<li>Execute the script</li>
</ul>
<p>Though it works, I am not able to debug like how I would do in, say, a VC++ environment or something like that.</p>
<p>My question is, is there any better way of debugging?</p>
<p>Note: I guess it may be a repeated question, if so, please point me to the answer.</p>
| 6 | 2009-10-07T06:41:49Z | 1,530,557 | <p>You can debug your Python scripts using the included pdb module. If you want a visual debugger, you can download <a href="http://winpdb.org/" rel="nofollow">winpdb</a> - don't be put off by that "win" prefix, winpdb is cross-platform.</p>
| 0 | 2009-10-07T09:39:48Z | [
"python",
"ruby",
"scripting-language"
] |
Debugging a scripting language like ruby | 1,529,896 | <p>I am basically from the world of C language programming, now delving into the world of scripting languages like Ruby and Python.</p>
<p>I am wondering how to do debugging.
At present the steps I follow is, </p>
<ul>
<li>I complete a large script,</li>
<li>Comment everything but the portion I
want to check</li>
<li>Execute the script</li>
</ul>
<p>Though it works, I am not able to debug like how I would do in, say, a VC++ environment or something like that.</p>
<p>My question is, is there any better way of debugging?</p>
<p>Note: I guess it may be a repeated question, if so, please point me to the answer.</p>
| 6 | 2009-10-07T06:41:49Z | 1,530,723 | <p>My question is, is there any better way of debugging?"</p>
<p>Yes.</p>
<p>Your approach, "1. I complete a large script, 2. Comment everything but the portion I want to check, 3. Execute the script" is not really the best way to write any software in any language (sorry, but that's the truth.)</p>
<p>Do not write a large anything. Ever.</p>
<p>Do this.</p>
<ol>
<li><p>Decompose your problem into classes of objects.</p></li>
<li><p>For each class, write the class by</p>
<p>2a. Outline the class, focus on the external interface, not the implementation details.</p>
<p>2b. Write tests to prove that interface works.</p>
<p>2c. Run the tests. They'll fail, since you only outlined the class.</p>
<p>2d. Fix the class until it passes the test.</p>
<p>2e. At some points, you'll realize your class designs aren't optimal. Refactor your design, assuring your tests still pass.</p></li>
<li><p>Now, write your final script. It should be short. All the classes have already been tested.</p>
<p>3a. Outline the script. Indeed, you can usually write the script.</p>
<p>3b. Write some test cases that prove the script works.</p>
<p>3c. Runt the tests. They may pass. You're done.</p>
<p>3d. If the tests don't pass, fix things until they do.</p></li>
</ol>
<p>Write many small things. It works out much better in the long run that writing a large thing and commenting parts of it out.</p>
| 2 | 2009-10-07T10:20:23Z | [
"python",
"ruby",
"scripting-language"
] |
Debugging a scripting language like ruby | 1,529,896 | <p>I am basically from the world of C language programming, now delving into the world of scripting languages like Ruby and Python.</p>
<p>I am wondering how to do debugging.
At present the steps I follow is, </p>
<ul>
<li>I complete a large script,</li>
<li>Comment everything but the portion I
want to check</li>
<li>Execute the script</li>
</ul>
<p>Though it works, I am not able to debug like how I would do in, say, a VC++ environment or something like that.</p>
<p>My question is, is there any better way of debugging?</p>
<p>Note: I guess it may be a repeated question, if so, please point me to the answer.</p>
| 6 | 2009-10-07T06:41:49Z | 1,531,112 | <p>The debugging method you described is perfect for a static language like C++, but given that the language is so different, the coding methods are similarly different. One of the big very important things in a dynamic language such as Python or Ruby is the interactive toplevel (what you get by typing, say <code>python</code> on the command line). This means that running a part of your program is very easy.</p>
<p>Even if you've written a large program before testing (which is a bad idea), it is hopefully separated into many functions. So, open up your interactive toplevel, do an <code>import thing</code> (for whatever <code>thing</code> happens to be) and then you can easily start testing your functions one by one, just calling them on the toplevel.</p>
<p>Of course, for a more mature project, you probably want to write out an actual test suite, and most languages have a method to do that (in Python, this is <code>doctest</code> and <code>nose</code>, don't know about other languages). At first, though, when you're writing something not particularly formal, just remember a few simple rules of debugging dynamic languages:</p>
<ul>
<li>Start small. Don't write large programs and test them. Test each function as you write it, at least cursorily.</li>
<li>Use the toplevel. Running small pieces of code in a language like Python is extremely lightweight: fire up the toplevel and run it. Compare with writing a complete program and the compile-running it in, say, C++. Use that fact that you can quickly change the correctness of any function.</li>
<li>Debuggers are handy. But often, so are <code>print</code> statements. If you're only running a single function, debugging with <code>print</code> statements isn't that inconvenient, and also frees you from dragging along an IDE.</li>
</ul>
| 0 | 2009-10-07T11:43:16Z | [
"python",
"ruby",
"scripting-language"
] |
Debugging a scripting language like ruby | 1,529,896 | <p>I am basically from the world of C language programming, now delving into the world of scripting languages like Ruby and Python.</p>
<p>I am wondering how to do debugging.
At present the steps I follow is, </p>
<ul>
<li>I complete a large script,</li>
<li>Comment everything but the portion I
want to check</li>
<li>Execute the script</li>
</ul>
<p>Though it works, I am not able to debug like how I would do in, say, a VC++ environment or something like that.</p>
<p>My question is, is there any better way of debugging?</p>
<p>Note: I guess it may be a repeated question, if so, please point me to the answer.</p>
| 6 | 2009-10-07T06:41:49Z | 1,533,469 | <p>There's a lot of good advice here, i recommend going through some best practices:</p>
<p><a href="http://github.com/edgecase/ruby%5Fkoans" rel="nofollow">http://github.com/edgecase/ruby%5Fkoans</a></p>
<p><a href="http://blog.rubybestpractices.com/" rel="nofollow">http://blog.rubybestpractices.com/</a></p>
<p><a href="http://on-ruby.blogspot.com/2009/01/ruby-best-practices-mini-interview-2.html" rel="nofollow">http://on-ruby.blogspot.com/2009/01/ruby-best-practices-mini-interview-2.html</a></p>
<p>(and read Greg Brown's book, it's superb)</p>
<p><hr /></p>
<p>You talk about large scripts. A lot of my workflow is working out logic in irb or the python shell, then capturing them into a cascade of small, single-task focused methods, with appropriate tests (not 100% coverage, more focus on edge and corner cases).</p>
<p><a href="http://binstock.blogspot.com/2008/04/perfecting-oos-small-classes-and-short.html" rel="nofollow">http://binstock.blogspot.com/2008/04/perfecting-oos-small-classes-and-short.html</a></p>
| 1 | 2009-10-07T18:47:44Z | [
"python",
"ruby",
"scripting-language"
] |
Ruby methods equivalent of "if a in list" in python? | 1,529,986 | <p>In python I can use this to check if the element in list <code>a</code>:</p>
<pre><code>>>> a = range(10)
>>> 5 in a
True
>>> 16 in a
False
</code></pre>
<p>How this can be done in Ruby?</p>
| 16 | 2009-10-07T07:05:15Z | 1,529,991 | <p>Use the <code><a href="http://www.ruby-doc.org/docs/ProgrammingRuby/html/ref%5Fc%5Farray.html#Array.include%5Fqm">include?()</a></code> method:</p>
<pre><code>(1..10).include?(5) #=>true
(1..10).include?(16) #=>false
</code></pre>
<p>EDIT:
<code>(1..10)</code> is <a href="http://ruby-doc.org/core/classes/Range.html">Range</a> in Ruby , in the case you want an Array(list) :</p>
<pre><code>(1..10).to_a #=> [1,2,3,4,5,6,7,8,9,10]
</code></pre>
| 25 | 2009-10-07T07:07:30Z | [
"python",
"ruby",
"syntax"
] |
Ruby methods equivalent of "if a in list" in python? | 1,529,986 | <p>In python I can use this to check if the element in list <code>a</code>:</p>
<pre><code>>>> a = range(10)
>>> 5 in a
True
>>> 16 in a
False
</code></pre>
<p>How this can be done in Ruby?</p>
| 16 | 2009-10-07T07:05:15Z | 1,530,866 | <p>Range has the === method, which checks whether the argument is part of the range.</p>
<p>You use it like this:</p>
<pre><code>(1..10) === 5 #=> true
(1..10) === 15 #=> false
</code></pre>
<p>or as you wrote it:</p>
<pre><code>a= (1..10)
a === 5 #=> true
a === 16 #=> false
</code></pre>
<p>You must be sure the values of the range and the value you are testing are of compatible type, otherwise an Exception will be thrown.</p>
<pre><code>(2.718..3.141) === 3 #=> true
(23..42) === "foo" # raises exception
</code></pre>
<ul>
<li>This is done in O(1), as Range#===(value) only compares value with Range#first and Range#last.</li>
<li>If you first call Range#to_a and then Array#include?, it runs in O(n), as Range#to_a, needs to fill an array with n elements, and Array#include? needs to search through the n elements again.</li>
</ul>
<p>If you want to see the difference, open irb and type:</p>
<pre><code>(1..10**9) === 5 #=> true
(1..10**9).to_a.include?(5) # wait some time until your computer is out of ram and freezess
</code></pre>
| 10 | 2009-10-07T10:50:48Z | [
"python",
"ruby",
"syntax"
] |
Cannot shuffle list in Python | 1,530,161 | <p>This is my list:</p>
<pre><code>biglist = [ {'title':'U2','link':'u2.com'}, {'title':'beatles','link':'beatles.com'} ]
print random.shuffle(biglist)
</code></pre>
<p>that doesn't work! It returns none.</p>
| 3 | 2009-10-07T07:53:55Z | 1,530,164 | <p><code>random.shuffle</code> shuffles the list, it does not return a new list. So check <code>biglist</code>, not the result of <code>random.shuffle</code>.</p>
<p>Documentation for the <code>random</code> module: <a href="http://docs.python.org/library/random.html">http://docs.python.org/library/random.html</a></p>
| 16 | 2009-10-07T07:55:35Z | [
"python",
"list",
"random"
] |
In Django, the HTML code is shown instead of the actual text | 1,530,178 | <p>& g t ; Welcome</p>
<p>How do I show the actual symbol instead? Is it a template filter?</p>
<p>Thanks.</p>
| 1 | 2009-10-07T08:02:01Z | 1,530,196 | <p>Bit hard to know without more details. If it's from data that you're passing in from the view, you might want to use <code>mark_safe</code>.</p>
<pre><code>from django.utils.safestring import mark_safe
def your_view(request):
...
foo = '&gt;'
mark_safe(foo)
...
</code></pre>
<p>Otherwise, you want the <a href="http://docs.djangoproject.com/en/dev/ref/templates/builtins/#safe" rel="nofollow"><code>safe</code></a> filter:</p>
<pre><code>{{ myvar|safe }}
</code></pre>
<p>Obviously, be careful with this, make sure the variable <em>actually is safe</em>, otherwise you'll open yourself up to cross-site scripting attacks and the like. There's a reason Django escapes this stuff.</p>
| 5 | 2009-10-07T08:07:35Z | [
"python",
"django"
] |
I heard that Python has automated "garbage collection" , but C++ does not. What does that mean? | 1,530,245 | <p>I heard that Python has automated "garbage collection" , but C++ does not. What does that mean?</p>
| 2 | 2009-10-07T08:21:31Z | 1,530,257 | <p>Try <a href="http://en.wikipedia.org/wiki/Garbage%5Fcollection%5F%28computer%5Fscience%29">reading</a> up on it.</p>
| 12 | 2009-10-07T08:23:19Z | [
"c++",
"python",
"garbage-collection"
] |
I heard that Python has automated "garbage collection" , but C++ does not. What does that mean? | 1,530,245 | <p>I heard that Python has automated "garbage collection" , but C++ does not. What does that mean?</p>
| 2 | 2009-10-07T08:21:31Z | 1,530,262 | <p>That means that python user doesn't need to clean his dynamic created objects, like you're obligated to do it in C/C++.</p>
<p>Example in C++:</p>
<pre><code>char *ch = new char[100];
ch[0]='a';
ch[1]='b';
//....
// somewhere else in your program you need to release the alocated memory.
delete [] ch;
// use *delete ch;* if you've initialized *ch with new char;
</code></pre>
<p>in python:</p>
<pre><code>def fun():
a=[1, 2] #dynamic allocation
a.append(3)
return a[0]
</code></pre>
<p>python takes care about "a" object by itself.</p>
| 8 | 2009-10-07T08:24:03Z | [
"c++",
"python",
"garbage-collection"
] |
I heard that Python has automated "garbage collection" , but C++ does not. What does that mean? | 1,530,245 | <p>I heard that Python has automated "garbage collection" , but C++ does not. What does that mean?</p>
| 2 | 2009-10-07T08:21:31Z | 1,530,267 | <p>It basically means the way they handle memory resources. When you need memory you usually ask for it to the OS and then return it back.</p>
<p>With python you don't need to worry about returning it, with C++ you need to track what you asked and return it back, one is easier, the other performant, you choose your tool.</p>
| 2 | 2009-10-07T08:24:56Z | [
"c++",
"python",
"garbage-collection"
] |
I heard that Python has automated "garbage collection" , but C++ does not. What does that mean? | 1,530,245 | <p>I heard that Python has automated "garbage collection" , but C++ does not. What does that mean?</p>
| 2 | 2009-10-07T08:21:31Z | 1,530,291 | <p>From Wikipedia <a href="http://en.wikipedia.org/wiki/Garbage%5Fcollection%5F%28computer%5Fscience%29" rel="nofollow">http://en.wikipedia.org/wiki/Garbage_collection_%28computer_science%29</a>:</p>
<p>...</p>
<p><em>Garbage collection frees the programmer from manually dealing with memory allocation and deallocation. As a result, certain categories of bugs are eliminated or substantially reduced:</em></p>
<ul>
<li><p><em>Dangling pointer bugs, which occur
when a piece of memory is freed while
there are still pointers to it, and
one of those pointers is used.</em></p></li>
<li><p><em>Double free bugs, which occur when
the program attempts to free a<br />
region of memory that is already<br />
free.</em></p></li>
<li><p><em>Certain kinds of memory leaks, in
which a program fails to free<br />
memory that is no longer referenced<br />
by any variable, leading, over time,</em>
to memory exhaustion.</p></li>
</ul>
<p>...</p>
<p><em>The basic principles of garbage collection are:</em></p>
<ol>
<li><em>Find data objects in a program that cannot be accessed in the future</em></li>
<li><em>Reclaim the resources used by those objects</em></li>
</ol>
| 4 | 2009-10-07T08:33:27Z | [
"c++",
"python",
"garbage-collection"
] |
I heard that Python has automated "garbage collection" , but C++ does not. What does that mean? | 1,530,245 | <p>I heard that Python has automated "garbage collection" , but C++ does not. What does that mean?</p>
| 2 | 2009-10-07T08:21:31Z | 1,530,379 | <p>Others already answered the main question, but I'd like to add that garbage collection is possible in C++. It's not that automatic like Python's, but it's doable.</p>
<p>Smart pointers are probably the simplest form of C++ garbage collecting - <a href="http://www.cplusplus.com/reference/std/memory/auto%5Fptr/" rel="nofollow"><code>std::auto_ptr</code></a>, <a href="http://www.boost.org/doc/libs/1%5F40%5F0/libs/smart%5Fptr/scoped%5Fptr.htm" rel="nofollow"><code>boost::scoped_ptr</code></a>, <a href="http://www.boost.org/doc/libs/1%5F40%5F0/libs/smart%5Fptr/scoped%5Farray.htm" rel="nofollow"><code>boost::scoped_array</code></a> that release memory after being destroyed. There's an example in one of the earlier answers, that could be rewritten as:</p>
<pre><code>boost::scoped_array<char> ch(new char[100]);
ch[0] = 'a';
ch[1] = 'b';
// ...
// boost::scoped_array will be destroyed when out of scope, or during unwind
// (i.e. when exception is thrown), releasing the array's memory
</code></pre>
<p>There are also <a href="http://www.boost.org/doc/libs/1%5F40%5F0/libs/smart%5Fptr/shared%5Fptr.htm" rel="nofollow"><code>boost::shared_ptr</code></a>, <a href="http://www.boost.org/doc/libs/1%5F40%5F0/libs/smart%5Fptr/shared%5Farray.htm" rel="nofollow"><code>boost::shared_array</code></a> that implement reference counting (like Python). And there are full-blown garbage collectors that are meant to replace standard memory allocators, e.g. <a href="http://www.hpl.hp.com/personal/Hans%5FBoehm/gc/" rel="nofollow">Boehm gc</a>.</p>
| 3 | 2009-10-07T08:56:46Z | [
"c++",
"python",
"garbage-collection"
] |
I heard that Python has automated "garbage collection" , but C++ does not. What does that mean? | 1,530,245 | <p>I heard that Python has automated "garbage collection" , but C++ does not. What does that mean?</p>
| 2 | 2009-10-07T08:21:31Z | 1,532,646 | <p>As you have got your answer, now it's better to know the cons of automated garbage collection:
it requires large amounts of extra memory and not suitable for hard real-time deadline applications.</p>
| 0 | 2009-10-07T16:15:44Z | [
"c++",
"python",
"garbage-collection"
] |
How do I change my float into a two decimal number with a comma as a decimal point separator in python? | 1,530,430 | <p>I have a float: 1.2333333</p>
<p>How do I change it into a two decimal number with a comma as a decimal point separator, eg 1,23?</p>
| 6 | 2009-10-07T09:06:12Z | 1,530,440 | <p>To get two decimals, use</p>
<pre><code>'%.2f' % 1.2333333
</code></pre>
<p>To get a comma, use <code>replace()</code>:</p>
<pre><code>('%.2f' % 1.2333333).replace('.', ',')
</code></pre>
<p>A second option would be to <a href="http://docs.python.org/library/locale.html" rel="nofollow">change the locale</a> to some place which uses a comma and then use <code>locale.format()</code>:</p>
<pre><code>locale.setlocale(locale.LC_ALL, 'FR')
locale.format('%.2f', 1.2333333)
</code></pre>
| 4 | 2009-10-07T09:09:49Z | [
"python",
"floating-point",
"decimal"
] |
How do I change my float into a two decimal number with a comma as a decimal point separator in python? | 1,530,430 | <p>I have a float: 1.2333333</p>
<p>How do I change it into a two decimal number with a comma as a decimal point separator, eg 1,23?</p>
| 6 | 2009-10-07T09:06:12Z | 1,530,519 | <p>If you don't want to mess with the locale, you can of course do the formatting yourself. This might serve as a starting point:</p>
<pre><code>def formatFloat(value, decimals = 2, sep = ","):
return "%s%s%0*u" % (int(value), sep, decimals, (10 ** decimals) * (value - int(value)))
</code></pre>
<p>Note that this will always truncate the fraction part (i.e. 1.04999 will print as 1,04).</p>
| 0 | 2009-10-07T09:29:11Z | [
"python",
"floating-point",
"decimal"
] |
How do I change my float into a two decimal number with a comma as a decimal point separator in python? | 1,530,430 | <p>I have a float: 1.2333333</p>
<p>How do I change it into a two decimal number with a comma as a decimal point separator, eg 1,23?</p>
| 6 | 2009-10-07T09:06:12Z | 1,530,644 | <p>The <a href="http://docs.python.org/library/locale.html">locale module</a> can help you with reading and writing numbers in the locale's format.</p>
<pre><code>>>> import locale
>>> locale.setlocale(locale.LC_ALL, "")
'sv_SE.UTF-8'
>>> locale.format("%f", 2.2)
'2,200000'
>>> locale.format("%g", 2.2)
'2,2'
>>> locale.atof("3,1415926")
3.1415926000000001
</code></pre>
| 7 | 2009-10-07T10:03:22Z | [
"python",
"floating-point",
"decimal"
] |
How to clear cookies using python 2.6.x cookielib | 1,530,464 | <p>It seems my previous description was not clear, so rewriting it. </p>
<p>Using python urllib2, I am automating fileupload task in my webapp. And am using Cookielib to store session information, and also I could able to successfully automate the fileupload task. Problem is, when I change the login credentials and did not supply those or supply wrong login credentials to automated python script, it still processing fileupload successfully. In this case, it should actually fail.</p>
<p>All I want is, how to clear the cookielib generated cookies.</p>
<p>Below is the code snippet....</p>
<pre><code>cookies = cookielib.CookieJar()
cookies.clear_session_cookies()
#cookies.clear() tried this as well
opener = urllib2.build_opener(SmartRedirectHandler,HTTPCookieProcessor(cookies),MultipartPostHandler)
urllib2.install_opener(opener)
login_req = urllib2.Request(login_url, login_params)
res = urllib2.urlopen(login_req)
#after login, do fileupload
fileupload_req = urllib2.Request(fileupload_url, params)
response = urllib2.urlopen(import_req)
</code></pre>
<p>I tried using clear() and clear_session_cookies() but still cookies are not cleared. </p>
| 1 | 2009-10-07T09:17:44Z | 1,553,712 | <p>you need to install the opener that you have built, otherwise it will just keep using the default</p>
| 0 | 2009-10-12T10:01:35Z | [
"python",
"cookies"
] |
How to clear cookies using python 2.6.x cookielib | 1,530,464 | <p>It seems my previous description was not clear, so rewriting it. </p>
<p>Using python urllib2, I am automating fileupload task in my webapp. And am using Cookielib to store session information, and also I could able to successfully automate the fileupload task. Problem is, when I change the login credentials and did not supply those or supply wrong login credentials to automated python script, it still processing fileupload successfully. In this case, it should actually fail.</p>
<p>All I want is, how to clear the cookielib generated cookies.</p>
<p>Below is the code snippet....</p>
<pre><code>cookies = cookielib.CookieJar()
cookies.clear_session_cookies()
#cookies.clear() tried this as well
opener = urllib2.build_opener(SmartRedirectHandler,HTTPCookieProcessor(cookies),MultipartPostHandler)
urllib2.install_opener(opener)
login_req = urllib2.Request(login_url, login_params)
res = urllib2.urlopen(login_req)
#after login, do fileupload
fileupload_req = urllib2.Request(fileupload_url, params)
response = urllib2.urlopen(import_req)
</code></pre>
<p>I tried using clear() and clear_session_cookies() but still cookies are not cleared. </p>
| 1 | 2009-10-07T09:17:44Z | 1,587,662 | <p>Instead of relying on cookies, I am restricting page access based response headers. Now, I could able to stop the file upload process when wrong credentials supplied. Thanks guys.</p>
| 0 | 2009-10-19T09:10:55Z | [
"python",
"cookies"
] |
Definition of mathematical operations (sinâ¦) on NumPy arrays containing objects | 1,530,598 | <p>I would like to provide "all" mathematical functions for the number-like objects created by a module (the <a href="http://pypi.python.org/pypi/uncertainties/" rel="nofollow"><code>uncertainties.py</code></a> module, which performs calculations with error propagation)âthese objects are numbers with uncertainties.</p>
<p>What is the best way to do this?</p>
<p>Currently, I redefine most of the functions from <code>math</code> in the module <code>uncertainties.py</code>, so that they work on numbers with uncertainties. One drawback is that users who want to do <code>from math import *</code> must do so <em>after</em> doing <code>import uncertainties</code>.</p>
<p>The interaction with NumPy is, however, restricted to basic operations (an array of numbers with uncertainties can be added, etc.); it does not (yet) include more complex functions (e.g. sin()) that would work on NumPy arrays that contain numbers with uncertainties. The approach I have taken so far consists in suggesting that the user define <code>sin = numpy.vectorize(math.sin)</code>, so that the new <code>math.sin</code> function (which works on numbers with uncertainties) is broadcast to the elements of any Numpy array. One drawback is that this has to be done for each function of interest by the user, which is cumbersome.</p>
<p>So, what is the best way to extend mathematical functions such as <code>sin()</code> so that they work conveniently with simple numbers and NumPy arrays?</p>
<p>The approach chosen by NumPy is to define its own <code>numpy.sin</code>, rather than modifying <code>math.sin</code> so that it works with Numpy arrays. Should I do the same for my <code>uncertainties.py</code> module, and stop redefining <code>math.sin</code>?</p>
<p>Furthermore, what would be the most efficient and correct way of defining <code>sin</code> so that it works both for simple numbers, numbers with uncertainties, and Numpy arrays? My redefined <code>math.sin</code> already handles simple numbers and numbers with uncertainties. However, vectorizing it with <code>numpy.vectorize</code> is likely to be much slower on "regular" NumPy arrays than <code>numpy.sin</code>.</p>
| 1 | 2009-10-07T09:51:46Z | 1,542,399 | <p>It looks like following what NumPy itself does keeps things clean: "extended" mathematical operations (sinâ¦) that work on new objects can be put in a separate name space. Thus, NumPy has <code>numpy.sin</code>, etc. These operations are mostly compatible with those from <code>math</code>, but also work on NumPy arrays.</p>
<p>Therefore, it seems to me that mathematical functions that should work on usual numbers <em>and</em> NumPy arrays <em>and</em> their counterparts with uncertainties are best defined in a separate name space. For instance, the user could do:</p>
<pre><code>from uncertainties import sin
</code></pre>
<p>or</p>
<pre><code>from uncertainties import * # sin, cos, etc.
</code></pre>
<p>For optimization purposes, an alternative might be to provide two distinct sets of mathematical functions: those that generalize functions to simple numbers with uncertainties, and those that generalize them to arrays with uncertainties:</p>
<pre><code>from uncertainties.math_ops import * # Work on scalars and scalars with uncertainty
</code></pre>
<p>or</p>
<pre><code>from uncertainties.numpy_ops import * # Work on everything (scalars, arrays, numbers with uncertainties, arrays with uncertainties)
</code></pre>
| 0 | 2009-10-09T07:46:38Z | [
"python",
"arrays",
"numpy",
"operations"
] |
Don't touch my shebang! | 1,530,702 | <p>One thing I hate about <a href="http://docs.python.org/distutils/"><em>distutils</em></a> (I guess he is the evil who does this) is that it changes the shebang line. In other words, the more rational and environment-vars decided scripture</p>
<pre><code>#!/usr/bin/env python
</code></pre>
<p>gets magically converted into </p>
<pre><code>#!/whatever/absolute/path/is/my/python
</code></pre>
<p>This is seen also with grok: I used grokproject in a virtualenv to start my project, but now I cannot move the development directory around anymore, because it puts absolute paths in the shebang directive.</p>
<p>The reason why I ask this is twofold</p>
<ul>
<li>I want to move it around because I started developing in one directory (Experiments) and now I want to move it into a proper path, but I could not do it. So I created a new virtualenv and grokproject and copied my files. That fixes the issue, but leaves my curiosity for a more rational solution unsatisfied. In particular, if the reference to the virtualenv python interpreter was relative, the problem would not have been present in the first place. You know the layout of the virtualenv, and you can refer to the virtualenv python easily.</li>
<li>The second reason is that I would like to be able to scp the virtualenv to another computer and run it there without trouble. This is not possible if you have hardcoded paths.</li>
</ul>
| 20 | 2009-10-07T10:15:31Z | 1,530,768 | <p>I have no solution to your problem, but I do see some rationale for the current behaviour of <em>distutils</em>.</p>
<p><code>#!/usr/bin/env python</code> executes the system's default Python version. That is fine as long as your code is compatible with said version. When the default version is updated (from 2.5 to 3, say) your code or other Python code which references <code>/usr/bin/env</code> may stop working, even though the old Python version is still installed. For that reason it makes sense to "hardcode" the path to the appropriate python interpreter.</p>
<p><strong>Edit:</strong> you are correct in asserting that specifying <code>python2.4</code> or similar solves this problem.</p>
<p><strong>Edit 2:</strong> things are not as clear cut when multiple installations of the same Python version are present, as <a href="http://stackoverflow.com/users/145403/ned-deily">Ned Deily</a> points out in the comments below.</p>
| 1 | 2009-10-07T10:29:42Z | [
"python",
"distutils",
"virtualenv"
] |
Don't touch my shebang! | 1,530,702 | <p>One thing I hate about <a href="http://docs.python.org/distutils/"><em>distutils</em></a> (I guess he is the evil who does this) is that it changes the shebang line. In other words, the more rational and environment-vars decided scripture</p>
<pre><code>#!/usr/bin/env python
</code></pre>
<p>gets magically converted into </p>
<pre><code>#!/whatever/absolute/path/is/my/python
</code></pre>
<p>This is seen also with grok: I used grokproject in a virtualenv to start my project, but now I cannot move the development directory around anymore, because it puts absolute paths in the shebang directive.</p>
<p>The reason why I ask this is twofold</p>
<ul>
<li>I want to move it around because I started developing in one directory (Experiments) and now I want to move it into a proper path, but I could not do it. So I created a new virtualenv and grokproject and copied my files. That fixes the issue, but leaves my curiosity for a more rational solution unsatisfied. In particular, if the reference to the virtualenv python interpreter was relative, the problem would not have been present in the first place. You know the layout of the virtualenv, and you can refer to the virtualenv python easily.</li>
<li>The second reason is that I would like to be able to scp the virtualenv to another computer and run it there without trouble. This is not possible if you have hardcoded paths.</li>
</ul>
| 20 | 2009-10-07T10:15:31Z | 1,530,808 | <p>Of course you can move the development directory around. Distutils changes the paths to the python that you should run with when you run it. It's in Grok run when you run the buildout. Move and re-run the bootstrap and the buildout. Done!</p>
<p>Distutils changes the path to the Python you use to run distutils with. If it didn't, then you might up installing a library in one python version, but when you try to run the script it would fail, because it would run with another python version that didn't have the library. </p>
<p>That's not insanity, it's in fact the only sane way to do it.</p>
<p>Update:
If you know what you are doing, you can do this:</p>
<pre><code>/path/to/install/python setup.py build -e "/the/path/you/want/python" install
</code></pre>
<p>Make sure you clean the build directory first though. :)</p>
| 13 | 2009-10-07T10:37:09Z | [
"python",
"distutils",
"virtualenv"
] |
Don't touch my shebang! | 1,530,702 | <p>One thing I hate about <a href="http://docs.python.org/distutils/"><em>distutils</em></a> (I guess he is the evil who does this) is that it changes the shebang line. In other words, the more rational and environment-vars decided scripture</p>
<pre><code>#!/usr/bin/env python
</code></pre>
<p>gets magically converted into </p>
<pre><code>#!/whatever/absolute/path/is/my/python
</code></pre>
<p>This is seen also with grok: I used grokproject in a virtualenv to start my project, but now I cannot move the development directory around anymore, because it puts absolute paths in the shebang directive.</p>
<p>The reason why I ask this is twofold</p>
<ul>
<li>I want to move it around because I started developing in one directory (Experiments) and now I want to move it into a proper path, but I could not do it. So I created a new virtualenv and grokproject and copied my files. That fixes the issue, but leaves my curiosity for a more rational solution unsatisfied. In particular, if the reference to the virtualenv python interpreter was relative, the problem would not have been present in the first place. You know the layout of the virtualenv, and you can refer to the virtualenv python easily.</li>
<li>The second reason is that I would like to be able to scp the virtualenv to another computer and run it there without trouble. This is not possible if you have hardcoded paths.</li>
</ul>
| 20 | 2009-10-07T10:15:31Z | 1,719,991 | <p>Distutils will automatically replace the shebang with the location of the Python binary that was used to execute setup.py. To override this behavior you have two options:</p>
<p><strong>Option 1: Manually</strong></p>
<p>You may pass the flag <strong>--executable=/path/to/my/python</strong> to setup.py. Arguments are accepted.</p>
<p>Example:</p>
<pre><code>% python setup.py build --executable=/opt/local/bin/python -d
</code></pre>
<p><strong>Option 2: Automatically</strong></p>
<p>Your other option is to add a line to setup.cfg. If you aren't using setup.cfg, create it in the same directory as setup.py. Setup.py looks for this on startup. Any options specified here can still be overridden with flags at the command-line.</p>
<pre><code>% cat setup.cfg
[build]
executable = /opt/local/bin/python -d
</code></pre>
| 8 | 2009-11-12T05:01:14Z | [
"python",
"distutils",
"virtualenv"
] |
Don't touch my shebang! | 1,530,702 | <p>One thing I hate about <a href="http://docs.python.org/distutils/"><em>distutils</em></a> (I guess he is the evil who does this) is that it changes the shebang line. In other words, the more rational and environment-vars decided scripture</p>
<pre><code>#!/usr/bin/env python
</code></pre>
<p>gets magically converted into </p>
<pre><code>#!/whatever/absolute/path/is/my/python
</code></pre>
<p>This is seen also with grok: I used grokproject in a virtualenv to start my project, but now I cannot move the development directory around anymore, because it puts absolute paths in the shebang directive.</p>
<p>The reason why I ask this is twofold</p>
<ul>
<li>I want to move it around because I started developing in one directory (Experiments) and now I want to move it into a proper path, but I could not do it. So I created a new virtualenv and grokproject and copied my files. That fixes the issue, but leaves my curiosity for a more rational solution unsatisfied. In particular, if the reference to the virtualenv python interpreter was relative, the problem would not have been present in the first place. You know the layout of the virtualenv, and you can refer to the virtualenv python easily.</li>
<li>The second reason is that I would like to be able to scp the virtualenv to another computer and run it there without trouble. This is not possible if you have hardcoded paths.</li>
</ul>
| 20 | 2009-10-07T10:15:31Z | 10,486,563 | <p>In one of the latest versions of <strong>distutils</strong>, there is a flag <strong>--no-autoreq</strong> that have worked for me:</p>
<pre><code>--no-autoreq do not automatically calculate dependencies
</code></pre>
<p>In my case, I was creating RPM files with python2.4 executable, in a server with both 2.4 and 2.6 installations. bdist just left the shebangs as they were, after running:</p>
<pre><code>python setup.py bdist_rpm --no-autoreq
</code></pre>
<p>In the case that you are handling the <strong>spec</strong> files, you may use the solution explained at <a href="http://stackoverflow.com/a/7423994/722997">http://stackoverflow.com/a/7423994/722997</a>, adding:</p>
<pre><code>AutoReq: no
</code></pre>
| 1 | 2012-05-07T17:41:58Z | [
"python",
"distutils",
"virtualenv"
] |
Don't touch my shebang! | 1,530,702 | <p>One thing I hate about <a href="http://docs.python.org/distutils/"><em>distutils</em></a> (I guess he is the evil who does this) is that it changes the shebang line. In other words, the more rational and environment-vars decided scripture</p>
<pre><code>#!/usr/bin/env python
</code></pre>
<p>gets magically converted into </p>
<pre><code>#!/whatever/absolute/path/is/my/python
</code></pre>
<p>This is seen also with grok: I used grokproject in a virtualenv to start my project, but now I cannot move the development directory around anymore, because it puts absolute paths in the shebang directive.</p>
<p>The reason why I ask this is twofold</p>
<ul>
<li>I want to move it around because I started developing in one directory (Experiments) and now I want to move it into a proper path, but I could not do it. So I created a new virtualenv and grokproject and copied my files. That fixes the issue, but leaves my curiosity for a more rational solution unsatisfied. In particular, if the reference to the virtualenv python interpreter was relative, the problem would not have been present in the first place. You know the layout of the virtualenv, and you can refer to the virtualenv python easily.</li>
<li>The second reason is that I would like to be able to scp the virtualenv to another computer and run it there without trouble. This is not possible if you have hardcoded paths.</li>
</ul>
| 20 | 2009-10-07T10:15:31Z | 33,345,596 | <p>had the same issue. tried to find a way to prevent the touching altogether by default. here is the solution. essentially we override the default script copy routine (build_scripts).</p>
<p>in setup.py add</p>
<pre><code>from distutils.command.build_scripts import build_scripts
# don't touch my shebang
class BSCommand (build_scripts):
def run(self):
"""
Copy, chmod each script listed in 'self.scripts'
essentially this is the stripped
distutils.command.build_scripts.copy_scripts()
routine
"""
from stat import ST_MODE
from distutils.dep_util import newer
from distutils import log
self.mkpath(self.build_dir)
outfiles = []
for script in self.scripts:
outfile = os.path.join(self.build_dir, os.path.basename(script))
outfiles.append(outfile)
if not self.force and not newer(script, outfile):
log.debug("not copying %s (up-to-date)", script)
continue
log.info("copying and NOT adjusting %s -> %s", script,
self.build_dir)
self.copy_file(script, outfile)
if os.name == 'posix':
for file in outfiles:
if self.dry_run:
log.info("changing mode of %s", file)
else:
oldmode = os.stat(file)[ST_MODE] & 0o7777
newmode = (oldmode | 0o555) & 0o7777
if newmode != oldmode:
log.info("changing mode of %s from %o to %o",
file, oldmode, newmode)
os.chmod(file, newmode)
setup(name="name",
version=version_string,
description="desc",
...
test_suite='testing',
cmdclass={'build_scripts': BSCommand},
)
</code></pre>
<p>.. ede/duply.net</p>
| 1 | 2015-10-26T12:18:26Z | [
"python",
"distutils",
"virtualenv"
] |
how do I sign data with pyme? | 1,530,797 | <p>I just installed <code>pyme</code> on my ubuntu system. it was easy (thanks apt-get) and I can reproduce the example code (encrypting using a public key in my keyring). now I would like to <em>sign</em> some data and I didn't manage to find any example code nor much documentation.</p>
<p>this is what I've been doing:</p>
<pre><code>>>> plain = pyme.core.Data('this is just some sample text\n')
>>> cipher = pyme.core.Data()
>>> c = pyme.core.Context()
>>> c.set_armor(1)
>>> name='me@office.com'
>>> c.op_keylist_start(name, 0)
>>> r = c.op_keylist_next()
>>> c.op_sign(???)
</code></pre>
<p>I don't know what to give as parameters, the <code>op_sign</code> method tells me </p>
<pre><code>>>> help(c.op_sign)
Help on function _funcwrap in module pyme.util:
_funcwrap(*args, **kwargs)
gpgme_op_sign(ctx, plain, sig, mode) -> gpgme_error_t
</code></pre>
<p>but I do not know how to create such objects.</p>
| 0 | 2009-10-07T10:34:35Z | 1,531,189 | <p>You can follow example from pyme doc and modify it a bit:</p>
<pre><code>import pyme.core
import pyme.pygpgme
plaintext = pyme.core.Data('this is a test message')
ciphertext = pyme.core.Data()
ctx = pyme.core.Context()
ctx.set_armor(1)
name = 'me@office.com'
ctx.op_keylist_start(name, 0)
key = ctx.op_keylist_next()
# first argument is message to sign, second argument is buffer where to write
# the signature, third argument is signing mode, see
# http://www.gnupg.org/documentation/manuals/gpgme/Creating-a-Signature.html#Creating-a-Signature for more details.
ctx.op_sign(plaintext, ciphertext, pyme.pygpgme.GPGME_SIG_MODE_CLEAR)
ciphertext.seek(0, 0)
print ciphertext.read()
</code></pre>
| 0 | 2009-10-07T11:56:06Z | [
"python",
"encryption",
"gnupg",
"gpgme",
"pyme"
] |
Incrementally building a numpy array and measuring memory usage | 1,530,960 | <p>I have a series of large text files (up to 1 gig) that are output from an experiment that need to be analysed in Python. They would be best loaded into a 2D numpy array, which presents the first question:</p>
<ul>
<li>As the number of rows is unknown at the beginning of the loading, how can
a very large numpy array be most efficiently built, row by row?</li>
</ul>
<p>Simply adding the row to the array would be inefficient in memory terms, as two large arrays would momentarily co-exist. The same problem would seem to be occur if you use <code>numpy.append</code>. The <code>stack</code> functions are promising, but ideally I would want to grow the array in place.</p>
<p>This leads to the second question:</p>
<ul>
<li>What is the best way to observe the memory usage of a Python program that heavily
uses numpy arrays?</li>
</ul>
<p>To study the above problem, I've used the usual memory profiling tools - heapy and pympler - but am only getting the size of the outer array objects (80 bytes) and not the data they are containing. Asides from a crude measuring of how much memory the Python process is using, how can I get at the "full" size of the arrays as they grow?</p>
<p>Local details: OSX 10.6, Python 2.6, but general solutions are welcome.</p>
| 11 | 2009-10-07T11:08:36Z | 1,534,233 | <p>There's no way to ensure you can grow the array in place other than creating an empty array (numpy.empty) of the maximum possible size and then using a view of that at the end. You can't start small because there's no guarantee that you can expand whatever memory the map is without clobbering some other data. (And all of this is much lower level than python allows you to get from inside the interpreter.)</p>
<p>Your best bet is probably <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.fromiter.html">numpy.fromiter</a>. Looking at the source, as the number of items increase, the array is expanded by a little over 50% each time. If you can easily get the number of rows (say from counting the lines), you can even pass it a count.</p>
| 7 | 2009-10-07T21:14:40Z | [
"python",
"numpy",
"memory-management"
] |
Incrementally building a numpy array and measuring memory usage | 1,530,960 | <p>I have a series of large text files (up to 1 gig) that are output from an experiment that need to be analysed in Python. They would be best loaded into a 2D numpy array, which presents the first question:</p>
<ul>
<li>As the number of rows is unknown at the beginning of the loading, how can
a very large numpy array be most efficiently built, row by row?</li>
</ul>
<p>Simply adding the row to the array would be inefficient in memory terms, as two large arrays would momentarily co-exist. The same problem would seem to be occur if you use <code>numpy.append</code>. The <code>stack</code> functions are promising, but ideally I would want to grow the array in place.</p>
<p>This leads to the second question:</p>
<ul>
<li>What is the best way to observe the memory usage of a Python program that heavily
uses numpy arrays?</li>
</ul>
<p>To study the above problem, I've used the usual memory profiling tools - heapy and pympler - but am only getting the size of the outer array objects (80 bytes) and not the data they are containing. Asides from a crude measuring of how much memory the Python process is using, how can I get at the "full" size of the arrays as they grow?</p>
<p>Local details: OSX 10.6, Python 2.6, but general solutions are welcome.</p>
| 11 | 2009-10-07T11:08:36Z | 1,534,340 | <p>On possible option is to do a single pass through the file first to count the number of rows, without loading them.</p>
<p>The other option is to double your table size each time, which has two benefits:</p>
<ol>
<li>You will only re-alloc memory log(n) times where n is the number of rows.</li>
<li>You only need 50% more ram than your largest table size</li>
</ol>
<p>If you take the dynamic route, you could measure the length of the first row in bytes, then guess the number of rows by calculating (num bytes in file / num bytes in first row). Start with a table of this size.</p>
| 1 | 2009-10-07T21:32:59Z | [
"python",
"numpy",
"memory-management"
] |
Incrementally building a numpy array and measuring memory usage | 1,530,960 | <p>I have a series of large text files (up to 1 gig) that are output from an experiment that need to be analysed in Python. They would be best loaded into a 2D numpy array, which presents the first question:</p>
<ul>
<li>As the number of rows is unknown at the beginning of the loading, how can
a very large numpy array be most efficiently built, row by row?</li>
</ul>
<p>Simply adding the row to the array would be inefficient in memory terms, as two large arrays would momentarily co-exist. The same problem would seem to be occur if you use <code>numpy.append</code>. The <code>stack</code> functions are promising, but ideally I would want to grow the array in place.</p>
<p>This leads to the second question:</p>
<ul>
<li>What is the best way to observe the memory usage of a Python program that heavily
uses numpy arrays?</li>
</ul>
<p>To study the above problem, I've used the usual memory profiling tools - heapy and pympler - but am only getting the size of the outer array objects (80 bytes) and not the data they are containing. Asides from a crude measuring of how much memory the Python process is using, how can I get at the "full" size of the arrays as they grow?</p>
<p>Local details: OSX 10.6, Python 2.6, but general solutions are welcome.</p>
| 11 | 2009-10-07T11:08:36Z | 4,666,155 | <p>Have you tried using memmap file? You can iterate through your input file (in chunks if possible) and convert the incoming data and insert them as rows into a memory-mapped numpy array. The downside is incurring more disk i/o in case there is insufficient main memory and paging from swap becomes necessary.</p>
<p>See: <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.memmap.html" rel="nofollow">http://docs.scipy.org/doc/numpy/reference/generated/numpy.memmap.html</a></p>
<p>Another alternative is PyTables. You'll need to construct some special sql-like table, but it's fairly simple. In fact, it provides transparent disk persistence (automated serialization) and hierarchical organization for your data. It also limits the amount of main memory used.</p>
<p>See: www.pytables.org/moin/HowToUse</p>
<p>Best of luck!</p>
| 2 | 2011-01-12T07:05:17Z | [
"python",
"numpy",
"memory-management"
] |
Incrementally building a numpy array and measuring memory usage | 1,530,960 | <p>I have a series of large text files (up to 1 gig) that are output from an experiment that need to be analysed in Python. They would be best loaded into a 2D numpy array, which presents the first question:</p>
<ul>
<li>As the number of rows is unknown at the beginning of the loading, how can
a very large numpy array be most efficiently built, row by row?</li>
</ul>
<p>Simply adding the row to the array would be inefficient in memory terms, as two large arrays would momentarily co-exist. The same problem would seem to be occur if you use <code>numpy.append</code>. The <code>stack</code> functions are promising, but ideally I would want to grow the array in place.</p>
<p>This leads to the second question:</p>
<ul>
<li>What is the best way to observe the memory usage of a Python program that heavily
uses numpy arrays?</li>
</ul>
<p>To study the above problem, I've used the usual memory profiling tools - heapy and pympler - but am only getting the size of the outer array objects (80 bytes) and not the data they are containing. Asides from a crude measuring of how much memory the Python process is using, how can I get at the "full" size of the arrays as they grow?</p>
<p>Local details: OSX 10.6, Python 2.6, but general solutions are welcome.</p>
| 11 | 2009-10-07T11:08:36Z | 14,831,202 | <p>The problem is essentially the text file. When your input data is stored in a more advanced from, such problems can be avoided. Take for example a look at the <a href="http://code.google.com/p/h5py/" rel="nofollow">h5py project</a>. It is worth the trouble to first convert your data to HDF5 files and then run analysis scripts on the HDF5 files.</p>
| 0 | 2013-02-12T11:13:06Z | [
"python",
"numpy",
"memory-management"
] |
Django: apply "same parent" constraint to ManyToManyField mapping to self | 1,531,065 | <p>I have a model where tasks are pieces of work that each may depend on some number of other tasks to complete before it can start. Tasks are grouped into jobs, and I want to disallow dependencies between jobs. This is the relevant subset of my model:</p>
<pre><code>class Job(models.Model):
name = models.CharField(max_length=60, unique=True)
class Task(models.Model):
job = models.ForeignKey(Job)
prerequisites = models.ManyToManyField(
'self',
symmetrical=False,
related_name="dependents",
blank=True)
</code></pre>
<p>Is there any way I can express the constraint that all prerequisite tasks must have the same job? I <em>could</em> enforce this at the view level, but I would really like to get it to work at the model level so that the admin interface will display appropriate options when choosing prerequisites for a task. I thought I could use "limit_choices_to", but on closer inspection it seems to require a static query, not something dependent on the values in this task object.</p>
| 3 | 2009-10-07T11:32:11Z | 1,531,900 | <p>There are two separate issues here.</p>
<p>If you want to enforce this constraint at the model level, you might have to define an explicit "through" model and override its save() method (you can't just override Task.save() as that isn't necessarily invoked for adding entries to an M2M). Django 1.2 will have a fuller model validation framework, more like form validation.</p>
<p>If you want only certain choices to appear in the admin, that's a form-level issue. You can dynamically set the queryset attribute of the ModelMultipleChoiceField in a form's <strong>init</strong> method:</p>
<pre><code>class TaskForm(forms.ModelForm):
class Meta:
model = Task
def __init__(self, *args, **kwargs):
super(TaskForm, self).__init__(*args, **kwargs)
self.fields['prerequisites'].queryset = Task.objects.filter(job=self.instance.job)
</code></pre>
<p>You may need to introduce some additional checking here to handle the case of creating a new Task (in that case "self.instance.job" will likely be None); what set of available prerequisites you want there is not clearly defined, since a new Task doesn't yet have a job.</p>
| 3 | 2009-10-07T14:12:45Z | [
"python",
"django",
"orm",
"constraints"
] |
For list unless empty in python | 1,531,402 | <p>I've been writing a lot of constructs like this the past couple of days:</p>
<pre><code>list = get_list()
if list:
for i in list:
pass # do something with the list
else:
pass # do something if the list was empty
</code></pre>
<p>Lot of junk and I assign the list to a real variable (keeping it in memory longer than needed). Python has simplified a lot of my code up til now... Is there a easy way to do this?</p>
<p>(My understanding is that the <code>else</code> in the <code>for: else:</code> construct always triggers after it has looped, empty or not - so not what I want)</p>
| 12 | 2009-10-07T12:43:07Z | 1,531,476 | <pre><code>def do_something_with_maybe_list(maybe_list):
if maybe_list:
for x in list:
do_something(x)
else:
do_something_else()
do_something_with_maybe_list(get_list())
</code></pre>
<p>You could even extract the actions to be done:</p>
<pre><code>def do_something_with_maybe_list(maybe_list, process_item, none_action):
if maybe_list:
for x in list:
process_item(x)
else:
none_action()
do_something_with_maybe_list(get_list(), do_something, do_something_else)
do_something_with_maybe_list(get_otherlist(), do_other, do_still_other)
</code></pre>
<p>Edit from Oli: Or go one further:</p>
<pre><code>def do_something_with_maybe_list(maybe_list, process_item, none_action):
if maybe_list:
return process_list(maybe_list)
return none_action()
do_something_with_maybe_list(get_list(), do_something, do_something_else)
do_something_with_maybe_list(get_otherlist(), do_other, do_still_other)
</code></pre>
| 2 | 2009-10-07T12:56:27Z | [
"for-loop",
"python"
] |
For list unless empty in python | 1,531,402 | <p>I've been writing a lot of constructs like this the past couple of days:</p>
<pre><code>list = get_list()
if list:
for i in list:
pass # do something with the list
else:
pass # do something if the list was empty
</code></pre>
<p>Lot of junk and I assign the list to a real variable (keeping it in memory longer than needed). Python has simplified a lot of my code up til now... Is there a easy way to do this?</p>
<p>(My understanding is that the <code>else</code> in the <code>for: else:</code> construct always triggers after it has looped, empty or not - so not what I want)</p>
| 12 | 2009-10-07T12:43:07Z | 1,531,505 | <p>Slighty more terse is:</p>
<pre><code>for i in my_list:
# got a list
if not my_list:
# not a list
</code></pre>
<p>assuming you are not changing the length of the list in the loop. </p>
<p>Edit from Oli: To compensate my worries of memory use, it would want <code>with</code>ing:</p>
<pre><code>with get_list() as my_list:
for i in my_list:
# got a list
if not my_list:
# not a list
</code></pre>
<p>But yes, that's quite a simple way around the issue.</p>
| 4 | 2009-10-07T13:02:12Z | [
"for-loop",
"python"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.