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 |
|---|---|---|---|---|---|---|---|---|---|
Django: Dynamic LOGIN_URL variable | 1,088,913 | <p>Currently, in my <code>settings</code> module I have this:</p>
<pre><code>LOGIN_URL = '/login'
</code></pre>
<p>If I ever decide to change the login URL in <code>urls.py</code>, I'll have to change it here as well. Is there any more dynamic way of doing this?</p>
| 6 | 2009-07-06T19:55:02Z | 1,088,929 | <p>Settings <em>IS</em> where you are setting your dynamic login url. Make sure to import <code>LOGIN_URL</code> from <code>settings.py</code> in your <code>urls.py</code> and use that instead.</p>
<pre><code>from projectname.settings import LOGIN_URL
</code></pre>
| 7 | 2009-07-06T19:58:53Z | [
"python",
"django",
"django-urls"
] |
Django: Dynamic LOGIN_URL variable | 1,088,913 | <p>Currently, in my <code>settings</code> module I have this:</p>
<pre><code>LOGIN_URL = '/login'
</code></pre>
<p>If I ever decide to change the login URL in <code>urls.py</code>, I'll have to change it here as well. Is there any more dynamic way of doing this?</p>
| 6 | 2009-07-06T19:55:02Z | 1,089,677 | <p>This works for me ... with LOGIN_URL = '/accounts/login'</p>
<p><strong>If the problem is</strong> that settings.py has ...</p>
<pre><code>LOGIN_URL = '/login/' # <-- remember trailing slash!
</code></pre>
<p>... but, urls.py wants ... </p>
<pre><code>url(r'^login/$',
auth_views.login, {'template_name': '/foo.html'},
name='auth_login'),
</code></pre>
<p><strong>Then do this:</strong></p>
<pre><code># - up top in the urls.py
from django.conf import settings
# - down below, in the list of URLs ...
# - blindly remove the leading '/' & trust that you have a trailing '/'
url(r'^%s$' % settings.LOGIN_URL[1:],
auth_views.login, {'template_name': '/foo.html'},
name='auth_login'),
</code></pre>
<p>If you can't trust whomever edits your settings.py
... then check LOGIN_URL startswith a slash & snip it off, or not.
... and then check for trailing slash LOGIN_URL endswith a slash & tack it on, or not
... and and then tack on the '$'</p>
| 4 | 2009-07-06T23:31:31Z | [
"python",
"django",
"django-urls"
] |
Decorator to mark a method to be executed no more than once even if called several times | 1,089,023 | <p>I will go straight to the example:</p>
<pre><code>class Foo:
@execonce
def initialize(self):
print 'Called'
>>> f1 = Foo()
>>> f1.initialize()
Called
>>> f1.initialize()
>>> f2 = Foo()
>>> f2.initialize()
Called
>>> f2.initialize()
>>>
</code></pre>
<p>I tried to define <code>execonce</code> but could not write one that works with methods.</p>
<p>PS: I cannot define the code in <code>__init__</code> for <code>initialize</code> has to be called <em>sometime after</em> the object is initialized. cf - <a href="http://code.google.com/p/cmdln/issues/detail?id=13&can=1" rel="nofollow">cmdln issue 13</a></p>
| 4 | 2009-07-06T20:18:27Z | 1,089,052 | <pre><code>import functools
def execonce(f):
@functools.wraps(f)
def donothing(*a, **k):
pass
@functools.wraps(f)
def doit(self, *a, **k):
try:
return f(self, *a, **k)
finally:
setattr(self, f.__name__, donothing)
return doit
</code></pre>
| 6 | 2009-07-06T20:25:13Z | [
"python",
"class",
"methods",
"decorator"
] |
Decorator to mark a method to be executed no more than once even if called several times | 1,089,023 | <p>I will go straight to the example:</p>
<pre><code>class Foo:
@execonce
def initialize(self):
print 'Called'
>>> f1 = Foo()
>>> f1.initialize()
Called
>>> f1.initialize()
>>> f2 = Foo()
>>> f2.initialize()
Called
>>> f2.initialize()
>>>
</code></pre>
<p>I tried to define <code>execonce</code> but could not write one that works with methods.</p>
<p>PS: I cannot define the code in <code>__init__</code> for <code>initialize</code> has to be called <em>sometime after</em> the object is initialized. cf - <a href="http://code.google.com/p/cmdln/issues/detail?id=13&can=1" rel="nofollow">cmdln issue 13</a></p>
| 4 | 2009-07-06T20:18:27Z | 1,089,057 | <p>You could do something like this:</p>
<pre><code>class Foo:
def __init__(self):
self.initialize_called = False
def initialize(self):
if self.initalize_called:
return
self.initialize_called = True
print 'Called'
</code></pre>
<p>This is straightforward and easy to read. There is another instance variable and some code required in the <code>__init__</code> function, but it would satisfy your requirements.</p>
| 0 | 2009-07-06T20:26:35Z | [
"python",
"class",
"methods",
"decorator"
] |
Decorator to mark a method to be executed no more than once even if called several times | 1,089,023 | <p>I will go straight to the example:</p>
<pre><code>class Foo:
@execonce
def initialize(self):
print 'Called'
>>> f1 = Foo()
>>> f1.initialize()
Called
>>> f1.initialize()
>>> f2 = Foo()
>>> f2.initialize()
Called
>>> f2.initialize()
>>>
</code></pre>
<p>I tried to define <code>execonce</code> but could not write one that works with methods.</p>
<p>PS: I cannot define the code in <code>__init__</code> for <code>initialize</code> has to be called <em>sometime after</em> the object is initialized. cf - <a href="http://code.google.com/p/cmdln/issues/detail?id=13&can=1" rel="nofollow">cmdln issue 13</a></p>
| 4 | 2009-07-06T20:18:27Z | 1,089,060 | <p>try something similar to this</p>
<pre><code>def foo():
try:
foo.called
except:
print "called"
foo.called = True
</code></pre>
<p>methods and functions are objects. you can add methods and attributes on them. This can be useful for your case. If you want a decorator, just have the decorator allocate the method but first, check the flag. If the flag is found, a null method is returned and consequently executed.</p>
| 0 | 2009-07-06T20:27:08Z | [
"python",
"class",
"methods",
"decorator"
] |
Pythonic way to log specific things to a file? | 1,089,269 | <p>I understand that Python loggers cannot be instantiated directly, as the documentation suggests:</p>
<blockquote>
<p>Note that Loggers are never
instantiated directly, but always
through the module-level function
<code>logging.getLogger(name)</code></p>
</blockquote>
<p>.. which is reasonable, as you are expected <em>not</em> to create logger objects for every class/module for there is a <a href="http://stackoverflow.com/questions/401277/naming-python-loggers/402471#402471">better alternative</a>.</p>
<p>However, there are cases where I want to <em>create</em> a logger object and attach a file to it exclusively for logging some app-specific output to that file; and then close the log file.</p>
<p>For instance, I have a program that builds all packages in <a href="http://pypi.python.org/" rel="nofollow">PyPI</a>. So basically assume there is a <code>for</code> loop going over every package. Inside the loop, I want to "create" a logger, attach a file handler (eg: /var/logs/pypi/django/20090302_1324.build.log and send the output of <code>python setup.py build</code> (along with other things) to this log file. Once that is done, I want to close/destroy the logger and <code>continue</code> building other packages in similar fashion.</p>
<p>So you see .. the normal Pythonic way of calling <code>logging.getLogger</code> does not apply here. One needs to create <strong>temporary</strong> logger objects. </p>
<p>Currently, I achieve this by passing the file name itself as the logger name:</p>
<pre><code>>>> packagelog = logging.getLogger('/var/..../..34.log')
>>> # attach handler, etc..
</code></pre>
<p>I want to ask .. is there a better way to do this?</p>
| 0 | 2009-07-06T21:18:58Z | 1,089,292 | <p>Assuming you're calling to <code>setup.py build</code> as a subprocess I think you really just want output redirection, which you can get via the subprocess invocation.</p>
<pre><code>from subprocess import Popen
with open('/var/logs/pypi/django/%s.build.log' % time_str, 'w') as fh:
Popen('python setup.py build'.split(), stdout=fh, stderr=fh).communicate()
</code></pre>
<p>If you're calling <code>setup.py build</code> as a Python subroutine (i.e. importing that module and invoking it's main routine) then you could try to add another <code>logging.Handler</code> (<code>FileHandler</code>) to a logger in that module if such a logger exists.</p>
<p><strong>Update</strong></p>
<p>Per answer comment, it sounds like you just want to <a href="http://docs.python.org/library/logging.html#logging.Logger.addHandler" rel="nofollow">add a new</a> <a href="http://docs.python.org/library/logging.html#filehandler" rel="nofollow">FileHandler</a> to your current module's logger, then log things into that, then <a href="http://docs.python.org/library/logging.html#logging.Logger.removeHandler" rel="nofollow">remove it from the logger later on</a>. Is that more what you're looking for?</p>
| 0 | 2009-07-06T21:26:42Z | [
"python",
"logging"
] |
Pythonic way to log specific things to a file? | 1,089,269 | <p>I understand that Python loggers cannot be instantiated directly, as the documentation suggests:</p>
<blockquote>
<p>Note that Loggers are never
instantiated directly, but always
through the module-level function
<code>logging.getLogger(name)</code></p>
</blockquote>
<p>.. which is reasonable, as you are expected <em>not</em> to create logger objects for every class/module for there is a <a href="http://stackoverflow.com/questions/401277/naming-python-loggers/402471#402471">better alternative</a>.</p>
<p>However, there are cases where I want to <em>create</em> a logger object and attach a file to it exclusively for logging some app-specific output to that file; and then close the log file.</p>
<p>For instance, I have a program that builds all packages in <a href="http://pypi.python.org/" rel="nofollow">PyPI</a>. So basically assume there is a <code>for</code> loop going over every package. Inside the loop, I want to "create" a logger, attach a file handler (eg: /var/logs/pypi/django/20090302_1324.build.log and send the output of <code>python setup.py build</code> (along with other things) to this log file. Once that is done, I want to close/destroy the logger and <code>continue</code> building other packages in similar fashion.</p>
<p>So you see .. the normal Pythonic way of calling <code>logging.getLogger</code> does not apply here. One needs to create <strong>temporary</strong> logger objects. </p>
<p>Currently, I achieve this by passing the file name itself as the logger name:</p>
<pre><code>>>> packagelog = logging.getLogger('/var/..../..34.log')
>>> # attach handler, etc..
</code></pre>
<p>I want to ask .. is there a better way to do this?</p>
| 0 | 2009-07-06T21:18:58Z | 1,089,358 | <p>Instead of many loggers, you could use one logger and many handlers. For example:</p>
<pre><code>log = logging.getLogger(name)
while some_condition:
try:
handler = make_handler(filename)
log.addHandler(handler)
# do something and log
finally:
log.removeHandler(handler)
handler.close()
</code></pre>
| 4 | 2009-07-06T21:47:31Z | [
"python",
"logging"
] |
Pythonic way to log specific things to a file? | 1,089,269 | <p>I understand that Python loggers cannot be instantiated directly, as the documentation suggests:</p>
<blockquote>
<p>Note that Loggers are never
instantiated directly, but always
through the module-level function
<code>logging.getLogger(name)</code></p>
</blockquote>
<p>.. which is reasonable, as you are expected <em>not</em> to create logger objects for every class/module for there is a <a href="http://stackoverflow.com/questions/401277/naming-python-loggers/402471#402471">better alternative</a>.</p>
<p>However, there are cases where I want to <em>create</em> a logger object and attach a file to it exclusively for logging some app-specific output to that file; and then close the log file.</p>
<p>For instance, I have a program that builds all packages in <a href="http://pypi.python.org/" rel="nofollow">PyPI</a>. So basically assume there is a <code>for</code> loop going over every package. Inside the loop, I want to "create" a logger, attach a file handler (eg: /var/logs/pypi/django/20090302_1324.build.log and send the output of <code>python setup.py build</code> (along with other things) to this log file. Once that is done, I want to close/destroy the logger and <code>continue</code> building other packages in similar fashion.</p>
<p>So you see .. the normal Pythonic way of calling <code>logging.getLogger</code> does not apply here. One needs to create <strong>temporary</strong> logger objects. </p>
<p>Currently, I achieve this by passing the file name itself as the logger name:</p>
<pre><code>>>> packagelog = logging.getLogger('/var/..../..34.log')
>>> # attach handler, etc..
</code></pre>
<p>I want to ask .. is there a better way to do this?</p>
| 0 | 2009-07-06T21:18:58Z | 1,089,442 | <p>There are two issues here:</p>
<ol>
<li>Being able to direct output to different log files during different phases of the process.</li>
<li>Being able to redirect stdout/stderr of arbitrary commands to those same log files.</li>
</ol>
<p>For point 1, I would go along with <code>ars</code>'s answer: he's spot on about just using multiple handlers and one logger. his formatting is a little messed up so I'll reiterate below:</p>
<pre><code>logger = logging.getLogger("pypibuild")
now_as_string = datetime.datetime.utcnow().strftime("%Y%m%d_%H%M")
for package in get_pypi_packages():
fn = '/var/logs/pypi/%s/%s.log' % (package, now_as_string)
h = logging.FileHandler(fn, 'w')
logger.addHandler(h)
perform_build(package)
logger.removeHandler(h)
h.close()
</code></pre>
<p>As for point 2, the <code>perform_build()</code> step, I'll assume for simplicity's sake that we don't need to worry about a multicore environment. Then, the <code>subprocess</code> module is your friend. In the snippet below, I've left out error handling, fancy formatting and a couple of other niceties, but it should give you a fair idea.</p>
<pre><code>def perform_build(package):
logger.debug("Starting build for package %r", package)
command_line = compute_command_line_for_package(package)
process = subprocess.Popen(command_line, shell=True,
stdin=PIPE, stdout=PIPE, stderr=PIPE)
stdout, stderr = process.communicate()
logger.debug("Build stdout contents: %r", stdout)
logger.debug("Build stderr contents: %r", stderr)
logger.debug("Finished build for package %r", package)
</code></pre>
<p>That's about it.</p>
| 1 | 2009-07-06T22:11:42Z | [
"python",
"logging"
] |
How to make custom PhotoEffects in Django Photologue? | 1,089,304 | <p>I'm creating an image gallery in Django using the <a href="http://code.google.com/p/django-photologue/" rel="nofollow">Photologue</a> application. There are a number of <a href="http://code.google.com/p/django-photologue/wiki/PhotoEffect" rel="nofollow">PhotoEffects</a> that come with it. I'd like to extend these and make my own so that I can do more complicated effects such as adding drop shadows, glossy overlays, etc.</p>
<p>Is is possible to create custom effects that Photologue can then use to process images that are uploaded?</p>
| 2 | 2009-07-06T21:30:06Z | 1,089,631 | <p>Looks like you could define another preset effect in the utils file, and then import it into models.py. Then you'd want to add it as an option to the PhotoEffect class in models.py. This would of course make your Photologue a bit custom to your needs though.</p>
| 1 | 2009-07-06T23:13:11Z | [
"python",
"django",
"python-imaging-library",
"photologue"
] |
How to make custom PhotoEffects in Django Photologue? | 1,089,304 | <p>I'm creating an image gallery in Django using the <a href="http://code.google.com/p/django-photologue/" rel="nofollow">Photologue</a> application. There are a number of <a href="http://code.google.com/p/django-photologue/wiki/PhotoEffect" rel="nofollow">PhotoEffects</a> that come with it. I'd like to extend these and make my own so that I can do more complicated effects such as adding drop shadows, glossy overlays, etc.</p>
<p>Is is possible to create custom effects that Photologue can then use to process images that are uploaded?</p>
| 2 | 2009-07-06T21:30:06Z | 1,089,801 | <p>I'm the developer of Photologue. I would suggest you look at the 3.x branch of Photologue and more specifically, django-imagekit, the new Library it's based on: <a href="http://bitbucket.org/jdriscoll/django-imagekit/wiki/Home" rel="nofollow" title="django-imagekit">http://bitbucket.org/jdriscoll/django-imagekit/wiki/Home</a>. One of the goals of ImageKit was to make it easier to extend Photologue. All effects and manipulations are now implemented as "Processors" which are just a class wrapping a function that takes a PIL image, does something, and returns it. These processors are then chained together in whatever configuration you like. The 3.x branch is early and has been neglected lately (I'll spare you the excuses) but it shouldn't be hard to drop in the latest release of ImageKit and have close to feature parity with Photologue 2.x.</p>
| 2 | 2009-07-07T00:16:59Z | [
"python",
"django",
"python-imaging-library",
"photologue"
] |
Financial Charts / Graphs in Ruby or Python | 1,089,307 | <p>What are my best options for creating a financial open-high-low-close (OHLC) chart in a high level language like Ruby or Python? While there seem to be a lot of options for graphing, I haven't seen any gems or eggs with this kind of chart.</p>
<p><a href="http://en.wikipedia.org/wiki/Open-high-low-close_chart">http://en.wikipedia.org/wiki/Open-high-low-close_chart</a> (but I don't need the moving average or Bollinger bands)</p>
<p>JFreeChart can do this in Java, but I'd like to make my codebase as small and simple as possible.</p>
<p>Thanks!</p>
| 12 | 2009-07-06T21:31:21Z | 1,089,346 | <p>Have you considered using R and the <a href="http://www.quantmod.com/" rel="nofollow">quantmod</a> package? It likely provides exactly what you need.</p>
| 4 | 2009-07-06T21:43:41Z | [
"python",
"ruby",
"charts",
"graph",
"financial"
] |
Financial Charts / Graphs in Ruby or Python | 1,089,307 | <p>What are my best options for creating a financial open-high-low-close (OHLC) chart in a high level language like Ruby or Python? While there seem to be a lot of options for graphing, I haven't seen any gems or eggs with this kind of chart.</p>
<p><a href="http://en.wikipedia.org/wiki/Open-high-low-close_chart">http://en.wikipedia.org/wiki/Open-high-low-close_chart</a> (but I don't need the moving average or Bollinger bands)</p>
<p>JFreeChart can do this in Java, but I'd like to make my codebase as small and simple as possible.</p>
<p>Thanks!</p>
| 12 | 2009-07-06T21:31:21Z | 1,089,435 | <p>You can use Pylab (<code>matplotlib.finance</code>) with Python. Here are some examples: <a href="http://matplotlib.sourceforge.net/examples/pylab%5Fexamples/plotfile%5Fdemo.html">http://matplotlib.sourceforge.net/examples/pylab_examples/plotfile_demo.html</a> . There is some good material specifically on this problem in <a href="http://rads.stackoverflow.com/amzn/click/1430218436">Beginning Python Visualization</a>.</p>
<p>Update: I think you can use <a href="http://doc.astro-wise.org/matplotlib.finance.html">matplotlib.finance.candlestick</a> for the Japanese candlestick effect.</p>
| 8 | 2009-07-06T22:10:44Z | [
"python",
"ruby",
"charts",
"graph",
"financial"
] |
Financial Charts / Graphs in Ruby or Python | 1,089,307 | <p>What are my best options for creating a financial open-high-low-close (OHLC) chart in a high level language like Ruby or Python? While there seem to be a lot of options for graphing, I haven't seen any gems or eggs with this kind of chart.</p>
<p><a href="http://en.wikipedia.org/wiki/Open-high-low-close_chart">http://en.wikipedia.org/wiki/Open-high-low-close_chart</a> (but I don't need the moving average or Bollinger bands)</p>
<p>JFreeChart can do this in Java, but I'd like to make my codebase as small and simple as possible.</p>
<p>Thanks!</p>
| 12 | 2009-07-06T21:31:21Z | 1,089,511 | <p>Are you free to use JRuby instead of Ruby? That'd let you use JFreeChart, plus your code would still be in Ruby</p>
| 1 | 2009-07-06T22:32:34Z | [
"python",
"ruby",
"charts",
"graph",
"financial"
] |
Financial Charts / Graphs in Ruby or Python | 1,089,307 | <p>What are my best options for creating a financial open-high-low-close (OHLC) chart in a high level language like Ruby or Python? While there seem to be a lot of options for graphing, I haven't seen any gems or eggs with this kind of chart.</p>
<p><a href="http://en.wikipedia.org/wiki/Open-high-low-close_chart">http://en.wikipedia.org/wiki/Open-high-low-close_chart</a> (but I don't need the moving average or Bollinger bands)</p>
<p>JFreeChart can do this in Java, but I'd like to make my codebase as small and simple as possible.</p>
<p>Thanks!</p>
| 12 | 2009-07-06T21:31:21Z | 1,089,512 | <p>You can use <a href="http://matplotlib.sourceforge.net/" rel="nofollow">matplotlib</a> and the the optional <code>bottom</code> parameter of <a href="http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.bar" rel="nofollow">matplotlib.pyplot.bar</a>. You can then use line <code>plot</code> to indicate the opening and closing prices:</p>
<p>For example:</p>
<pre><code>#!/usr/bin/env python
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import lines
import random
deltas = [4, 6, 13, 18, 15, 14, 10, 13, 9, 6, 15, 9, 6, 1, 1, 2, 4, 4, 4, 4, 10, 11, 16, 17, 12, 10, 12, 15, 17, 16, 11, 10, 9, 9, 7, 10, 7, 16, 8, 12, 10, 14, 10, 15, 15, 16, 12, 8, 15, 16]
bases = [46, 49, 45, 45, 44, 49, 51, 52, 56, 58, 53, 57, 62, 63, 68, 66, 65, 66, 63, 63, 62, 61, 61, 57, 61, 64, 63, 58, 56, 56, 56, 60, 59, 54, 57, 54, 54, 50, 53, 51, 48, 43, 42, 38, 37, 39, 44, 49, 47, 43]
def rand_pt(bases, deltas):
return [random.randint(base, base + delta) for base, delta in zip(bases, deltas)]
# randomly assign opening and closing prices
openings = rand_pt(bases, deltas)
closings = rand_pt(bases, deltas)
# First we draw the bars which show the high and low prices
# bottom holds the low price while deltas holds the difference
# between high and low.
width = 0
ax = plt.axes()
rects1 = ax.bar(np.arange(50), deltas, width, color='r', bottom=bases)
# Now draw the ticks indicating the opening and closing price
for opening, closing, bar in zip(openings, closings, rects1):
x, w = bar.get_x(), 0.2
args = {
}
ax.plot((x - w, x), (opening, opening), **args)
ax.plot((x, x + w), (closing, closing), **args)
plt.show()
</code></pre>
<p>creates a plot like this:</p>
<p><img src="http://i.stack.imgur.com/4dWF7.png" alt="enter image description here"></p>
<p>Obviously, you'd want to package this up in a function that drew the plot using <code>(open, close, min, max)</code> tuples (and you probably wouldn't want to randomly assign your opening and closing prices).</p>
| 16 | 2009-07-06T22:32:49Z | [
"python",
"ruby",
"charts",
"graph",
"financial"
] |
Financial Charts / Graphs in Ruby or Python | 1,089,307 | <p>What are my best options for creating a financial open-high-low-close (OHLC) chart in a high level language like Ruby or Python? While there seem to be a lot of options for graphing, I haven't seen any gems or eggs with this kind of chart.</p>
<p><a href="http://en.wikipedia.org/wiki/Open-high-low-close_chart">http://en.wikipedia.org/wiki/Open-high-low-close_chart</a> (but I don't need the moving average or Bollinger bands)</p>
<p>JFreeChart can do this in Java, but I'd like to make my codebase as small and simple as possible.</p>
<p>Thanks!</p>
| 12 | 2009-07-06T21:31:21Z | 1,511,267 | <p>Please look at the Open Flash Chart embedding for WHIFF
<a href="http://aaron.oirt.rutgers.edu/myapp/docs/W1100%5F1600.openFlashCharts" rel="nofollow">http://aaron.oirt.rutgers.edu/myapp/docs/W1100_1600.openFlashCharts</a>
An example of a candle chart is right at the top. This would be especially
good for embedding in web pages.</p>
| 0 | 2009-10-02T19:02:08Z | [
"python",
"ruby",
"charts",
"graph",
"financial"
] |
Financial Charts / Graphs in Ruby or Python | 1,089,307 | <p>What are my best options for creating a financial open-high-low-close (OHLC) chart in a high level language like Ruby or Python? While there seem to be a lot of options for graphing, I haven't seen any gems or eggs with this kind of chart.</p>
<p><a href="http://en.wikipedia.org/wiki/Open-high-low-close_chart">http://en.wikipedia.org/wiki/Open-high-low-close_chart</a> (but I don't need the moving average or Bollinger bands)</p>
<p>JFreeChart can do this in Java, but I'd like to make my codebase as small and simple as possible.</p>
<p>Thanks!</p>
| 12 | 2009-07-06T21:31:21Z | 2,591,495 | <p>Open Flash Chart is nice choice if you like the look of examples. I've moved to JavaScript/Canvas library like <a href="http://code.google.com/p/flot/" rel="nofollow">Flot</a> for HTML embedded charts, as it is more customizable and I get desired effect without much hacking (http://itprolife.worona.eu/2009/08/scatter-chart-library-moving-to-flot.html).</p>
| 0 | 2010-04-07T10:08:44Z | [
"python",
"ruby",
"charts",
"graph",
"financial"
] |
Financial Charts / Graphs in Ruby or Python | 1,089,307 | <p>What are my best options for creating a financial open-high-low-close (OHLC) chart in a high level language like Ruby or Python? While there seem to be a lot of options for graphing, I haven't seen any gems or eggs with this kind of chart.</p>
<p><a href="http://en.wikipedia.org/wiki/Open-high-low-close_chart">http://en.wikipedia.org/wiki/Open-high-low-close_chart</a> (but I don't need the moving average or Bollinger bands)</p>
<p>JFreeChart can do this in Java, but I'd like to make my codebase as small and simple as possible.</p>
<p>Thanks!</p>
| 12 | 2009-07-06T21:31:21Z | 5,611,490 | <p>This is the stock chart I draw just days ago using Matplotlib, I've posted the source too, for your reference: <a href="http://bluegene8210.is-programmer.com/posts/25954.html" rel="nofollow">StockChart_Matplotlib</a></p>
| 0 | 2011-04-10T11:37:45Z | [
"python",
"ruby",
"charts",
"graph",
"financial"
] |
Financial Charts / Graphs in Ruby or Python | 1,089,307 | <p>What are my best options for creating a financial open-high-low-close (OHLC) chart in a high level language like Ruby or Python? While there seem to be a lot of options for graphing, I haven't seen any gems or eggs with this kind of chart.</p>
<p><a href="http://en.wikipedia.org/wiki/Open-high-low-close_chart">http://en.wikipedia.org/wiki/Open-high-low-close_chart</a> (but I don't need the moving average or Bollinger bands)</p>
<p>JFreeChart can do this in Java, but I'd like to make my codebase as small and simple as possible.</p>
<p>Thanks!</p>
| 12 | 2009-07-06T21:31:21Z | 6,272,093 | <p>Some examples about financial plots (OHLC) using matplotlib can be found here:</p>
<ul>
<li><p><a href="http://matplotlib.sourceforge.net/examples/pylab_examples/finance_demo.html" rel="nofollow">finance demo</a></p>
<pre><code>#!/usr/bin/env python
from pylab import *
from matplotlib.dates import DateFormatter, WeekdayLocator, HourLocator, \
DayLocator, MONDAY
from matplotlib.finance import quotes_historical_yahoo, candlestick,\
plot_day_summary, candlestick2
# (Year, month, day) tuples suffice as args for quotes_historical_yahoo
date1 = ( 2004, 2, 1)
date2 = ( 2004, 4, 12 )
mondays = WeekdayLocator(MONDAY) # major ticks on the mondays
alldays = DayLocator() # minor ticks on the days
weekFormatter = DateFormatter('%b %d') # Eg, Jan 12
dayFormatter = DateFormatter('%d') # Eg, 12
quotes = quotes_historical_yahoo('INTC', date1, date2)
if len(quotes) == 0:
raise SystemExit
fig = figure()
fig.subplots_adjust(bottom=0.2)
ax = fig.add_subplot(111)
ax.xaxis.set_major_locator(mondays)
ax.xaxis.set_minor_locator(alldays)
ax.xaxis.set_major_formatter(weekFormatter)
#ax.xaxis.set_minor_formatter(dayFormatter)
#plot_day_summary(ax, quotes, ticksize=3)
candlestick(ax, quotes, width=0.6)
ax.xaxis_date()
ax.autoscale_view()
setp( gca().get_xticklabels(), rotation=45, horizontalalignment='right')
show()
</code></pre></li>
</ul>
<p><img src="http://i.stack.imgur.com/Sxycb.png" alt="enter image description here"></p>
<ul>
<li><a href="http://matplotlib.sourceforge.net/examples/pylab_examples/finance_work2.html" rel="nofollow">finance work 2</a></li>
</ul>
| 4 | 2011-06-07T21:58:38Z | [
"python",
"ruby",
"charts",
"graph",
"financial"
] |
Python remove all lines which have common value in fields | 1,089,550 | <p>I have lines of data comprising of 4 fields </p>
<pre><code>aaaa bbb1 cccc dddd
aaaa bbb2 cccc dddd
aaaa bbb3 cccc eeee
aaaa bbb4 cccc ffff
aaaa bbb5 cccc gggg
aaaa bbb6 cccc dddd
</code></pre>
<p>Please bear with me.</p>
<p>The first and third field is always the same - but I don't need them, the 4th field can be the same or different. The thing is, I only want 2nd and 4th fields from lines which don't share the common field. For example like this from the above data </p>
<pre><code>bbb3 eeee
bbb4 ffff
bbb5 gggg
</code></pre>
<p>Now I don't mean deduplication as that would leave one of the entries in. If the 4th field shares a value with another line, I don't want any line which ever had that value. </p>
<p>humblest apologies once again for asking what is probably simple.</p>
| 1 | 2009-07-06T22:46:13Z | 1,089,563 | <p>Here you go:</p>
<pre><code>from collections import defaultdict
LINES = """\
aaaa bbb1 cccc dddd
aaaa bbb2 cccc dddd
aaaa bbb3 cccc eeee
aaaa bbb4 cccc ffff
aaaa bbb5 cccc gggg
aaaa bbb6 cccc dddd""".split('\n')
# Count how many lines each unique value of the fourth field appears in.
d_counts = defaultdict(int)
for line in LINES:
a, b, c, d = line.split()
d_counts[d] += 1
# Print only those lines with a unique value for the fourth field.
for line in LINES:
a, b, c, d = line.split()
if d_counts[d] == 1:
print b, d
# Prints
# bbb3 eeee
# bbb4 ffff
# bbb5 gggg
</code></pre>
| 6 | 2009-07-06T22:50:32Z | [
"python",
"duplicate-removal"
] |
Python remove all lines which have common value in fields | 1,089,550 | <p>I have lines of data comprising of 4 fields </p>
<pre><code>aaaa bbb1 cccc dddd
aaaa bbb2 cccc dddd
aaaa bbb3 cccc eeee
aaaa bbb4 cccc ffff
aaaa bbb5 cccc gggg
aaaa bbb6 cccc dddd
</code></pre>
<p>Please bear with me.</p>
<p>The first and third field is always the same - but I don't need them, the 4th field can be the same or different. The thing is, I only want 2nd and 4th fields from lines which don't share the common field. For example like this from the above data </p>
<pre><code>bbb3 eeee
bbb4 ffff
bbb5 gggg
</code></pre>
<p>Now I don't mean deduplication as that would leave one of the entries in. If the 4th field shares a value with another line, I don't want any line which ever had that value. </p>
<p>humblest apologies once again for asking what is probably simple.</p>
| 1 | 2009-07-06T22:46:13Z | 1,090,462 | <p>For your amplified requirement, you can avoid reading the file twice or saving it in a list:</p>
<pre><code>LINES = """\
aaaa bbb1 cccc dddd
aaaa bbb2 cccc dddd
aaaa bbb3 cccc eeee
aaaa bbb4 cccc ffff
aaaa bbb5 cccc gggg
aaaa bbb6 cccc dddd""".split('\n')
import collections
adict = collections.defaultdict(list)
for line in LINES: # or file ...
a, b, c, d = line.split()
adict[d].append(b)
map_b_to_d = dict((blist[0], d) for d, blist in adict.items() if len(blist) == 1)
print(map_b_to_d)
# alternative; saves some memory
xdict = {}
duplicated = object()
for line in LINES: # or file ...
a, b, c, d = line.split()
xdict[d] = duplicated if d in xdict else b
map_b_to_d2 = dict((b, d) for d, b in xdict.items() if b is not duplicated)
print(map_b_to_d2)
</code></pre>
| 0 | 2009-07-07T05:16:01Z | [
"python",
"duplicate-removal"
] |
Sending an email from Pylons | 1,089,576 | <p>I am using Pylons to develop an application and I want my controller actions to send emails to certain addresses. Is there a built in Pylons feature for sending email?</p>
| 4 | 2009-07-06T22:55:20Z | 1,089,588 | <p>Can't you just use standard Python library modules, <code>email</code> to prepare the mail and <code>smtp</code> to send it? What extra value beyond that are you looking for from the "built-in feature"?</p>
| 2 | 2009-07-06T22:59:13Z | [
"python",
"pylons"
] |
Sending an email from Pylons | 1,089,576 | <p>I am using Pylons to develop an application and I want my controller actions to send emails to certain addresses. Is there a built in Pylons feature for sending email?</p>
| 4 | 2009-07-06T22:55:20Z | 1,089,592 | <p>Try this: <a href="http://jjinux.blogspot.com/2009/02/python-logging-to-email-in-pylons.html" rel="nofollow">http://jjinux.blogspot.com/2009/02/python-logging-to-email-in-pylons.html</a></p>
| 2 | 2009-07-06T23:00:07Z | [
"python",
"pylons"
] |
Sending an email from Pylons | 1,089,576 | <p>I am using Pylons to develop an application and I want my controller actions to send emails to certain addresses. Is there a built in Pylons feature for sending email?</p>
| 4 | 2009-07-06T22:55:20Z | 1,224,696 | <p>What you want is <a href="http://www.python-turbomail.org/" rel="nofollow">turbomail</a>. In documentation you have an entry where is explains how to integrate it with Pylons.</p>
| 5 | 2009-08-03T21:20:25Z | [
"python",
"pylons"
] |
Python: Inflate and Deflate implementations | 1,089,662 | <p>I am interfacing with a server that requires that data sent to it is compressed with <em>Deflate</em> algorithm (Huffman encoding + LZ77) and also sends data that I need to <em>Inflate</em>. </p>
<p>I know that Python includes Zlib, and that the C libraries in Zlib support calls to <em>Inflate</em> and <em>Deflate</em>, but these apparently are not provided by the Python Zlib module. It does provide <em>Compress</em> and <em>Decompress</em>, but when I make a call such as the following:</p>
<pre><code>result_data = zlib.decompress( base64_decoded_compressed_string )
</code></pre>
<p>I receive the following error:</p>
<pre><code>Error -3 while decompressing data: incorrect header check
</code></pre>
<p>Gzip does no better; when making a call such as:</p>
<pre><code>result_data = gzip.GzipFile( fileobj = StringIO.StringIO( base64_decoded_compressed_string ) ).read()
</code></pre>
<p>I receive the error:</p>
<pre><code>IOError: Not a gzipped file
</code></pre>
<p>which makes sense as the data is a <em>Deflated</em> file not a true <em>Gzipped</em> file.</p>
<p>Now I know that there is a <em>Deflate</em> implementation available (Pyflate), but I do not know of an <em>Inflate</em> implementation.</p>
<p>It seems that there are a few options:
<br/>1. <strong>Find an existing implementation (ideal) of <em>Inflate</em> and <em>Deflate</em> in Python</strong>
<br/>2. Write my own Python extension to the zlib c library that includes <em>Inflate</em> and <em>Deflate</em>
<br/>3. Call something else that can be executed from the command line (such as a Ruby script, since <em>Inflate</em>/<em>Deflate</em> calls in zlib are fully wrapped in Ruby)
<br/>4. ?</p>
<p>I am seeking a solution, but lacking a solution I will be thankful for insights, constructive opinions, and ideas.</p>
<p><strong>Additional information</strong>:
The result of deflating (and encoding) a string should, for the purposes I need, give the same result as the following snippet of C# code, where the input parameter is an array of UTF bytes corresponding to the data to compress:</p>
<pre><code>public static string DeflateAndEncodeBase64(byte[] data)
{
if (null == data || data.Length < 1) return null;
string compressedBase64 = "";
//write into a new memory stream wrapped by a deflate stream
using (MemoryStream ms = new MemoryStream())
{
using (DeflateStream deflateStream = new DeflateStream(ms, CompressionMode.Compress, true))
{
//write byte buffer into memorystream
deflateStream.Write(data, 0, data.Length);
deflateStream.Close();
//rewind memory stream and write to base 64 string
byte[] compressedBytes = new byte[ms.Length];
ms.Seek(0, SeekOrigin.Begin);
ms.Read(compressedBytes, 0, (int)ms.Length);
compressedBase64 = Convert.ToBase64String(compressedBytes);
}
}
return compressedBase64;
}
</code></pre>
<p>Running this .NET code for the string "deflate and encode me" gives the result "7b0HYBxJliUmL23Ke39K9UrX4HShCIBgEyTYkEAQ7MGIzeaS7B1pRyMpqyqBymVWZV1mFkDM7Z28995777333nvvvfe6O51OJ/ff/z9cZmQBbPbOStrJniGAqsgfP358Hz8iZvl5mbV5mi1nab6cVrM8XeT/Dw=="</p>
<p>When "deflate and encode me" is run through the Python Zlib.compress() and then base64 encoded, the result is "eJxLSU3LSSxJVUjMS1FIzUvOT0lVyE0FAFXHB6k=". </p>
<p>It is clear that zlib.compress() is not an implementation of the same algorithm as the standard Deflate algorithm.</p>
<p><strong>More Information</strong>:</p>
<p>The first 2 bytes of the .NET deflate data ("7b0HY..."), after b64 decoding are 0xEDBD, which does not correspond to Gzip data (0x1f8b), BZip2 (0x425A) data, or Zlib (0x789C) data.</p>
<p>The first 2 bytes of the Python compressed data ("eJxLS..."), after b64 decoding are 0x789C. This is a Zlib header.</p>
<p><strong>SOLVED</strong>
<br/>To handle the raw deflate and inflate, without header and checksum, the following things needed to happen:</p>
<p>On deflate/compress: strip the first two bytes (header) and the last four bytes (checksum).
<br/>
On inflate/decompress: there is a second argument for window size. If this value is negative it suppresses headers.
<br/>
here are my methods currently, including the base64 encoding/decoding - and working properly:</p>
<pre><code>import zlib
import base64
def decode_base64_and_inflate( b64string ):
decoded_data = base64.b64decode( b64string )
return zlib.decompress( decoded_data , -15)
def deflate_and_base64_encode( string_val ):
zlibbed_str = zlib.compress( string_val )
compressed_string = zlibbed_str[2:-4]
return base64.b64encode( compressed_string )
</code></pre>
| 32 | 2009-07-06T23:24:10Z | 1,089,787 | <p>You can still use the <a href="https://docs.python.org/2/library/zlib.html"><code>zlib</code></a> module to inflate/deflate data. The <a href="https://docs.python.org/2/library/gzip.html"><code>gzip</code></a> module uses it internally, but adds a file-header to make it into a gzip-file. Looking at the <a href="http://hg.python.org/cpython/file/8ebda8114e97/Lib/gzip.py"><code>gzip.py</code></a> file, something like this could work:</p>
<pre><code>import zlib
def deflate(data, compresslevel=9):
compress = zlib.compressobj(
compresslevel, # level: 0-9
zlib.DEFLATED, # method: must be DEFLATED
-zlib.MAX_WBITS, # window size in bits:
# -15..-8: negate, suppress header
# 8..15: normal
# 16..30: subtract 16, gzip header
zlib.DEF_MEM_LEVEL, # mem level: 1..8/9
0 # strategy:
# 0 = Z_DEFAULT_STRATEGY
# 1 = Z_FILTERED
# 2 = Z_HUFFMAN_ONLY
# 3 = Z_RLE
# 4 = Z_FIXED
)
deflated = compress.compress(data)
deflated += compress.flush()
return deflated
def inflate(data):
decompress = zlib.decompressobj(
-zlib.MAX_WBITS # see above
)
inflated = decompress.decompress(data)
inflated += decompress.flush()
return inflated
</code></pre>
<p>I don't know if this corresponds exactly to whatever your server requires, but those two functions are able to round-trip any data I tried.</p>
<p>The parameters maps directly to what is passed to the zlib library functions.</p>
<p><strong>Python</strong> ⇒ <strong>C</strong><br>
<code>zlib.compressobj(...)</code> ⇒ <code>deflateInit(...)</code><br>
<code>compressobj.compress(...)</code> ⇒ <code>deflate(...)</code><br>
<code>zlib.decompressobj(...)</code> ⇒ <code>inflateInit(...)</code><br>
<code>decompressobj.decompress(...)</code> ⇒ <code>inflate(...)</code></p>
<p>The constructors create the structure and populate it with default values, and pass it along to the init-functions.
The <code>compress</code>/<code>decompress</code> methods update the structure and pass it to <code>inflate</code>/<code>deflate</code>.</p>
| 16 | 2009-07-07T00:12:26Z | [
"c#",
"python",
"compression",
"zlib"
] |
Python: Inflate and Deflate implementations | 1,089,662 | <p>I am interfacing with a server that requires that data sent to it is compressed with <em>Deflate</em> algorithm (Huffman encoding + LZ77) and also sends data that I need to <em>Inflate</em>. </p>
<p>I know that Python includes Zlib, and that the C libraries in Zlib support calls to <em>Inflate</em> and <em>Deflate</em>, but these apparently are not provided by the Python Zlib module. It does provide <em>Compress</em> and <em>Decompress</em>, but when I make a call such as the following:</p>
<pre><code>result_data = zlib.decompress( base64_decoded_compressed_string )
</code></pre>
<p>I receive the following error:</p>
<pre><code>Error -3 while decompressing data: incorrect header check
</code></pre>
<p>Gzip does no better; when making a call such as:</p>
<pre><code>result_data = gzip.GzipFile( fileobj = StringIO.StringIO( base64_decoded_compressed_string ) ).read()
</code></pre>
<p>I receive the error:</p>
<pre><code>IOError: Not a gzipped file
</code></pre>
<p>which makes sense as the data is a <em>Deflated</em> file not a true <em>Gzipped</em> file.</p>
<p>Now I know that there is a <em>Deflate</em> implementation available (Pyflate), but I do not know of an <em>Inflate</em> implementation.</p>
<p>It seems that there are a few options:
<br/>1. <strong>Find an existing implementation (ideal) of <em>Inflate</em> and <em>Deflate</em> in Python</strong>
<br/>2. Write my own Python extension to the zlib c library that includes <em>Inflate</em> and <em>Deflate</em>
<br/>3. Call something else that can be executed from the command line (such as a Ruby script, since <em>Inflate</em>/<em>Deflate</em> calls in zlib are fully wrapped in Ruby)
<br/>4. ?</p>
<p>I am seeking a solution, but lacking a solution I will be thankful for insights, constructive opinions, and ideas.</p>
<p><strong>Additional information</strong>:
The result of deflating (and encoding) a string should, for the purposes I need, give the same result as the following snippet of C# code, where the input parameter is an array of UTF bytes corresponding to the data to compress:</p>
<pre><code>public static string DeflateAndEncodeBase64(byte[] data)
{
if (null == data || data.Length < 1) return null;
string compressedBase64 = "";
//write into a new memory stream wrapped by a deflate stream
using (MemoryStream ms = new MemoryStream())
{
using (DeflateStream deflateStream = new DeflateStream(ms, CompressionMode.Compress, true))
{
//write byte buffer into memorystream
deflateStream.Write(data, 0, data.Length);
deflateStream.Close();
//rewind memory stream and write to base 64 string
byte[] compressedBytes = new byte[ms.Length];
ms.Seek(0, SeekOrigin.Begin);
ms.Read(compressedBytes, 0, (int)ms.Length);
compressedBase64 = Convert.ToBase64String(compressedBytes);
}
}
return compressedBase64;
}
</code></pre>
<p>Running this .NET code for the string "deflate and encode me" gives the result "7b0HYBxJliUmL23Ke39K9UrX4HShCIBgEyTYkEAQ7MGIzeaS7B1pRyMpqyqBymVWZV1mFkDM7Z28995777333nvvvfe6O51OJ/ff/z9cZmQBbPbOStrJniGAqsgfP358Hz8iZvl5mbV5mi1nab6cVrM8XeT/Dw=="</p>
<p>When "deflate and encode me" is run through the Python Zlib.compress() and then base64 encoded, the result is "eJxLSU3LSSxJVUjMS1FIzUvOT0lVyE0FAFXHB6k=". </p>
<p>It is clear that zlib.compress() is not an implementation of the same algorithm as the standard Deflate algorithm.</p>
<p><strong>More Information</strong>:</p>
<p>The first 2 bytes of the .NET deflate data ("7b0HY..."), after b64 decoding are 0xEDBD, which does not correspond to Gzip data (0x1f8b), BZip2 (0x425A) data, or Zlib (0x789C) data.</p>
<p>The first 2 bytes of the Python compressed data ("eJxLS..."), after b64 decoding are 0x789C. This is a Zlib header.</p>
<p><strong>SOLVED</strong>
<br/>To handle the raw deflate and inflate, without header and checksum, the following things needed to happen:</p>
<p>On deflate/compress: strip the first two bytes (header) and the last four bytes (checksum).
<br/>
On inflate/decompress: there is a second argument for window size. If this value is negative it suppresses headers.
<br/>
here are my methods currently, including the base64 encoding/decoding - and working properly:</p>
<pre><code>import zlib
import base64
def decode_base64_and_inflate( b64string ):
decoded_data = base64.b64decode( b64string )
return zlib.decompress( decoded_data , -15)
def deflate_and_base64_encode( string_val ):
zlibbed_str = zlib.compress( string_val )
compressed_string = zlibbed_str[2:-4]
return base64.b64encode( compressed_string )
</code></pre>
| 32 | 2009-07-06T23:24:10Z | 1,090,361 | <p>This is an add-on to MizardX's answer, giving some explanation and background.</p>
<p>See <a href="http://www.chiramattel.com/george/blog/2007/09/09/deflatestream-block-length-does-not-match.html" rel="nofollow">http://www.chiramattel.com/george/blog/2007/09/09/deflatestream-block-length-does-not-match.html</a></p>
<p>According to <a href="http://www.ietf.org/rfc/rfc1950.txt" rel="nofollow">RFC 1950</a>, a zlib stream constructed in the default manner is composed of:</p>
<ul>
<li>a 2-byte header (e.g. 0x78 0x9C) </li>
<li>a deflate stream -- see <a href="http://www.ietf.org/rfc/rfc1951.txt" rel="nofollow">RFC 1951</a> </li>
<li>an Adler-32 checksum of the uncompressed data (4 bytes) </li>
</ul>
<p>The C# <code>DeflateStream</code> works on (you guessed it) a deflate stream. MizardX's code is telling the zlib module that the data is a raw deflate stream.</p>
<p>Observations: (1) One hopes the C# "deflation" method producing a longer string happens only with short input (2) Using the raw deflate stream without the Adler-32 checksum? Bit risky, unless replaced with something better.</p>
<p><strong>Updates</strong></p>
<p><strong>error message <code>Block length does not match with its complement</code></strong></p>
<p>If you are trying to inflate some compressed data with the C# <code>DeflateStream</code> and you get that message, then it is quite possible that you are giving it a a zlib stream, not a deflate stream. </p>
<p>See <a href="http://stackoverflow.com/q/762614/12892">How do you use a DeflateStream on part of a file?</a></p>
<p>Also copy/paste the error message into a Google search and you will get numerous hits (including the one up the front of this answer) saying much the same thing.</p>
<p><strong>The Java <a href="http://docs.oracle.com/javase/1.5.0/docs/api/java/util/zip/Deflater.html" rel="nofollow"><code>Deflater</code></a></strong> ... used by "the website" ... C# DeflateStream "is pretty straightforward and has been tested against the Java implementation". Which of the following possible Java Deflater constructors is the website using?</p>
<blockquote>
<p><code>public Deflater(int level, boolean nowrap)</code></p>
<p>Creates a new compressor using the specified compression level. If 'nowrap' is true then the ZLIB header and checksum fields will not be used in order to support the compression format used in both GZIP and PKZIP.</p>
<p><code>public Deflater(int level)</code></p>
<p>Creates a new compressor using the specified compression level. Compressed data will be generated in ZLIB format.</p>
<p><code>public Deflater()</code></p>
<p>Creates a new compressor with the default compression level. Compressed data will be generated in ZLIB format. </p>
</blockquote>
<p><strong>A one-line deflater</strong> after throwing away the 2-byte zlib header and the 4-byte checksum:
</p>
<pre><code>uncompressed_string.encode('zlib')[2:-4] # does not work in Python 3.x
</code></pre>
<p>or
</p>
<pre><code>zlib.compress(uncompressed_string)[2:-4]
</code></pre>
| 13 | 2009-07-07T04:31:48Z | [
"c#",
"python",
"compression",
"zlib"
] |
Is & faster than % when checking for odd numbers? | 1,089,936 | <p>To check for odd and even integer, is the lowest bit checking more efficient than using the modulo?</p>
<pre><code>>>> def isodd(num):
return num & 1 and True or False
>>> isodd(10)
False
>>> isodd(9)
True
</code></pre>
| 23 | 2009-07-07T01:26:42Z | 1,089,945 | <p>Yep. The <code>timeit</code> module in the standard library is how you check on those things. E.g:</p>
<pre><code>AmAir:stko aleax$ python -mtimeit -s'def isodd(x): x & 1' 'isodd(9)'
1000000 loops, best of 3: 0.446 usec per loop
AmAir:stko aleax$ python -mtimeit -s'def isodd(x): x & 1' 'isodd(10)'
1000000 loops, best of 3: 0.443 usec per loop
AmAir:stko aleax$ python -mtimeit -s'def isodd(x): x % 2' 'isodd(10)'
1000000 loops, best of 3: 0.453 usec per loop
AmAir:stko aleax$ python -mtimeit -s'def isodd(x): x % 2' 'isodd(9)'
1000000 loops, best of 3: 0.461 usec per loop
</code></pre>
<p>As you see, on my (first-day==old==slow;-) Macbook Air, the <code>&</code> solution is repeatably between 7 and 18 nanoseconds faster than the <code>%</code> solution.</p>
<p><code>timeit</code> not only tells you what's faster, but by how much (just run the tests a few times), which usually shows how supremely UNimportant it is (do you <em>really</em> care about 10 nanoseconds' difference, when the overhead of calling the function is around 400?!-)...</p>
<p>Convincing programmers that micro-optimizations are essentially irrelevant has proven to be an impossible task -- even though it's been 35 years (over which computers have gotten orders of magnitude faster!) since Knuth <a href="http://pplab.snu.ac.kr/courses/adv%5Fpl05/papers/p261-knuth.pdf">wrote</a></p>
<blockquote>
<p>We should forget about small
efficiencies, say about 97% of the
time: premature optimization is the
root of all evil.</p>
</blockquote>
<p>which as he explained is a quote from an even older statement from Hoare. I guess everybody's totally convinced that THEIR case falls in the remaining 3%!</p>
<p>So instead of endlessly repeating "it doesn't matter", we (Tim Peters in particular deserves the honors there) put in the standard Python library module <code>timeit</code>, that makes it trivially easy to measure such micro-benchmarks and thereby lets at least <em>some</em> programmers convince themselves that, hmmm, this case DOES fall in the 97% group!-)</p>
| 53 | 2009-07-07T01:28:58Z | [
"python",
"performance",
"bit-manipulation",
"modulo"
] |
Is & faster than % when checking for odd numbers? | 1,089,936 | <p>To check for odd and even integer, is the lowest bit checking more efficient than using the modulo?</p>
<pre><code>>>> def isodd(num):
return num & 1 and True or False
>>> isodd(10)
False
>>> isodd(9)
True
</code></pre>
| 23 | 2009-07-07T01:26:42Z | 1,089,949 | <p>To be totally honest, <strong>I don't think it matters.</strong></p>
<p>The first issue is readability. What makes more sense to other developers? I, personally, would expect a modulo when checking the evenness/oddness of a number. I would expect that most other developers would expect the same thing. By introducing a different, and unexpected, method, you might make code reading, and therefore maintenance, more difficult.</p>
<p>The second is just a fact that you probably won't ever have a bottleneck when doing either operation. I'm for optimization, but early optimization is the worst thing you can do in any language or environment. If, for some reason, determining if a number is even or odd is a bottleneck, then find the fastest way of solving the problem. However, this brings me back to my first point - the first time you write a routine, it should be written in the most readable way possible.</p>
| 23 | 2009-07-07T01:30:52Z | [
"python",
"performance",
"bit-manipulation",
"modulo"
] |
Is & faster than % when checking for odd numbers? | 1,089,936 | <p>To check for odd and even integer, is the lowest bit checking more efficient than using the modulo?</p>
<pre><code>>>> def isodd(num):
return num & 1 and True or False
>>> isodd(10)
False
>>> isodd(9)
True
</code></pre>
| 23 | 2009-07-07T01:26:42Z | 1,089,970 | <p>"return num & 1 and True or False" ? Wah! If you're speed-crazy (1) "return num & 1" (2) inline it: <code>if somenumber % 2 == 1</code> is legible AND beats <code>isodd(somenumber)</code> because it avoids the Python function call.</p>
| 4 | 2009-07-07T01:37:53Z | [
"python",
"performance",
"bit-manipulation",
"modulo"
] |
Is & faster than % when checking for odd numbers? | 1,089,936 | <p>To check for odd and even integer, is the lowest bit checking more efficient than using the modulo?</p>
<pre><code>>>> def isodd(num):
return num & 1 and True or False
>>> isodd(10)
False
>>> isodd(9)
True
</code></pre>
| 23 | 2009-07-07T01:26:42Z | 1,090,020 | <p>John brings up a good point. The real overhead is in the function call:</p>
<pre><code>me@localhost ~> python -mtimeit -s'9 % 2'
10000000 loops, best of 3: 0.0271 usec per loop
me@localhost ~> python -mtimeit -s'10 % 2'
10000000 loops, best of 3: 0.0271 usec per loop
me@localhost ~> python -mtimeit -s'9 & 1'
10000000 loops, best of 3: 0.0271 usec per loop
me@localhost ~> python -mtimeit -s'9 & 1'
10000000 loops, best of 3: 0.0271 usec per loop
me@localhost ~> python -mtimeit -s'def isodd(x): x % 2' 'isodd(10)'
1000000 loops, best of 3: 0.334 usec per loop
me@localhost ~> python -mtimeit -s'def isodd(x): x % 2' 'isodd(9)'
1000000 loops, best of 3: 0.358 usec per loop
me@localhost ~> python -mtimeit -s'def isodd(x): x & 1' 'isodd(10)'
1000000 loops, best of 3: 0.317 usec per loop
me@localhost ~> python -mtimeit -s'def isodd(x): x & 1' 'isodd(9)'
1000000 loops, best of 3: 0.319 usec per loop
</code></pre>
<p>Interestingly both methods remore the same time without the function call. </p>
| 3 | 2009-07-07T01:56:27Z | [
"python",
"performance",
"bit-manipulation",
"modulo"
] |
Is & faster than % when checking for odd numbers? | 1,089,936 | <p>To check for odd and even integer, is the lowest bit checking more efficient than using the modulo?</p>
<pre><code>>>> def isodd(num):
return num & 1 and True or False
>>> isodd(10)
False
>>> isodd(9)
True
</code></pre>
| 23 | 2009-07-07T01:26:42Z | 1,090,027 | <p>The best optimization you can get is to <em>not</em> put the test into a function. '<code>number % 2</code>' and 'number & 1' are very common ways of checking odd/evenness, experienced programmers will recognize the pattern instantly, and you can always throw in a comment such as '# if number is odd, then blah blah blah' if you really need it to be obvious.</p>
<pre><code># state whether number is odd or even
if number & 1:
print "Your number is odd"
else:
print "Your number is even"
</code></pre>
| 10 | 2009-07-07T02:00:48Z | [
"python",
"performance",
"bit-manipulation",
"modulo"
] |
Is & faster than % when checking for odd numbers? | 1,089,936 | <p>To check for odd and even integer, is the lowest bit checking more efficient than using the modulo?</p>
<pre><code>>>> def isodd(num):
return num & 1 and True or False
>>> isodd(10)
False
>>> isodd(9)
True
</code></pre>
| 23 | 2009-07-07T01:26:42Z | 1,954,646 | <p>Apart from the evil optimization, it takes away the very idiomatic "var % 2 == 0" that every coder understands without looking twice. So this is violates pythons zen as well for very little gain.</p>
<p>Furthermore a = b and True or False has been superseded for better readability by </p>
<p>return True if num & 1 else False</p>
| 1 | 2009-12-23T18:51:02Z | [
"python",
"performance",
"bit-manipulation",
"modulo"
] |
Is & faster than % when checking for odd numbers? | 1,089,936 | <p>To check for odd and even integer, is the lowest bit checking more efficient than using the modulo?</p>
<pre><code>>>> def isodd(num):
return num & 1 and True or False
>>> isodd(10)
False
>>> isodd(9)
True
</code></pre>
| 23 | 2009-07-07T01:26:42Z | 5,153,295 | <p>Was really surprised none of the above answers did both variable setup (timing literal is different story) and no function invocation (which obviously hides "lower terms"). Stuck on that timing from ipython's timeit, where I got clear winner x&1 - better for ~18% using python2.6 (~12% using python3.1).</p>
<p>On my very old machine:</p>
<pre><code>$ python -mtimeit -s 'x = 777' 'x&1'
10000000 loops, best of 3: 0.18 usec per loop
$ python -mtimeit -s 'x = 777' 'x%2'
1000000 loops, best of 3: 0.219 usec per loop
$ python3 -mtimeit -s 'x = 777' 'x&1'
1000000 loops, best of 3: 0.282 usec per loop
$ python3 -mtimeit -s 'x = 777' 'x%2'
1000000 loops, best of 3: 0.323 usec per loop
</code></pre>
| 0 | 2011-03-01T10:33:20Z | [
"python",
"performance",
"bit-manipulation",
"modulo"
] |
Any drawbacks to storing an integer as a string in a database? | 1,090,022 | <p>I have id values for products that I need store. Right now they are all integers, but I'm not sure if the data provider in the future will introduce letters or symbols into that mix, so I'm debating whether to store it now as integer or string.</p>
<p>Are there performance or other disadvantages to saving the values as strings?</p>
| 13 | 2009-07-07T01:58:05Z | 1,090,035 | <p>Integers are more efficient from a storage and performance perspective. However, if there is a remote chance that alpha characters may be introduced, then you should use a string. In my opinion, the efficiency and performance benefits are likely to be negligible, whereas the time it takes to modify your code may not be.</p>
| 0 | 2009-07-07T02:04:15Z | [
"python",
"mysql",
"database",
"database-design"
] |
Any drawbacks to storing an integer as a string in a database? | 1,090,022 | <p>I have id values for products that I need store. Right now they are all integers, but I'm not sure if the data provider in the future will introduce letters or symbols into that mix, so I'm debating whether to store it now as integer or string.</p>
<p>Are there performance or other disadvantages to saving the values as strings?</p>
| 13 | 2009-07-07T01:58:05Z | 1,090,048 | <p>I'm not sure how good databases are at comparing whether one string is greater than another, like it can with integers. Try a query like this:</p>
<pre><code>SELECT * FROM my_table WHERE integer_as_string > '100';
</code></pre>
| 1 | 2009-07-07T02:07:35Z | [
"python",
"mysql",
"database",
"database-design"
] |
Any drawbacks to storing an integer as a string in a database? | 1,090,022 | <p>I have id values for products that I need store. Right now they are all integers, but I'm not sure if the data provider in the future will introduce letters or symbols into that mix, so I'm debating whether to store it now as integer or string.</p>
<p>Are there performance or other disadvantages to saving the values as strings?</p>
| 13 | 2009-07-07T01:58:05Z | 1,090,057 | <p>It really depends on what kind of id you are talking about. If it's a code like a phone number it would actually be better to use a varchar for the id and then have your own id to be a serial for the db and use for primary key. In a case where the integer have no numerical value, varchars are generally prefered. </p>
| 3 | 2009-07-07T02:09:18Z | [
"python",
"mysql",
"database",
"database-design"
] |
Any drawbacks to storing an integer as a string in a database? | 1,090,022 | <p>I have id values for products that I need store. Right now they are all integers, but I'm not sure if the data provider in the future will introduce letters or symbols into that mix, so I'm debating whether to store it now as integer or string.</p>
<p>Are there performance or other disadvantages to saving the values as strings?</p>
| 13 | 2009-07-07T01:58:05Z | 1,090,065 | <p>Unless you really need the features of an integer (that is, the ability to do arithmetic), then it is probably better for you to store the product IDs as strings. You will never need to do anything like add two product IDs together, or compute the average of a group of product IDs, so there is no need for an actual numeric type.</p>
<p>It is unlikely that storing product IDs as strings will cause a measurable difference in performance. While there will be a slight increase in storage size, the size of a product ID string is likely to be much smaller than the data in the rest of your database row anyway.</p>
<p>Storing product IDs as strings today will save you much pain in the future if the data provider decides to start using alphabetic or symbol characters. There is no real downside.</p>
| 23 | 2009-07-07T02:12:26Z | [
"python",
"mysql",
"database",
"database-design"
] |
Any drawbacks to storing an integer as a string in a database? | 1,090,022 | <p>I have id values for products that I need store. Right now they are all integers, but I'm not sure if the data provider in the future will introduce letters or symbols into that mix, so I'm debating whether to store it now as integer or string.</p>
<p>Are there performance or other disadvantages to saving the values as strings?</p>
| 13 | 2009-07-07T01:58:05Z | 1,090,071 | <p>As answered in <a href="http://stackoverflow.com/questions/747802/integer-vs-string-in-database">Integer vs String in database</a></p>
<p>In my country, post-codes are also always 4 digits. But the first digit can be zero.</p>
<blockquote>
<p>If you store "0700" as an integer, you can get a lot of problems:</p>
<p>It may be read as an octal value
If it is read correctly as a decimal value, it gets turned into "700"
When you get the value "700", you must remember to add the zero
I you don't add the zero, later on, how will you know if "700" is "0700", or someone mistyped "7100"?
Technically, our post codes is actual strings, even if it is always 4 digits.</p>
<p>You can store them as integers, to save space. But remember this is a simple DB-trick, and be careful about leading zeroes.</p>
<p>But what about for storing how many files are in a torrent? Integer or string?</p>
<p>That's clearly an integer.</p>
</blockquote>
<p>If the ID would ever start with zero, store it as in interger. </p>
| 0 | 2009-07-07T02:14:22Z | [
"python",
"mysql",
"database",
"database-design"
] |
Any drawbacks to storing an integer as a string in a database? | 1,090,022 | <p>I have id values for products that I need store. Right now they are all integers, but I'm not sure if the data provider in the future will introduce letters or symbols into that mix, so I'm debating whether to store it now as integer or string.</p>
<p>Are there performance or other disadvantages to saving the values as strings?</p>
| 13 | 2009-07-07T01:58:05Z | 1,090,100 | <p>Do NOT consider performance. Consider meaning.</p>
<p>ID "numbers" are not numeric except that they are written with an alphabet of all digits.</p>
<p>If I have part number 12 and part number 14, what is the difference between the two? Is part number 2 or -2 meaningful? No.</p>
<p>Part numbers (and anything that doesn't have units of measure) are not "numeric". They're just strings of digits.</p>
<p>Zip codes in the US, for example. Phone numbers. Social security numbers. These are not numbers. In my town the difference between zip code 12345 and 12309 isn't the distance from my house to downtown. </p>
<p>Do not conflate numbers -- with units -- where sums and differences <em>mean</em> something with strings of digits without sums or differences.</p>
<p>Part ID numbers are -- properly -- strings. Not integers. They'll never be integers because they don't have sums, differences or averages.</p>
| 12 | 2009-07-07T02:28:35Z | [
"python",
"mysql",
"database",
"database-design"
] |
Any drawbacks to storing an integer as a string in a database? | 1,090,022 | <p>I have id values for products that I need store. Right now they are all integers, but I'm not sure if the data provider in the future will introduce letters or symbols into that mix, so I'm debating whether to store it now as integer or string.</p>
<p>Are there performance or other disadvantages to saving the values as strings?</p>
| 13 | 2009-07-07T01:58:05Z | 1,090,132 | <p>The space an integer would take up would me much less than a string. For example 2^32-1 = 4,294,967,295. This would take 10 bytes to store, where as the integer would take 4 bytes to store. For a single entry this is not very much space, but when you start in the millions... As many other posts suggest there are several other issues to consider, but this is one drawback of the string representation. </p>
| 1 | 2009-07-07T02:42:17Z | [
"python",
"mysql",
"database",
"database-design"
] |
Any drawbacks to storing an integer as a string in a database? | 1,090,022 | <p>I have id values for products that I need store. Right now they are all integers, but I'm not sure if the data provider in the future will introduce letters or symbols into that mix, so I'm debating whether to store it now as integer or string.</p>
<p>Are there performance or other disadvantages to saving the values as strings?</p>
| 13 | 2009-07-07T01:58:05Z | 1,090,390 | <p>I've just spent the last year dealing with a database that has almost all IDs as strings, some with digits only, and others mixed. These are the problems:</p>
<ol>
<li>Grossly restricted ID space. A 4 char (digit-only) ID has capacity for 10,000 unique values. A 4 byte numeric has capacity for over 4 billion.</li>
<li>Unpredictable ID space coverage. Once IDs start including non-digits it becomes hard to predict where you can create new IDs without collisions.</li>
<li>Conversion and display problems in certain circumstances, when scripting or on export for instance. If the ID gets interpreted as a number and there is a leading zero, the ID gets altered.</li>
<li>Sorting problems. You can't rely on the natural order being helpful.</li>
</ol>
<p>Of course, if you run out of IDs, or don't know how to create new IDs, your app is dead. I suggest that if you can't control the format of your incoming IDs then you need to create your own (numeric) IDs and relate the user provided ID to that. You can then ensure that your own ID is reliable and unique (and numeric) but provide a user-viewable ID that can have whatever format your users want, and doesn't even have to be unique across the whole app. This is more work, but if you'd been through what I have you'd know which way to go.</p>
<p>Anil G</p>
| 3 | 2009-07-07T04:45:21Z | [
"python",
"mysql",
"database",
"database-design"
] |
Any drawbacks to storing an integer as a string in a database? | 1,090,022 | <p>I have id values for products that I need store. Right now they are all integers, but I'm not sure if the data provider in the future will introduce letters or symbols into that mix, so I'm debating whether to store it now as integer or string.</p>
<p>Are there performance or other disadvantages to saving the values as strings?</p>
| 13 | 2009-07-07T01:58:05Z | 1,090,708 | <ol>
<li>You won't be able to do comparisons correctly. "... where x > 500" is not same as ".. where x > '500'" because "500" > "100000"</li>
<li>Performance wise string it would be a hit especially if you use indexes as integer indexes are much faster than string indexes.</li>
</ol>
<p>On the other hand it really depends upon your situation. If you intend to store something like phone numbers or student enrollment numbers, then it makes perfect sense to use strings.</p>
| 1 | 2009-07-07T06:41:48Z | [
"python",
"mysql",
"database",
"database-design"
] |
Any drawbacks to storing an integer as a string in a database? | 1,090,022 | <p>I have id values for products that I need store. Right now they are all integers, but I'm not sure if the data provider in the future will introduce letters or symbols into that mix, so I'm debating whether to store it now as integer or string.</p>
<p>Are there performance or other disadvantages to saving the values as strings?</p>
| 13 | 2009-07-07T01:58:05Z | 1,090,924 | <p>Better use independent ID and add string ID if necessary: if there's a business indicator you need to include, why make it system ID?</p>
<p>Main drawbacks:</p>
<ol>
<li><p>Integer operations and indexing always show better performance on large scales of data (more than 1k rows in a table, not to speak of connected tables)</p></li>
<li><p>You'll have to make additional checks to restrict numeric-only values in a column: these can be regex whether on client or database side. Anyway, you'll have to guarantee somehow that there's actually integer.</p></li>
<li><p>And you will create additional context layer for developers to know, and anyway someone will always mess this up :)</p></li>
</ol>
| 0 | 2009-07-07T07:58:05Z | [
"python",
"mysql",
"database",
"database-design"
] |
How does Python store lists internally? | 1,090,104 | <p>How are lists in python stored internally? Is it an array? A linked list? Something else?</p>
<p>Or does the interpreter guess at the right structure for each instance based on length, etc.</p>
<p>If the question is implementation dependent, what about the classic CPython?</p>
| 9 | 2009-07-07T02:31:01Z | 1,090,117 | <p>from <a href="http://www.pycon.it/media/stuff/slides/core-python-containers-under-hood.ppt">Core Python Containers: Under the Hood</a><br>
List Implementation:<br>
Fixed-length array of pointers<br>
* When the array grows or shrinks, calls realloc() and, if necessary, copies all of the items to the new space<br>
source code: <a href="http://svn.python.org/view/python/trunk/Include/listobject.h?view=markup&pathrev=59564">Include/listobject.h</a> and <a href="http://svn.python.org/view/python/trunk/Objects/listobject.c?view=markup&pathrev=61049">Objects/listobject.c</a><br>
btw: <a href="http://www.viddler.com/explore/python-italia/videos/41/">here is the video</a> or <a href="http://www.youtube.com/watch?v=hYUsssClE94">here</a></p>
| 21 | 2009-07-07T02:35:40Z | [
"python",
"data-structures"
] |
How can I parse marked up text for further processing? | 1,090,280 | <p><strong>See updated input and output data at Edit-1.</strong></p>
<p>What I am trying to accomplish is turning</p>
<pre>
+ 1
+ 1.1
+ 1.1.1
- 1.1.1.1
- 1.1.1.2
+ 1.2
- 1.2.1
- 1.2.2
- 1.3
+ 2
- 3
</pre>
<p>into a python data structure such as </p>
<pre><code>[{'1': [{'1.1': {'1.1.1': ['1.1.1.1', '1.1.1.2']}, '1.2': ['1.2.1', '1.2.2']}, '1.3'], '2': {}}, ['3',]]
</code></pre>
<p>I've looked at many different wiki markup languages, markdown, restructured text, etc but they are all extremely complicated for me to understand how it works since they must cover a large amount of tags and syntax (I would only need the "list" parts of most of these but converted to python instead of html of course.)</p>
<p>I've also taken a look at tokenizers, lexers and parsers but again they are much more complicated than I need and that I can understand.</p>
<p>I have no idea where to begin and would appreciate any help possible on this subject. Thanks</p>
<p><strong>Edit-1</strong>: Yes the character at the beginning of the line matters, from the required output from before and now it could be seen that the <strong><code>*</code></strong> denotes a root node with children, the <strong>+</strong> has children and the <strong>-</strong> has no children (root or otherwise) and is just extra information pertaining to that node. The <strong><code>*</code></strong> is not important and can be interchanged with <strong>+</strong> (I can get root status other ways.) </p>
<p>Therefore the new requirement would be using only <strong><code>*</code></strong> to denote a node with or without children and <strong>-</strong> cannot have children. I've also changed it so the key isn't the text after the <strong><code>*</code></strong> since that will no doubt changer later to an actual title.</p>
<p>For example </p>
<pre>
* 1
* 1.1
* 1.2
- Note for 1.2
* 2
* 3
- Note for root
</pre>
<p>would give </p>
<pre><code>[{'title': '1', 'children': [{'title': '1.1', 'children': []}, {'title': '1.2', 'children': []}]}, {'title': '2', 'children': [], 'notes': ['Note for 1.2', ]}, {'title': '3', 'children': []}, 'Note for root']
</code></pre>
<p>Or if you have another idea to represent the outline in python then bring it forward.</p>
| 4 | 2009-07-07T03:47:13Z | 1,090,424 | <p>Since you're dealing with an outline situation, you can simplify things by using a stack. Basically, you want to create a stack that has <code>dict</code>s corresponding to the depth of the outline. When you parse a new line and the depth of the outline has increased, you push a new <code>dict</code> onto the stack that was referenced by the previous <code>dict</code> at the top of the stack. When you parse a line that has a lower depth, you pop the stack to get back to the parent. And when you encounter a line that has the same depth, you add it to the <code>dict</code> at the top of the stack.</p>
| 1 | 2009-07-07T04:59:28Z | [
"python",
"parsing",
"markdown",
"markup",
"lexer"
] |
How can I parse marked up text for further processing? | 1,090,280 | <p><strong>See updated input and output data at Edit-1.</strong></p>
<p>What I am trying to accomplish is turning</p>
<pre>
+ 1
+ 1.1
+ 1.1.1
- 1.1.1.1
- 1.1.1.2
+ 1.2
- 1.2.1
- 1.2.2
- 1.3
+ 2
- 3
</pre>
<p>into a python data structure such as </p>
<pre><code>[{'1': [{'1.1': {'1.1.1': ['1.1.1.1', '1.1.1.2']}, '1.2': ['1.2.1', '1.2.2']}, '1.3'], '2': {}}, ['3',]]
</code></pre>
<p>I've looked at many different wiki markup languages, markdown, restructured text, etc but they are all extremely complicated for me to understand how it works since they must cover a large amount of tags and syntax (I would only need the "list" parts of most of these but converted to python instead of html of course.)</p>
<p>I've also taken a look at tokenizers, lexers and parsers but again they are much more complicated than I need and that I can understand.</p>
<p>I have no idea where to begin and would appreciate any help possible on this subject. Thanks</p>
<p><strong>Edit-1</strong>: Yes the character at the beginning of the line matters, from the required output from before and now it could be seen that the <strong><code>*</code></strong> denotes a root node with children, the <strong>+</strong> has children and the <strong>-</strong> has no children (root or otherwise) and is just extra information pertaining to that node. The <strong><code>*</code></strong> is not important and can be interchanged with <strong>+</strong> (I can get root status other ways.) </p>
<p>Therefore the new requirement would be using only <strong><code>*</code></strong> to denote a node with or without children and <strong>-</strong> cannot have children. I've also changed it so the key isn't the text after the <strong><code>*</code></strong> since that will no doubt changer later to an actual title.</p>
<p>For example </p>
<pre>
* 1
* 1.1
* 1.2
- Note for 1.2
* 2
* 3
- Note for root
</pre>
<p>would give </p>
<pre><code>[{'title': '1', 'children': [{'title': '1.1', 'children': []}, {'title': '1.2', 'children': []}]}, {'title': '2', 'children': [], 'notes': ['Note for 1.2', ]}, {'title': '3', 'children': []}, 'Note for root']
</code></pre>
<p>Or if you have another idea to represent the outline in python then bring it forward.</p>
| 4 | 2009-07-07T03:47:13Z | 1,090,463 | <p><strong>Edit</strong>: thanks to the clarification and change in the spec I've edited my code, still using an explicit <code>Node</code> class as an intermediate step for clarity -- the logic is to turn the list of lines into a list of nodes, then turn that list of nodes into a tree (by using their indent attribute appropriately), then print that tree in a readable form (this is just a "debug-help" step, to check the tree is well constructed, and can of course get commented out in the final version of the script -- which, just as of course, will take the lines from a file rather than having them hardcoded for debugging!-), finally build the desired Python structure and print it. Here's the code, and as we'll see after that the result is <em>almost</em> as the OP specifies with one exception -- but, the code first:</p>
<pre><code>import sys
class Node(object):
def __init__(self, title, indent):
self.title = title
self.indent = indent
self.children = []
self.notes = []
self.parent = None
def __repr__(self):
return 'Node(%s, %s, %r, %s)' % (
self.indent, self.parent, self.title, self.notes)
def aspython(self):
result = dict(title=self.title, children=topython(self.children))
if self.notes:
result['notes'] = self.notes
return result
def print_tree(node):
print ' ' * node.indent, node.title
for subnode in node.children:
print_tree(subnode)
for note in node.notes:
print ' ' * node.indent, 'Note:', note
def topython(nodelist):
return [node.aspython() for node in nodelist]
def lines_to_tree(lines):
nodes = []
for line in lines:
indent = len(line) - len(line.lstrip())
marker, body = line.strip().split(None, 1)
if marker == '*':
nodes.append(Node(body, indent))
elif marker == '-':
nodes[-1].notes.append(body)
else:
print>>sys.stderr, "Invalid marker %r" % marker
tree = Node('', -1)
curr = tree
for node in nodes:
while node.indent <= curr.indent:
curr = curr.parent
node.parent = curr
curr.children.append(node)
curr = node
return tree
data = """\
* 1
* 1.1
* 1.2
- Note for 1.2
* 2
* 3
- Note for root
""".splitlines()
def main():
tree = lines_to_tree(data)
print_tree(tree)
print
alist = topython(tree.children)
print alist
if __name__ == '__main__':
main()
</code></pre>
<p>When run, this emits:</p>
<pre><code> 1
1.1
1.2
Note: 1.2
2
3
Note: 3
[{'children': [{'children': [], 'title': '1.1'}, {'notes': ['Note for 1.2'], 'children': [], 'title': '1.2'}], 'title': '1'}, {'children': [], 'title': '2'}, {'notes': ['Note for root'], 'children': [], 'title': '3'}]
</code></pre>
<p>Apart from the ordering of keys (which is immaterial and not guaranteed in a dict, of course), this is <em>almost</em> as requested -- except that here <strong>all</strong> notes appear as dict entries with a key of <code>notes</code> and a value that's a list of strings (but the notes entry is omitted if the list would be empty, roughly as done in the example in the question).</p>
<p>In the current version of the question, how to represent the notes is slightly unclear; one note appears as a stand-alone string, others as entries whose value is a string (instead of a list of strings as I'm using). It's not clear what's supposed to imply that the note must appear as a stand-alone string in one case and as a dict entry in all others, so this scheme I'm using is more regular; and if a note (if any) is a single string rather than a list, would that mean it's an error if more than one note appears for a node? In the latter regard, this scheme I'm using is more general (lets a node have any number of notes from 0 up, instead of just 0 or 1 as apparently implied in the question).</p>
<p>Having written so much code (the pre-edit answer was about as long and helped clarify and change the specs) to provide (I hope) 99% of the desired solution, I hope this satisfies the original poster, since the last few tweaks to code and/or specs to make them match each other should be easy for him to do!</p>
| 6 | 2009-07-07T05:16:12Z | [
"python",
"parsing",
"markdown",
"markup",
"lexer"
] |
How can I parse marked up text for further processing? | 1,090,280 | <p><strong>See updated input and output data at Edit-1.</strong></p>
<p>What I am trying to accomplish is turning</p>
<pre>
+ 1
+ 1.1
+ 1.1.1
- 1.1.1.1
- 1.1.1.2
+ 1.2
- 1.2.1
- 1.2.2
- 1.3
+ 2
- 3
</pre>
<p>into a python data structure such as </p>
<pre><code>[{'1': [{'1.1': {'1.1.1': ['1.1.1.1', '1.1.1.2']}, '1.2': ['1.2.1', '1.2.2']}, '1.3'], '2': {}}, ['3',]]
</code></pre>
<p>I've looked at many different wiki markup languages, markdown, restructured text, etc but they are all extremely complicated for me to understand how it works since they must cover a large amount of tags and syntax (I would only need the "list" parts of most of these but converted to python instead of html of course.)</p>
<p>I've also taken a look at tokenizers, lexers and parsers but again they are much more complicated than I need and that I can understand.</p>
<p>I have no idea where to begin and would appreciate any help possible on this subject. Thanks</p>
<p><strong>Edit-1</strong>: Yes the character at the beginning of the line matters, from the required output from before and now it could be seen that the <strong><code>*</code></strong> denotes a root node with children, the <strong>+</strong> has children and the <strong>-</strong> has no children (root or otherwise) and is just extra information pertaining to that node. The <strong><code>*</code></strong> is not important and can be interchanged with <strong>+</strong> (I can get root status other ways.) </p>
<p>Therefore the new requirement would be using only <strong><code>*</code></strong> to denote a node with or without children and <strong>-</strong> cannot have children. I've also changed it so the key isn't the text after the <strong><code>*</code></strong> since that will no doubt changer later to an actual title.</p>
<p>For example </p>
<pre>
* 1
* 1.1
* 1.2
- Note for 1.2
* 2
* 3
- Note for root
</pre>
<p>would give </p>
<pre><code>[{'title': '1', 'children': [{'title': '1.1', 'children': []}, {'title': '1.2', 'children': []}]}, {'title': '2', 'children': [], 'notes': ['Note for 1.2', ]}, {'title': '3', 'children': []}, 'Note for root']
</code></pre>
<p>Or if you have another idea to represent the outline in python then bring it forward.</p>
| 4 | 2009-07-07T03:47:13Z | 1,091,364 | <p>Stacks are a really useful datastructure when parsing trees. You just keep the path from the last added node up to the root on the stack at all times so you can find the correct parent by the length of the indent. Something like this should work for parsing your last example:</p>
<pre><code>import re
line_tokens = re.compile('( *)(\\*|-) (.*)')
def parse_tree(data):
stack = [{'title': 'Root node', 'children': []}]
for line in data.split("\n"):
indent, symbol, content = line_tokens.match(line).groups()
while len(indent) + 1 < len(stack):
stack.pop() # Remove everything up to current parent
if symbol == '-':
stack[-1].setdefault('notes', []).append(content)
elif symbol == '*':
node = {'title': content, 'children': []}
stack[-1]['children'].append(node)
stack.append(node) # Add as the current deepest node
return stack[0]
</code></pre>
| 1 | 2009-07-07T09:47:20Z | [
"python",
"parsing",
"markdown",
"markup",
"lexer"
] |
How can I parse marked up text for further processing? | 1,090,280 | <p><strong>See updated input and output data at Edit-1.</strong></p>
<p>What I am trying to accomplish is turning</p>
<pre>
+ 1
+ 1.1
+ 1.1.1
- 1.1.1.1
- 1.1.1.2
+ 1.2
- 1.2.1
- 1.2.2
- 1.3
+ 2
- 3
</pre>
<p>into a python data structure such as </p>
<pre><code>[{'1': [{'1.1': {'1.1.1': ['1.1.1.1', '1.1.1.2']}, '1.2': ['1.2.1', '1.2.2']}, '1.3'], '2': {}}, ['3',]]
</code></pre>
<p>I've looked at many different wiki markup languages, markdown, restructured text, etc but they are all extremely complicated for me to understand how it works since they must cover a large amount of tags and syntax (I would only need the "list" parts of most of these but converted to python instead of html of course.)</p>
<p>I've also taken a look at tokenizers, lexers and parsers but again they are much more complicated than I need and that I can understand.</p>
<p>I have no idea where to begin and would appreciate any help possible on this subject. Thanks</p>
<p><strong>Edit-1</strong>: Yes the character at the beginning of the line matters, from the required output from before and now it could be seen that the <strong><code>*</code></strong> denotes a root node with children, the <strong>+</strong> has children and the <strong>-</strong> has no children (root or otherwise) and is just extra information pertaining to that node. The <strong><code>*</code></strong> is not important and can be interchanged with <strong>+</strong> (I can get root status other ways.) </p>
<p>Therefore the new requirement would be using only <strong><code>*</code></strong> to denote a node with or without children and <strong>-</strong> cannot have children. I've also changed it so the key isn't the text after the <strong><code>*</code></strong> since that will no doubt changer later to an actual title.</p>
<p>For example </p>
<pre>
* 1
* 1.1
* 1.2
- Note for 1.2
* 2
* 3
- Note for root
</pre>
<p>would give </p>
<pre><code>[{'title': '1', 'children': [{'title': '1.1', 'children': []}, {'title': '1.2', 'children': []}]}, {'title': '2', 'children': [], 'notes': ['Note for 1.2', ]}, {'title': '3', 'children': []}, 'Note for root']
</code></pre>
<p>Or if you have another idea to represent the outline in python then bring it forward.</p>
| 4 | 2009-07-07T03:47:13Z | 1,159,300 | <p>The syntax you`re using is <em>very</em> similar to Yaml. It has some differences, but itâs quite easy to learn â itâs main focus is to be human readable (and writable). </p>
<p>Take look at Yaml website. There are some python bindings, documentation and other stuff there.</p>
<ul>
<li><a href="http://www.yaml.org" rel="nofollow">http://www.yaml.org</a></li>
</ul>
| 0 | 2009-07-21T13:45:08Z | [
"python",
"parsing",
"markdown",
"markup",
"lexer"
] |
Using Python to call Mencoder with some arguments | 1,090,503 | <p>I'll start by saying that I am very, very new to Python.</p>
<p>I used to have a Windows/Dos batch file in order to launch Mencoder with the right set of parameters, without having to type them each time.</p>
<p>Things got messy when I tried to improve my script, and I decided that it would be a good opportunity to try coding something in python.</p>
<p>I've come up with that :</p>
<pre><code>#!/usr/bin/python
import sys, os
#Path to mencoder
mencoder = "C:\Program Files\MPlayer-1.0rc2\mencoder.exe"
infile = "holidays.avi"
outfile = "holidays (part1).avi"
startTime = "00:48:00"
length = "00:00:15"
commande = "%s %s -ovc copy -oac copy -ss %s -endpos %s -o %s"
os.system(commande % (mencoder, infile, startTime, length, outfile))
#Pause
raw_input()
</code></pre>
<p>But that doesn't work, windows complains that "C:\Program" is not recognized command.</p>
<p>I've trying putting some "\"" here and there, but that didn't help.</p>
| 1 | 2009-07-07T05:28:54Z | 1,090,541 | <p>Python have two types of quotes, " and ' and they are completely equal. So easiest way to get quotes in a string is to say '"C:\Program Files\MPlayer-1.0rc2\mencoder.exe"'.</p>
<p>Using the raw prefix (ie r'"C:\Program Files\MPlayer-1.0rc2\mencoder.exe"') is a good idea, but that is not the error here, as none of the backslashes are followed by a letter that is an escape code. So your original string would not change at all by having an r in front of it.</p>
| 4 | 2009-07-07T05:38:10Z | [
"python",
"windows",
"mencoder"
] |
Using Python to call Mencoder with some arguments | 1,090,503 | <p>I'll start by saying that I am very, very new to Python.</p>
<p>I used to have a Windows/Dos batch file in order to launch Mencoder with the right set of parameters, without having to type them each time.</p>
<p>Things got messy when I tried to improve my script, and I decided that it would be a good opportunity to try coding something in python.</p>
<p>I've come up with that :</p>
<pre><code>#!/usr/bin/python
import sys, os
#Path to mencoder
mencoder = "C:\Program Files\MPlayer-1.0rc2\mencoder.exe"
infile = "holidays.avi"
outfile = "holidays (part1).avi"
startTime = "00:48:00"
length = "00:00:15"
commande = "%s %s -ovc copy -oac copy -ss %s -endpos %s -o %s"
os.system(commande % (mencoder, infile, startTime, length, outfile))
#Pause
raw_input()
</code></pre>
<p>But that doesn't work, windows complains that "C:\Program" is not recognized command.</p>
<p>I've trying putting some "\"" here and there, but that didn't help.</p>
| 1 | 2009-07-07T05:28:54Z | 2,015,918 | <p>use two quotes instead of one if you are doing on windows. </p>
<pre><code>"\\"
</code></pre>
| 1 | 2010-01-06T20:20:54Z | [
"python",
"windows",
"mencoder"
] |
Using Python to call Mencoder with some arguments | 1,090,503 | <p>I'll start by saying that I am very, very new to Python.</p>
<p>I used to have a Windows/Dos batch file in order to launch Mencoder with the right set of parameters, without having to type them each time.</p>
<p>Things got messy when I tried to improve my script, and I decided that it would be a good opportunity to try coding something in python.</p>
<p>I've come up with that :</p>
<pre><code>#!/usr/bin/python
import sys, os
#Path to mencoder
mencoder = "C:\Program Files\MPlayer-1.0rc2\mencoder.exe"
infile = "holidays.avi"
outfile = "holidays (part1).avi"
startTime = "00:48:00"
length = "00:00:15"
commande = "%s %s -ovc copy -oac copy -ss %s -endpos %s -o %s"
os.system(commande % (mencoder, infile, startTime, length, outfile))
#Pause
raw_input()
</code></pre>
<p>But that doesn't work, windows complains that "C:\Program" is not recognized command.</p>
<p>I've trying putting some "\"" here and there, but that didn't help.</p>
| 1 | 2009-07-07T05:28:54Z | 2,679,562 | <p>You can even put the mencoder.exe into a directory which doesn't have a space char inside it's name (opposed to Program Files).</p>
| 0 | 2010-04-21T00:14:30Z | [
"python",
"windows",
"mencoder"
] |
Using Python to call Mencoder with some arguments | 1,090,503 | <p>I'll start by saying that I am very, very new to Python.</p>
<p>I used to have a Windows/Dos batch file in order to launch Mencoder with the right set of parameters, without having to type them each time.</p>
<p>Things got messy when I tried to improve my script, and I decided that it would be a good opportunity to try coding something in python.</p>
<p>I've come up with that :</p>
<pre><code>#!/usr/bin/python
import sys, os
#Path to mencoder
mencoder = "C:\Program Files\MPlayer-1.0rc2\mencoder.exe"
infile = "holidays.avi"
outfile = "holidays (part1).avi"
startTime = "00:48:00"
length = "00:00:15"
commande = "%s %s -ovc copy -oac copy -ss %s -endpos %s -o %s"
os.system(commande % (mencoder, infile, startTime, length, outfile))
#Pause
raw_input()
</code></pre>
<p>But that doesn't work, windows complains that "C:\Program" is not recognized command.</p>
<p>I've trying putting some "\"" here and there, but that didn't help.</p>
| 1 | 2009-07-07T05:28:54Z | 8,200,180 | <p>I'm new to Python but I know when ever I see that problem, to fix it, the file (executable or argument) must be in quotes. Just add <strong>\"</strong> before and after any file that contains a space in it to differentiate between the command-line arguments. So, that applies to your outfile variable as well. The code should look like this...</p>
<pre><code>#!/usr/bin/python
import sys, os
#Path to mencoder
mencoder = "\"C:\Program Files\MPlayer-1.0rc2\mencoder.exe\""
infile = "holidays.avi"
outfile = "\"holidays (part1).avi\""
startTime = "00:48:00"
length = "00:00:15"
commande = "%s %s -ovc copy -oac copy -ss %s -endpos %s -o %s"
os.system(commande % (mencoder, infile, startTime, length, outfile))
#Pause
raw_input()
</code></pre>
| 1 | 2011-11-20T07:55:05Z | [
"python",
"windows",
"mencoder"
] |
Search a folder for files like "/*tmp*.log" in Python | 1,090,651 | <p>As the title says, I'm using Linux, and the folder could contain more than one file, I want to get the one its name contain <code>*tmp*.log</code> (<code>*</code> means anything of course!). Just like what I do using Linux command line.</p>
| 3 | 2009-07-07T06:17:18Z | 1,090,656 | <p>Use the <a href="http://docs.python.org/library/glob.html"><code>glob</code></a> module.</p>
<pre><code>>>> import glob
>>> glob.glob('./[0-9].*')
['./1.gif', './2.txt']
>>> glob.glob('*.gif')
['1.gif', 'card.gif']
>>> glob.glob('?.gif')
['1.gif']
</code></pre>
| 12 | 2009-07-07T06:18:58Z | [
"python",
"linux",
"file",
"folders"
] |
Search a folder for files like "/*tmp*.log" in Python | 1,090,651 | <p>As the title says, I'm using Linux, and the folder could contain more than one file, I want to get the one its name contain <code>*tmp*.log</code> (<code>*</code> means anything of course!). Just like what I do using Linux command line.</p>
| 3 | 2009-07-07T06:17:18Z | 1,094,073 | <p>The glob answer is easier, but for the sake of completeness: You could also use os.listdir and a regular expression check:</p>
<pre><code>import os
import re
dirEntries = os.listdir(path/to/dir)
for entry in dirEntries:
if re.match(".*tmp.*\.log", entry):
print entry
</code></pre>
| 2 | 2009-07-07T18:43:59Z | [
"python",
"linux",
"file",
"folders"
] |
Search a folder for files like "/*tmp*.log" in Python | 1,090,651 | <p>As the title says, I'm using Linux, and the folder could contain more than one file, I want to get the one its name contain <code>*tmp*.log</code> (<code>*</code> means anything of course!). Just like what I do using Linux command line.</p>
| 3 | 2009-07-07T06:17:18Z | 12,544,486 | <p>The code below expands on previous answers by showing a more complicated search case. </p>
<p>I had an application that was heavily controlled by a configuration file. In fact there were many versions of the configuration each with different tradeoffs. So one configuration set would result in a thorough work but would be very slow while another will be much faster but wonât be as thorough, etc. So the GUI would have a configuration combo box with options corresponding to different configurations. Since I felt that the set of configurations will be growing over the time, I did not want to hardcode the list of files and the corresponding options (and their order) in the application but instead resorted to a file naming convention that would convey all this information. </p>
<p>The naming convention that I used was as following. Files are located in directory $MY_APP_HOME/dat. File name begins with my_config_ followed by the combo index number, followed by the text for the combo item. For example: If the directory contained (among others) files my_config_11_fast_but_sloppy.txt, my_config_100_balanced.txt, my_config_3_thorough_but_slow.txt, my combo box would have options (in that order): Thorough But Slow, Fast But Sloppy, Balanced.</p>
<p>So at runtime I needed to </p>
<ol>
<li>Find my configuration files in the directory</li>
<li>Extract a list of options from all the file names to put in the combo box</li>
<li>Sort options according to the index</li>
<li>Be able to get file path from the selected option</li>
</ol>
<p>MyConfiguration class below does all the work in just a few lines of code (significantly fewer that it took me to explain the purpose :-) and it can be used as following:</p>
<pre><code># populate my_config combobox
self.my_config = MyConfiguration()
self.gui.my_config.addItems(self.my_config.get_items())
# get selected file path
index = self.gui.my_config.currentIndex()
self.config_file = self.my_config.get_file_path_by_index(index);
</code></pre>
<p>Here is the MyConfiguration class:</p>
<pre><code>import os, re
class MyConfiguration:
def __init__(self):
# determine directory that contains configuration files
self.__config_dir = '';
env_name = 'MY_APP_HOME'
if env_name in os.environ:
self.__config_dir = os.environ[env_name] + '/dat/';
else:
raise Exception(env_name + ' environment variable is not set.')
# prepare regular expression
regex = re.compile("^(?P<file_name>my_config_(?P<index>\d+?)_(?P<desc>.*?)[.]txt?)$",re.MULTILINE)
# get the list of all files in the directory
file_names = os.listdir(self.__config_dir)
# find all files that are our parameters files and parse them into a list of tuples: (file name, index, item_text)
self.__items = regex.findall("\n".join(file_names))
# sort by index as an integer
self.__items.sort(key=lambda x: int(x[1]))
def get_items(self):
items = []
for item in self.__items:
items.append( self.__format_item_text(item[2]))
return items
def get_file_path_by_index(self, index):
return self.__config_dir + self.__items[index][0]
def __format_item_text(self, text):
return text.replace("_", " ").title();
</code></pre>
| 0 | 2012-09-22T14:11:44Z | [
"python",
"linux",
"file",
"folders"
] |
Handling Multiple Network Interfaces in Python | 1,090,731 | <p>How can I do the following things in python:</p>
<ol>
<li>List all the IP interfaces on the current machine.</li>
<li>Receive updates about changes in network interfaces (goes up, goes down, changes IP address).</li>
</ol>
<p>Any python package available in Ubuntu Hardy will do.</p>
| 2 | 2009-07-07T06:48:38Z | 1,090,766 | <p>I think the best way to do this is via <a href="http://dbus.freedesktop.org/releases/dbus-python/" rel="nofollow">dbus-python</a>.</p>
<p>The <a href="http://dbus.freedesktop.org/doc/dbus-python/doc/tutorial.html" rel="nofollow">tutorial</a> touches on network interfaces a little bit:</p>
<pre><code>import dbus
bus = dbus.SystemBus()
proxy = bus.get_object('org.freedesktop.NetworkManager',
'/org/freedesktop/NetworkManager/Devices/eth0')
# proxy is a dbus.proxies.ProxyObject
</code></pre>
| 3 | 2009-07-07T07:02:55Z | [
"python",
"linux",
"networking",
"ip"
] |
Handling Multiple Network Interfaces in Python | 1,090,731 | <p>How can I do the following things in python:</p>
<ol>
<li>List all the IP interfaces on the current machine.</li>
<li>Receive updates about changes in network interfaces (goes up, goes down, changes IP address).</li>
</ol>
<p>Any python package available in Ubuntu Hardy will do.</p>
| 2 | 2009-07-07T06:48:38Z | 14,047,551 | <p>I have been using the following code,</p>
<pre><code>temp = str(os.system("ifconfig -a | awk '$2~/^Link/{_1=$1;getline;if($2~/^addr/){print _1" "}}'"))
</code></pre>
<p>it will give the 'up' network interfaces</p>
<p>e.g. eth0, eth2, wlan0</p>
| 0 | 2012-12-26T23:27:31Z | [
"python",
"linux",
"networking",
"ip"
] |
Handling Multiple Network Interfaces in Python | 1,090,731 | <p>How can I do the following things in python:</p>
<ol>
<li>List all the IP interfaces on the current machine.</li>
<li>Receive updates about changes in network interfaces (goes up, goes down, changes IP address).</li>
</ol>
<p>Any python package available in Ubuntu Hardy will do.</p>
| 2 | 2009-07-07T06:48:38Z | 14,048,341 | <p>No, no... You don't need to bother os.system() or dbus API.</p>
<p>What you really need is to use netlink API to implement this. Either use <a href="http://www.infradead.org/~tgr/libnl/doc/" rel="nofollow">libnl</a> interface (netlink.route.link) or handle netlink messages by yourself. Take a look at <a href="http://partiallystapled.com/~gxti/tools/netlink.py" rel="nofollow">this example</a>.</p>
| 0 | 2012-12-27T01:27:57Z | [
"python",
"linux",
"networking",
"ip"
] |
How to communicate between Python and C# using XML-RPC? | 1,090,792 | <p>Assume I have simple XML-RPC service that is implemented with Python:</p>
<pre><code>from SimpleXMLRPCServer import SimpleXMLRPCServer
def getTest():
return 'test message'
if __name__ == '__main__' :
server = SimpleThreadedXMLRPCServer(('localhost', 8888))
server.register_fuction(getText)
server.serve_forever()
</code></pre>
<p>Can anyone tell me how to call getTest() function from C#?</p>
| 5 | 2009-07-07T07:13:05Z | 1,090,839 | <p>In order to call the getTest method from c# you will need an XML-RPC client library. <a href="http://www.xml-rpc.net/" rel="nofollow">XML-RPC</a> is an example of such a library.</p>
| 2 | 2009-07-07T07:30:34Z | [
"c#",
"python",
"xml-rpc"
] |
How to communicate between Python and C# using XML-RPC? | 1,090,792 | <p>Assume I have simple XML-RPC service that is implemented with Python:</p>
<pre><code>from SimpleXMLRPCServer import SimpleXMLRPCServer
def getTest():
return 'test message'
if __name__ == '__main__' :
server = SimpleThreadedXMLRPCServer(('localhost', 8888))
server.register_fuction(getText)
server.serve_forever()
</code></pre>
<p>Can anyone tell me how to call getTest() function from C#?</p>
| 5 | 2009-07-07T07:13:05Z | 1,090,843 | <p>Not to toot my own horn, but: <a href="http://liboxide.svn.sourceforge.net/viewvc/liboxide/trunk/Oxide.Net/Rpc/" rel="nofollow">http://liboxide.svn.sourceforge.net/viewvc/liboxide/trunk/Oxide.Net/Rpc/</a></p>
<pre><code>class XmlRpcTest : XmlRpcClient
{
private static Uri remoteHost = new Uri("http://localhost:8888/");
[RpcCall]
public string GetTest()
{
return (string)DoRequest(remoteHost,
CreateRequest("getTest", null));
}
}
static class Program
{
static void Main(string[] args)
{
XmlRpcTest test = new XmlRpcTest();
Console.WriteLine(test.GetTest());
}
}
</code></pre>
<p>That should do the trick... Note, the above library is LGPL, which may or may not be good enough for you.</p>
| 3 | 2009-07-07T07:31:21Z | [
"c#",
"python",
"xml-rpc"
] |
How to communicate between Python and C# using XML-RPC? | 1,090,792 | <p>Assume I have simple XML-RPC service that is implemented with Python:</p>
<pre><code>from SimpleXMLRPCServer import SimpleXMLRPCServer
def getTest():
return 'test message'
if __name__ == '__main__' :
server = SimpleThreadedXMLRPCServer(('localhost', 8888))
server.register_fuction(getText)
server.serve_forever()
</code></pre>
<p>Can anyone tell me how to call getTest() function from C#?</p>
| 5 | 2009-07-07T07:13:05Z | 1,090,995 | <p>Thank you for answer, I try xml-rpc library from darin link. I can call getTest function with following code</p>
<pre><code>using CookComputing.XmlRpc;
...
namespace Hello
{
/* proxy interface */
[XmlRpcUrl("http://localhost:8888")]
public interface IStateName : IXmlRpcProxy
{
[XmlRpcMethod("getTest")]
string getTest();
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
/* implement section */
IStateName proxy = (IStateName)XmlRpcProxyGen.Create(typeof(IStateName));
string message = proxy.getTest();
MessageBox.Show(message);
}
}
}
</code></pre>
| 3 | 2009-07-07T08:19:15Z | [
"c#",
"python",
"xml-rpc"
] |
Python operators | 1,090,863 | <p>I am learning Python for the past few days and I have written this piece of code to evaluate a postfix expression.</p>
<pre><code>postfix_expression = "34*34*+"
stack = []
for char in postfix_expression :
try :
char = int(char);
stack.append(char);
except ValueError:
if char == '+' :
stack.append(stack.pop() + stack.pop())
elif char == '-' :
stack.append(stack.pop() - stack.pop())
elif char == '*' :
stack.append(stack.pop() * stack.pop())
elif char == '/' :
stack.append(stack.pop() / stack.pop())
print stack.pop()
</code></pre>
<p>Is there a way I can avoid that huge if else block? As in, is there module that takes a mathematical operator in the string form and invokes the corresponding mathematical operator or some python idiom that makes this simple?</p>
| 7 | 2009-07-07T07:37:49Z | 1,090,886 | <p>The <a href="http://docs.python.org/library/operator.html" rel="nofollow"><code>operator</code></a> module has functions that implement the standard arithmetic operators. With that, you can set up a mapping like:</p>
<pre><code>OperatorFunctions = {
'+': operator.add,
'-': operator.sub,
'*': operator.mul,
'/': operator.div,
# etc
}
</code></pre>
<p>Then your main loop can look something like this:</p>
<pre><code>for char in postfix_expression:
if char in OperatorFunctions:
stack.append(OperatorFunctions[char](stack.pop(), stack.pop()))
else:
stack.append(char)
</code></pre>
<p>You will want to take care to ensure that the operands to subtraction and division are popped off the stack in the correct order.</p>
| 15 | 2009-07-07T07:43:50Z | [
"python",
"operators"
] |
Python operators | 1,090,863 | <p>I am learning Python for the past few days and I have written this piece of code to evaluate a postfix expression.</p>
<pre><code>postfix_expression = "34*34*+"
stack = []
for char in postfix_expression :
try :
char = int(char);
stack.append(char);
except ValueError:
if char == '+' :
stack.append(stack.pop() + stack.pop())
elif char == '-' :
stack.append(stack.pop() - stack.pop())
elif char == '*' :
stack.append(stack.pop() * stack.pop())
elif char == '/' :
stack.append(stack.pop() / stack.pop())
print stack.pop()
</code></pre>
<p>Is there a way I can avoid that huge if else block? As in, is there module that takes a mathematical operator in the string form and invokes the corresponding mathematical operator or some python idiom that makes this simple?</p>
| 7 | 2009-07-07T07:37:49Z | 1,090,891 | <p>Just use <a href="http://docs.python.org/library/functions.html#eval" rel="nofollow">eval</a> along with string generation:</p>
<pre><code>postfix_expression = "34*34*+"
stack = []
for char in postfix_expression:
if char in '+-*/':
expression = '%d%s%d' % (stack.pop(), char, stack.pop())
stack.append(eval(expression))
else:
stack.append(int(char))
print stack.pop()
</code></pre>
<p><strong>EDIT</strong>: made an even nicer version without the exception handling.</p>
| 0 | 2009-07-07T07:46:37Z | [
"python",
"operators"
] |
Python operators | 1,090,863 | <p>I am learning Python for the past few days and I have written this piece of code to evaluate a postfix expression.</p>
<pre><code>postfix_expression = "34*34*+"
stack = []
for char in postfix_expression :
try :
char = int(char);
stack.append(char);
except ValueError:
if char == '+' :
stack.append(stack.pop() + stack.pop())
elif char == '-' :
stack.append(stack.pop() - stack.pop())
elif char == '*' :
stack.append(stack.pop() * stack.pop())
elif char == '/' :
stack.append(stack.pop() / stack.pop())
print stack.pop()
</code></pre>
<p>Is there a way I can avoid that huge if else block? As in, is there module that takes a mathematical operator in the string form and invokes the corresponding mathematical operator or some python idiom that makes this simple?</p>
| 7 | 2009-07-07T07:37:49Z | 1,090,908 | <pre><code>[untested]
from operator import add, sub, mul, div
# read the docs; this is a tiny part of the operator module
despatcher = {
'+': add,
'-': sub,
# etc
}
opfunc = despatcher[op_char]
operand2 = stack.pop()
# your - and / are bassackwards
stack[-1] = opfunc(stack[-1], operand2)
</code></pre>
| 0 | 2009-07-07T07:52:48Z | [
"python",
"operators"
] |
How to test if a class attribute is an instance method | 1,091,259 | <p>In Python I need to efficiently and generically test whether an attribute of a class is an instance method. The inputs to the call would be the name of the attribute being checked (a string) and an object.</p>
<p>hasattr returns true regardless of whether the attribute is an instance method or not.</p>
<p>Any suggestions?</p>
<p><hr /></p>
<p>For example:</p>
<pre><code>class Test(object):
testdata = 123
def testmethod(self):
pass
test = Test()
print ismethod(test, 'testdata') # Should return false
print ismethod(test, 'testmethod') # Should return true
</code></pre>
| 2 | 2009-07-07T09:23:23Z | 1,091,281 | <pre><code>import types
print isinstance(getattr(your_object, "your_attribute"), types.MethodType)
</code></pre>
| 3 | 2009-07-07T09:32:10Z | [
"python",
"methods",
"attributes",
"instance"
] |
How to test if a class attribute is an instance method | 1,091,259 | <p>In Python I need to efficiently and generically test whether an attribute of a class is an instance method. The inputs to the call would be the name of the attribute being checked (a string) and an object.</p>
<p>hasattr returns true regardless of whether the attribute is an instance method or not.</p>
<p>Any suggestions?</p>
<p><hr /></p>
<p>For example:</p>
<pre><code>class Test(object):
testdata = 123
def testmethod(self):
pass
test = Test()
print ismethod(test, 'testdata') # Should return false
print ismethod(test, 'testmethod') # Should return true
</code></pre>
| 2 | 2009-07-07T09:23:23Z | 1,091,288 | <pre><code>def hasmethod(obj, name):
return hasattr(obj, name) and type(getattr(obj, name)) == types.MethodType
</code></pre>
| 8 | 2009-07-07T09:33:55Z | [
"python",
"methods",
"attributes",
"instance"
] |
How to test if a class attribute is an instance method | 1,091,259 | <p>In Python I need to efficiently and generically test whether an attribute of a class is an instance method. The inputs to the call would be the name of the attribute being checked (a string) and an object.</p>
<p>hasattr returns true regardless of whether the attribute is an instance method or not.</p>
<p>Any suggestions?</p>
<p><hr /></p>
<p>For example:</p>
<pre><code>class Test(object):
testdata = 123
def testmethod(self):
pass
test = Test()
print ismethod(test, 'testdata') # Should return false
print ismethod(test, 'testmethod') # Should return true
</code></pre>
| 2 | 2009-07-07T09:23:23Z | 1,091,297 | <p>You can use the <code>inspect</code> module:</p>
<pre><code>class A(object):
def method_name(self):
pass
import inspect
print inspect.ismethod(getattr(A, 'method_name')) # prints True
a = A()
print inspect.ismethod(getattr(a, 'method_name')) # prints True
</code></pre>
| 3 | 2009-07-07T09:35:20Z | [
"python",
"methods",
"attributes",
"instance"
] |
How to test if a class attribute is an instance method | 1,091,259 | <p>In Python I need to efficiently and generically test whether an attribute of a class is an instance method. The inputs to the call would be the name of the attribute being checked (a string) and an object.</p>
<p>hasattr returns true regardless of whether the attribute is an instance method or not.</p>
<p>Any suggestions?</p>
<p><hr /></p>
<p>For example:</p>
<pre><code>class Test(object):
testdata = 123
def testmethod(self):
pass
test = Test()
print ismethod(test, 'testdata') # Should return false
print ismethod(test, 'testmethod') # Should return true
</code></pre>
| 2 | 2009-07-07T09:23:23Z | 1,091,300 | <p>This function checks if the attribute exists and then checks if the attribute is a method using the <code>inspect</code> module.</p>
<pre><code>import inspect
def ismethod(obj, name):
if hasattr(obj, name):
if inspect.ismethod(getattr(obj, name)):
return True
return False
class Foo:
x = 0
def bar(self):
pass
foo = Foo()
print ismethod(foo, "spam")
print ismethod(foo, "x")
print ismethod(foo, "bar")
</code></pre>
| 1 | 2009-07-07T09:35:49Z | [
"python",
"methods",
"attributes",
"instance"
] |
how do I get the process list in Python? | 1,091,327 | <p>How do I get a process list of all running processes from Python, on Unix, containing then name of the command/process and process id, so I can filter and kill processes. </p>
| 7 | 2009-07-07T09:41:39Z | 1,091,353 | <p>Why Python?<br />
You can directly use <a href="http://manpages.ubuntu.com/manpages/karmic/man1/killall.1.html" rel="nofollow"><code>killall</code></a> on the process name.</p>
| -1 | 2009-07-07T09:45:20Z | [
"python",
"unix",
"kill",
"ps",
"processlist"
] |
how do I get the process list in Python? | 1,091,327 | <p>How do I get a process list of all running processes from Python, on Unix, containing then name of the command/process and process id, so I can filter and kill processes. </p>
| 7 | 2009-07-07T09:41:39Z | 1,091,426 | <p>On linux, the easiest solution is probably to use the external <code>ps</code> command:</p>
<pre><code>>>> import os
>>> data = [(int(p), c) for p, c in [x.rstrip('\n').split(' ', 1) \
... for x in os.popen('ps h -eo pid:1,command')]]
</code></pre>
<p>On other systems you might have to change the options to <code>ps</code>.</p>
<p>Still, you might want to run <code>man</code> on <code>pgrep</code> and <code>pkill</code>.</p>
| 2 | 2009-07-07T10:01:45Z | [
"python",
"unix",
"kill",
"ps",
"processlist"
] |
how do I get the process list in Python? | 1,091,327 | <p>How do I get a process list of all running processes from Python, on Unix, containing then name of the command/process and process id, so I can filter and kill processes. </p>
| 7 | 2009-07-07T09:41:39Z | 1,091,428 | <p>On Linux, with a suitably recent Python which includes the <code>subprocess</code> module:</p>
<pre><code>from subprocess import Popen, PIPE
process = Popen(['ps', '-eo' ,'pid,args'], stdout=PIPE, stderr=PIPE)
stdout, notused = process.communicate()
for line in stdout.splitlines():
pid, cmdline = line.split(' ', 1)
#Do whatever filtering and processing is needed
</code></pre>
<p>You may need to tweak the ps command slightly depending on your exact needs.</p>
| 6 | 2009-07-07T10:02:17Z | [
"python",
"unix",
"kill",
"ps",
"processlist"
] |
Python composite pattern exception handling & pylint | 1,091,337 | <p>I'm implementig a Composite pattern in <a href="http://en.wikipedia.org/wiki/Composite_pattern" rel="nofollow">this way</a>:</p>
<p>1) the "abstract" component is:</p>
<pre><code>class Component(object):
"""Basic Component Abstraction"""
def __init__(self, *args, **kw):
raise NotImplementedError("must be subclassed")
def status(self):
"""Base Abstract method"""
raise NotImplementedError("must be implemented")
</code></pre>
<p>2) a leaf:</p>
<pre><code>class Leaf(Component):
"""Basic atomic component
"""
def __init__(self, *args, **kw):
self.dict = {}
def status(self):
"""Retrieves properties
"""
return self.dict
</code></pre>
<p>The Problem is that pylint generates, of course, this warning:</p>
<pre><code>Leaf.__init__: __init__ method from base class 'Component' is not called
</code></pre>
<p>but into my Leaf i cannot call for:</p>
<pre><code>def __init__(self, *args, **kw):
Component.__init__(self, *args, **kw)
self.dict = {}
</code></pre>
<p>without raise of the exception.</p>
<p>Must I ignore pylint warning or there is some bad coding?</p>
| 1 | 2009-07-07T09:42:31Z | 1,091,390 | <p>Abstract initializers are a bad idea. Your code might evolve so that you want to do some initialization in the root component. And even if you don't why require the implementation of the initializer. For some subclasses an empty initializer would be an acceptable choice.</p>
<p>If you don't want any instances of the Component class around, check for that in the initializer:</p>
<pre><code>class Component(object):
def __init__(self, **kwargs):
assert type(self) != Component, "Component must not be instantiated directly"
class Leaf(Component):
def __init__(self, some, args, **kwargs):
# regular initialization
Component.__init__(self, **kwargs)
</code></pre>
| 4 | 2009-07-07T09:52:05Z | [
"python",
"composite",
"pylint"
] |
Python composite pattern exception handling & pylint | 1,091,337 | <p>I'm implementig a Composite pattern in <a href="http://en.wikipedia.org/wiki/Composite_pattern" rel="nofollow">this way</a>:</p>
<p>1) the "abstract" component is:</p>
<pre><code>class Component(object):
"""Basic Component Abstraction"""
def __init__(self, *args, **kw):
raise NotImplementedError("must be subclassed")
def status(self):
"""Base Abstract method"""
raise NotImplementedError("must be implemented")
</code></pre>
<p>2) a leaf:</p>
<pre><code>class Leaf(Component):
"""Basic atomic component
"""
def __init__(self, *args, **kw):
self.dict = {}
def status(self):
"""Retrieves properties
"""
return self.dict
</code></pre>
<p>The Problem is that pylint generates, of course, this warning:</p>
<pre><code>Leaf.__init__: __init__ method from base class 'Component' is not called
</code></pre>
<p>but into my Leaf i cannot call for:</p>
<pre><code>def __init__(self, *args, **kw):
Component.__init__(self, *args, **kw)
self.dict = {}
</code></pre>
<p>without raise of the exception.</p>
<p>Must I ignore pylint warning or there is some bad coding?</p>
| 1 | 2009-07-07T09:42:31Z | 1,091,452 | <p>You want to guarantee, that the base class Component is not instanciated. This is a noble guesture common in other programming languages like C++ (where you can make the constructors private or so to prevent direct usage).</p>
<p>But it is not supported in Python. Python does not support all programming notions and also is more "dynamic". So initialization is done in a "Pythonic" way and your notion is not supported thus.</p>
<p>Python is much more based on trust than other languages -- so, for example static variables are not supported and private ones also only in a limited way.</p>
<p>What you could do (when you distrust the users of your module) -- you could hide the base class by naming it "_Component" -- make it an internal secret. But of course this can create other troubles.</p>
| 1 | 2009-07-07T10:07:28Z | [
"python",
"composite",
"pylint"
] |
Python composite pattern exception handling & pylint | 1,091,337 | <p>I'm implementig a Composite pattern in <a href="http://en.wikipedia.org/wiki/Composite_pattern" rel="nofollow">this way</a>:</p>
<p>1) the "abstract" component is:</p>
<pre><code>class Component(object):
"""Basic Component Abstraction"""
def __init__(self, *args, **kw):
raise NotImplementedError("must be subclassed")
def status(self):
"""Base Abstract method"""
raise NotImplementedError("must be implemented")
</code></pre>
<p>2) a leaf:</p>
<pre><code>class Leaf(Component):
"""Basic atomic component
"""
def __init__(self, *args, **kw):
self.dict = {}
def status(self):
"""Retrieves properties
"""
return self.dict
</code></pre>
<p>The Problem is that pylint generates, of course, this warning:</p>
<pre><code>Leaf.__init__: __init__ method from base class 'Component' is not called
</code></pre>
<p>but into my Leaf i cannot call for:</p>
<pre><code>def __init__(self, *args, **kw):
Component.__init__(self, *args, **kw)
self.dict = {}
</code></pre>
<p>without raise of the exception.</p>
<p>Must I ignore pylint warning or there is some bad coding?</p>
| 1 | 2009-07-07T09:42:31Z | 1,091,524 | <p>Not bad coding as such, but the <code>__init__</code> of the component is simply not needed. If you want it, you can ignore pylint, but it's a better idea to simply remove the <code>__init__</code> from Component.</p>
<p>Embrace the dynamicism!</p>
| 1 | 2009-07-07T10:21:46Z | [
"python",
"composite",
"pylint"
] |
Python composite pattern exception handling & pylint | 1,091,337 | <p>I'm implementig a Composite pattern in <a href="http://en.wikipedia.org/wiki/Composite_pattern" rel="nofollow">this way</a>:</p>
<p>1) the "abstract" component is:</p>
<pre><code>class Component(object):
"""Basic Component Abstraction"""
def __init__(self, *args, **kw):
raise NotImplementedError("must be subclassed")
def status(self):
"""Base Abstract method"""
raise NotImplementedError("must be implemented")
</code></pre>
<p>2) a leaf:</p>
<pre><code>class Leaf(Component):
"""Basic atomic component
"""
def __init__(self, *args, **kw):
self.dict = {}
def status(self):
"""Retrieves properties
"""
return self.dict
</code></pre>
<p>The Problem is that pylint generates, of course, this warning:</p>
<pre><code>Leaf.__init__: __init__ method from base class 'Component' is not called
</code></pre>
<p>but into my Leaf i cannot call for:</p>
<pre><code>def __init__(self, *args, **kw):
Component.__init__(self, *args, **kw)
self.dict = {}
</code></pre>
<p>without raise of the exception.</p>
<p>Must I ignore pylint warning or there is some bad coding?</p>
| 1 | 2009-07-07T09:42:31Z | 1,091,528 | <p>Another suggestion to complement the idea of Markus:</p>
<p>If you really must, I suggest that you use __new __ and check for the given object type. When it is "Component" you could fire your exception:</p>
<pre><code>class Component(object):
"""Basic Component Abstraction"""
def __new__(objType, *args, **kwargs):
if objType == Component:
raise NotImplementedError("must be subclassed")
return object.__new__(type, *args, **kwargs)
</code></pre>
<p>When a subclass is created, objType will be != Component and all will be fine!</p>
| 2 | 2009-07-07T10:22:43Z | [
"python",
"composite",
"pylint"
] |
Python composite pattern exception handling & pylint | 1,091,337 | <p>I'm implementig a Composite pattern in <a href="http://en.wikipedia.org/wiki/Composite_pattern" rel="nofollow">this way</a>:</p>
<p>1) the "abstract" component is:</p>
<pre><code>class Component(object):
"""Basic Component Abstraction"""
def __init__(self, *args, **kw):
raise NotImplementedError("must be subclassed")
def status(self):
"""Base Abstract method"""
raise NotImplementedError("must be implemented")
</code></pre>
<p>2) a leaf:</p>
<pre><code>class Leaf(Component):
"""Basic atomic component
"""
def __init__(self, *args, **kw):
self.dict = {}
def status(self):
"""Retrieves properties
"""
return self.dict
</code></pre>
<p>The Problem is that pylint generates, of course, this warning:</p>
<pre><code>Leaf.__init__: __init__ method from base class 'Component' is not called
</code></pre>
<p>but into my Leaf i cannot call for:</p>
<pre><code>def __init__(self, *args, **kw):
Component.__init__(self, *args, **kw)
self.dict = {}
</code></pre>
<p>without raise of the exception.</p>
<p>Must I ignore pylint warning or there is some bad coding?</p>
| 1 | 2009-07-07T09:42:31Z | 2,341,833 | <p>Renaming your class Component to AbstractComponent should help. And don't provide an <code>__init__</code> method in your base class if it's not supposed to be called by subclasses. </p>
| 2 | 2010-02-26T13:21:51Z | [
"python",
"composite",
"pylint"
] |
TeamCity for Python/Django continuous integration | 1,091,465 | <p>I've set up <a href="http://en.wikipedia.org/wiki/TeamCity">TeamCity</a> on a Linux (Ubuntu) box and would like to use it for some of Python/Django projects.</p>
<p>The problem is that I don't really see what to do next - I tried searching for a Python specific build agent for TeamCity but without much of the success.</p>
<p>How can I manage that?</p>
| 9 | 2009-07-07T10:09:26Z | 1,102,217 | <p>Ok, so there's how to get it working with proper TeamCity integration:</p>
<p>Presuming you have TeamCity installed with at least 1 build agent available</p>
<p>1) Configure your build agent to execute </p>
<pre><code>manage.py test
</code></pre>
<p>2) Download and install this plugin for TC <a href="http://pypi.python.org/pypi/teamcity-messages">http://pypi.python.org/pypi/teamcity-messages</a></p>
<p>3) You'll have to provide your custom test runner for plugin in (2) to work. It can be straight copy of run_tests from django.test.simple, with only one slight modification: replace line where test runner is called with TeamcityTestRunner, so insted of </p>
<pre><code>def run_tests(test_labels, verbosity=1, interactive=True, extra_tests=[]):
...
result = unittest.TextTestRunner(verbosity=verbosity).run(suite)
</code></pre>
<p>use this:</p>
<pre><code>def run_tests(test_labels, verbosity=1, interactive=True, extra_tests=[]):
...
result = TeamcityTestRunner().run(suite)
</code></pre>
<p>You'll have to place that function into a file in your solution, and specify a custome test runner, using Django's TEST_RUNNER configuration property like this:</p>
<pre><code>TEST_RUNNER = 'my_site.file_name_with_run_tests.run_tests'
</code></pre>
<p>Make sure you reference all required imports in your <strong>file_name_with_run_tests</strong></p>
<p>You can test it by running </p>
<pre><code>./manage.py test
</code></pre>
<p>from command line and noticing that output has changed and now messages like</p>
<pre><code>#teamcity....
</code></pre>
<p>appearing in it.</p>
| 21 | 2009-07-09T06:51:57Z | [
"python",
"django",
"continuous-integration",
"teamcity"
] |
TeamCity for Python/Django continuous integration | 1,091,465 | <p>I've set up <a href="http://en.wikipedia.org/wiki/TeamCity">TeamCity</a> on a Linux (Ubuntu) box and would like to use it for some of Python/Django projects.</p>
<p>The problem is that I don't really see what to do next - I tried searching for a Python specific build agent for TeamCity but without much of the success.</p>
<p>How can I manage that?</p>
| 9 | 2009-07-07T10:09:26Z | 14,136,986 | <p>I have added feature request to TeamCity issue tracker, to make full-featured python support. This is the link: <a href="http://youtrack.jetbrains.com/issue/TW-25141" rel="nofollow">http://youtrack.jetbrains.com/issue/TW-25141</a>. If you interested, you can vote for it, and that may force JetBrains to improve python support. </p>
| 1 | 2013-01-03T10:26:41Z | [
"python",
"django",
"continuous-integration",
"teamcity"
] |
Dropdown menus in forms containing database primary keys | 1,091,668 | <p>In a framework like Django or Pylons you can set up function to handle form submissions. If your form involves a dropdown menu (i.e. a select tag) populated with objects from a database you can set the values equal to the primary key for the record like:</p>
<pre><code><select>
<option value="1">Volvo</option>
<option value="2">Saab</option>
<option value="3">Mercedes</option>
<option value="4">Audi</option>
</select>
</code></pre>
<p>Is this a safe practice? Is there anything wrong with using a primary key? If you were not to use the primary key for the value how else can you make this form?</p>
| 0 | 2009-07-07T10:58:13Z | 1,091,728 | <p>Using the primary key is fine. What exactly are you concerned with? This is an implementation detail that won't show up to the user in the actual rendered page.</p>
| 3 | 2009-07-07T11:09:22Z | [
"python",
"django",
"pylons"
] |
Programmatic control of python optimization? | 1,092,243 | <p>I've been playing with <a href="http://www.pyglet.org/index.html" rel="nofollow">pyglet</a>. It's very nice. However, if I run my code, which is in an executable file (call it game.py) prefixed with the usual</p>
<pre><code>#!/usr/bin/env python
</code></pre>
<p>by doing</p>
<pre><code>./game.py
</code></pre>
<p>then it's a bit clunky. But if I run it with</p>
<pre><code>python -O ./game.py
</code></pre>
<p>or </p>
<pre><code>PYTHONOPTIMIZE=1 ./game.py
</code></pre>
<p>then its super-smooth.</p>
<p>I'm don't care much why it runs slow without optimization; pyglet's documentation mentions that optimizing disables numerous asserts and also OpenGL's error checking, and I'm happy to leave it at that.</p>
<p>My question is: how do people distributing Python code make sure the end users (with zero interest in debugging or modifying the code) run the optimized version of the code. Surely there's some better way than just telling people to make sure they use optimization in the release notes (which they probably won't read anyway) ?</p>
<p>On Linux I can easily provide a <code>./game</code> script to run the file for end users:</p>
<pre><code>#!/bin/sh
PYTHONOPTIMIZE=1 ./game.py $*
</code></pre>
<p>but that's not very cross-platform.</p>
<p>I have an idea I ought to be able to change the <code>#!</code> line to </p>
<pre><code>#!/usr/bin/env PYTHONOPTIMIZE=1 python
</code></pre>
<p>or</p>
<pre><code>#!/usr/bin/env python -O
</code></pre>
<p>but those don't seem to work as expected, and I'm not sure what they'd do on Windows.</p>
<p>Is there some way of controlling optimization from within the code I'm unaware of ?
Something like:</p>
<pre><code> import runtime
runtime.optimize(True)
</code></pre>
<p>What's considered best-practice in this area by people shipping multi-platform python code ?</p>
| 5 | 2009-07-07T13:06:14Z | 1,092,266 | <p><strong>"On Linux I can easily provide a ./game script to run the file for end users:"</strong></p>
<p>Correct.</p>
<p><strong>"but that's not very cross-platform."</strong></p>
<p>Half-correct. There are exactly two shell languages that matter. Standard Linux "sh" and Non-standard Windows "bat" (a/k/a cmd.exe) and that's all there is nowadays. [When I was a kid, there was Open VMS DCL and Data General's weird shell language and RSX-11 and all kinds of great stuff. Thank God for the Posix standard.]</p>
<p>game.sh</p>
<pre><code>python -O game.py
</code></pre>
<p>game.bat</p>
<pre><code>python -O game.py
</code></pre>
<p>Interestingly the files are the same, only the extension (and the file format) had to be changed to make the various OS's happy.</p>
<p>If you want <strong>true</strong> one-size-fits-all cross platform, you have to remember that Python is a shell language. This kind of thing works, also.</p>
<p>game-startup.py</p>
<pre><code>import subprocess
subprocess.Popen( "python -O game.py" )
</code></pre>
| 14 | 2009-07-07T13:11:41Z | [
"python",
"optimization",
"pyglet",
"multiplatform"
] |
Programmatic control of python optimization? | 1,092,243 | <p>I've been playing with <a href="http://www.pyglet.org/index.html" rel="nofollow">pyglet</a>. It's very nice. However, if I run my code, which is in an executable file (call it game.py) prefixed with the usual</p>
<pre><code>#!/usr/bin/env python
</code></pre>
<p>by doing</p>
<pre><code>./game.py
</code></pre>
<p>then it's a bit clunky. But if I run it with</p>
<pre><code>python -O ./game.py
</code></pre>
<p>or </p>
<pre><code>PYTHONOPTIMIZE=1 ./game.py
</code></pre>
<p>then its super-smooth.</p>
<p>I'm don't care much why it runs slow without optimization; pyglet's documentation mentions that optimizing disables numerous asserts and also OpenGL's error checking, and I'm happy to leave it at that.</p>
<p>My question is: how do people distributing Python code make sure the end users (with zero interest in debugging or modifying the code) run the optimized version of the code. Surely there's some better way than just telling people to make sure they use optimization in the release notes (which they probably won't read anyway) ?</p>
<p>On Linux I can easily provide a <code>./game</code> script to run the file for end users:</p>
<pre><code>#!/bin/sh
PYTHONOPTIMIZE=1 ./game.py $*
</code></pre>
<p>but that's not very cross-platform.</p>
<p>I have an idea I ought to be able to change the <code>#!</code> line to </p>
<pre><code>#!/usr/bin/env PYTHONOPTIMIZE=1 python
</code></pre>
<p>or</p>
<pre><code>#!/usr/bin/env python -O
</code></pre>
<p>but those don't seem to work as expected, and I'm not sure what they'd do on Windows.</p>
<p>Is there some way of controlling optimization from within the code I'm unaware of ?
Something like:</p>
<pre><code> import runtime
runtime.optimize(True)
</code></pre>
<p>What's considered best-practice in this area by people shipping multi-platform python code ?</p>
| 5 | 2009-07-07T13:06:14Z | 1,097,256 | <p>Answering your question (as opposing to fixing your problem, which S. Lott did perfectly), I think a lot of the time people who distribute Python code don't worry about this, because it's rare for the optimisation flag to have any effect. I believe Pyglet is the only exception I've heard of in years of using Python. Quoting from the <a href="http://docs.python.org/tutorial/modules.html" rel="nofollow">Python docs</a>, <em>"The optimizer currently doesnât help much; it only removes assert statements".</em></p>
| 2 | 2009-07-08T10:25:15Z | [
"python",
"optimization",
"pyglet",
"multiplatform"
] |
What is the correct way to "pipe" Maven's output in Python to the screen when used in a Python shell script? | 1,092,299 | <p>My Python utility script contains UNIX system calls such as </p>
<pre><code>status, output = commands.getstatusoutput("ls -ltr")
print "Output: ", output
print "Status: ", status
</code></pre>
<p>Which work fine and print the output to the console but as soon as I run Maven from the same script,</p>
<pre><code>status, output = commands.getstatusoutput("mvn clean install -s./../../foo/bar/settings.xml -Dportal -Dmain.dir=${PWD}/../.. -o")
print "Output: ", output
print "Status: ", status
</code></pre>
<p>The output is not read out like the previous regular system commands. The Maven command in quotes works fine if I simply execute it from the command line. What is the correct way to pipe Maven's output to the screen?</p>
| 0 | 2009-07-07T13:21:56Z | 1,092,345 | <p>Are you sure that <code>${PWD}</code> is properly expanded? If not, try:</p>
<pre><code>status, output = commands.getstatusoutput("mvn clean install -s./../../foo/bar/settings.xml -Dportal -Dmain.dir=%s/../.. -o" % os.getcwd ())
</code></pre>
| 0 | 2009-07-07T13:29:45Z | [
"python",
"unix",
"shell",
"maven-2"
] |
want to get mac address of remote PC | 1,092,379 | <p>I have my web page in python, i am able to get the ip address of the user, who will be accessing our web page, we want to get the mac address of the user's PC, is it possible in python, we are using linux PC, we want to get it on linux.</p>
| 1 | 2009-07-07T13:35:37Z | 1,092,392 | <p>All you can access is what the user sends to you.</p>
<p>MAC address is not part of that data.</p>
| 1 | 2009-07-07T13:38:25Z | [
"python",
"python-3.x"
] |
want to get mac address of remote PC | 1,092,379 | <p>I have my web page in python, i am able to get the ip address of the user, who will be accessing our web page, we want to get the mac address of the user's PC, is it possible in python, we are using linux PC, we want to get it on linux.</p>
| 1 | 2009-07-07T13:35:37Z | 1,092,395 | <p><a href="http://code.activestate.com/recipes/347812/" rel="nofollow">from Active code</a> </p>
<pre><code>#!/usr/bin/env python
import ctypes
import socket
import struct
def get_macaddress(host):
""" Returns the MAC address of a network host, requires >= WIN2K. """
# Check for api availability
try:
SendARP = ctypes.windll.Iphlpapi.SendARP
except:
raise NotImplementedError('Usage only on Windows 2000 and above')
# Doesn't work with loopbacks, but let's try and help.
if host == '127.0.0.1' or host.lower() == 'localhost':
host = socket.gethostname()
# gethostbyname blocks, so use it wisely.
try:
inetaddr = ctypes.windll.wsock32.inet_addr(host)
if inetaddr in (0, -1):
raise Exception
except:
hostip = socket.gethostbyname(host)
inetaddr = ctypes.windll.wsock32.inet_addr(hostip)
buffer = ctypes.c_buffer(6)
addlen = ctypes.c_ulong(ctypes.sizeof(buffer))
if SendARP(inetaddr, 0, ctypes.byref(buffer), ctypes.byref(addlen)) != 0:
raise WindowsError('Retreival of mac address(%s) - failed' % host)
# Convert binary data into a string.
macaddr = ''
for intval in struct.unpack('BBBBBB', buffer):
if intval > 15:
replacestr = '0x'
else:
replacestr = 'x'
macaddr = ''.join([macaddr, hex(intval).replace(replacestr, '')])
return macaddr.upper()
if __name__ == '__main__':
print 'Your mac address is %s' % get_macaddress('localhost')
</code></pre>
| 2 | 2009-07-07T13:39:04Z | [
"python",
"python-3.x"
] |
want to get mac address of remote PC | 1,092,379 | <p>I have my web page in python, i am able to get the ip address of the user, who will be accessing our web page, we want to get the mac address of the user's PC, is it possible in python, we are using linux PC, we want to get it on linux.</p>
| 1 | 2009-07-07T13:35:37Z | 1,092,409 | <p>I have a small, signed Java Applet, which requires Java 6 runtime on the remote computer to do this. It uses the <a href="http://java.sun.com/javase/6/docs/api/java/net/NetworkInterface.html#getHardwareAddress%28%29" rel="nofollow">getHardwareAddress()</a> method on <a href="http://java.sun.com/javase/6/docs/api/java/net/NetworkInterface.html" rel="nofollow">NetworkInterface</a> to obtain the MAC address. I use javascript to access a method in the applet that calls this and returns a JSON object containing the address. This gets stuffed into a hidden field in the form and posted with the rest of the fields.</p>
| 5 | 2009-07-07T13:41:33Z | [
"python",
"python-3.x"
] |
want to get mac address of remote PC | 1,092,379 | <p>I have my web page in python, i am able to get the ip address of the user, who will be accessing our web page, we want to get the mac address of the user's PC, is it possible in python, we are using linux PC, we want to get it on linux.</p>
| 1 | 2009-07-07T13:35:37Z | 1,092,454 | <p>The <a href="http://code.google.com/p/dpkt/" rel="nofollow">dpkt</a> package was <a href="http://stackoverflow.com/questions/85577/search-for-host-with-mac-address-using-python/85632">already mentioned</a> on SO. It allows for parsing TCP/IP packets. I have not yet used it for your case, though.</p>
| 0 | 2009-07-07T13:48:37Z | [
"python",
"python-3.x"
] |
Where do I find the Python Crypto package when installing Paramiko on windows? | 1,092,402 | <p>I am trying to SFTP from Python running on windows and installed Paramiko as was recommended here. Unfortunately, it asks for Crypto.Util.randpool so I need to install the Crypto package. I found RPMS for Linux, but can't find anything or source code for windows.</p>
<p>The readme for Paramiko states:
pycrypto compiled for Win32 can be downloaded from the HashTar homepage:
<a href="http://nitace.bsd.uchicago.edu:8080/hashtar" rel="nofollow">http://nitace.bsd.uchicago.edu:8080/hashtar</a>. </p>
<p>Unfortunately, that link does not work.
Neither does the link to given from PCrypto's homepage. </p>
<p>Any idea how to overcome this? </p>
| 3 | 2009-07-07T13:40:06Z | 1,092,441 | <p>See <a href="http://www.voidspace.org.uk/python/modules.shtml#pycrypto" rel="nofollow">here</a> for Win32 binaries for Python 2.2 through to 2.7</p>
| 6 | 2009-07-07T13:46:05Z | [
"python",
"paramiko"
] |
Windows XP - mute/unmute audio in programmatically in Python | 1,092,466 | <p>My machine has two audio inputs: a mic in that I use for gaming, and a line in that I use for guitar. When using one it's important that the other be muted to remove hiss/static, so I was hoping to write a small script that would toggle which one was muted (it's fairly inconvenient to click through the tray icon, switch to my input device, mute and unmute).</p>
<p>I thought perhaps I could do this with <a href="http://python.net/crew/mhammond/" rel="nofollow">pywin32</a>, but <a href="http://stackoverflow.com/questions/255419/how-can-i-mute-unmute-my-sound-from-powershell">everything</a> I could <a href="http://www.geekpedia.com/tutorial176%5FGet-and-set-the-wave-sound-volume.html" rel="nofollow">find</a> seemed specific to setting the output volume rather than input, and I'm not familiar enough with win32 to even know where to look for better info.</p>
<p>Could anybody point me in the right direction?</p>
| 1 | 2009-07-07T13:50:58Z | 1,093,445 | <p><strong><em>Disclaimer:</strong> I'm not a windows programming guru by any means...but here's my best guess</em></p>
<p>Per the <a href="http://python.net/crew/mhammond/win32/FAQ.html" rel="nofollow">pywin32 FAQ</a>:</p>
<blockquote>
<p><strong>How do I use the exposed Win32 functions to do xyz?</strong></p>
<p>In general, the trick is to not
consider it a Python/PyWin32 question
at all, but to search for
documentation or examples of your
problem, regardless of the language.
This will generally give you the
information you need to perform the
same operations using these
extensions. The included
documentation will tell you the
arguments and return types of the
functions so you can easily determine
the correct way to "spell" things in
Python.</p>
</blockquote>
<p>Sounds like you're looking to control the "endpoint device" volumes (i.e. your sound card / line-in). Here's the <a href="http://msdn.microsoft.com/en-us/library/dd370832%28VS.85%29.aspx" rel="nofollow">API reference</a> in that direction.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/dd370825%28VS.85%29.aspx" rel="nofollow">Here</a>'s a slightly broader look at controlling audio devices in windows if the previous wasn't what you're looking for.</p>
<p><a href="http://blog.xploiter.com/c-and-aspnet/muting-audio-channels-mixer-control-api/" rel="nofollow">Here</a>'s a blog entry from someone who did what you're trying to do in C# (I know you specified python, but you might be able to extract the correct API calls from the code).</p>
<p>Good luck! And if you do get working code, I'm interested to see it.</p>
| 4 | 2009-07-07T16:42:40Z | [
"python",
"windows",
"winapi",
"audio",
"pywin32"
] |
Windows XP - mute/unmute audio in programmatically in Python | 1,092,466 | <p>My machine has two audio inputs: a mic in that I use for gaming, and a line in that I use for guitar. When using one it's important that the other be muted to remove hiss/static, so I was hoping to write a small script that would toggle which one was muted (it's fairly inconvenient to click through the tray icon, switch to my input device, mute and unmute).</p>
<p>I thought perhaps I could do this with <a href="http://python.net/crew/mhammond/" rel="nofollow">pywin32</a>, but <a href="http://stackoverflow.com/questions/255419/how-can-i-mute-unmute-my-sound-from-powershell">everything</a> I could <a href="http://www.geekpedia.com/tutorial176%5FGet-and-set-the-wave-sound-volume.html" rel="nofollow">find</a> seemed specific to setting the output volume rather than input, and I'm not familiar enough with win32 to even know where to look for better info.</p>
<p>Could anybody point me in the right direction?</p>
| 1 | 2009-07-07T13:50:58Z | 1,093,624 | <p>You are probably better off using <code>ctypes</code> - <code>pywin32</code> is good if you are using one of the already included APIs, but I think you'll be out of luck with the sound APIs. Together with the example code from the C# link provided by <code>tgray</code>, use <code>ctypes</code> and <code>winmm.dll</code>, or alternatively, use <code>SWIG</code> to wrap <code>winmm.dll</code>. This may well be quicker as you won't have to build C structure mapping types in <code>ctypes</code> for the types such as <code>MIXERCONTROLDETAILS</code> which are used in the API calls.</p>
| 1 | 2009-07-07T17:22:31Z | [
"python",
"windows",
"winapi",
"audio",
"pywin32"
] |
Windows XP - mute/unmute audio in programmatically in Python | 1,092,466 | <p>My machine has two audio inputs: a mic in that I use for gaming, and a line in that I use for guitar. When using one it's important that the other be muted to remove hiss/static, so I was hoping to write a small script that would toggle which one was muted (it's fairly inconvenient to click through the tray icon, switch to my input device, mute and unmute).</p>
<p>I thought perhaps I could do this with <a href="http://python.net/crew/mhammond/" rel="nofollow">pywin32</a>, but <a href="http://stackoverflow.com/questions/255419/how-can-i-mute-unmute-my-sound-from-powershell">everything</a> I could <a href="http://www.geekpedia.com/tutorial176%5FGet-and-set-the-wave-sound-volume.html" rel="nofollow">find</a> seemed specific to setting the output volume rather than input, and I'm not familiar enough with win32 to even know where to look for better info.</p>
<p>Could anybody point me in the right direction?</p>
| 1 | 2009-07-07T13:50:58Z | 1,093,683 | <p><strong>tgray</strong> seems to have pointed you in the right direction, but once you find out the right Win32 APIs to deal with, you have a couple of options:</p>
<p>1) Try using pywin32...but it may or may not wrap the functionality you need (it probably doesn't). So you probably only want to do this if you need to use COM to get at the functionality you need.</p>
<p>2) Use ctypes. It's generally pretty easy to wrap just about any C functionality with ctypes.</p>
<p>3) If the C# example looks like what you need, you should be able to translate it to IronPython with fairly little effort. Might be easier than using the C API. YMMV, of course.</p>
| 0 | 2009-07-07T17:32:31Z | [
"python",
"windows",
"winapi",
"audio",
"pywin32"
] |
Windows XP - mute/unmute audio in programmatically in Python | 1,092,466 | <p>My machine has two audio inputs: a mic in that I use for gaming, and a line in that I use for guitar. When using one it's important that the other be muted to remove hiss/static, so I was hoping to write a small script that would toggle which one was muted (it's fairly inconvenient to click through the tray icon, switch to my input device, mute and unmute).</p>
<p>I thought perhaps I could do this with <a href="http://python.net/crew/mhammond/" rel="nofollow">pywin32</a>, but <a href="http://stackoverflow.com/questions/255419/how-can-i-mute-unmute-my-sound-from-powershell">everything</a> I could <a href="http://www.geekpedia.com/tutorial176%5FGet-and-set-the-wave-sound-volume.html" rel="nofollow">find</a> seemed specific to setting the output volume rather than input, and I'm not familiar enough with win32 to even know where to look for better info.</p>
<p>Could anybody point me in the right direction?</p>
| 1 | 2009-07-07T13:50:58Z | 1,094,204 | <p>I had a similar problem and couldn't figure out how to use Windows API's to do what I wanted. I ended up just automating the GUI with AutoIt. I think that will be the fastest and easiest solution (albeit a "hacky" one). As I <a href="http://stackoverflow.com/questions/1084514/make-your-program-use-a-gui/1092401#1092401">answered</a> earlier today, you can use AutoIT from within Python.</p>
| 2 | 2009-07-07T19:11:01Z | [
"python",
"windows",
"winapi",
"audio",
"pywin32"
] |
Event system in Python | 1,092,531 | <p>What event system for Python do you use? I'm already aware of <a href="http://pydispatcher.sourceforge.net/">pydispatcher</a>, but I was wondering what else can be found, or is commonly used?</p>
<p>I'm not interested in event managers that are part of large frameworks, I'd rather use a small bare-bones solution that I can easily extend.</p>
| 111 | 2009-07-07T14:00:51Z | 1,092,617 | <p>I use <a href="http://pypi.python.org/pypi/zope.event" rel="nofollow">zope.event</a>. It's the most bare bones you can imagine. :-)
In fact, here is the complete source code:</p>
<pre><code>subscribers = []
def notify(event):
for subscriber in subscribers:
subscriber(event)
</code></pre>
<p>Note that you can't send messages between processes, for example. It's not a messaging system, just an event system, nothing more, nothing less.</p>
| 10 | 2009-07-07T14:19:39Z | [
"python",
"events",
"event-handling",
"dispatcher"
] |
Event system in Python | 1,092,531 | <p>What event system for Python do you use? I'm already aware of <a href="http://pydispatcher.sourceforge.net/">pydispatcher</a>, but I was wondering what else can be found, or is commonly used?</p>
<p>I'm not interested in event managers that are part of large frameworks, I'd rather use a small bare-bones solution that I can easily extend.</p>
| 111 | 2009-07-07T14:00:51Z | 1,092,860 | <p>If I do code in pyQt I use QT sockets/signals paradigm, same is for django</p>
<p>If I'm doing async I/O I use native select module</p>
<p>If I'm usign a SAX python parser I'm using event API provided by SAX. So it looks like I'm victim of underlying API :-)</p>
<p>Maybe you should ask yourself what do you expect from event framework/module. My personal preference is to use Socket/Signal paradigm from QT. more info about that can be found <a href="http://techbase.kde.org/Development/Tutorials/Python%5Fintroduction%5Fto%5Fsignals%5Fand%5Fslots" rel="nofollow">here</a></p>
| 1 | 2009-07-07T15:02:48Z | [
"python",
"events",
"event-handling",
"dispatcher"
] |
Event system in Python | 1,092,531 | <p>What event system for Python do you use? I'm already aware of <a href="http://pydispatcher.sourceforge.net/">pydispatcher</a>, but I was wondering what else can be found, or is commonly used?</p>
<p>I'm not interested in event managers that are part of large frameworks, I'd rather use a small bare-bones solution that I can easily extend.</p>
| 111 | 2009-07-07T14:00:51Z | 1,094,423 | <p>We use an EventHook as suggested from Michael Foord in his <a href="http://www.voidspace.org.uk/python/weblog/arch_d7_2007_02_03.shtml#e616">Event Pattern</a>:</p>
<p>Just add EventHooks to your classes with:</p>
<pre><code>class MyBroadcaster()
def __init__():
self.onChange = EventHook()
theBroadcaster = MyBroadcaster()
# add a listener to the event
theBroadcaster.onChange += myFunction
# remove listener from the event
theBroadcaster.onChange -= myFunction
# fire event
theBroadcaster.onChange.fire()
</code></pre>
<p>We add the functionality to remove all listener from an object to Michaels class and ended up with this:</p>
<pre><code>class EventHook(object):
def __init__(self):
self.__handlers = []
def __iadd__(self, handler):
self.__handlers.append(handler)
return self
def __isub__(self, handler):
self.__handlers.remove(handler)
return self
def fire(self, *args, **keywargs):
for handler in self.__handlers:
handler(*args, **keywargs)
def clearObjectHandlers(self, inObject):
for theHandler in self.__handlers:
if theHandler.im_self == inObject:
self -= theHandler
</code></pre>
| 58 | 2009-07-07T19:46:51Z | [
"python",
"events",
"event-handling",
"dispatcher"
] |
Event system in Python | 1,092,531 | <p>What event system for Python do you use? I'm already aware of <a href="http://pydispatcher.sourceforge.net/">pydispatcher</a>, but I was wondering what else can be found, or is commonly used?</p>
<p>I'm not interested in event managers that are part of large frameworks, I'd rather use a small bare-bones solution that I can easily extend.</p>
| 111 | 2009-07-07T14:00:51Z | 1,096,614 | <p>I found this small script on <a href="http://www.valuedlessons.com/2008/04/events-in-python.html">Valued Lessons</a>. It seems to have just the right simplicity/power ratio I'm after. Peter Thatcher is the author of following code (no licensing is mentioned).</p>
<pre><code>class Event:
def __init__(self):
self.handlers = set()
def handle(self, handler):
self.handlers.add(handler)
return self
def unhandle(self, handler):
try:
self.handlers.remove(handler)
except:
raise ValueError("Handler is not handling this event, so cannot unhandle it.")
return self
def fire(self, *args, **kargs):
for handler in self.handlers:
handler(*args, **kargs)
def getHandlerCount(self):
return len(self.handlers)
__iadd__ = handle
__isub__ = unhandle
__call__ = fire
__len__ = getHandlerCount
class MockFileWatcher:
def __init__(self):
self.fileChanged = Event()
def watchFiles(self):
source_path = "foo"
self.fileChanged(source_path)
def log_file_change(source_path):
print "%r changed." % (source_path,)
def log_file_change2(source_path):
print "%r changed!" % (source_path,)
watcher = MockFileWatcher()
watcher.fileChanged += log_file_change2
watcher.fileChanged += log_file_change
watcher.fileChanged -= log_file_change2
watcher.watchFiles()
</code></pre>
| 8 | 2009-07-08T07:32:24Z | [
"python",
"events",
"event-handling",
"dispatcher"
] |
Event system in Python | 1,092,531 | <p>What event system for Python do you use? I'm already aware of <a href="http://pydispatcher.sourceforge.net/">pydispatcher</a>, but I was wondering what else can be found, or is commonly used?</p>
<p>I'm not interested in event managers that are part of large frameworks, I'd rather use a small bare-bones solution that I can easily extend.</p>
| 111 | 2009-07-07T14:00:51Z | 1,097,401 | <p>Here's another <a href="http://home.gna.org/py-notify/" rel="nofollow">module</a> for consideration. It seems a viable choice for more demanding applications.</p>
<blockquote>
<p>Py-notify is a Python package
providing tools for implementing
Observer programming pattern. These
tools include signals, conditions and
variables.</p>
<p>Signals are lists of handlers that are
called when signal is emitted.
Conditions are basically boolean
variables coupled with a signal that
is emitted when condition state
changes. They can be combined using
standard logical operators (not, and,
etc.) into compound conditions.
Variables, unlike conditions, can hold
any Python object, not just booleans,
but they cannot be combined.</p>
</blockquote>
| 1 | 2009-07-08T11:10:07Z | [
"python",
"events",
"event-handling",
"dispatcher"
] |
Event system in Python | 1,092,531 | <p>What event system for Python do you use? I'm already aware of <a href="http://pydispatcher.sourceforge.net/">pydispatcher</a>, but I was wondering what else can be found, or is commonly used?</p>
<p>I'm not interested in event managers that are part of large frameworks, I'd rather use a small bare-bones solution that I can easily extend.</p>
| 111 | 2009-07-07T14:00:51Z | 2,022,629 | <p>I've been doing it this way:</p>
<pre><code>class Event(list):
"""Event subscription.
A list of callable objects. Calling an instance of this will cause a
call to each item in the list in ascending order by index.
Example Usage:
>>> def f(x):
... print 'f(%s)' % x
>>> def g(x):
... print 'g(%s)' % x
>>> e = Event()
>>> e()
>>> e.append(f)
>>> e(123)
f(123)
>>> e.remove(f)
>>> e()
>>> e += (f, g)
>>> e(10)
f(10)
g(10)
>>> del e[0]
>>> e(2)
g(2)
"""
def __call__(self, *args, **kwargs):
for f in self:
f(*args, **kwargs)
def __repr__(self):
return "Event(%s)" % list.__repr__(self)
</code></pre>
<p>However, like with everything else I've seen, there is no auto generated pydoc for this, and no signatures, which really sucks.</p>
| 53 | 2010-01-07T18:28:47Z | [
"python",
"events",
"event-handling",
"dispatcher"
] |
Event system in Python | 1,092,531 | <p>What event system for Python do you use? I'm already aware of <a href="http://pydispatcher.sourceforge.net/">pydispatcher</a>, but I was wondering what else can be found, or is commonly used?</p>
<p>I'm not interested in event managers that are part of large frameworks, I'd rather use a small bare-bones solution that I can easily extend.</p>
| 111 | 2009-07-07T14:00:51Z | 16,192,256 | <p>Wrapping up the various event systems that are mentioned in the answers here:</p>
<p>The most basic style of event system is the 'bag of handler methods', which is a simple implementation of the <a href="http://en.wikipedia.org/wiki/Observer_pattern">Observer pattern</a>. Basically, the handler methods (callables) are stored in an array and are each called when the event 'fires'.</p>
<ul>
<li><a href="https://pypi.python.org/pypi/zope.event">zope.event</a> shows the bare bones of how this works (see <a href="http://stackoverflow.com/a/1092617/1075152">Lennart's answer</a>). Note: this example does not even support handler arguments.</li>
<li><a href="http://stackoverflow.com/a/2022629/1075152">LongPoke's 'callable list'</a> implementation shows that such an event system can be implemented very minimalistically by subclassing <code>list</code>.</li>
<li><a href="http://stackoverflow.com/a/1094423/1075152">spassig's EventHook</a> (Michael Foord's Event Pattern) is a straightforward implementation.</li>
<li><a href="http://stackoverflow.com/a/1096614/1075152">Josip's Valued Lessons Event class</a> is basically the same, but uses a <code>set</code> instead of a <code>list</code> to store the bag, and implements <code>__call__</code> which are both reasonable additions.</li>
<li><a href="http://home.gna.org/py-notify/">PyNotify</a> is similar in concept and also provides additional concepts of variables and conditions ('variable changed event').</li>
<li><a href="https://pypi.python.org/pypi/axel">axel</a> is basically a bag-of-handlers with more features related to threading, error handling, ...</li>
</ul>
<p>The disadvantage of these event systems is that you can only register the handlers on the actual Event object (or handlers list).
So at registration time the event already needs to exist.</p>
<p>That's why the second style of event systems exists: the <a href="http://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern">publish-subscribe pattern</a>.
Here, the handlers don't register on an event object (or handler list), but on a central dispatcher. Also the notifiers only talk to the dispatcher. What to listen for, or what to publish is determined by 'signal', which is nothing more than a name (string).</p>
<ul>
<li><a href="https://pythonhosted.org/blinker/">blinker</a> has some nifty features such as automatic disconnection and filtering based on sender.</li>
<li><a href="http://pubsub.sourceforge.net/">PyPubSub</a> at first sight seems to be pretty straightforward; apparently does not yet support Python3</li>
<li><a href="http://pydispatcher.sourceforge.net/">PyDispatcher</a> seems to emphasize flexibility with regards to many-to-many publication etc.</li>
<li><a href="https://github.com/11craft/louie">louie</a> is a reworked PyDispatcher "providing plugin infrastructure including Twisted and PyQt specific support".</li>
<li><a href="https://code.djangoproject.com/browser/django/trunk/django/dispatch">django.dispatch</a> is a rewritten PyDispatcher "with a more limited interface, but higher performance".</li>
<li>Qt's Signals and Slots are available from <a href="http://pyqt.sourceforge.net/Docs/PyQt4/new_style_signals_slots.html">PyQt</a> or <a href="https://wiki.qt.io/Signals_and_Slots_in_PySide">PySide</a>. They work as callback when used in the same thread, or as events (using an event loop) between two different threads. Signals and Slots have the limitation that they only work in objects of classes that derive from <code>QObject</code>.</li>
</ul>
<p>Note: <a href="https://docs.python.org/3.5/library/threading.html#event-objects">threading.Event</a> is not an 'event system' in the above sense. It's a thread synchronization system where one thread waits until another thread 'signals' the Event object.</p>
| 59 | 2013-04-24T12:38:55Z | [
"python",
"events",
"event-handling",
"dispatcher"
] |
Event system in Python | 1,092,531 | <p>What event system for Python do you use? I'm already aware of <a href="http://pydispatcher.sourceforge.net/">pydispatcher</a>, but I was wondering what else can be found, or is commonly used?</p>
<p>I'm not interested in event managers that are part of large frameworks, I'd rather use a small bare-bones solution that I can easily extend.</p>
| 111 | 2009-07-07T14:00:51Z | 20,807,692 | <p>I created an <code>EventManager</code> class (code at the end). The syntax is the following:</p>
<pre><code>#Create an event with no listeners assigned to it
EventManager.addEvent( eventName = [] )
#Create an event with listeners assigned to it
EventManager.addEvent( eventName = [fun1, fun2,...] )
#Create any number event with listeners assigned to them
EventManager.addEvent( eventName1 = [e1fun1, e1fun2,...], eventName2 = [e2fun1, e2fun2,...], ... )
#Add or remove listener to an existing event
EventManager.eventName += extra_fun
EventManager.eventName -= removed_fun
#Delete an event
del EventManager.eventName
#Fire the event
EventManager.eventName()
</code></pre>
<p>Here is an Example:</p>
<pre><code>def hello(name):
print "Hello {}".format(name)
def greetings(name):
print "Greetings {}".format(name)
EventManager.addEvent( salute = [greetings] )
EventManager.salute += hello
print "\nInitial salute"
EventManager.salute('Oscar')
print "\nNow remove greetings"
EventManager.salute -= greetings
EventManager.salute('Oscar')
</code></pre>
<p>Output:</p>
<blockquote>
<p>Initial salute <br>
Greetings Oscar <br>
Hello Oscar <br></p>
<p>Now remove greetings <br>
Hello Oscar</p>
</blockquote>
<p>EventManger Code:</p>
<pre><code>class EventManager:
class Event:
def __init__(self,functions):
if type(functions) is not list:
raise ValueError("functions parameter has to be a list")
self.functions = functions
def __iadd__(self,func):
self.functions.append(func)
return self
def __isub__(self,func):
self.functions.remove(func)
return self
def __call__(self,*args,**kvargs):
for func in self.functions : func(*args,**kvargs)
@classmethod
def addEvent(cls,**kvargs):
"""
addEvent( event1 = [f1,f2,...], event2 = [g1,g2,...], ... )
creates events using **kvargs to create any number of events. Each event recieves a list of functions,
where every function in the list recieves the same parameters.
Example:
def hello(): print "Hello ",
def world(): print "World"
EventManager.addEvent( salute = [hello] )
EventManager.salute += world
EventManager.salute()
Output:
Hello World
"""
for key in kvargs.keys():
if type(kvargs[key]) is not list:
raise ValueError("value has to be a list")
else:
kvargs[key] = cls.Event(kvargs[key])
cls.__dict__.update(kvargs)
</code></pre>
| 2 | 2013-12-27T20:53:42Z | [
"python",
"events",
"event-handling",
"dispatcher"
] |
Event system in Python | 1,092,531 | <p>What event system for Python do you use? I'm already aware of <a href="http://pydispatcher.sourceforge.net/">pydispatcher</a>, but I was wondering what else can be found, or is commonly used?</p>
<p>I'm not interested in event managers that are part of large frameworks, I'd rather use a small bare-bones solution that I can easily extend.</p>
| 111 | 2009-07-07T14:00:51Z | 28,479,007 | <p>Here is a minimal design that should work fine. What you have to do is to simply inherit <code>Observer</code> in a class and afterwards use <code>observe(event_name, callback_fn)</code> to listen for a specific event. Whenever that specific event is fired anywhere in the code (ie. <code>Event('USB connected')</code>), the corresponding callback will fire.</p>
<pre><code>class Observer():
_observers = []
def __init__(self):
self._observers.append(self)
self._observed_events = []
def observe(self, event_name, callback_fn):
self._observed_events.append({'event_name' : event_name, 'callback_fn' : callback_fn})
class Event():
def __init__(self, event_name, *callback_args):
for observer in Observer._observers:
for observable in observer._observed_events:
if observable['event_name'] == event_name:
observable['callback_fn'](*callback_args)
</code></pre>
<p>Example:</p>
<pre><code>class Room(Observer):
def __init__(self):
print("Room is ready.")
Observer.__init__(self) # DON'T FORGET THIS
def someone_arrived(self, who):
print(who + " has arrived!")
# Observe for specific event
room = Room()
room.observe('someone arrived', room.someone_arrived)
# Fire some events
Event('someone left', 'John')
Event('someone arrived', 'Lenard') # will output "Lenard has arrived!"
Event('someone Farted', 'Lenard')
</code></pre>
| 2 | 2015-02-12T13:43:22Z | [
"python",
"events",
"event-handling",
"dispatcher"
] |
Event system in Python | 1,092,531 | <p>What event system for Python do you use? I'm already aware of <a href="http://pydispatcher.sourceforge.net/">pydispatcher</a>, but I was wondering what else can be found, or is commonly used?</p>
<p>I'm not interested in event managers that are part of large frameworks, I'd rather use a small bare-bones solution that I can easily extend.</p>
| 111 | 2009-07-07T14:00:51Z | 29,059,561 | <p>You may have a look at <a href="https://github.com/riga/pymitter" rel="nofollow">pymitter</a> (<a href="https://pypi.python.org/pypi/pymitter" rel="nofollow">pypi</a>). Its a small single-file (~250 loc) approach
"providing namespaces, wildcards and TTL".</p>
<p>Here's a basic example:</p>
<pre><code>from pymitter import EventEmitter
ee = EventEmitter()
# decorator usage
@ee.on("myevent")
def handler1(arg):
print "handler1 called with", arg
# callback usage
def handler2(arg):
print "handler2 called with", arg
ee.on("myotherevent", handler2)
# emit
ee.emit("myevent", "foo")
# -> "handler1 called with foo"
ee.emit("myotherevent", "bar")
# -> "handler2 called with bar"
</code></pre>
| 3 | 2015-03-15T10:23:32Z | [
"python",
"events",
"event-handling",
"dispatcher"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.