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 |
|---|---|---|---|---|---|---|---|---|---|
Writing XML from Python : Python equivalent of .NET XmlTextWriter? | 1,022,429 | <p>I have some IronPython code which makes use of XmlTextWriter which allows me to write code like</p>
<pre><code>self.writer = System.Xml.XmlTextWriter(filename, None)
self.writer.Formatting = Formatting.Indented
self.writer.WriteStartElement(name)
self.writer.WriteString(str(text))
self.writer.WriteEndElement()
...
self.writer.Close()
</code></pre>
<p>I would like to make my code portable across Python implementations (CPython, IronPython and Jython). Is there a streaming Python XML writer I can use for this without needing to use either print statements, or to construct a whole DOM tree before writing it out to file?</p>
| 3 | 2009-06-20T20:10:28Z | 1,022,437 | <p>I've never used the .NET implementation you're talking about, but it sounds like the closest you're going to get is Python's <a href="http://docs.python.org/library/xml.sax.html" rel="nofollow">SAX parser</a> (specifically, the <a href="http://docs.python.org/library/xml.sax.utils.html#xml.sax.saxutils.XMLGenerator" rel="nofollow">XMLGenerator class</a> -- some sample code <a href="http://www.xml.com/pub/a/2003/03/12/py-xml.html" rel="nofollow">here</a>).</p>
| 2 | 2009-06-20T20:14:54Z | [
"python",
"xml",
"ironpython",
"jython"
] |
Writing XML from Python : Python equivalent of .NET XmlTextWriter? | 1,022,429 | <p>I have some IronPython code which makes use of XmlTextWriter which allows me to write code like</p>
<pre><code>self.writer = System.Xml.XmlTextWriter(filename, None)
self.writer.Formatting = Formatting.Indented
self.writer.WriteStartElement(name)
self.writer.WriteString(str(text))
self.writer.WriteEndElement()
...
self.writer.Close()
</code></pre>
<p>I would like to make my code portable across Python implementations (CPython, IronPython and Jython). Is there a streaming Python XML writer I can use for this without needing to use either print statements, or to construct a whole DOM tree before writing it out to file?</p>
| 3 | 2009-06-20T20:10:28Z | 1,023,168 | <p>I wrote a tool to facilitate XML generation from Python (<a href="http://github.com/billzeller/xmlegant-for-python/tree/master" rel="nofollow">code</a> and <a href="http://www.from.bz/2009/03/28/announcing-xmlegant-for-python/" rel="nofollow">tutorial</a>)</p>
| 2 | 2009-06-21T03:54:44Z | [
"python",
"xml",
"ironpython",
"jython"
] |
Writing XML from Python : Python equivalent of .NET XmlTextWriter? | 1,022,429 | <p>I have some IronPython code which makes use of XmlTextWriter which allows me to write code like</p>
<pre><code>self.writer = System.Xml.XmlTextWriter(filename, None)
self.writer.Formatting = Formatting.Indented
self.writer.WriteStartElement(name)
self.writer.WriteString(str(text))
self.writer.WriteEndElement()
...
self.writer.Close()
</code></pre>
<p>I would like to make my code portable across Python implementations (CPython, IronPython and Jython). Is there a streaming Python XML writer I can use for this without needing to use either print statements, or to construct a whole DOM tree before writing it out to file?</p>
| 3 | 2009-06-20T20:10:28Z | 2,884,756 | <p>I wrote a module named loxun to do just that: <a href="http://pypi.python.org/pypi/loxun/" rel="nofollow">http://pypi.python.org/pypi/loxun/</a>. It runs with CPython 2.5 and Jython 2.5, but I never tried it with IronPython.</p>
<p>Example usage:</p>
<pre><code>with open("...", "wb") as out:
xml = XmlWriter(out)
xml.addNamespace("xhtml", "http://www.w3.org/1999/xhtml")
xml.startTag("xhtml:html")
xml.startTag("xhtml:body")
xml.text("Hello world!")
xml.tag("xhtml:img", {"src": "smile.png", "alt": ":-)"})
xml.endTag()
xml.endTag()
xml.close()
</code></pre>
<p>And the result:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<xhtml:html xlmns:xhtml="http://www.w3.org/1999/xhtml">
<xhtml:body>
Hello world!
<xhtml:img alt=":-)" src="smile.png" />
</xhtml:body>
</xhtml:html>
</code></pre>
<p>Among other features, it detects missalligned tags while you write, uses a streaming API with a small memory footprint, supports Unicode and allows to disable pretty printing.</p>
| 3 | 2010-05-21T18:56:15Z | [
"python",
"xml",
"ironpython",
"jython"
] |
Emulating membership-test in Python: delegating __contains__ to contained-object correctly | 1,022,499 | <p>I am used to that Python allows some neat tricks to delegate functionality to other objects. One example is delegation to contained objects.</p>
<p>But it seams, that I don't have luck, when I want to delegate __contains __:</p>
<pre><code>class A(object):
def __init__(self):
self.mydict = {}
self.__contains__ = self.mydict.__contains__
a = A()
1 in a
</code></pre>
<p>I get:</p>
<pre><code>Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: argument of type 'A' is not iterable
</code></pre>
<p>What I am making wrong? When I call a.__contains __(1), everything goes smooth. I even tried to define an __iter __ method in A to make A more look like an iterable, but it did not help. What I am missing out here?</p>
| 6 | 2009-06-20T20:39:05Z | 1,022,505 | <p>Special methods such as <code>__contains__</code> are only special when defined on the class, not on the instance (except in legacy classes in Python 2, which you should <em>not</em> use anyway).</p>
<p>So, do your delegation at class level:</p>
<pre><code>class A(object):
def __init__(self):
self.mydict = {}
def __contains__(self, other):
return self.mydict.__contains__(other)
</code></pre>
<p>I'd actually prefer to spell the latter as <code>return other in self.mydict</code>, but that's a minor style issue.</p>
<p><strong>Edit</strong>: if and when "totally dynamic per-instance redirecting of special methods" (like old-style classes offered) is indispensable, it's not hard to implement it with new-style classes: you just need each instance that has such peculiar need to be wrapped in its own special class. For example:</p>
<pre><code>class BlackMagic(object):
def __init__(self):
self.mydict = {}
self.__class__ = type(self.__class__.__name__, (self.__class__,), {})
self.__class__.__contains__ = self.mydict.__contains__
</code></pre>
<p>Essentially, after the little bit of black magic reassigning <code>self.__class__</code> to a new class object (which behaves just like the previous one but has an empty dict and no other instances except this one <code>self</code>), anywhere in an old-style class you would assign to <code>self.__magicname__</code>, assign to <code>self.__class__.__magicname__</code> instead (and make sure it's a built-in or <code>staticmethod</code>, not a normal Python function, unless of course in some different case you do want it to receive the <code>self</code> when called on the instance).</p>
<p>Incidentally, the <code>in</code> operator on an instance of this <code>BlackMagic</code> class is <em>faster</em>, as it happens, than with any of the previously proposed solutions -- or at least so I'm measuring with my usual trusty <code>-mtimeit</code> (going directly to the <code>built-in method</code>, instead of following normal lookup routes involving inheritance and descriptors, shaves a bit of the overhead).</p>
<p>A metaclass to automate the <code>self.__class__</code>-per-instance idea would not be hard to write (it could do the dirty work in the generated class's <code>__new__</code> method, and maybe also set all magic names to actually assign on the class if assigned on the instance, either via <code>__setattr__</code> or many, <em>many</em> properties). But that would be justified only if the need for this feature was really widespread (e.g. porting a huge ancient Python 1.5.2 project that liberally use "per-instance special methods" to modern Python, including Python 3).</p>
<p>Do I <em>recommend</em> "clever" or "black magic" solutions? No, I don't: almost invariably it's better to do things in simple, straightforward ways. But "almost" is an important word here, and it's nice to have at hand such advanced "hooks" for the rare, but not non-existent, situations where their use may actually be warranted.</p>
| 17 | 2009-06-20T20:42:37Z | [
"python",
"containers",
"delegation",
"emulation",
"iterable"
] |
Problem getting date with Universal Feed Parser | 1,022,504 | <p>It looks like <a href="http://portland.beerandblog.com/feed/atom/" rel="nofollow">http://portland.beerandblog.com/feed/atom/</a> is messed up (as are the 0.92 and 2.0 RSS feeds). </p>
<p>Universal Feed Parser (latest version from <a href="http://code.google.com/p/feedparser/source/browse/trunk/feedparser/feedparser.py?spec=svn295&r=295" rel="nofollow">http://code.google.com/p/feedparser/source/browse/trunk/feedparser/feedparser.py?spec=svn295&r=295</a> ) doesn't see any dates.</p>
<pre><code> <title>Beer and Blog Portland</title>
<atom:link href="http://portland.beerandblog.com/feed/" rel="self" type="application/rss+xml" />
<link>http://portland.beerandblog.com</link>
<description>Bloggers helping bloggers over beers in Portland, Oregon</description>
<pubDate>Fri, 19 Jun 2009 22:54:57 +0000</pubDate>
<generator>http://wordpress.org/?v=2.7.1</generator>
<language>en</language>
<sy:updatePeriod>hourly</sy:updatePeriod>
<sy:updateFrequency>1</sy:updateFrequency>
<item>
<title>Widmer is sponsoring our beer for the After Party!!</title>
<link>http://portland.beerandblog.com/2009/06/19/widmer-is-sponsoring-our-beer-for-the-after-party/</link>
<comments>http://portland.beerandblog.com/2009/06/19/widmer-is-sponsoring-our-beer-for-the-after-party/#comments</comments>
<pubDate>Fri, 19 Jun 2009 22:30:35 +0000</pubDate>
<dc:creator>Justin Kistner</dc:creator>
<category><![CDATA[beer]]></category>
</code></pre>
<p>I'm trying </p>
<pre>
try:
published = e.published_parsed
except:
try:
published = e.updated_parsed
except:
published = e.created_parsed
</pre>
<p>and it's failing because I can't get a date.</p>
<p>Any thoughts on how to extract the date in a reasonable manner? </p>
<p>Thanks!</p>
| 1 | 2009-06-20T20:42:09Z | 1,022,720 | <p>Using a naked <code>except</code> may be masking a problem in your code. Assuming (I don't use feed parsers) that AttributeError is the specific exception that you should be checking for, try (accidental pun) this:</p>
<pre><code>try:
published = e.published_parsed
except AttributeError:
try:
published = e.updated_parsed
except AttributeError:
published = e.created_parsed
</code></pre>
<p>In any case, instead of "it's failing", please show the error message and traceback.</p>
<p><strong>Edit</strong>
I've download the latest release (i.e. not from svn) and followed the example in the docs with this result:</p>
<pre><code>C:\feedparser>\python26\python
Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import feedparser
>>> d = feedparser.parse('http://portland.beerandblog.com/feed/atom/')
>>> d.entries[0].updated
u'2009-06-19T22:54:57Z'
>>> d.entries[0].updated_parsed
time.struct_time(tm_year=2009, tm_mon=6, tm_mday=19, tm_hour=22, tm_min=54, tm_sec=57, tm_wday=4, tm_yday=170, tm_isdst=0)
>>> d.entries[0].title
u'Widmer is sponsoring our beer for the After Party!!'
>>> d.entries[0].published
u'2009-06-19T22:30:35Z'
>>> d.entries[0].published_parsed
time.struct_time(tm_year=2009, tm_mon=6, tm_mday=19, tm_hour=22, tm_min=30, tm_sec=35, tm_wday=4, tm_yday=170, tm_isdst=0)
>>>
</code></pre>
<p>Like I said, I'm not into RSS and Atoms and suchlike but it seems to be quite straightforward to me. Except that I don't understand where you are getting the <code><pubDate></code> tag and arpanet-style timestamps from; AFAICT that is not present in the raw source -- it has <code><published></code> and ISO timestamps: </p>
<pre><code>>>> import urllib
>>> guff = urllib.urlopen('http://portland.beerandblog.com/feed/atom/').read()
>>> guff.find('pubDate')
-1
>>> guff.find('published')
1171
>>> guff[1160:1200]
'pdated>\n\t\t<published>2009-06-19T22:30:35'
>>>
</code></pre>
<p>What is your "e" in "e.published_parsed"? Consider showing the full story with accessing feedparser, as I did above.</p>
| 1 | 2009-06-20T22:36:49Z | [
"python",
"parsing",
"feeds",
"feed"
] |
Problem getting date with Universal Feed Parser | 1,022,504 | <p>It looks like <a href="http://portland.beerandblog.com/feed/atom/" rel="nofollow">http://portland.beerandblog.com/feed/atom/</a> is messed up (as are the 0.92 and 2.0 RSS feeds). </p>
<p>Universal Feed Parser (latest version from <a href="http://code.google.com/p/feedparser/source/browse/trunk/feedparser/feedparser.py?spec=svn295&r=295" rel="nofollow">http://code.google.com/p/feedparser/source/browse/trunk/feedparser/feedparser.py?spec=svn295&r=295</a> ) doesn't see any dates.</p>
<pre><code> <title>Beer and Blog Portland</title>
<atom:link href="http://portland.beerandblog.com/feed/" rel="self" type="application/rss+xml" />
<link>http://portland.beerandblog.com</link>
<description>Bloggers helping bloggers over beers in Portland, Oregon</description>
<pubDate>Fri, 19 Jun 2009 22:54:57 +0000</pubDate>
<generator>http://wordpress.org/?v=2.7.1</generator>
<language>en</language>
<sy:updatePeriod>hourly</sy:updatePeriod>
<sy:updateFrequency>1</sy:updateFrequency>
<item>
<title>Widmer is sponsoring our beer for the After Party!!</title>
<link>http://portland.beerandblog.com/2009/06/19/widmer-is-sponsoring-our-beer-for-the-after-party/</link>
<comments>http://portland.beerandblog.com/2009/06/19/widmer-is-sponsoring-our-beer-for-the-after-party/#comments</comments>
<pubDate>Fri, 19 Jun 2009 22:30:35 +0000</pubDate>
<dc:creator>Justin Kistner</dc:creator>
<category><![CDATA[beer]]></category>
</code></pre>
<p>I'm trying </p>
<pre>
try:
published = e.published_parsed
except:
try:
published = e.updated_parsed
except:
published = e.created_parsed
</pre>
<p>and it's failing because I can't get a date.</p>
<p>Any thoughts on how to extract the date in a reasonable manner? </p>
<p>Thanks!</p>
| 1 | 2009-06-20T20:42:09Z | 1,022,776 | <p>Works for me:</p>
<pre><code>>>> e = feedparser.parse('http://portland.beerandblog.com/feed/atom/')
>>> e.feed.date
u'2009-06-19T22:54:57Z'
>>> e.feed.date_parsed
(2009, 6, 19, 22, 54, 57, 4, 170, 0)
>>> e.feed.updated_parsed
(2009, 6, 19, 22, 54, 57, 4, 170, 0)
</code></pre>
<p>Maybe you're looking for <code>e.updated_parsed</code> where you should be looking for <code>e.feed.updated_parsed</code> instead?</p>
| 3 | 2009-06-20T23:14:58Z | [
"python",
"parsing",
"feeds",
"feed"
] |
Weighted slope one algorithm? (porting from Python to R) | 1,022,649 | <p>I was reading about the <a href="http://en.wikipedia.org/wiki/Slope%5FOne#Slope%5Fone%5Fcollaborative%5Ffiltering%5Ffor%5Frated%5Fresources">Weighted slope one algorithm</a> ( and more
formally <a href="http://www.daniel-lemire.com/fr/documents/publications/lemiremaclachlan%5Fsdm05.pdf">here (PDF)</a>) which is supposed to take item ratings from different users and, given a user vector containing at least 1 rating and 1 missing value, predict the missing ratings.</p>
<p>I found a <a href="http://www.serpentine.com/wordpress/wp-content/uploads/2006/12/slope%5Fone.py.txt">Python implementation of the algorithm</a>, but I'm having a hard time porting it to <a href="http://www.r-project.org/">R</a> (which I'm more comfortable with). Below is my attempt. Any suggestions on how to make it work?</p>
<p>Thanks in advance, folks.</p>
<pre><code># take a 'training' set, tr.set and a vector with some missing ratings, d
pred=function(tr.set,d) {
tr.set=rbind(tr.set,d)
n.items=ncol(tr.set)
# tally frequencies to use as weights
freqs=sapply(1:n.items, function(i) {
unlist(lapply(1:n.items, function(j) {
sum(!(i==j)&!is.na(tr.set[,i])&!is.na(tr.set[,j])) })) })
# estimate product-by-product mean differences in ratings
diffs=array(NA, dim=c(n.items,n.items))
diffs=sapply(1:n.items, function(i) {
unlist(lapply(1:n.items, function(j) {
diffs[j,i]=mean(tr.set[,i]-tr.set[,j],na.rm=T) })) })
# create an output vector with NAs for all the items the user has already rated
pred.out=as.numeric(is.na(d))
pred.out[!is.na(d)]=NA
a=which(!is.na(pred.out))
b=which(is.na(pred.out))
# calculated the weighted slope one estimate
pred.out[a]=sapply(a, function(i) {
sum(unlist(lapply(b,function (j) {
sum((d[j]+diffs[j,i])*freqs[j,i])/rowSums(freqs)[i] }))) })
names(pred.out)=colnames(tr.set)
return(pred.out) }
# end function
# test, using example from [3]
alice=c(squid=1.0, octopus=0.2, cuttlefish=0.5, nautilus=NA)
bob=c(squid=1.0, octopus=0.5, cuttlefish=NA, nautilus=0.2)
carole=c(squid=0.2, octopus=1.0, cuttlefish=0.4, nautilus=0.4)
dave=c(squid=NA, octopus=0.4, cuttlefish=0.9, nautilus=0.5)
tr.set2=rbind(alice,bob,carole,dave)
lucy2=c(squid=0.4, octopus=NA, cuttlefish=NA, nautilus=NA)
pred(tr.set2,lucy2)
# not correct
# correct(?): {'nautilus': 0.10, 'octopus': 0.23, 'cuttlefish': 0.25}
</code></pre>
| 7 | 2009-06-20T21:53:56Z | 1,054,561 | <p>I used the same reference (Bryan O'Sullivan's python code) to write an R version of Slope One a while back. I'm pasting the code below in case it helps.</p>
<pre><code>predict <- function(userprefs, data.freqs, data.diffs) {
seen <- names(userprefs)
preds <- sweep(data.diffs[ , seen, drop=FALSE], 2, userprefs, '+')
preds <- preds * data.freqs[ , seen]
preds <- apply(preds, 1, sum)
freqs <- apply(data.freqs[ , seen, drop=FALSE], 1, sum)
unseen <- setdiff(names(preds), seen)
result <- preds[unseen] / freqs[unseen]
return(result[is.finite(result)])
}
update <- function(userdata, freqs, diffs) {
for (ratings in userdata) {
items <- names(ratings)
n <- length(ratings)
ratdiff <- rep(ratings, n) - rep(ratings, rep(n, n))
diffs[items, items] <- diffs[items, items] + ratdiff
freqs[items, items] <- freqs[items, items] + 1
}
diffs <- diffs / freqs
return(list(freqs=freqs, diffs=diffs))
}
userdata <- list(alice=c(squid=1.0, cuttlefish=0.5, octopus=0.2),
bob=c(squid=1.0, octopus=0.5, nautilus=0.2),
carole=c(squid=0.2, octopus=1.0, cuttlefish=0.4, nautilus=0.4),
dave=c(cuttlefish=0.9, octopus=0.4, nautilus=0.5))
items <- c('squid', 'cuttlefish', 'nautilus', 'octopus')
n.items <- length(items)
freqs <- diffs <- matrix(0, nrow=n.items, ncol=n.items, dimnames=list(items, items))
result <- update(userdata, freqs, diffs)
print(result$freqs)
print(result$diffs)
userprefs <- c(squid=.4)
predresult <- predict(userprefs, result$freqs, result$diffs)
print(predresult)
</code></pre>
| 9 | 2009-06-28T08:57:29Z | [
"python",
"prediction",
"recommendation-engine"
] |
How can I pass the environment from my Python web application to a Perl program? | 1,022,694 | <p>How do I set Perl's %ENV to introduce a Perl script into the context of my web application?</p>
<p>I have a website, written in a language different from Perl (Python). However I need to use a Perl application, which consists of a .pl file:</p>
<pre><code> #!/usr/bin/env perl
"$ENV{DOCUMENT_ROOT}/foo/bar.pm" =~ /^(.+)$/;
require $1;
my $BAR = new BAR(
user => 'foo',
);
print $bar->get_content;
</code></pre>
<p>... and a module bar.pm, which relies on <code>"$ENV{HTTP_HOST}"</code>, <code>"$ENV{REQUEST_URI}"</code>,
<code>"$ENV{REMOTE_ADDR}"</code> and <code>"$ENV{DOCUMENT_ROOT}"</code>.</p>
<p>How should I set this hash? This is my very first experience with Perl, so I may be missing something really obvious here :)</p>
| 1 | 2009-06-20T22:19:43Z | 1,022,711 | <p>Perl's special <code>%ENV</code> hash is the interface to the environment. (Under the hood, it calls <code>getenv</code> and <code>putenv</code> as appropriate.)</p>
<p>For example:</p>
<pre><code>$ cat run.sh
#! /bin/bash
export REMOTE_ADDR=127.0.0.1
perl -le 'print $ENV{REMOTE_ADDR}'
$ ./run.sh
127.0.0.1
</code></pre>
<p>Your web server ought to be setting these environment variables.</p>
| 2 | 2009-06-20T22:30:14Z | [
"python",
"perl",
"environment"
] |
How can I pass the environment from my Python web application to a Perl program? | 1,022,694 | <p>How do I set Perl's %ENV to introduce a Perl script into the context of my web application?</p>
<p>I have a website, written in a language different from Perl (Python). However I need to use a Perl application, which consists of a .pl file:</p>
<pre><code> #!/usr/bin/env perl
"$ENV{DOCUMENT_ROOT}/foo/bar.pm" =~ /^(.+)$/;
require $1;
my $BAR = new BAR(
user => 'foo',
);
print $bar->get_content;
</code></pre>
<p>... and a module bar.pm, which relies on <code>"$ENV{HTTP_HOST}"</code>, <code>"$ENV{REQUEST_URI}"</code>,
<code>"$ENV{REMOTE_ADDR}"</code> and <code>"$ENV{DOCUMENT_ROOT}"</code>.</p>
<p>How should I set this hash? This is my very first experience with Perl, so I may be missing something really obvious here :)</p>
| 1 | 2009-06-20T22:19:43Z | 1,022,793 | <p>If you're spawning that Perl process from your Python code (as opposed to "directly from the webserver"), there are several ways to set the child process environment from the Python parent process environment, depending on what you're using for the "spawning".</p>
<p>For example, if you're using <code>subprocess.Popen</code>, you can pass an <code>env=</code> argument set to the dictionary you desire, as the <a href="http://docs.python.org/library/subprocess.html" rel="nofollow">docs</a> explain:</p>
<blockquote>
<p>If env is not None, it must be a
mapping that defines the environment
variables for the new process; these
are used instead of inheriting the
current processâ environment, which is
the default behavior.</p>
</blockquote>
| 4 | 2009-06-20T23:29:10Z | [
"python",
"perl",
"environment"
] |
Deploying Django | 1,022,914 | <p>When finding web hosting for Rails apps, the hoster must have support for ruby on rails -- that is evident. What about hosting for Django? What support does the hoster need to provide? Python, or more than just Python?</p>
<p>This might seem like an obvious question, but I'm new to web development frameworks so I must ask :)</p>
| 2 | 2009-06-21T01:00:04Z | 1,022,921 | <p>It just needs to support Python 2.3 or later (but not 3.0, yet), preferably with <code>mod_wsgi</code> support (although it also works with <a href="http://code.djangoproject.com/wiki/ServerArrangements">a bunch of other options</a>, if required).</p>
| 6 | 2009-06-21T01:04:55Z | [
"python",
"ruby-on-rails",
"django"
] |
Deploying Django | 1,022,914 | <p>When finding web hosting for Rails apps, the hoster must have support for ruby on rails -- that is evident. What about hosting for Django? What support does the hoster need to provide? Python, or more than just Python?</p>
<p>This might seem like an obvious question, but I'm new to web development frameworks so I must ask :)</p>
| 2 | 2009-06-21T01:00:04Z | 1,022,932 | <p>Python is all that is needed.</p>
<p>I think there is a cPanel plugin which allows your users to create and deploy Django applications, so if you have a VPS or Reseller account, or your host is running cPanel, you could simply tell them to install it. If I find the link to the plugin I will post it here.</p>
| 2 | 2009-06-21T01:10:17Z | [
"python",
"ruby-on-rails",
"django"
] |
Deploying Django | 1,022,914 | <p>When finding web hosting for Rails apps, the hoster must have support for ruby on rails -- that is evident. What about hosting for Django? What support does the hoster need to provide? Python, or more than just Python?</p>
<p>This might seem like an obvious question, but I'm new to web development frameworks so I must ask :)</p>
| 2 | 2009-06-21T01:00:04Z | 1,023,270 | <p>Technically, as other responders say, the host needs very little (hey, Django even runs with Google app engine for all the latter's limitations!-). But if you want a little bit more (as in, say, <em>support</em> for any issues you might encounter!), I suggest you read <a href="http://djangohosting.org/" rel="nofollow">this site</a> as well -- it will take you but a short time, and it may prove to be really useful info.</p>
| 3 | 2009-06-21T05:22:15Z | [
"python",
"ruby-on-rails",
"django"
] |
Deploying Django | 1,022,914 | <p>When finding web hosting for Rails apps, the hoster must have support for ruby on rails -- that is evident. What about hosting for Django? What support does the hoster need to provide? Python, or more than just Python?</p>
<p>This might seem like an obvious question, but I'm new to web development frameworks so I must ask :)</p>
| 2 | 2009-06-21T01:00:04Z | 1,027,937 | <p>Other responses have covered the technical question, but it should also be mentioned that <a href="http://djangofriendly.com" rel="nofollow">djangofriendly.com</a> is an invaluable resource for selecting a Django web host.</p>
| 3 | 2009-06-22T15:47:24Z | [
"python",
"ruby-on-rails",
"django"
] |
Deploying Django | 1,022,914 | <p>When finding web hosting for Rails apps, the hoster must have support for ruby on rails -- that is evident. What about hosting for Django? What support does the hoster need to provide? Python, or more than just Python?</p>
<p>This might seem like an obvious question, but I'm new to web development frameworks so I must ask :)</p>
| 2 | 2009-06-21T01:00:04Z | 1,857,390 | <p>Well, Python is <strong>not</strong> the <em>only</em> thing need <strong>if you run a dedicated server</strong>.</p>
<p>You need(please correct me if I'm missing something):</p>
<ul>
<li>A webserver which will communicate
with your Django web application,
e.g.: Apache with mod_wsgi.</li>
<li>A database interface, such as MySQL or PostgreSQL (just to mention some popular).</li>
<li>Python.</li>
<li>(Dependencies, Libraries, etc.)</li>
</ul>
<p>You may want to read <a href="http://code.djangoproject.com/wiki/ServerArrangements" rel="nofollow">this</a> or <a href="http://code.djangoproject.com/wiki/DjangoResources#CheatSheetsandQuickStarts" rel="nofollow">some general resources</a></p>
<p><strong>If you use some hosting service</strong>, then you'll probably need to find a provider who claims to be able to run Django ;)</p>
| 0 | 2009-12-07T02:06:17Z | [
"python",
"ruby-on-rails",
"django"
] |
What classes of applications or problems do you prefer Python to strictly OO Languages? | 1,022,971 | <p>I've got a pretty strong background in C-style languages. And have worked on several different types of projects. I have just started taking a serious look at Python after reading <a href="http://oreilly.com/catalog/9780596529321/" rel="nofollow">Programming Collective Intelligence</a>. I understand that Python can solve any problem that C# can, and vice-versa. But I am curious to know from those who use both regularly, when they choose one over the other. Removing other factors, like coworkers experience, etc. </p>
<p>When do you choose to create an application in Python instead of a static typed, purely OO language like C# or Java?</p>
<h2>Edit:</h2>
<p>I was afraid we were going to get off topic a bit with this question. Python is an object oriented language. But, as is stated below it may not be the preferred language when your application will have a very heavy business domain, etc. I am aware that Python uses objects extensively, and that even functions are objects, something that is not true in all of the "OO" languages I brought up earlier. </p>
<p>Despite my poor choice of words in the question (almost no languages fit nicely into two or three word descriptions, and it is really difficult to point out differences in languages without it appearing that you are talking down to a certain class of developer.), I am still very interested in what you have to say about when you prefer Python to other languages.</p>
| 4 | 2009-06-21T01:50:07Z | 1,023,009 | <p>I almost exclusively use Python to support my development of software in other languages. I should stress, this is not a result of some failing in Python, rather that the software domains I am working in tend to have other languages/frameworks that are more appropriate or simply the only option:</p>
<ul>
<li>Web Development : I would love to check out Python on Google App Engine, but at the moment I am doing all my personal web development in PHP.</li>
<li>Desktop Application Development : I use the <a href="http://www.ogre3d.org/" rel="nofollow">Ogre SDK</a> for developing windows screensavers and use C++/Win32 for that.</li>
<li>Server Application Development : Writing server side software for Windows professionally is almost always in C++.</li>
</ul>
<p>However, for all of these application domains I use Python regularly write tools, process data and generally to streamline my development efforts. A few examples here are probably the best way to describe how I tend to use Python:</p>
<ul>
<li>To <a href="http://www.cannonade.net/blog.php?id=1418" rel="nofollow">scape data</a> from existing websites.</li>
<li><a href="http://www.cannonade.net/statistics.php" rel="nofollow">Generate reports</a> based on XML data.</li>
<li>Generate sets of SQL queries to populate databases based on other data formats.</li>
<li>Parse entire C++ projects and pull out a distinct set of error messages and their corresponding error codes.</li>
<li><a href="http://www.cannonade.net/blog.php?id=1389" rel="nofollow">Compare</a> data sets to find data that I have inadvertantly lost.</li>
<li><a href="http://stackoverflow.com/questions/656981/what-software-for-your-own-personal-use-did-you-write/656989#656989">Image processing</a> to generate data for other sotware.</li>
</ul>
<p>Python is such an empowering and useful language that although I have never used it as the primary language for software development, I would like to.</p>
| 3 | 2009-06-21T02:16:06Z | [
"c#",
"java",
"c++",
"python",
"programming-languages"
] |
What classes of applications or problems do you prefer Python to strictly OO Languages? | 1,022,971 | <p>I've got a pretty strong background in C-style languages. And have worked on several different types of projects. I have just started taking a serious look at Python after reading <a href="http://oreilly.com/catalog/9780596529321/" rel="nofollow">Programming Collective Intelligence</a>. I understand that Python can solve any problem that C# can, and vice-versa. But I am curious to know from those who use both regularly, when they choose one over the other. Removing other factors, like coworkers experience, etc. </p>
<p>When do you choose to create an application in Python instead of a static typed, purely OO language like C# or Java?</p>
<h2>Edit:</h2>
<p>I was afraid we were going to get off topic a bit with this question. Python is an object oriented language. But, as is stated below it may not be the preferred language when your application will have a very heavy business domain, etc. I am aware that Python uses objects extensively, and that even functions are objects, something that is not true in all of the "OO" languages I brought up earlier. </p>
<p>Despite my poor choice of words in the question (almost no languages fit nicely into two or three word descriptions, and it is really difficult to point out differences in languages without it appearing that you are talking down to a certain class of developer.), I am still very interested in what you have to say about when you prefer Python to other languages.</p>
| 4 | 2009-06-21T01:50:07Z | 1,023,054 | <p>JavaScript and Python have affected how I program even in C now. I think the best thing about knowing multiple languages is that you get more tools to use mentally, because you often don't have a choice of which language to use.</p>
| 2 | 2009-06-21T02:34:20Z | [
"c#",
"java",
"c++",
"python",
"programming-languages"
] |
What classes of applications or problems do you prefer Python to strictly OO Languages? | 1,022,971 | <p>I've got a pretty strong background in C-style languages. And have worked on several different types of projects. I have just started taking a serious look at Python after reading <a href="http://oreilly.com/catalog/9780596529321/" rel="nofollow">Programming Collective Intelligence</a>. I understand that Python can solve any problem that C# can, and vice-versa. But I am curious to know from those who use both regularly, when they choose one over the other. Removing other factors, like coworkers experience, etc. </p>
<p>When do you choose to create an application in Python instead of a static typed, purely OO language like C# or Java?</p>
<h2>Edit:</h2>
<p>I was afraid we were going to get off topic a bit with this question. Python is an object oriented language. But, as is stated below it may not be the preferred language when your application will have a very heavy business domain, etc. I am aware that Python uses objects extensively, and that even functions are objects, something that is not true in all of the "OO" languages I brought up earlier. </p>
<p>Despite my poor choice of words in the question (almost no languages fit nicely into two or three word descriptions, and it is really difficult to point out differences in languages without it appearing that you are talking down to a certain class of developer.), I am still very interested in what you have to say about when you prefer Python to other languages.</p>
| 4 | 2009-06-21T01:50:07Z | 1,023,110 | <p>My motto is (and has long been) "Python where I can, C++ where I must" (one day I'll find opportunity to actually use Java, C#, &c &C, in a real-world project, but I haven't yet, except for a pilot project in Java 1.1, more tha ten years ago...;-) -- Javascript (with dojo) when code has to run in the client's browser, and SQL when it has to run in the DB server, of course, but C++ and Python are my daily bread on the "normal" servers and clients I develop, and that's the case in all parts of Google I've been working in in 4+ years (there are many parts using Java, too, I just never happened to work there;-). Hmmm, there's pure C when I'm working on the Python core and related extensions, too, of course;-).</p>
<p>Neither Python nor C++ are "strictly OO" -- they're multi-paradigm, and therein lies a good part of their strength in the hands of programmers who are highly skilled at OO <em>and</em> other paradigms, such as functional, generic, declarative, and so forth. I gather C# has pulled in some of each of these too (sometimes surpassing C++, e.g. by offering lambdas), and even Java has had to succumb to some (at least generic) to a tiny extent, so surely it's clear that "one size fits all" <em>doesn't</em> -- multi-paradigm programming is alive and well!-)</p>
<p>C++ (like C) forces me to control all memory carefully (our internal c++ style guide forbids the use of "smart pointers" that amount to poor implementations of garbage collection!-), which multiplies my work a lot, but helps ensure I'm not using one bit of memory more than strictly needed at any time: so, C++ (or C when needed) is the choice when memory is tight and precious. Otherwise, the extremely high productivity of Python (and Ruby or Javascript aren't all that different, if that's what you are used to) makes it preferable.</p>
<p>I'm sure there IS a niche in-between for a language that's garbage collected but mostly static, like Java (or C# before it started piling on more and more features, including dynamic ones in 4.0, I hear), or else those languages and cognate ones wouldn't be so widespread -- I've just never found myself inhabiting that peculiar niche, as yet.</p>
| 10 | 2009-06-21T03:16:41Z | [
"c#",
"java",
"c++",
"python",
"programming-languages"
] |
What classes of applications or problems do you prefer Python to strictly OO Languages? | 1,022,971 | <p>I've got a pretty strong background in C-style languages. And have worked on several different types of projects. I have just started taking a serious look at Python after reading <a href="http://oreilly.com/catalog/9780596529321/" rel="nofollow">Programming Collective Intelligence</a>. I understand that Python can solve any problem that C# can, and vice-versa. But I am curious to know from those who use both regularly, when they choose one over the other. Removing other factors, like coworkers experience, etc. </p>
<p>When do you choose to create an application in Python instead of a static typed, purely OO language like C# or Java?</p>
<h2>Edit:</h2>
<p>I was afraid we were going to get off topic a bit with this question. Python is an object oriented language. But, as is stated below it may not be the preferred language when your application will have a very heavy business domain, etc. I am aware that Python uses objects extensively, and that even functions are objects, something that is not true in all of the "OO" languages I brought up earlier. </p>
<p>Despite my poor choice of words in the question (almost no languages fit nicely into two or three word descriptions, and it is really difficult to point out differences in languages without it appearing that you are talking down to a certain class of developer.), I am still very interested in what you have to say about when you prefer Python to other languages.</p>
| 4 | 2009-06-21T01:50:07Z | 1,023,383 | <p>Python is much more strictly OO than Java and C#.</p>
<p>But if your question is when to use Python and when Java or C#, I find Python useful for small programs that build on existing libraries and don't involve much domain modelling. For example, little desktop utilities written with the Python Gtk bindings or website maintenance scripts written with lxml and elementtree.</p>
<p>When there is a lot of application domain modelling to do, especially if the domain is poorly understood or changing rapidly, I find Python's limited tooling makes changing the code very arduous compared to Java (not so relevant for C# because .NET tool support trails Java by a few years). So for projects like that I'll use Java and IntelliJ. </p>
| 1 | 2009-06-21T07:33:07Z | [
"c#",
"java",
"c++",
"python",
"programming-languages"
] |
What classes of applications or problems do you prefer Python to strictly OO Languages? | 1,022,971 | <p>I've got a pretty strong background in C-style languages. And have worked on several different types of projects. I have just started taking a serious look at Python after reading <a href="http://oreilly.com/catalog/9780596529321/" rel="nofollow">Programming Collective Intelligence</a>. I understand that Python can solve any problem that C# can, and vice-versa. But I am curious to know from those who use both regularly, when they choose one over the other. Removing other factors, like coworkers experience, etc. </p>
<p>When do you choose to create an application in Python instead of a static typed, purely OO language like C# or Java?</p>
<h2>Edit:</h2>
<p>I was afraid we were going to get off topic a bit with this question. Python is an object oriented language. But, as is stated below it may not be the preferred language when your application will have a very heavy business domain, etc. I am aware that Python uses objects extensively, and that even functions are objects, something that is not true in all of the "OO" languages I brought up earlier. </p>
<p>Despite my poor choice of words in the question (almost no languages fit nicely into two or three word descriptions, and it is really difficult to point out differences in languages without it appearing that you are talking down to a certain class of developer.), I am still very interested in what you have to say about when you prefer Python to other languages.</p>
| 4 | 2009-06-21T01:50:07Z | 1,023,545 | <p>Both C and python are my languages of choice, but I almost always start doing something in python for correctness, and then dive into C when needed. I am mostly using programming for research/numerical code, where the specifications keep changing, and C is an awful language for prototyping (this is true for most statically typed languages in my experience). When you have something working in C, you rarely change it significantly so that it is 'better', because you don't have the time. But sometimes, C is easier than python when you need to control resources (be it CPU, memory, etc...).</p>
<p>So the question really is "when is python not enough for the task", rather than the contrary.</p>
| 0 | 2009-06-21T09:45:41Z | [
"c#",
"java",
"c++",
"python",
"programming-languages"
] |
What classes of applications or problems do you prefer Python to strictly OO Languages? | 1,022,971 | <p>I've got a pretty strong background in C-style languages. And have worked on several different types of projects. I have just started taking a serious look at Python after reading <a href="http://oreilly.com/catalog/9780596529321/" rel="nofollow">Programming Collective Intelligence</a>. I understand that Python can solve any problem that C# can, and vice-versa. But I am curious to know from those who use both regularly, when they choose one over the other. Removing other factors, like coworkers experience, etc. </p>
<p>When do you choose to create an application in Python instead of a static typed, purely OO language like C# or Java?</p>
<h2>Edit:</h2>
<p>I was afraid we were going to get off topic a bit with this question. Python is an object oriented language. But, as is stated below it may not be the preferred language when your application will have a very heavy business domain, etc. I am aware that Python uses objects extensively, and that even functions are objects, something that is not true in all of the "OO" languages I brought up earlier. </p>
<p>Despite my poor choice of words in the question (almost no languages fit nicely into two or three word descriptions, and it is really difficult to point out differences in languages without it appearing that you are talking down to a certain class of developer.), I am still very interested in what you have to say about when you prefer Python to other languages.</p>
| 4 | 2009-06-21T01:50:07Z | 1,023,659 | <p>Generally the language is dictated by the job, who wants the stuff done and who you are working with. I only use java and c/c++ for my programming needs, mainly because the people i work with use it. That being said ive used python for fast prototyping and such.</p>
| 0 | 2009-06-21T10:59:39Z | [
"c#",
"java",
"c++",
"python",
"programming-languages"
] |
What classes of applications or problems do you prefer Python to strictly OO Languages? | 1,022,971 | <p>I've got a pretty strong background in C-style languages. And have worked on several different types of projects. I have just started taking a serious look at Python after reading <a href="http://oreilly.com/catalog/9780596529321/" rel="nofollow">Programming Collective Intelligence</a>. I understand that Python can solve any problem that C# can, and vice-versa. But I am curious to know from those who use both regularly, when they choose one over the other. Removing other factors, like coworkers experience, etc. </p>
<p>When do you choose to create an application in Python instead of a static typed, purely OO language like C# or Java?</p>
<h2>Edit:</h2>
<p>I was afraid we were going to get off topic a bit with this question. Python is an object oriented language. But, as is stated below it may not be the preferred language when your application will have a very heavy business domain, etc. I am aware that Python uses objects extensively, and that even functions are objects, something that is not true in all of the "OO" languages I brought up earlier. </p>
<p>Despite my poor choice of words in the question (almost no languages fit nicely into two or three word descriptions, and it is really difficult to point out differences in languages without it appearing that you are talking down to a certain class of developer.), I am still very interested in what you have to say about when you prefer Python to other languages.</p>
| 4 | 2009-06-21T01:50:07Z | 1,024,405 | <p>I select Python as often as possible. It is the most useful and productive programming environment that I know of.</p>
<p>If I run into projects where Python cannot be used directly or for the entire project (for instance a .NET-based app. server) my approach is usually to do as much with Python as possible. Depending on the situation that might mean:</p>
<ul>
<li>Embed a python interpreter</li>
<li>Use Jython</li>
<li>Use IronPython</li>
<li>Use some IPC mechanism (usually http or sockets) to call an external python process</li>
<li>Export data - process using python - import data</li>
<li>Generate code using Python</li>
</ul>
<p>From <a href="http://stackoverflow.com/questions/819056/i-know-c-will-i-be-more-productive-with-python/824064#824064">my answer</a> to a previous question: <a href="http://stackoverflow.com/questions/819056/i-know-c-will-i-be-more-productive-with-python">I know C#. Will I be more productive with Python?</a></p>
<p><hr /></p>
<p>In my experience, what makes me more productive in Python vs. C#, is:</p>
<ul>
<li>It is a dynamic language. Using a dynamic language often allows you to remove whole architectural layers from your app. Pythons dynamic nature allows you to create reusable high-level abstractions in more natural and flexible (syntax-wise) way than you can in C#.</li>
<li>Libraries. The standard libraries and a lot of the open-source libraries provided by the community are of high quality. The range of applications that Python is used for means that the range of libraries is wide.</li>
<li>Faster development cycle. No compile step means I can test changes faster. For instance, when developing a web app, the dev server detects changes and reloads the app when the files are saved. Running a unit test from within my editor is just a keystroke away, and executes instantaneously.</li>
<li>'Easy access' to often-used features: lists, list comprehensions, generators, tuples etc.</li>
<li>Less verbose syntax. You can create a WSGI-based Python web framework in fewer lines of code than your typical .NET <code>web.config</code> file :-)</li>
<li>Good documentation. Good books.</li>
</ul>
<p><hr /></p>
| 4 | 2009-06-21T17:49:01Z | [
"c#",
"java",
"c++",
"python",
"programming-languages"
] |
What classes of applications or problems do you prefer Python to strictly OO Languages? | 1,022,971 | <p>I've got a pretty strong background in C-style languages. And have worked on several different types of projects. I have just started taking a serious look at Python after reading <a href="http://oreilly.com/catalog/9780596529321/" rel="nofollow">Programming Collective Intelligence</a>. I understand that Python can solve any problem that C# can, and vice-versa. But I am curious to know from those who use both regularly, when they choose one over the other. Removing other factors, like coworkers experience, etc. </p>
<p>When do you choose to create an application in Python instead of a static typed, purely OO language like C# or Java?</p>
<h2>Edit:</h2>
<p>I was afraid we were going to get off topic a bit with this question. Python is an object oriented language. But, as is stated below it may not be the preferred language when your application will have a very heavy business domain, etc. I am aware that Python uses objects extensively, and that even functions are objects, something that is not true in all of the "OO" languages I brought up earlier. </p>
<p>Despite my poor choice of words in the question (almost no languages fit nicely into two or three word descriptions, and it is really difficult to point out differences in languages without it appearing that you are talking down to a certain class of developer.), I am still very interested in what you have to say about when you prefer Python to other languages.</p>
| 4 | 2009-06-21T01:50:07Z | 1,352,569 | <p><strong>All</strong> of them. </p>
<p>Except for code that is already written in different language, obviously.</p>
<p>Even if something seems too big for python to handle, I usually make Python prototype anyway, mainly because it's goes so smooth. Often I'll stick with Python eitherway and just use C API or ctypes to tackle bottlenecks (after I rewrite the prototype in a nice clean manner, that is).</p>
| 0 | 2009-08-29T22:42:47Z | [
"c#",
"java",
"c++",
"python",
"programming-languages"
] |
Change process priority in Python, cross-platform | 1,023,038 | <p>I've got a Python program that does time-consuming computations. Since it uses high CPU, and I want my system to remain responsive, I'd like the program to change its priority to below-normal.</p>
<p>I found this:
<a href="http://code.activestate.com/recipes/496767/">Set Process Priority In Windows - ActiveState</a></p>
<p>But I'm looking for a cross-platform solution.</p>
| 17 | 2009-06-21T02:27:19Z | 1,023,088 | <p>On every Unix-like platform (including Linux and MacOsX), see <code>os.nice</code> <a href="http://docs.python.org/library/os.html">here</a>:</p>
<pre><code>os.nice(increment)
Add increment to the processâs ânicenessâ. Return the new niceness. Availability: Unix.
</code></pre>
<p>Since you already have a recipe for Windows, that covers most platforms -- call os.nice with a positive argument everywhere but Windows, use that recipe there. There is no "nicely packaged" cross-platform solution AFAIK (would be hard to package this combo up, but, how much extra value would you see in just packaging it?-)</p>
| 9 | 2009-06-21T03:01:50Z | [
"python"
] |
Change process priority in Python, cross-platform | 1,023,038 | <p>I've got a Python program that does time-consuming computations. Since it uses high CPU, and I want my system to remain responsive, I'd like the program to change its priority to below-normal.</p>
<p>I found this:
<a href="http://code.activestate.com/recipes/496767/">Set Process Priority In Windows - ActiveState</a></p>
<p>But I'm looking for a cross-platform solution.</p>
| 17 | 2009-06-21T02:27:19Z | 1,023,269 | <p>Here's the solution I'm using to set my process to below-normal priority:</p>
<p><strong><code>lowpriority.py</code></strong></p>
<pre><code>def lowpriority():
""" Set the priority of the process to below-normal."""
import sys
try:
sys.getwindowsversion()
except:
isWindows = False
else:
isWindows = True
if isWindows:
# Based on:
# "Recipe 496767: Set Process Priority In Windows" on ActiveState
# http://code.activestate.com/recipes/496767/
import win32api,win32process,win32con
pid = win32api.GetCurrentProcessId()
handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, True, pid)
win32process.SetPriorityClass(handle, win32process.BELOW_NORMAL_PRIORITY_CLASS)
else:
import os
os.nice(1)
</code></pre>
<p>Tested on Python 2.6 on Windows and Linux.</p>
| 24 | 2009-06-21T05:21:37Z | [
"python"
] |
Change process priority in Python, cross-platform | 1,023,038 | <p>I've got a Python program that does time-consuming computations. Since it uses high CPU, and I want my system to remain responsive, I'd like the program to change its priority to below-normal.</p>
<p>I found this:
<a href="http://code.activestate.com/recipes/496767/">Set Process Priority In Windows - ActiveState</a></p>
<p>But I'm looking for a cross-platform solution.</p>
| 17 | 2009-06-21T02:27:19Z | 6,245,096 | <p>You can use <a href="http://code.google.com/p/psutil/wiki/Documentation" rel="nofollow">psutil</a> module.</p>
<p>On POSIX platforms:</p>
<pre><code>>>> import psutil, os
>>> p = psutil.Process(os.getpid())
>>> p.nice()
0
>>> p.nice(10) # set
>>> p.nice()
10
</code></pre>
<p>On Windows:</p>
<pre><code>>>> p.nice(psutil.HIGH_PRIORITY_CLASS)
</code></pre>
| 12 | 2011-06-05T18:56:37Z | [
"python"
] |
Connecting C# (frontend) to an apache/php/python (backend) | 1,023,187 | <p><strong>Overview:</strong> We are looking to write a C# user interface to select parts of our web applications. This is for a very captive audience (internally, for example).</p>
<p>Our web applications are written in PHP and/or Python using Apache as the web server.</p>
<p><sup>Why? A well thought out native Windows interface can at times be far more effective than living with the rules imposed by a web browser.</sup> </p>
<p><strong>Question:</strong> What is the best way to communicate between C# and PHP/Python using HTTPS? I'm speaking mostly of serialization / unserialization and conversion of the various data types resident in each language.</p>
<p>Ideally, we would have strongly typed structs or objects to work with in C#, and appropriate data structures created in PHP/Python to work with on that end. Code generators are fine.</p>
<p>I've looked at <a href="http://incubator.apache.org/thrift/" rel="nofollow">Apache Thrift</a>, considered extending our internal data libraries, reviewed Google's Protocol Buffers, etc... <em>Thrift looks promising, but their documentation is very sparse.</em></p>
<ol>
<li>Keeping developer overhead to a minimum is essential. </li>
<li>Keeping performance reasonable , especially on the server side, is important.</li>
</ol>
<p>Comments on the usefulness of XMLRPC, SOAP, or other related technologies would be welcome.</p>
<p><strong>Any pointers?</strong></p>
| 1 | 2009-06-21T04:17:05Z | 1,023,201 | <p>Using web services sounds like the most appropriate way for your scenario.</p>
| 0 | 2009-06-21T04:28:12Z | [
"c#",
"php",
"python",
"web-applications",
"data-structures"
] |
Connecting C# (frontend) to an apache/php/python (backend) | 1,023,187 | <p><strong>Overview:</strong> We are looking to write a C# user interface to select parts of our web applications. This is for a very captive audience (internally, for example).</p>
<p>Our web applications are written in PHP and/or Python using Apache as the web server.</p>
<p><sup>Why? A well thought out native Windows interface can at times be far more effective than living with the rules imposed by a web browser.</sup> </p>
<p><strong>Question:</strong> What is the best way to communicate between C# and PHP/Python using HTTPS? I'm speaking mostly of serialization / unserialization and conversion of the various data types resident in each language.</p>
<p>Ideally, we would have strongly typed structs or objects to work with in C#, and appropriate data structures created in PHP/Python to work with on that end. Code generators are fine.</p>
<p>I've looked at <a href="http://incubator.apache.org/thrift/" rel="nofollow">Apache Thrift</a>, considered extending our internal data libraries, reviewed Google's Protocol Buffers, etc... <em>Thrift looks promising, but their documentation is very sparse.</em></p>
<ol>
<li>Keeping developer overhead to a minimum is essential. </li>
<li>Keeping performance reasonable , especially on the server side, is important.</li>
</ol>
<p>Comments on the usefulness of XMLRPC, SOAP, or other related technologies would be welcome.</p>
<p><strong>Any pointers?</strong></p>
| 1 | 2009-06-21T04:17:05Z | 1,023,220 | <p>I have no real experience with PHP, but I've done plenty of Python back-end web services consumed by front-end clients in a variety of languages and environment. SOAP is the only technology, out of those I've tried, that has mostly left a sour taste in my mouth -- too much "ceremony"/overhead. (Back in the far past I also tried Corba and, as soon as I was trying to interoperate among independed implementations for different languages, the feeling wasn't all that different;-).</p>
<p>XML-RPC, JSON, and protocol buffers, all proved quite usable for me.</p>
<p>Protocol buffers is what we normally use within Google, and I'm not sure what you find so under-documented about them -- please ask specific questions and I'll see what I can do to make our documentation better, officially or unofficially! Their main advantage is that they're so "tight" on the wire -- minimal overhead with maximum flexibility. JSON is great, too -- and not just for ease of use in Javascript clients, either: sometimes I've used it as the default format for communication among different languages, too, when no JS was involved at all!</p>
<p>Once you have your web app set up to emit (say) a protocol buffer, it's not hard <em>at all</em> to make it able to emit XML or JSON on request - one ?outputformat=JSON extra parameter in the GET request is all it takes, and picking the right output serializer is trivially easy (in Python, but, I'm sure, in PHP as well).</p>
<p>"Getting strongly typed objects" on your C# end is, in my view, a job you can best do in a C# layer on your end. No direct experience with that, but, for example, I <em>have</em> wrapped reception of protocol buffers in C++ into factory classes that spewed out perfectly formed and statically typed objects (or raised exceptions when the incoming data was not semantically correct); I know it wouldn't be any harder for JSON or XML, and I very much doubt it would be any harder for Java, C#, Python if you cared, or any other language that's any use at all in the real world!-)</p>
| 4 | 2009-06-21T04:44:50Z | [
"c#",
"php",
"python",
"web-applications",
"data-structures"
] |
Connecting C# (frontend) to an apache/php/python (backend) | 1,023,187 | <p><strong>Overview:</strong> We are looking to write a C# user interface to select parts of our web applications. This is for a very captive audience (internally, for example).</p>
<p>Our web applications are written in PHP and/or Python using Apache as the web server.</p>
<p><sup>Why? A well thought out native Windows interface can at times be far more effective than living with the rules imposed by a web browser.</sup> </p>
<p><strong>Question:</strong> What is the best way to communicate between C# and PHP/Python using HTTPS? I'm speaking mostly of serialization / unserialization and conversion of the various data types resident in each language.</p>
<p>Ideally, we would have strongly typed structs or objects to work with in C#, and appropriate data structures created in PHP/Python to work with on that end. Code generators are fine.</p>
<p>I've looked at <a href="http://incubator.apache.org/thrift/" rel="nofollow">Apache Thrift</a>, considered extending our internal data libraries, reviewed Google's Protocol Buffers, etc... <em>Thrift looks promising, but their documentation is very sparse.</em></p>
<ol>
<li>Keeping developer overhead to a minimum is essential. </li>
<li>Keeping performance reasonable , especially on the server side, is important.</li>
</ol>
<p>Comments on the usefulness of XMLRPC, SOAP, or other related technologies would be welcome.</p>
<p><strong>Any pointers?</strong></p>
| 1 | 2009-06-21T04:17:05Z | 1,023,436 | <p>I have done this using a PHP SOAP Server and VB.Net client. Once you connect the VB.Net/C# client to the server (the location of the WSDL file) C# will automatically detect all the functions and all the objects that are exposed. Making programming much easier.</p>
<p>I would also recommend using NuSOAP which I found to be more functional. <a href="http://sourceforge.net/projects/nusoap/" rel="nofollow">http://sourceforge.net/projects/nusoap/</a></p>
| 0 | 2009-06-21T08:25:45Z | [
"c#",
"php",
"python",
"web-applications",
"data-structures"
] |
Connecting C# (frontend) to an apache/php/python (backend) | 1,023,187 | <p><strong>Overview:</strong> We are looking to write a C# user interface to select parts of our web applications. This is for a very captive audience (internally, for example).</p>
<p>Our web applications are written in PHP and/or Python using Apache as the web server.</p>
<p><sup>Why? A well thought out native Windows interface can at times be far more effective than living with the rules imposed by a web browser.</sup> </p>
<p><strong>Question:</strong> What is the best way to communicate between C# and PHP/Python using HTTPS? I'm speaking mostly of serialization / unserialization and conversion of the various data types resident in each language.</p>
<p>Ideally, we would have strongly typed structs or objects to work with in C#, and appropriate data structures created in PHP/Python to work with on that end. Code generators are fine.</p>
<p>I've looked at <a href="http://incubator.apache.org/thrift/" rel="nofollow">Apache Thrift</a>, considered extending our internal data libraries, reviewed Google's Protocol Buffers, etc... <em>Thrift looks promising, but their documentation is very sparse.</em></p>
<ol>
<li>Keeping developer overhead to a minimum is essential. </li>
<li>Keeping performance reasonable , especially on the server side, is important.</li>
</ol>
<p>Comments on the usefulness of XMLRPC, SOAP, or other related technologies would be welcome.</p>
<p><strong>Any pointers?</strong></p>
| 1 | 2009-06-21T04:17:05Z | 1,162,990 | <p>I recommend the PHP/Java Bridge. Don't let the name fool you. This can be used to connect both PHP and Python to any ECMA-335 virtual machine (Java and C#)!</p>
<p><a href="http://php-java-bridge.sourceforge.net/pjb/" rel="nofollow">http://php-java-bridge.sourceforge.net/pjb/</a></p>
<p>To answer your comment:</p>
<blockquote>
<p>The communication works in both directions, the JSR 223 interface can be used to connect to a running PHP server (Apache/IIS, FastCGI, ...) so that Java components can call PHP instances and PHP scripts can invoke CLR (e.g. VB.NET, C#, COM) or Java (e.g. Java, KAWA, JRuby) based applications or transfer control back to the environment where the request came from. The bridge can be set up to automatically start a PHP front-end or start a Java/.NET back end, if needed.</p>
</blockquote>
| 0 | 2009-07-22T03:58:52Z | [
"c#",
"php",
"python",
"web-applications",
"data-structures"
] |
How to pickle a CookieJar? | 1,023,224 | <p>I have an object with a CookieJar that I want to pickle. </p>
<p>However as you all probably know, pickle chokes on objects that contain lock objects. And for some horrible reason, a CookieJar has a lock object.</p>
<pre><code>from cPickle import dumps
from cookielib import CookieJar
class Person(object):
def __init__(self, name):
self.name = name
self.cookies = CookieJar()
bob = Person("bob")
dumps(bob)
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# cPickle.UnpickleableError: Cannot pickle <type 'thread.lock'> objects
</code></pre>
<p>How do I persist this? </p>
<p>The only solution I can think of is to use FileCookieJar.save and FileCookieJar.load to a stringIO object. But is there a better way?</p>
| 8 | 2009-06-21T04:46:07Z | 1,023,235 | <p><code>CookieJar</code> is not particularly well-designed for persisting (that's what the <code>FileCookieJar</code> subclasses are mostly about!-), but you can iterate over a <code>CookieJar</code> instance to get all cookies (and persist a list of those, for example), and, to rebuild the jar given the cookies, use <code>set_cookie</code> on each. That's how I would set about persisting and unpersisting cookie jars, using the <code>copy_reg</code> method to register the appropriate functions if I needed to use them often.</p>
| 6 | 2009-06-21T04:56:19Z | [
"python",
"persistence",
"pickle",
"cookiejar",
"cookielib"
] |
How to pickle a CookieJar? | 1,023,224 | <p>I have an object with a CookieJar that I want to pickle. </p>
<p>However as you all probably know, pickle chokes on objects that contain lock objects. And for some horrible reason, a CookieJar has a lock object.</p>
<pre><code>from cPickle import dumps
from cookielib import CookieJar
class Person(object):
def __init__(self, name):
self.name = name
self.cookies = CookieJar()
bob = Person("bob")
dumps(bob)
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# cPickle.UnpickleableError: Cannot pickle <type 'thread.lock'> objects
</code></pre>
<p>How do I persist this? </p>
<p>The only solution I can think of is to use FileCookieJar.save and FileCookieJar.load to a stringIO object. But is there a better way?</p>
| 8 | 2009-06-21T04:46:07Z | 1,023,245 | <p>Here is an attempt, by deriving a class from CookieJar, which override getstate/setstate used by pickle. I haven't used cookieJar, so don't know if it is usable but you can dump derived class</p>
<pre><code>from cPickle import dumps
from cookielib import CookieJar
import threading
class MyCookieJar(CookieJar):
def __getstate__(self):
state = self.__dict__.copy()
del state['_cookies_lock']
return state
def __setstate__(self, state):
self.__dict__ = state
self._cookies_lock = threading.RLock()
class Person(object):
def __init__(self, name):
self.name = name
self.cookies = MyCookieJar()
bob = Person("bob")
print dumps(bob)
</code></pre>
| 9 | 2009-06-21T05:01:30Z | [
"python",
"persistence",
"pickle",
"cookiejar",
"cookielib"
] |
Why does mass importing not work but importing definition individually works? | 1,023,326 | <p>So I just met a strange so-called bug. Because this work on my other .py files, but just on this file it suddenly stopped working.</p>
<pre><code>from tuttobelo.management.models import *
</code></pre>
<p>The above used to work, but it stopped working all of a sudden, and I had to replace it with the bottom.</p>
<pre><code>from tuttobelo.management.models import Preferences, ProductVariant, UserSeller, ProductOwner, ProductModel, ProductVariant
from tuttobelo.management.models import ProductMeta, ShippingMethods
</code></pre>
<p>I know the following is the better way of coding, however ALL of the models mentioned in models are used, so my question is, what possible reasons can wildcard stop working?</p>
<p>The error I got was that the model I was trying to import does not exist, only if I remove the wildcard and import the name of the model could I get it imported properly.</p>
<p>Thanks!</p>
| 2 | 2009-06-21T06:33:41Z | 1,023,344 | <p>Maybe the <code>models</code> module has an <code>__all__</code> which does not include what you're looking for. Anyway, <code>from ... import *</code> is <strong>never</strong> a good idea in production code -- we always meant the <code>import *</code> feature for interactive exploratory use, <em>not</em> production use. Specifically import the module you need -- use that name to qualify names that belong there -- and you'll be vastly happier in the long run!-)</p>
| 4 | 2009-06-21T07:02:51Z | [
"python",
"django"
] |
Why does mass importing not work but importing definition individually works? | 1,023,326 | <p>So I just met a strange so-called bug. Because this work on my other .py files, but just on this file it suddenly stopped working.</p>
<pre><code>from tuttobelo.management.models import *
</code></pre>
<p>The above used to work, but it stopped working all of a sudden, and I had to replace it with the bottom.</p>
<pre><code>from tuttobelo.management.models import Preferences, ProductVariant, UserSeller, ProductOwner, ProductModel, ProductVariant
from tuttobelo.management.models import ProductMeta, ShippingMethods
</code></pre>
<p>I know the following is the better way of coding, however ALL of the models mentioned in models are used, so my question is, what possible reasons can wildcard stop working?</p>
<p>The error I got was that the model I was trying to import does not exist, only if I remove the wildcard and import the name of the model could I get it imported properly.</p>
<p>Thanks!</p>
| 2 | 2009-06-21T06:33:41Z | 1,023,836 | <p>There are some cases in Python where importing with * will not yield anything. In your example, if tuttobelo.management.models is a package (i.e. a directory with an <code>__init__.py</code>) with the files Preferences.py, ProductVariant.py, etc in it, importing with star will not work, unless you already have imported it explicitly somewhere else.</p>
<p>This can be solved by putting in the <code>__init__.py</code>:</p>
<pre><code>__all__ = ['Preferences', 'ProductVariant', 'UserSeller', <etc...> ]
</code></pre>
<p>This will make it possible to do import * again, but as noted, that's a horrible coding style for several reasons. One, tools like pyflakes and pylint, and code introspection in your editor, stops working. Secondly, you end up putting a lot of names in the local namespace, which in your code you don't know where they come from, and secondly you can get clashes in names like this.</p>
<p>A better way is to do</p>
<pre><code>from tuttobelo.management import models
</code></pre>
<p>And then refer to the other things by models.Preferences, models.ProductVariant etc. This however will not work with the <code>__all__</code> variable. Instead you need to import the modules from the <code>__init__.py</code>:</p>
<pre><code>import Preferences, ProductVariant, UserSeller, ProductOwner, <etc...>
</code></pre>
<p>The drawback of this is that all modules get imported even if you don't use them, which means it will take more memory.</p>
| 1 | 2009-06-21T12:56:27Z | [
"python",
"django"
] |
working with django and sqlalchemy but backend mysql | 1,023,417 | <p>i am working with python django framework but in model part is sqlalchemy and back end data base is mysql how i will configure them?</p>
| 1 | 2009-06-21T08:09:55Z | 1,023,490 | <p>See <a href="http://docs.djangoproject.com/en/dev/topics/install/#database-installation" rel="nofollow">Django database installation</a>,</p>
<blockquote>
<p>If youâre using MySQL, youâll need MySQLdb, version 1.2.1p2 or higher. You will also want to read the database-specific notes for the MySQL backend.</p>
</blockquote>
<p>And the <a href="http://docs.djangoproject.com/en/dev/ref/databases/#id2" rel="nofollow">MySQL notes</a>,</p>
<blockquote>
<p>Django expects the database to support transactions, referential integrity, and Unicode (UTF-8 encoding). Fortunately, MySQL has all these features as available as far back as 3.23. While it may be possible to use 3.23 or 4.0, you'll probably have less trouble if you use 4.1 or 5.0.</p>
</blockquote>
| 0 | 2009-06-21T09:09:24Z | [
"python",
"mysql",
"django",
"sqlalchemy"
] |
working with django and sqlalchemy but backend mysql | 1,023,417 | <p>i am working with python django framework but in model part is sqlalchemy and back end data base is mysql how i will configure them?</p>
| 1 | 2009-06-21T08:09:55Z | 1,023,828 | <p>Some links that might help you:</p>
<blockquote>
<p><a href="http://lethain.com/entry/2008/jul/23/replacing-django-s-orm-with-sqlalchemy/" rel="nofollow">http://lethain.com/entry/2008/jul/23/replacing-django-s-orm-with-sqlalchemy/</a></p>
<p><a href="http://code.google.com/p/django-sqlalchemy/" rel="nofollow">http://code.google.com/p/django-sqlalchemy/</a></p>
<p><a href="http://adam.gomaa.us/blog/2007/aug/26/the-django-orm-problem/" rel="nofollow">http://adam.gomaa.us/blog/2007/aug/26/the-django-orm-problem/</a></p>
<p><a href="http://gitorious.org/django-sqlalchemy" rel="nofollow">http://gitorious.org/django-sqlalchemy</a></p>
</blockquote>
| 1 | 2009-06-21T12:52:13Z | [
"python",
"mysql",
"django",
"sqlalchemy"
] |
smoothing irregularly sampled time data | 1,023,719 | <p>Given a table where the first column is seconds past a certain reference point and the second one is an arbitrary measurement:</p>
<pre><code>6 0.738158581
21 0.801697222
39 1.797224596
49 2.77920469
54 2.839757536
79 3.832232283
91 4.676794376
97 5.18244704
100 5.521878863
118 6.316630137
131 6.778507504
147 7.020395216
157 7.331607129
176 7.637492223
202 7.848079136
223 7.989456499
251 8.76853608
278 9.092367123
...
</code></pre>
<p>As you see, the measurements are sampled at irregular time points. I need to smooth the data by averaging the reading up to 100 seconds prior each measurement (in Python). Since the data table is huge, an iterator-based method is really preferred.
Unfortunately, after two hours of coding I can't figure out efficient and elegant solution.</p>
<p>Can anyone help me?</p>
<p><strong>EDIT</strong>s</p>
<ol>
<li><p>I want one smoothed reading for each raw reading, and the smoothed reading is to be the arithmetic mean of the raw reading and any others in the previous 100 (delta) seconds. (John, you are right)</p></li>
<li><p>Huge ~ 1e6 - 10e6 lines + need to work with tight RAM</p></li>
<li><p>The data is approximately random walk</p></li>
<li><p>The data is sorted</p></li>
</ol>
<h1>RESOLUTION</h1>
<p>I have tested solutions proposed by J Machin and yairchu. They both gave the same results, however, on my data set, J Machin's version performs exponentially, while that of yairchu is linear. Following are execution times as measured by IPython's <em>%timeit</em> (in microseconds):</p>
<pre><code>data size J Machin yairchu
10 90.2 55.6
50 930 258
100 3080 514
500 64700 2660
1000 253000 5390
2000 952000 11500
</code></pre>
<p>Thank you all for the help.</p>
| 5 | 2009-06-21T11:36:57Z | 1,023,740 | <p>what about something like this, keep storing values till time difference with last time is > 100, average and yield such values
e.g.</p>
<pre><code>def getAvgValues(data):
lastTime = 0
prevValues = []
avgSampleTime=100
for t, v in data:
if t - lastTime < avgSampleTime:
prevValues.append(v)
else:
avgV = sum(prevValues)/len(prevValues)
lastTime = t
prevValues = [v]
yield (t,avgV)
for v in getAvgValues(data):
print v
</code></pre>
| -1 | 2009-06-21T11:50:55Z | [
"python",
"datetime",
"data-mining",
"smoothing"
] |
smoothing irregularly sampled time data | 1,023,719 | <p>Given a table where the first column is seconds past a certain reference point and the second one is an arbitrary measurement:</p>
<pre><code>6 0.738158581
21 0.801697222
39 1.797224596
49 2.77920469
54 2.839757536
79 3.832232283
91 4.676794376
97 5.18244704
100 5.521878863
118 6.316630137
131 6.778507504
147 7.020395216
157 7.331607129
176 7.637492223
202 7.848079136
223 7.989456499
251 8.76853608
278 9.092367123
...
</code></pre>
<p>As you see, the measurements are sampled at irregular time points. I need to smooth the data by averaging the reading up to 100 seconds prior each measurement (in Python). Since the data table is huge, an iterator-based method is really preferred.
Unfortunately, after two hours of coding I can't figure out efficient and elegant solution.</p>
<p>Can anyone help me?</p>
<p><strong>EDIT</strong>s</p>
<ol>
<li><p>I want one smoothed reading for each raw reading, and the smoothed reading is to be the arithmetic mean of the raw reading and any others in the previous 100 (delta) seconds. (John, you are right)</p></li>
<li><p>Huge ~ 1e6 - 10e6 lines + need to work with tight RAM</p></li>
<li><p>The data is approximately random walk</p></li>
<li><p>The data is sorted</p></li>
</ol>
<h1>RESOLUTION</h1>
<p>I have tested solutions proposed by J Machin and yairchu. They both gave the same results, however, on my data set, J Machin's version performs exponentially, while that of yairchu is linear. Following are execution times as measured by IPython's <em>%timeit</em> (in microseconds):</p>
<pre><code>data size J Machin yairchu
10 90.2 55.6
50 930 258
100 3080 514
500 64700 2660
1000 253000 5390
2000 952000 11500
</code></pre>
<p>Thank you all for the help.</p>
| 5 | 2009-06-21T11:36:57Z | 1,023,819 | <p>You haven't said exactly when you want output. I'm assuming that you want one smoothed reading for each raw reading, and the smoothed reading is to be the arithmetic mean of the raw reading and any others in the previous 100 (delta) seconds.</p>
<p>Short answer: use a collections.deque ... it will never hold more than "delta" seconds of readings. The way I've set it up you can treat the deque just like a list, and easily calculate the mean or some fancy gizmoid that gives more weight to recent readings.</p>
<p>Long answer:</p>
<pre><code>>>> the_data = [tuple(map(float, x.split())) for x in """\
... 6 0.738158581
... 21 0.801697222
[snip]
... 251 8.76853608
... 278 9.092367123""".splitlines()]
>>> import collections
>>> delta = 100.0
>>> q = collections.deque()
>>> for t, v in the_data:
... while q and q[0][0] <= t - delta:
... # jettison outdated readings
... _unused = q.popleft()
... q.append((t, v))
... count = len(q)
... print t, sum(item[1] for item in q) / count, count
...
...
6.0 0.738158581 1
21.0 0.7699279015 2
39.0 1.112360133 3
49.0 1.52907127225 4
54.0 1.791208525 5
79.0 2.13137915133 6
91.0 2.49500989771 7
97.0 2.8309395405 8
100.0 3.12993279856 9
118.0 3.74976297144 9
131.0 4.41385300278 9
147.0 4.99420529389 9
157.0 5.8325615685 8
176.0 6.033109419 9
202.0 7.15545189083 6
223.0 7.4342562845 6
251.0 7.9150342134 5
278.0 8.4246097095 4
>>>
</code></pre>
<p><strong>Edit</strong> </p>
<p>One-stop shop: get your fancy gizmoid here. Here's the code:</p>
<pre><code>numerator = sum(item[1] * upsilon ** (t - item[0]) for item in q)
denominator = sum(upsilon ** (t - item[0]) for item in q)
gizmoid = numerator / denominator
</code></pre>
<p>where upsilon should be a little less than 1.0 (<= zero is illegal, just above zero does little smoothing, one gets you the arithmetic mean plus wasted CPU time, and greater than one gives the inverse of your purpose).</p>
| 2 | 2009-06-21T12:48:04Z | [
"python",
"datetime",
"data-mining",
"smoothing"
] |
smoothing irregularly sampled time data | 1,023,719 | <p>Given a table where the first column is seconds past a certain reference point and the second one is an arbitrary measurement:</p>
<pre><code>6 0.738158581
21 0.801697222
39 1.797224596
49 2.77920469
54 2.839757536
79 3.832232283
91 4.676794376
97 5.18244704
100 5.521878863
118 6.316630137
131 6.778507504
147 7.020395216
157 7.331607129
176 7.637492223
202 7.848079136
223 7.989456499
251 8.76853608
278 9.092367123
...
</code></pre>
<p>As you see, the measurements are sampled at irregular time points. I need to smooth the data by averaging the reading up to 100 seconds prior each measurement (in Python). Since the data table is huge, an iterator-based method is really preferred.
Unfortunately, after two hours of coding I can't figure out efficient and elegant solution.</p>
<p>Can anyone help me?</p>
<p><strong>EDIT</strong>s</p>
<ol>
<li><p>I want one smoothed reading for each raw reading, and the smoothed reading is to be the arithmetic mean of the raw reading and any others in the previous 100 (delta) seconds. (John, you are right)</p></li>
<li><p>Huge ~ 1e6 - 10e6 lines + need to work with tight RAM</p></li>
<li><p>The data is approximately random walk</p></li>
<li><p>The data is sorted</p></li>
</ol>
<h1>RESOLUTION</h1>
<p>I have tested solutions proposed by J Machin and yairchu. They both gave the same results, however, on my data set, J Machin's version performs exponentially, while that of yairchu is linear. Following are execution times as measured by IPython's <em>%timeit</em> (in microseconds):</p>
<pre><code>data size J Machin yairchu
10 90.2 55.6
50 930 258
100 3080 514
500 64700 2660
1000 253000 5390
2000 952000 11500
</code></pre>
<p>Thank you all for the help.</p>
| 5 | 2009-06-21T11:36:57Z | 1,023,823 | <p>Your data seems to be roughly linear:</p>
<p><img src="http://rix0r.nl/~rix0r/share/shot-20090621.144851.gif" alt="Plot of your data" /></p>
<p>What kind of smoothing are you looking for? A least squares fit of a line to this data set? Some sort of low-pass filter? Or something else?</p>
<p>Please tell us the application so we can advise you a bit better.</p>
<p>EDIT: For example, depending on the application, interpolating a line between the first and last point may be good enough for your purposes.</p>
| 0 | 2009-06-21T12:50:36Z | [
"python",
"datetime",
"data-mining",
"smoothing"
] |
smoothing irregularly sampled time data | 1,023,719 | <p>Given a table where the first column is seconds past a certain reference point and the second one is an arbitrary measurement:</p>
<pre><code>6 0.738158581
21 0.801697222
39 1.797224596
49 2.77920469
54 2.839757536
79 3.832232283
91 4.676794376
97 5.18244704
100 5.521878863
118 6.316630137
131 6.778507504
147 7.020395216
157 7.331607129
176 7.637492223
202 7.848079136
223 7.989456499
251 8.76853608
278 9.092367123
...
</code></pre>
<p>As you see, the measurements are sampled at irregular time points. I need to smooth the data by averaging the reading up to 100 seconds prior each measurement (in Python). Since the data table is huge, an iterator-based method is really preferred.
Unfortunately, after two hours of coding I can't figure out efficient and elegant solution.</p>
<p>Can anyone help me?</p>
<p><strong>EDIT</strong>s</p>
<ol>
<li><p>I want one smoothed reading for each raw reading, and the smoothed reading is to be the arithmetic mean of the raw reading and any others in the previous 100 (delta) seconds. (John, you are right)</p></li>
<li><p>Huge ~ 1e6 - 10e6 lines + need to work with tight RAM</p></li>
<li><p>The data is approximately random walk</p></li>
<li><p>The data is sorted</p></li>
</ol>
<h1>RESOLUTION</h1>
<p>I have tested solutions proposed by J Machin and yairchu. They both gave the same results, however, on my data set, J Machin's version performs exponentially, while that of yairchu is linear. Following are execution times as measured by IPython's <em>%timeit</em> (in microseconds):</p>
<pre><code>data size J Machin yairchu
10 90.2 55.6
50 930 258
100 3080 514
500 64700 2660
1000 253000 5390
2000 952000 11500
</code></pre>
<p>Thank you all for the help.</p>
| 5 | 2009-06-21T11:36:57Z | 1,023,872 | <p>I'm using a sum result to which I'm adding the new members and subtracting the old ones. However in this way one may suffer accumulating floating point inaccuracies.</p>
<p>Therefore I implement a "Deque" with a list. And whenever my Deque reallocates to a smaller size. I recalculate the sum at the same occasion.</p>
<p>I'm also calculating the average up to point x including point x so there's at least one sample point to average.</p>
<pre><code>def getAvgValues(data, avgSampleTime):
lastTime = 0
prevValsBuf = []
prevValsStart = 0
tot = 0
for t, v in data:
avgStart = t - avgSampleTime
# remove too old values
while prevValsStart < len(prevValsBuf):
pt, pv = prevValsBuf[prevValsStart]
if pt > avgStart:
break
tot -= pv
prevValsStart += 1
# add new item
tot += v
prevValsBuf.append((t, v))
# yield result
numItems = len(prevValsBuf) - prevValsStart
yield (t, tot / numItems)
# clean prevVals if it's time
if prevValsStart * 2 > len(prevValsBuf):
prevValsBuf = prevValsBuf[prevValsStart:]
prevValsStart = 0
# recalculate tot for not accumulating float precision error
tot = sum(v for (t, v) in prevValsBuf)
</code></pre>
| 2 | 2009-06-21T13:17:51Z | [
"python",
"datetime",
"data-mining",
"smoothing"
] |
smoothing irregularly sampled time data | 1,023,719 | <p>Given a table where the first column is seconds past a certain reference point and the second one is an arbitrary measurement:</p>
<pre><code>6 0.738158581
21 0.801697222
39 1.797224596
49 2.77920469
54 2.839757536
79 3.832232283
91 4.676794376
97 5.18244704
100 5.521878863
118 6.316630137
131 6.778507504
147 7.020395216
157 7.331607129
176 7.637492223
202 7.848079136
223 7.989456499
251 8.76853608
278 9.092367123
...
</code></pre>
<p>As you see, the measurements are sampled at irregular time points. I need to smooth the data by averaging the reading up to 100 seconds prior each measurement (in Python). Since the data table is huge, an iterator-based method is really preferred.
Unfortunately, after two hours of coding I can't figure out efficient and elegant solution.</p>
<p>Can anyone help me?</p>
<p><strong>EDIT</strong>s</p>
<ol>
<li><p>I want one smoothed reading for each raw reading, and the smoothed reading is to be the arithmetic mean of the raw reading and any others in the previous 100 (delta) seconds. (John, you are right)</p></li>
<li><p>Huge ~ 1e6 - 10e6 lines + need to work with tight RAM</p></li>
<li><p>The data is approximately random walk</p></li>
<li><p>The data is sorted</p></li>
</ol>
<h1>RESOLUTION</h1>
<p>I have tested solutions proposed by J Machin and yairchu. They both gave the same results, however, on my data set, J Machin's version performs exponentially, while that of yairchu is linear. Following are execution times as measured by IPython's <em>%timeit</em> (in microseconds):</p>
<pre><code>data size J Machin yairchu
10 90.2 55.6
50 930 258
100 3080 514
500 64700 2660
1000 253000 5390
2000 952000 11500
</code></pre>
<p>Thank you all for the help.</p>
| 5 | 2009-06-21T11:36:57Z | 1,023,969 | <p>This one makes it linear:</p>
<pre><code>def process_data(datafile):
previous_n = 0
previous_t = 0
for line in datafile:
t, number = line.strip().split()
t = int(t)
number = float(number)
delta_n = number - previous_n
delta_t = t - previous_t
n_per_t = delta_n / delta_t
for t0 in xrange(delta_t):
yield previous_t + t0, previous_n + (n_per_t * t0)
previous_n = n
previous_t = t
f = open('datafile.dat')
for sample in process_data(f):
print sample
</code></pre>
| 0 | 2009-06-21T14:02:32Z | [
"python",
"datetime",
"data-mining",
"smoothing"
] |
smoothing irregularly sampled time data | 1,023,719 | <p>Given a table where the first column is seconds past a certain reference point and the second one is an arbitrary measurement:</p>
<pre><code>6 0.738158581
21 0.801697222
39 1.797224596
49 2.77920469
54 2.839757536
79 3.832232283
91 4.676794376
97 5.18244704
100 5.521878863
118 6.316630137
131 6.778507504
147 7.020395216
157 7.331607129
176 7.637492223
202 7.848079136
223 7.989456499
251 8.76853608
278 9.092367123
...
</code></pre>
<p>As you see, the measurements are sampled at irregular time points. I need to smooth the data by averaging the reading up to 100 seconds prior each measurement (in Python). Since the data table is huge, an iterator-based method is really preferred.
Unfortunately, after two hours of coding I can't figure out efficient and elegant solution.</p>
<p>Can anyone help me?</p>
<p><strong>EDIT</strong>s</p>
<ol>
<li><p>I want one smoothed reading for each raw reading, and the smoothed reading is to be the arithmetic mean of the raw reading and any others in the previous 100 (delta) seconds. (John, you are right)</p></li>
<li><p>Huge ~ 1e6 - 10e6 lines + need to work with tight RAM</p></li>
<li><p>The data is approximately random walk</p></li>
<li><p>The data is sorted</p></li>
</ol>
<h1>RESOLUTION</h1>
<p>I have tested solutions proposed by J Machin and yairchu. They both gave the same results, however, on my data set, J Machin's version performs exponentially, while that of yairchu is linear. Following are execution times as measured by IPython's <em>%timeit</em> (in microseconds):</p>
<pre><code>data size J Machin yairchu
10 90.2 55.6
50 930 258
100 3080 514
500 64700 2660
1000 253000 5390
2000 952000 11500
</code></pre>
<p>Thank you all for the help.</p>
| 5 | 2009-06-21T11:36:57Z | 1,023,994 | <p>Sounds like you need a simple rounding formula. To round any number to an arbitrary interval:</p>
<p>round(num/interval)*interval</p>
<p>You can substitute round with floor or ceiling for "leading up to" or "since" affects. It can work in any language, including SQL. </p>
| -2 | 2009-06-21T14:13:38Z | [
"python",
"datetime",
"data-mining",
"smoothing"
] |
smoothing irregularly sampled time data | 1,023,719 | <p>Given a table where the first column is seconds past a certain reference point and the second one is an arbitrary measurement:</p>
<pre><code>6 0.738158581
21 0.801697222
39 1.797224596
49 2.77920469
54 2.839757536
79 3.832232283
91 4.676794376
97 5.18244704
100 5.521878863
118 6.316630137
131 6.778507504
147 7.020395216
157 7.331607129
176 7.637492223
202 7.848079136
223 7.989456499
251 8.76853608
278 9.092367123
...
</code></pre>
<p>As you see, the measurements are sampled at irregular time points. I need to smooth the data by averaging the reading up to 100 seconds prior each measurement (in Python). Since the data table is huge, an iterator-based method is really preferred.
Unfortunately, after two hours of coding I can't figure out efficient and elegant solution.</p>
<p>Can anyone help me?</p>
<p><strong>EDIT</strong>s</p>
<ol>
<li><p>I want one smoothed reading for each raw reading, and the smoothed reading is to be the arithmetic mean of the raw reading and any others in the previous 100 (delta) seconds. (John, you are right)</p></li>
<li><p>Huge ~ 1e6 - 10e6 lines + need to work with tight RAM</p></li>
<li><p>The data is approximately random walk</p></li>
<li><p>The data is sorted</p></li>
</ol>
<h1>RESOLUTION</h1>
<p>I have tested solutions proposed by J Machin and yairchu. They both gave the same results, however, on my data set, J Machin's version performs exponentially, while that of yairchu is linear. Following are execution times as measured by IPython's <em>%timeit</em> (in microseconds):</p>
<pre><code>data size J Machin yairchu
10 90.2 55.6
50 930 258
100 3080 514
500 64700 2660
1000 253000 5390
2000 952000 11500
</code></pre>
<p>Thank you all for the help.</p>
| 5 | 2009-06-21T11:36:57Z | 1,024,066 | <p>O(1) memory in case you can iterate the input more than once - you can use one iterator for the "left" and one for the "right".</p>
<pre><code>def getAvgValues(makeIter, avgSampleTime):
leftIter = makeIter()
leftT, leftV = leftIter.next()
tot = 0
count = 0
for rightT, rightV in makeIter():
tot += rightV
count += 1
while leftT <= rightT - avgSampleTime:
tot -= leftV
count -= 1
leftT, leftV = leftIter.next()
yield rightT, tot / count
</code></pre>
| 0 | 2009-06-21T14:46:42Z | [
"python",
"datetime",
"data-mining",
"smoothing"
] |
smoothing irregularly sampled time data | 1,023,719 | <p>Given a table where the first column is seconds past a certain reference point and the second one is an arbitrary measurement:</p>
<pre><code>6 0.738158581
21 0.801697222
39 1.797224596
49 2.77920469
54 2.839757536
79 3.832232283
91 4.676794376
97 5.18244704
100 5.521878863
118 6.316630137
131 6.778507504
147 7.020395216
157 7.331607129
176 7.637492223
202 7.848079136
223 7.989456499
251 8.76853608
278 9.092367123
...
</code></pre>
<p>As you see, the measurements are sampled at irregular time points. I need to smooth the data by averaging the reading up to 100 seconds prior each measurement (in Python). Since the data table is huge, an iterator-based method is really preferred.
Unfortunately, after two hours of coding I can't figure out efficient and elegant solution.</p>
<p>Can anyone help me?</p>
<p><strong>EDIT</strong>s</p>
<ol>
<li><p>I want one smoothed reading for each raw reading, and the smoothed reading is to be the arithmetic mean of the raw reading and any others in the previous 100 (delta) seconds. (John, you are right)</p></li>
<li><p>Huge ~ 1e6 - 10e6 lines + need to work with tight RAM</p></li>
<li><p>The data is approximately random walk</p></li>
<li><p>The data is sorted</p></li>
</ol>
<h1>RESOLUTION</h1>
<p>I have tested solutions proposed by J Machin and yairchu. They both gave the same results, however, on my data set, J Machin's version performs exponentially, while that of yairchu is linear. Following are execution times as measured by IPython's <em>%timeit</em> (in microseconds):</p>
<pre><code>data size J Machin yairchu
10 90.2 55.6
50 930 258
100 3080 514
500 64700 2660
1000 253000 5390
2000 952000 11500
</code></pre>
<p>Thank you all for the help.</p>
| 5 | 2009-06-21T11:36:57Z | 1,030,120 | <p>While it gives an exponentially decaying average, rather than a total average, I think you may want what I called an <a href="http://stackoverflow.com/questions/1023860/exponential-moving-average-sampled-at-varying-times">exponential moving average with varying alpha</a>, which is really a single-pole low-pass filter. There's now a solution to that question, and it runs in time linear to the number of data points. See if it works for you.</p>
| 0 | 2009-06-23T00:51:54Z | [
"python",
"datetime",
"data-mining",
"smoothing"
] |
How can I have variable assertions in Perl? | 1,023,813 | <p>How can I check that a variable has a specific value in Perl? Is there a command to stop a script's execution to look up some of it's variables?</p>
<p>I wonder if I can use the Pythonic practice of inserting:</p>
<pre><code> assert 0, (foo, bar)
</code></pre>
<p>to debug scripts in a debuger-less way?</p>
| 6 | 2009-06-21T12:45:21Z | 1,023,831 | <p>There is a script at <a href="http://www.perlmonks.org/?node%5Fid=391780" rel="nofollow">PerlMonks</a> that introduces a fast assert method.</p>
<p>Speed is important since Perl is interpreted and any inline checks will impact performance (unlike simple C macros for example)</p>
<p><hr /></p>
<p>I am not sure if these things are going to be directly usable.</p>
<ul>
<li>there is <a href="http://search.cpan.org/perldoc?Test::Harness" rel="nofollow">Test::Harness</a> in default installs. Here <a href="http://tomacorp.com/perl/harness/index.html" rel="nofollow">is a starter tutorial</a>. The more recent module is <a href="http://search.cpan.org/perldoc?TAP::Harness" rel="nofollow">TAP::Harness</a></li>
<li>A slower version along the lines you talk is <a href="http://search.cpan.org/perldoc?Sub::Assert" rel="nofollow">Sub::Assert</a></li>
</ul>
<p><hr /></p>
<p>Ok! This is what i was looking for -- <a href="http://www.wgz.org/chromatic/perl/Test-Tutorial.pdf" rel="nofollow">PDF Warning: Test-Tutorial.pdf</a>. The <code>Test::Harness</code> is used for writing Perl module tests.</p>
| 2 | 2009-06-21T12:54:23Z | [
"python",
"perl",
"debugging",
"assertions"
] |
How can I have variable assertions in Perl? | 1,023,813 | <p>How can I check that a variable has a specific value in Perl? Is there a command to stop a script's execution to look up some of it's variables?</p>
<p>I wonder if I can use the Pythonic practice of inserting:</p>
<pre><code> assert 0, (foo, bar)
</code></pre>
<p>to debug scripts in a debuger-less way?</p>
| 6 | 2009-06-21T12:45:21Z | 1,023,839 | <p>A quick CPAN search suggests <a href="http://search.cpan.org/perldoc?Carp::Assert">Carp::Assert</a>.</p>
| 10 | 2009-06-21T12:58:04Z | [
"python",
"perl",
"debugging",
"assertions"
] |
How can I have variable assertions in Perl? | 1,023,813 | <p>How can I check that a variable has a specific value in Perl? Is there a command to stop a script's execution to look up some of it's variables?</p>
<p>I wonder if I can use the Pythonic practice of inserting:</p>
<pre><code> assert 0, (foo, bar)
</code></pre>
<p>to debug scripts in a debuger-less way?</p>
| 6 | 2009-06-21T12:45:21Z | 1,023,840 | <p>See <a href="http://search.cpan.org/perldoc?Carp::Assert">Carp::Assert</a>.</p>
| 5 | 2009-06-21T12:58:05Z | [
"python",
"perl",
"debugging",
"assertions"
] |
How can I have variable assertions in Perl? | 1,023,813 | <p>How can I check that a variable has a specific value in Perl? Is there a command to stop a script's execution to look up some of it's variables?</p>
<p>I wonder if I can use the Pythonic practice of inserting:</p>
<pre><code> assert 0, (foo, bar)
</code></pre>
<p>to debug scripts in a debuger-less way?</p>
| 6 | 2009-06-21T12:45:21Z | 1,023,925 | <p><a href="http://search.cpan.org/perldoc?Smart::Comments">Smart::Comments</a> are nice.</p>
| 5 | 2009-06-21T13:44:06Z | [
"python",
"perl",
"debugging",
"assertions"
] |
How can I have variable assertions in Perl? | 1,023,813 | <p>How can I check that a variable has a specific value in Perl? Is there a command to stop a script's execution to look up some of it's variables?</p>
<p>I wonder if I can use the Pythonic practice of inserting:</p>
<pre><code> assert 0, (foo, bar)
</code></pre>
<p>to debug scripts in a debuger-less way?</p>
| 6 | 2009-06-21T12:45:21Z | 1,023,941 | <pre><code>$var_to_check =~ /sometest/ or die "bad variable!";
</code></pre>
<p>I tend to throw things like this in my code, and later use a find and replace to get rid of them (in production code).</p>
<p>Also, '<a href="http://perldoc.perl.org/functions/eval.html" rel="nofollow">eval</a>' can be used to run a section of code and capture errors and can be used to create exception handling functionality. If you are asserting that a value is not 0, perhaps you want to throw an exception and handle that case in a special way?</p>
| 1 | 2009-06-21T13:51:18Z | [
"python",
"perl",
"debugging",
"assertions"
] |
How can I have variable assertions in Perl? | 1,023,813 | <p>How can I check that a variable has a specific value in Perl? Is there a command to stop a script's execution to look up some of it's variables?</p>
<p>I wonder if I can use the Pythonic practice of inserting:</p>
<pre><code> assert 0, (foo, bar)
</code></pre>
<p>to debug scripts in a debuger-less way?</p>
| 6 | 2009-06-21T12:45:21Z | 9,707,289 | <pre><code>if ( $next_sunrise_time > 24*60*60 ) { warn( "assertion failed" ); } # Assert that the sun must rise in the next 24 hours.
</code></pre>
<p>You can do this if you do not have access to Perl 5.9 which is required for <a href="http://search.cpan.org/perldoc?Carp%3a%3aAssert" rel="nofollow">Carp::Assert</a>.</p>
| 0 | 2012-03-14T17:50:37Z | [
"python",
"perl",
"debugging",
"assertions"
] |
It is possible to match a character repetition with regex? How? | 1,023,902 | <p><strong>Question:</strong><br />
Is is possible, with regex, to match a word that contains the same character in different positions?</p>
<p><strong>Condition:</strong><br />
All words have the same length, you know the character positions (example the 1st, the 2nd and the 4th) of the repeated char, but you don't know what is it.</p>
<p><strong>Examples:</strong> <br />
using lowercase 6char words I'd like to match words where the 3rd and the 4th chars are the same.</p>
<pre><code>parrot <- match for double r
follia <- match for double l
carrot <- match for double r
mattia <- match for double t
rettoo <- match for double t
melone <- doesn't match
</code></pre>
<p>I can't use the quantifier [\d]{2} because it match any succession of two chars, and what if I say the 2nd and the 4th position instead of 3rd and 4th?</p>
<p>Is it possible to do what I want with regex? If yes, how can I do that?</p>
<p><strong>EDIT:</strong><br />
Ask asked in the comments, I'm using python</p>
| 5 | 2009-06-21T13:33:53Z | 1,023,909 | <p>You can use a backreference to do this:</p>
<pre><code>(.)\1
</code></pre>
<p>This will match consecutive occurrences of any character.</p>
<p><hr /></p>
<p><strong>Edit</strong>Â Â Â Hereâs some Python example:</p>
<pre><code>import re
regexp = re.compile(r"(.)\1")
data = ["parrot","follia","carrot","mattia","rettoo","melone"]
for str in data:
match = re.search(regexp, str)
if match:
print str, "<- match for double", match.group(1)
else:
print str, "<- doesn't match"
</code></pre>
| 22 | 2009-06-21T13:38:33Z | [
"python",
"regex"
] |
It is possible to match a character repetition with regex? How? | 1,023,902 | <p><strong>Question:</strong><br />
Is is possible, with regex, to match a word that contains the same character in different positions?</p>
<p><strong>Condition:</strong><br />
All words have the same length, you know the character positions (example the 1st, the 2nd and the 4th) of the repeated char, but you don't know what is it.</p>
<p><strong>Examples:</strong> <br />
using lowercase 6char words I'd like to match words where the 3rd and the 4th chars are the same.</p>
<pre><code>parrot <- match for double r
follia <- match for double l
carrot <- match for double r
mattia <- match for double t
rettoo <- match for double t
melone <- doesn't match
</code></pre>
<p>I can't use the quantifier [\d]{2} because it match any succession of two chars, and what if I say the 2nd and the 4th position instead of 3rd and 4th?</p>
<p>Is it possible to do what I want with regex? If yes, how can I do that?</p>
<p><strong>EDIT:</strong><br />
Ask asked in the comments, I'm using python</p>
| 5 | 2009-06-21T13:33:53Z | 1,023,920 | <p><code>/(\b\w*?(\w)\2.*?\b)/</code></p>
<p>will match any word with atleast on character repetition
$1 being the word
$2 the first repetition.</p>
| 2 | 2009-06-21T13:42:34Z | [
"python",
"regex"
] |
It is possible to match a character repetition with regex? How? | 1,023,902 | <p><strong>Question:</strong><br />
Is is possible, with regex, to match a word that contains the same character in different positions?</p>
<p><strong>Condition:</strong><br />
All words have the same length, you know the character positions (example the 1st, the 2nd and the 4th) of the repeated char, but you don't know what is it.</p>
<p><strong>Examples:</strong> <br />
using lowercase 6char words I'd like to match words where the 3rd and the 4th chars are the same.</p>
<pre><code>parrot <- match for double r
follia <- match for double l
carrot <- match for double r
mattia <- match for double t
rettoo <- match for double t
melone <- doesn't match
</code></pre>
<p>I can't use the quantifier [\d]{2} because it match any succession of two chars, and what if I say the 2nd and the 4th position instead of 3rd and 4th?</p>
<p>Is it possible to do what I want with regex? If yes, how can I do that?</p>
<p><strong>EDIT:</strong><br />
Ask asked in the comments, I'm using python</p>
| 5 | 2009-06-21T13:33:53Z | 1,023,922 | <p>You need to use back references for such cases. I am not sure which language you are using, I tried the following example in my VI editor to search for any alphabet repeating.
<strong>Pattern Regex:</strong> <code>\([a-z]\)\1</code> </p>
<p>If you see the example, [a-z] is the pattern you are searching for, and enclose that inside the paranthesis (the parantheses should be escaped in some languages). Once you have a paranthesis, it is a group and can be referred again anywhere in the regex by using \1. If there is more than one group, you can use \1, \2 etc. \1 will be replaced by whatever was matched in the first group.</p>
<p>Thanks
Arvind</p>
| 6 | 2009-06-21T13:42:59Z | [
"python",
"regex"
] |
It is possible to match a character repetition with regex? How? | 1,023,902 | <p><strong>Question:</strong><br />
Is is possible, with regex, to match a word that contains the same character in different positions?</p>
<p><strong>Condition:</strong><br />
All words have the same length, you know the character positions (example the 1st, the 2nd and the 4th) of the repeated char, but you don't know what is it.</p>
<p><strong>Examples:</strong> <br />
using lowercase 6char words I'd like to match words where the 3rd and the 4th chars are the same.</p>
<pre><code>parrot <- match for double r
follia <- match for double l
carrot <- match for double r
mattia <- match for double t
rettoo <- match for double t
melone <- doesn't match
</code></pre>
<p>I can't use the quantifier [\d]{2} because it match any succession of two chars, and what if I say the 2nd and the 4th position instead of 3rd and 4th?</p>
<p>Is it possible to do what I want with regex? If yes, how can I do that?</p>
<p><strong>EDIT:</strong><br />
Ask asked in the comments, I'm using python</p>
| 5 | 2009-06-21T13:33:53Z | 1,024,178 | <p>Yes, you can use backreference construct to match the double letters.</p>
<p>The regular expression <code>(?<char>\w)\k<char></code>, using named groups and backreferencing, searches for adjacent paired characters. When applied to the string "I'll have a small coffee," it finds matches in the words "I'll", "small", and "coffee". The metacharacter <code>\w</code> finds any single-word character. The grouping construct <code>(?<char>)</code> encloses the metacharacter to force the regular expression engine to remember a subexpression match (which, in this case, will be any single character) and save it under the name "char". The backreference construct <code>\k<char></code> causes the engine to compare the current character to the previously matched character stored under "char". The entire regular expression successfully finds a match wherever a single character is the same as the preceding character.</p>
| 0 | 2009-06-21T15:43:40Z | [
"python",
"regex"
] |
Is it pythonic to import inside functions? | 1,024,049 | <p><a href="http://www.python.org/dev/peps/pep-0008/">PEP 8</a> says:</p>
<blockquote>
<ul>
<li>Imports are always put at the top of the file, just after any module
comments and docstrings, and before module globals and constants.</li>
</ul>
</blockquote>
<p>On occation, I violate PEP 8. Some times I import stuff inside functions. As a general rule, I do this if there is an import that is only used within a single function.</p>
<p>Any opinions?</p>
<p><strong>EDIT (the reason I feel importing in functions can be a good idea):</strong></p>
<p>Main reason: It can make the code clearer.</p>
<ul>
<li>When looking at the code of a function I might ask myself: "What is function/class xxx?" (xxx being used inside the function). If I have all my imports at the top of the module, I have to go look there to determine what xxx is. This is more of an issue when using <code>from m import xxx</code>. Seeing <code>m.xxx</code> in the function probably tells me more. Depending on what <code>m</code> is: Is it a well-known top-level module/package (<code>import m</code>)? Or is it a sub-module/package (<code>from a.b.c import m</code>)?</li>
<li>In some cases having that extra information ("What is xxx?") close to where xxx is used can make the function easier to understand.</li>
</ul>
| 41 | 2009-06-21T14:41:00Z | 1,024,058 | <p>As long as it's <code>import</code> and not <code>from x import *</code>, you should put them at the top. It adds just one name to the global namespace, and you stick to PEP 8. Plus, if you later need it somewhere else, you don't have to move anything around.</p>
<p>It's no big deal, but since there's almost no difference I'd suggest doing what PEP 8 says.</p>
| 2 | 2009-06-21T14:44:43Z | [
"python",
"conventions"
] |
Is it pythonic to import inside functions? | 1,024,049 | <p><a href="http://www.python.org/dev/peps/pep-0008/">PEP 8</a> says:</p>
<blockquote>
<ul>
<li>Imports are always put at the top of the file, just after any module
comments and docstrings, and before module globals and constants.</li>
</ul>
</blockquote>
<p>On occation, I violate PEP 8. Some times I import stuff inside functions. As a general rule, I do this if there is an import that is only used within a single function.</p>
<p>Any opinions?</p>
<p><strong>EDIT (the reason I feel importing in functions can be a good idea):</strong></p>
<p>Main reason: It can make the code clearer.</p>
<ul>
<li>When looking at the code of a function I might ask myself: "What is function/class xxx?" (xxx being used inside the function). If I have all my imports at the top of the module, I have to go look there to determine what xxx is. This is more of an issue when using <code>from m import xxx</code>. Seeing <code>m.xxx</code> in the function probably tells me more. Depending on what <code>m</code> is: Is it a well-known top-level module/package (<code>import m</code>)? Or is it a sub-module/package (<code>from a.b.c import m</code>)?</li>
<li>In some cases having that extra information ("What is xxx?") close to where xxx is used can make the function easier to understand.</li>
</ul>
| 41 | 2009-06-21T14:41:00Z | 1,024,087 | <p>There are two occasions where I violate PEP 8 in this regard:</p>
<ul>
<li>Circular imports: module A imports module B, but something in module B needs module A (though this is often a sign that I need to refactor the modules to eliminate the circular dependency)</li>
<li>Inserting a pdb breakpoint: <code>import pdb; pdb.set_trace()</code> This is handy b/c I don't want to put <code>import pdb</code> at the top of every module I might want to debug, and it easy to remember to remove the import when I remove the breakpoint.</li>
</ul>
<p>Outside of these two cases, it's a good idea to put everything at the top. It makes the dependencies clearer.</p>
| 19 | 2009-06-21T14:53:55Z | [
"python",
"conventions"
] |
Is it pythonic to import inside functions? | 1,024,049 | <p><a href="http://www.python.org/dev/peps/pep-0008/">PEP 8</a> says:</p>
<blockquote>
<ul>
<li>Imports are always put at the top of the file, just after any module
comments and docstrings, and before module globals and constants.</li>
</ul>
</blockquote>
<p>On occation, I violate PEP 8. Some times I import stuff inside functions. As a general rule, I do this if there is an import that is only used within a single function.</p>
<p>Any opinions?</p>
<p><strong>EDIT (the reason I feel importing in functions can be a good idea):</strong></p>
<p>Main reason: It can make the code clearer.</p>
<ul>
<li>When looking at the code of a function I might ask myself: "What is function/class xxx?" (xxx being used inside the function). If I have all my imports at the top of the module, I have to go look there to determine what xxx is. This is more of an issue when using <code>from m import xxx</code>. Seeing <code>m.xxx</code> in the function probably tells me more. Depending on what <code>m</code> is: Is it a well-known top-level module/package (<code>import m</code>)? Or is it a sub-module/package (<code>from a.b.c import m</code>)?</li>
<li>In some cases having that extra information ("What is xxx?") close to where xxx is used can make the function easier to understand.</li>
</ul>
| 41 | 2009-06-21T14:41:00Z | 1,024,117 | <p>One thing to bear in mind: needless imports can cause performance problems. So if this is a function that will be called frequently, you're better off just putting the import at the top. Of course this <em>is</em> an optimization, so if there's a valid case to be made that importing inside a function is more clear than importing at the top of a file, that trumps performance in most cases.</p>
<p>If you're doing IronPython, I'm told that it's better to import inside functions (since compiling code in IronPython can be slow). Thus, you may be able to get a way with importing inside functions then. But other than that, I'd argue that it's just not worth it to fight convention.</p>
<blockquote>
<p>As a general rule, I do this if there is an import that is only used within a single function.</p>
</blockquote>
<p>Another point I'd like to make is that this may be a potential maintenence problem. What happens if you add a function that uses a module that was previously used by only one function? Are you going to remember to add the import to the top of the file? Or are you going to scan each and every function for imports?</p>
<p>FWIW, there are cases where it makes sense to import inside a function. For example, if you want to set the language in cx_Oracle, you need to set an NLS<code>_</code>LANG environment variable <em>before</em> it is imported. Thus, you may see code like this:</p>
<pre><code>import os
oracle = None
def InitializeOracle(lang):
global oracle
os.environ['NLS_LANG'] = lang
import cx_Oracle
oracle = cx_Oracle
</code></pre>
| 6 | 2009-06-21T15:08:40Z | [
"python",
"conventions"
] |
Is it pythonic to import inside functions? | 1,024,049 | <p><a href="http://www.python.org/dev/peps/pep-0008/">PEP 8</a> says:</p>
<blockquote>
<ul>
<li>Imports are always put at the top of the file, just after any module
comments and docstrings, and before module globals and constants.</li>
</ul>
</blockquote>
<p>On occation, I violate PEP 8. Some times I import stuff inside functions. As a general rule, I do this if there is an import that is only used within a single function.</p>
<p>Any opinions?</p>
<p><strong>EDIT (the reason I feel importing in functions can be a good idea):</strong></p>
<p>Main reason: It can make the code clearer.</p>
<ul>
<li>When looking at the code of a function I might ask myself: "What is function/class xxx?" (xxx being used inside the function). If I have all my imports at the top of the module, I have to go look there to determine what xxx is. This is more of an issue when using <code>from m import xxx</code>. Seeing <code>m.xxx</code> in the function probably tells me more. Depending on what <code>m</code> is: Is it a well-known top-level module/package (<code>import m</code>)? Or is it a sub-module/package (<code>from a.b.c import m</code>)?</li>
<li>In some cases having that extra information ("What is xxx?") close to where xxx is used can make the function easier to understand.</li>
</ul>
| 41 | 2009-06-21T14:41:00Z | 1,024,120 | <p>I've broken this rule before for modules that are self-testing. That is, they are normally just used for support, but I define a main for them so that if you run them by themselves you can test their functionality. In that case I sometimes import <code>getopt</code> and <code>cmd</code> just in main, because I want it to be clear to someone reading the code that these modules have nothing to do with the normal operation of the module and are only being included for testing.</p>
| 5 | 2009-06-21T15:10:58Z | [
"python",
"conventions"
] |
Is it pythonic to import inside functions? | 1,024,049 | <p><a href="http://www.python.org/dev/peps/pep-0008/">PEP 8</a> says:</p>
<blockquote>
<ul>
<li>Imports are always put at the top of the file, just after any module
comments and docstrings, and before module globals and constants.</li>
</ul>
</blockquote>
<p>On occation, I violate PEP 8. Some times I import stuff inside functions. As a general rule, I do this if there is an import that is only used within a single function.</p>
<p>Any opinions?</p>
<p><strong>EDIT (the reason I feel importing in functions can be a good idea):</strong></p>
<p>Main reason: It can make the code clearer.</p>
<ul>
<li>When looking at the code of a function I might ask myself: "What is function/class xxx?" (xxx being used inside the function). If I have all my imports at the top of the module, I have to go look there to determine what xxx is. This is more of an issue when using <code>from m import xxx</code>. Seeing <code>m.xxx</code> in the function probably tells me more. Depending on what <code>m</code> is: Is it a well-known top-level module/package (<code>import m</code>)? Or is it a sub-module/package (<code>from a.b.c import m</code>)?</li>
<li>In some cases having that extra information ("What is xxx?") close to where xxx is used can make the function easier to understand.</li>
</ul>
| 41 | 2009-06-21T14:41:00Z | 1,024,139 | <p>Here are the four import use cases that we use</p>
<ol>
<li><p><code>import</code> (and <code>from x import y</code> and <code>import x as y</code>) at the top</p></li>
<li><p>Choices for Import. At the top.</p>
<pre><code>import settings
if setting.something:
import this as foo
else:
import that as foo
</code></pre></li>
<li><p>Conditional Import. Used with JSON, XML libraries and the like. At the top.</p>
<pre><code>try:
import this as foo
except ImportError:
import that as foo
</code></pre></li>
<li><p>Dynamic Import. So far, we only have one example of this.</p>
<pre><code>import settings
module_stuff = {}
module= __import__( settings.some_module, module_stuff )
x = module_stuff['x']
</code></pre>
<p>Note that this dynamic import doesn't bring in code, but brings in complex
data structures written in Python. It's kind of like a pickled piece of data
except we pickled it by hand.</p>
<p>This is also, more-or-less, at the top of a module</p></li>
</ol>
<p><hr /></p>
<p>Here's what we do to make the code clearer:</p>
<ul>
<li><p>Keep the modules short.</p></li>
<li><p>If I have all my imports at the top of the module, I have to go look there to determine what a name is. If the module is short, that's easy to do.</p></li>
<li><p>In some cases having that extra information close to where a name is used can make the function easier to understand. If the module is short, that's easy to do.</p></li>
</ul>
| 11 | 2009-06-21T15:20:52Z | [
"python",
"conventions"
] |
Is it pythonic to import inside functions? | 1,024,049 | <p><a href="http://www.python.org/dev/peps/pep-0008/">PEP 8</a> says:</p>
<blockquote>
<ul>
<li>Imports are always put at the top of the file, just after any module
comments and docstrings, and before module globals and constants.</li>
</ul>
</blockquote>
<p>On occation, I violate PEP 8. Some times I import stuff inside functions. As a general rule, I do this if there is an import that is only used within a single function.</p>
<p>Any opinions?</p>
<p><strong>EDIT (the reason I feel importing in functions can be a good idea):</strong></p>
<p>Main reason: It can make the code clearer.</p>
<ul>
<li>When looking at the code of a function I might ask myself: "What is function/class xxx?" (xxx being used inside the function). If I have all my imports at the top of the module, I have to go look there to determine what xxx is. This is more of an issue when using <code>from m import xxx</code>. Seeing <code>m.xxx</code> in the function probably tells me more. Depending on what <code>m</code> is: Is it a well-known top-level module/package (<code>import m</code>)? Or is it a sub-module/package (<code>from a.b.c import m</code>)?</li>
<li>In some cases having that extra information ("What is xxx?") close to where xxx is used can make the function easier to understand.</li>
</ul>
| 41 | 2009-06-21T14:41:00Z | 1,025,259 | <p>In the long run I think you'll appreciate having most of your imports at the top of the file, that way you can tell at a glance how complicated your module is by what it needs to import.</p>
<p>If I'm adding new code to an existing file I'll usually do the import where it's needed and then if the code stays I'll makes things more permanent by moving the import line up to the top of the file.</p>
<p>One other point, I prefer to get an ImportError exception before any code is run -- as a sanity check, so that's another reason to import at the top. </p>
<p>I use pyChecker to check for unused modules.</p>
| 31 | 2009-06-22T02:05:00Z | [
"python",
"conventions"
] |
What's a good beginner setup for C++/Python on OSX? | 1,024,062 | <p>I'm looking for a good setup for learning C++ and eventually Python on Mac OSX. As I'm going use C++ I don't want to use XCode, as (I understand) this is primarily used with Objective-C. I have a small bit of experience in Java and MATLAB programming, and math is probably not going to be my main problem. I was thinking on an approach looking something like this:</p>
<ol>
<li>Work through <a href="http://rads.stackoverflow.com/amzn/click/020170353X" rel="nofollow" title="Accelerated C++ @ Amazon">Accelerated C++</a>.</li>
<li>Write a couple of small math-programs; something like the Mandelbrot set, a PDE-solver, or a graphing-app. This would be done using a widget toolkit.</li>
<li>Write a small game with really crappy graphics. This is probably going to be a rip-off of Jetmen Revival or Space Invaders ;-)</li>
<li>(When I'm fed up with the game not working), work my way through <a href="http://rads.stackoverflow.com/amzn/click/0132269937" rel="nofollow">Core Python</a>.</li>
<li>Repeat steps 2 and 3 in Python.</li>
</ol>
<p>I'm thinking about going with Eclipse and GTK+ / X11. Any thoughts on IDE's and GUI toolkits? Preferably open source, and definitely free. And what do you think about the 5 steps?</p>
<p>Any help would be much appreciated - thanks in advance!</p>
| 4 | 2009-06-21T14:45:46Z | 1,024,089 | <p>I'd definitely go GTK+. It is very easy. I'm not sure about graphics libraries on OS X. I know OS X primarily uses Objective-C, but if the native graphics library can be used from C++, use that for game graphics.</p>
<p>As far as IDEs, I don't know. I use GNU Emacs, but I wouldn't recommend that to a beginner. Learning how to use Emacs is like learning a new programming language all by itself. I would start with a basic text editor (look up one with syntax highlighting) and compiling from the terminal for now, so you don't have to learn an IDE too. They make huge projects easier, but can be a PITA for little things.</p>
| 0 | 2009-06-21T14:54:04Z | [
"c++",
"python",
"osx",
"ide"
] |
What's a good beginner setup for C++/Python on OSX? | 1,024,062 | <p>I'm looking for a good setup for learning C++ and eventually Python on Mac OSX. As I'm going use C++ I don't want to use XCode, as (I understand) this is primarily used with Objective-C. I have a small bit of experience in Java and MATLAB programming, and math is probably not going to be my main problem. I was thinking on an approach looking something like this:</p>
<ol>
<li>Work through <a href="http://rads.stackoverflow.com/amzn/click/020170353X" rel="nofollow" title="Accelerated C++ @ Amazon">Accelerated C++</a>.</li>
<li>Write a couple of small math-programs; something like the Mandelbrot set, a PDE-solver, or a graphing-app. This would be done using a widget toolkit.</li>
<li>Write a small game with really crappy graphics. This is probably going to be a rip-off of Jetmen Revival or Space Invaders ;-)</li>
<li>(When I'm fed up with the game not working), work my way through <a href="http://rads.stackoverflow.com/amzn/click/0132269937" rel="nofollow">Core Python</a>.</li>
<li>Repeat steps 2 and 3 in Python.</li>
</ol>
<p>I'm thinking about going with Eclipse and GTK+ / X11. Any thoughts on IDE's and GUI toolkits? Preferably open source, and definitely free. And what do you think about the 5 steps?</p>
<p>Any help would be much appreciated - thanks in advance!</p>
| 4 | 2009-06-21T14:45:46Z | 1,024,104 | <p>You can use VIM with cscope and ctags plugins for C++, I personally find that to be the fastest. Eclipse for C++ is also good if you need a gui, but it is not as feature rich as it is for Java but it is a good open source IDE. </p>
<p>In terms of books, Effective C++ and More Effective C++ are good.</p>
| 0 | 2009-06-21T15:00:54Z | [
"c++",
"python",
"osx",
"ide"
] |
What's a good beginner setup for C++/Python on OSX? | 1,024,062 | <p>I'm looking for a good setup for learning C++ and eventually Python on Mac OSX. As I'm going use C++ I don't want to use XCode, as (I understand) this is primarily used with Objective-C. I have a small bit of experience in Java and MATLAB programming, and math is probably not going to be my main problem. I was thinking on an approach looking something like this:</p>
<ol>
<li>Work through <a href="http://rads.stackoverflow.com/amzn/click/020170353X" rel="nofollow" title="Accelerated C++ @ Amazon">Accelerated C++</a>.</li>
<li>Write a couple of small math-programs; something like the Mandelbrot set, a PDE-solver, or a graphing-app. This would be done using a widget toolkit.</li>
<li>Write a small game with really crappy graphics. This is probably going to be a rip-off of Jetmen Revival or Space Invaders ;-)</li>
<li>(When I'm fed up with the game not working), work my way through <a href="http://rads.stackoverflow.com/amzn/click/0132269937" rel="nofollow">Core Python</a>.</li>
<li>Repeat steps 2 and 3 in Python.</li>
</ol>
<p>I'm thinking about going with Eclipse and GTK+ / X11. Any thoughts on IDE's and GUI toolkits? Preferably open source, and definitely free. And what do you think about the 5 steps?</p>
<p>Any help would be much appreciated - thanks in advance!</p>
| 4 | 2009-06-21T14:45:46Z | 1,024,118 | <blockquote>
<p>As I'm going use C++ I don't
want to use XCode, as (I understand)
this is primarily used with
Objective-C.</p>
</blockquote>
<p>XCode is a fine choice, even for pure C++ solutions.</p>
<blockquote>
<p>Work through Accelerated C++.</p>
</blockquote>
<p>That's the book that got me started! It's an excellent choice, but not a walk in the park. It took me a month or two, at a rate of about 1 to 2 hours a day. But after this you'll have made a MAJOR jump towards becoming a really good C++ programmer.</p>
<blockquote>
<p>Write a couple of small math-programs;
something like the Mandelbrot set, a
PDE-solver, or a graphing-app. This
would be done using a widget toolkit.
Write a small game with really crappy
graphics. This is probably going to be
a rip-off of Jetmen Revival or Space
Invaders ;-) (When I'm fed up with the
game not working), work my way through
Core Python (this is a book; max. one
link/question for new users...).</p>
</blockquote>
<p>Fine, I did Tetris.</p>
<blockquote>
<p>Repeat steps 2 and 3 in Python.</p>
</blockquote>
<p>I have no experience using Python, but I know it's a much easier language to master than C++. So if you can master C++, Python's won't be any problem.</p>
<p>For GUI you could use Qt, especially now it has been made LGPL. However, Cocoa is interesting as well, if feel courageous enough to also learn Objective-C :) (Btw, there is a Python port for Cocoa as well.)</p>
| 3 | 2009-06-21T15:10:17Z | [
"c++",
"python",
"osx",
"ide"
] |
What's a good beginner setup for C++/Python on OSX? | 1,024,062 | <p>I'm looking for a good setup for learning C++ and eventually Python on Mac OSX. As I'm going use C++ I don't want to use XCode, as (I understand) this is primarily used with Objective-C. I have a small bit of experience in Java and MATLAB programming, and math is probably not going to be my main problem. I was thinking on an approach looking something like this:</p>
<ol>
<li>Work through <a href="http://rads.stackoverflow.com/amzn/click/020170353X" rel="nofollow" title="Accelerated C++ @ Amazon">Accelerated C++</a>.</li>
<li>Write a couple of small math-programs; something like the Mandelbrot set, a PDE-solver, or a graphing-app. This would be done using a widget toolkit.</li>
<li>Write a small game with really crappy graphics. This is probably going to be a rip-off of Jetmen Revival or Space Invaders ;-)</li>
<li>(When I'm fed up with the game not working), work my way through <a href="http://rads.stackoverflow.com/amzn/click/0132269937" rel="nofollow">Core Python</a>.</li>
<li>Repeat steps 2 and 3 in Python.</li>
</ol>
<p>I'm thinking about going with Eclipse and GTK+ / X11. Any thoughts on IDE's and GUI toolkits? Preferably open source, and definitely free. And what do you think about the 5 steps?</p>
<p>Any help would be much appreciated - thanks in advance!</p>
| 4 | 2009-06-21T14:45:46Z | 1,024,141 | <p>XCode is a mature IDE well suited to almost any language. C++ is particularly well supported. </p>
<p>Apparently GTK+ has <a href="http://gtk-osx.sourceforge.net/" rel="nofollow">native OSX widget support</a>, though I've never used it, so you could skip the X11 stack altogether if you desired. Other cross platform widget sets include <a href="http://www.wxwidgets.org/" rel="nofollow">wxWidgets</a>, <a href="http://www.fltk.org/" rel="nofollow">fltk</a> and <a href="http://www.tkdocs.com/" rel="nofollow">Tk</a>.</p>
<p>For games, though, they are less than optimal. for this I strongly recommend <a href="http://www.libsdl.org/" rel="nofollow">LibSDL</a> or its python binding, <a href="http://www.pygame.org/" rel="nofollow">PyGame</a>. These can provide a convenient, standard interface to OpenGL if you want to use that, or you can use hardware accelerated 2d primitives if that's all you need. </p>
| 2 | 2009-06-21T15:22:29Z | [
"c++",
"python",
"osx",
"ide"
] |
What's a good beginner setup for C++/Python on OSX? | 1,024,062 | <p>I'm looking for a good setup for learning C++ and eventually Python on Mac OSX. As I'm going use C++ I don't want to use XCode, as (I understand) this is primarily used with Objective-C. I have a small bit of experience in Java and MATLAB programming, and math is probably not going to be my main problem. I was thinking on an approach looking something like this:</p>
<ol>
<li>Work through <a href="http://rads.stackoverflow.com/amzn/click/020170353X" rel="nofollow" title="Accelerated C++ @ Amazon">Accelerated C++</a>.</li>
<li>Write a couple of small math-programs; something like the Mandelbrot set, a PDE-solver, or a graphing-app. This would be done using a widget toolkit.</li>
<li>Write a small game with really crappy graphics. This is probably going to be a rip-off of Jetmen Revival or Space Invaders ;-)</li>
<li>(When I'm fed up with the game not working), work my way through <a href="http://rads.stackoverflow.com/amzn/click/0132269937" rel="nofollow">Core Python</a>.</li>
<li>Repeat steps 2 and 3 in Python.</li>
</ol>
<p>I'm thinking about going with Eclipse and GTK+ / X11. Any thoughts on IDE's and GUI toolkits? Preferably open source, and definitely free. And what do you think about the 5 steps?</p>
<p>Any help would be much appreciated - thanks in advance!</p>
| 4 | 2009-06-21T14:45:46Z | 1,024,162 | <blockquote>
<ol>
<li>Work through Accelerated C++.</li>
<li>Write a couple of small math-programs; something like the
Mandelbrot set, a PDE-solver, or a
graphing-app. This would be done using
a widget toolkit.</li>
<li>Write a small game with really crappy graphics. This is probably
going to be a rip-off of Jetmen
Revival or Space Invaders ;-)</li>
<li>(When I'm fed up with the game not working), work my way through Core
Python (this is a book; max. one
link/question for new users...).</li>
<li>Repeat steps 2 and 3 in Python.</li>
</ol>
</blockquote>
<p>Might I recommend doing this in reverse order with respect to languages? Bear in mind that GTK+ isn't trivial to learn, neither is C++. In fact, I'd really recommend starting out with Cocoa and <a href="http://pyobjc.sourceforge.net/" rel="nofollow">PyObjC</a> first. Cocoa is a little bit more to wrap your head around, but once you get it down, it's very easy to see its benefit. A development setup of GTK and PyGTK can be a PITA to set up on OS X (at least it was for me).</p>
| 0 | 2009-06-21T15:33:40Z | [
"c++",
"python",
"osx",
"ide"
] |
What's a good beginner setup for C++/Python on OSX? | 1,024,062 | <p>I'm looking for a good setup for learning C++ and eventually Python on Mac OSX. As I'm going use C++ I don't want to use XCode, as (I understand) this is primarily used with Objective-C. I have a small bit of experience in Java and MATLAB programming, and math is probably not going to be my main problem. I was thinking on an approach looking something like this:</p>
<ol>
<li>Work through <a href="http://rads.stackoverflow.com/amzn/click/020170353X" rel="nofollow" title="Accelerated C++ @ Amazon">Accelerated C++</a>.</li>
<li>Write a couple of small math-programs; something like the Mandelbrot set, a PDE-solver, or a graphing-app. This would be done using a widget toolkit.</li>
<li>Write a small game with really crappy graphics. This is probably going to be a rip-off of Jetmen Revival or Space Invaders ;-)</li>
<li>(When I'm fed up with the game not working), work my way through <a href="http://rads.stackoverflow.com/amzn/click/0132269937" rel="nofollow">Core Python</a>.</li>
<li>Repeat steps 2 and 3 in Python.</li>
</ol>
<p>I'm thinking about going with Eclipse and GTK+ / X11. Any thoughts on IDE's and GUI toolkits? Preferably open source, and definitely free. And what do you think about the 5 steps?</p>
<p>Any help would be much appreciated - thanks in advance!</p>
| 4 | 2009-06-21T14:45:46Z | 1,024,165 | <p>When choosing an IDE, it's very much a matter of taste, so the best choice is probably to try out several for a day or two each. Eclipse and XCode are both popular choices that surely are excellent in their own ways. I can't help you with the widgets, as I know very little about that. GTK+ is a popular framework, but the native OS X support wasn't ready last time I checked, but development is ongoing so this could have changed. Qt is less popular, but is nowadays completely open source, so the licensing issues it used to have are solved now, so you might want to look into that as well. wxWidgets are popular in Python and I found it easy to use, but I don't know if it's as good as the other ones, but it may very well be.</p>
<p>As for the five steps, it makes much more sense to do them in Python first. Python is easy to learn and master, especially if you are NOT tainted by C/C++. C/C++ programmers often has to unlearn things, as there are so many things you must do and think of that you don't have to bother with in Python. </p>
<p>With Python you can concentrate on learning the libraries and tools, instead of having to learn how to not shoot yourself in the foot with C++. Learn C++ afterwards, and you'll have a nicer smoother learning curve, and enjoy yourself more.</p>
| 1 | 2009-06-21T15:36:08Z | [
"c++",
"python",
"osx",
"ide"
] |
What's a good beginner setup for C++/Python on OSX? | 1,024,062 | <p>I'm looking for a good setup for learning C++ and eventually Python on Mac OSX. As I'm going use C++ I don't want to use XCode, as (I understand) this is primarily used with Objective-C. I have a small bit of experience in Java and MATLAB programming, and math is probably not going to be my main problem. I was thinking on an approach looking something like this:</p>
<ol>
<li>Work through <a href="http://rads.stackoverflow.com/amzn/click/020170353X" rel="nofollow" title="Accelerated C++ @ Amazon">Accelerated C++</a>.</li>
<li>Write a couple of small math-programs; something like the Mandelbrot set, a PDE-solver, or a graphing-app. This would be done using a widget toolkit.</li>
<li>Write a small game with really crappy graphics. This is probably going to be a rip-off of Jetmen Revival or Space Invaders ;-)</li>
<li>(When I'm fed up with the game not working), work my way through <a href="http://rads.stackoverflow.com/amzn/click/0132269937" rel="nofollow">Core Python</a>.</li>
<li>Repeat steps 2 and 3 in Python.</li>
</ol>
<p>I'm thinking about going with Eclipse and GTK+ / X11. Any thoughts on IDE's and GUI toolkits? Preferably open source, and definitely free. And what do you think about the 5 steps?</p>
<p>Any help would be much appreciated - thanks in advance!</p>
| 4 | 2009-06-21T14:45:46Z | 1,024,205 | <p><a href="http://www.netbeans.org/features/cpp/index.html" rel="nofollow">NetBeans</a> is another choice. Although both Python and C++ support are rather new for it. The Python works find, but I haven't tried the C support.</p>
| 0 | 2009-06-21T15:57:02Z | [
"c++",
"python",
"osx",
"ide"
] |
How to stop Python parse_qs from parsing single values into lists? | 1,024,143 | <p>In python 2.6, the following code:</p>
<pre><code>import urlparse
qsdata = "test=test&test2=test2&test2=test3"
qs = urlparse.parse_qs(qsdata)
print qs
</code></pre>
<p>Gives the following output:</p>
<pre><code>{'test': ['test'], 'test2': ['test2', 'test3']}
</code></pre>
<p>Which means that even though there is only one value for test, it is still being parsed into a list. Is there a way to ensure that if there's only one value, it is not parsed into a list, so that the result would look like this?</p>
<pre><code>{'test': 'test', 'test2': ['test2', 'test3']}
</code></pre>
| 22 | 2009-06-21T15:23:35Z | 1,024,164 | <p>You could fix it afterwards...</p>
<pre><code>import urlparse
qsdata = "test=test&test2=test2&test2=test3"
qs = dict( (k, v if len(v)>1 else v[0] )
for k, v in urlparse.parse_qs(qsdata).iteritems() )
print qs
</code></pre>
<p>However, I don't think <em>I</em> would want this. If a parameter that is normally a list happens to arrive with only one item set, then I would have a string instead of the list of strings I normally receive.</p>
| 21 | 2009-06-21T15:35:11Z | [
"python",
"python-2.6"
] |
How to stop Python parse_qs from parsing single values into lists? | 1,024,143 | <p>In python 2.6, the following code:</p>
<pre><code>import urlparse
qsdata = "test=test&test2=test2&test2=test3"
qs = urlparse.parse_qs(qsdata)
print qs
</code></pre>
<p>Gives the following output:</p>
<pre><code>{'test': ['test'], 'test2': ['test2', 'test3']}
</code></pre>
<p>Which means that even though there is only one value for test, it is still being parsed into a list. Is there a way to ensure that if there's only one value, it is not parsed into a list, so that the result would look like this?</p>
<pre><code>{'test': 'test', 'test2': ['test2', 'test3']}
</code></pre>
| 22 | 2009-06-21T15:23:35Z | 8,239,167 | <p>A sidenote for someone just wanting a simple dictionary and never needing multiple values with the same key, try:</p>
<pre><code>dict(urlparse.parse_qsl('foo=bar&baz=qux'))
</code></pre>
<p>This will give you a nice <code>{'foo': 'bar', 'baz': 'qux'}</code>. Please note that if there <em>are</em> multiple values for the same key, you'll only get the last one.</p>
| 72 | 2011-11-23T08:35:34Z | [
"python",
"python-2.6"
] |
Looping Fget with fsockopen in PHP 5.x | 1,024,370 | <p>I have a Python Server finally working and responding to multiple command's with the output's, however I'm now having problem's with PHP receiving the full output. I have tried commands such as fgets, fread, the only command that seems to work is "fgets".</p>
<p>However this only recieve's on line of data, I then created a while statement shown bellow:</p>
<pre><code> while (!feof($handle)) {
$buffer = fgets($handle, 4096);
echo $buffer;
}
</code></pre>
<p>However it seems the Python server is not sending a Feof at the end of the output so the php page times out and does not display anything. Like I said above, just running echo fgets($handle), work's fine, and output's one line, running the command again under neither will display the next line e.t.c</p>
<p>I have attached the important part of my Python Script bellow:</p>
<pre><code>s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("", port))
s.listen(5)
print "OK."
print " Listening on port:", port
import subprocess
while 1:
con, addr = s.accept()
while True:
datagram = con.recv(1024)
if not datagram:
break
print "Rx Cmd:", datagram
print "Launch:", datagram
process = subprocess.Popen(datagram+" &", shell=True, stdout=subprocess.PIPE)
stdout, stderr = process.communicate()
con.send(stdout)
con.close()
s.close()
</code></pre>
<p>I have also attached the full PHP script:</p>
<pre><code><?php
$handle = fsockopen("tcp://xxx.xxx.xxx.xxx",12345);
fwrite($handle,"ls");
echo fgets($handle);
fclose($handle);
?>
</code></pre>
<p>Thanks,
Ashley</p>
| 3 | 2009-06-21T17:31:28Z | 1,024,459 | <p>I believe you need to fix your server code a bit. I have removed the inner while loop. The problem with your code was that the server never closed the connection, so <code>feof</code> never returned true.</p>
<p>I also removed the <code>+ " &"</code> bit. To get the output, you need to wait until the process ends anyway. And I am not sure how the shell would handle the <code>&</code> in this case.</p>
<pre><code>s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("", port))
s.listen(5)
print "OK."
print " Listening on port:", port
import subprocess
try:
while 1:
con, addr = s.accept()
try:
datagram = con.recv(1024)
if not datagram:
continue
print "Rx Cmd:", datagram
print "Launch:", datagram
process = subprocess.Popen(datagram, shell=True, stdout=subprocess.PIPE)
stdout, stderr = process.communicate()
con.send(stdout)
finally:
print "closing connection"
con.close()
except KeyboardInterrupt:
pass
finally:
print "closing socket"
s.close()
</code></pre>
<p>BTW, you need to use the while-loop in your php script. <code>fgets</code> returns until a single line only.</p>
| 1 | 2009-06-21T18:19:09Z | [
"php",
"python",
"sockets",
"tcp",
"fgets"
] |
Can python doctest ignore some output lines? | 1,024,411 | <p>I'd like to write a doctest like this:</p>
<pre><code>"""
>>> print a.string()
foo : a
bar : b
date : <I don't care about the date output>
baz : c
"""
</code></pre>
<p>Is there any way to do this? I think it would make more sense to switch to unittest, but I'm curious whether it's possible to specify a range of output that shouldn't be matched for the test in doctest.</p>
<p>Thanks!</p>
| 18 | 2009-06-21T17:54:11Z | 1,024,426 | <p>With <code>doctest.ELLIPSIS</code>, you can use <code>...</code> to mean "match any string here". You can set <code>doctest</code> options with a doctest directive, to make it active for just one test case: one example in the <a href="http://docs.python.org/library/doctest.html">online docs</a> is:</p>
<pre><code>>>> print range(20) # doctest:+ELLIPSIS
[0, 1, ..., 18, 19]
</code></pre>
<p>If you want a doctest option to be active throughout, you can pass it as the <code>optionflags=</code> argument to whatever doctest functions you use, e.g. <code>doctest.testfile</code>. (You can pass multiple option flags there by using the <code>|</code> operator to bit-or them).</p>
| 30 | 2009-06-21T18:03:19Z | [
"python",
"doctest"
] |
Can python doctest ignore some output lines? | 1,024,411 | <p>I'd like to write a doctest like this:</p>
<pre><code>"""
>>> print a.string()
foo : a
bar : b
date : <I don't care about the date output>
baz : c
"""
</code></pre>
<p>Is there any way to do this? I think it would make more sense to switch to unittest, but I'm curious whether it's possible to specify a range of output that shouldn't be matched for the test in doctest.</p>
<p>Thanks!</p>
| 18 | 2009-06-21T17:54:11Z | 9,399,878 | <p>Ignoring the whole line is bit tricky though. Here:</p>
<pre><code>"""
>>> do_your_thing() #doctest:+ELLIPSIS
...
"""
</code></pre>
<p>The triple dot will be interpreted as line continuation, and cause a syntax error.</p>
<p>If you want to ignore the whole line, you'll need something like:</p>
<pre><code>"""
>>> sys.stdout.write('skip from here '); do_your_thing() #doctest:+ELLIPSIS
skip from here ...
"""
</code></pre>
| 4 | 2012-02-22T17:27:29Z | [
"python",
"doctest"
] |
Can python doctest ignore some output lines? | 1,024,411 | <p>I'd like to write a doctest like this:</p>
<pre><code>"""
>>> print a.string()
foo : a
bar : b
date : <I don't care about the date output>
baz : c
"""
</code></pre>
<p>Is there any way to do this? I think it would make more sense to switch to unittest, but I'm curious whether it's possible to specify a range of output that shouldn't be matched for the test in doctest.</p>
<p>Thanks!</p>
| 18 | 2009-06-21T17:54:11Z | 9,400,829 | <p>Responding to questions about "how can we ignore the whole line": yes, the fact that "..." also looks like a continuation like makes it hard to ignore the entire output. You can use "#doctest: +SKIP" if you just want to skip the example entirely, but that won't work if you are relying on its side-effects. If you <em>really</em> need to do this, I suppose you could monkey-patch the doctest module itself, though I wouldn't particularly recommend it:</p>
<pre><code>>>> import doctest
>>> doctest.ELLIPSIS_MARKER = '-etc-'
>>> print 12 # doctest: +ELLIPSIS
-etc-
</code></pre>
<p>(this test passes.)</p>
<p>Or you could temporarily suppress stdout and/or stderr:</p>
<pre><code>>>> # Suppress stdout
>>> import sys
>>> class DevNull:
... def noop(*args, **kwargs): pass
... close = write = flush = writelines = noop
>>> sys.stdout = DevNull()
>>> # Run a test and ignore output (but we need its side effects)
>>> print 12 # NOTE: stdout is suppressed!
>>> # Restore stdout
>>> sys.stdout = sys.__stdout__
</code></pre>
<p>(this test also passes.)</p>
| 5 | 2012-02-22T18:33:27Z | [
"python",
"doctest"
] |
Can python doctest ignore some output lines? | 1,024,411 | <p>I'd like to write a doctest like this:</p>
<pre><code>"""
>>> print a.string()
foo : a
bar : b
date : <I don't care about the date output>
baz : c
"""
</code></pre>
<p>Is there any way to do this? I think it would make more sense to switch to unittest, but I'm curious whether it's possible to specify a range of output that shouldn't be matched for the test in doctest.</p>
<p>Thanks!</p>
| 18 | 2009-06-21T17:54:11Z | 12,227,048 | <p><a href="http://stackoverflow.com/questions/5812833/can-i-have-an-ellipsis-at-the-beginning-of-the-line-in-a-python-doctest">Can I have an ellipsis at the beginning of the line in a Python doctest?</a> explains how to create a custom output checker that uses an additional string as an ellipsis. This would let you write the following, while still used '...' elsewhere.</p>
<pre><code>def foo():
"""
>>> foo() # doctest: +ELLIPSIS
[...] world
"""
print "hello world"
</code></pre>
| 0 | 2012-09-01T10:39:45Z | [
"python",
"doctest"
] |
Can python doctest ignore some output lines? | 1,024,411 | <p>I'd like to write a doctest like this:</p>
<pre><code>"""
>>> print a.string()
foo : a
bar : b
date : <I don't care about the date output>
baz : c
"""
</code></pre>
<p>Is there any way to do this? I think it would make more sense to switch to unittest, but I'm curious whether it's possible to specify a range of output that shouldn't be matched for the test in doctest.</p>
<p>Thanks!</p>
| 18 | 2009-06-21T17:54:11Z | 22,537,703 | <p>I found it easier to simply assign the unneeded return values to a variable:</p>
<pre><code>>>> _ = do_something()
>>> check_something()
True
</code></pre>
| 2 | 2014-03-20T15:29:32Z | [
"python",
"doctest"
] |
Can python doctest ignore some output lines? | 1,024,411 | <p>I'd like to write a doctest like this:</p>
<pre><code>"""
>>> print a.string()
foo : a
bar : b
date : <I don't care about the date output>
baz : c
"""
</code></pre>
<p>Is there any way to do this? I think it would make more sense to switch to unittest, but I'm curious whether it's possible to specify a range of output that shouldn't be matched for the test in doctest.</p>
<p>Thanks!</p>
| 18 | 2009-06-21T17:54:11Z | 33,400,983 | <p>You can write tuples before and after your function (hack inspired by answer of Mark Horvath):</p>
<pre><code>def foo():
"""
>>> ();foo();() # doctest: +ELLIPSIS
(...)
"""
print "Hello world"
return "Hello world"
</code></pre>
| 1 | 2015-10-28T20:27:08Z | [
"python",
"doctest"
] |
How to fix python indentation | 1,024,435 | <p>I have some python code that have inconsistent indentation, there is a lot of mixture of tabs and spaces to make the matter even worse even space indentation is not preserved.</p>
<p>The code works as expected but it's difficult to maintain.</p>
<p>How can I fix the indentation (like "html tidy" but for python) without breaking the code?</p>
| 185 | 2009-06-21T18:10:18Z | 1,024,448 | <p>Using vim, it shouldn't be more involved than hitting Esc, and then typing..</p>
<pre><code>:%s/\t/ /g
</code></pre>
<p>..on the file you want to change. That will convert all tabs to 4 spaces. If you have inconsistent spacing as well, then that will be more difficult.</p>
| 6 | 2009-06-21T18:14:12Z | [
"python"
] |
How to fix python indentation | 1,024,435 | <p>I have some python code that have inconsistent indentation, there is a lot of mixture of tabs and spaces to make the matter even worse even space indentation is not preserved.</p>
<p>The code works as expected but it's difficult to maintain.</p>
<p>How can I fix the indentation (like "html tidy" but for python) without breaking the code?</p>
| 185 | 2009-06-21T18:10:18Z | 1,024,460 | <p>Try emacs. It has good support for indentation needed in Python. Please check this link <a href="http://python.about.com/b/2007/09/24/emacs-tips-for-python-programmers.htm" rel="nofollow">http://python.about.com/b/2007/09/24/emacs-tips-for-python-programmers.htm</a></p>
<p>cheers</p>
| 2 | 2009-06-21T18:19:32Z | [
"python"
] |
How to fix python indentation | 1,024,435 | <p>I have some python code that have inconsistent indentation, there is a lot of mixture of tabs and spaces to make the matter even worse even space indentation is not preserved.</p>
<p>The code works as expected but it's difficult to maintain.</p>
<p>How can I fix the indentation (like "html tidy" but for python) without breaking the code?</p>
| 185 | 2009-06-21T18:10:18Z | 1,024,463 | <p>If you're using <a href="http://www.vim.org/">Vim</a>, see <a href="http://vimdoc.sourceforge.net/htmldoc/change.html#:retab"><code>:h retab</code></a>.</p>
<pre> *:ret* *:retab*
:[range]ret[ab][!] [new_tabstop]
Replace all sequences of white-space containing a
<Tab> with new strings of white-space using the new
tabstop value given. If you do not specify a new
tabstop size or it is zero, Vim uses the current value
of 'tabstop'.
The current value of 'tabstop' is always used to
compute the width of existing tabs.
With !, Vim also replaces strings of only normal
spaces with tabs where appropriate.
With 'expandtab' on, Vim replaces all tabs with the
appropriate number of spaces.
This command sets 'tabstop' to the new value given,
and if performed on the whole file, which is default,
should not make any visible change.
Careful: This command modifies any <Tab> characters
inside of strings in a C program. Use "\t" to avoid
this (that's a good habit anyway).
":retab!" may also change a sequence of spaces by
<Tab> characters, which can mess up a printf().
{not in Vi}
Not available when |+ex_extra| feature was disabled at
compile time.
</pre>
<p>For example, if you simply type</p>
<pre>
:ret
</pre>
<p>all your tabs will be expanded into spaces.</p>
<p>You may want to</p>
<pre>
:se et " shorthand for :set expandtab
</pre>
<p>to make sure that any new lines will not use literal tabs.</p>
<p><hr /></p>
<p>If you're not using Vim,</p>
<pre>
perl -i.bak -pe "s/\t/' 'x(8-pos()%8)/eg" file.py
</pre>
<p>will replace tabs with spaces, assuming tab stops every 8 characters, in <code>file.py</code> (with the original going to <code>file.py.bak</code>, just in case). Replace the 8s with 4s if your tab stops are every 4 spaces instead.</p>
| 37 | 2009-06-21T18:20:38Z | [
"python"
] |
How to fix python indentation | 1,024,435 | <p>I have some python code that have inconsistent indentation, there is a lot of mixture of tabs and spaces to make the matter even worse even space indentation is not preserved.</p>
<p>The code works as expected but it's difficult to maintain.</p>
<p>How can I fix the indentation (like "html tidy" but for python) without breaking the code?</p>
| 185 | 2009-06-21T18:10:18Z | 1,024,489 | <p>Use the <code>reindent.py</code> script that you find in the <code>Tools/scripts/</code> directory of your Python installation:</p>
<blockquote>
<p>Change Python (.py) files to use
4-space indents and no hard tab
characters. Also trim excess spaces
and tabs from ends of lines, and
remove empty lines at the end of
files. Also ensure the last line ends
with a newline.</p>
</blockquote>
<p>Have a look at that script for detailed usage instructions.</p>
| 235 | 2009-06-21T18:36:59Z | [
"python"
] |
How to fix python indentation | 1,024,435 | <p>I have some python code that have inconsistent indentation, there is a lot of mixture of tabs and spaces to make the matter even worse even space indentation is not preserved.</p>
<p>The code works as expected but it's difficult to maintain.</p>
<p>How can I fix the indentation (like "html tidy" but for python) without breaking the code?</p>
| 185 | 2009-06-21T18:10:18Z | 2,260,185 | <p>There is also PythonTidy (since you said you like HTMLTidy)
It can be found here: <a href="http://pypi.python.org/pypi/PythonTidy/1.16">http://pypi.python.org/pypi/PythonTidy/1.16</a>
It can do a lot more than just clean up tabs though. If you like that type of thing it's worth a look.</p>
| 7 | 2010-02-14T04:55:29Z | [
"python"
] |
How to fix python indentation | 1,024,435 | <p>I have some python code that have inconsistent indentation, there is a lot of mixture of tabs and spaces to make the matter even worse even space indentation is not preserved.</p>
<p>The code works as expected but it's difficult to maintain.</p>
<p>How can I fix the indentation (like "html tidy" but for python) without breaking the code?</p>
| 185 | 2009-06-21T18:10:18Z | 3,539,318 | <p>If you're lazy (like me), you can also download a trial version of Wingware Python IDE, which has an auto-fix tool for messed up indentation. It works pretty well.
<a href="http://www.wingware.com/">http://www.wingware.com/</a></p>
| 5 | 2010-08-21T22:35:51Z | [
"python"
] |
How to fix python indentation | 1,024,435 | <p>I have some python code that have inconsistent indentation, there is a lot of mixture of tabs and spaces to make the matter even worse even space indentation is not preserved.</p>
<p>The code works as expected but it's difficult to maintain.</p>
<p>How can I fix the indentation (like "html tidy" but for python) without breaking the code?</p>
| 185 | 2009-06-21T18:10:18Z | 15,983,399 | <p>I have a simple solution for this problem. You can first type ":retab" and then ":retab!", then everything would be fine</p>
| 0 | 2013-04-13T01:59:44Z | [
"python"
] |
How to fix python indentation | 1,024,435 | <p>I have some python code that have inconsistent indentation, there is a lot of mixture of tabs and spaces to make the matter even worse even space indentation is not preserved.</p>
<p>The code works as expected but it's difficult to maintain.</p>
<p>How can I fix the indentation (like "html tidy" but for python) without breaking the code?</p>
| 185 | 2009-06-21T18:10:18Z | 16,749,450 | <p>try Idle, and use ALT+X to find indentation</p>
| 0 | 2013-05-25T12:14:22Z | [
"python"
] |
How to fix python indentation | 1,024,435 | <p>I have some python code that have inconsistent indentation, there is a lot of mixture of tabs and spaces to make the matter even worse even space indentation is not preserved.</p>
<p>The code works as expected but it's difficult to maintain.</p>
<p>How can I fix the indentation (like "html tidy" but for python) without breaking the code?</p>
| 185 | 2009-06-21T18:10:18Z | 16,749,652 | <p>On most UNIX-like systems, you can also run:</p>
<pre><code>expand -t4 oldfilename.py > newfilename.py
</code></pre>
<p>from the command line, changing the number if you want to replace tabs with a number of spaces other than 4. You can easily write a shell script to do this with a bunch of files at once, retaining the original file names.</p>
| 0 | 2013-05-25T12:40:05Z | [
"python"
] |
How to fix python indentation | 1,024,435 | <p>I have some python code that have inconsistent indentation, there is a lot of mixture of tabs and spaces to make the matter even worse even space indentation is not preserved.</p>
<p>The code works as expected but it's difficult to maintain.</p>
<p>How can I fix the indentation (like "html tidy" but for python) without breaking the code?</p>
| 185 | 2009-06-21T18:10:18Z | 26,643,477 | <p>I would reach for <a href="https://pypi.python.org/pypi/autopep8">autopep8</a> to do this:</p>
<pre class="lang-sh prettyprint-override"><code>$ # see what changes it would make
$ autopep8 path/to/file.py --select=E101,E121 --diff
$ # make these changes
$ autopep8 path/to/file.py --select=E101,E121 --in-place
</code></pre>
<p><em>Note: <a href="https://github.com/hhatto/autopep8#features">E101 and E121</a> are pep8 indentation (I think you can simply pass <code>--select=E1</code> to fix all indentation related issues - those starting with E1).</em></p>
<p>You can apply this to your entire project using recursive flag:</p>
<pre class="lang-sh prettyprint-override"><code>$ autopep8 package_dir --recursive --select=E101,E121 --in-place
</code></pre>
<p><em>See also <a href="http://stackoverflow.com/a/14328499/1240268">Tool to convert Python code to be PEP8 compliant</a>.</em></p>
| 21 | 2014-10-30T01:19:35Z | [
"python"
] |
How to fix python indentation | 1,024,435 | <p>I have some python code that have inconsistent indentation, there is a lot of mixture of tabs and spaces to make the matter even worse even space indentation is not preserved.</p>
<p>The code works as expected but it's difficult to maintain.</p>
<p>How can I fix the indentation (like "html tidy" but for python) without breaking the code?</p>
| 185 | 2009-06-21T18:10:18Z | 29,636,895 | <p>Use <a href="https://pypi.python.org/pypi/autopep8/1.1.1" rel="nofollow">autopep8</a></p>
<p>autopep8 automatically formats Python code to conform to the PEP 8
nullstyle guide. It uses the pep8 utility to determine what parts of the
nullcode needs to be formatted. autopep8 is capable of fixing most of the
nullformatting issues that can be reported by pep8.</p>
<pre><code>pip install autopep8
autopep8 script.py # print only
autopep8 -i script.py # write file
</code></pre>
| 4 | 2015-04-14T20:33:02Z | [
"python"
] |
How to fix python indentation | 1,024,435 | <p>I have some python code that have inconsistent indentation, there is a lot of mixture of tabs and spaces to make the matter even worse even space indentation is not preserved.</p>
<p>The code works as expected but it's difficult to maintain.</p>
<p>How can I fix the indentation (like "html tidy" but for python) without breaking the code?</p>
| 185 | 2009-06-21T18:10:18Z | 33,320,387 | <p>The reindent script did not work for me, due to some missing module. Anyways, I found this <code>sed</code> command which does the job perfect for me:</p>
<pre><code>sed -r 's/^([ ]*)([^ ])/\1\1\2/' file.py
</code></pre>
| 3 | 2015-10-24T16:17:15Z | [
"python"
] |
Python newbie: What does this code do? | 1,024,437 | <p>This is a snippet from Google AppEngine tutorial.</p>
<pre><code>application = webapp.WSGIApplication([('/', MainPage)], debug=True)
</code></pre>
<p>I'm not quite sure what <strong><code>debug=True</code></strong> does inside the constructor call.
Does it create a local variable with name <code>debug</code>, assign <code>True</code> to it, and pass it to constructor, or is this a way to set a class instance member variable's value in constructor?</p>
| 1 | 2009-06-21T18:10:57Z | 1,024,442 | <p>It's using named arguments. See <a href="http://diveintopython.net/power_of_introspection/optional_arguments.html" rel="nofollow">Using Optional and Named Arguments</a>.</p>
| 3 | 2009-06-21T18:12:54Z | [
"python"
] |
Python newbie: What does this code do? | 1,024,437 | <p>This is a snippet from Google AppEngine tutorial.</p>
<pre><code>application = webapp.WSGIApplication([('/', MainPage)], debug=True)
</code></pre>
<p>I'm not quite sure what <strong><code>debug=True</code></strong> does inside the constructor call.
Does it create a local variable with name <code>debug</code>, assign <code>True</code> to it, and pass it to constructor, or is this a way to set a class instance member variable's value in constructor?</p>
| 1 | 2009-06-21T18:10:57Z | 1,024,444 | <p>Neither -- rather, <code>webapp.WSGIApplication</code> takes an optional argument named <code>debug</code>, and this code is passing the value <code>True</code> for that parameter.</p>
<p>The reference page for <code>WSGIApplication</code> is <a href="http://code.google.com/appengine/docs/python/tools/webapp/wsgiapplicationclass.html" rel="nofollow">here</a> and it clearly shows the optional <code>debug</code> argument and the fact that it defaults to <code>False</code> unless explicitly passed in.</p>
<p>As the page further makes clear, passing <code>debug</code> as <code>True</code> means that helpful debugging information is shown to the browser if and when an exception occurs while handling the request.</p>
<p>How exactly that effect is obtained (in particular, whether it implies the existence of an attribute on the instance of <code>WSGIApplication</code>, or how that hypothetical attribute might be named) is an internal, undocumented implementation detail, which we're not supposed to worry about (of course, you can study the sources of <code>WSGIApplication</code> in the SDK if you <em>do</em> worry, or just want to learn more about one possible implementation of these specs!-).</p>
| 4 | 2009-06-21T18:13:42Z | [
"python"
] |
Python newbie: What does this code do? | 1,024,437 | <p>This is a snippet from Google AppEngine tutorial.</p>
<pre><code>application = webapp.WSGIApplication([('/', MainPage)], debug=True)
</code></pre>
<p>I'm not quite sure what <strong><code>debug=True</code></strong> does inside the constructor call.
Does it create a local variable with name <code>debug</code>, assign <code>True</code> to it, and pass it to constructor, or is this a way to set a class instance member variable's value in constructor?</p>
| 1 | 2009-06-21T18:10:57Z | 1,024,449 | <p>Python functions accept keyword arguments. If you define a function like so:</p>
<pre><code>def my_func(a, b='abc', c='def'):
print a, b, c
</code></pre>
<p>You can call it like this:</p>
<pre><code>my_func('hello', c='world')
</code></pre>
<p>And the result will be:</p>
<pre><code>hello abc world
</code></pre>
<p>You can also support dynamic keyword arguments, using special syntax:</p>
<pre><code>def my_other_func(a, *b, **c):
print a, b, c
</code></pre>
<ul>
<li><code>*b</code> means that the <code>b</code> variable will take all non-named arguments after <code>a</code>, as a <code>tuple</code> object.</li>
<li><code>**c</code> means that the <code>c</code> variable will take all named arguments, as a <code>dict</code> object.</li>
</ul>
<p>If you call the function like this:</p>
<pre><code>my_other_func('hello', 'world', 'what a', state='fine', what='day')
</code></pre>
<p>You will get:</p>
<pre><code>hello ('world', 'what a') {'state': 'fine', 'what': 'day'}
</code></pre>
| 11 | 2009-06-21T18:14:24Z | [
"python"
] |
Perl's AUTOLOAD in Python (__getattr__ on a module) | 1,024,455 | <p>In the past I've used perl's AUTOLOAD facility for implementing lazy loading of symbols into a namespace, and wanted the same functionality in python. </p>
<p>Traditionally the closest you appear to be able to get is to use a class and a <code>__getattr__</code> class to achieve this sort of thing. However I've also tried rummaging around in <code>sys.modules</code>, and come up with this:</p>
<pre><code># mymod.py
def greet(greeting="Hello World"):
print greeting
class AutoLoad(object):
def __init__(self, mod_name):
super(autoload, self).__init__()
self.wrapped_name = mod_name
self.wrapped = sys.modules[mod_name]
def __getattr__(self, name):
try:
return getattr(self.wrapped, name)
except AttributeError:
def f():
greet(name + " " + self.wrapped_name)
return f
if __name__ != "__main__":
import sys
sys.modules[__name__] = AutoLoad(__name__)
</code></pre>
<p>This does work the way I'd like from a user perspective:</p>
<pre><code>~> python
Python 2.5.1 (r251:54863, Jan 10 2008, 18:01:57)
[GCC 4.2.1 (SUSE Linux)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import mymod
>>> mymod.hello()
hello mymod
>>> from mymod import Hello_World
>>> Hello_World()
Hello_World mymod
</code></pre>
<p>But it strikes me - is there a standard approach that people tend to use for autoloading in python?</p>
<p>Secondly, a question for experienced python developers really is "does this strike you as good or bad practice"? I'm a reasonably experienced python developer, and it strikes me as really useful, but it strikes me as borderline and interested in whether this can be viewed as good practice, bad practice or similar.</p>
| 14 | 2009-06-21T18:17:47Z | 1,024,468 | <p>"Lazy imports" could be built on top of the "new import hooks" specified in <a href="http://www.python.org/dev/peps/pep-0302/">PEP 302</a>, and now fully implemented. PEP 369 used to cover "lazy imports" as well as post-import hooks, but has since been simplified and now only covers post-import hooks; still, you might be interested in the <a href="http://permalink.gmane.org/gmane.comp.python.devel/90949">original draft</a>.</p>
<p>A good implementation of "lazy imports" via the <code>meta_path</code> hook can be found in <a href="http://code.activestate.com/recipes/473888/">this recipe</a>.</p>
| 10 | 2009-06-21T18:24:23Z | [
"python",
"module",
"autoload",
"getattr"
] |
Perl's AUTOLOAD in Python (__getattr__ on a module) | 1,024,455 | <p>In the past I've used perl's AUTOLOAD facility for implementing lazy loading of symbols into a namespace, and wanted the same functionality in python. </p>
<p>Traditionally the closest you appear to be able to get is to use a class and a <code>__getattr__</code> class to achieve this sort of thing. However I've also tried rummaging around in <code>sys.modules</code>, and come up with this:</p>
<pre><code># mymod.py
def greet(greeting="Hello World"):
print greeting
class AutoLoad(object):
def __init__(self, mod_name):
super(autoload, self).__init__()
self.wrapped_name = mod_name
self.wrapped = sys.modules[mod_name]
def __getattr__(self, name):
try:
return getattr(self.wrapped, name)
except AttributeError:
def f():
greet(name + " " + self.wrapped_name)
return f
if __name__ != "__main__":
import sys
sys.modules[__name__] = AutoLoad(__name__)
</code></pre>
<p>This does work the way I'd like from a user perspective:</p>
<pre><code>~> python
Python 2.5.1 (r251:54863, Jan 10 2008, 18:01:57)
[GCC 4.2.1 (SUSE Linux)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import mymod
>>> mymod.hello()
hello mymod
>>> from mymod import Hello_World
>>> Hello_World()
Hello_World mymod
</code></pre>
<p>But it strikes me - is there a standard approach that people tend to use for autoloading in python?</p>
<p>Secondly, a question for experienced python developers really is "does this strike you as good or bad practice"? I'm a reasonably experienced python developer, and it strikes me as really useful, but it strikes me as borderline and interested in whether this can be viewed as good practice, bad practice or similar.</p>
| 14 | 2009-06-21T18:17:47Z | 1,026,612 | <p>No, I don't think that's useful.</p>
<p>Why create a function on the fly for <strong>every</strong> attribute you're trying to get from the module? Seems confusing to me. It appears that new functions are being created by magic so one has to look deep into the implementation to understand what is going on. And all that for no syntactical benefits.</p>
<p>And even if you had a good reason to do that, why do it with a module? Why register your class instance in <code>sys.modules</code>? I think making things appear what they aren't is frowned upon in python.</p>
<p>Unless you are obfuscating code on purpose, I don't see why one would do all that.</p>
| -1 | 2009-06-22T11:18:48Z | [
"python",
"module",
"autoload",
"getattr"
] |
Resolving a relative path from py:match in a genshi template | 1,024,475 | <pre><code><py:match path="foo">
<?python
import os
href = select('@href').render()
SOMEWHERE = ... # what file contained the foo tag?
path = os.path.abspath(os.path.join(os.path.dirname(SOMEWHERE), href)
f = file(path,'r')
# (do something interesting with f)
?>
</py:match>
...
<foo href="../path/relative/to/this/template/abcd.xyz"/>
</code></pre>
<p>What should go as "somewhere" above? I want that <code>href</code> attribute to be relative to the file with the <code>foo</code> tag in it, like <code>href</code> attributes on other tags.</p>
<p>Alternatively, what file contained the py:match block? This is less good because it may be in a different directory from the file with the <code>foo</code> tag.</p>
<p>Even less good: I could supply the path of the file I'm rendering as a context argument from outside Genshi, but that might be in a different directory from both of the above.</p>
| 0 | 2009-06-21T18:28:47Z | 2,875,664 | <p>You need to make sure that the driver program (i.e., the Python program that parses the input file) runs in the directory of the file containing the <code>foo</code> tag. Otherwise, you need to pass down the relative path (i.e., how to get from the directory in which the reader runs to the directory of the file being read) as a context argument to your Python code and add it to the <code>os.path.join</code> command.</p>
<p>With this setup (and using Genshi 0.6 installed on MacOS X 10.6.3 via the Fink package genshi-py26) the command <code>os.getcwd()</code> returns the current working directory of the file containing the <code>foo</code> tag.</p>
<p>For such complicated path constructs I also strongly recommend to use <code>path=os.path.normpath(path)</code>, since you may not want such things to leak in your resulting HTML code.</p>
| 1 | 2010-05-20T16:09:39Z | [
"python",
"relative-path",
"genshi"
] |
How to test a Python script with an input file filled with testcases? | 1,024,529 | <p>I'm participating in online judge contests and I want to test my code with a .in file full of testcases to time my algorithm. How can I get my script to take input from this .in file?</p>
| 1 | 2009-06-21T18:57:59Z | 1,024,544 | <p><a href="http://pyunit.sourceforge.net/" rel="nofollow">PyUnit</a> "the standard unit testing framework for Python" might be what you are looking for.</p>
<p><hr /></p>
<p>Doing a small script that does something like this:</p>
<pre><code>#!/usr/bin/env python
import sys
def main():
in_file = open('path_to_file')
for line in in_file:
sys.stdout.write(line)
if __name__ == "__main__":
main()
</code></pre>
<p>And run as</p>
<pre><code>this_script.py | your_app.py
</code></pre>
| 1 | 2009-06-21T19:06:44Z | [
"python",
"input"
] |
How to test a Python script with an input file filled with testcases? | 1,024,529 | <p>I'm participating in online judge contests and I want to test my code with a .in file full of testcases to time my algorithm. How can I get my script to take input from this .in file?</p>
| 1 | 2009-06-21T18:57:59Z | 1,024,592 | <p>So the script normally takes test cases from stdin, and now you want to test using test cases from a file?</p>
<p>If that is the case, use the <code><</code> redirection operation on the cmd line:</p>
<pre><code>my_script < testcases.in
</code></pre>
| 6 | 2009-06-21T19:31:23Z | [
"python",
"input"
] |
How to test a Python script with an input file filled with testcases? | 1,024,529 | <p>I'm participating in online judge contests and I want to test my code with a .in file full of testcases to time my algorithm. How can I get my script to take input from this .in file?</p>
| 1 | 2009-06-21T18:57:59Z | 1,024,633 | <p>Read from file(s) and/or stdin:</p>
<pre><code>import fileinput
for line in fileinput.input():
process(line)
</code></pre>
| 2 | 2009-06-21T19:57:07Z | [
"python",
"input"
] |
How to test a Python script with an input file filled with testcases? | 1,024,529 | <p>I'm participating in online judge contests and I want to test my code with a .in file full of testcases to time my algorithm. How can I get my script to take input from this .in file?</p>
| 1 | 2009-06-21T18:57:59Z | 1,024,718 | <p>You can do this in a separate file.</p>
<p><code>testmyscript.py</code></p>
<pre><code>import sys
someFile= open( "somefile.in", "r" )
sys.stdin= someFile
execfile( "yourscript.py" )
</code></pre>
| 0 | 2009-06-21T20:48:35Z | [
"python",
"input"
] |
Django - alternative to subclassing User? | 1,024,684 | <p>I am using the standard User model (django.contrib.auth) which comes with Django. I have made some of my own models in a Django application and created a relationship between like this:</p>
<pre><code>from django.db import models
from django.contrib.auth.models import User
class GroupMembership(models.Model):
user = models.ForeignKey(User, null = True, blank = True, related_name='memberships')
#other irrelevant fields removed from example
</code></pre>
<p>So I can now do this to get all of a user's current memberships:</p>
<pre><code>user.memberships.all()
</code></pre>
<p>However, I want to be able to do a more complex query, like this:</p>
<pre><code>user.memberships.all().select_related('group__name')
</code></pre>
<p>This works fine but I want to fetch this data in a template. It seems silly to try to put this sort of logic inside a template (and I can't seem to make it work anyway), so I want to create a better way of doing it. I could sub-class User, but that doesn't seem like a great solution - I may in future want to move my application into other Django sites, and presumably if there was any another application that sub-classed User I wouldn't be able to get it to work.</p>
<p>Is the best to create a method inside <code>GroupMembership</code> called something like <code>get_by_user(user)</code>? Would I be able to call this from a template?</p>
<p>I would appreciate any advice anybody can give on structuring this - sorry if this is a bit long/vague.</p>
| 0 | 2009-06-21T20:27:52Z | 1,024,765 | <p>First, calling <code>select_related</code> and passing arguments, doesn't do anything. It's a hint that cache should be populated.</p>
<p>You would never call <code>select_related</code> in a template, only a view function. And only when you knew you needed all those related objects for other processing.</p>
<p>"Is the best to create a method inside GroupMembership called something like get_by_user(user)?"</p>
<p>You have this. I'm not sure what's wrong with it.</p>
<pre><code> GroupMembership.objects.filter( user="someUser" )
</code></pre>
<p>"Would I be able to call this from a template?"</p>
<p>No. That's what view functions are for.</p>
<pre><code> groups = GroupMembership.objects.filter( user="someUser" )
</code></pre>
<p>Then you provide the <code>groups</code> object to the template for rendering.</p>
<p><hr /></p>
<p><strong>Edit</strong></p>
<p>This is one line of code; it doesn't seem that onerous a burden to include this in all your view functions.</p>
<p>If you want this to appear on every page, you have lots of choices that do not involve repeating this line of code..</p>
<ol>
<li><p>A view function can call another function.</p></li>
<li><p>You might want to try callable objects instead of simple functions; these can subclass a common callable object that fills in this information.</p></li>
<li><p>You can add a template context processor to put this into the context of all templates that are rendered.</p></li>
<li><p>You could write your own decorator to assure that this is done in every view function that has the decorator.</p></li>
</ol>
| 3 | 2009-06-21T21:12:30Z | [
"python",
"django"
] |
Add key to a dictionary in Python? | 1,024,847 | <p>Is it possible to add a key to a Python dictionary after it has been created? It doesn't seem to have an <code>.add()</code> method.</p>
| 1,201 | 2009-06-21T22:07:39Z | 1,024,850 | <pre><code>dictionary[key] = value
</code></pre>
| 60 | 2009-06-21T22:08:57Z | [
"python",
"dictionary"
] |
Add key to a dictionary in Python? | 1,024,847 | <p>Is it possible to add a key to a Python dictionary after it has been created? It doesn't seem to have an <code>.add()</code> method.</p>
| 1,201 | 2009-06-21T22:07:39Z | 1,024,851 | <pre><code>>>> d = {'key':'value'}
>>> print d
{'key': 'value'}
>>> d['mynewkey'] = 'mynewvalue'
>>> print d
{'mynewkey': 'mynewvalue', 'key': 'value'}
</code></pre>
| 1,611 | 2009-06-21T22:09:06Z | [
"python",
"dictionary"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.