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
list |
|---|---|---|---|---|---|---|---|---|---|
How can I strip Python logging calls without commenting them out?
| 522,730
|
<p>Today I was thinking about a Python project I wrote about a year back where I used <code>logging</code> pretty extensively. I remember having to comment out a lot of logging calls in inner-loop-like scenarios (the 90% code) because of the overhead (<code>hotshot</code> indicated it was one of my biggest bottlenecks).</p>
<p>I wonder now if there's some canonical way to programmatically strip out logging calls in Python applications without commenting and uncommenting all the time. I'd think you could use inspection/recompilation or bytecode manipulation to do something like this and <strong>target only the code objects that are causing bottlenecks</strong>. This way, you could add a manipulator as a post-compilation step and use a centralized configuration file, like so:</p>
<pre><code>[Leave ERROR and above]
my_module.SomeClass.method_with_lots_of_warn_calls
[Leave WARN and above]
my_module.SomeOtherClass.method_with_lots_of_info_calls
[Leave INFO and above]
my_module.SomeWeirdClass.method_with_lots_of_debug_calls
</code></pre>
<p>Of course, <strong>you'd want to use it sparingly and probably with per-function granularity</strong> -- only for code objects that have shown <code>logging</code> to be a bottleneck. Anybody know of anything like this?</p>
<p><strong>Note:</strong> There are a few things that make this more difficult to do in a performant manner because of dynamic typing and late binding. For example, any calls to a method named <code>debug</code> may have to be wrapped with an <code>if not isinstance(log, Logger)</code>. In any case, I'm assuming all of the minor details can be overcome, either by a gentleman's agreement or some run-time checking. :-)</p>
| 25
|
2009-02-07T00:08:11Z
| 522,779
|
<p>As an imperfect shortcut, how about mocking out <code>logging</code> in specific modules using something like <a href="http://pypi.python.org/pypi/MiniMock/" rel="nofollow">MiniMock</a>?</p>
<p>For example, if <code>my_module.py</code> was:</p>
<pre><code>import logging
class C(object):
def __init__(self, *args, **kw):
logging.info("Instantiating")
</code></pre>
<p>You would replace your use of <code>my_module</code> with:</p>
<pre><code>from minimock import Mock
import my_module
my_module.logging = Mock('logging')
c = my_module.C()
</code></pre>
<p>You'd only have to do this once, before the initial import of the module.</p>
<p>Getting the level specific behaviour would be simple enough by mocking specific methods, or having <code>logging.getLogger</code> return a mock object with some methods impotent and others delegating to the real <code>logging</code> module.</p>
<p>In practice, you'd probably want to replace MiniMock with something simpler and faster; at the very least something which doesn't print usage to stdout! Of course, this doesn't handle the problem of module A importing <code>logging</code> from module B (and hence A also importing the log granularity of B)...</p>
<p>This will never be as fast as not running the log statements at all, but should be much faster than going all the way into the depths of the logging module only to discover this record shouldn't be logged after all.</p>
| 2
|
2009-02-07T00:27:15Z
|
[
"python",
"optimization",
"logging",
"bytecode"
] |
How can I strip Python logging calls without commenting them out?
| 522,730
|
<p>Today I was thinking about a Python project I wrote about a year back where I used <code>logging</code> pretty extensively. I remember having to comment out a lot of logging calls in inner-loop-like scenarios (the 90% code) because of the overhead (<code>hotshot</code> indicated it was one of my biggest bottlenecks).</p>
<p>I wonder now if there's some canonical way to programmatically strip out logging calls in Python applications without commenting and uncommenting all the time. I'd think you could use inspection/recompilation or bytecode manipulation to do something like this and <strong>target only the code objects that are causing bottlenecks</strong>. This way, you could add a manipulator as a post-compilation step and use a centralized configuration file, like so:</p>
<pre><code>[Leave ERROR and above]
my_module.SomeClass.method_with_lots_of_warn_calls
[Leave WARN and above]
my_module.SomeOtherClass.method_with_lots_of_info_calls
[Leave INFO and above]
my_module.SomeWeirdClass.method_with_lots_of_debug_calls
</code></pre>
<p>Of course, <strong>you'd want to use it sparingly and probably with per-function granularity</strong> -- only for code objects that have shown <code>logging</code> to be a bottleneck. Anybody know of anything like this?</p>
<p><strong>Note:</strong> There are a few things that make this more difficult to do in a performant manner because of dynamic typing and late binding. For example, any calls to a method named <code>debug</code> may have to be wrapped with an <code>if not isinstance(log, Logger)</code>. In any case, I'm assuming all of the minor details can be overcome, either by a gentleman's agreement or some run-time checking. :-)</p>
| 25
|
2009-02-07T00:08:11Z
| 522,899
|
<p>You could try something like this:</p>
<pre><code># Create something that accepts anything
class Fake(object):
def __getattr__(self, key):
return self
def __call__(self, *args, **kwargs):
return True
# Replace the logging module
import sys
sys.modules["logging"] = Fake()
</code></pre>
<p>It essentially replaces (or initially fills in) the space for the logging module with an instance of <code>Fake</code> which simply takes in anything. You must run the above code (just once!) before the logging module is attempted to be used anywhere. <em>Here is a test:</em></p>
<pre><code>import logging
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(levelname)-8s %(message)s',
datefmt='%a, %d %b %Y %H:%M:%S',
filename='/temp/myapp.log',
filemode='w')
logging.debug('A debug message')
logging.info('Some information')
logging.warning('A shot across the bows')
</code></pre>
<p>With the above, nothing at all was logged, as was to be expected.</p>
| 1
|
2009-02-07T01:30:41Z
|
[
"python",
"optimization",
"logging",
"bytecode"
] |
How can I strip Python logging calls without commenting them out?
| 522,730
|
<p>Today I was thinking about a Python project I wrote about a year back where I used <code>logging</code> pretty extensively. I remember having to comment out a lot of logging calls in inner-loop-like scenarios (the 90% code) because of the overhead (<code>hotshot</code> indicated it was one of my biggest bottlenecks).</p>
<p>I wonder now if there's some canonical way to programmatically strip out logging calls in Python applications without commenting and uncommenting all the time. I'd think you could use inspection/recompilation or bytecode manipulation to do something like this and <strong>target only the code objects that are causing bottlenecks</strong>. This way, you could add a manipulator as a post-compilation step and use a centralized configuration file, like so:</p>
<pre><code>[Leave ERROR and above]
my_module.SomeClass.method_with_lots_of_warn_calls
[Leave WARN and above]
my_module.SomeOtherClass.method_with_lots_of_info_calls
[Leave INFO and above]
my_module.SomeWeirdClass.method_with_lots_of_debug_calls
</code></pre>
<p>Of course, <strong>you'd want to use it sparingly and probably with per-function granularity</strong> -- only for code objects that have shown <code>logging</code> to be a bottleneck. Anybody know of anything like this?</p>
<p><strong>Note:</strong> There are a few things that make this more difficult to do in a performant manner because of dynamic typing and late binding. For example, any calls to a method named <code>debug</code> may have to be wrapped with an <code>if not isinstance(log, Logger)</code>. In any case, I'm assuming all of the minor details can be overcome, either by a gentleman's agreement or some run-time checking. :-)</p>
| 25
|
2009-02-07T00:08:11Z
| 524,226
|
<p>I'd use some fancy logging decorator, or a bunch of them:</p>
<pre><code>def doLogging(logTreshold):
def logFunction(aFunc):
def innerFunc(*args, **kwargs):
if LOGLEVEL >= logTreshold:
print ">>Called %s at %s"%(aFunc.__name__, time.strftime("%H:%M:%S"))
print ">>Parameters: ", args, kwargs if kwargs else ""
try:
return aFunc(*args, **kwargs)
finally:
print ">>%s took %s"%(aFunc.__name__, time.strftime("%H:%M:%S"))
return innerFunc
return logFunction
</code></pre>
<p>All you need is to declare LOGLEVEL constant in each module (or just globally and just import it in all modules) and then you can use it like this:</p>
<pre><code>@doLogging(2.5)
def myPreciousFunction(one, two, three=4):
print "I'm doing some fancy computations :-)"
return
</code></pre>
<p>And if LOGLEVEL is no less than 2.5 you'll get output like this: </p>
<pre><code>>>Called myPreciousFunction at 18:49:13
>>Parameters: (1, 2)
I'm doing some fancy computations :-)
>>myPreciousFunction took 18:49:13
</code></pre>
<p>As you can see, some work is needed for better handling of kwargs, so the default values will be printed if they are present, but that's another question.</p>
<p>You should probably use some <strong><code>logger</code></strong> module instead of raw <strong><code>print</code></strong> statements, but I wanted to focus on the decorator idea and avoid making code too long.</p>
<p>Anyway - with such decorator you get function-level logging, arbitrarily many log levels, ease of application to new function, and to disable logging you only need to set LOGLEVEL. And you can define different output streams/files for each function if you wish. You can write doLogging as:</p>
<pre><code> def doLogging(logThreshold, outStream=sys.stdout):
.....
print >>outStream, ">>Called %s at %s" etc.
</code></pre>
<p>And utilize log files defined on a per-function basis.</p>
| 1
|
2009-02-07T17:59:32Z
|
[
"python",
"optimization",
"logging",
"bytecode"
] |
How can I strip Python logging calls without commenting them out?
| 522,730
|
<p>Today I was thinking about a Python project I wrote about a year back where I used <code>logging</code> pretty extensively. I remember having to comment out a lot of logging calls in inner-loop-like scenarios (the 90% code) because of the overhead (<code>hotshot</code> indicated it was one of my biggest bottlenecks).</p>
<p>I wonder now if there's some canonical way to programmatically strip out logging calls in Python applications without commenting and uncommenting all the time. I'd think you could use inspection/recompilation or bytecode manipulation to do something like this and <strong>target only the code objects that are causing bottlenecks</strong>. This way, you could add a manipulator as a post-compilation step and use a centralized configuration file, like so:</p>
<pre><code>[Leave ERROR and above]
my_module.SomeClass.method_with_lots_of_warn_calls
[Leave WARN and above]
my_module.SomeOtherClass.method_with_lots_of_info_calls
[Leave INFO and above]
my_module.SomeWeirdClass.method_with_lots_of_debug_calls
</code></pre>
<p>Of course, <strong>you'd want to use it sparingly and probably with per-function granularity</strong> -- only for code objects that have shown <code>logging</code> to be a bottleneck. Anybody know of anything like this?</p>
<p><strong>Note:</strong> There are a few things that make this more difficult to do in a performant manner because of dynamic typing and late binding. For example, any calls to a method named <code>debug</code> may have to be wrapped with an <code>if not isinstance(log, Logger)</code>. In any case, I'm assuming all of the minor details can be overcome, either by a gentleman's agreement or some run-time checking. :-)</p>
| 25
|
2009-02-07T00:08:11Z
| 526,078
|
<p>What about using <a href="http://docs.python.org/library/logging.html?highlight=logging#logging.disable">logging.disable</a>?</p>
<p>I've also found I had to use <a href="http://docs.python.org/library/logging.html?highlight=logging#logging.Logger.isEnabledFor">logging.isEnabledFor</a> if the logging message is expensive to create.</p>
| 19
|
2009-02-08T17:33:41Z
|
[
"python",
"optimization",
"logging",
"bytecode"
] |
How can I strip Python logging calls without commenting them out?
| 522,730
|
<p>Today I was thinking about a Python project I wrote about a year back where I used <code>logging</code> pretty extensively. I remember having to comment out a lot of logging calls in inner-loop-like scenarios (the 90% code) because of the overhead (<code>hotshot</code> indicated it was one of my biggest bottlenecks).</p>
<p>I wonder now if there's some canonical way to programmatically strip out logging calls in Python applications without commenting and uncommenting all the time. I'd think you could use inspection/recompilation or bytecode manipulation to do something like this and <strong>target only the code objects that are causing bottlenecks</strong>. This way, you could add a manipulator as a post-compilation step and use a centralized configuration file, like so:</p>
<pre><code>[Leave ERROR and above]
my_module.SomeClass.method_with_lots_of_warn_calls
[Leave WARN and above]
my_module.SomeOtherClass.method_with_lots_of_info_calls
[Leave INFO and above]
my_module.SomeWeirdClass.method_with_lots_of_debug_calls
</code></pre>
<p>Of course, <strong>you'd want to use it sparingly and probably with per-function granularity</strong> -- only for code objects that have shown <code>logging</code> to be a bottleneck. Anybody know of anything like this?</p>
<p><strong>Note:</strong> There are a few things that make this more difficult to do in a performant manner because of dynamic typing and late binding. For example, any calls to a method named <code>debug</code> may have to be wrapped with an <code>if not isinstance(log, Logger)</code>. In any case, I'm assuming all of the minor details can be overcome, either by a gentleman's agreement or some run-time checking. :-)</p>
| 25
|
2009-02-07T00:08:11Z
| 620,732
|
<p>This is an issue in my project as well--logging ends up on profiler reports pretty consistently.</p>
<p>I've used the _ast module before in a fork of PyFlakes (<a href="http://github.com/kevinw/pyflakes" rel="nofollow">http://github.com/kevinw/pyflakes</a>) ... and it is definitely possible to do what you suggest in your question--to inspect and inject guards before calls to logging methods (with your acknowledged caveat that you'd have to do some runtime type checking). See <a href="http://pyside.blogspot.com/2008/03/ast-compilation-from-python.html" rel="nofollow">http://pyside.blogspot.com/2008/03/ast-compilation-from-python.html</a> for a simple example.</p>
<p><strong>Edit:</strong> I just noticed <a href="http://blog.pythonisito.com/2009/03/announcing-metapython-macros-for-python.html" rel="nofollow">MetaPython</a> on my planetpython.org feed--the example use case is removing log statements at import time.</p>
<p>Maybe the best solution would be for someone to reimplement logging as a C module, but I wouldn't be the first to jump at such an...opportunity :p</p>
| 1
|
2009-03-06T22:38:39Z
|
[
"python",
"optimization",
"logging",
"bytecode"
] |
How can I strip Python logging calls without commenting them out?
| 522,730
|
<p>Today I was thinking about a Python project I wrote about a year back where I used <code>logging</code> pretty extensively. I remember having to comment out a lot of logging calls in inner-loop-like scenarios (the 90% code) because of the overhead (<code>hotshot</code> indicated it was one of my biggest bottlenecks).</p>
<p>I wonder now if there's some canonical way to programmatically strip out logging calls in Python applications without commenting and uncommenting all the time. I'd think you could use inspection/recompilation or bytecode manipulation to do something like this and <strong>target only the code objects that are causing bottlenecks</strong>. This way, you could add a manipulator as a post-compilation step and use a centralized configuration file, like so:</p>
<pre><code>[Leave ERROR and above]
my_module.SomeClass.method_with_lots_of_warn_calls
[Leave WARN and above]
my_module.SomeOtherClass.method_with_lots_of_info_calls
[Leave INFO and above]
my_module.SomeWeirdClass.method_with_lots_of_debug_calls
</code></pre>
<p>Of course, <strong>you'd want to use it sparingly and probably with per-function granularity</strong> -- only for code objects that have shown <code>logging</code> to be a bottleneck. Anybody know of anything like this?</p>
<p><strong>Note:</strong> There are a few things that make this more difficult to do in a performant manner because of dynamic typing and late binding. For example, any calls to a method named <code>debug</code> may have to be wrapped with an <code>if not isinstance(log, Logger)</code>. In any case, I'm assuming all of the minor details can be overcome, either by a gentleman's agreement or some run-time checking. :-)</p>
| 25
|
2009-02-07T00:08:11Z
| 716,708
|
<p>I've also seen assert used in this fashion.</p>
<pre><code>assert logging.warn('disable me with the -O option') is None
</code></pre>
<p>(I'm guessing that warn always returns none.. if not, you'll get an AssertionError</p>
<p>But really that's just a funny way of doing this:</p>
<pre><code>if __debug__: logging.warn('disable me with the -O option')
</code></pre>
<p>When you run a script with that line in it with the -O option, the line will be removed from the optimized .pyo code. If, instead, you had your own variable, like in the following, you will have a conditional that is always executed (no matter what value the variable is), although a conditional should execute quicker than a function call:</p>
<pre><code>my_debug = True
...
if my_debug: logging.warn('disable me by setting my_debug = False')
</code></pre>
<p>so if my understanding of <strong>debug</strong> is correct, it seems like a nice way to get rid of unnecessary logging calls. The flipside is that it also disables all of your asserts, so it is a problem if you need the asserts.</p>
| 4
|
2009-04-04T07:22:20Z
|
[
"python",
"optimization",
"logging",
"bytecode"
] |
How can I strip Python logging calls without commenting them out?
| 522,730
|
<p>Today I was thinking about a Python project I wrote about a year back where I used <code>logging</code> pretty extensively. I remember having to comment out a lot of logging calls in inner-loop-like scenarios (the 90% code) because of the overhead (<code>hotshot</code> indicated it was one of my biggest bottlenecks).</p>
<p>I wonder now if there's some canonical way to programmatically strip out logging calls in Python applications without commenting and uncommenting all the time. I'd think you could use inspection/recompilation or bytecode manipulation to do something like this and <strong>target only the code objects that are causing bottlenecks</strong>. This way, you could add a manipulator as a post-compilation step and use a centralized configuration file, like so:</p>
<pre><code>[Leave ERROR and above]
my_module.SomeClass.method_with_lots_of_warn_calls
[Leave WARN and above]
my_module.SomeOtherClass.method_with_lots_of_info_calls
[Leave INFO and above]
my_module.SomeWeirdClass.method_with_lots_of_debug_calls
</code></pre>
<p>Of course, <strong>you'd want to use it sparingly and probably with per-function granularity</strong> -- only for code objects that have shown <code>logging</code> to be a bottleneck. Anybody know of anything like this?</p>
<p><strong>Note:</strong> There are a few things that make this more difficult to do in a performant manner because of dynamic typing and late binding. For example, any calls to a method named <code>debug</code> may have to be wrapped with an <code>if not isinstance(log, Logger)</code>. In any case, I'm assuming all of the minor details can be overcome, either by a gentleman's agreement or some run-time checking. :-)</p>
| 25
|
2009-02-07T00:08:11Z
| 2,218,371
|
<p>I like the 'if _<em>debug</em>' solution except that putting it in front of every call is a bit distracting and ugly. I had this same problem and overcame it by writing a script which automatically parses your source files and replaces logging statements with pass statements (and commented out copies of the logging statements). It can also undo this conversion.</p>
<p>I use it when I deploy new code to a production environment when there are lots of logging statements which I don't need in a production setting and they are affecting performance.</p>
<p>You can find the script here: <a href="http://dound.com/2010/02/python-logging-performance/" rel="nofollow">http://dound.com/2010/02/python-logging-performance/</a></p>
| 0
|
2010-02-07T21:16:58Z
|
[
"python",
"optimization",
"logging",
"bytecode"
] |
How can I strip Python logging calls without commenting them out?
| 522,730
|
<p>Today I was thinking about a Python project I wrote about a year back where I used <code>logging</code> pretty extensively. I remember having to comment out a lot of logging calls in inner-loop-like scenarios (the 90% code) because of the overhead (<code>hotshot</code> indicated it was one of my biggest bottlenecks).</p>
<p>I wonder now if there's some canonical way to programmatically strip out logging calls in Python applications without commenting and uncommenting all the time. I'd think you could use inspection/recompilation or bytecode manipulation to do something like this and <strong>target only the code objects that are causing bottlenecks</strong>. This way, you could add a manipulator as a post-compilation step and use a centralized configuration file, like so:</p>
<pre><code>[Leave ERROR and above]
my_module.SomeClass.method_with_lots_of_warn_calls
[Leave WARN and above]
my_module.SomeOtherClass.method_with_lots_of_info_calls
[Leave INFO and above]
my_module.SomeWeirdClass.method_with_lots_of_debug_calls
</code></pre>
<p>Of course, <strong>you'd want to use it sparingly and probably with per-function granularity</strong> -- only for code objects that have shown <code>logging</code> to be a bottleneck. Anybody know of anything like this?</p>
<p><strong>Note:</strong> There are a few things that make this more difficult to do in a performant manner because of dynamic typing and late binding. For example, any calls to a method named <code>debug</code> may have to be wrapped with an <code>if not isinstance(log, Logger)</code>. In any case, I'm assuming all of the minor details can be overcome, either by a gentleman's agreement or some run-time checking. :-)</p>
| 25
|
2009-02-07T00:08:11Z
| 2,807,939
|
<p>:-) We used to call that a preprocessor and although C's preprocessor had some of those capablities, the "king of the hill" was the preprocessor for IBM mainframe PL/I. It provided extensive language support in the preprocessor (full assignments, conditionals, looping, etc.) and it was possible to write "programs that wrote programs" using just the PL/I PP.</p>
<p>I wrote many applications with full-blown sophisticated program and data tracing (we didn't have a decent debugger for a back-end process at that time) for use in development and testing which then, when compiled with the appropriate "runtime flag" simply stripped all the tracing code out cleanly without any performance impact. </p>
<p>I think the decorator idea is a good one. You can write a decorator to wrap the functions that need logging. Then, for runtime distribution, the decorator is turned into a "no-op" which eliminates the debugging statements.</p>
<p>Jon R</p>
| 1
|
2010-05-11T03:43:26Z
|
[
"python",
"optimization",
"logging",
"bytecode"
] |
How can I strip Python logging calls without commenting them out?
| 522,730
|
<p>Today I was thinking about a Python project I wrote about a year back where I used <code>logging</code> pretty extensively. I remember having to comment out a lot of logging calls in inner-loop-like scenarios (the 90% code) because of the overhead (<code>hotshot</code> indicated it was one of my biggest bottlenecks).</p>
<p>I wonder now if there's some canonical way to programmatically strip out logging calls in Python applications without commenting and uncommenting all the time. I'd think you could use inspection/recompilation or bytecode manipulation to do something like this and <strong>target only the code objects that are causing bottlenecks</strong>. This way, you could add a manipulator as a post-compilation step and use a centralized configuration file, like so:</p>
<pre><code>[Leave ERROR and above]
my_module.SomeClass.method_with_lots_of_warn_calls
[Leave WARN and above]
my_module.SomeOtherClass.method_with_lots_of_info_calls
[Leave INFO and above]
my_module.SomeWeirdClass.method_with_lots_of_debug_calls
</code></pre>
<p>Of course, <strong>you'd want to use it sparingly and probably with per-function granularity</strong> -- only for code objects that have shown <code>logging</code> to be a bottleneck. Anybody know of anything like this?</p>
<p><strong>Note:</strong> There are a few things that make this more difficult to do in a performant manner because of dynamic typing and late binding. For example, any calls to a method named <code>debug</code> may have to be wrapped with an <code>if not isinstance(log, Logger)</code>. In any case, I'm assuming all of the minor details can be overcome, either by a gentleman's agreement or some run-time checking. :-)</p>
| 25
|
2009-02-07T00:08:11Z
| 5,320,785
|
<p>Use <a href="http://code.google.com/p/pypreprocessor/" rel="nofollow">pypreprocessor</a></p>
<p>Which can also be found on <a href="http://pypi.python.org/pypi/pypreprocessor" rel="nofollow">PYPI (Python Package Index)</a> and be fetched using pip.</p>
<p>Here's a basic usage example:</p>
<pre><code>from pypreprocessor import pypreprocessor
pypreprocessor.parse()
#define nologging
#ifdef nologging
...logging code you'd usually comment out manually...
#endif
</code></pre>
<p>Essentially, the preprocessor comments out code the way you were doing it manually before. It just does it on the fly conditionally depending on what you define.</p>
<p>You can also remove all of the preprocessor directives and commented out code from the postprocessed code by adding 'pypreprocessor.removeMeta = True' between the import and
parse() statements.</p>
<p>The bytecode output (.pyc) file will contain the optimized output.</p>
<p><em>SideNote: pypreprocessor is compatible with python2x and python3k.</em></p>
<p><em>Disclaimer: I'm the author of pypreprocessor.</em></p>
| 4
|
2011-03-16T03:36:10Z
|
[
"python",
"optimization",
"logging",
"bytecode"
] |
How can I strip Python logging calls without commenting them out?
| 522,730
|
<p>Today I was thinking about a Python project I wrote about a year back where I used <code>logging</code> pretty extensively. I remember having to comment out a lot of logging calls in inner-loop-like scenarios (the 90% code) because of the overhead (<code>hotshot</code> indicated it was one of my biggest bottlenecks).</p>
<p>I wonder now if there's some canonical way to programmatically strip out logging calls in Python applications without commenting and uncommenting all the time. I'd think you could use inspection/recompilation or bytecode manipulation to do something like this and <strong>target only the code objects that are causing bottlenecks</strong>. This way, you could add a manipulator as a post-compilation step and use a centralized configuration file, like so:</p>
<pre><code>[Leave ERROR and above]
my_module.SomeClass.method_with_lots_of_warn_calls
[Leave WARN and above]
my_module.SomeOtherClass.method_with_lots_of_info_calls
[Leave INFO and above]
my_module.SomeWeirdClass.method_with_lots_of_debug_calls
</code></pre>
<p>Of course, <strong>you'd want to use it sparingly and probably with per-function granularity</strong> -- only for code objects that have shown <code>logging</code> to be a bottleneck. Anybody know of anything like this?</p>
<p><strong>Note:</strong> There are a few things that make this more difficult to do in a performant manner because of dynamic typing and late binding. For example, any calls to a method named <code>debug</code> may have to be wrapped with an <code>if not isinstance(log, Logger)</code>. In any case, I'm assuming all of the minor details can be overcome, either by a gentleman's agreement or some run-time checking. :-)</p>
| 25
|
2009-02-07T00:08:11Z
| 24,120,427
|
<p>I am doing a project currently that uses extensive logging for testing logic and execution times for a data analysis API using the Pandas library. </p>
<p>I found this string with a similar concern - e.g. what is the overhead on the logging.debug statements even if the logging.basicConfig level is set to level=logging.WARNING</p>
<p>I have resorted to writing the following script to comment out or uncomment the debug logging prior to deployment:</p>
<pre><code>import os
import fileinput
comment = True
# exclude files or directories matching string
fil_dir_exclude = ["__","_archive",".pyc"]
if comment :
## Variables to comment
source_str = 'logging.debug'
replace_str = '#logging.debug'
else :
## Variables to uncomment
source_str = '#logging.debug'
replace_str = 'logging.debug'
# walk through directories
for root, dirs, files in os.walk('root/directory') :
# where files exist
if files:
# for each file
for file_single in files :
# build full file name
file_name = os.path.join(root,file_single)
# exclude files with matching string
if not any(exclude_str in file_name for exclude_str in fil_dir_exclude) :
# replace string in line
for line in fileinput.input(file_name, inplace=True):
print "%s" % (line.replace(source_str, replace_str)),
</code></pre>
<p>This is a file recursion that excludes files based on a list of criteria and performs an in place replace based on an answer found here: <a href="http://stackoverflow.com/questions/39086/search-and-replace-a-line-in-a-file-in-python">Search and replace a line in a file in Python</a></p>
| 0
|
2014-06-09T12:35:04Z
|
[
"python",
"optimization",
"logging",
"bytecode"
] |
how to search for specific file type with yahoo search API?
| 522,781
|
<p>Does anyone know if there is some parameter available for programmatic search on yahoo allowing to restrict results so only links to files of specific type will be returned (like PDF for example)?
It's possible to do that in GUI, but how to make it happen through API?</p>
<p>I'd very much appreciate a sample code in Python, but any other solutions might be helpful as well.</p>
| 1
|
2009-02-07T00:27:40Z
| 522,787
|
<p>Yes, there is:</p>
<p><a href="http://developer.yahoo.com/search/boss/boss_guide/Web_Search.html#id356163" rel="nofollow">http://developer.yahoo.com/search/boss/boss_guide/Web_Search.html#id356163</a></p>
| 0
|
2009-02-07T00:30:34Z
|
[
"python",
"yahoo-api",
"yahoo-search"
] |
how to search for specific file type with yahoo search API?
| 522,781
|
<p>Does anyone know if there is some parameter available for programmatic search on yahoo allowing to restrict results so only links to files of specific type will be returned (like PDF for example)?
It's possible to do that in GUI, but how to make it happen through API?</p>
<p>I'd very much appreciate a sample code in Python, but any other solutions might be helpful as well.</p>
| 1
|
2009-02-07T00:27:40Z
| 526,491
|
<p>Thank you.
I found myself that something like this works OK (file type is the first argument, and query is the second):</p>
<p>format = sys.argv[1]</p>
<p>query = " ".join(sys.argv[2:])</p>
<p>srch = create_search("Web", app_id, query=query, format=format)</p>
| 0
|
2009-02-08T21:54:07Z
|
[
"python",
"yahoo-api",
"yahoo-search"
] |
how to search for specific file type with yahoo search API?
| 522,781
|
<p>Does anyone know if there is some parameter available for programmatic search on yahoo allowing to restrict results so only links to files of specific type will be returned (like PDF for example)?
It's possible to do that in GUI, but how to make it happen through API?</p>
<p>I'd very much appreciate a sample code in Python, but any other solutions might be helpful as well.</p>
| 1
|
2009-02-07T00:27:40Z
| 1,178,208
|
<p>Here's what I do for this sort of thing. It exposes more of the parameters so you can tune it to your needs. This should print out the first ten PDFs URLs from the query "resume" [mine's not one of them ;) ]. You can download those URLs however you like.</p>
<p>The json dictionary that gets returned from the query is a little gross, but this should get you started. Be aware that in real code you will need to check whether some of the keys in the dictionary exist. When there are no results, this code will probably throw an exception. </p>
<p>The link that Tiago provided is good for knowing what values are supported for the "type" parameter. </p>
<pre><code>from yos.crawl import rest
APPID="XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
base_url = "http://boss.yahooapis.com/ysearch/%s/v%d/%s?start=%d&count=%d&type=%s" + "&appid=" + APPID
querystr="resume"
start=0
count=10
type="pdf"
search_url = base_url % ("web", 1, querystr, start, count, type)
json_result = rest.load_json(search_url)
for url in [recs['url'] for recs in json_result['ysearchresponse']['resultset_web']]:
print url
</code></pre>
| 0
|
2009-07-24T14:52:02Z
|
[
"python",
"yahoo-api",
"yahoo-search"
] |
Python cannot create instances
| 522,921
|
<p>I am trying to create a simple Python extension using [PyCXX]. And I'm compiling against my Python 2.5 installation.</p>
<p>My goal is to be able to do the following in Python:</p>
<pre><code>import Cats
kitty = Cats.Kitty()
if type(kitty) == Cats.Kitty:
kitty.Speak()
</code></pre>
<p>But every time I try, this is the error that I get:</p>
<p><code>TypeError: cannot create 'Kitty' instances</code></p>
<p>It does see <code>Cats.Kitty</code> as a type object, but I can't create instances of the Kitty class, any ideas?</p>
<p>Here is my current source:</p>
<pre><code>#include "CXX/Objects.hxx"
#include "CXX/Extensions.hxx"
#include <iostream>
using namespace Py;
using namespace std;
class Kitty : public Py::PythonExtension<Kitty>
{
public:
Kitty()
{
}
virtual ~Kitty()
{
}
static void init_type(void)
{
behaviors().name("Kitty");
behaviors().supportGetattr();
add_varargs_method("Speak", &Kitty::Speak);
}
virtual Py::Object getattr( const char *name )
{
return getattr_methods( name );
}
Py::Object Speak( const Py::Tuple &args )
{
cout << "Meow!" << endl;
return Py::None();
}
};
class Cats : public ExtensionModule<Cats>
{
public:
Cats()
: ExtensionModule<Cats>("Cats")
{
Kitty::init_type();
initialize();
Dict d(moduleDictionary());
d["Kitty"] = Type((PyObject*)Kitty::type_object());
}
virtual ~Cats()
{
}
Py::Object factory_Kitty( const Py::Tuple &rargs )
{
return Py::asObject( new Kitty );
}
};
void init_Cats()
{
static Cats* cats = new Cats;
}
int main(int argc, char* argv[])
{
Py_Initialize();
init_Cats();
return Py_Main(argc, argv);
return 0;
}
</code></pre>
| 4
|
2009-02-07T01:39:29Z
| 523,041
|
<p>I do'nt see it in the code, but sort of thing normally means it can't create an instance, which means it can't find a ctor. Are you sure you've got a ctor that <em>exactly</em> matches the expected signature?</p>
| 2
|
2009-02-07T03:05:25Z
|
[
"python",
"pycxx"
] |
Python + Django page redirect
| 523,356
|
<p>How do I accomplish a simple redirect (e.g. <code>cflocation</code> in ColdFusion, or <code>header(location:http://)</code> in Django)?</p>
| 131
|
2009-02-07T07:08:03Z
| 523,366
|
<p>It's simple:</p>
<pre><code>from django.http import HttpResponseRedirect
def myview(request):
...
return HttpResponseRedirect("/path/")
</code></pre>
<p>More info in the <a href="https://docs.djangoproject.com/en/1.4/ref/request-response/#django.http.HttpResponseRedirect">official Django docs</a></p>
<p><strong>Update: Django 1.0</strong></p>
<p>There is apparently a better way of doing this in Django now using <code>generic views</code>.</p>
<p>Example -</p>
<pre><code>from django.views.generic.simple import redirect_to
urlpatterns = patterns('',
(r'^one/$', redirect_to, {'url': '/another/'}),
#etc...
)
</code></pre>
<p>There is more in the <a href="https://docs.djangoproject.com/en/1.4/ref/generic-views/#django-views-generic-simple-redirect-to">generic views documentation</a>.
Credit - <a href="http://stackoverflow.com/users/166761/carles-barrobes">Carles Barrobés</a>.</p>
<p><strong>Update #2: Django 1.3+</strong></p>
<p>In Django 1.5 *redirect_to* no longer exists and has been replaced by <a href="https://docs.djangoproject.com/en/1.5/ref/class-based-views/base/#redirectview">RedirectView</a>. Credit to <a href="http://stackoverflow.com/users/221917/yonatan">Yonatan</a></p>
<pre><code>from django.views.generic import RedirectView
urlpatterns = patterns('',
(r'^one/$', RedirectView.as_view(url='/another/')),
)
</code></pre>
| 213
|
2009-02-07T07:14:37Z
|
[
"python",
"django",
"redirect",
"location"
] |
Python + Django page redirect
| 523,356
|
<p>How do I accomplish a simple redirect (e.g. <code>cflocation</code> in ColdFusion, or <code>header(location:http://)</code> in Django)?</p>
| 131
|
2009-02-07T07:08:03Z
| 2,080,377
|
<p>There's actually a simpler way than having a view for each redirect - you can do it <em>directly</em> in <code>urls.py</code>:</p>
<pre><code>from django.http import HttpResponsePermanentRedirect
urlpatterns = patterns(
'',
# ...normal patterns here...
(r'^bad-old-link\.php',
lambda request: HttpResponsePermanentRedirect('/nice-link')),
)
</code></pre>
<p><a href="http://docs.djangoproject.com/en/1.0/topics/http/urls/#passing-callable-objects-instead-of-strings">A target can be a callable as well as a string</a>, which is what I'm using here.</p>
| 37
|
2010-01-17T08:07:32Z
|
[
"python",
"django",
"redirect",
"location"
] |
Python + Django page redirect
| 523,356
|
<p>How do I accomplish a simple redirect (e.g. <code>cflocation</code> in ColdFusion, or <code>header(location:http://)</code> in Django)?</p>
| 131
|
2009-02-07T07:08:03Z
| 3,645,846
|
<p>Since Django 1.1, you can also use the simpler <a href="http://docs.djangoproject.com/en/dev/topics/http/shortcuts/#redirect">redirect</a> shortcut:</p>
<pre><code>from django.shortcuts import redirect
def myview(request):
return redirect('/path')
</code></pre>
<p>It also takes an optional permanent=True keyword argument.</p>
| 22
|
2010-09-05T11:09:03Z
|
[
"python",
"django",
"redirect",
"location"
] |
Python + Django page redirect
| 523,356
|
<p>How do I accomplish a simple redirect (e.g. <code>cflocation</code> in ColdFusion, or <code>header(location:http://)</code> in Django)?</p>
| 131
|
2009-02-07T07:08:03Z
| 3,841,632
|
<p>Depending on what you want (i.e. if you do not want to do any additional pre-processing), it is simpler to just use Django's <code>redirect_to</code> generic view:</p>
<pre><code>from django.views.generic.simple import redirect_to
urlpatterns = patterns('',
(r'^one/$', redirect_to, {'url': '/another/'}),
#etc...
)
</code></pre>
<p>See <a href="https://docs.djangoproject.com/en/1.4/ref/generic-views/#django-views-generic-simple-redirect-to" rel="nofollow">documentation</a> for more advanced examples.</p>
<hr>
<p>For Django 1.3+ use:</p>
<pre><code>from django.views.generic import RedirectView
urlpatterns = patterns('',
(r'^one/$', RedirectView.as_view(url='/another/')),
)
</code></pre>
| 109
|
2010-10-01T17:31:30Z
|
[
"python",
"django",
"redirect",
"location"
] |
Python + Django page redirect
| 523,356
|
<p>How do I accomplish a simple redirect (e.g. <code>cflocation</code> in ColdFusion, or <code>header(location:http://)</code> in Django)?</p>
| 131
|
2009-02-07T07:08:03Z
| 7,416,655
|
<p>With Django version 1.3, the class based approach is:</p>
<pre><code>from django.conf.urls.defaults import patterns, url
from django.views.generic import RedirectView
urlpatterns = patterns('',
url(r'^some-url/$', RedirectView.as_view(url='/redirect-url/'), name='some_redirect'),
)
</code></pre>
<p>This example lives in in urls.py</p>
| 10
|
2011-09-14T12:55:33Z
|
[
"python",
"django",
"redirect",
"location"
] |
Python + Django page redirect
| 523,356
|
<p>How do I accomplish a simple redirect (e.g. <code>cflocation</code> in ColdFusion, or <code>header(location:http://)</code> in Django)?</p>
| 131
|
2009-02-07T07:08:03Z
| 9,368,564
|
<p>You can do this in the Admin section. It's explained in the documentation.</p>
<p><a href="https://docs.djangoproject.com/en/dev/ref/contrib/redirects/" rel="nofollow">https://docs.djangoproject.com/en/dev/ref/contrib/redirects/</a></p>
| 1
|
2012-02-20T21:19:33Z
|
[
"python",
"django",
"redirect",
"location"
] |
Python + Django page redirect
| 523,356
|
<p>How do I accomplish a simple redirect (e.g. <code>cflocation</code> in ColdFusion, or <code>header(location:http://)</code> in Django)?</p>
| 131
|
2009-02-07T07:08:03Z
| 13,243,040
|
<p>Beware. I did this on a development server and wanted to change it later. </p>
<ul>
<li><a href="http://stackoverflow.com/questions/6980192/firefox-5-caching-301-redirects">Firefox 5 'caching' 301 redirects</a></li>
</ul>
<p>I had to clear my caches to change it. In order to avoid this head-scratching in the future, I was able to make it temporary like so:</p>
<pre><code>from django.views.generic import RedirectView
url(r'^source$', RedirectView.as_view(permanent=False,
url='/dest/')),
</code></pre>
| 6
|
2012-11-06T01:18:20Z
|
[
"python",
"django",
"redirect",
"location"
] |
Python + Django page redirect
| 523,356
|
<p>How do I accomplish a simple redirect (e.g. <code>cflocation</code> in ColdFusion, or <code>header(location:http://)</code> in Django)?</p>
| 131
|
2009-02-07T07:08:03Z
| 17,615,240
|
<p>page_path = define in urls.py</p>
<pre><code>def deletePolls(request):
pollId = deletePool(request.GET['id'])
return HttpResponseRedirect("/page_path/")
</code></pre>
| 1
|
2013-07-12T12:45:36Z
|
[
"python",
"django",
"redirect",
"location"
] |
Python + Django page redirect
| 523,356
|
<p>How do I accomplish a simple redirect (e.g. <code>cflocation</code> in ColdFusion, or <code>header(location:http://)</code> in Django)?</p>
| 131
|
2009-02-07T07:08:03Z
| 22,300,866
|
<p>If you want to redirect a whole subfolder, the <code>url</code> argument in <a href="https://docs.djangoproject.com/en/1.8/ref/class-based-views/base/#redirectview" rel="nofollow">RedirectView is actually interpolated</a>, so you can do something like this in <code>urls.py</code>:</p>
<pre><code>from django.conf.urls.defaults import url
from django.views.generic import RedirectView
urlpatterns = [
url(r'^old/(?P<path>.*)$', RedirectView.as_view(url='/new_path/%(path)s')),
]
</code></pre>
<hr>
<p>The <code>?P<path></code> you capture will be fed into <code>RedirectView</code>. This captured variable will then be replaced in the <code>url</code> argument you gave, giving us <code>/new_path/yay/mypath</code> if your original path was <code>/old/yay/mypath</code>.</p>
<p>You can also do <code>...as_view(url='...', query_string=True)</code> if you want to copy the query string over as well.</p>
| 8
|
2014-03-10T13:02:02Z
|
[
"python",
"django",
"redirect",
"location"
] |
Python + Django page redirect
| 523,356
|
<p>How do I accomplish a simple redirect (e.g. <code>cflocation</code> in ColdFusion, or <code>header(location:http://)</code> in Django)?</p>
| 131
|
2009-02-07T07:08:03Z
| 24,191,391
|
<p>This should work in most versions of django, I am using it in 1.6.5:</p>
<pre><code>from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
urlpatterns = patterns('',
....
url(r'^(?P<location_id>\d+)/$', lambda x, location_id: HttpResponseRedirect(reverse('dailyreport_location', args=[location_id])), name='location_stats_redirect'),
....
)
</code></pre>
<p>You can still use the name of the url pattern instead of a hard coded url with this solution. The location_id parameter from the url is passed down to the lambda function.</p>
| 0
|
2014-06-12T18:23:52Z
|
[
"python",
"django",
"redirect",
"location"
] |
How do I layout a 3 pane window using wxPython?
| 523,363
|
<p>I am trying to find a simple way to layout a 3 pane window using wxPython.</p>
<p>I want to have a tree list in the left pane, then have a right pane that is split into two - with an edit component in the top part and a grid component in the bottom part.</p>
<p>Something along the lines of:</p>
<pre>
--------------------------------------
| | |
| | Edit |
| Tree | Control |
| Control | |
| |----------------------|
| | |
| | Grid |
| | |
--------------------------------------
</pre>
<p>I would like the window to be re-sizable and give the user the ability to change the (relative) size of each of the components within the windows by dragging the borders.</p>
<p>I figure that I need some combination of sizers and/or splitter-window components but can't find a decent example of this kind of window in the documentation or on the web. </p>
| 5
|
2009-02-07T07:12:13Z
| 523,377
|
<p>You should use wxSplitter, <a href="http://wiki.wxpython.org/ProportionalSplitterWindow" rel="nofollow">here's</a> an example. Another one <a href="http://www.zetcode.com/wxpython/widgets/#splitterwindow" rel="nofollow">here</a>. And <a href="http://wiki.wxpython.org/AnotherTutorial" rel="nofollow">another</a>.</p>
| 3
|
2009-02-07T07:20:29Z
|
[
"python",
"layout",
"wxpython",
"elasticlayout"
] |
How do I layout a 3 pane window using wxPython?
| 523,363
|
<p>I am trying to find a simple way to layout a 3 pane window using wxPython.</p>
<p>I want to have a tree list in the left pane, then have a right pane that is split into two - with an edit component in the top part and a grid component in the bottom part.</p>
<p>Something along the lines of:</p>
<pre>
--------------------------------------
| | |
| | Edit |
| Tree | Control |
| Control | |
| |----------------------|
| | |
| | Grid |
| | |
--------------------------------------
</pre>
<p>I would like the window to be re-sizable and give the user the ability to change the (relative) size of each of the components within the windows by dragging the borders.</p>
<p>I figure that I need some combination of sizers and/or splitter-window components but can't find a decent example of this kind of window in the documentation or on the web. </p>
| 5
|
2009-02-07T07:12:13Z
| 523,485
|
<p>First of all download <a href="http://wxglade.sourceforge.net/">wxGlade</a> a gui builder for wxPython (alternative <a href="http://xrced.sourceforge.net/">XRCed</a>, i prefere wxGlade).</p>
<p>Then you have to decide if you want to use a <a href="http://www.wxpython.org/docs/api/wx.GridSizer-class.html">GridSizer</a> or a <a href="http://www.wxpython.org/docs/api/wx.SplitterWindow-class.html">Splitter</a> and you are done. Below you find both (between Tree and right side is a GridSizer -> resizes automatically). Between Edit and GridCtrl is a Sizer (manual Resize).</p>
<p>Regards. </p>
<p>one minute work without entering a single line of code:</p>
<pre><code>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# generated by wxGlade 0.6.3 on Sat Feb 07 10:02:31 2009
import wx
import wx.grid
# begin wxGlade: extracode
# end wxGlade
class MyDialog(wx.Dialog):
def __init__(self, *args, **kwds):
# begin wxGlade: MyDialog.__init__
kwds["style"] = wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER|wx.THICK_FRAME
wx.Dialog.__init__(self, *args, **kwds)
self.window_1 = wx.SplitterWindow(self, -1, style=wx.SP_3D|wx.SP_BORDER)
self.tree_ctrl_1 = wx.TreeCtrl(self, -1, style=wx.TR_HAS_BUTTONS|wx.TR_LINES_AT_ROOT|wx.TR_DEFAULT_STYLE|wx.SUNKEN_BORDER)
self.text_ctrl_1 = wx.TextCtrl(self.window_1, -1, "This is the Edit", style=wx.TE_MULTILINE)
self.grid_1 = wx.grid.Grid(self.window_1, -1, size=(1, 1))
self.__set_properties()
self.__do_layout()
# end wxGlade
def __set_properties(self):
# begin wxGlade: MyDialog.__set_properties
self.SetTitle("dialog_1")
self.grid_1.CreateGrid(10, 3)
# end wxGlade
def __do_layout(self):
# begin wxGlade: MyDialog.__do_layout
grid_sizer_1 = wx.FlexGridSizer(1, 2, 3, 3)
grid_sizer_1.Add(self.tree_ctrl_1, 1, wx.EXPAND, 0)
self.window_1.SplitHorizontally(self.text_ctrl_1, self.grid_1)
grid_sizer_1.Add(self.window_1, 1, wx.EXPAND, 0)
self.SetSizer(grid_sizer_1)
grid_sizer_1.Fit(self)
grid_sizer_1.AddGrowableRow(0)
grid_sizer_1.AddGrowableCol(0)
grid_sizer_1.AddGrowableCol(1)
self.Layout()
# end wxGlade
# end of class MyDialog
class MyApp(wx.App):
def OnInit(self):
wx.InitAllImageHandlers()
mainDlg = MyDialog(None, -1, "")
self.SetTopWindow(mainDlg)
mainDlg.Show()
return 1
# end of class MyApp
if __name__ == "__main__":
app = MyApp(0)
app.MainLoop()
</code></pre>
| 7
|
2009-02-07T09:08:11Z
|
[
"python",
"layout",
"wxpython",
"elasticlayout"
] |
How do I layout a 3 pane window using wxPython?
| 523,363
|
<p>I am trying to find a simple way to layout a 3 pane window using wxPython.</p>
<p>I want to have a tree list in the left pane, then have a right pane that is split into two - with an edit component in the top part and a grid component in the bottom part.</p>
<p>Something along the lines of:</p>
<pre>
--------------------------------------
| | |
| | Edit |
| Tree | Control |
| Control | |
| |----------------------|
| | |
| | Grid |
| | |
--------------------------------------
</pre>
<p>I would like the window to be re-sizable and give the user the ability to change the (relative) size of each of the components within the windows by dragging the borders.</p>
<p>I figure that I need some combination of sizers and/or splitter-window components but can't find a decent example of this kind of window in the documentation or on the web. </p>
| 5
|
2009-02-07T07:12:13Z
| 524,313
|
<p>You could consider using the <a href="http://docs.wxwidgets.org/stable/wx_wxauioverview.html#wxauioverview" rel="nofollow">wx.aui</a> advanced user interface module, as it allows you to build UIs like this very easily. Also the user can then minimise, maximise, and drag the panes around as they see fit, or not. It's pretty flexible. I actually find it easier to lay out this sort of UI with the aui toolkit, rather than with grids and splitters. Plus all the fancy buttons make apps look cooler. :)</p>
<p>There is a nice example in the official demos, called AUI_DockingWindowMgr.</p>
| 2
|
2009-02-07T18:31:34Z
|
[
"python",
"layout",
"wxpython",
"elasticlayout"
] |
How do I layout a 3 pane window using wxPython?
| 523,363
|
<p>I am trying to find a simple way to layout a 3 pane window using wxPython.</p>
<p>I want to have a tree list in the left pane, then have a right pane that is split into two - with an edit component in the top part and a grid component in the bottom part.</p>
<p>Something along the lines of:</p>
<pre>
--------------------------------------
| | |
| | Edit |
| Tree | Control |
| Control | |
| |----------------------|
| | |
| | Grid |
| | |
--------------------------------------
</pre>
<p>I would like the window to be re-sizable and give the user the ability to change the (relative) size of each of the components within the windows by dragging the borders.</p>
<p>I figure that I need some combination of sizers and/or splitter-window components but can't find a decent example of this kind of window in the documentation or on the web. </p>
| 5
|
2009-02-07T07:12:13Z
| 532,873
|
<p>This is a very simple layout using wx.aui and three panels. I guess you can easily adapt it to suit your needs.</p>
<p>Orjanp...</p>
<pre><code>import wx
import wx.aui
class MyFrame(wx.Frame):
def __init__(self, *args, **kwargs):
wx.Frame.__init__(self, *args, **kwargs)
self.mgr = wx.aui.AuiManager(self)
leftpanel = wx.Panel(self, -1, size = (200, 150))
rightpanel = wx.Panel(self, -1, size = (200, 150))
bottompanel = wx.Panel(self, -1, size = (200, 150))
self.mgr.AddPane(leftpanel, wx.aui.AuiPaneInfo().Bottom())
self.mgr.AddPane(rightpanel, wx.aui.AuiPaneInfo().Left().Layer(1))
self.mgr.AddPane(bottompanel, wx.aui.AuiPaneInfo().Center().Layer(2))
self.mgr.Update()
class MyApp(wx.App):
def OnInit(self):
frame = MyFrame(None, -1, '07_wxaui.py')
frame.Show()
self.SetTopWindow(frame)
return 1
if __name__ == "__main__":
app = MyApp(0)
app.MainLoop()
</code></pre>
| 7
|
2009-02-10T15:50:22Z
|
[
"python",
"layout",
"wxpython",
"elasticlayout"
] |
How to scale an image without occasionally inverting it (with the Python Imaging Library)
| 523,503
|
<p>When resizing images along the lines shown <a href="http://stackoverflow.com/questions/400788/resize-image-in-python-without-losing-exif-data">in this question</a> occasionally the resulting image is inverted. About 1% of the images I resize are inverted, the rest is fine. So far I was unable to find out what is different about these images.</p>
<p>See <a href="http://images.hudora.de/640x480/NIRV2MRR3XJGR52JATL6BOVMQMFSV54I01.jpeg" rel="nofollow">resized example</a> and <a href="http://images.hudora.de/o/NIRV2MRR3XJGR52JATL6BOVMQMFSV54I01.jpeg" rel="nofollow">original image</a> for examples.</p>
<p>Any suggestions on how to track down that problem?</p>
| -1
|
2009-02-07T09:29:37Z
| 523,518
|
<p>Your original image won't display for me; Firefox says</p>
<pre><code>The image âhttp://images.hudora.de/o/NIRV2MRR3XJGR52JATL6BOVMQMFSV54I01.jpegâ
cannot be displayed, because it contains errors.
</code></pre>
<p>This suggests that the problem arises when you attempt to resize a corrupted JPEG, and indeed your resized example shows what looks like JPEG corruption to my eye (Ever cracked open a JPEG image and twiddled a few bits to see what it does to the output? I have, and a few of my abominable creations looked like that). There are a few JPEG repair tools out there, but I've never seriously tried any of them and don't know if they might be able to help you out.</p>
| 2
|
2009-02-07T09:39:38Z
|
[
"python",
"image-processing",
"python-imaging-library"
] |
How to scale an image without occasionally inverting it (with the Python Imaging Library)
| 523,503
|
<p>When resizing images along the lines shown <a href="http://stackoverflow.com/questions/400788/resize-image-in-python-without-losing-exif-data">in this question</a> occasionally the resulting image is inverted. About 1% of the images I resize are inverted, the rest is fine. So far I was unable to find out what is different about these images.</p>
<p>See <a href="http://images.hudora.de/640x480/NIRV2MRR3XJGR52JATL6BOVMQMFSV54I01.jpeg" rel="nofollow">resized example</a> and <a href="http://images.hudora.de/o/NIRV2MRR3XJGR52JATL6BOVMQMFSV54I01.jpeg" rel="nofollow">original image</a> for examples.</p>
<p>Any suggestions on how to track down that problem?</p>
| -1
|
2009-02-07T09:29:37Z
| 538,458
|
<p>I was finally able to find someone experienced in JPEG and with some additional knowledge was able to find a solution.</p>
<ol>
<li>JPEG is a very underspecified
Format.</li>
<li>The second image is a valid JPEG but it is in CMYK color space, not in RGB color space.</li>
<li>Design minded tools (read: things from Apple) can process CMYK JPEGs, other stuff (Firefox, IE) can't.</li>
<li>CMYK JPEG is <em>very</em> under specified and the way Adobe Photoshop writes it to disk is borderline to buggy.</li>
</ol>
<p>Best of it all <a href="http://mail.python.org/pipermail/image-sig/2006-April/003871.html" rel="nofollow">there is a patch</a> to fix the issue.</p>
| 3
|
2009-02-11T19:46:07Z
|
[
"python",
"image-processing",
"python-imaging-library"
] |
Google Apps HTTP Streaming with Python question
| 523,579
|
<p>I got a little question here:</p>
<p>Some time ago I implemented HTTP Streaming using PHP code, something similar to what is on this page:</p>
<p><a href="http://my.opera.com/WebApplications/blog/show.dml/438711#comments" rel="nofollow">http://my.opera.com/WebApplications/blog/show.dml/438711#comments</a></p>
<p>And I get data with very similar solution. Now I tried to use second code from this page (in Python), but no matter what I do, I receive responseText from python server after everything completes. Here are some python code:</p>
<pre><code>print "Content-Type: application/x-www-form-urlencoded\n\n"
i=1
while i<4:
print("Event: server-time<br>")
print("data: %f<br>" % (time.time(),))
sys.stdout.flush()
i=i+1
time.sleep(1)
</code></pre>
<p>And here is Javascript Code:</p>
<pre><code>ask = new XMLHttpRequest();
ask.open("GET","/Chat",true);
setInterval(function()
{
if (ask.responseText) document.write(ask.responseText);
},200);
ask.send(null);
</code></pre>
<p>Anyone got idea what I do wrong ? How can I receive those damn messages one after another, not just all of them at the end of while loop? Thanks for any help here!</p>
<p>Edit:</p>
<p>Main thing I forgot to add: server is google app server (i'm not sure is that google own implementation), here is a link with some explanation (i think uhh):</p>
<p><a href="http://code.google.com/intl/pl-PL/appengine/docs/python/gettingstarted/devenvironment.html" rel="nofollow">http://code.google.com/intl/pl-PL/appengine/docs/python/gettingstarted/devenvironment.html</a>
<a href="http://code.google.com/intl/pl-PL/appengine/docs/whatisgoogleappengine.html" rel="nofollow">http://code.google.com/intl/pl-PL/appengine/docs/whatisgoogleappengine.html</a></p>
| 0
|
2009-02-07T10:27:18Z
| 524,133
|
<p>That looks like a cgi code - I imagine the web server buffers the response from the cgi handlers. So it's really a matter of picking the right tools and making the right configuration.</p>
<p>I suggest using a wsgi server and take advantage of the streaming support wsgi has.</p>
<p>Here's your sample code translated to a wsgi app:</p>
<pre><code>def app(environ, start_response):
start_response('200 OK', [('Content-type','application/x-www-form-urlencoded')])
i=1
while i<4:
yield "Event: server-time<br>"
yield "data: %f<br>" % (time.time(),)
i=i+1
time.sleep(1)
</code></pre>
<p>There are plenty of wsgi servers but here's an example with the reference one from python std lib:</p>
<pre><code>from wsgiref.simple_server import make_server
httpd = make_server('', 8000, app)
httpd.serve_forever()
</code></pre>
| 1
|
2009-02-07T17:10:36Z
|
[
"javascript",
"python",
"streaming"
] |
Google Apps HTTP Streaming with Python question
| 523,579
|
<p>I got a little question here:</p>
<p>Some time ago I implemented HTTP Streaming using PHP code, something similar to what is on this page:</p>
<p><a href="http://my.opera.com/WebApplications/blog/show.dml/438711#comments" rel="nofollow">http://my.opera.com/WebApplications/blog/show.dml/438711#comments</a></p>
<p>And I get data with very similar solution. Now I tried to use second code from this page (in Python), but no matter what I do, I receive responseText from python server after everything completes. Here are some python code:</p>
<pre><code>print "Content-Type: application/x-www-form-urlencoded\n\n"
i=1
while i<4:
print("Event: server-time<br>")
print("data: %f<br>" % (time.time(),))
sys.stdout.flush()
i=i+1
time.sleep(1)
</code></pre>
<p>And here is Javascript Code:</p>
<pre><code>ask = new XMLHttpRequest();
ask.open("GET","/Chat",true);
setInterval(function()
{
if (ask.responseText) document.write(ask.responseText);
},200);
ask.send(null);
</code></pre>
<p>Anyone got idea what I do wrong ? How can I receive those damn messages one after another, not just all of them at the end of while loop? Thanks for any help here!</p>
<p>Edit:</p>
<p>Main thing I forgot to add: server is google app server (i'm not sure is that google own implementation), here is a link with some explanation (i think uhh):</p>
<p><a href="http://code.google.com/intl/pl-PL/appengine/docs/python/gettingstarted/devenvironment.html" rel="nofollow">http://code.google.com/intl/pl-PL/appengine/docs/python/gettingstarted/devenvironment.html</a>
<a href="http://code.google.com/intl/pl-PL/appengine/docs/whatisgoogleappengine.html" rel="nofollow">http://code.google.com/intl/pl-PL/appengine/docs/whatisgoogleappengine.html</a></p>
| 0
|
2009-02-07T10:27:18Z
| 524,332
|
<p>Its highly likely App Engine buffers output. A quick search found this: <a href="http://code.google.com/appengine/docs/python/tools/webapp/buildingtheresponse.html" rel="nofollow">http://code.google.com/appengine/docs/python/tools/webapp/buildingtheresponse.html</a></p>
<blockquote>
<p>The out stream buffers all output in memory, then sends the final output when the handler exits. webapp does not support streaming data to the client.</p>
</blockquote>
| 3
|
2009-02-07T18:40:55Z
|
[
"javascript",
"python",
"streaming"
] |
BaseHTTPRequestHandler freezes while writing to self.wfile after installing Python 3.0
| 523,885
|
<p>I'm starting to lose my head with this one.</p>
<p>I have a class that extends BaseHTTPRequestHandler. It works fine on
Python 2.5. And yesterday I was curious and decided to install Python
3.0 on my Mac (I followed this tutorial, to be sure I wasn't messing
things up: <a href="http://farmdev.com/thoughts/66/python-3-0-on-mac-os-x-alongside-2-6-2-5-etc-/" rel="nofollow">http://farmdev.com/thoughts/66/python-3-0-on-mac-os-x-alongside-2-6-2-5-etc-/</a>
). I tried my application on Python 3.0 and the code just freezed on
this line:</p>
<pre><code>self.wfile.write(f.read())
</code></pre>
<p>I searched and got to this bug <a href="http://bugs.python.org/issue3826" rel="nofollow">http://bugs.python.org/issue3826</a>. I
couldn't understand if there's already a fix for that. But, the
strangest thing was that, when I tried my application on 2.5, it
started freezing on the same spot! I then removed everything I
installed from 3.0, fixed the paths, and it still gives me the error.
I don't know what else to do.</p>
<p>The app works fine on 2.5, because I tried it on another computer.</p>
<p>Thanks for your help.</p>
| 0
|
2009-02-07T14:57:29Z
| 523,900
|
<p>I would suggest develop a simple page that would dump the version details of the perl environment and confirm that now you are back on 2.5. Mostly in such scenarios there are some environment entries or binaries that are left out.</p>
| 0
|
2009-02-07T15:03:53Z
|
[
"python",
"sockets"
] |
BaseHTTPRequestHandler freezes while writing to self.wfile after installing Python 3.0
| 523,885
|
<p>I'm starting to lose my head with this one.</p>
<p>I have a class that extends BaseHTTPRequestHandler. It works fine on
Python 2.5. And yesterday I was curious and decided to install Python
3.0 on my Mac (I followed this tutorial, to be sure I wasn't messing
things up: <a href="http://farmdev.com/thoughts/66/python-3-0-on-mac-os-x-alongside-2-6-2-5-etc-/" rel="nofollow">http://farmdev.com/thoughts/66/python-3-0-on-mac-os-x-alongside-2-6-2-5-etc-/</a>
). I tried my application on Python 3.0 and the code just freezed on
this line:</p>
<pre><code>self.wfile.write(f.read())
</code></pre>
<p>I searched and got to this bug <a href="http://bugs.python.org/issue3826" rel="nofollow">http://bugs.python.org/issue3826</a>. I
couldn't understand if there's already a fix for that. But, the
strangest thing was that, when I tried my application on 2.5, it
started freezing on the same spot! I then removed everything I
installed from 3.0, fixed the paths, and it still gives me the error.
I don't know what else to do.</p>
<p>The app works fine on 2.5, because I tried it on another computer.</p>
<p>Thanks for your help.</p>
| 0
|
2009-02-07T14:57:29Z
| 525,552
|
<p>I'm sorry, it seems to have been a weird setting between routers <code>(mac <-> router <-> router <-> ISP)</code> here at home.</p>
<p>Small files ( < 100kB ) were served with no problem at all, but larger files got stuck. I found it out after formatting my mac, and realized that it was still happening. I tried to remove on of the routers out of the way and it sure works now. The real reason that caused it, and why it worked before and suddently stopped working after (coincidently, for sure) installing Python 3.0 is still incognito for me.</p>
<p>Thanks for the readers.</p>
| 0
|
2009-02-08T11:14:51Z
|
[
"python",
"sockets"
] |
Insert Command into Bash Shell
| 524,068
|
<p>Is there any way to inject a command into a bash prompt in Linux? I am working on a command history app - like the Ctrl+R lookup but different. I am using python for this.</p>
<p>I will show a list of commands from history based on the user's search term - if the user presses enter, the app will execute the command and print the results. So far, so good.</p>
<p>If the user chooses a command and then press the right or left key, I want to insert the command into the prompt - so that the user can edit the command before executing it.</p>
<p>If you are on Linux, just fire up a bash console, press Ctrl+r, type cd(or something), and then press the right arrow key - the selected command will be shown at the prompt. This is the functionality I am looking for - but I want to know how to do that from within python.</p>
| 0
|
2009-02-07T16:30:31Z
| 524,092
|
<p><a href="http://www.gnu.org/software/ncurses/ncurses.html" rel="nofollow" title="ncurses">ncurses</a> with its <a href="http://docs.python.org/library/curses.html" rel="nofollow" title="python port">python port</a> is a way to go, IMHO.</p>
| 1
|
2009-02-07T16:42:45Z
|
[
"python",
"linux",
"bash",
"shell",
"command"
] |
Insert Command into Bash Shell
| 524,068
|
<p>Is there any way to inject a command into a bash prompt in Linux? I am working on a command history app - like the Ctrl+R lookup but different. I am using python for this.</p>
<p>I will show a list of commands from history based on the user's search term - if the user presses enter, the app will execute the command and print the results. So far, so good.</p>
<p>If the user chooses a command and then press the right or left key, I want to insert the command into the prompt - so that the user can edit the command before executing it.</p>
<p>If you are on Linux, just fire up a bash console, press Ctrl+r, type cd(or something), and then press the right arrow key - the selected command will be shown at the prompt. This is the functionality I am looking for - but I want to know how to do that from within python.</p>
| 0
|
2009-02-07T16:30:31Z
| 524,104
|
<p>You can do this, but only if the shell runs as a subprocess of your Python program; you can't feed content into the stdin of your parent process. (If you could, UNIX would have a host of related security issues when folks run processes with fewer privileges than the calling shell!)</p>
<p>If you're familiar with how <A HREF="http://expect.nist.gov/" rel="nofollow">Expect</A> allows passthrough to interactive subprocesses (with specific key sequences from the user or strings received from the child process triggering matches and sending control back to your program), the same thing can be done from Python with <A HREF="http://www.noah.org/wiki/Pexpect" rel="nofollow">pexpect</A>. Alternately, as another post mentioned, the <A HREF="http://docs.python.org/library/curses.html" rel="nofollow">curses</A> module provides full control over the drawing of terminal displays -- which you'll want if this history menu is happening within the window rather than in a graphical (X11/win32) pop-up.</p>
| 3
|
2009-02-07T16:50:09Z
|
[
"python",
"linux",
"bash",
"shell",
"command"
] |
Insert Command into Bash Shell
| 524,068
|
<p>Is there any way to inject a command into a bash prompt in Linux? I am working on a command history app - like the Ctrl+R lookup but different. I am using python for this.</p>
<p>I will show a list of commands from history based on the user's search term - if the user presses enter, the app will execute the command and print the results. So far, so good.</p>
<p>If the user chooses a command and then press the right or left key, I want to insert the command into the prompt - so that the user can edit the command before executing it.</p>
<p>If you are on Linux, just fire up a bash console, press Ctrl+r, type cd(or something), and then press the right arrow key - the selected command will be shown at the prompt. This is the functionality I am looking for - but I want to know how to do that from within python.</p>
| 0
|
2009-02-07T16:30:31Z
| 740,490
|
<p>See <a href="http://docs.python.org/library/readline.html" rel="nofollow">readline</a> module. It implements all these features.</p>
| 3
|
2009-04-11T17:32:30Z
|
[
"python",
"linux",
"bash",
"shell",
"command"
] |
Insert Command into Bash Shell
| 524,068
|
<p>Is there any way to inject a command into a bash prompt in Linux? I am working on a command history app - like the Ctrl+R lookup but different. I am using python for this.</p>
<p>I will show a list of commands from history based on the user's search term - if the user presses enter, the app will execute the command and print the results. So far, so good.</p>
<p>If the user chooses a command and then press the right or left key, I want to insert the command into the prompt - so that the user can edit the command before executing it.</p>
<p>If you are on Linux, just fire up a bash console, press Ctrl+r, type cd(or something), and then press the right arrow key - the selected command will be shown at the prompt. This is the functionality I am looking for - but I want to know how to do that from within python.</p>
| 0
|
2009-02-07T16:30:31Z
| 740,529
|
<p>If I understand correctly, you would like history behaviour similar to that of bash in
a python app. If this is what you want the <a href="http://en.wikipedia.org/wiki/GNU%5Freadline" rel="nofollow">GNU Readline Library</a> is the way to go.</p>
<p>There is a python wrapper <a href="http://docs.python.org/library/readline.html" rel="nofollow">GNU readline interface</a> but it runs only on Unix.
<a href="http://newcenturycomputers.net/projects/readline.html" rel="nofollow">readline.py</a> is seem to be a version for Windows, but I never tried it.</p>
| 3
|
2009-04-11T17:55:56Z
|
[
"python",
"linux",
"bash",
"shell",
"command"
] |
Is there a Python equivalent of Groovy/Grails for Java
| 524,147
|
<p>I'm thinking of something like Jython/Jango? Does this exist? Or does Jython allow you to do everything-Python in Java including Django (I'm not sure how Jython differs from Python)?</p>
| 3
|
2009-02-07T17:21:41Z
| 524,172
|
<p><a href="http://wiki.python.org/jython/DjangoOnJython">http://wiki.python.org/jython/DjangoOnJython</a></p>
| 8
|
2009-02-07T17:32:47Z
|
[
"python",
"django",
"grails",
"groovy",
"jython"
] |
Is there a Python equivalent of Groovy/Grails for Java
| 524,147
|
<p>I'm thinking of something like Jython/Jango? Does this exist? Or does Jython allow you to do everything-Python in Java including Django (I'm not sure how Jython differs from Python)?</p>
| 3
|
2009-02-07T17:21:41Z
| 524,201
|
<p>"I'm not sure how Jython differs from Python"</p>
<p><a href="http://www.jython.org/Project/" rel="nofollow">http://www.jython.org/Project/</a></p>
<blockquote>
<p>Jython is an implementation of the
high-level, dynamic, object-oriented
language Python seamlessly integrated
with the Java platform.</p>
</blockquote>
<p><a href="http://docs.python.org/reference/introduction.html#alternate-implementations" rel="nofollow">http://docs.python.org/reference/introduction.html#alternate-implementations</a></p>
<blockquote>
<p>Python implemented in Java. This
implementation can be used as a
scripting language for Java
applications, or can be used to create
applications using the Java class
libraries. It is also often used to
create tests for Java libraries. More
information can be found at the Jython
website.</p>
</blockquote>
| 3
|
2009-02-07T17:48:53Z
|
[
"python",
"django",
"grails",
"groovy",
"jython"
] |
Is there a Python equivalent of Groovy/Grails for Java
| 524,147
|
<p>I'm thinking of something like Jython/Jango? Does this exist? Or does Jython allow you to do everything-Python in Java including Django (I'm not sure how Jython differs from Python)?</p>
| 3
|
2009-02-07T17:21:41Z
| 4,229,750
|
<p><a href="http://turbogears.org/" rel="nofollow">http://turbogears.org/</a></p>
<p>might be closer to what you are looking for</p>
| 1
|
2010-11-19T21:54:43Z
|
[
"python",
"django",
"grails",
"groovy",
"jython"
] |
How to externally populate a Django model?
| 524,214
|
<p>What is the best idea to fill up data into a Django model from an external source?</p>
<p>E.g. I have a model Run, and runs data in an XML file, which changes weekly.</p>
<p>Should I create a view and call that view URL from a curl cronjob (with the advantage that that data can be read anytime, not only when the cronjob runs), or create a python script and install that script as a cron (with DJANGO _SETTINGS _MODULE variable setup before executing the script)?</p>
| 8
|
2009-02-07T17:54:54Z
| 524,239
|
<p>You don't need to create a view, you should just trigger a python script with the appropriate <a href="http://stackoverflow.com/questions/383073/django-how-can-i-use-my-model-classes-to-interact-with-my-database-from-outside/383089#383089">Django environment settings configured</a>. Then call your models directly the way you would if you were using a view, process your data, add it to your model, then .save() the model to the database.</p>
| 4
|
2009-02-07T18:03:44Z
|
[
"python",
"django",
"django-models"
] |
How to externally populate a Django model?
| 524,214
|
<p>What is the best idea to fill up data into a Django model from an external source?</p>
<p>E.g. I have a model Run, and runs data in an XML file, which changes weekly.</p>
<p>Should I create a view and call that view URL from a curl cronjob (with the advantage that that data can be read anytime, not only when the cronjob runs), or create a python script and install that script as a cron (with DJANGO _SETTINGS _MODULE variable setup before executing the script)?</p>
| 8
|
2009-02-07T17:54:54Z
| 524,333
|
<p>There is excellent way to do some maintenance-like jobs in project environment- write a <a href="http://docs.djangoproject.com/en/dev/howto/custom-management-commands/#howto-custom-management-commands">custom manage.py command</a>. It takes all environment configuration and other stuff allows you to concentrate on concrete task.</p>
<p>And of course call it directly by cron.</p>
| 10
|
2009-02-07T18:43:12Z
|
[
"python",
"django",
"django-models"
] |
How to externally populate a Django model?
| 524,214
|
<p>What is the best idea to fill up data into a Django model from an external source?</p>
<p>E.g. I have a model Run, and runs data in an XML file, which changes weekly.</p>
<p>Should I create a view and call that view URL from a curl cronjob (with the advantage that that data can be read anytime, not only when the cronjob runs), or create a python script and install that script as a cron (with DJANGO _SETTINGS _MODULE variable setup before executing the script)?</p>
| 8
|
2009-02-07T17:54:54Z
| 524,401
|
<p>"create a python script and install that script as a cron (with DJANGO _SETTINGS _MODULE variable setup before executing the script)?" </p>
<p>First, be sure to declare your Forms in a separate module (e.g. <code>forms.py</code>) </p>
<p>Then, you can write batch loaders that look like this. (We have a LOT of these.)</p>
<pre><code>from myapp.forms import MyObjectLoadForm
from myapp.models import MyObject
import xml.etree.ElementTree as ET
def xmlToDict( element ):
return dict(
field1= element.findtext('tag1'),
field2= element.findtext('tag2'),
)
def loadRow( aDict ):
f= MyObjectLoadForm( aDict )
if f.is_valid():
f.save()
def parseAndLoad( someFile ):
doc= ET.parse( someFile ).getroot()
for tag in doc.getiterator( "someTag" )
loadRow( xmlToDict(tag) )
</code></pre>
<p>Note that there is very little unique processing here -- it just uses the same Form and Model as your view functions. </p>
<p>We put these batch scripts in with our Django application, since it depends on the application's <code>models.py</code> and <code>forms.py</code>.</p>
<p>The only "interesting" part is transforming your XML row into a dictionary so that it works seamlessly with Django's forms. Other than that, this command-line program uses all the same Django components as your view.</p>
<p>You'll probably want to add options parsing and logging to make a complete command-line app out of this. You'll also notice that much of the logic is generic -- only the <code>xmlToDict</code> function is truly unique. We call these "Builders" and have a class hierarchy so that our Builders are all polymorphic mappings from our source documents to Python dictionaries.</p>
| 2
|
2009-02-07T19:26:13Z
|
[
"python",
"django",
"django-models"
] |
How to externally populate a Django model?
| 524,214
|
<p>What is the best idea to fill up data into a Django model from an external source?</p>
<p>E.g. I have a model Run, and runs data in an XML file, which changes weekly.</p>
<p>Should I create a view and call that view URL from a curl cronjob (with the advantage that that data can be read anytime, not only when the cronjob runs), or create a python script and install that script as a cron (with DJANGO _SETTINGS _MODULE variable setup before executing the script)?</p>
| 8
|
2009-02-07T17:54:54Z
| 524,414
|
<p>I've used cron to update my DB using both a script and a view. From cron's point of view it doesn't really matter which one you choose. As you've noted, though, it's hard to beat the simplicity of firing up a browser and hitting a URL if you ever want to update at a non-scheduled interval.</p>
<p>If you go the view route, it might be worth considering a view that accepts the XML file itself via an HTTP POST. If that makes sense for your data (you don't give much information about that XML file), it would still work from cron, but could also accept an upload from a browser -- potentially letting the person who produces the XML file update the DB by themselves. That's a big win if you're not the one making the XML file, which is usually the case in my experience.</p>
| 2
|
2009-02-07T19:33:52Z
|
[
"python",
"django",
"django-models"
] |
How to 'zoom' in on a section of the Mandelbrot set?
| 524,291
|
<p>I have created a Python file to generate a Mandelbrot set image. The original maths code was not mine, so I do not understand it - I only heavily modified it to make it about 250x faster (Threads rule!).</p>
<p>Anyway, I was wondering how I could modify the maths part of the code to make it render one specific bit. Here is the maths part:</p>
<pre><code>for y in xrange(size[1]):
coords = (uleft[0] + (x/size[0]) * (xwidth),uleft[1] - (y/size[1]) * (ywidth))
z = complex(coords[0],coords[1])
o = complex(0,0)
dotcolor = 0 # default, convergent
for trials in xrange(n):
if abs(o) <= 2.0:
o = o**2 + z
else:
dotcolor = trials
break # diverged
im.putpixel((x,y),dotcolor)
</code></pre>
<p>And the size definitions:</p>
<pre><code>size1 = 500
size2 = 500
n=64
box=((-2,1.25),(0.5,-1.25))
plus = size[1]+size[0]
uleft = box[0]
lright = box[1]
xwidth = lright[0] - uleft[0]
ywidth = uleft[1] - lright[1]
</code></pre>
<p>what do I need to modify to make it render a certain section of the set?</p>
| 5
|
2009-02-07T18:22:48Z
| 524,312
|
<p>The line:</p>
<pre><code>box=((-2,1.25),(0.5,-1.25))
</code></pre>
<p>is the bit that defines the area of coordinate space that is being rendered, so you just need to change this line. First coordinate pair is the top-left of the area, the second is the bottom right. </p>
<p>To get a new coordinate from the image should be quite straightforward. You've got two coordinate systems, your "image" system 100x100 pixels in size, origin at (0,0). And your "complex" plane coordinate system defined by "box". For X:</p>
<pre><code>X_complex=X_complex_origin+(X_image/X_image_width)*X_complex_width
</code></pre>
| 14
|
2009-02-07T18:31:16Z
|
[
"python",
"math",
"mandelbrot"
] |
How to 'zoom' in on a section of the Mandelbrot set?
| 524,291
|
<p>I have created a Python file to generate a Mandelbrot set image. The original maths code was not mine, so I do not understand it - I only heavily modified it to make it about 250x faster (Threads rule!).</p>
<p>Anyway, I was wondering how I could modify the maths part of the code to make it render one specific bit. Here is the maths part:</p>
<pre><code>for y in xrange(size[1]):
coords = (uleft[0] + (x/size[0]) * (xwidth),uleft[1] - (y/size[1]) * (ywidth))
z = complex(coords[0],coords[1])
o = complex(0,0)
dotcolor = 0 # default, convergent
for trials in xrange(n):
if abs(o) <= 2.0:
o = o**2 + z
else:
dotcolor = trials
break # diverged
im.putpixel((x,y),dotcolor)
</code></pre>
<p>And the size definitions:</p>
<pre><code>size1 = 500
size2 = 500
n=64
box=((-2,1.25),(0.5,-1.25))
plus = size[1]+size[0]
uleft = box[0]
lright = box[1]
xwidth = lright[0] - uleft[0]
ywidth = uleft[1] - lright[1]
</code></pre>
<p>what do I need to modify to make it render a certain section of the set?</p>
| 5
|
2009-02-07T18:22:48Z
| 524,501
|
<p>The key in understanding how to do this is to understand what the <code>coords =</code> line is doing:</p>
<pre><code>coords = (uleft[0] + (x/size[0]) * (xwidth),uleft[1] - (y/size[1]) * (ywidth))
</code></pre>
<p>Effectively, the <code>x</code> and <code>y</code> values you are looping through which correspond to the coordinates of the on-screen pixel are being translated to the corresponding point on the complex plane being looked at. This means that <code>(0,0)</code> screen coordinate will translate to the upper left region being looked at <code>(-2,1.25)</code>, and <code>(1,0)</code> will be the same, but moved 1/500 of the distance (assuming a 500 pixel width window) between the <code>-2</code> and <code>0.5</code> x-coordinate.</p>
<p>That's exactly what that line is doing - I'll expand just the X-coordinate bit with more illustrative variable names to indicate this:</p>
<pre><code>mandel_x = mandel_start_x + (screen_x / screen_width) * mandel_width
</code></pre>
<p>(The <code>mandel_</code> variables refer to the coordinates on the complex plane, the <code>screen_</code> variables refer to the on-screen coordinates of the pixel being plotted.)</p>
<p>If you want then to take a region of the screen to zoom into, you want to do exactly the same: take the screen coordinates of the upper-left and lower-right region, translate them to the complex-plane coordinates, and make those the new uleft and lright variables. ie to zoom in on the box delimited by on-screen coordinates (x1,y1)..(x2,y2), use:</p>
<pre><code>new_uleft = (uleft[0] + (x1/size[0]) * (xwidth), uleft[1] - (y1/size[1]) * (ywidth))
new_lright = (uleft[0] + (x2/size[0]) * (xwidth), uleft[1] - (y2/size[1]) * (ywidth))
</code></pre>
<p>(Obviously you'll need to recalculate the size, xwidth, ywidth and other dependent variables based on the new coordinates)</p>
<p>In case you're curious, the maths behind the mandelbrot set isn't that complicated (just complex).
All it is doing is taking a particular coordinate, treating it as a complex number, and then repeatedly squaring it and adding the original number to it. </p>
<p>For some numbers, doing this will cause the result diverge, constantly growing towards infinity as you repeat the process. For others, it will always stay below a certain level (eg. obviously (0.0, 0.0) never gets any bigger under this process. The mandelbrot set (the black region) is those coordinates which don't diverge. Its been shown that if any number gets above the square root of 5, it will diverge - your code is just using <code>2.0</code> as its approximation to <code>sqrt(5)</code> (~<code>2.236</code>), but this won't make much noticeable difference. </p>
<p>Usually the regions that diverge get plotted with the number of iterations of the process that it takes for them to exceed this value (the <code>trials</code> variable in your code) which is what produces the coloured regions.</p>
| 4
|
2009-02-07T20:19:36Z
|
[
"python",
"math",
"mandelbrot"
] |
Regular expression to detect semi-colon terminated C++ for & while loops
| 524,548
|
<p>In my Python application, I need to write a regular expression that matches a C++ <code>for</code> or <code>while</code> loop that has been terminated with a semi-colon (<code>;</code>). For example, it should match this:</p>
<pre><code>for (int i = 0; i < 10; i++);
</code></pre>
<p>... but not this:</p>
<pre><code>for (int i = 0; i < 10; i++)
</code></pre>
<p>This looks trivial at first glance, until you realise that the text between the opening and closing parenthesis may contain other parenthesis, for example:</p>
<pre><code>for (int i = funcA(); i < funcB(); i++);
</code></pre>
<p>I'm using the python.re module. Right now my regular expression looks like this (I've left my comments in so you can understand it easier):</p>
<pre><code># match any line that begins with a "for" or "while" statement:
^\s*(for|while)\s*
\( # match the initial opening parenthesis
# Now make a named group 'balanced' which matches a balanced substring.
(?P<balanced>
# A balanced substring is either something that is not a parenthesis:
[^()]
| # â¦or a parenthesised string:
\( # A parenthesised string begins with an opening parenthesis
(?P=balanced)* # â¦followed by a sequence of balanced substrings
\) # â¦and ends with a closing parenthesis
)* # Look for a sequence of balanced substrings
\) # Finally, the outer closing parenthesis.
# must end with a semi-colon to match:
\s*;\s*
</code></pre>
<p>This works perfectly for all the above cases, but it breaks as soon as you try and make the third part of the for loop contain a function, like so:</p>
<pre><code>for (int i = 0; i < 10; doSomethingTo(i));
</code></pre>
<p>I think it breaks because as soon as you put some text between the opening and closing parenthesis, the "balanced" group matches that contained text, and thus the <code>(?P=balanced)</code> part doesn't work any more since it won't match (due to the fact that the text inside the parenthesis is different).</p>
<p>In my Python code I'm using the VERBOSE and MULTILINE flags, and creating the regular expression like so:</p>
<pre><code>REGEX_STR = r"""# match any line that begins with a "for" or "while" statement:
^\s*(for|while)\s*
\( # match the initial opening parenthesis
# Now make a named group 'balanced' which matches
# a balanced substring.
(?P<balanced>
# A balanced substring is either something that is not a parenthesis:
[^()]
| # â¦or a parenthesised string:
\( # A parenthesised string begins with an opening parenthesis
(?P=balanced)* # â¦followed by a sequence of balanced substrings
\) # â¦and ends with a closing parenthesis
)* # Look for a sequence of balanced substrings
\) # Finally, the outer closing parenthesis.
# must end with a semi-colon to match:
\s*;\s*"""
REGEX_OBJ = re.compile(REGEX_STR, re.MULTILINE| re.VERBOSE)
</code></pre>
<p>Can anyone suggest an improvement to this regular expression? It's getting too complicated for me to get my head around.</p>
| 25
|
2009-02-07T20:43:52Z
| 524,562
|
<p>This is the kind of thing you really shouldn't do with a regular expression. Just parse the string one character at a time, keeping track of opening/closing parentheses.</p>
<p>If this is all you're looking for, you definitely don't need a full-blown C++ grammar lexer/parser. If you want practice, you can write a little recursive-decent parser, but even that's a bit much for just matching parentheses.</p>
| 19
|
2009-02-07T20:50:09Z
|
[
"c++",
"python",
"regex",
"parsing",
"recursion"
] |
Regular expression to detect semi-colon terminated C++ for & while loops
| 524,548
|
<p>In my Python application, I need to write a regular expression that matches a C++ <code>for</code> or <code>while</code> loop that has been terminated with a semi-colon (<code>;</code>). For example, it should match this:</p>
<pre><code>for (int i = 0; i < 10; i++);
</code></pre>
<p>... but not this:</p>
<pre><code>for (int i = 0; i < 10; i++)
</code></pre>
<p>This looks trivial at first glance, until you realise that the text between the opening and closing parenthesis may contain other parenthesis, for example:</p>
<pre><code>for (int i = funcA(); i < funcB(); i++);
</code></pre>
<p>I'm using the python.re module. Right now my regular expression looks like this (I've left my comments in so you can understand it easier):</p>
<pre><code># match any line that begins with a "for" or "while" statement:
^\s*(for|while)\s*
\( # match the initial opening parenthesis
# Now make a named group 'balanced' which matches a balanced substring.
(?P<balanced>
# A balanced substring is either something that is not a parenthesis:
[^()]
| # â¦or a parenthesised string:
\( # A parenthesised string begins with an opening parenthesis
(?P=balanced)* # â¦followed by a sequence of balanced substrings
\) # â¦and ends with a closing parenthesis
)* # Look for a sequence of balanced substrings
\) # Finally, the outer closing parenthesis.
# must end with a semi-colon to match:
\s*;\s*
</code></pre>
<p>This works perfectly for all the above cases, but it breaks as soon as you try and make the third part of the for loop contain a function, like so:</p>
<pre><code>for (int i = 0; i < 10; doSomethingTo(i));
</code></pre>
<p>I think it breaks because as soon as you put some text between the opening and closing parenthesis, the "balanced" group matches that contained text, and thus the <code>(?P=balanced)</code> part doesn't work any more since it won't match (due to the fact that the text inside the parenthesis is different).</p>
<p>In my Python code I'm using the VERBOSE and MULTILINE flags, and creating the regular expression like so:</p>
<pre><code>REGEX_STR = r"""# match any line that begins with a "for" or "while" statement:
^\s*(for|while)\s*
\( # match the initial opening parenthesis
# Now make a named group 'balanced' which matches
# a balanced substring.
(?P<balanced>
# A balanced substring is either something that is not a parenthesis:
[^()]
| # â¦or a parenthesised string:
\( # A parenthesised string begins with an opening parenthesis
(?P=balanced)* # â¦followed by a sequence of balanced substrings
\) # â¦and ends with a closing parenthesis
)* # Look for a sequence of balanced substrings
\) # Finally, the outer closing parenthesis.
# must end with a semi-colon to match:
\s*;\s*"""
REGEX_OBJ = re.compile(REGEX_STR, re.MULTILINE| re.VERBOSE)
</code></pre>
<p>Can anyone suggest an improvement to this regular expression? It's getting too complicated for me to get my head around.</p>
| 25
|
2009-02-07T20:43:52Z
| 524,563
|
<p>This is a great example of using the wrong tool for the job. Regular expressions do not handle arbitrarily nested sub-matches very well. What you should do instead is use a real lexer and parser (a grammar for C++ should be easy to find) and look for unexpectedly empty loop bodies.</p>
| 7
|
2009-02-07T20:51:09Z
|
[
"c++",
"python",
"regex",
"parsing",
"recursion"
] |
Regular expression to detect semi-colon terminated C++ for & while loops
| 524,548
|
<p>In my Python application, I need to write a regular expression that matches a C++ <code>for</code> or <code>while</code> loop that has been terminated with a semi-colon (<code>;</code>). For example, it should match this:</p>
<pre><code>for (int i = 0; i < 10; i++);
</code></pre>
<p>... but not this:</p>
<pre><code>for (int i = 0; i < 10; i++)
</code></pre>
<p>This looks trivial at first glance, until you realise that the text between the opening and closing parenthesis may contain other parenthesis, for example:</p>
<pre><code>for (int i = funcA(); i < funcB(); i++);
</code></pre>
<p>I'm using the python.re module. Right now my regular expression looks like this (I've left my comments in so you can understand it easier):</p>
<pre><code># match any line that begins with a "for" or "while" statement:
^\s*(for|while)\s*
\( # match the initial opening parenthesis
# Now make a named group 'balanced' which matches a balanced substring.
(?P<balanced>
# A balanced substring is either something that is not a parenthesis:
[^()]
| # â¦or a parenthesised string:
\( # A parenthesised string begins with an opening parenthesis
(?P=balanced)* # â¦followed by a sequence of balanced substrings
\) # â¦and ends with a closing parenthesis
)* # Look for a sequence of balanced substrings
\) # Finally, the outer closing parenthesis.
# must end with a semi-colon to match:
\s*;\s*
</code></pre>
<p>This works perfectly for all the above cases, but it breaks as soon as you try and make the third part of the for loop contain a function, like so:</p>
<pre><code>for (int i = 0; i < 10; doSomethingTo(i));
</code></pre>
<p>I think it breaks because as soon as you put some text between the opening and closing parenthesis, the "balanced" group matches that contained text, and thus the <code>(?P=balanced)</code> part doesn't work any more since it won't match (due to the fact that the text inside the parenthesis is different).</p>
<p>In my Python code I'm using the VERBOSE and MULTILINE flags, and creating the regular expression like so:</p>
<pre><code>REGEX_STR = r"""# match any line that begins with a "for" or "while" statement:
^\s*(for|while)\s*
\( # match the initial opening parenthesis
# Now make a named group 'balanced' which matches
# a balanced substring.
(?P<balanced>
# A balanced substring is either something that is not a parenthesis:
[^()]
| # â¦or a parenthesised string:
\( # A parenthesised string begins with an opening parenthesis
(?P=balanced)* # â¦followed by a sequence of balanced substrings
\) # â¦and ends with a closing parenthesis
)* # Look for a sequence of balanced substrings
\) # Finally, the outer closing parenthesis.
# must end with a semi-colon to match:
\s*;\s*"""
REGEX_OBJ = re.compile(REGEX_STR, re.MULTILINE| re.VERBOSE)
</code></pre>
<p>Can anyone suggest an improvement to this regular expression? It's getting too complicated for me to get my head around.</p>
| 25
|
2009-02-07T20:43:52Z
| 524,570
|
<p>I wouldn't even pay attention to the contents of the parens.</p>
<p>Just match any line that starts with <code>for</code> and ends with semi-colon:</p>
<pre><code>^\t*for.+;$
</code></pre>
<p>Unless you've got <code>for</code> statements split over multiple lines, that will work fine?</p>
| 2
|
2009-02-07T20:54:36Z
|
[
"c++",
"python",
"regex",
"parsing",
"recursion"
] |
Regular expression to detect semi-colon terminated C++ for & while loops
| 524,548
|
<p>In my Python application, I need to write a regular expression that matches a C++ <code>for</code> or <code>while</code> loop that has been terminated with a semi-colon (<code>;</code>). For example, it should match this:</p>
<pre><code>for (int i = 0; i < 10; i++);
</code></pre>
<p>... but not this:</p>
<pre><code>for (int i = 0; i < 10; i++)
</code></pre>
<p>This looks trivial at first glance, until you realise that the text between the opening and closing parenthesis may contain other parenthesis, for example:</p>
<pre><code>for (int i = funcA(); i < funcB(); i++);
</code></pre>
<p>I'm using the python.re module. Right now my regular expression looks like this (I've left my comments in so you can understand it easier):</p>
<pre><code># match any line that begins with a "for" or "while" statement:
^\s*(for|while)\s*
\( # match the initial opening parenthesis
# Now make a named group 'balanced' which matches a balanced substring.
(?P<balanced>
# A balanced substring is either something that is not a parenthesis:
[^()]
| # â¦or a parenthesised string:
\( # A parenthesised string begins with an opening parenthesis
(?P=balanced)* # â¦followed by a sequence of balanced substrings
\) # â¦and ends with a closing parenthesis
)* # Look for a sequence of balanced substrings
\) # Finally, the outer closing parenthesis.
# must end with a semi-colon to match:
\s*;\s*
</code></pre>
<p>This works perfectly for all the above cases, but it breaks as soon as you try and make the third part of the for loop contain a function, like so:</p>
<pre><code>for (int i = 0; i < 10; doSomethingTo(i));
</code></pre>
<p>I think it breaks because as soon as you put some text between the opening and closing parenthesis, the "balanced" group matches that contained text, and thus the <code>(?P=balanced)</code> part doesn't work any more since it won't match (due to the fact that the text inside the parenthesis is different).</p>
<p>In my Python code I'm using the VERBOSE and MULTILINE flags, and creating the regular expression like so:</p>
<pre><code>REGEX_STR = r"""# match any line that begins with a "for" or "while" statement:
^\s*(for|while)\s*
\( # match the initial opening parenthesis
# Now make a named group 'balanced' which matches
# a balanced substring.
(?P<balanced>
# A balanced substring is either something that is not a parenthesis:
[^()]
| # â¦or a parenthesised string:
\( # A parenthesised string begins with an opening parenthesis
(?P=balanced)* # â¦followed by a sequence of balanced substrings
\) # â¦and ends with a closing parenthesis
)* # Look for a sequence of balanced substrings
\) # Finally, the outer closing parenthesis.
# must end with a semi-colon to match:
\s*;\s*"""
REGEX_OBJ = re.compile(REGEX_STR, re.MULTILINE| re.VERBOSE)
</code></pre>
<p>Can anyone suggest an improvement to this regular expression? It's getting too complicated for me to get my head around.</p>
| 25
|
2009-02-07T20:43:52Z
| 524,575
|
<p>Greg is absolutely correct. This kind of parsing cannot be done with regular expressions. I suppose it is possible to build some horrendous monstrosity that would work for many cases, but then you'll just run across something that does.</p>
<p>You really need to use more traditional parsing techniques. For example, its pretty simple to write a recursive decent parser to do what you need. </p>
| 1
|
2009-02-07T20:57:32Z
|
[
"c++",
"python",
"regex",
"parsing",
"recursion"
] |
Regular expression to detect semi-colon terminated C++ for & while loops
| 524,548
|
<p>In my Python application, I need to write a regular expression that matches a C++ <code>for</code> or <code>while</code> loop that has been terminated with a semi-colon (<code>;</code>). For example, it should match this:</p>
<pre><code>for (int i = 0; i < 10; i++);
</code></pre>
<p>... but not this:</p>
<pre><code>for (int i = 0; i < 10; i++)
</code></pre>
<p>This looks trivial at first glance, until you realise that the text between the opening and closing parenthesis may contain other parenthesis, for example:</p>
<pre><code>for (int i = funcA(); i < funcB(); i++);
</code></pre>
<p>I'm using the python.re module. Right now my regular expression looks like this (I've left my comments in so you can understand it easier):</p>
<pre><code># match any line that begins with a "for" or "while" statement:
^\s*(for|while)\s*
\( # match the initial opening parenthesis
# Now make a named group 'balanced' which matches a balanced substring.
(?P<balanced>
# A balanced substring is either something that is not a parenthesis:
[^()]
| # â¦or a parenthesised string:
\( # A parenthesised string begins with an opening parenthesis
(?P=balanced)* # â¦followed by a sequence of balanced substrings
\) # â¦and ends with a closing parenthesis
)* # Look for a sequence of balanced substrings
\) # Finally, the outer closing parenthesis.
# must end with a semi-colon to match:
\s*;\s*
</code></pre>
<p>This works perfectly for all the above cases, but it breaks as soon as you try and make the third part of the for loop contain a function, like so:</p>
<pre><code>for (int i = 0; i < 10; doSomethingTo(i));
</code></pre>
<p>I think it breaks because as soon as you put some text between the opening and closing parenthesis, the "balanced" group matches that contained text, and thus the <code>(?P=balanced)</code> part doesn't work any more since it won't match (due to the fact that the text inside the parenthesis is different).</p>
<p>In my Python code I'm using the VERBOSE and MULTILINE flags, and creating the regular expression like so:</p>
<pre><code>REGEX_STR = r"""# match any line that begins with a "for" or "while" statement:
^\s*(for|while)\s*
\( # match the initial opening parenthesis
# Now make a named group 'balanced' which matches
# a balanced substring.
(?P<balanced>
# A balanced substring is either something that is not a parenthesis:
[^()]
| # â¦or a parenthesised string:
\( # A parenthesised string begins with an opening parenthesis
(?P=balanced)* # â¦followed by a sequence of balanced substrings
\) # â¦and ends with a closing parenthesis
)* # Look for a sequence of balanced substrings
\) # Finally, the outer closing parenthesis.
# must end with a semi-colon to match:
\s*;\s*"""
REGEX_OBJ = re.compile(REGEX_STR, re.MULTILINE| re.VERBOSE)
</code></pre>
<p>Can anyone suggest an improvement to this regular expression? It's getting too complicated for me to get my head around.</p>
| 25
|
2009-02-07T20:43:52Z
| 524,588
|
<p>I don't know that regex would handle something like that very well. Try something like this</p>
<pre><code>line = line.Trim();
if(line.StartsWith("for") && line.EndsWith(";")){
//your code here
}
</code></pre>
| 1
|
2009-02-07T21:08:02Z
|
[
"c++",
"python",
"regex",
"parsing",
"recursion"
] |
Regular expression to detect semi-colon terminated C++ for & while loops
| 524,548
|
<p>In my Python application, I need to write a regular expression that matches a C++ <code>for</code> or <code>while</code> loop that has been terminated with a semi-colon (<code>;</code>). For example, it should match this:</p>
<pre><code>for (int i = 0; i < 10; i++);
</code></pre>
<p>... but not this:</p>
<pre><code>for (int i = 0; i < 10; i++)
</code></pre>
<p>This looks trivial at first glance, until you realise that the text between the opening and closing parenthesis may contain other parenthesis, for example:</p>
<pre><code>for (int i = funcA(); i < funcB(); i++);
</code></pre>
<p>I'm using the python.re module. Right now my regular expression looks like this (I've left my comments in so you can understand it easier):</p>
<pre><code># match any line that begins with a "for" or "while" statement:
^\s*(for|while)\s*
\( # match the initial opening parenthesis
# Now make a named group 'balanced' which matches a balanced substring.
(?P<balanced>
# A balanced substring is either something that is not a parenthesis:
[^()]
| # â¦or a parenthesised string:
\( # A parenthesised string begins with an opening parenthesis
(?P=balanced)* # â¦followed by a sequence of balanced substrings
\) # â¦and ends with a closing parenthesis
)* # Look for a sequence of balanced substrings
\) # Finally, the outer closing parenthesis.
# must end with a semi-colon to match:
\s*;\s*
</code></pre>
<p>This works perfectly for all the above cases, but it breaks as soon as you try and make the third part of the for loop contain a function, like so:</p>
<pre><code>for (int i = 0; i < 10; doSomethingTo(i));
</code></pre>
<p>I think it breaks because as soon as you put some text between the opening and closing parenthesis, the "balanced" group matches that contained text, and thus the <code>(?P=balanced)</code> part doesn't work any more since it won't match (due to the fact that the text inside the parenthesis is different).</p>
<p>In my Python code I'm using the VERBOSE and MULTILINE flags, and creating the regular expression like so:</p>
<pre><code>REGEX_STR = r"""# match any line that begins with a "for" or "while" statement:
^\s*(for|while)\s*
\( # match the initial opening parenthesis
# Now make a named group 'balanced' which matches
# a balanced substring.
(?P<balanced>
# A balanced substring is either something that is not a parenthesis:
[^()]
| # â¦or a parenthesised string:
\( # A parenthesised string begins with an opening parenthesis
(?P=balanced)* # â¦followed by a sequence of balanced substrings
\) # â¦and ends with a closing parenthesis
)* # Look for a sequence of balanced substrings
\) # Finally, the outer closing parenthesis.
# must end with a semi-colon to match:
\s*;\s*"""
REGEX_OBJ = re.compile(REGEX_STR, re.MULTILINE| re.VERBOSE)
</code></pre>
<p>Can anyone suggest an improvement to this regular expression? It's getting too complicated for me to get my head around.</p>
| 25
|
2009-02-07T20:43:52Z
| 524,624
|
<p>You could write a little, very simple routine that does it, without using a regular expression:</p>
<ul>
<li>Set a position counter <code>pos</code> so that is points to just before the opening bracket after your <code>for</code> or <code>while</code>. </li>
<li>Set an open brackets counter <code>openBr</code> to <code>0</code>.</li>
<li>Now keep incrementing <code>pos</code>, reading the characters at the respective positions, and increment <code>openBr</code> when you see an opening bracket, and decrement it when you see a closing bracket. That will increment it once at the beginning, for the first opening bracket in "<code>for (</code>", increment and decrement some more for some brackets in between, and set it back to <code>0</code> when your <code>for</code> bracket closes. </li>
<li>So, stop when <code>openBr</code> is <code>0</code> again.</li>
</ul>
<p>The stopping positon is your closing bracket of <code>for(...)</code>. Now you can check if there is a semicolon following or not.</p>
| 77
|
2009-02-07T21:29:57Z
|
[
"c++",
"python",
"regex",
"parsing",
"recursion"
] |
Regular expression to detect semi-colon terminated C++ for & while loops
| 524,548
|
<p>In my Python application, I need to write a regular expression that matches a C++ <code>for</code> or <code>while</code> loop that has been terminated with a semi-colon (<code>;</code>). For example, it should match this:</p>
<pre><code>for (int i = 0; i < 10; i++);
</code></pre>
<p>... but not this:</p>
<pre><code>for (int i = 0; i < 10; i++)
</code></pre>
<p>This looks trivial at first glance, until you realise that the text between the opening and closing parenthesis may contain other parenthesis, for example:</p>
<pre><code>for (int i = funcA(); i < funcB(); i++);
</code></pre>
<p>I'm using the python.re module. Right now my regular expression looks like this (I've left my comments in so you can understand it easier):</p>
<pre><code># match any line that begins with a "for" or "while" statement:
^\s*(for|while)\s*
\( # match the initial opening parenthesis
# Now make a named group 'balanced' which matches a balanced substring.
(?P<balanced>
# A balanced substring is either something that is not a parenthesis:
[^()]
| # â¦or a parenthesised string:
\( # A parenthesised string begins with an opening parenthesis
(?P=balanced)* # â¦followed by a sequence of balanced substrings
\) # â¦and ends with a closing parenthesis
)* # Look for a sequence of balanced substrings
\) # Finally, the outer closing parenthesis.
# must end with a semi-colon to match:
\s*;\s*
</code></pre>
<p>This works perfectly for all the above cases, but it breaks as soon as you try and make the third part of the for loop contain a function, like so:</p>
<pre><code>for (int i = 0; i < 10; doSomethingTo(i));
</code></pre>
<p>I think it breaks because as soon as you put some text between the opening and closing parenthesis, the "balanced" group matches that contained text, and thus the <code>(?P=balanced)</code> part doesn't work any more since it won't match (due to the fact that the text inside the parenthesis is different).</p>
<p>In my Python code I'm using the VERBOSE and MULTILINE flags, and creating the regular expression like so:</p>
<pre><code>REGEX_STR = r"""# match any line that begins with a "for" or "while" statement:
^\s*(for|while)\s*
\( # match the initial opening parenthesis
# Now make a named group 'balanced' which matches
# a balanced substring.
(?P<balanced>
# A balanced substring is either something that is not a parenthesis:
[^()]
| # â¦or a parenthesised string:
\( # A parenthesised string begins with an opening parenthesis
(?P=balanced)* # â¦followed by a sequence of balanced substrings
\) # â¦and ends with a closing parenthesis
)* # Look for a sequence of balanced substrings
\) # Finally, the outer closing parenthesis.
# must end with a semi-colon to match:
\s*;\s*"""
REGEX_OBJ = re.compile(REGEX_STR, re.MULTILINE| re.VERBOSE)
</code></pre>
<p>Can anyone suggest an improvement to this regular expression? It's getting too complicated for me to get my head around.</p>
| 25
|
2009-02-07T20:43:52Z
| 524,677
|
<p>Another thought that ignores parentheses and treats the <code>for</code> as a construct holding three semicolon-delimited values:</p>
<pre><code>for\s*\([^;]+;[^;]+;[^;]+\)\s*;
</code></pre>
<p>This option works even when split over multiple lines (once MULTILINE enabled), but assumes that <code>for ( ... ; ... ; ... )</code> is the only valid construct, so wouldn't work with a <code>for ( x in y )</code> construct, or other deviations.</p>
<p>Also assumes that there are no functions containing semi-colons as arguments, such as:</p>
<pre><code>for ( var i = 0; i < ListLen('a;b;c',';') ; i++ );
</code></pre>
<p>Whether this is a likely case depends on what you're actually doing this for.</p>
| 1
|
2009-02-07T21:59:38Z
|
[
"c++",
"python",
"regex",
"parsing",
"recursion"
] |
Regular expression to detect semi-colon terminated C++ for & while loops
| 524,548
|
<p>In my Python application, I need to write a regular expression that matches a C++ <code>for</code> or <code>while</code> loop that has been terminated with a semi-colon (<code>;</code>). For example, it should match this:</p>
<pre><code>for (int i = 0; i < 10; i++);
</code></pre>
<p>... but not this:</p>
<pre><code>for (int i = 0; i < 10; i++)
</code></pre>
<p>This looks trivial at first glance, until you realise that the text between the opening and closing parenthesis may contain other parenthesis, for example:</p>
<pre><code>for (int i = funcA(); i < funcB(); i++);
</code></pre>
<p>I'm using the python.re module. Right now my regular expression looks like this (I've left my comments in so you can understand it easier):</p>
<pre><code># match any line that begins with a "for" or "while" statement:
^\s*(for|while)\s*
\( # match the initial opening parenthesis
# Now make a named group 'balanced' which matches a balanced substring.
(?P<balanced>
# A balanced substring is either something that is not a parenthesis:
[^()]
| # â¦or a parenthesised string:
\( # A parenthesised string begins with an opening parenthesis
(?P=balanced)* # â¦followed by a sequence of balanced substrings
\) # â¦and ends with a closing parenthesis
)* # Look for a sequence of balanced substrings
\) # Finally, the outer closing parenthesis.
# must end with a semi-colon to match:
\s*;\s*
</code></pre>
<p>This works perfectly for all the above cases, but it breaks as soon as you try and make the third part of the for loop contain a function, like so:</p>
<pre><code>for (int i = 0; i < 10; doSomethingTo(i));
</code></pre>
<p>I think it breaks because as soon as you put some text between the opening and closing parenthesis, the "balanced" group matches that contained text, and thus the <code>(?P=balanced)</code> part doesn't work any more since it won't match (due to the fact that the text inside the parenthesis is different).</p>
<p>In my Python code I'm using the VERBOSE and MULTILINE flags, and creating the regular expression like so:</p>
<pre><code>REGEX_STR = r"""# match any line that begins with a "for" or "while" statement:
^\s*(for|while)\s*
\( # match the initial opening parenthesis
# Now make a named group 'balanced' which matches
# a balanced substring.
(?P<balanced>
# A balanced substring is either something that is not a parenthesis:
[^()]
| # â¦or a parenthesised string:
\( # A parenthesised string begins with an opening parenthesis
(?P=balanced)* # â¦followed by a sequence of balanced substrings
\) # â¦and ends with a closing parenthesis
)* # Look for a sequence of balanced substrings
\) # Finally, the outer closing parenthesis.
# must end with a semi-colon to match:
\s*;\s*"""
REGEX_OBJ = re.compile(REGEX_STR, re.MULTILINE| re.VERBOSE)
</code></pre>
<p>Can anyone suggest an improvement to this regular expression? It's getting too complicated for me to get my head around.</p>
| 25
|
2009-02-07T20:43:52Z
| 524,979
|
<p>Try this regexp</p>
<pre><code>^\s*(for|while)\s*
\(
(?P<balanced>
[^()]*
|
(?P=balanced)
\)
\s*;\s
</code></pre>
<p>I removed the wrapping <code>\( \)</code> around <code>(?P=balanced)</code> and moved the <code>*</code> to behind the any not paren sequence. I have had this work with boost xpressive, and rechecked that website (<a href="http://www.boost.org/doc/libs/1_37_0/doc/html/xpressive/user_s_guide.html#boost_xpressive.user_s_guide.grammars_and_nested_matches" rel="nofollow">Xpressive</a>) to refresh my memory.</p>
| 2
|
2009-02-08T01:53:09Z
|
[
"c++",
"python",
"regex",
"parsing",
"recursion"
] |
Regular expression to detect semi-colon terminated C++ for & while loops
| 524,548
|
<p>In my Python application, I need to write a regular expression that matches a C++ <code>for</code> or <code>while</code> loop that has been terminated with a semi-colon (<code>;</code>). For example, it should match this:</p>
<pre><code>for (int i = 0; i < 10; i++);
</code></pre>
<p>... but not this:</p>
<pre><code>for (int i = 0; i < 10; i++)
</code></pre>
<p>This looks trivial at first glance, until you realise that the text between the opening and closing parenthesis may contain other parenthesis, for example:</p>
<pre><code>for (int i = funcA(); i < funcB(); i++);
</code></pre>
<p>I'm using the python.re module. Right now my regular expression looks like this (I've left my comments in so you can understand it easier):</p>
<pre><code># match any line that begins with a "for" or "while" statement:
^\s*(for|while)\s*
\( # match the initial opening parenthesis
# Now make a named group 'balanced' which matches a balanced substring.
(?P<balanced>
# A balanced substring is either something that is not a parenthesis:
[^()]
| # â¦or a parenthesised string:
\( # A parenthesised string begins with an opening parenthesis
(?P=balanced)* # â¦followed by a sequence of balanced substrings
\) # â¦and ends with a closing parenthesis
)* # Look for a sequence of balanced substrings
\) # Finally, the outer closing parenthesis.
# must end with a semi-colon to match:
\s*;\s*
</code></pre>
<p>This works perfectly for all the above cases, but it breaks as soon as you try and make the third part of the for loop contain a function, like so:</p>
<pre><code>for (int i = 0; i < 10; doSomethingTo(i));
</code></pre>
<p>I think it breaks because as soon as you put some text between the opening and closing parenthesis, the "balanced" group matches that contained text, and thus the <code>(?P=balanced)</code> part doesn't work any more since it won't match (due to the fact that the text inside the parenthesis is different).</p>
<p>In my Python code I'm using the VERBOSE and MULTILINE flags, and creating the regular expression like so:</p>
<pre><code>REGEX_STR = r"""# match any line that begins with a "for" or "while" statement:
^\s*(for|while)\s*
\( # match the initial opening parenthesis
# Now make a named group 'balanced' which matches
# a balanced substring.
(?P<balanced>
# A balanced substring is either something that is not a parenthesis:
[^()]
| # â¦or a parenthesised string:
\( # A parenthesised string begins with an opening parenthesis
(?P=balanced)* # â¦followed by a sequence of balanced substrings
\) # â¦and ends with a closing parenthesis
)* # Look for a sequence of balanced substrings
\) # Finally, the outer closing parenthesis.
# must end with a semi-colon to match:
\s*;\s*"""
REGEX_OBJ = re.compile(REGEX_STR, re.MULTILINE| re.VERBOSE)
</code></pre>
<p>Can anyone suggest an improvement to this regular expression? It's getting too complicated for me to get my head around.</p>
| 25
|
2009-02-07T20:43:52Z
| 11,725,855
|
<p>Not a Python solution (maybe you could write a wrapper...)</p>
<p>First, download lexertl (<a href="http://www.benhanson.net/lexertl.html" rel="nofollow">http:/www.benhanson.net/lexertl.html</a>), then:</p>
<pre><code>#include <algorithm>
#include "lexertl/generator.hpp"
#include <iostream>
#include "lexertl/lookup.hpp"
int main()
{
lexertl::rules rules_;
lexertl::state_machine sm_;
rules_.add_state("FW");
rules_.add_state("SEMI");
rules_.add_state("NESTED");
rules_.add("*", "[/][/].*|[/][*](.|\n)*?[*][/]|[\"](.|\\\")*[\"]",
rules_.skip(), ".");
rules_.add("INITIAL", "for\\s*\\([^;]*;[^;]*;|while\\s*\\(",
rules_.skip(), "FW");
rules_.add("FW", "\\)", rules_.skip(), "SEMI");
rules_.add("FW,NESTED", "\\(", ">NESTED");
rules_.add("NESTED", "\\)", rules_.skip(), "<");
rules_.add("SEMI", "\\s*;", 1, "INITIAL");
rules_.add("SEMI", ".|\n", rules_.skip(), "INITIAL");
lexertl::generator::build (rules_, sm_);
lexertl::memory_file buff_("main.cpp");
const char *start_ = buff_.data ();
const char *end_ = start_ + buff_.size ();
lexertl::crmatch results_(start_, end_);
do
{
lexertl::lookup(sm_, results_);
if (results_.id == 1)
{
std::cout << "found on line " <<
std::count(start_, results_.end, '\n') + 1 << '\n';
}
} while (results_.id != sm_.eoi());
return 0;
}
</code></pre>
| 1
|
2012-07-30T16:42:32Z
|
[
"c++",
"python",
"regex",
"parsing",
"recursion"
] |
Does Python have class prototypes (or forward declarations)?
| 524,714
|
<p>I have a series of Python classes in a file. Some classes reference others.</p>
<p>My code is something like this:</p>
<pre><code>class A():
pass
class B():
c = C()
class C():
pass
</code></pre>
<p>Trying to run that, I get <code>NameError: name 'C' is not defined</code>. Fair enough, but is there any way to make it work, or do I have to manually re-order my classes to accommodate? In C++, I can create a class prototype. Does Python have an equivalent?</p>
<p>(I'm actually playing with Django models, but I tried not complicate matters).</p>
| 20
|
2009-02-07T22:21:50Z
| 524,722
|
<p>In Python you don't create a prototype per se, but you do need to understand the difference between "class attributes" and instance-level attributes. In the example you've shown above, you are declaring a class attribute on class B, not an instance-level attribute.</p>
<p>This is what you are looking for:</p>
<pre><code>class B():
def __init__(self):
self.c = C()
</code></pre>
| 30
|
2009-02-07T22:27:33Z
|
[
"python",
"class",
"oop",
"prototype"
] |
Does Python have class prototypes (or forward declarations)?
| 524,714
|
<p>I have a series of Python classes in a file. Some classes reference others.</p>
<p>My code is something like this:</p>
<pre><code>class A():
pass
class B():
c = C()
class C():
pass
</code></pre>
<p>Trying to run that, I get <code>NameError: name 'C' is not defined</code>. Fair enough, but is there any way to make it work, or do I have to manually re-order my classes to accommodate? In C++, I can create a class prototype. Does Python have an equivalent?</p>
<p>(I'm actually playing with Django models, but I tried not complicate matters).</p>
| 20
|
2009-02-07T22:21:50Z
| 524,726
|
<p>This would solve your problem as presented (but I think you are really looking for an instance attribute as jholloway7 responded):</p>
<pre><code>class A:
pass
class B:
pass
class C:
pass
B.c = C()
</code></pre>
| 6
|
2009-02-07T22:30:13Z
|
[
"python",
"class",
"oop",
"prototype"
] |
Does Python have class prototypes (or forward declarations)?
| 524,714
|
<p>I have a series of Python classes in a file. Some classes reference others.</p>
<p>My code is something like this:</p>
<pre><code>class A():
pass
class B():
c = C()
class C():
pass
</code></pre>
<p>Trying to run that, I get <code>NameError: name 'C' is not defined</code>. Fair enough, but is there any way to make it work, or do I have to manually re-order my classes to accommodate? In C++, I can create a class prototype. Does Python have an equivalent?</p>
<p>(I'm actually playing with Django models, but I tried not complicate matters).</p>
| 20
|
2009-02-07T22:21:50Z
| 524,801
|
<p>All correct answers about class vs instance attributes. However, the reason you have an error is just the order of defining your classes. Of course class C has not yet been defined (as class-level code is executed immediately on import):</p>
<pre><code>class A():
pass
class C():
pass
class B():
c = C()
</code></pre>
<p>Will work.</p>
| 0
|
2009-02-07T23:19:28Z
|
[
"python",
"class",
"oop",
"prototype"
] |
Does Python have class prototypes (or forward declarations)?
| 524,714
|
<p>I have a series of Python classes in a file. Some classes reference others.</p>
<p>My code is something like this:</p>
<pre><code>class A():
pass
class B():
c = C()
class C():
pass
</code></pre>
<p>Trying to run that, I get <code>NameError: name 'C' is not defined</code>. Fair enough, but is there any way to make it work, or do I have to manually re-order my classes to accommodate? In C++, I can create a class prototype. Does Python have an equivalent?</p>
<p>(I'm actually playing with Django models, but I tried not complicate matters).</p>
| 20
|
2009-02-07T22:21:50Z
| 525,866
|
<p>Python doesn't have prototypes or Ruby-style open classes. But if you really need them, you can write a metaclass that overloads <strong>new</strong> so that it does a lookup in the current namespace to see if the class already exists, and if it does returns the existing type object rather than creating a new one. I did something like this on a ORM I write a while back and it's worked very well.</p>
| 2
|
2009-02-08T14:56:03Z
|
[
"python",
"class",
"oop",
"prototype"
] |
Does Python have class prototypes (or forward declarations)?
| 524,714
|
<p>I have a series of Python classes in a file. Some classes reference others.</p>
<p>My code is something like this:</p>
<pre><code>class A():
pass
class B():
c = C()
class C():
pass
</code></pre>
<p>Trying to run that, I get <code>NameError: name 'C' is not defined</code>. Fair enough, but is there any way to make it work, or do I have to manually re-order my classes to accommodate? In C++, I can create a class prototype. Does Python have an equivalent?</p>
<p>(I'm actually playing with Django models, but I tried not complicate matters).</p>
| 20
|
2009-02-07T22:21:50Z
| 2,330,235
|
<p>Actually, all of the above are great observations about Python, but none of them will solve your problem.</p>
<p>Django needs to introspect stuff.</p>
<p>The <em>right</em> way to do what you want is the following:</p>
<pre><code>class Car(models.Model):
manufacturer = models.ForeignKey('Manufacturer')
# ...
class Manufacturer(models.Model):
# ...
</code></pre>
<p>Note the use of the class name as a <em>string</em> rather than the literal class reference. Django offers this alternative to deal with exactly the problem that Python doesn't provide forward declarations.</p>
<p>This question reminds me of the classic support question that you should always ask any customer with an issue: "What are you <em>really</em> trying to do?"</p>
| 36
|
2010-02-24T22:45:09Z
|
[
"python",
"class",
"oop",
"prototype"
] |
python, how to tell what type of obj was returned
| 524,734
|
<p>How can i find out if the obj returned by a func is a int or something else (like a sqlite cursor)</p>
| 1
|
2009-02-07T22:39:47Z
| 524,736
|
<p>Use <code>isinstance(item, type)</code> -- for instance:</p>
<pre><code>if isinstance(foo, int):
pass # handle this case
</code></pre>
<p>However, explicit type checking is not considered a good practice in the Python world -- it means that much of the power of duck typing is lost: Something which walks and quacks like a duck should be allowed to be a duck, even if it isn't! :)</p>
| 12
|
2009-02-07T22:42:24Z
|
[
"python",
"types"
] |
python, how to tell what type of obj was returned
| 524,734
|
<p>How can i find out if the obj returned by a func is a int or something else (like a sqlite cursor)</p>
| 1
|
2009-02-07T22:39:47Z
| 524,739
|
<p>Use the built-in "type" function, e.g. type(10) -> .</p>
| -1
|
2009-02-07T22:45:43Z
|
[
"python",
"types"
] |
Python, SQLite and threading
| 524,797
|
<p>I'm working on an application that will gather data through HTTP from several places, cache the data locally and then serve it through HTTP.</p>
<p>So I was looking at the following. My application will first create several threads that will gather data at a specified interval and cache that data locally into a SQLite database. </p>
<p>Then in the main thread start a CherryPy application that will query that SQLite database and serve the data.</p>
<p>My problem is: how do I handle connections to the SQLite database from my threads and from the CherryPy application?</p>
<p>If I'd do a connection per thread to the database will I also be able to create/use an in memory database?</p>
| 7
|
2009-02-07T23:18:03Z
| 524,806
|
<p>Short answer: Don't use Sqlite3 in a threaded application.</p>
<p>Sqlite3 databases scale well for size, but rather terribly for concurrency. You will be plagued with "Database is locked" errors.</p>
<p>If you do, you will need a connection per thread, and you have to ensure that these connections clean up after themselves. This is traditionally handled using thread-local sessions, and is performed rather well (for example) using SQLAlchemy's ScopedSession. I would use this if I were you, even if you aren't using the SQLAlchemy ORM features.</p>
| 7
|
2009-02-07T23:25:02Z
|
[
"python",
"multithreading",
"sqlite"
] |
Python, SQLite and threading
| 524,797
|
<p>I'm working on an application that will gather data through HTTP from several places, cache the data locally and then serve it through HTTP.</p>
<p>So I was looking at the following. My application will first create several threads that will gather data at a specified interval and cache that data locally into a SQLite database. </p>
<p>Then in the main thread start a CherryPy application that will query that SQLite database and serve the data.</p>
<p>My problem is: how do I handle connections to the SQLite database from my threads and from the CherryPy application?</p>
<p>If I'd do a connection per thread to the database will I also be able to create/use an in memory database?</p>
| 7
|
2009-02-07T23:18:03Z
| 524,901
|
<p>"...create several threads that will gather data at a specified interval and cache that data locally into a sqlite database.
Then in the main thread start a CherryPy app that will query that sqlite db and serve the data."</p>
<p>Don't waste a lot of time on threads. The things you're describing are simply OS processes. Just start ordinary processes to do gathering and run Cherry Py.</p>
<p>You have no real use for concurrent threads in a single process for this. Gathering data at a specified interval -- when done with simple OS processes -- can be scheduled by the OS very simply. Cron, for example, does a great job of this.</p>
<p>A CherryPy App, also, is an OS process, not a single thread of some larger process.</p>
<p>Just use processes -- threads won't help you.</p>
| 2
|
2009-02-08T00:54:01Z
|
[
"python",
"multithreading",
"sqlite"
] |
Python, SQLite and threading
| 524,797
|
<p>I'm working on an application that will gather data through HTTP from several places, cache the data locally and then serve it through HTTP.</p>
<p>So I was looking at the following. My application will first create several threads that will gather data at a specified interval and cache that data locally into a SQLite database. </p>
<p>Then in the main thread start a CherryPy application that will query that SQLite database and serve the data.</p>
<p>My problem is: how do I handle connections to the SQLite database from my threads and from the CherryPy application?</p>
<p>If I'd do a connection per thread to the database will I also be able to create/use an in memory database?</p>
| 7
|
2009-02-07T23:18:03Z
| 524,937
|
<p>Depending on the application the DB could be a real overhead. If we are talking about volatile data, maybe you could skip the communication via DB completely and share the data between the <em>data gathering process</em> and the <em>data serving process(es)</em> via IPC. This is not an option if the data has to be persisted, of course.</p>
| 0
|
2009-02-08T01:21:37Z
|
[
"python",
"multithreading",
"sqlite"
] |
Python, SQLite and threading
| 524,797
|
<p>I'm working on an application that will gather data through HTTP from several places, cache the data locally and then serve it through HTTP.</p>
<p>So I was looking at the following. My application will first create several threads that will gather data at a specified interval and cache that data locally into a SQLite database. </p>
<p>Then in the main thread start a CherryPy application that will query that SQLite database and serve the data.</p>
<p>My problem is: how do I handle connections to the SQLite database from my threads and from the CherryPy application?</p>
<p>If I'd do a connection per thread to the database will I also be able to create/use an in memory database?</p>
| 7
|
2009-02-07T23:18:03Z
| 524,955
|
<p>Depending on the data rate sqlite could be exactly the correct way to do this. The entire database is locked for each write so you aren't going to scale to 1000s of simultaneous writes per second. But if you only have a few it is the safest way of assuring you don't overwrite each other. </p>
| 0
|
2009-02-08T01:33:41Z
|
[
"python",
"multithreading",
"sqlite"
] |
Python, SQLite and threading
| 524,797
|
<p>I'm working on an application that will gather data through HTTP from several places, cache the data locally and then serve it through HTTP.</p>
<p>So I was looking at the following. My application will first create several threads that will gather data at a specified interval and cache that data locally into a SQLite database. </p>
<p>Then in the main thread start a CherryPy application that will query that SQLite database and serve the data.</p>
<p>My problem is: how do I handle connections to the SQLite database from my threads and from the CherryPy application?</p>
<p>If I'd do a connection per thread to the database will I also be able to create/use an in memory database?</p>
| 7
|
2009-02-07T23:18:03Z
| 816,571
|
<p>You can use something like <a href="http://code.activestate.com/recipes/526618/" rel="nofollow">that</a>.</p>
| 3
|
2009-05-03T08:17:18Z
|
[
"python",
"multithreading",
"sqlite"
] |
Python's equivalent of $this->$varName
| 524,831
|
<p>In PHP I can do the following:</p>
<pre><code>$myVar = 'name';
print $myClass->$myVar;
// Identical to $myClass->name
</code></pre>
<p>I wish to do this in Python but can't find out how</p>
| 3
|
2009-02-08T00:17:52Z
| 524,842
|
<p>In python, it's the getattr built-in function.</p>
<pre><code>class Something( object ):
def __init__( self ):
self.a= 2
self.b= 3
x= Something()
getattr( x, 'a' )
getattr( x, 'b' )
</code></pre>
| 16
|
2009-02-08T00:21:43Z
|
[
"php",
"python"
] |
Python's equivalent of $this->$varName
| 524,831
|
<p>In PHP I can do the following:</p>
<pre><code>$myVar = 'name';
print $myClass->$myVar;
// Identical to $myClass->name
</code></pre>
<p>I wish to do this in Python but can't find out how</p>
| 3
|
2009-02-08T00:17:52Z
| 524,847
|
<p>You'll want to use the getattr builtin function.</p>
<pre><code>myvar = 'name'
//both should produce the same results
value = obj.name
value = getattr(obj, myvar)
</code></pre>
| 5
|
2009-02-08T00:24:51Z
|
[
"php",
"python"
] |
NumPy, PIL adding an image
| 524,930
|
<p>I'm trying to add two images together using NumPy and PIL. The way I would do this in <a href="http://en.wikipedia.org/wiki/MATLAB">MATLAB</a> would be something like:</p>
<pre><code>>> M1 = imread('_1.jpg');
>> M2 = imread('_2.jpg');
>> resM = M1 + M2;
>> imwrite(resM, 'res.jpg');
</code></pre>
<p>I get something like this:</p>
<p><img src="http://www.deadlink.cc/matlab.jpg" alt="alt text"></p>
<p>Using a compositing program and adding the images the MATLAB result seems to be right.</p>
<p>In Python I'm trying to do the same thing like this:</p>
<pre><code>from PIL import Image
from numpy import *
im1 = Image.open('/Users/rem7/Desktop/_1.jpg')
im2 = Image.open('/Users/rem7/Desktop/_2.jpg')
im1arr = asarray(im1)
im2arr = asarray(im2)
addition = im1arr + im2arr
resultImage = Image.fromarray(addition)
resultImage.save('/Users/rem7/Desktop/a.jpg')
</code></pre>
<p>and I get something like this:</p>
<p><img src="http://www.deadlink.cc/python.jpg" alt="alt text"></p>
<p>Why am I getting all those funky colors? I also tried using <code>ImageMath.eval("a+b", a=im1, b=im2)</code>, but I get an error about RGB unsupported.</p>
<p>I also saw that there is an <code>Image.blend()</code> but that requires an alpha.</p>
<p>What's the best way to achieve what I'm looking for?</p>
<p>Source Images (images have been removed):</p>
<p><img src="http://www.deadlink.cc/_1.jpg" alt="alt text">
<img src="http://www.deadlink.cc/_2.jpg" alt="alt text"></p>
<p>Humm, OK, well I added the source images using the add image icon and they show up when I'm editing the post, but for some reason the images don't show up in the post. </p>
<p>(images have been removed) 2013 05 09</p>
| 21
|
2009-02-08T01:15:16Z
| 524,943
|
<p>It seems the code you posted just sums up the values and values bigger than 256 are overflowing. You want something like "(a + b) / 2" or "min(a + b, 256)". The latter seems to be the way that your Matlab example does it.</p>
| 2
|
2009-02-08T01:28:27Z
|
[
"python",
"image-processing",
"numpy",
"python-imaging-library"
] |
NumPy, PIL adding an image
| 524,930
|
<p>I'm trying to add two images together using NumPy and PIL. The way I would do this in <a href="http://en.wikipedia.org/wiki/MATLAB">MATLAB</a> would be something like:</p>
<pre><code>>> M1 = imread('_1.jpg');
>> M2 = imread('_2.jpg');
>> resM = M1 + M2;
>> imwrite(resM, 'res.jpg');
</code></pre>
<p>I get something like this:</p>
<p><img src="http://www.deadlink.cc/matlab.jpg" alt="alt text"></p>
<p>Using a compositing program and adding the images the MATLAB result seems to be right.</p>
<p>In Python I'm trying to do the same thing like this:</p>
<pre><code>from PIL import Image
from numpy import *
im1 = Image.open('/Users/rem7/Desktop/_1.jpg')
im2 = Image.open('/Users/rem7/Desktop/_2.jpg')
im1arr = asarray(im1)
im2arr = asarray(im2)
addition = im1arr + im2arr
resultImage = Image.fromarray(addition)
resultImage.save('/Users/rem7/Desktop/a.jpg')
</code></pre>
<p>and I get something like this:</p>
<p><img src="http://www.deadlink.cc/python.jpg" alt="alt text"></p>
<p>Why am I getting all those funky colors? I also tried using <code>ImageMath.eval("a+b", a=im1, b=im2)</code>, but I get an error about RGB unsupported.</p>
<p>I also saw that there is an <code>Image.blend()</code> but that requires an alpha.</p>
<p>What's the best way to achieve what I'm looking for?</p>
<p>Source Images (images have been removed):</p>
<p><img src="http://www.deadlink.cc/_1.jpg" alt="alt text">
<img src="http://www.deadlink.cc/_2.jpg" alt="alt text"></p>
<p>Humm, OK, well I added the source images using the add image icon and they show up when I'm editing the post, but for some reason the images don't show up in the post. </p>
<p>(images have been removed) 2013 05 09</p>
| 21
|
2009-02-08T01:15:16Z
| 524,952
|
<p>Your sample images are not showing up form me so I am going to do a bit of guessing.</p>
<p>I can't remember exactly how the numpy to pil conversion works but there are two likely cases. I am 95% sure it is 1 but am giving 2 just in case I am wrong.
1) 1 im1Arr is a MxN array of integers (ARGB) and when you add im1arr and im2arr together you are overflowing from one channel into the next if the components b1+b2>255. I am guessing matlab represents their images as MxNx3 arrays so each color channel is separate. You can solve this by splitting the PIL image channels and then making numpy arrays</p>
<p>2) 1 im1Arr is a MxNx3 array of bytes and when you add im1arr and im2arr together you are wrapping the component around. </p>
<p>You are also going to have to rescale the range back to between 0-255 before displaying. Your choices are divide by 2, scale by 255/array.max() or do a clip. I don't know what matlab does</p>
| 0
|
2009-02-08T01:32:40Z
|
[
"python",
"image-processing",
"numpy",
"python-imaging-library"
] |
NumPy, PIL adding an image
| 524,930
|
<p>I'm trying to add two images together using NumPy and PIL. The way I would do this in <a href="http://en.wikipedia.org/wiki/MATLAB">MATLAB</a> would be something like:</p>
<pre><code>>> M1 = imread('_1.jpg');
>> M2 = imread('_2.jpg');
>> resM = M1 + M2;
>> imwrite(resM, 'res.jpg');
</code></pre>
<p>I get something like this:</p>
<p><img src="http://www.deadlink.cc/matlab.jpg" alt="alt text"></p>
<p>Using a compositing program and adding the images the MATLAB result seems to be right.</p>
<p>In Python I'm trying to do the same thing like this:</p>
<pre><code>from PIL import Image
from numpy import *
im1 = Image.open('/Users/rem7/Desktop/_1.jpg')
im2 = Image.open('/Users/rem7/Desktop/_2.jpg')
im1arr = asarray(im1)
im2arr = asarray(im2)
addition = im1arr + im2arr
resultImage = Image.fromarray(addition)
resultImage.save('/Users/rem7/Desktop/a.jpg')
</code></pre>
<p>and I get something like this:</p>
<p><img src="http://www.deadlink.cc/python.jpg" alt="alt text"></p>
<p>Why am I getting all those funky colors? I also tried using <code>ImageMath.eval("a+b", a=im1, b=im2)</code>, but I get an error about RGB unsupported.</p>
<p>I also saw that there is an <code>Image.blend()</code> but that requires an alpha.</p>
<p>What's the best way to achieve what I'm looking for?</p>
<p>Source Images (images have been removed):</p>
<p><img src="http://www.deadlink.cc/_1.jpg" alt="alt text">
<img src="http://www.deadlink.cc/_2.jpg" alt="alt text"></p>
<p>Humm, OK, well I added the source images using the add image icon and they show up when I'm editing the post, but for some reason the images don't show up in the post. </p>
<p>(images have been removed) 2013 05 09</p>
| 21
|
2009-02-08T01:15:16Z
| 525,129
|
<p>Using PIL's blend() with an alpha value of 0.5 would be equivalent to (im1arr + im2arr)/2. Blend does not require that the images have alpha layers.</p>
<p>Try this:</p>
<pre><code>from PIL import Image
im1 = Image.open('/Users/rem7/Desktop/_1.jpg')
im2 = Image.open('/Users/rem7/Desktop/_2.jpg')
Image.blend(im1,im2,0.5).save('/Users/rem7/Desktop/a.jpg')
</code></pre>
| 16
|
2009-02-08T03:58:33Z
|
[
"python",
"image-processing",
"numpy",
"python-imaging-library"
] |
NumPy, PIL adding an image
| 524,930
|
<p>I'm trying to add two images together using NumPy and PIL. The way I would do this in <a href="http://en.wikipedia.org/wiki/MATLAB">MATLAB</a> would be something like:</p>
<pre><code>>> M1 = imread('_1.jpg');
>> M2 = imread('_2.jpg');
>> resM = M1 + M2;
>> imwrite(resM, 'res.jpg');
</code></pre>
<p>I get something like this:</p>
<p><img src="http://www.deadlink.cc/matlab.jpg" alt="alt text"></p>
<p>Using a compositing program and adding the images the MATLAB result seems to be right.</p>
<p>In Python I'm trying to do the same thing like this:</p>
<pre><code>from PIL import Image
from numpy import *
im1 = Image.open('/Users/rem7/Desktop/_1.jpg')
im2 = Image.open('/Users/rem7/Desktop/_2.jpg')
im1arr = asarray(im1)
im2arr = asarray(im2)
addition = im1arr + im2arr
resultImage = Image.fromarray(addition)
resultImage.save('/Users/rem7/Desktop/a.jpg')
</code></pre>
<p>and I get something like this:</p>
<p><img src="http://www.deadlink.cc/python.jpg" alt="alt text"></p>
<p>Why am I getting all those funky colors? I also tried using <code>ImageMath.eval("a+b", a=im1, b=im2)</code>, but I get an error about RGB unsupported.</p>
<p>I also saw that there is an <code>Image.blend()</code> but that requires an alpha.</p>
<p>What's the best way to achieve what I'm looking for?</p>
<p>Source Images (images have been removed):</p>
<p><img src="http://www.deadlink.cc/_1.jpg" alt="alt text">
<img src="http://www.deadlink.cc/_2.jpg" alt="alt text"></p>
<p>Humm, OK, well I added the source images using the add image icon and they show up when I'm editing the post, but for some reason the images don't show up in the post. </p>
<p>(images have been removed) 2013 05 09</p>
| 21
|
2009-02-08T01:15:16Z
| 525,476
|
<p>To clamp numpy array values:</p>
<pre><code>>>> c = a + b
>>> c[c > 256] = 256
</code></pre>
| 1
|
2009-02-08T09:54:53Z
|
[
"python",
"image-processing",
"numpy",
"python-imaging-library"
] |
NumPy, PIL adding an image
| 524,930
|
<p>I'm trying to add two images together using NumPy and PIL. The way I would do this in <a href="http://en.wikipedia.org/wiki/MATLAB">MATLAB</a> would be something like:</p>
<pre><code>>> M1 = imread('_1.jpg');
>> M2 = imread('_2.jpg');
>> resM = M1 + M2;
>> imwrite(resM, 'res.jpg');
</code></pre>
<p>I get something like this:</p>
<p><img src="http://www.deadlink.cc/matlab.jpg" alt="alt text"></p>
<p>Using a compositing program and adding the images the MATLAB result seems to be right.</p>
<p>In Python I'm trying to do the same thing like this:</p>
<pre><code>from PIL import Image
from numpy import *
im1 = Image.open('/Users/rem7/Desktop/_1.jpg')
im2 = Image.open('/Users/rem7/Desktop/_2.jpg')
im1arr = asarray(im1)
im2arr = asarray(im2)
addition = im1arr + im2arr
resultImage = Image.fromarray(addition)
resultImage.save('/Users/rem7/Desktop/a.jpg')
</code></pre>
<p>and I get something like this:</p>
<p><img src="http://www.deadlink.cc/python.jpg" alt="alt text"></p>
<p>Why am I getting all those funky colors? I also tried using <code>ImageMath.eval("a+b", a=im1, b=im2)</code>, but I get an error about RGB unsupported.</p>
<p>I also saw that there is an <code>Image.blend()</code> but that requires an alpha.</p>
<p>What's the best way to achieve what I'm looking for?</p>
<p>Source Images (images have been removed):</p>
<p><img src="http://www.deadlink.cc/_1.jpg" alt="alt text">
<img src="http://www.deadlink.cc/_2.jpg" alt="alt text"></p>
<p>Humm, OK, well I added the source images using the add image icon and they show up when I'm editing the post, but for some reason the images don't show up in the post. </p>
<p>(images have been removed) 2013 05 09</p>
| 21
|
2009-02-08T01:15:16Z
| 526,031
|
<p>As everyone suggested already, the weird colors you're observing are overflow. And as you point out in the <a href="http://stackoverflow.com/questions/524930/numpy-pil-adding-an-image/524943#524943">comment of schnaader's answer</a> you <strong>still get overflow</strong> if you add your images like this:</p>
<pre><code>addition=(im1arr+im2arr)/2
</code></pre>
<p>The reason for this overflow is that your NumPy arrays (<em>im1arr</em> <em>im2arr</em>) are of the <strong>uint8</strong> type (i.e. 8-bit). This means each element of the array can only hold values up to 255, so when your sum exceeds 255, it loops back around 0:</p>
<pre><code>>>>array([255,10,100],dtype='uint8') + array([1,10,160],dtype='uint8')
array([ 0, 20, 4], dtype=uint8)
</code></pre>
<p>To avoid overflow, your arrays should be able to contain values beyond 255. You need to <strong>convert them to floats</strong> for instance, perform the blending operation and <strong>convert the result back to uint8</strong>:</p>
<pre><code>im1arrF = im1arr.astype('float')
im2arrF = im2arr.astype('float')
additionF = (im1arrF+im2arrF)/2
addition = additionF.astype('uint8')
</code></pre>
<p>You <strong>should not</strong> do this:</p>
<pre><code>addition = im1arr/2 + im2arr/2
</code></pre>
<p>as you lose information, by squashing the dynamic of the image (you effectively make the images 7-bit) before you perform the blending information.</p>
<p><strong>MATLAB note</strong>: the reason you don't see this problem in MATLAB, is probably because MATLAB takes care of the overflow implicitly in one of its functions.</p>
| 27
|
2009-02-08T17:05:45Z
|
[
"python",
"image-processing",
"numpy",
"python-imaging-library"
] |
Django templates: create a "back" link?
| 524,992
|
<p>I'm tooling around with <a href="http://www.djangoproject.com/">Django</a> and I'm wondering if there is a simple way to create a "back" link to the previous page using the template system.</p>
<p>I figure that in the worst case I can get this information from the request object in the view function, and pass it along to the template rendering method, but I'm hoping I can avoid all this boilerplate code somehow.</p>
<p>I've checked the Django template docs and I haven't seen anything that mentions this explicitly.</p>
| 11
|
2009-02-08T02:02:04Z
| 525,000
|
<p>Well you can enable:</p>
<pre><code>'django.core.context_processors.request',
</code></pre>
<p>in your <code>settings.TEMPLATE_CONTEXT_PROCESSORS</code> block and hook out the referrer but that's a bit nauseating and could break all over the place. </p>
<p>Most places where you'd want this (eg the edit post page on SO) you have a real object to hook on to (in that example, the post) so you can easily work out what the proper previous page should be.</p>
| 10
|
2009-02-08T02:08:27Z
|
[
"python",
"django",
"request",
"referrer"
] |
Django templates: create a "back" link?
| 524,992
|
<p>I'm tooling around with <a href="http://www.djangoproject.com/">Django</a> and I'm wondering if there is a simple way to create a "back" link to the previous page using the template system.</p>
<p>I figure that in the worst case I can get this information from the request object in the view function, and pass it along to the template rendering method, but I'm hoping I can avoid all this boilerplate code somehow.</p>
<p>I've checked the Django template docs and I haven't seen anything that mentions this explicitly.</p>
| 11
|
2009-02-08T02:02:04Z
| 657,757
|
<p>You can always use the client side option which is very simple:</p>
<pre><code><a href="javascript:history.go(1)">Back</a>
</code></pre>
| 0
|
2009-03-18T10:50:13Z
|
[
"python",
"django",
"request",
"referrer"
] |
Django templates: create a "back" link?
| 524,992
|
<p>I'm tooling around with <a href="http://www.djangoproject.com/">Django</a> and I'm wondering if there is a simple way to create a "back" link to the previous page using the template system.</p>
<p>I figure that in the worst case I can get this information from the request object in the view function, and pass it along to the template rendering method, but I'm hoping I can avoid all this boilerplate code somehow.</p>
<p>I've checked the Django template docs and I haven't seen anything that mentions this explicitly.</p>
| 11
|
2009-02-08T02:02:04Z
| 666,407
|
<p>actually it's go(-1)</p>
<p><
input type=button value="Previous Page" onClick="javascript:history.go(-1);"></p>
| 16
|
2009-03-20T14:33:04Z
|
[
"python",
"django",
"request",
"referrer"
] |
Django templates: create a "back" link?
| 524,992
|
<p>I'm tooling around with <a href="http://www.djangoproject.com/">Django</a> and I'm wondering if there is a simple way to create a "back" link to the previous page using the template system.</p>
<p>I figure that in the worst case I can get this information from the request object in the view function, and pass it along to the template rendering method, but I'm hoping I can avoid all this boilerplate code somehow.</p>
<p>I've checked the Django template docs and I haven't seen anything that mentions this explicitly.</p>
| 11
|
2009-02-08T02:02:04Z
| 26,867,597
|
<p>This solution worked out for me:</p>
<pre><code><a href="{{request.META.HTTP_REFERER}}">Go back</a>
</code></pre>
<p>But that's previously adding <code>'django.core.context_processors.request',</code> to <code>TEMPLATE_CONTEXT_PROCESSORS</code> in your project's settings.</p>
| 10
|
2014-11-11T14:49:38Z
|
[
"python",
"django",
"request",
"referrer"
] |
Django templates: create a "back" link?
| 524,992
|
<p>I'm tooling around with <a href="http://www.djangoproject.com/">Django</a> and I'm wondering if there is a simple way to create a "back" link to the previous page using the template system.</p>
<p>I figure that in the worst case I can get this information from the request object in the view function, and pass it along to the template rendering method, but I'm hoping I can avoid all this boilerplate code somehow.</p>
<p>I've checked the Django template docs and I haven't seen anything that mentions this explicitly.</p>
| 11
|
2009-02-08T02:02:04Z
| 38,895,097
|
<p>For a 'back' button in change forms for Django admin what I end up doing is a custom template filter to parse and decode the 'preserved_filters' variable in the template. I placed the following on a customized templates/admin/submit_line.html file:</p>
<pre><code><a href="../{% if original}../{% endif %}?{{ preserved_filters | decode_filter }}">
{% trans "Back" %}
</a>
</code></pre>
<p>And then created a custom template filter:</p>
<pre><code>from urllib.parse import unquote
from django import template
def decode_filter(variable):
if variable.startswith('_changelist_filters='):
return unquote(variable[20:])
return variable
register = template.Library()
register.filter('decode_filter', decode_filter)
</code></pre>
| 0
|
2016-08-11T11:27:15Z
|
[
"python",
"django",
"request",
"referrer"
] |
Django templates: create a "back" link?
| 524,992
|
<p>I'm tooling around with <a href="http://www.djangoproject.com/">Django</a> and I'm wondering if there is a simple way to create a "back" link to the previous page using the template system.</p>
<p>I figure that in the worst case I can get this information from the request object in the view function, and pass it along to the template rendering method, but I'm hoping I can avoid all this boilerplate code somehow.</p>
<p>I've checked the Django template docs and I haven't seen anything that mentions this explicitly.</p>
| 11
|
2009-02-08T02:02:04Z
| 39,746,102
|
<p>Using client side solution would be the proper solution.</p>
<pre><code><a href="javascript:history.go(-1)" class="btn btn-default">Cancel</a>
</code></pre>
| 0
|
2016-09-28T11:26:03Z
|
[
"python",
"django",
"request",
"referrer"
] |
Is there an alternative to rexec for Python sandboxing?
| 525,056
|
<p>Implementing a 'sandbox' environment in Python used to be done with the rexec module (<a href="http://docs.python.org/library/rexec.html">http://docs.python.org/library/rexec.html</a>). Unfortunately, it has been deprecated/removed due to some security vulnerabilities. Is there an alternative?</p>
<p>My goal is to have Python code execute semi-trusted Python scripts. In a perfect world, calls to any functions outside of a pre-defined set would raise exceptions. From what I've read about rexec's deprecation, this may not be possible. So I'll settle for as much as I can get. I can spawn a separate process to run the scripts, which helps a lot. But they could still abuse I/O or processor/memory resources.</p>
| 5
|
2009-02-08T02:51:32Z
| 525,091
|
<p>You might want to provide your own <code>__import__</code> to prevent inclusion of any modules you deem "abuse I/O or processor/memory resources."</p>
<p>You might want to start with <a href="http://codespeak.net/pypy/dist/pypy/doc/" rel="nofollow">pypy</a> and create your own interpreter with limitations and constraints on resource use.</p>
| 4
|
2009-02-08T03:18:33Z
|
[
"python",
"security",
"sandbox",
"rexec"
] |
Is there an alternative to rexec for Python sandboxing?
| 525,056
|
<p>Implementing a 'sandbox' environment in Python used to be done with the rexec module (<a href="http://docs.python.org/library/rexec.html">http://docs.python.org/library/rexec.html</a>). Unfortunately, it has been deprecated/removed due to some security vulnerabilities. Is there an alternative?</p>
<p>My goal is to have Python code execute semi-trusted Python scripts. In a perfect world, calls to any functions outside of a pre-defined set would raise exceptions. From what I've read about rexec's deprecation, this may not be possible. So I'll settle for as much as I can get. I can spawn a separate process to run the scripts, which helps a lot. But they could still abuse I/O or processor/memory resources.</p>
| 5
|
2009-02-08T02:51:32Z
| 525,472
|
<p>in cpython "sandboxing" for security reasons is a:
<strong>"<em>don't do that at your company kids</em>"-thing</strong>.</p>
<p>try :</p>
<ul>
<li>jython with java "sandboxing"</li>
<li>pypy -> see Answer S.Lott</li>
<li>maybe ironpython has a solution ?</li>
</ul>
<p>see <a href="http://www.wingware.com/psupport/python-manual/2.6/library/restricted.html" rel="nofollow">Warning</a>:</p>
<p><strong><em>Warning</em></strong></p>
<p>In Python 2.3 these modules have been disabled due to various known and not readily fixable security holes. The modules are still documented here to help in reading old code that uses the rexec and Bastion modules.</p>
| 2
|
2009-02-08T09:51:57Z
|
[
"python",
"security",
"sandbox",
"rexec"
] |
python coding speed and cleanest
| 525,080
|
<p>Python is pretty clean, and I can code neat apps quickly.
But I notice I have some minor error someplace and I dont find the error at compile but at run time. Then I need to change and run the script again. Is there a way to have it break and let me modify and run?</p>
<p>Also, I dislike how python has no enums. If I were to write code that needs a lot of enums and types, should I be doing it in C++? It feels like I can do it quicker in C++.</p>
| 0
|
2009-02-08T03:14:04Z
| 525,099
|
<p><strong>"I don't find the error at compile but at run time"</strong></p>
<p>Correct. True for all non-compiled interpreted languages.</p>
<p><strong>"I need to change and run the script again"</strong></p>
<p>Also correct. True for all non-compiled interpreted languages.</p>
<p><strong>"Is there a way to have it break and let me modify and run?"</strong></p>
<p>What?</p>
<p>If it's a run-time error, the script breaks, you fix it and run again.</p>
<p>If it's not a proper error, but a logic problem of some kind, then the program finishes, but doesn't work correctly. No language can anticipate what you hoped for and break for you.</p>
<p>Or perhaps you mean something else.</p>
<p><strong>"...code that needs a lot of enums"</strong></p>
<p>You'll need to provide examples of code that needs a lot of enums. I've been writing Python for years, and have no use for enums. Indeed, I've been writing C++ with no use for enums either.</p>
<p>You'll have to provide code that needs a lot of enums as a specific example. Perhaps in another question along the lines of "What's a Pythonic replacement for all these enums."</p>
<p>It's usually polymorphic class definitions, but without an example, it's hard to be sure.</p>
| 9
|
2009-02-08T03:25:30Z
|
[
"python"
] |
python coding speed and cleanest
| 525,080
|
<p>Python is pretty clean, and I can code neat apps quickly.
But I notice I have some minor error someplace and I dont find the error at compile but at run time. Then I need to change and run the script again. Is there a way to have it break and let me modify and run?</p>
<p>Also, I dislike how python has no enums. If I were to write code that needs a lot of enums and types, should I be doing it in C++? It feels like I can do it quicker in C++.</p>
| 0
|
2009-02-08T03:14:04Z
| 525,106
|
<p>Python is an interpreted language, there <em>is</em> no compile stage, at least not that is visible to the user. If you get an error, go back, modify the script, and try again. If your script has long execution time, and you don't want to stop-restart, you can try a debugger like pdb, using which you can fix some of your errors during runtime.</p>
<p>There are a large number of ways in which you can implement enums, a quick google search for "python enums" gives everything you're likely to need. However, you should look into whether or not you really need them, and if there's a better, more 'pythonic' way of doing the same thing.</p>
| 2
|
2009-02-08T03:28:24Z
|
[
"python"
] |
python coding speed and cleanest
| 525,080
|
<p>Python is pretty clean, and I can code neat apps quickly.
But I notice I have some minor error someplace and I dont find the error at compile but at run time. Then I need to change and run the script again. Is there a way to have it break and let me modify and run?</p>
<p>Also, I dislike how python has no enums. If I were to write code that needs a lot of enums and types, should I be doing it in C++? It feels like I can do it quicker in C++.</p>
| 0
|
2009-02-08T03:14:04Z
| 525,135
|
<p>With interpreted languages you have a lot of freedom. Freedom isn't free here either. While the interpreter won't torture you into dotting every i and crossing every T before it deems your code worthy of a run, it also won't try to statically analyze your code for all those problems. So you have a few choices.</p>
<p>1) {Pyflakes, pychecker, pylint} will do static analysis on your code. That settles the syntax issue mostly. </p>
<p>2) Test-driven development with nosetests or the like will help you. If you make a code change that breaks your existing code, the tests will fail and you will know about it. This is actually better than static analysis and can be as fast. If you test-first, then you will have all your code checked at <em>test</em> runtime instead of program runtime.</p>
<p>Note that with 1 & 2 in place you are a bit better off than if you had just a static-typing compiler on your side. Even so, it will not create a proof of correctness. </p>
<p>It is possible that your tests may miss some plumbing you need for the app to actually run. If that happens, you fix it by writing more tests usually. But you still need to fire up the app and bang on it to see what tests you should have written and didn't. </p>
| 3
|
2009-02-08T04:05:03Z
|
[
"python"
] |
python coding speed and cleanest
| 525,080
|
<p>Python is pretty clean, and I can code neat apps quickly.
But I notice I have some minor error someplace and I dont find the error at compile but at run time. Then I need to change and run the script again. Is there a way to have it break and let me modify and run?</p>
<p>Also, I dislike how python has no enums. If I were to write code that needs a lot of enums and types, should I be doing it in C++? It feels like I can do it quicker in C++.</p>
| 0
|
2009-02-08T03:14:04Z
| 525,196
|
<p>You might want to look into something like <a href="http://jeffwinkler.net/2006/04/27/keeping-your-nose-green/" rel="nofollow">nosey</a>, which runs your unit tests periodically when you've saved changes to a file. You could also set up a save-event trigger to run your unit tests in the background whenever you save a file (possible e.g. with Komodo Edit).</p>
<p>That said, what I do is bind the F7 key to run unit tests in the current directory and subdirectories, and the F6 key to run <a href="http://www.logilab.org/857" rel="nofollow">pylint</a> on the current file. Frequent use of these allows me to spot errors pretty quickly.</p>
| 3
|
2009-02-08T05:24:30Z
|
[
"python"
] |
pycurl and unescape
| 525,244
|
<p>curl_unescape doesnt seem to be in pycurl, what do i use instead?</p>
| 2
|
2009-02-08T06:08:00Z
| 525,271
|
<p>Have you tried <code>urllib.quote</code>?</p>
<pre><code>import urllib
print urllib.quote("some url")
some%20url
</code></pre>
<p><a href="http://docs.python.org/library/urllib.html">here's</a> the documentation</p>
| 5
|
2009-02-08T06:34:39Z
|
[
"python",
"pycurl"
] |
pycurl and unescape
| 525,244
|
<p>curl_unescape doesnt seem to be in pycurl, what do i use instead?</p>
| 2
|
2009-02-08T06:08:00Z
| 525,508
|
<p><a
href="http://curl.haxx.se/libcurl/c/curl_unescape.html"> curl_ unescape </a>
is an obsolete function. Use <a href="http://curl.haxx.se/libcurl/c/curl_easy_unescape.html" rel="nofollow"> curl_ easy_unescape </a>
instead.</p>
| 2
|
2009-02-08T10:30:13Z
|
[
"python",
"pycurl"
] |
pycurl and unescape
| 525,244
|
<p>curl_unescape doesnt seem to be in pycurl, what do i use instead?</p>
| 2
|
2009-02-08T06:08:00Z
| 9,639,360
|
<p>We are planning to release new version of pycURL in a month or two. The new version would have all features of libcurl installed on your machine. -:)</p>
| 0
|
2012-03-09T18:46:46Z
|
[
"python",
"pycurl"
] |
Python truncate lines as they are read
| 525,272
|
<p>I have an application that reads lines from a file and runs its magic on each line as it is read. Once the line is read and properly processed, I would like to delete the line from the file. A backup of the removed line is already being kept. I would like to do something like</p>
<pre><code>file = open('myfile.txt', 'rw+')
for line in file:
processLine(line)
file.truncate(line)
</code></pre>
<p>This seems like a simple problem, but I would like to do it right rather than a whole lot of complicated seek() and tell() calls.</p>
<p>Maybe all I really want to do is remove a particular line from a file.</p>
<p>After spending far to long on this problem I decided that everyone was probably right and this it just not a good way to do things. It just seemed so elegant solution. What I was looking for was something akin to a FIFO that would just let me pop lines out of a file.</p>
| 7
|
2009-02-08T06:34:52Z
| 525,287
|
<p>Truncating the file as you read it seems a bit extreme. What if your script has a bug that doesn't cause an error? In that case you'll want to restart at the beginning of your file.</p>
<p>How about having your script print the line number it breaks on and having it take a line number as a parameter so you can tell it which line to start processing from?</p>
| 4
|
2009-02-08T06:47:38Z
|
[
"python",
"file-io"
] |
Python truncate lines as they are read
| 525,272
|
<p>I have an application that reads lines from a file and runs its magic on each line as it is read. Once the line is read and properly processed, I would like to delete the line from the file. A backup of the removed line is already being kept. I would like to do something like</p>
<pre><code>file = open('myfile.txt', 'rw+')
for line in file:
processLine(line)
file.truncate(line)
</code></pre>
<p>This seems like a simple problem, but I would like to do it right rather than a whole lot of complicated seek() and tell() calls.</p>
<p>Maybe all I really want to do is remove a particular line from a file.</p>
<p>After spending far to long on this problem I decided that everyone was probably right and this it just not a good way to do things. It just seemed so elegant solution. What I was looking for was something akin to a FIFO that would just let me pop lines out of a file.</p>
| 7
|
2009-02-08T06:34:52Z
| 525,296
|
<p>First of all, calling the operation <code>truncate</code> is probably not the best pick. If I understand the problem correctly, you want to delete everything up to the current position in file. (I would expect <code>truncate</code> to cut everything from the current position up to the end of the file. This is how the standard Python <code>truncate</code> method works, at least if I Googled correctly.)</p>
<p>Second, I am not sure it is wise to modify the file while iterating on in using the <code>for</code> loop. Wouldnât it be better to save the number of lines processed and delete them after the main loop has finished, exception or not? The file iterator supports <a href="http://docs.python.org/library/fileinput.html" rel="nofollow">in-place filtering</a>, which means it should be fairly simple to drop the processed lines afterwards.</p>
<p>P.S. I donât know Python, take this with a grain of salt.</p>
| 4
|
2009-02-08T06:54:25Z
|
[
"python",
"file-io"
] |
Python truncate lines as they are read
| 525,272
|
<p>I have an application that reads lines from a file and runs its magic on each line as it is read. Once the line is read and properly processed, I would like to delete the line from the file. A backup of the removed line is already being kept. I would like to do something like</p>
<pre><code>file = open('myfile.txt', 'rw+')
for line in file:
processLine(line)
file.truncate(line)
</code></pre>
<p>This seems like a simple problem, but I would like to do it right rather than a whole lot of complicated seek() and tell() calls.</p>
<p>Maybe all I really want to do is remove a particular line from a file.</p>
<p>After spending far to long on this problem I decided that everyone was probably right and this it just not a good way to do things. It just seemed so elegant solution. What I was looking for was something akin to a FIFO that would just let me pop lines out of a file.</p>
| 7
|
2009-02-08T06:34:52Z
| 525,299
|
<p>You're better off keeping a index into the file so that you can start where you stopped last, without destroying part of the file. Something like this would work :</p>
<pre><code>try :
for index, line in enumerate(file) :
processLine(line)
except :
# Failed, start from this line number next time.
print(index)
raise
</code></pre>
| 6
|
2009-02-08T06:55:36Z
|
[
"python",
"file-io"
] |
Python truncate lines as they are read
| 525,272
|
<p>I have an application that reads lines from a file and runs its magic on each line as it is read. Once the line is read and properly processed, I would like to delete the line from the file. A backup of the removed line is already being kept. I would like to do something like</p>
<pre><code>file = open('myfile.txt', 'rw+')
for line in file:
processLine(line)
file.truncate(line)
</code></pre>
<p>This seems like a simple problem, but I would like to do it right rather than a whole lot of complicated seek() and tell() calls.</p>
<p>Maybe all I really want to do is remove a particular line from a file.</p>
<p>After spending far to long on this problem I decided that everyone was probably right and this it just not a good way to do things. It just seemed so elegant solution. What I was looking for was something akin to a FIFO that would just let me pop lines out of a file.</p>
| 7
|
2009-02-08T06:34:52Z
| 525,312
|
<h3>Remove all lines after you've done with them:</h3>
<pre><code>with open('myfile.txt', 'rw+') as file:
for line in file:
processLine(line)
file.truncate(0)
</code></pre>
<h3>Remove each line independently:</h3>
<pre><code>lines = open('myfile.txt').readlines()
for i, line in enumerate(lines[:]):
processLine(line)
del lines[i]
open('myfile.txt', 'w').writelines(lines)
</code></pre>
<h3>You can leave only those lines that cause exceptions:</h3>
<pre><code>import fileinput
for line in fileinput.input(['myfile.txt'], inplace=1):
try: processLine(line)
except:
sys.stdout.write(line) # it prints to 'myfile.txt'
</code></pre>
<p>In general, as other people already said it is a bad idea what you are trying to do.</p>
| 13
|
2009-02-08T07:08:14Z
|
[
"python",
"file-io"
] |
Python truncate lines as they are read
| 525,272
|
<p>I have an application that reads lines from a file and runs its magic on each line as it is read. Once the line is read and properly processed, I would like to delete the line from the file. A backup of the removed line is already being kept. I would like to do something like</p>
<pre><code>file = open('myfile.txt', 'rw+')
for line in file:
processLine(line)
file.truncate(line)
</code></pre>
<p>This seems like a simple problem, but I would like to do it right rather than a whole lot of complicated seek() and tell() calls.</p>
<p>Maybe all I really want to do is remove a particular line from a file.</p>
<p>After spending far to long on this problem I decided that everyone was probably right and this it just not a good way to do things. It just seemed so elegant solution. What I was looking for was something akin to a FIFO that would just let me pop lines out of a file.</p>
| 7
|
2009-02-08T06:34:52Z
| 525,454
|
<p><strong>You can't</strong>. It is just not possible with actual text file implementations on current filesystems.</p>
<p>Text files are sequential, because the lines in a text file can be of any length.
Deleting a particular line would mean rewriting the entire file from that point on.</p>
<p>Suppose you have a file with the following 3 lines;</p>
<pre><code>'line1\nline2reallybig\nline3\nlast line'
</code></pre>
<p>To delete the second line you'd have to move the third and fourth lines' positions in the disk. The only way would be to store the third and fourth lines somewhere, truncate the file on the second line, and rewrite the missing lines.</p>
<p>If you know the size of every line in the text file, you can truncate the file in any position using <code>.truncate(line_size * line_number)</code> but even then you'd have to rewrite everything after the line.</p>
| 8
|
2009-02-08T09:25:03Z
|
[
"python",
"file-io"
] |
Python truncate lines as they are read
| 525,272
|
<p>I have an application that reads lines from a file and runs its magic on each line as it is read. Once the line is read and properly processed, I would like to delete the line from the file. A backup of the removed line is already being kept. I would like to do something like</p>
<pre><code>file = open('myfile.txt', 'rw+')
for line in file:
processLine(line)
file.truncate(line)
</code></pre>
<p>This seems like a simple problem, but I would like to do it right rather than a whole lot of complicated seek() and tell() calls.</p>
<p>Maybe all I really want to do is remove a particular line from a file.</p>
<p>After spending far to long on this problem I decided that everyone was probably right and this it just not a good way to do things. It just seemed so elegant solution. What I was looking for was something akin to a FIFO that would just let me pop lines out of a file.</p>
| 7
|
2009-02-08T06:34:52Z
| 2,827,323
|
<p>A related post has what seems a good strategy to do that, see
<a href="http://stackoverflow.com/questions/366533/how-can-i-run-the-first-process-from-a-list-of-processes-stored-in-a-file-and-imm/366604#366604">http://stackoverflow.com/questions/366533/how-can-i-run-the-first-process-from-a-list-of-processes-stored-in-a-file-and-imm/366604#366604</a></p>
<p>I have used it as follows:</p>
<pre><code> import os;
tasklist_file = open(tasklist_filename, 'rw');
first_line = tasklist_file.readline();
temp = os.system("sed -i -e '1d' " + tasklist_filename); # remove first line from task file;
</code></pre>
<p>I'm not sure it works on Windows.
Tried it on a mac and it did do the trick.</p>
| 2
|
2010-05-13T13:56:53Z
|
[
"python",
"file-io"
] |
Embedding icon in .exe with py2exe, visible in Vista?
| 525,329
|
<p>I've been trying to embed an icon (.ico) into my "compyled" .exe with py2exe.</p>
<p>Py2Exe does have a way to embed an icon:</p>
<pre><code>windows=[{
'script':'MyScript.py',
'icon_resources':[(1,'MyIcon.ico')]
}]
</code></pre>
<p>And that's what I am using. The icon shows up fine on Windows XP or lower, but doesn't show at all on Vista. I suppose this is because of the new Vista icon format, which can be in PNG format, up to 256x256 pixels.</p>
<p>So, how can I get py2exe to embed them into my executable, without breaking the icons on Windows XP?</p>
<p>I'm cool with doing it with an external utility rather than py2exe - I've tried <a href="http://www.rw-designer.com/compile-vista-icon">this command-line utility</a> to embed it, but it always corrupts my exe and truncates its size for some reason.</p>
| 15
|
2009-02-08T07:26:06Z
| 525,486
|
<p>Vista uses icons of high resolution <em>256x256</em> pixels images, they are stored using <em>PNG-based</em> compression. The problem is if you simply make the icon and save it in standard XP <code>ICO</code> format, the resulting file will be <code>400Kb</code> on disk. The solution is to compress the images. The compression scheme used is <code>PNG</code> (Portable Network Graphic) because it has a good lossless ratio and supports alpha channel.</p>
<p>And use</p>
<pre><code>png2ico myicon.ico logo16x16.png logo32x32.png logo255x255.png
</code></pre>
<p>It creates an <code>ICO</code> file from 1 or more <code>PNG</code>'s and handles multiple sizes etc. And I guess XP would have no problem with that.</p>
| 19
|
2009-02-08T10:06:26Z
|
[
"python",
"windows-vista",
"embed",
"icons",
"py2exe"
] |
Embedding icon in .exe with py2exe, visible in Vista?
| 525,329
|
<p>I've been trying to embed an icon (.ico) into my "compyled" .exe with py2exe.</p>
<p>Py2Exe does have a way to embed an icon:</p>
<pre><code>windows=[{
'script':'MyScript.py',
'icon_resources':[(1,'MyIcon.ico')]
}]
</code></pre>
<p>And that's what I am using. The icon shows up fine on Windows XP or lower, but doesn't show at all on Vista. I suppose this is because of the new Vista icon format, which can be in PNG format, up to 256x256 pixels.</p>
<p>So, how can I get py2exe to embed them into my executable, without breaking the icons on Windows XP?</p>
<p>I'm cool with doing it with an external utility rather than py2exe - I've tried <a href="http://www.rw-designer.com/compile-vista-icon">this command-line utility</a> to embed it, but it always corrupts my exe and truncates its size for some reason.</p>
| 15
|
2009-02-08T07:26:06Z
| 6,198,910
|
<p>It seems that the order of icon sizes is the key, as said by Helmut.
To invert the pages (larger ones first) solves the issue on Windows 7 for 'include_resources' (using Py2exe 0.6.9).</p>
| 3
|
2011-06-01T09:21:52Z
|
[
"python",
"windows-vista",
"embed",
"icons",
"py2exe"
] |
Embedding icon in .exe with py2exe, visible in Vista?
| 525,329
|
<p>I've been trying to embed an icon (.ico) into my "compyled" .exe with py2exe.</p>
<p>Py2Exe does have a way to embed an icon:</p>
<pre><code>windows=[{
'script':'MyScript.py',
'icon_resources':[(1,'MyIcon.ico')]
}]
</code></pre>
<p>And that's what I am using. The icon shows up fine on Windows XP or lower, but doesn't show at all on Vista. I suppose this is because of the new Vista icon format, which can be in PNG format, up to 256x256 pixels.</p>
<p>So, how can I get py2exe to embed them into my executable, without breaking the icons on Windows XP?</p>
<p>I'm cool with doing it with an external utility rather than py2exe - I've tried <a href="http://www.rw-designer.com/compile-vista-icon">this command-line utility</a> to embed it, but it always corrupts my exe and truncates its size for some reason.</p>
| 15
|
2009-02-08T07:26:06Z
| 9,072,420
|
<p>The link to the Greenfish Iceon Editor Pro is broken.
I scanned the net and found <a href="http://icofx.ro/downloads.html" rel="nofollow">Download IcoFX</a>
Used the IcoFX program on my .exe file and could see that indeed it contained my icon. </p>
<p>Using the menu Image->Create Windows Icons from Image, and then accepting the choices I got a new .ico file that worked on both win7 and win xp. </p>
<p>Before that my single 48x48.ico file just didn't show up as an icon for the program. </p>
| 3
|
2012-01-30T23:38:49Z
|
[
"python",
"windows-vista",
"embed",
"icons",
"py2exe"
] |
Embedding icon in .exe with py2exe, visible in Vista?
| 525,329
|
<p>I've been trying to embed an icon (.ico) into my "compyled" .exe with py2exe.</p>
<p>Py2Exe does have a way to embed an icon:</p>
<pre><code>windows=[{
'script':'MyScript.py',
'icon_resources':[(1,'MyIcon.ico')]
}]
</code></pre>
<p>And that's what I am using. The icon shows up fine on Windows XP or lower, but doesn't show at all on Vista. I suppose this is because of the new Vista icon format, which can be in PNG format, up to 256x256 pixels.</p>
<p>So, how can I get py2exe to embed them into my executable, without breaking the icons on Windows XP?</p>
<p>I'm cool with doing it with an external utility rather than py2exe - I've tried <a href="http://www.rw-designer.com/compile-vista-icon">this command-line utility</a> to embed it, but it always corrupts my exe and truncates its size for some reason.</p>
| 15
|
2009-02-08T07:26:06Z
| 10,404,866
|
<p>I was having problems with embedding the icon resource with py2exe on Windows7 using a .ico file containing a 32x32 pixel image. I was using the same method as the original question.</p>
<p>Once compiled the icon on the exe disappears. On investigation the icon is added at index 0, according to the <a href="http://www.angusj.com/resourcehacker/" rel="nofollow">Resource Hacker</a> tool, but if I use the same tool to replace the icon it is added at index 1. Once at index 1 the icon magically appears in explorer against the exe again.</p>
<p>If desperate, you could use Resource Hacker to amend the exe post-build and it can be scripted via the command line interface but I tried the method explained above and managed to get it to work after reversing the png files like so.</p>
<pre><code>png2ico.exe myico.ico myico248x248.png myico48x48.png myico32x32.png myico16x16.png
</code></pre>
<p>By the way by adding multiple icons to the ico file you are then populating the resource at icon index 1 anyway, in this case myico248x248.png.</p>
| 2
|
2012-05-01T21:49:00Z
|
[
"python",
"windows-vista",
"embed",
"icons",
"py2exe"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.