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 |
---|---|---|---|---|---|---|---|---|---|
SQLAlchemy DateTime timezone | 414,952 | <p>SQLAlchemy's <code>DateTime</code> type allows for a <code>timezone=True</code> argument to save a non-naive datetime object to the datbase, and to return it as such. Is there any way to modify the timezone of the <code>tzinfo</code> that SQLAlchemy passes in so it could be, for instance, UTC? I realize that I could just use <code>default=datetime.datetime.utcnow</code>; however, this is a naive time that would happily accept someone passing in a naive localtime-based datetime, even if I used <code>timezone=True</code> with it, because it makes local or UTC time non-naive without having a base timezone to normailze it with. I have tried (using <a href="http://pytz.sourceforge.net/">pytz</a>) to make the datetime object non-naive, but when I save this to the db it comes back as naive.</p>
<p>Note how datetime.datetime.utcnow does not work with timezone=True so well:</p>
<pre><code>import sqlalchemy as sa
from sqlalchemy.sql import select
import datetime
metadata = sa.MetaData('postgres://user:pass@machine/db')
data_table = sa.Table('data', metadata,
sa.Column('id', sa.types.Integer, primary_key=True),
sa.Column('date', sa.types.DateTime(timezone=True), default=datetime.datetime.utcnow)
)
metadata.create_all()
engine = metadata.bind
conn = engine.connect()
result = conn.execute(data_table.insert().values(id=1))
s = select([data_table])
result = conn.execute(s)
row = result.fetchone()
</code></pre>
<blockquote>
<p>(1, datetime.datetime(2009, 1, 6, 0, 9, 36, 891887))</p>
</blockquote>
<pre><code>row[1].utcoffset()
</code></pre>
<blockquote>
<p>datetime.timedelta(-1, 64800) # that's my localtime offset!!</p>
</blockquote>
<pre><code>datetime.datetime.now(tz=pytz.timezone("US/Central"))
</code></pre>
<blockquote>
<p>datetime.timedelta(-1, 64800)</p>
</blockquote>
<pre><code>datetime.datetime.now(tz=pytz.timezone("UTC"))
</code></pre>
<blockquote>
<p>datetime.timedelta(0) #UTC</p>
</blockquote>
<p>Even if I change it to explicitly use UTC:</p>
<p>...</p>
<pre><code>data_table = sa.Table('data', metadata,
sa.Column('id', sa.types.Integer, primary_key=True),
sa.Column('date', sa.types.DateTime(timezone=True), default=datetime.datetime.now(tz=pytz.timezone('UTC')))
)
row[1].utcoffset()
</code></pre>
<p>...</p>
<blockquote>
<p>datetime.timedelta(-1, 64800) # it did not use the timezone I explicitly added</p>
</blockquote>
<p>Or if I drop the timezone=True:</p>
<p>...</p>
<pre><code>data_table = sa.Table('data', metadata,
sa.Column('id', sa.types.Integer, primary_key=True),
sa.Column('date', sa.types.DateTime(), default=datetime.datetime.now(tz=pytz.timezone('UTC')))
)
row[1].utcoffset() is None
</code></pre>
<p>...</p>
<blockquote>
<p>True # it didn't even save a timezone to the db this time</p>
</blockquote>
| 24 | 2009-01-05T23:46:02Z | 462,028 | <p><a href="http://www.postgresql.org/docs/8.3/interactive/datatype-datetime.html#DATATYPE-TIMEZONES">http://www.postgresql.org/docs/8.3/interactive/datatype-datetime.html#DATATYPE-TIMEZONES</a></p>
<blockquote>
<p>All timezone-aware dates and times are stored internally in UTC. They are converted to local time in the zone specified by the timezone configuration parameter before being displayed to the client. </p>
</blockquote>
<p>The only way to store it with postgresql is to store it separately.</p>
| 14 | 2009-01-20T16:24:22Z | [
"python",
"datetime",
"timezone",
"sqlalchemy"
]
|
SQLAlchemy DateTime timezone | 414,952 | <p>SQLAlchemy's <code>DateTime</code> type allows for a <code>timezone=True</code> argument to save a non-naive datetime object to the datbase, and to return it as such. Is there any way to modify the timezone of the <code>tzinfo</code> that SQLAlchemy passes in so it could be, for instance, UTC? I realize that I could just use <code>default=datetime.datetime.utcnow</code>; however, this is a naive time that would happily accept someone passing in a naive localtime-based datetime, even if I used <code>timezone=True</code> with it, because it makes local or UTC time non-naive without having a base timezone to normailze it with. I have tried (using <a href="http://pytz.sourceforge.net/">pytz</a>) to make the datetime object non-naive, but when I save this to the db it comes back as naive.</p>
<p>Note how datetime.datetime.utcnow does not work with timezone=True so well:</p>
<pre><code>import sqlalchemy as sa
from sqlalchemy.sql import select
import datetime
metadata = sa.MetaData('postgres://user:pass@machine/db')
data_table = sa.Table('data', metadata,
sa.Column('id', sa.types.Integer, primary_key=True),
sa.Column('date', sa.types.DateTime(timezone=True), default=datetime.datetime.utcnow)
)
metadata.create_all()
engine = metadata.bind
conn = engine.connect()
result = conn.execute(data_table.insert().values(id=1))
s = select([data_table])
result = conn.execute(s)
row = result.fetchone()
</code></pre>
<blockquote>
<p>(1, datetime.datetime(2009, 1, 6, 0, 9, 36, 891887))</p>
</blockquote>
<pre><code>row[1].utcoffset()
</code></pre>
<blockquote>
<p>datetime.timedelta(-1, 64800) # that's my localtime offset!!</p>
</blockquote>
<pre><code>datetime.datetime.now(tz=pytz.timezone("US/Central"))
</code></pre>
<blockquote>
<p>datetime.timedelta(-1, 64800)</p>
</blockquote>
<pre><code>datetime.datetime.now(tz=pytz.timezone("UTC"))
</code></pre>
<blockquote>
<p>datetime.timedelta(0) #UTC</p>
</blockquote>
<p>Even if I change it to explicitly use UTC:</p>
<p>...</p>
<pre><code>data_table = sa.Table('data', metadata,
sa.Column('id', sa.types.Integer, primary_key=True),
sa.Column('date', sa.types.DateTime(timezone=True), default=datetime.datetime.now(tz=pytz.timezone('UTC')))
)
row[1].utcoffset()
</code></pre>
<p>...</p>
<blockquote>
<p>datetime.timedelta(-1, 64800) # it did not use the timezone I explicitly added</p>
</blockquote>
<p>Or if I drop the timezone=True:</p>
<p>...</p>
<pre><code>data_table = sa.Table('data', metadata,
sa.Column('id', sa.types.Integer, primary_key=True),
sa.Column('date', sa.types.DateTime(), default=datetime.datetime.now(tz=pytz.timezone('UTC')))
)
row[1].utcoffset() is None
</code></pre>
<p>...</p>
<blockquote>
<p>True # it didn't even save a timezone to the db this time</p>
</blockquote>
| 24 | 2009-01-05T23:46:02Z | 12,695,076 | <p>a solution is given in <a href="http://stackoverflow.com/questions/2528189/can-sqlalchemy-datetime-objects-only-be-naive">this questionâs</a> answer:</p>
<p>you can circumvent that by storing all (date)time objects in your database in UTC, and converting the resulting naïve datetime objects to aware ones on retrieval.</p>
<p>the only drawback is that you lose timezone information, but itâs probably a good idea to store your datetime objects in utc, anyway.</p>
<p>if you care about the timezone information, iâd store it separately, and only convert the utc to local time in the last possible instance (e.g. right before displaying)</p>
<p>or maybe you donât need to care after all, and can use local timezone information from the machine you run your progam on, or the userâs browser if itâs a webapp.</p>
| 3 | 2012-10-02T17:16:57Z | [
"python",
"datetime",
"timezone",
"sqlalchemy"
]
|
can cherrypy receive multipart/mixed POSTs out of the box? | 415,019 | <p>We're receiving some POST data of xml + arbitrary binary files (like images and audio) from a device that only gives us multipart/mixed encoding.</p>
<p>I've setup a cherrypy upload/POST handler for our receiver end. I've managed to allow it to do arbitrary number of parameters using multipart/form-data. However when we try to send the multipart-mixed data, we're not getting any processing.</p>
<pre><code>@cherrypy.expose
def upload(self, *args,**kwargs):
"""upload adapted from cherrypy tutorials
We use our variation of cgi.FieldStorage to parse the MIME
encoded HTML form data containing the file."""
print args
print kwargs
cherrypy.response.timeout = 1300
lcHDRS = {}
for key, val in cherrypy.request.headers.iteritems():
lcHDRS[key.lower()] = val
incomingBytes = int(lcHDRS['content-length'])
print cherrypy.request.rfile
#etc..etc...
</code></pre>
<p>So, when submitting multipart/form-data, args and kwargs are well defined.<br />
args are the form fields, kwargs=hash of vars and values.
When I submit multipart/mixed, args and kwargs are empty, and I just have cherrypy.request.rfile as the raw POST information. </p>
<p>My question is, does cherrypy have a built in handler to handle multipart/mixed and chunked encoding for POST? Or will I need to override the cherrypy.tools.process_request_body and roll my own decoder?</p>
<p>It seems like the builtin wsgi server with cherrypy handles this as part of the HTTP/1.1 spec, but I could not seem to find documentation in cherrypy in accessing this functionality.</p>
<p><hr /></p>
<p>...to clarify</p>
<p>I'm using latest version 3.1.1 or so of Cherrypy.</p>
<p>Making a default form just involves making parameters in the upload function.</p>
<p>For the multipart/form-data, I've been calling curl -F param1=@file1.jpg -F param2=sometext -F param3=@file3.wav <a href="http://destination:port/upload" rel="nofollow">http://destination:port/upload</a></p>
<p>In that example, I get:</p>
<pre><code>args = ['param1','param2','param3]
kwargs = {'param1':CString<>, 'param2': 'sometext', 'param3':CString<>}
</code></pre>
<p>When trying to submit the multipart/mixed, I tried looking at the request.body, but kept on getting None for that, regardless of setting the body processing.</p>
<p>The input we're getting is coming in as this:</p>
<pre><code>user-agent:UNTRUSTED/1.0 Profile/MIDP-2.0 Configuration/CLDC-1.1
content-language:en-US
content-length:565719
mime-version:1.0
content-type:multipart/mixed; boundary='newdivider'
host:192.168.1.1:8180
transfer-encoding:chunked
--newdivider
Content-type: text/xml
<?xml version='1.0' ?><data><Stuff>....
etc...etc...
--newdivider
Content-type: image/jpeg
Content-ID: file://localhost/root1/photos/Garden.jpg
Content-transfer-encoding: binary
<binary data>
</code></pre>
<p>I've got a sneaking suspicion that the multipart/mixed is the problem that cherrypy is just giving me just the rfile. Our goal is to have cherrypy process the body into its parts with minimal processing on the receive side (ie, let cherrypy do its magic). If that requires us being tougher on the sending format to be a content-type that cherrypy likes, then so be it. What are the accepted formats? Is it only multipart/form-data?</p>
| 5 | 2009-01-06T00:16:30Z | 422,957 | <p>My bad. Whenever the Content-Type is of type "multipart/*", then CP tries to stick the contents into request.params (if any other Content-Type, it goes into request.body).</p>
<p>Unfortunately, CP has assumed that any multipart message is form-data, and made no provision for other subtypes. I've just fixed this in trunk, and it should be released in 3.1.2. Sorry for the inconvenience. In the short term, you can try applying the changeset locally; see <a href="http://www.cherrypy.org/ticket/890">http://www.cherrypy.org/ticket/890</a>.</p>
| 5 | 2009-01-08T01:55:49Z | [
"python",
"cherrypy"
]
|
Why does gethostbyaddr(gethostname()) return my IPv6 IP? | 415,407 | <p>I'm working on making a simple server application with python, and I'm trying to get the IP to bind the listening socket to. An example I looked at uses this: </p>
<pre><code>HOST = gethostbyaddr(gethostname())
</code></pre>
<p>With a little more processing after this, it should give me just the host IP as a string. This should return the IPv4 address. But when I run this code, it returns my IPv6 address. Why does it do this and how can I get my IPv4 address?</p>
<p>If its relevant, I'm using windows vista and python 2.5</p>
| 3 | 2009-01-06T04:01:41Z | 415,417 | <p>Getting your IP address is harder than you might think.</p>
<p>Check <a href="http://stackoverflow.com/questions/270745/how-do-i-determine-all-of-my-ip-addresses-when-i-have-multiple-nics#274644">this answer</a> I gave for the one reliable way I've found.</p>
<p>Here's what the answer says in case you don't like clicking on things:</p>
<p>Use the <a href="http://alastairs-place.net/netifaces/"><code>netifaces</code></a> module. Because networking is complex, using netifaces can be a little tricky, but here's how to do what you want:</p>
<pre><code>>>> import netifaces
>>> netifaces.interfaces()
['lo', 'eth0']
>>> netifaces.ifaddresses('eth0')
{17: [{'broadcast': 'ff:ff:ff:ff:ff:ff', 'addr': '00:11:2f:32:63:45'}], 2: [{'broadcast': '10.0.0.255', 'netmask': '255.255.255.0', 'addr': '10.0.0.2'}], 10: [{'netmask': 'ffff:ffff:ffff:ffff::', 'addr': 'fe80::211:2fff:fe32:6345%eth0'}]}
>>> for interface in netifaces.interfaces():
... print netifaces.ifaddresses(interface)[netifaces.AF_INET]
...
[{'peer': '127.0.0.1', 'netmask': '255.0.0.0', 'addr': '127.0.0.1'}]
[{'broadcast': '10.0.0.255', 'netmask': '255.255.255.0', 'addr': '10.0.0.2'}]
>>> for interface in netifaces.interfaces():
... for link in netifaces.ifaddresses(interface)[netifaces.AF_INET]:
... print link['addr']
...
127.0.0.1
10.0.0.2
</code></pre>
<p>This can be made a little more readable like this:</p>
<pre><code>from netifaces import interfaces, ifaddresses, AF_INET
def ip4_addresses():
ip_list = []
for interface in interfaces():
for link in ifaddresses(interface)[AF_INET]:
ip_list.append(link['addr'])
return ip_list
</code></pre>
<p>If you want IPv6 addresses, use <code>AF_INET6</code> instead of <code>AF_INET</code>. If you're wondering why <code>netifaces</code> uses lists and dictionaries all over the place, it's because a single computer can have multiple NICs, and each NIC can have multiple addresses, and each address has its own set of options.</p>
| 11 | 2009-01-06T04:07:16Z | [
"python",
"sockets",
"ip-address",
"ipv6",
"ipv4"
]
|
Why does gethostbyaddr(gethostname()) return my IPv6 IP? | 415,407 | <p>I'm working on making a simple server application with python, and I'm trying to get the IP to bind the listening socket to. An example I looked at uses this: </p>
<pre><code>HOST = gethostbyaddr(gethostname())
</code></pre>
<p>With a little more processing after this, it should give me just the host IP as a string. This should return the IPv4 address. But when I run this code, it returns my IPv6 address. Why does it do this and how can I get my IPv4 address?</p>
<p>If its relevant, I'm using windows vista and python 2.5</p>
| 3 | 2009-01-06T04:01:41Z | 415,430 | <p><a href="http://docs.python.org/library/socket.html#socket.gethostbyaddr" rel="nofollow"><code>gethostbyaddr()</code></a> takes an IP address as a parameter, not a hostname, so I'm surprised it's working at all without throwing an exception. If instead you meant <a href="http://docs.python.org/library/socket.html#socket.gethostbyname" rel="nofollow"><code>gethostbyname()</code></a>, then your results are more surprising, since that function claims not to support IPv6. <a href="http://stackoverflow.com/questions/415407/why-does-gethostbyaddrgethostname-return-my-ipv6-ip#415417">Harley's answer</a> explains how to correctly get your IP address.</p>
| 0 | 2009-01-06T04:10:55Z | [
"python",
"sockets",
"ip-address",
"ipv6",
"ipv4"
]
|
Why does gethostbyaddr(gethostname()) return my IPv6 IP? | 415,407 | <p>I'm working on making a simple server application with python, and I'm trying to get the IP to bind the listening socket to. An example I looked at uses this: </p>
<pre><code>HOST = gethostbyaddr(gethostname())
</code></pre>
<p>With a little more processing after this, it should give me just the host IP as a string. This should return the IPv4 address. But when I run this code, it returns my IPv6 address. Why does it do this and how can I get my IPv4 address?</p>
<p>If its relevant, I'm using windows vista and python 2.5</p>
| 3 | 2009-01-06T04:01:41Z | 2,211,983 | <p>IPv6 is taking precedence over IPv4 as it's the newer family, it's generally what you want if your hostname is associated with multiple families. You should be using <a href="http://docs.python.org/library/socket.html#socket.getaddrinfo">getaddrinfo</a> for family independent resolution, here is an example,</p>
<pre><code>import sys, socket;
host = socket.gethostname();
result = socket.getaddrinfo(host, None);
print "family:%i socktype:%i proto:%i canonname:%s sockaddr:%s"%result[0];
result = socket.getaddrinfo(host, None, socket.AF_INET);
print "family:%i socktype:%i proto:%i canonname:%s sockaddr:%s"%result[0];
result = socket.getaddrinfo(host, None, socket.AF_INET6);
print "family:%i socktype:%i proto:%i canonname:%s sockaddr:%s"%result[0];
</code></pre>
<p>Which on a dual-stack configured host gives me the following,</p>
<pre><code>family:10 socktype:1 proto:6 canonname: sockaddr:('2002:dce8:d28e::31', 0, 0, 0)
family:2 socktype:1 proto:6 canonname: sockaddr:('10.6.28.31', 0)
family:10 socktype:1 proto:6 canonname: sockaddr:('2002:dce8:d28e::31', 0, 0, 0)
</code></pre>
| 5 | 2010-02-06T04:02:29Z | [
"python",
"sockets",
"ip-address",
"ipv6",
"ipv4"
]
|
How to get current time in Python | 415,511 | <p>What is the module/method used to get current time?</p>
| 1,153 | 2009-01-06T04:54:23Z | 415,519 | <pre><code>>>> import datetime
>>> datetime.datetime.now()
datetime(2009, 1, 6, 15, 8, 24, 78915)
</code></pre>
<p>And just the time:</p>
<pre><code>>>> datetime.datetime.time(datetime.datetime.now())
datetime.time(15, 8, 24, 78915)
</code></pre>
<p>The same but slightly more compact:</p>
<pre><code>>>> datetime.datetime.now().time()
</code></pre>
<p>See the <a href="https://docs.python.org/3/library/datetime.html"><strong>documentation</strong></a> for more info.</p>
<p>To save typing, you can import the <code>datetime</code> object from the <code>datetime</code> module:</p>
<pre><code>>>> from datetime import datetime
</code></pre>
<p>Then remove the leading <code>datetime.</code> from all the above.</p>
| 1,151 | 2009-01-06T04:57:05Z | [
"python",
"datetime",
"time"
]
|
How to get current time in Python | 415,511 | <p>What is the module/method used to get current time?</p>
| 1,153 | 2009-01-06T04:54:23Z | 415,525 | <p>You can use <a href="http://docs.python.org/3.3/library/time.html?highlight=time.strftime#time.strftime"><code>time.strftime()</code></a>: </p>
<pre><code>>>> from time import gmtime, strftime
>>> strftime("%Y-%m-%d %H:%M:%S", gmtime())
'2009-01-05 22:14:39'
</code></pre>
| 475 | 2009-01-06T04:59:52Z | [
"python",
"datetime",
"time"
]
|
How to get current time in Python | 415,511 | <p>What is the module/method used to get current time?</p>
| 1,153 | 2009-01-06T04:54:23Z | 415,527 | <pre><code>>>> from time import gmtime, strftime
>>> strftime("%a, %d %b %Y %X +0000", gmtime())
'Tue, 06 Jan 2009 04:54:56 +0000'
</code></pre>
<p>That outputs the current GMT in the specified format. There is also a localtime() method. </p>
<p>This <a href="http://docs.python.org/library/time.html#module-time">page</a> has more details.</p>
| 66 | 2009-01-06T05:02:43Z | [
"python",
"datetime",
"time"
]
|
How to get current time in Python | 415,511 | <p>What is the module/method used to get current time?</p>
| 1,153 | 2009-01-06T04:54:23Z | 416,605 | <p>Do</p>
<pre><code>from time import time
t = time()
</code></pre>
<ul>
<li><code>t</code> - float number, good for time interval measurement.</li>
</ul>
<p>There is some difference for Unix and Windows platforms.</p>
| 74 | 2009-01-06T13:55:23Z | [
"python",
"datetime",
"time"
]
|
How to get current time in Python | 415,511 | <p>What is the module/method used to get current time?</p>
| 1,153 | 2009-01-06T04:54:23Z | 4,538,034 | <p>If you need current time as a <code>time</code> object:</p>
<pre><code>>>> import datetime
>>> now = datetime.datetime.now()
>>> datetime.time(now.hour, now.minute, now.second)
datetime.time(11, 23, 44)
</code></pre>
| 26 | 2010-12-27T10:24:12Z | [
"python",
"datetime",
"time"
]
|
How to get current time in Python | 415,511 | <p>What is the module/method used to get current time?</p>
| 1,153 | 2009-01-06T04:54:23Z | 5,877,368 | <p>Similar to <a href="http://stackoverflow.com/questions/415511/how-to-get-current-time-in-python/415519#415519">Harley's answer</a>, but use the <code>str()</code> function for a quick-n-dirty, slightly more human readable format:</p>
<pre><code>>>> from datetime import datetime
>>> str(datetime.now())
'2011-05-03 17:45:35.177000'
</code></pre>
| 222 | 2011-05-04T00:56:29Z | [
"python",
"datetime",
"time"
]
|
How to get current time in Python | 415,511 | <p>What is the module/method used to get current time?</p>
| 1,153 | 2009-01-06T04:54:23Z | 14,229,023 | <pre><code>>>> from datetime import datetime
>>> datetime.now().strftime('%Y-%m-%d %H:%M:%S')
</code></pre>
<p>For this example, the output will be like this: <code>'2013-09-18 11:16:32'</code></p>
<p>The format for <code>strftime</code> is at:<br>
<a href="https://docs.python.org/2/library/time.html#time.strftime">https://docs.python.org/2/library/time.html#time.strftime</a></p>
| 175 | 2013-01-09T05:50:34Z | [
"python",
"datetime",
"time"
]
|
How to get current time in Python | 415,511 | <p>What is the module/method used to get current time?</p>
| 1,153 | 2009-01-06T04:54:23Z | 17,287,377 | <p>I'll contribute to this because <code>.isoformat()</code> is in the documentation but not yet here
(this is mighty similar to @Ray Vega's answer):</p>
<pre><code>>>>import datetime
>>> datetime.datetime.now().isoformat()
'2013-06-24T20:35:55.982000'
</code></pre>
| 16 | 2013-06-25T00:38:25Z | [
"python",
"datetime",
"time"
]
|
How to get current time in Python | 415,511 | <p>What is the module/method used to get current time?</p>
| 1,153 | 2009-01-06T04:54:23Z | 18,980,227 | <p>Quickest way is</p>
<pre><code>>>> import time
>>> time.strftime("%Y%m%d")
'20130924'
</code></pre>
| 13 | 2013-09-24T11:21:10Z | [
"python",
"datetime",
"time"
]
|
How to get current time in Python | 415,511 | <p>What is the module/method used to get current time?</p>
| 1,153 | 2009-01-06T04:54:23Z | 19,710,846 | <p>All good suggestions, but I find it easiest to use <code>ctime()</code> myself:</p>
<pre><code>In [2]: from time import ctime
In [3]: ctime()
Out[3]: 'Thu Oct 31 11:40:53 2013'
</code></pre>
<p>This gives a nicely formatted string representation of current local time.</p>
| 27 | 2013-10-31T15:39:39Z | [
"python",
"datetime",
"time"
]
|
How to get current time in Python | 415,511 | <p>What is the module/method used to get current time?</p>
| 1,153 | 2009-01-06T04:54:23Z | 23,753,208 | <pre><code>>>> import datetime, time
>>> time = strftime("%H:%M:%S:%MS", time.localtime())
>>> print time
'00:20:58:20S'
</code></pre>
| 5 | 2014-05-20T07:13:36Z | [
"python",
"datetime",
"time"
]
|
How to get current time in Python | 415,511 | <p>What is the module/method used to get current time?</p>
| 1,153 | 2009-01-06T04:54:23Z | 27,611,645 | <p><code>datetime.now()</code> returns the current time as a naive datetime object that represents time in the local timezone. That value may be ambiguous e.g., during DST transitions ("fall back"). To avoid ambiguity either UTC timezone should be used:</p>
<pre><code>from datetime import datetime
utc_time = datetime.utcnow()
print(utc_time) # -> 2014-12-22 22:48:59.916417
</code></pre>
<p>Or a timezone-aware object that has the corresponding timezone info attached (Python 3.2+):</p>
<pre><code>from datetime import datetime, timezone
now = datetime.now(timezone.utc).astimezone()
print(now) # -> 2014-12-23 01:49:25.837541+03:00
</code></pre>
| 8 | 2014-12-22T22:52:47Z | [
"python",
"datetime",
"time"
]
|
How to get current time in Python | 415,511 | <p>What is the module/method used to get current time?</p>
| 1,153 | 2009-01-06T04:54:23Z | 27,866,830 | <p>This is what I ended up going with: </p>
<pre><code>>>>from time import strftime
>>>strftime("%m/%d/%Y %H:%M")
01/09/2015 13:11
</code></pre>
<p>Also, this table is a necessary reference for choosing the appropriate format codes to get the date formatted just the way you want it (from Python "datetime" documentation <a href="https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior">here</a>).</p>
<p><img src="http://i.stack.imgur.com/i6Hg7.jpg" alt="strftime format code table"></p>
| 11 | 2015-01-09T18:24:49Z | [
"python",
"datetime",
"time"
]
|
How to get current time in Python | 415,511 | <p>What is the module/method used to get current time?</p>
| 1,153 | 2009-01-06T04:54:23Z | 28,371,709 | <p>You can use the time module.</p>
<pre><code>import time
print time.strftime("%d/%m/%Y")
>>> 06/02/2015
</code></pre>
<p>The use of the captial <code>Y</code> gives the full year, using <code>y</code> would give <code>06/02/15</code></p>
<p>You could also use to give a more lengthy time.</p>
<pre><code>time.strftime("%a, %d %b %Y %H:%M:%S")
>>> 'Fri, 06 Feb 2015 17:45:09'
</code></pre>
| 6 | 2015-02-06T17:46:46Z | [
"python",
"datetime",
"time"
]
|
How to get current time in Python | 415,511 | <p>What is the module/method used to get current time?</p>
| 1,153 | 2009-01-06T04:54:23Z | 28,576,383 | <blockquote>
<h1>How do I get the current time in Python?</h1>
</blockquote>
<h2>The <code>time</code> module</h2>
<p>The <code>time</code> module provides functions that tells us the time in "seconds since the epoch" as well as other utilities.</p>
<pre><code>import time
</code></pre>
<h3>Unix Epoch Time</h3>
<p>This is the format you should get timestamps in for saving in databases. It is a simple floating point number that can be converted to an integer. It is also good for arithmetic in seconds, as it represents the number of seconds since Jan 1, 1970 00:00:00, and it is memory light relative to the other representations of time we'll be looking at next:</p>
<pre><code>>>> time.time()
1424233311.771502
</code></pre>
<p>This timestamp does not account for leap-seconds, so it's not linear - leap seconds are ignored. So while it is not equivalent to the international UTC standard, it is close, and therefore quite good for most cases of record-keeping. </p>
<p>This is not ideal for human scheduling, however. If you have a future event you wish to take place at a certain point in time, you'll want to store that time with a string that can be parsed into a datetime object or a serialized datetime object (these will be described later).</p>
<h3><code>time.ctime</code></h3>
<p>You can also represent the current time in the way preferred by your operating system (which means it can change when you change your system preferences, so don't rely on this to be standard across all systems, as I've seen others expect). This is typically user friendly, but doesn't typically result in strings one can sort chronologically:</p>
<pre><code>>>> time.ctime()
'Tue Feb 17 23:21:56 2015'
</code></pre>
<p>You can hydrate timestamps into human readable form with <code>ctime</code> as well:</p>
<pre><code>>>> time.ctime(1424233311.771502)
'Tue Feb 17 23:21:51 2015'
</code></pre>
<p>This conversion is also not good for record-keeping (except in text that will only be parsed by humans - and with improved Optical Character Recognition and Artificial Intelligence, I think the number of these cases will diminish).</p>
<h2><code>datetime</code> module</h2>
<p>The <code>datetime</code> module is also quite useful here:</p>
<pre><code>>>> import datetime
</code></pre>
<h3><code>datetime.datetime.now</code></h3>
<p>The <code>datetime.now</code> is a class method that returns the current time. It uses the <code>time.localtime</code> without the timezone info (if not given, otherwise see timezone aware below). It has a representation (which would allow you to recreate an equivalent object) echoed on the shell, but when printed (or coerced to a <code>str</code>), it is in human readable (and nearly ISO) format, and the lexicographic sort is equivalent to the chronological sort:</p>
<pre><code>>>> datetime.datetime.now()
datetime.datetime(2015, 2, 17, 23, 43, 49, 94252)
>>> print(datetime.datetime.now())
2015-02-17 23:43:51.782461
</code></pre>
<h3>datetime's <code>utcnow</code></h3>
<p>You can get a datetime object in UTC time, a global standard, by doing this:</p>
<pre><code>>>> datetime.datetime.utcnow()
datetime.datetime(2015, 2, 18, 4, 53, 28, 394163)
>>> print(datetime.datetime.utcnow())
2015-02-18 04:53:31.783988
</code></pre>
<p>UTC is a time standard that is nearly equivalent to the GMT timezone. (While GMT and UTC do not change for Daylight Savings Time, their users may switch to other timezones, like British Summer Time, during the Summer.) </p>
<h3>datetime timezone aware</h3>
<p>However, none of the datetime objects we've created so far can be easily converted to various timezones. We can solve that problem with the <code>pytz</code> module:</p>
<pre><code>>>> import pytz
>>> then = datetime.datetime.now(pytz.utc)
>>> then
datetime.datetime(2015, 2, 18, 4, 55, 58, 753949, tzinfo=<UTC>)
</code></pre>
<p>Equivalently, in Python 3 we have the <code>timezone</code> class with a utc <code>timezone</code> instance attached, which also makes the object timezone aware (but to convert to another timezone without the handy <code>pytz</code> module is left as an exercise to the reader):</p>
<pre><code>>>> datetime.datetime.now(datetime.timezone.utc)
datetime.datetime(2015, 2, 18, 22, 31, 56, 564191, tzinfo=datetime.timezone.utc)
</code></pre>
<p>And we see we can easily convert to timezones from the original utc object.</p>
<pre><code>>>> print(then)
2015-02-18 04:55:58.753949+00:00
>>> print(then.astimezone(pytz.timezone('US/Eastern')))
2015-02-17 23:55:58.753949-05:00
</code></pre>
<p>You can also make a naive datetime object aware with the <code>pytz</code> timezone <code>localize</code> method, or by replacing the tzinfo attribute (with <code>replace</code>, this is done blindly), but these are more last resorts than best practices:</p>
<pre><code>>>> pytz.utc.localize(datetime.datetime.utcnow())
datetime.datetime(2015, 2, 18, 6, 6, 29, 32285, tzinfo=<UTC>)
>>> datetime.datetime.utcnow().replace(tzinfo=pytz.utc)
datetime.datetime(2015, 2, 18, 6, 9, 30, 728550, tzinfo=<UTC>)
</code></pre>
<p>The <code>pytz</code> module allows us to make our <code>datetime</code> objects timezone aware and convert the times to the hundreds of timezones available in the <code>pytz</code> module.</p>
<p>One could ostensibly serialize this object for UTC time and store <em>that</em> in a database, but it would require far more memory and be more prone to error than simply storing the Unix Epoch time, which I demonstrated first. </p>
<p>The other ways of viewing times are much more error prone, especially when dealing with data that may come from different time zones. You want there to be no confusion as to which timezone a string or serialized datetime object was intended for.</p>
<p>If you're displaying the time with Python for the user, <code>ctime</code> works nicely, not in a table (it doesn't typically sort well), but perhaps in a clock. However, I personally recommend, when dealing with time in Python, either using Unix time, or a timezone aware UTC <code>datetime</code> object. </p>
| 38 | 2015-02-18T05:08:34Z | [
"python",
"datetime",
"time"
]
|
How to get current time in Python | 415,511 | <p>What is the module/method used to get current time?</p>
| 1,153 | 2009-01-06T04:54:23Z | 29,980,465 | <p>This is what i use to get the time without having to format , some people dont like the split method but it is useful here :</p>
<pre><code>from time import ctime
print ctime().split()[3]
</code></pre>
<p>Will print in HH:MM:SS format</p>
| 2 | 2015-05-01T01:39:08Z | [
"python",
"datetime",
"time"
]
|
How to get current time in Python | 415,511 | <p>What is the module/method used to get current time?</p>
| 1,153 | 2009-01-06T04:54:23Z | 33,704,374 | <p>Try the arrow module from <a href="http://crsmithdev.com/arrow/">http://crsmithdev.com/arrow/</a></p>
<pre><code>import arrow
arrow.now()
</code></pre>
<p>or the utc version</p>
<pre><code>arrow.utcnow()
</code></pre>
<p>to change it's output add .format()</p>
<pre><code>arrow.utcnow().format('YYYY-MM-DD HH:mm:ss ZZ')
</code></pre>
<p>for a specific timezone?</p>
<pre><code>arrow.now('US/Pacific')
</code></pre>
<p>an hour ago</p>
<pre><code>arrow.utcnow().replace(hours=-1)
</code></pre>
<p>or if you want the gist.</p>
<pre><code>arrow.get('2013-05-11T21:23:58.970460+00:00').humanize()
>>> '2 years ago'
</code></pre>
| 6 | 2015-11-14T02:02:45Z | [
"python",
"datetime",
"time"
]
|
How to get current time in Python | 415,511 | <p>What is the module/method used to get current time?</p>
| 1,153 | 2009-01-06T04:54:23Z | 38,366,394 | <pre><code>import datetime
date_time = str(datetime.datetime.now())
date = date_time.split()[0]
time = date_time.split()[1]
</code></pre>
<p>date will print date and time will print time.</p>
| 0 | 2016-07-14T05:50:20Z | [
"python",
"datetime",
"time"
]
|
How to get current time in Python | 415,511 | <p>What is the module/method used to get current time?</p>
| 1,153 | 2009-01-06T04:54:23Z | 38,433,505 | <p>I am a simple man and i want time with milliseconds. Simple way to get them:</p>
<pre><code>import time, datetime
print(datetime.datetime.now().time()) # 11:20:08.272239
# or in a more complicated way
print(datetime.datetime.now().time().isoformat()) # 11:20:08.272239
print(datetime.datetime.now().time().strftime('%H:%M:%S.%f')) # 11:20:08.272239
# but do not use this
print(time.strftime("%H:%M:%S.%f", time.localtime()), str) # 11:20:08.%f
</code></pre>
<p>But i want <strong>only miliseconds</strong>, right? Shortest way to get them:</p>
<pre><code>import time
time.strftime("%H:%M:%S", time.localtime()) + '.%d' % (time.time() % 1 * 1000)
# 11:34:23.751
</code></pre>
<p>Add or remove zeroes from the last multiplication to adjust number of decimal points, or just:</p>
<pre><code>def get_time_str(decimal_points=3):
return time.strftime("%H:%M:%S", time.localtime()) + '.%d' % (time.time() % 1 * 10**decimal_points)
</code></pre>
| 0 | 2016-07-18T09:45:50Z | [
"python",
"datetime",
"time"
]
|
How to get current time in Python | 415,511 | <p>What is the module/method used to get current time?</p>
| 1,153 | 2009-01-06T04:54:23Z | 38,615,092 | <p>why not just keep things simple. </p>
<pre><code>>>> from datetime import datetime
>>> datetime.now().strftime("%Y-%m-%d %H:%M:%S")
'2016-07-27 15:56:59'
>>>
</code></pre>
| 5 | 2016-07-27T13:58:36Z | [
"python",
"datetime",
"time"
]
|
How to get current time in Python | 415,511 | <p>What is the module/method used to get current time?</p>
| 1,153 | 2009-01-06T04:54:23Z | 39,046,637 | <p>Why not ask the <a href="http://tycho.usno.navy.mil/cgi-bin/timer.pl">U.S. Naval Observatory</a>, the official timekeeper of the United States Navy?</p>
<pre><code>import requests
from lxml import html
page = requests.get('http://tycho.usno.navy.mil/cgi-bin/timer.pl')
tree = html.fromstring(page.content)
print(tree.xpath('//html//body//h3//pre/text()')[1])
</code></pre>
<p>If you live in the D.C. area (like me) the latency might not be too bad...</p>
| 5 | 2016-08-19T19:45:08Z | [
"python",
"datetime",
"time"
]
|
URLs: Binary Blob, Unicode or Encoded Unicode String? | 416,315 | <p>I wish to store URLs in a database (MySQL in this case) and process it in Python. Though the database and programming language are probably not this relevant to my question.</p>
<p>In my setup I receive unicode strings when querying a text field in the database. But is a URL actually text? Is encoding from and decoding to unicode an operation that should be done to a URL? Or is it better to make the column in the database a binary blob?</p>
<p>So, how do you handle this problem?</p>
<p>Clarification:
This question is not about urlencoding non-ASCII characters with the percent notation. It's about the distiction that unicode represents text and byte strings represent a way to encode this text into a sequence of bytes. In Python (prior to 3.0) this distinction is between the unicode and the str types. In MySQL it is TEXT to BLOBS. So the concepts seem to correspond between programming language and database. But what is the best way to handle URLs in this scheme?</p>
| 2 | 2009-01-06T12:22:10Z | 416,339 | <p>On the question: "But is a URL actually text?"</p>
<p>It depends on the context, in some languages or libraries (for example java, I'm not sure about python), a URL may be represented internally as an object. However, a URL always has a well defined text representation. So storing the text-representation is much more portable than storing the internal representation used by whatever is the current language of choice.</p>
<p>URL syntax and semantics are covered by quite a few standards, recommendations and implementations, but I think the most authoritative source for parsing and constructing correct URL-s would be <a href="http://www.ietf.org/rfc/rfc2396.txt" rel="nofollow">RFC 2396</a>.</p>
<p>On the question about unicode, section 2.1 deals with non-ascii characters.</p>
<p>(Edit: changed rfc-reference to the newest edition, thank you S.Lott)</p>
| 1 | 2009-01-06T12:30:39Z | [
"python",
"mysql",
"database",
"url"
]
|
URLs: Binary Blob, Unicode or Encoded Unicode String? | 416,315 | <p>I wish to store URLs in a database (MySQL in this case) and process it in Python. Though the database and programming language are probably not this relevant to my question.</p>
<p>In my setup I receive unicode strings when querying a text field in the database. But is a URL actually text? Is encoding from and decoding to unicode an operation that should be done to a URL? Or is it better to make the column in the database a binary blob?</p>
<p>So, how do you handle this problem?</p>
<p>Clarification:
This question is not about urlencoding non-ASCII characters with the percent notation. It's about the distiction that unicode represents text and byte strings represent a way to encode this text into a sequence of bytes. In Python (prior to 3.0) this distinction is between the unicode and the str types. In MySQL it is TEXT to BLOBS. So the concepts seem to correspond between programming language and database. But what is the best way to handle URLs in this scheme?</p>
| 2 | 2009-01-06T12:22:10Z | 416,423 | <p>The relevant answer is found in <a href="http://www.ietf.org/rfc/rfc2396.txt" rel="nofollow">RFC 2396</a>, section
2.1 <em>URI and non-ASCII characters</em></p>
<p><hr /></p>
<p>The relationship between URI and characters has been a source of
confusion for characters that are not part of US-ASCII. To describe
the relationship, it is useful to distinguish between a "character"
(as a distinguishable semantic entity) and an "octet" (an 8-bit
byte). There are two mappings, one from URI characters to octets, and
a second from octets to original characters:</p>
<p>URI character sequence->octet sequence->original character sequence</p>
<p>A URI is represented as a sequence of characters, not as a sequence
of octets. That is because URI might be "transported" by means that
are not through a computer network, e.g., printed on paper, read over
the radio, etc.</p>
<p><hr /></p>
| 3 | 2009-01-06T13:01:10Z | [
"python",
"mysql",
"database",
"url"
]
|
URLs: Binary Blob, Unicode or Encoded Unicode String? | 416,315 | <p>I wish to store URLs in a database (MySQL in this case) and process it in Python. Though the database and programming language are probably not this relevant to my question.</p>
<p>In my setup I receive unicode strings when querying a text field in the database. But is a URL actually text? Is encoding from and decoding to unicode an operation that should be done to a URL? Or is it better to make the column in the database a binary blob?</p>
<p>So, how do you handle this problem?</p>
<p>Clarification:
This question is not about urlencoding non-ASCII characters with the percent notation. It's about the distiction that unicode represents text and byte strings represent a way to encode this text into a sequence of bytes. In Python (prior to 3.0) this distinction is between the unicode and the str types. In MySQL it is TEXT to BLOBS. So the concepts seem to correspond between programming language and database. But what is the best way to handle URLs in this scheme?</p>
| 2 | 2009-01-06T12:22:10Z | 416,994 | <p>Do note there is also a standard for Unicode Web addresses, IRI (Internationalized Resource Identifiers). <a href="http://www.ietf.org/rfc/rfc3987.txt" rel="nofollow">RFC 3987</a></p>
| 1 | 2009-01-06T15:37:53Z | [
"python",
"mysql",
"database",
"url"
]
|
Filtering away nearby points from a list | 416,406 | <p>I <a href="http://stackoverflow.com/questions/411837/finding-clusters-of-mass-in-a-matrix-bitmap#411855">half-answered a question about finding clusters of mass in a bitmap</a>. I say half-answered because I left it in a condition where I had all the points in the bitmap sorted by mass and left it to the reader to filter the list removing points from the same cluster. </p>
<p>Then when thinking about that step I found that the solution didn't jump out at me like I thought it would. So now I'm asking you guys for help. We have a list of points with masses like so (a Python list of tuples, but you can represent it as you see fit in any language):</p>
<pre><code>[ (6, 2, 6.1580555555555554),
(2, 1, 5.4861111111111107),
(1, 1, 4.6736111111111107),
(1, 4, 4.5938888888888885),
(2, 0, 4.54),
(1, 5, 4.4480555555555554),
(4, 7, 4.4480555555555554),
(5, 7, 4.4059637188208614),
(4, 8, 4.3659637188208613),
(1, 0, 4.3611111111111107),
(5, 8, 4.3342191043083904),
(5, 2, 4.119574829931973),
...
(8, 8, 0.27611111111111108),
(0, 8, 0.24138888888888888) ]
</code></pre>
<p>Each tuple is of the form:</p>
<pre><code>(x, y, mass)
</code></pre>
<p>Note that the list is sorted here. If your solution prefers to not have them sorted it's perfectly OK.</p>
<p>The challenge, <a href="http://stackoverflow.com/questions/411837/finding-clusters-of-mass-in-a-matrix-bitmap">if you recall</a>, is to find the main clusters of mass. The number of clusters is not known. But you know the dimensions of the bitmap. Sometimes several points within a cluster has more mass than the center of the next (in size) cluster. So what I want to do is go from the higher-mass points and remove points in the same cluster (points nearby).</p>
<p>When I tried this I ended up having to walk through parts of the list over and over again. I have a feeling I'm just stupid about it. How would you do it? Pseudo code or real code. Of course, if you can just take off where I left in that answer with Python code it's easier for me to experiment with it. </p>
<p>Next step is to figure out how many clusters there really are in the bitmap. I'm still struggling with defining that problem so I might return with a question about it.</p>
<p><strong>EDIT:</strong> I should clarify that I know that there's no "correct" answer to this question. And the name of the question is key. Phase one of the my clustering is done. <strong>Im in search of a fast, accurate-"enough" method of filtering away nearby points.</strong> </p>
<p>Let me know if you see how I can make the question clearer.</p>
| 0 | 2009-01-06T12:54:57Z | 416,426 | <p>This sounds like color quantization, where you reduce the number of colors in an image. One way would be to plot the colors in space, and combine clusters into the center (or a weighted average) of a cluster.</p>
<p>The exact name of the algorithm that triggered this memory fails me, but I'll edit the answer if it pops up, but in the meantime, you should look at color quantization and see if some of the algorithms are useful.</p>
| 1 | 2009-01-06T13:02:17Z | [
"python",
"algorithm",
"language-agnostic",
"bitmap",
"filtering"
]
|
Filtering away nearby points from a list | 416,406 | <p>I <a href="http://stackoverflow.com/questions/411837/finding-clusters-of-mass-in-a-matrix-bitmap#411855">half-answered a question about finding clusters of mass in a bitmap</a>. I say half-answered because I left it in a condition where I had all the points in the bitmap sorted by mass and left it to the reader to filter the list removing points from the same cluster. </p>
<p>Then when thinking about that step I found that the solution didn't jump out at me like I thought it would. So now I'm asking you guys for help. We have a list of points with masses like so (a Python list of tuples, but you can represent it as you see fit in any language):</p>
<pre><code>[ (6, 2, 6.1580555555555554),
(2, 1, 5.4861111111111107),
(1, 1, 4.6736111111111107),
(1, 4, 4.5938888888888885),
(2, 0, 4.54),
(1, 5, 4.4480555555555554),
(4, 7, 4.4480555555555554),
(5, 7, 4.4059637188208614),
(4, 8, 4.3659637188208613),
(1, 0, 4.3611111111111107),
(5, 8, 4.3342191043083904),
(5, 2, 4.119574829931973),
...
(8, 8, 0.27611111111111108),
(0, 8, 0.24138888888888888) ]
</code></pre>
<p>Each tuple is of the form:</p>
<pre><code>(x, y, mass)
</code></pre>
<p>Note that the list is sorted here. If your solution prefers to not have them sorted it's perfectly OK.</p>
<p>The challenge, <a href="http://stackoverflow.com/questions/411837/finding-clusters-of-mass-in-a-matrix-bitmap">if you recall</a>, is to find the main clusters of mass. The number of clusters is not known. But you know the dimensions of the bitmap. Sometimes several points within a cluster has more mass than the center of the next (in size) cluster. So what I want to do is go from the higher-mass points and remove points in the same cluster (points nearby).</p>
<p>When I tried this I ended up having to walk through parts of the list over and over again. I have a feeling I'm just stupid about it. How would you do it? Pseudo code or real code. Of course, if you can just take off where I left in that answer with Python code it's easier for me to experiment with it. </p>
<p>Next step is to figure out how many clusters there really are in the bitmap. I'm still struggling with defining that problem so I might return with a question about it.</p>
<p><strong>EDIT:</strong> I should clarify that I know that there's no "correct" answer to this question. And the name of the question is key. Phase one of the my clustering is done. <strong>Im in search of a fast, accurate-"enough" method of filtering away nearby points.</strong> </p>
<p>Let me know if you see how I can make the question clearer.</p>
| 0 | 2009-01-06T12:54:57Z | 416,428 | <p>Start with the "<a href="http://en.wikipedia.org/wiki/Convex_hull" rel="nofollow">Convex Hull</a>" problem. You're also looking for some "convex hull"-like clusters.</p>
<p>Note that "clusters" is vague. You have an average mass across your field. Some points have above average mass, and some below average. How far above average means you've found a cluster? How far apart do nodes have to be to be part of a cluster or a separate cluster?</p>
<p>What's the difference between two mountain peaks and a ridge? </p>
<p>You have to compute a "topography" - joining all points with equal density into regions. This requires that you pick a spot and work your want out from a point radially, locating positions where the densities are equal. You can connect those points into regions.</p>
<p>If you picked your initial point wisely, the regions should nest. Picking your starting point is easy because you start at local highs.</p>
| 1 | 2009-01-06T13:03:48Z | [
"python",
"algorithm",
"language-agnostic",
"bitmap",
"filtering"
]
|
Filtering away nearby points from a list | 416,406 | <p>I <a href="http://stackoverflow.com/questions/411837/finding-clusters-of-mass-in-a-matrix-bitmap#411855">half-answered a question about finding clusters of mass in a bitmap</a>. I say half-answered because I left it in a condition where I had all the points in the bitmap sorted by mass and left it to the reader to filter the list removing points from the same cluster. </p>
<p>Then when thinking about that step I found that the solution didn't jump out at me like I thought it would. So now I'm asking you guys for help. We have a list of points with masses like so (a Python list of tuples, but you can represent it as you see fit in any language):</p>
<pre><code>[ (6, 2, 6.1580555555555554),
(2, 1, 5.4861111111111107),
(1, 1, 4.6736111111111107),
(1, 4, 4.5938888888888885),
(2, 0, 4.54),
(1, 5, 4.4480555555555554),
(4, 7, 4.4480555555555554),
(5, 7, 4.4059637188208614),
(4, 8, 4.3659637188208613),
(1, 0, 4.3611111111111107),
(5, 8, 4.3342191043083904),
(5, 2, 4.119574829931973),
...
(8, 8, 0.27611111111111108),
(0, 8, 0.24138888888888888) ]
</code></pre>
<p>Each tuple is of the form:</p>
<pre><code>(x, y, mass)
</code></pre>
<p>Note that the list is sorted here. If your solution prefers to not have them sorted it's perfectly OK.</p>
<p>The challenge, <a href="http://stackoverflow.com/questions/411837/finding-clusters-of-mass-in-a-matrix-bitmap">if you recall</a>, is to find the main clusters of mass. The number of clusters is not known. But you know the dimensions of the bitmap. Sometimes several points within a cluster has more mass than the center of the next (in size) cluster. So what I want to do is go from the higher-mass points and remove points in the same cluster (points nearby).</p>
<p>When I tried this I ended up having to walk through parts of the list over and over again. I have a feeling I'm just stupid about it. How would you do it? Pseudo code or real code. Of course, if you can just take off where I left in that answer with Python code it's easier for me to experiment with it. </p>
<p>Next step is to figure out how many clusters there really are in the bitmap. I'm still struggling with defining that problem so I might return with a question about it.</p>
<p><strong>EDIT:</strong> I should clarify that I know that there's no "correct" answer to this question. And the name of the question is key. Phase one of the my clustering is done. <strong>Im in search of a fast, accurate-"enough" method of filtering away nearby points.</strong> </p>
<p>Let me know if you see how I can make the question clearer.</p>
| 0 | 2009-01-06T12:54:57Z | 416,489 | <p>Since you are already talking about mass, why not a gravity based solution. A simple particle system would not need to be super accurate, and you would not have to run it for too long before you could make a much better guess at the number of clusters.</p>
<p>If you have a better idea about cluster numbers, k-means nearest neighbour becomes feasible.</p>
| 1 | 2009-01-06T13:21:28Z | [
"python",
"algorithm",
"language-agnostic",
"bitmap",
"filtering"
]
|
Filtering away nearby points from a list | 416,406 | <p>I <a href="http://stackoverflow.com/questions/411837/finding-clusters-of-mass-in-a-matrix-bitmap#411855">half-answered a question about finding clusters of mass in a bitmap</a>. I say half-answered because I left it in a condition where I had all the points in the bitmap sorted by mass and left it to the reader to filter the list removing points from the same cluster. </p>
<p>Then when thinking about that step I found that the solution didn't jump out at me like I thought it would. So now I'm asking you guys for help. We have a list of points with masses like so (a Python list of tuples, but you can represent it as you see fit in any language):</p>
<pre><code>[ (6, 2, 6.1580555555555554),
(2, 1, 5.4861111111111107),
(1, 1, 4.6736111111111107),
(1, 4, 4.5938888888888885),
(2, 0, 4.54),
(1, 5, 4.4480555555555554),
(4, 7, 4.4480555555555554),
(5, 7, 4.4059637188208614),
(4, 8, 4.3659637188208613),
(1, 0, 4.3611111111111107),
(5, 8, 4.3342191043083904),
(5, 2, 4.119574829931973),
...
(8, 8, 0.27611111111111108),
(0, 8, 0.24138888888888888) ]
</code></pre>
<p>Each tuple is of the form:</p>
<pre><code>(x, y, mass)
</code></pre>
<p>Note that the list is sorted here. If your solution prefers to not have them sorted it's perfectly OK.</p>
<p>The challenge, <a href="http://stackoverflow.com/questions/411837/finding-clusters-of-mass-in-a-matrix-bitmap">if you recall</a>, is to find the main clusters of mass. The number of clusters is not known. But you know the dimensions of the bitmap. Sometimes several points within a cluster has more mass than the center of the next (in size) cluster. So what I want to do is go from the higher-mass points and remove points in the same cluster (points nearby).</p>
<p>When I tried this I ended up having to walk through parts of the list over and over again. I have a feeling I'm just stupid about it. How would you do it? Pseudo code or real code. Of course, if you can just take off where I left in that answer with Python code it's easier for me to experiment with it. </p>
<p>Next step is to figure out how many clusters there really are in the bitmap. I'm still struggling with defining that problem so I might return with a question about it.</p>
<p><strong>EDIT:</strong> I should clarify that I know that there's no "correct" answer to this question. And the name of the question is key. Phase one of the my clustering is done. <strong>Im in search of a fast, accurate-"enough" method of filtering away nearby points.</strong> </p>
<p>Let me know if you see how I can make the question clearer.</p>
| 0 | 2009-01-06T12:54:57Z | 416,544 | <p>As I mentioned in the comment to your question, the answer is based on whether or not mass can be considered scalar in this context. If so, color based solutions are probably not going to work as color is often not taken as being scalar.</p>
<p>For example, if I have a given area with 1 point of high mass, is that the same as having the same area with 10 points of 1/10 the mass? If this is true, mass is not scalar in this context, and I would tend to look at an algorithm used for spatially gouping similar non-scalable values, e.g. <a href="http://en.wikipedia.org/wiki/Voronoi_diagram" rel="nofollow">voronoi diagrams</a>.</p>
<p><img src="http://upload.wikimedia.org/wikipedia/commons/thumb/2/20/Coloured_Voronoi_2D.svg/600px-Coloured_Voronoi_2D.svg.png" alt="alt text" /></p>
<p>In this case, where two adjacent voronoi areas have a close enough mass match and distance, they can be clustered together. You could repeat this to find all clusters.</p>
<p>If on the other hand, your mass is scalable, or that the mass at an unknown position can be interpolated from surrounding points, I would tend to <a href="http://en.wikipedia.org/wiki/Delaunay_trianglulation" rel="nofollow">triangulate</a> and contour the input data and use areas between contours to find clusters of similar mass.</p>
| 3 | 2009-01-06T13:42:05Z | [
"python",
"algorithm",
"language-agnostic",
"bitmap",
"filtering"
]
|
Filtering away nearby points from a list | 416,406 | <p>I <a href="http://stackoverflow.com/questions/411837/finding-clusters-of-mass-in-a-matrix-bitmap#411855">half-answered a question about finding clusters of mass in a bitmap</a>. I say half-answered because I left it in a condition where I had all the points in the bitmap sorted by mass and left it to the reader to filter the list removing points from the same cluster. </p>
<p>Then when thinking about that step I found that the solution didn't jump out at me like I thought it would. So now I'm asking you guys for help. We have a list of points with masses like so (a Python list of tuples, but you can represent it as you see fit in any language):</p>
<pre><code>[ (6, 2, 6.1580555555555554),
(2, 1, 5.4861111111111107),
(1, 1, 4.6736111111111107),
(1, 4, 4.5938888888888885),
(2, 0, 4.54),
(1, 5, 4.4480555555555554),
(4, 7, 4.4480555555555554),
(5, 7, 4.4059637188208614),
(4, 8, 4.3659637188208613),
(1, 0, 4.3611111111111107),
(5, 8, 4.3342191043083904),
(5, 2, 4.119574829931973),
...
(8, 8, 0.27611111111111108),
(0, 8, 0.24138888888888888) ]
</code></pre>
<p>Each tuple is of the form:</p>
<pre><code>(x, y, mass)
</code></pre>
<p>Note that the list is sorted here. If your solution prefers to not have them sorted it's perfectly OK.</p>
<p>The challenge, <a href="http://stackoverflow.com/questions/411837/finding-clusters-of-mass-in-a-matrix-bitmap">if you recall</a>, is to find the main clusters of mass. The number of clusters is not known. But you know the dimensions of the bitmap. Sometimes several points within a cluster has more mass than the center of the next (in size) cluster. So what I want to do is go from the higher-mass points and remove points in the same cluster (points nearby).</p>
<p>When I tried this I ended up having to walk through parts of the list over and over again. I have a feeling I'm just stupid about it. How would you do it? Pseudo code or real code. Of course, if you can just take off where I left in that answer with Python code it's easier for me to experiment with it. </p>
<p>Next step is to figure out how many clusters there really are in the bitmap. I'm still struggling with defining that problem so I might return with a question about it.</p>
<p><strong>EDIT:</strong> I should clarify that I know that there's no "correct" answer to this question. And the name of the question is key. Phase one of the my clustering is done. <strong>Im in search of a fast, accurate-"enough" method of filtering away nearby points.</strong> </p>
<p>Let me know if you see how I can make the question clearer.</p>
| 0 | 2009-01-06T12:54:57Z | 416,609 | <p>It sounds to me like you're looking for the <a href="http://en.wikipedia.org/wiki/K_means" rel="nofollow">K-means</a> algorithm.</p>
| 4 | 2009-01-06T13:56:27Z | [
"python",
"algorithm",
"language-agnostic",
"bitmap",
"filtering"
]
|
Filtering away nearby points from a list | 416,406 | <p>I <a href="http://stackoverflow.com/questions/411837/finding-clusters-of-mass-in-a-matrix-bitmap#411855">half-answered a question about finding clusters of mass in a bitmap</a>. I say half-answered because I left it in a condition where I had all the points in the bitmap sorted by mass and left it to the reader to filter the list removing points from the same cluster. </p>
<p>Then when thinking about that step I found that the solution didn't jump out at me like I thought it would. So now I'm asking you guys for help. We have a list of points with masses like so (a Python list of tuples, but you can represent it as you see fit in any language):</p>
<pre><code>[ (6, 2, 6.1580555555555554),
(2, 1, 5.4861111111111107),
(1, 1, 4.6736111111111107),
(1, 4, 4.5938888888888885),
(2, 0, 4.54),
(1, 5, 4.4480555555555554),
(4, 7, 4.4480555555555554),
(5, 7, 4.4059637188208614),
(4, 8, 4.3659637188208613),
(1, 0, 4.3611111111111107),
(5, 8, 4.3342191043083904),
(5, 2, 4.119574829931973),
...
(8, 8, 0.27611111111111108),
(0, 8, 0.24138888888888888) ]
</code></pre>
<p>Each tuple is of the form:</p>
<pre><code>(x, y, mass)
</code></pre>
<p>Note that the list is sorted here. If your solution prefers to not have them sorted it's perfectly OK.</p>
<p>The challenge, <a href="http://stackoverflow.com/questions/411837/finding-clusters-of-mass-in-a-matrix-bitmap">if you recall</a>, is to find the main clusters of mass. The number of clusters is not known. But you know the dimensions of the bitmap. Sometimes several points within a cluster has more mass than the center of the next (in size) cluster. So what I want to do is go from the higher-mass points and remove points in the same cluster (points nearby).</p>
<p>When I tried this I ended up having to walk through parts of the list over and over again. I have a feeling I'm just stupid about it. How would you do it? Pseudo code or real code. Of course, if you can just take off where I left in that answer with Python code it's easier for me to experiment with it. </p>
<p>Next step is to figure out how many clusters there really are in the bitmap. I'm still struggling with defining that problem so I might return with a question about it.</p>
<p><strong>EDIT:</strong> I should clarify that I know that there's no "correct" answer to this question. And the name of the question is key. Phase one of the my clustering is done. <strong>Im in search of a fast, accurate-"enough" method of filtering away nearby points.</strong> </p>
<p>Let me know if you see how I can make the question clearer.</p>
| 0 | 2009-01-06T12:54:57Z | 417,034 | <p>Just so you know, you are asking for a solution to an <a href="http://en.wikipedia.org/wiki/Ill-posed" rel="nofollow">ill-posed problem: no definitive solution exists. That's fine...it just makes it more fun. Your problem is ill-posed mostly because you don't know how many clusters you want. Clustering is one of the key areas of machine learning</a> and there a quite a few approaches that have been developed over the years.</p>
<p>As Arachnid pointed out, the <a href="http://en.wikipedia.org/wiki/K_means" rel="nofollow">k-means</a> algorithm tends to be a good one and it's pretty easy to implement. The results depend critically on the initial guess made and on the number of desired clusters. To overcome the initial guess problem, it's common to run the algorithm many times with random initializations and pick the best result. You'll need to define what "best" means. One measure would be the mean squared distance of each point to its cluster center. If you want to automatically guess how many clusters there are, you should run the algorithm with a whole range of numbers of clusters. For any good "best" measure, more clusters will always look better than fewer, so you'll need a way to penalize having too many clusters. The <a href="http://en.wikipedia.org/wiki/Minimum_description_length" rel="nofollow">MDL</a> discussion on wikipedia is a good starting point. </p>
<p>K-means clustering is basically the simplest <a href="http://en.wikipedia.org/wiki/Mixture_model" rel="nofollow">mixture model</a>. Sometimes it's helpful to upgrade to a mixture of Gaussians learned by expectation maximization (described in the link just given). This can be more robust than k-means. It takes a little more effort to understand it, but when you do, it's not much harder than k-means to implement. </p>
<p>There are plenty of other <a href="http://en.wikipedia.org/wiki/Data_clustering" rel="nofollow">clustering techniques</a> such as agglomerative clustering and spectral clustering. Agglomerative clustering is pretty easy to implement, but choosing when to stop building the clusters can be tricky. If you do agglomerative clustering, you'll probably want to look at <a href="http://en.wikipedia.org/wiki/Kd-tree" rel="nofollow">kd trees</a> for faster nearest neighbor searches. smacl's answer describes one slightly different way of doing agglomerative clustering using a Voronoi diagram.</p>
<p>There are models that can automatically choose the number of clusters for you such as ones based on <a href="http://en.wikipedia.org/wiki/Latent_Dirichlet_allocation" rel="nofollow">Latent Dirichlet Allocation</a>, but they are a lot harder to understand an implement correctly. </p>
<p>You might also want to look at the <a href="http://www.wisdom.weizmann.ac.il/~deniss/vision_spring04/files/mean_shift/mean_shift.ppt" rel="nofollow">mean-shift</a> algorithm to see if it's closer to what you really want.</p>
| 5 | 2009-01-06T15:46:16Z | [
"python",
"algorithm",
"language-agnostic",
"bitmap",
"filtering"
]
|
Java Servlet Filter Equivalent in Ruby [on Rails] and PHP? | 417,158 | <p>Not sure if the terminology is correct, but are there rough equivalents to Java Servlet Filters in Ruby and PHP ? Are they actual concrete <em>classes</em> ?</p>
<p>I assume there is also a number of common web app libraries/frameworks in Python. Is there an equivalent there ?</p>
<p>Thanks.</p>
<p><strong>=== ADDENDUM ===</strong></p>
<p>On the good advice of <a href="http://stackoverflow.com/users/49993/kevin-davis">Kevin Davis</a>, I just want to quickly elaborate on what Java Servlet Filters are. It is basically an HTTP request interceptor. A chain of filters can be configured between the raw receipt of the request and the final destination of the request. The request parameters (and cookies, headers etc. etc.) are passed to the first filter in the chain and each filter does something with them (or not) and then passes them up the chain (or not. eg. a caching filter may simply return the result, bypassing the rest of the chain and the endpoint).</p>
<p>One of the advantages is the ability to modify or enhance the web app without touching the original endpoint code.</p>
<p>Cheers.</p>
| 1 | 2009-01-06T16:17:01Z | 420,249 | <p>In a typical <strong>Apache/PHP</strong> scenario, the answer is generally: No, there are no custom filters. However, there some solutions for problems solved with Java Servlet Filters:</p>
<ul>
<li>There are multiple collaborating <a href="http://httpd.apache.org/docs/2.2/howto/auth.html" rel="nofollow">access control modules</a></li>
<li>Compression can be set in <a href="http://php.net/manual/en/zlib.configuration.php#ini.zlib.output-compression" rel="nofollow">the php configuration</a></li>
</ul>
<p>You can create a <a href="http://httpd.apache.org/docs/2.2/howto/htaccess.html" rel="nofollow"><code>.htaccess</code> file</a> to set those properties for a directory and its subdirectories.</p>
| 0 | 2009-01-07T13:07:55Z | [
"java",
"php",
"python",
"ruby-on-rails",
"servlets"
]
|
Java Servlet Filter Equivalent in Ruby [on Rails] and PHP? | 417,158 | <p>Not sure if the terminology is correct, but are there rough equivalents to Java Servlet Filters in Ruby and PHP ? Are they actual concrete <em>classes</em> ?</p>
<p>I assume there is also a number of common web app libraries/frameworks in Python. Is there an equivalent there ?</p>
<p>Thanks.</p>
<p><strong>=== ADDENDUM ===</strong></p>
<p>On the good advice of <a href="http://stackoverflow.com/users/49993/kevin-davis">Kevin Davis</a>, I just want to quickly elaborate on what Java Servlet Filters are. It is basically an HTTP request interceptor. A chain of filters can be configured between the raw receipt of the request and the final destination of the request. The request parameters (and cookies, headers etc. etc.) are passed to the first filter in the chain and each filter does something with them (or not) and then passes them up the chain (or not. eg. a caching filter may simply return the result, bypassing the rest of the chain and the endpoint).</p>
<p>One of the advantages is the ability to modify or enhance the web app without touching the original endpoint code.</p>
<p>Cheers.</p>
| 1 | 2009-01-06T16:17:01Z | 453,350 | <blockquote>
<p>I assume there is also a number of
common web app libraries/frameworks in
Python. Is there an equivalent there ?</p>
</blockquote>
<p><strong>Django</strong> provides a framework of middleware hooks that can be used to alter input/output in request/response processing. See the <a href="http://docs.djangoproject.com/en/dev/topics/http/middleware/" rel="nofollow">Middleware documentation page</a> for more details.</p>
| 2 | 2009-01-17T14:09:04Z | [
"java",
"php",
"python",
"ruby-on-rails",
"servlets"
]
|
Java Servlet Filter Equivalent in Ruby [on Rails] and PHP? | 417,158 | <p>Not sure if the terminology is correct, but are there rough equivalents to Java Servlet Filters in Ruby and PHP ? Are they actual concrete <em>classes</em> ?</p>
<p>I assume there is also a number of common web app libraries/frameworks in Python. Is there an equivalent there ?</p>
<p>Thanks.</p>
<p><strong>=== ADDENDUM ===</strong></p>
<p>On the good advice of <a href="http://stackoverflow.com/users/49993/kevin-davis">Kevin Davis</a>, I just want to quickly elaborate on what Java Servlet Filters are. It is basically an HTTP request interceptor. A chain of filters can be configured between the raw receipt of the request and the final destination of the request. The request parameters (and cookies, headers etc. etc.) are passed to the first filter in the chain and each filter does something with them (or not) and then passes them up the chain (or not. eg. a caching filter may simply return the result, bypassing the rest of the chain and the endpoint).</p>
<p>One of the advantages is the ability to modify or enhance the web app without touching the original endpoint code.</p>
<p>Cheers.</p>
| 1 | 2009-01-06T16:17:01Z | 550,839 | <p><a href="http://api.rubyonrails.com/classes/ActionController/Filters/ClassMethods.html" rel="nofollow">Ruby on Rails has filters</a> that serve this purpose</p>
<p>A new feature is <a href="http://www.pathf.com/blogs/2009/02/its-only-rack-on-rails-but-i-like-it/" rel="nofollow">Rack Middleware</a>, which is similar to Django middleware</p>
| 0 | 2009-02-15T12:56:39Z | [
"java",
"php",
"python",
"ruby-on-rails",
"servlets"
]
|
Java Servlet Filter Equivalent in Ruby [on Rails] and PHP? | 417,158 | <p>Not sure if the terminology is correct, but are there rough equivalents to Java Servlet Filters in Ruby and PHP ? Are they actual concrete <em>classes</em> ?</p>
<p>I assume there is also a number of common web app libraries/frameworks in Python. Is there an equivalent there ?</p>
<p>Thanks.</p>
<p><strong>=== ADDENDUM ===</strong></p>
<p>On the good advice of <a href="http://stackoverflow.com/users/49993/kevin-davis">Kevin Davis</a>, I just want to quickly elaborate on what Java Servlet Filters are. It is basically an HTTP request interceptor. A chain of filters can be configured between the raw receipt of the request and the final destination of the request. The request parameters (and cookies, headers etc. etc.) are passed to the first filter in the chain and each filter does something with them (or not) and then passes them up the chain (or not. eg. a caching filter may simply return the result, bypassing the rest of the chain and the endpoint).</p>
<p>One of the advantages is the ability to modify or enhance the web app without touching the original endpoint code.</p>
<p>Cheers.</p>
| 1 | 2009-01-06T16:17:01Z | 550,856 | <p>In the PHP world, <a href="http://framework.zend.com/" rel="nofollow">Zend Framework</a> provides a plugin API for its front controller object that allows hooking of plugin objects between the pre-routing and post-dispatching phases. Although I didn't have a chance to work with Java servlets I assume this would match the descripton in your addendum. Anyway, this is not built into PHP, its framework dependent as with RoR or Django.</p>
| 0 | 2009-02-15T13:20:03Z | [
"java",
"php",
"python",
"ruby-on-rails",
"servlets"
]
|
Cross Platform SWF Playback with Python? | 417,159 | <p>I'm looking for different solutions to playing back SWF files on Windows, OSX and Linux using Python. Ideally I'd like to embed the player inside a wxPython frame/window.</p>
<p>One possibility I'm investigating is the Mozilla XPCOM framework since its used by FireFox to load the Flash plugin within the browser.</p>
| 3 | 2009-01-06T16:17:06Z | 425,445 | <p>Though I don't know how to embed a browser within a wxPython window, the following code might serve in a pinch (and will work cross-platform, assuming you're working in Python 2.5 or above):</p>
<pre><code>import webbrowser
webbrowser.open(your_swf_url)
</code></pre>
<p>It might be best to delegate this task to the browser anyway.</p>
| 2 | 2009-01-08T19:03:16Z | [
"python",
"cross-platform",
"flash",
"wxpython"
]
|
Cross Platform SWF Playback with Python? | 417,159 | <p>I'm looking for different solutions to playing back SWF files on Windows, OSX and Linux using Python. Ideally I'd like to embed the player inside a wxPython frame/window.</p>
<p>One possibility I'm investigating is the Mozilla XPCOM framework since its used by FireFox to load the Flash plugin within the browser.</p>
| 3 | 2009-01-06T16:17:06Z | 426,461 | <p>Have you considered <a href="http://www.onflex.org/ted/2008/02/why-adobe-air.php" rel="nofollow">Adobe AIR</a>? </p>
<p>Bruce Eckel said: <a href="http://www.artima.com/weblogs/viewpost.jsp?thread=208528" rel="nofollow">Try combining the power of Python with the polish of Adobe Flash to create a desktop application.</a></p>
| 3 | 2009-01-08T23:23:16Z | [
"python",
"cross-platform",
"flash",
"wxpython"
]
|
What does "|" sign mean in a Django template? | 417,265 | <p>I often see something like that:
<code>something.property|escape</code>
<hr />
<code>something</code> is an object, <code>property</code> is it's string property. <code>escape</code> - i don't know :)
<br />
What does this mean? And what min python version it is used in?</p>
<p><br /></p>
<p>EDIT: The question was asked wrongly, it said "What does | mean in Python", so the bitwise or answers are correct, but irrelevant, please do not downvote them</p>
| 1 | 2009-01-06T16:44:18Z | 417,273 | <p>It's a bitwise "or". It means escape if the property doesn't exist/is null.</p>
| -1 | 2009-01-06T16:46:54Z | [
"python",
"django",
"django-templates"
]
|
What does "|" sign mean in a Django template? | 417,265 | <p>I often see something like that:
<code>something.property|escape</code>
<hr />
<code>something</code> is an object, <code>property</code> is it's string property. <code>escape</code> - i don't know :)
<br />
What does this mean? And what min python version it is used in?</p>
<p><br /></p>
<p>EDIT: The question was asked wrongly, it said "What does | mean in Python", so the bitwise or answers are correct, but irrelevant, please do not downvote them</p>
| 1 | 2009-01-06T16:44:18Z | 417,299 | <p>obj.property|escape is the way to apply the <a href="http://docs.djangoproject.com/en/dev/ref/templates/builtins/#built-in-filter-reference" rel="nofollow">escape filter in a template</a>, which will HTML escape the string representation of that property.</p>
| 8 | 2009-01-06T16:55:04Z | [
"python",
"django",
"django-templates"
]
|
What does "|" sign mean in a Django template? | 417,265 | <p>I often see something like that:
<code>something.property|escape</code>
<hr />
<code>something</code> is an object, <code>property</code> is it's string property. <code>escape</code> - i don't know :)
<br />
What does this mean? And what min python version it is used in?</p>
<p><br /></p>
<p>EDIT: The question was asked wrongly, it said "What does | mean in Python", so the bitwise or answers are correct, but irrelevant, please do not downvote them</p>
| 1 | 2009-01-06T16:44:18Z | 417,630 | <p>The pipe character indicates that you want to send the results of the left hand side to the filter defined on the right side. The filter will modify the value in some way. </p>
<p>The 'escape' filter is just one of many.</p>
<p>The list of built in filters can be found here:
<a href="http://docs.djangoproject.com/en/dev/ref/templates/builtins/#built-in-filter-reference">Django Documentation - Built-in filters reference</a></p>
<p>In a django template the | character definitely does not mean the 'bitwise OR' operator.</p>
| 6 | 2009-01-06T18:27:44Z | [
"python",
"django",
"django-templates"
]
|
What does the â|â sign mean in Python? | 417,396 | <p><a href="http://stackoverflow.com/questions/417265/what-does-sign-mean-in-django">This question</a> originally asked (wrongly) what does "|" mean in Python, when the actual question was about Django. That question had a wonderful answer by Triptych I want to preserve. </p>
| 7 | 2009-01-06T17:18:20Z | 417,402 | <p>Bitwise OR</p>
| 0 | 2009-01-06T17:20:22Z | [
"python",
"syntax-rules"
]
|
What does the â|â sign mean in Python? | 417,396 | <p><a href="http://stackoverflow.com/questions/417265/what-does-sign-mean-in-django">This question</a> originally asked (wrongly) what does "|" mean in Python, when the actual question was about Django. That question had a wonderful answer by Triptych I want to preserve. </p>
| 7 | 2009-01-06T17:18:20Z | 417,438 | <p>In Python, the <code>'|'</code> operator is defined by default on integer types and set types. </p>
<p>If the two operands are integers, then it will perform a <a href="http://en.wikipedia.org/wiki/Bitwise_operation#OR">bitwise or</a>, which is a mathematical operation.</p>
<p>If the two operands are <code>set</code> types, the <code>'|'</code> operator will return the union of two sets.</p>
<pre><code>a = set([1,2,3])
b = set([2,3,4])
c = a|b # = set([1,2,3,4])
</code></pre>
<p>Additionally, authors may define operator behavior for custom types, so if <code>something.property</code> is a user-defined object, you should check that class definition for an <code>__or__()</code> method, which will then define the behavior in your code sample.</p>
<p>So, it's impossible to give you a precise answer without knowing the data types for the two operands, but <em>usually</em> it will be a bitwise or.</p>
| 16 | 2009-01-06T17:28:40Z | [
"python",
"syntax-rules"
]
|
What does the â|â sign mean in Python? | 417,396 | <p><a href="http://stackoverflow.com/questions/417265/what-does-sign-mean-in-django">This question</a> originally asked (wrongly) what does "|" mean in Python, when the actual question was about Django. That question had a wonderful answer by Triptych I want to preserve. </p>
| 7 | 2009-01-06T17:18:20Z | 1,986,034 | <p>It could also be "tricked" into a pipe like in unix shells, see here <a href="http://code.google.com/p/python-pipeline/" rel="nofollow">http://code.google.com/p/python-pipeline/</a></p>
| 0 | 2009-12-31T16:33:02Z | [
"python",
"syntax-rules"
]
|
How can I tell if an Expando subclass has a property defined? | 417,584 | <p>I'm creating an app that I want to have an expandable set of properties (each a RatingProperty) I also want to validate that any dynamic properties are of the RatingProperty type. </p>
<p>In the Expando documentation it says:</p>
<blockquote>
<p>Tip: If you want to validate a dynamic property value using a Property class, you can instantiate the Property class and call its validate() method on the value. </p>
</blockquote>
<p>So if I want to validate a dynamic property I need to know what the class's non-dynamic properties are. How can I ask my class what it's defined properties are?</p>
<p>I've considered creating a class method that takes a string and returns true if that string is in a list of property names that I create and maintain, but it seems like a hack. I've searched the Google for tips, but haven't had any luck.</p>
<p>Thanks,
Pat</p>
| 0 | 2009-01-06T18:14:01Z | 418,905 | <p>After a bit more research (damn you lazyweb!) I've found a solution that I think is acceptable: </p>
<p>A dynamic property can't be of a db subclassed property type. Thus, there are two distinct steps that must be taken. First you need to create an instance of your property class and validate your value: </p>
<pre><code>test = db.RatingProperty()
if test.validate(valueToSave):
#do your thing
</code></pre>
<p>Next you need to check if the property you want to save is a declared property:</p>
<pre><code>if valueToSaveKey not in myObject.properties():
#if not save it as desired
myObject.valueToSaveKey = valueToSave
</code></pre>
<p>The down side here is that the value you save isn't stored as the property type you want.</p>
| 1 | 2009-01-07T01:51:44Z | [
"python",
"google-app-engine"
]
|
How can I tell if an Expando subclass has a property defined? | 417,584 | <p>I'm creating an app that I want to have an expandable set of properties (each a RatingProperty) I also want to validate that any dynamic properties are of the RatingProperty type. </p>
<p>In the Expando documentation it says:</p>
<blockquote>
<p>Tip: If you want to validate a dynamic property value using a Property class, you can instantiate the Property class and call its validate() method on the value. </p>
</blockquote>
<p>So if I want to validate a dynamic property I need to know what the class's non-dynamic properties are. How can I ask my class what it's defined properties are?</p>
<p>I've considered creating a class method that takes a string and returns true if that string is in a list of property names that I create and maintain, but it seems like a hack. I've searched the Google for tips, but haven't had any luck.</p>
<p>Thanks,
Pat</p>
| 0 | 2009-01-06T18:14:01Z | 420,416 | <p>I may be misunderstanding your question, but if you have a list of properties you expect to find, why not just use a standard db.Model, instead of an Expando? You can add additional properties to a Model class, as long as you either provide a default or don't make them required.</p>
| 0 | 2009-01-07T14:07:47Z | [
"python",
"google-app-engine"
]
|
How can I tell if an Expando subclass has a property defined? | 417,584 | <p>I'm creating an app that I want to have an expandable set of properties (each a RatingProperty) I also want to validate that any dynamic properties are of the RatingProperty type. </p>
<p>In the Expando documentation it says:</p>
<blockquote>
<p>Tip: If you want to validate a dynamic property value using a Property class, you can instantiate the Property class and call its validate() method on the value. </p>
</blockquote>
<p>So if I want to validate a dynamic property I need to know what the class's non-dynamic properties are. How can I ask my class what it's defined properties are?</p>
<p>I've considered creating a class method that takes a string and returns true if that string is in a list of property names that I create and maintain, but it seems like a hack. I've searched the Google for tips, but haven't had any luck.</p>
<p>Thanks,
Pat</p>
| 0 | 2009-01-06T18:14:01Z | 4,505,283 | <p>It's actually quite easy!</p>
<p><a href="http://msdn.microsoft.com/en-us/library/system.dynamic.expandoobject.aspx" rel="nofollow">ExpandoObject</a> implements <code>(IDictionary<String, Object>)</code> so you just need to do this :</p>
<pre><code> dynamic person = new ExpandoObject();
person.FirstName = "Barack";
person.LastName = "Obama"
(((IDictionary<String, Object>)person).Keys
=> { "FirstName", "LastName" }
(((IDictionary<String, Object>)person).ContainsKey("FirstName")
=> true
</code></pre>
<p>Note: You need to explicitly cast to <code>(IDictionary<string, object></code> because ExpandoObject explicitly implements this interface - and the instance itself doesn't have <code>ContainsKey()</code> or <code>Keys</code>.</p>
<p>Don't expect this method to work with all dynamic objects - just ExpandoObject and anything else that implements this interface.</p>
| 0 | 2010-12-22T00:45:30Z | [
"python",
"google-app-engine"
]
|
How can I tell if an Expando subclass has a property defined? | 417,584 | <p>I'm creating an app that I want to have an expandable set of properties (each a RatingProperty) I also want to validate that any dynamic properties are of the RatingProperty type. </p>
<p>In the Expando documentation it says:</p>
<blockquote>
<p>Tip: If you want to validate a dynamic property value using a Property class, you can instantiate the Property class and call its validate() method on the value. </p>
</blockquote>
<p>So if I want to validate a dynamic property I need to know what the class's non-dynamic properties are. How can I ask my class what it's defined properties are?</p>
<p>I've considered creating a class method that takes a string and returns true if that string is in a list of property names that I create and maintain, but it seems like a hack. I've searched the Google for tips, but haven't had any luck.</p>
<p>Thanks,
Pat</p>
| 0 | 2009-01-06T18:14:01Z | 8,359,602 | <p><a href="http://code.google.com/appengine/docs/python/datastore/modelclass.html#Model_properties" rel="nofollow">http://code.google.com/appengine/docs/python/datastore/modelclass.html#Model_properties</a></p>
<p>db.Model has methods to find out all the properties on an instance.</p>
<p>The class exposes a list of Property objects: db.Model.properties()</p>
<p>The instance exposes the dynamic names only: instance.dynamic_properties()</p>
<p>You want to loop through the list and build Property objects, and run p.validate().</p>
<pre><code>for p_name in instance.dynamic_properties():
p = db.RatingProperty()
p.validate() # raises BadValueError, etc.
</code></pre>
| 1 | 2011-12-02T16:41:17Z | [
"python",
"google-app-engine"
]
|
How can I use Numerical Python with Python 2.6 | 417,664 | <p>I'm forced to upgrade to Python 2.6 and am having issues using Numerical Python (<a href="http://en.wikipedia.org/wiki/NumPy" rel="nofollow">NumPy</a>) with Python 2.6 in Windows. I'm getting the following error...</p>
<pre><code>Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
from numpy.core.numeric import array,dot,all
File "C:\svn\svn_urbansim\UrbanSimDev\Builds\working\urbansim\Tools\Python26\lib\site-packages\numpy\__init__.py", line 39, in <module>
import core
File "C:\svn\svn_urbansim\UrbanSimDev\Builds\working\urbansim\Tools\Python26\lib\site-packages\numpy\core\__init__.py", line 5, in <module>
import multiarray
ImportError: Module use of python25.dll conflicts with this version of Python.
</code></pre>
<p>It appears that the existing module is trying to use the <code>python25.dll</code> file. Is there any way I can tell it to use the <code>python26.dll</code> file instead without modifying the source code?</p>
| 2 | 2009-01-06T18:41:29Z | 417,674 | <p>How did you install it? NumPy doesn't currently have a Python 2.6 binary.</p>
<p>If you have <a href="http://en.wikipedia.org/wiki/LAPACK" rel="nofollow">LAPACK</a>/<a href="http://en.wikipedia.org/wiki/Automatically_Tuned_Linear_Algebra_Software" rel="nofollow">ATLAS</a>/<a href="http://en.wikipedia.org/wiki/Basic_Linear_Algebra_Subprograms" rel="nofollow">BLAS</a>, etc. and a development environment you should be able to compile numpy from sources. Otherwise I think you're stuck with using Python 2.5 on Windows if you need NumPy.</p>
<p>The next version of NumPy should have a 2.6 binary, and it's likely to be out within the next month or so.</p>
<p>[Edit]: It appears that a pygame developer created a NumPy 1.2.1 binary for Python 2.6 on Windows, available <a href="http://www.mail-archive.com/numpy-discussion@scipy.org/msg14552.html" rel="nofollow">here</a>.</p>
| 9 | 2009-01-06T18:45:16Z | [
"python",
"windows",
"numpy"
]
|
How can I use Numerical Python with Python 2.6 | 417,664 | <p>I'm forced to upgrade to Python 2.6 and am having issues using Numerical Python (<a href="http://en.wikipedia.org/wiki/NumPy" rel="nofollow">NumPy</a>) with Python 2.6 in Windows. I'm getting the following error...</p>
<pre><code>Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
from numpy.core.numeric import array,dot,all
File "C:\svn\svn_urbansim\UrbanSimDev\Builds\working\urbansim\Tools\Python26\lib\site-packages\numpy\__init__.py", line 39, in <module>
import core
File "C:\svn\svn_urbansim\UrbanSimDev\Builds\working\urbansim\Tools\Python26\lib\site-packages\numpy\core\__init__.py", line 5, in <module>
import multiarray
ImportError: Module use of python25.dll conflicts with this version of Python.
</code></pre>
<p>It appears that the existing module is trying to use the <code>python25.dll</code> file. Is there any way I can tell it to use the <code>python26.dll</code> file instead without modifying the source code?</p>
| 2 | 2009-01-06T18:41:29Z | 823,331 | <p><a href="http://sourceforge.net/project/downloading.php?group%5Fid=1369&filename=numpy-1.3.0-win32-superpack-python2.6.exe&a=35708818" rel="nofollow">NumPy 1.3.0 is available for Python 2.6 now</a>.</p>
| 3 | 2009-05-05T04:23:14Z | [
"python",
"windows",
"numpy"
]
|
Python: C++-like stream input | 417,703 | <p>Is there a pythonic way of reading - say - mixed integer and char input without reading the whole input at once and without worrying about linebreaks? For example I have a file with whitespace-separated data of which I only know that there are x integers, then y chars and then z more integers. I don't want to assume anything about linebreaks.</p>
<p>I mean something as mindless as the following in C++:</p>
<p>...</p>
<pre><code>int i, buf;
char cbuf;
vector<int> X, Z;
vector<int> Y;
for (i = 0; i < x; i++) {
cin >> buf;
X.push_back(buf);
}
for (i = 0; i < y; i++) {
cin >> cbuf;
Y.push_back(cbuf);
}
for (i = 0; i < z; i++) {
cin >> buf;
Z.push_back(buf);
}
</code></pre>
<p>EDIT: i forgot to say that I'd like it to behave well under live input from console as well - i.e. there should be no need to press ctrl+d before getting tokens and the function should be able to return them as soon as a line has been entered. :)</p>
<p>Best regards,
Artur Gajowy</p>
| 2 | 2009-01-06T18:55:14Z | 417,741 | <p>Like this?</p>
<pre><code>>>> data = "1 2 3 4 5 6 abcdefg 9 8 7 6 5 4 3"
</code></pre>
<p>For example, we might get this with <code>data= someFile.read()</code></p>
<pre><code>>>> fields= data.split()
>>> x= map(int,fields[:6])
>>> y= fields[6]
>>> z= map(int,fields[7:])
</code></pre>
<p>Results</p>
<pre><code>>>> x
[1, 2, 3, 4, 5, 6]
>>> y
'abcdefg'
>>> z
[9, 8, 7, 6, 5, 4, 3]
</code></pre>
| 2 | 2009-01-06T19:13:09Z | [
"c++",
"input",
"stream",
"python"
]
|
Python: C++-like stream input | 417,703 | <p>Is there a pythonic way of reading - say - mixed integer and char input without reading the whole input at once and without worrying about linebreaks? For example I have a file with whitespace-separated data of which I only know that there are x integers, then y chars and then z more integers. I don't want to assume anything about linebreaks.</p>
<p>I mean something as mindless as the following in C++:</p>
<p>...</p>
<pre><code>int i, buf;
char cbuf;
vector<int> X, Z;
vector<int> Y;
for (i = 0; i < x; i++) {
cin >> buf;
X.push_back(buf);
}
for (i = 0; i < y; i++) {
cin >> cbuf;
Y.push_back(cbuf);
}
for (i = 0; i < z; i++) {
cin >> buf;
Z.push_back(buf);
}
</code></pre>
<p>EDIT: i forgot to say that I'd like it to behave well under live input from console as well - i.e. there should be no need to press ctrl+d before getting tokens and the function should be able to return them as soon as a line has been entered. :)</p>
<p>Best regards,
Artur Gajowy</p>
| 2 | 2009-01-06T18:55:14Z | 417,773 | <p>if you don't want to read in a whole line at a time, you might want to try something like this:</p>
<pre><code>def read_tokens(file):
while True:
token = []
while True:
c = file.read(1)
if c not in ['', ' ', '\t', '\n']:
token.append(c)
elif c in [' ', '\t', '\n']:
yield ''.join(token)
break
elif c == '':
yield ''.join(token)
raise StopIteration
</code></pre>
<p>that should generate each whitespace-delimited token in the file reading one character at a time. from there you should be able to convert them to whatever type they should be. the whitespace can probably be taken care of better, too.</p>
| 3 | 2009-01-06T19:24:52Z | [
"c++",
"input",
"stream",
"python"
]
|
Python: C++-like stream input | 417,703 | <p>Is there a pythonic way of reading - say - mixed integer and char input without reading the whole input at once and without worrying about linebreaks? For example I have a file with whitespace-separated data of which I only know that there are x integers, then y chars and then z more integers. I don't want to assume anything about linebreaks.</p>
<p>I mean something as mindless as the following in C++:</p>
<p>...</p>
<pre><code>int i, buf;
char cbuf;
vector<int> X, Z;
vector<int> Y;
for (i = 0; i < x; i++) {
cin >> buf;
X.push_back(buf);
}
for (i = 0; i < y; i++) {
cin >> cbuf;
Y.push_back(cbuf);
}
for (i = 0; i < z; i++) {
cin >> buf;
Z.push_back(buf);
}
</code></pre>
<p>EDIT: i forgot to say that I'd like it to behave well under live input from console as well - i.e. there should be no need to press ctrl+d before getting tokens and the function should be able to return them as soon as a line has been entered. :)</p>
<p>Best regards,
Artur Gajowy</p>
| 2 | 2009-01-06T18:55:14Z | 417,893 | <p>How about a small generator function that returns a stream of tokens and behaves like <code>cin</code>:</p>
<pre><code>def read_tokens(f):
for line in f:
for token in line.split():
yield token
x = y = z = 5 # for simplicity: 5 ints, 5 char tokens, 5 ints
f = open('data.txt', 'r')
tokens = read_tokens(f)
X = []
for i in xrange(x):
X.append(int(tokens.next()))
Y = []
for i in xrange(y):
Y.append(tokens.next())
Z = []
for i in xrange(z):
Z.append(int(tokens.next()))
</code></pre>
| 6 | 2009-01-06T20:02:33Z | [
"c++",
"input",
"stream",
"python"
]
|
Python: C++-like stream input | 417,703 | <p>Is there a pythonic way of reading - say - mixed integer and char input without reading the whole input at once and without worrying about linebreaks? For example I have a file with whitespace-separated data of which I only know that there are x integers, then y chars and then z more integers. I don't want to assume anything about linebreaks.</p>
<p>I mean something as mindless as the following in C++:</p>
<p>...</p>
<pre><code>int i, buf;
char cbuf;
vector<int> X, Z;
vector<int> Y;
for (i = 0; i < x; i++) {
cin >> buf;
X.push_back(buf);
}
for (i = 0; i < y; i++) {
cin >> cbuf;
Y.push_back(cbuf);
}
for (i = 0; i < z; i++) {
cin >> buf;
Z.push_back(buf);
}
</code></pre>
<p>EDIT: i forgot to say that I'd like it to behave well under live input from console as well - i.e. there should be no need to press ctrl+d before getting tokens and the function should be able to return them as soon as a line has been entered. :)</p>
<p>Best regards,
Artur Gajowy</p>
| 2 | 2009-01-06T18:55:14Z | 418,257 | <p>How's this? Building on heikogerlach's excellent <code>read_tokens</code>.</p>
<pre><code>def read_tokens(f):
for line in f:
for token in line.split():
yield token
</code></pre>
<p>We can do things like the following to pick up 6 numbers, 7 characters and 6 numbers.</p>
<pre><code>fi = read_tokens(data)
x= [ int(fi.next()) for i in xrange(6) ]
y= [ fi.next() for i in xrange(7) ]
z= [ int(fi.next()) for i in xrange(6) ]
</code></pre>
| 0 | 2009-01-06T21:31:22Z | [
"c++",
"input",
"stream",
"python"
]
|
Process size in XP from Python | 417,763 | <p>I have a python script that can approach the 2 GB process limit under Windows XP. On a machine with 2 GB physical memory, that can pretty much lock up the machine, even if the Python script is running at below normal priority.</p>
<p>Is there a way in Python to find out my own process size?</p>
<p>Thanks,
Gerry</p>
| 5 | 2009-01-06T19:22:11Z | 418,533 | <p>try:</p>
<pre><code>import win32process
print win32process.GetProcessMemoryInfo(win32process.GetCurrentProcess())
</code></pre>
| 2 | 2009-01-06T23:00:19Z | [
"python",
"windows-xp"
]
|
Process size in XP from Python | 417,763 | <p>I have a python script that can approach the 2 GB process limit under Windows XP. On a machine with 2 GB physical memory, that can pretty much lock up the machine, even if the Python script is running at below normal priority.</p>
<p>Is there a way in Python to find out my own process size?</p>
<p>Thanks,
Gerry</p>
| 5 | 2009-01-06T19:22:11Z | 4,229,753 | <p>By using psutil <a href="https://github.com/giampaolo/psutil" rel="nofollow">https://github.com/giampaolo/psutil</a> :</p>
<pre><code>>>> import psutil, os
>>> p = psutil.Process(os.getpid())
>>> p.memory_info()
meminfo(rss=6971392, vms=47755264)
>>> p.memory_percent()
0.16821255914801228
>>>
</code></pre>
| 1 | 2010-11-19T21:55:33Z | [
"python",
"windows-xp"
]
|
Process size in XP from Python | 417,763 | <p>I have a python script that can approach the 2 GB process limit under Windows XP. On a machine with 2 GB physical memory, that can pretty much lock up the machine, even if the Python script is running at below normal priority.</p>
<p>Is there a way in Python to find out my own process size?</p>
<p>Thanks,
Gerry</p>
| 5 | 2009-01-06T19:22:11Z | 4,229,975 | <p>Rather than worrying about limiting your process size at runtime, it might be better to figure out if all the pieces of data that you're currently storing in memory truly need to be in memory at all times.</p>
<p>You probably have plenty of disk space, and simply by creating some temporary files (see the <a href="http://docs.python.org/library/tempfile.html" rel="nofollow">tempfile module</a>) there should be ample opportunity to write any data you are no longer using for the current calculation to disk. You can then read it back in later when/if you need it again. This is (simplistically) how many databases work.</p>
<p>While disk is considered "slow" in a computational sense, it is still very fast and it is an extremely useful tool when working with large data sets. And since you are already setting the process priority to "Below Normal" it doesn't sound like speed should be a serious issue for you anyway, whereas the memory clearly is.</p>
| 0 | 2010-11-19T22:34:29Z | [
"python",
"windows-xp"
]
|
Why does Python's string.printable contains unprintable characters? | 418,176 | <p>I have two String.printable mysteries in the one question.</p>
<p>First, in Python 2.6:</p>
<pre><code>>>> string.printable
'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c'
</code></pre>
<p>Look at the end of the string, and you'll find '\x0b\x0c' sticking out like a sore-thumb. Why are they there? I am using a machine set to Australian settings, so there shouldn't be any accented characters or the like.</p>
<p>Next, try running this code:</p>
<pre><code>for x in string.printable: print x,
print
for x in string.printable: print x
</code></pre>
<p>The first line successfully prints all the characters separated by a space. The two odd characters turn out as the Male and Female symbols.</p>
<p>The second line successfully prints all the characters EXCEPT THE LAST separated by a line feed. The Male symbol prints; the female symbol is replaced with a missing character (a box).</p>
<p>I'm sure Python wasn't intended to be gender-biased, so what gives with the difference?</p>
| 12 | 2009-01-06T21:10:31Z | 418,200 | <p>There is a difference in "printable" for "can be displayed on your screen". Your terminal displays the low ascii printer control codes 0x0B and 0x0C as the male and female symbols because that is what those indices in your font contain. Those characters are more accurately described as the Vertical Tabulator and Form Feed characters. These two characters, along with \t \r and \n, are all printable, and do well defined things on a printer.</p>
| 25 | 2009-01-06T21:15:36Z | [
"python",
"character-encoding"
]
|
Why does Python's string.printable contains unprintable characters? | 418,176 | <p>I have two String.printable mysteries in the one question.</p>
<p>First, in Python 2.6:</p>
<pre><code>>>> string.printable
'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c'
</code></pre>
<p>Look at the end of the string, and you'll find '\x0b\x0c' sticking out like a sore-thumb. Why are they there? I am using a machine set to Australian settings, so there shouldn't be any accented characters or the like.</p>
<p>Next, try running this code:</p>
<pre><code>for x in string.printable: print x,
print
for x in string.printable: print x
</code></pre>
<p>The first line successfully prints all the characters separated by a space. The two odd characters turn out as the Male and Female symbols.</p>
<p>The second line successfully prints all the characters EXCEPT THE LAST separated by a line feed. The Male symbol prints; the female symbol is replaced with a missing character (a box).</p>
<p>I'm sure Python wasn't intended to be gender-biased, so what gives with the difference?</p>
| 12 | 2009-01-06T21:10:31Z | 418,445 | <p>From within cmd.exe:</p>
<pre><code>>>> print '\x0b'
â
>>> print '\x0c'
â
>>> print '\f' # form feed
â
>>> print '\v' # vertical tab
â
>>>
</code></pre>
<p>Inside Emacs:</p>
<pre><code>>>> print '\f\v'
^L^K
</code></pre>
<p>Here's an excerpt from <a href="http://docs.sun.com/app/docs/doc/819-2252/formats-5?a=view">formats(5)</a>' man page:</p>
<pre>
| Sequence | Character | Terminal Action |
|----------+--------------+---------------------------------------------|
| \f | form-feed | Moves the printing position to the initial |
| | | printing position of the next logical page. |
| \v | vertical-tab | Moves the printing position to the start of |
| | | the next vertical tab position. If there |
| | | are no more vertical tab positions left on |
| | | the page, the behavior is undefined. |
</pre>
| 6 | 2009-01-06T22:27:59Z | [
"python",
"character-encoding"
]
|
How to check that a path has a sticky bit in python? | 418,204 | <p>How to check with python if a path has the sticky bit set?</p>
| 1 | 2009-01-06T21:16:59Z | 418,240 | <p><a href="http://docs.python.org/library/os.html#os.stat" rel="nofollow">os.stat()</a> will return a tupple of information about the file. The first item will be the mode. You would then be able to use some bit arithmetic to get for the sticky bit. The sticky bit has an octal value of 1000.</p>
| 2 | 2009-01-06T21:25:43Z | [
"python"
]
|
How to check that a path has a sticky bit in python? | 418,204 | <p>How to check with python if a path has the sticky bit set?</p>
| 1 | 2009-01-06T21:16:59Z | 418,243 | <pre><code>import os
def is_sticky(path):
return os.stat(path).st_mode & 01000 == 01000
</code></pre>
| 7 | 2009-01-06T21:26:05Z | [
"python"
]
|
How to convert XML to objects? | 418,497 | <p>I need to load an XML file and put the contents into an object-oriented structure. I want to take this:</p>
<pre><code><main>
<object1 attr="name">content</object>
</main>
</code></pre>
<p>and turn it into something like this:</p>
<pre><code>main
main.object1 = "content"
main.object1.attr = "name"
</code></pre>
<p>It'll have a more complicated structure than that and I can't hard code the element names. The names need to be collected when parsing and used as the object properties.</p>
<p>Any thoughts on what would be the best way to go about this?</p>
| 19 | 2009-01-06T22:47:14Z | 418,534 | <p>How about this</p>
<p><a href="http://evanjones.ca/software/simplexmlparse.html" rel="nofollow">http://evanjones.ca/software/simplexmlparse.html</a></p>
| 1 | 2009-01-06T23:00:31Z | [
"python",
"xml"
]
|
How to convert XML to objects? | 418,497 | <p>I need to load an XML file and put the contents into an object-oriented structure. I want to take this:</p>
<pre><code><main>
<object1 attr="name">content</object>
</main>
</code></pre>
<p>and turn it into something like this:</p>
<pre><code>main
main.object1 = "content"
main.object1.attr = "name"
</code></pre>
<p>It'll have a more complicated structure than that and I can't hard code the element names. The names need to be collected when parsing and used as the object properties.</p>
<p>Any thoughts on what would be the best way to go about this?</p>
| 19 | 2009-01-06T22:47:14Z | 418,587 | <p>If googling around for a code-generator doesn't work, you could write your own that uses XML as input and outputs objects in your language of choice.</p>
<p>It's not terribly difficult, however the three step process of Parse XML, Generate Code, Compile/Execute Script does making debugging a bit harder.</p>
| 0 | 2009-01-06T23:18:48Z | [
"python",
"xml"
]
|
How to convert XML to objects? | 418,497 | <p>I need to load an XML file and put the contents into an object-oriented structure. I want to take this:</p>
<pre><code><main>
<object1 attr="name">content</object>
</main>
</code></pre>
<p>and turn it into something like this:</p>
<pre><code>main
main.object1 = "content"
main.object1.attr = "name"
</code></pre>
<p>It'll have a more complicated structure than that and I can't hard code the element names. The names need to be collected when parsing and used as the object properties.</p>
<p>Any thoughts on what would be the best way to go about this?</p>
| 19 | 2009-01-06T22:47:14Z | 418,720 | <p>There are three common XML parsers for python: xml.dom.minidom, elementree, and BeautifulSoup.</p>
<p>IMO, BeautifulSoup is by far the best. </p>
<p><a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">http://www.crummy.com/software/BeautifulSoup/</a></p>
| 0 | 2009-01-07T00:09:03Z | [
"python",
"xml"
]
|
How to convert XML to objects? | 418,497 | <p>I need to load an XML file and put the contents into an object-oriented structure. I want to take this:</p>
<pre><code><main>
<object1 attr="name">content</object>
</main>
</code></pre>
<p>and turn it into something like this:</p>
<pre><code>main
main.object1 = "content"
main.object1.attr = "name"
</code></pre>
<p>It'll have a more complicated structure than that and I can't hard code the element names. The names need to be collected when parsing and used as the object properties.</p>
<p>Any thoughts on what would be the best way to go about this?</p>
| 19 | 2009-01-06T22:47:14Z | 418,728 | <p>I've been recommending this more than once today, but try <a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">Beautiful Soup</a> (easy_install BeautifulSoup).</p>
<pre><code>from BeautifulSoup import BeautifulSoup
xml = """
<main>
<object attr="name">content</object>
</main>
"""
soup = BeautifulSoup(xml)
# look in the main node for object's with attr=name, optionally look up attrs with regex
my_objects = soup.main.findAll("object", attrs={'attr':'name'})
for my_object in my_objects:
# this will print a list of the contents of the tag
print my_object.contents
# if only text is inside the tag you can use this
# print tag.string
</code></pre>
| 7 | 2009-01-07T00:15:27Z | [
"python",
"xml"
]
|
How to convert XML to objects? | 418,497 | <p>I need to load an XML file and put the contents into an object-oriented structure. I want to take this:</p>
<pre><code><main>
<object1 attr="name">content</object>
</main>
</code></pre>
<p>and turn it into something like this:</p>
<pre><code>main
main.object1 = "content"
main.object1.attr = "name"
</code></pre>
<p>It'll have a more complicated structure than that and I can't hard code the element names. The names need to be collected when parsing and used as the object properties.</p>
<p>Any thoughts on what would be the best way to go about this?</p>
| 19 | 2009-01-06T22:47:14Z | 418,823 | <pre><code>#@Stephen:
#"can't hardcode the element names, so I need to collect them
#at parse and use them somehow as the object names."
#I don't think thats possible. Instead you can do this.
#this will help you getting any object with a required name.
import BeautifulSoup
class Coll(object):
"""A class which can hold your Foo clas objects
and retrieve them easily when you want
abstracting the storage and retrieval logic
"""
def __init__(self):
self.foos={}
def add(self, fooobj):
self.foos[fooobj.name]=fooobj
def get(self, name):
return self.foos[name]
class Foo(object):
"""The required class
"""
def __init__(self, name, attr1=None, attr2=None):
self.name=name
self.attr1=attr1
self.attr2=attr2
s="""<main>
<object name="somename">
<attr name="attr1">value1</attr>
<attr name="attr2">value2</attr>
</object>
<object name="someothername">
<attr name="attr1">value3</attr>
<attr name="attr2">value4</attr>
</object>
</main>
"""
</code></pre>
<p>#</p>
<pre><code>soup=BeautifulSoup.BeautifulSoup(s)
bars=Coll()
for each in soup.findAll('object'):
bar=Foo(each['name'])
attrs=each.findAll('attr')
for attr in attrs:
setattr(bar, attr['name'], attr.renderContents())
bars.add(bar)
#retrieve objects by name
print bars.get('somename').__dict__
print '\n\n', bars.get('someothername').__dict__
</code></pre>
<p>output</p>
<pre><code>{'attr2': 'value2', 'name': u'somename', 'attr1': 'value1'}
{'attr2': 'value4', 'name': u'someothername', 'attr1': 'value3'}
</code></pre>
| 0 | 2009-01-07T01:06:09Z | [
"python",
"xml"
]
|
How to convert XML to objects? | 418,497 | <p>I need to load an XML file and put the contents into an object-oriented structure. I want to take this:</p>
<pre><code><main>
<object1 attr="name">content</object>
</main>
</code></pre>
<p>and turn it into something like this:</p>
<pre><code>main
main.object1 = "content"
main.object1.attr = "name"
</code></pre>
<p>It'll have a more complicated structure than that and I can't hard code the element names. The names need to be collected when parsing and used as the object properties.</p>
<p>Any thoughts on what would be the best way to go about this?</p>
| 19 | 2009-01-06T22:47:14Z | 418,854 | <p>David Mertz's <a href="http://www.xml.com/pub/a/2003/07/02/py-xml.html" rel="nofollow">gnosis.xml.objectify</a> would seem to do this for you. Documentation's a bit hard to come by, but there are a few IBM articles on it, including <a href="http://www.ibm.com/developerworks/xml/library/x-matters39.html" rel="nofollow">this one</a>.</p>
<pre><code>from gnosis.xml import objectify
xml = "<root><nodes><node>node 1</node><node>node 2</node></nodes></root>"
root = objectify.make_instance(xml)
print root.nodes.node[0].PCDATA # node 1
print root.nodes.node[1].PCDATA # node 2
</code></pre>
<p>Creating xml from objects in this way is a different matter, though.</p>
| 3 | 2009-01-07T01:21:22Z | [
"python",
"xml"
]
|
How to convert XML to objects? | 418,497 | <p>I need to load an XML file and put the contents into an object-oriented structure. I want to take this:</p>
<pre><code><main>
<object1 attr="name">content</object>
</main>
</code></pre>
<p>and turn it into something like this:</p>
<pre><code>main
main.object1 = "content"
main.object1.attr = "name"
</code></pre>
<p>It'll have a more complicated structure than that and I can't hard code the element names. The names need to be collected when parsing and used as the object properties.</p>
<p>Any thoughts on what would be the best way to go about this?</p>
| 19 | 2009-01-06T22:47:14Z | 419,232 | <p>It's worth to have a look at <a href="http://lxml.de/objectify.html">http://lxml.de/objectify.html</a></p>
<pre><code>>>> xml = """<main>
... <object1 attr="name">content</object1>
... <object1 attr="foo">contenbar</object1>
... <test>me</test>
... </main>"""
>>> from lxml import objectify
>>> main = objectify.fromstring(xml)
>>> main.object1[0]
'content'
>>> main.object1[1]
'contenbar'
>>> main.object1[0].get("attr")
'name'
>>> main.test
'me'
</code></pre>
<p>Or the other way around to build xml structures:</p>
<pre><code>>>> item = objectify.Element("item")
>>> item.title = "Best of python"
>>> item.price = 17.98
>>> item.price.set("currency", "EUR")
>>> order = objectify.Element("order")
>>> order.append(item)
>>> order.item.quantity = 3
>>> order.price = sum(item.price * item.quantity
... for item in order.item)
>>> import lxml.etree
>>> print lxml.etree.tostring(order, pretty_print=True)
<order>
<item>
<title>Best of python</title>
<price currency="EUR">17.98</price>
<quantity>3</quantity>
</item>
<price>53.94</price>
</order>
</code></pre>
| 31 | 2009-01-07T04:51:26Z | [
"python",
"xml"
]
|
Are there any graph/plotting/anything-like-that libraries for Python 3.0? | 418,835 | <p>As per the title. I am trying to create a simple scater plot, but haven't found any Python 3.0 libraries that can do it. Note, this isn't for a website, so the web ones are a bit useless.</p>
| 3 | 2009-01-07T01:12:41Z | 418,858 | <p>Have you looked at the Google Chart Wrapper?</p>
<p><a href="http://pypi.python.org/pypi/GChartWrapper/0.7" rel="nofollow">http://pypi.python.org/pypi/GChartWrapper/0.7</a></p>
| 0 | 2009-01-07T01:22:17Z | [
"python",
"python-3.x",
"plot",
"graphing",
"scatter-plot"
]
|
Are there any graph/plotting/anything-like-that libraries for Python 3.0? | 418,835 | <p>As per the title. I am trying to create a simple scater plot, but haven't found any Python 3.0 libraries that can do it. Note, this isn't for a website, so the web ones are a bit useless.</p>
| 3 | 2009-01-07T01:12:41Z | 419,538 | <p>I would call <a href="http://gnuplot-py.sourceforge.net" rel="nofollow">Gnuplot</a> from Python. No need to reinvent the wheel in Python, Gnuplot is already there and already has a Python interface.</p>
| 0 | 2009-01-07T08:10:37Z | [
"python",
"python-3.x",
"plot",
"graphing",
"scatter-plot"
]
|
Are there any graph/plotting/anything-like-that libraries for Python 3.0? | 418,835 | <p>As per the title. I am trying to create a simple scater plot, but haven't found any Python 3.0 libraries that can do it. Note, this isn't for a website, so the web ones are a bit useless.</p>
| 3 | 2009-01-07T01:12:41Z | 421,947 | <p>Maybe you can use Python Imaging Library (PIL).
Also have a look at PyX, but this library is meant to output to PDF, ...</p>
| 1 | 2009-01-07T20:32:30Z | [
"python",
"python-3.x",
"plot",
"graphing",
"scatter-plot"
]
|
Are there any graph/plotting/anything-like-that libraries for Python 3.0? | 418,835 | <p>As per the title. I am trying to create a simple scater plot, but haven't found any Python 3.0 libraries that can do it. Note, this isn't for a website, so the web ones are a bit useless.</p>
| 3 | 2009-01-07T01:12:41Z | 467,124 | <p>The GChartWrapper (<a href="http://pypi.python.org/pypi/GChartWrapper/0.7" rel="nofollow">http://pypi.python.org/pypi/GChartWrapper/0.7</a>) does work for py3k</p>
| 1 | 2009-01-21T21:36:59Z | [
"python",
"python-3.x",
"plot",
"graphing",
"scatter-plot"
]
|
Are there any graph/plotting/anything-like-that libraries for Python 3.0? | 418,835 | <p>As per the title. I am trying to create a simple scater plot, but haven't found any Python 3.0 libraries that can do it. Note, this isn't for a website, so the web ones are a bit useless.</p>
| 3 | 2009-01-07T01:12:41Z | 8,732,336 | <p>The current <a href="https://github.com/matplotlib/matplotlib" rel="nofollow">development version of matplotlib</a> should work on Python 3.</p>
| 0 | 2012-01-04T18:56:23Z | [
"python",
"python-3.x",
"plot",
"graphing",
"scatter-plot"
]
|
Pythonic equivalent of unshift or redo? | 418,915 | <p>I'm learning Python, and I have a situation where I want to consume items from an iterator. The tricky part is that under certain conditions, I want to "un-iterate." That is, put an item back onto the front of the iterator before I loop.</p>
<p>For example, suppose I'm picking apples from a tree. My fruit basket can only hold 10kg before it needs to be emptied. But I have to pick each apple before I can weigh it and determine if this apple would exceed the capacity of the basket.</p>
<p>In a language like Perl, I could <code>unshift()</code> the apple back onto the tree, and then let the loop expression re-pick the apple:</p>
<pre><code>while ($apple = shift(@tree)) {
$wt = weight($apple);
if ($wt + weight(@basket) > 10) {
send(@basket);
@basket = ();
unshift(@tree, $apple);
} else {
push(@basket, $element);
}
}
</code></pre>
<p>Or else I can also use <code>redo</code>, which resumes processing at the top of block, without evaluating the loop expression. So the same apple can be re-processed, after the basket has been emptied.</p>
<pre><code>while ($apple = shift(@tree)) {
$wt = weight($apple);
if ($wt + weight(@basket) > 10) {
send(@basket);
@basket = ();
redo;
} else {
push(@basket, $apple);
}
}
</code></pre>
<p>What would be the most <strong>pythonic</strong> solution for this kind of problem?</p>
| 12 | 2009-01-07T01:59:07Z | 418,946 | <p>Why bother with unshifting when the else clause should always occur?</p>
<pre><code>for apple in tree:
if (apple.weight + basket.weight) > 10:
send(basket)
basket.clear()
basket.add(apple)
</code></pre>
<p>Anyway, I'm fairly certain that Python doesn't have the sort of behavior you're looking for.</p>
| 13 | 2009-01-07T02:12:11Z | [
"python",
"redo"
]
|
Pythonic equivalent of unshift or redo? | 418,915 | <p>I'm learning Python, and I have a situation where I want to consume items from an iterator. The tricky part is that under certain conditions, I want to "un-iterate." That is, put an item back onto the front of the iterator before I loop.</p>
<p>For example, suppose I'm picking apples from a tree. My fruit basket can only hold 10kg before it needs to be emptied. But I have to pick each apple before I can weigh it and determine if this apple would exceed the capacity of the basket.</p>
<p>In a language like Perl, I could <code>unshift()</code> the apple back onto the tree, and then let the loop expression re-pick the apple:</p>
<pre><code>while ($apple = shift(@tree)) {
$wt = weight($apple);
if ($wt + weight(@basket) > 10) {
send(@basket);
@basket = ();
unshift(@tree, $apple);
} else {
push(@basket, $element);
}
}
</code></pre>
<p>Or else I can also use <code>redo</code>, which resumes processing at the top of block, without evaluating the loop expression. So the same apple can be re-processed, after the basket has been emptied.</p>
<pre><code>while ($apple = shift(@tree)) {
$wt = weight($apple);
if ($wt + weight(@basket) > 10) {
send(@basket);
@basket = ();
redo;
} else {
push(@basket, $apple);
}
}
</code></pre>
<p>What would be the most <strong>pythonic</strong> solution for this kind of problem?</p>
| 12 | 2009-01-07T01:59:07Z | 418,964 | <p>There is no way general way to push a value into an iterator in python. A stack or linked list is better suited to that.</p>
<p>If you're iterating over a list or something, of course you can add the item manually back to the list. But you can also iterate over objects which can't be manipulated in such a way.</p>
<p>If you want to use python to implement that algorithm, you'll have to choose a data structure that allows the operations you want to use. I suggest the <code>.push()</code> and <code>.pop()</code> methods which let you treat lists as stacks.</p>
| -2 | 2009-01-07T02:18:04Z | [
"python",
"redo"
]
|
Pythonic equivalent of unshift or redo? | 418,915 | <p>I'm learning Python, and I have a situation where I want to consume items from an iterator. The tricky part is that under certain conditions, I want to "un-iterate." That is, put an item back onto the front of the iterator before I loop.</p>
<p>For example, suppose I'm picking apples from a tree. My fruit basket can only hold 10kg before it needs to be emptied. But I have to pick each apple before I can weigh it and determine if this apple would exceed the capacity of the basket.</p>
<p>In a language like Perl, I could <code>unshift()</code> the apple back onto the tree, and then let the loop expression re-pick the apple:</p>
<pre><code>while ($apple = shift(@tree)) {
$wt = weight($apple);
if ($wt + weight(@basket) > 10) {
send(@basket);
@basket = ();
unshift(@tree, $apple);
} else {
push(@basket, $element);
}
}
</code></pre>
<p>Or else I can also use <code>redo</code>, which resumes processing at the top of block, without evaluating the loop expression. So the same apple can be re-processed, after the basket has been emptied.</p>
<pre><code>while ($apple = shift(@tree)) {
$wt = weight($apple);
if ($wt + weight(@basket) > 10) {
send(@basket);
@basket = ();
redo;
} else {
push(@basket, $apple);
}
}
</code></pre>
<p>What would be the most <strong>pythonic</strong> solution for this kind of problem?</p>
| 12 | 2009-01-07T01:59:07Z | 418,987 | <blockquote>
<p>I'm learning Python, and I have a situation where I want to consume items from an iterator. The tricky part is that under certain conditions, I want to "un-iterate." That is, put an item back onto the front of the iterator before I loop.</p>
</blockquote>
<p>Here's a simple solution:</p>
<pre><code>class MyIterator(object): # undo-able iterator wrapper
def __init__(self, iterable):
super(MyIterator, self).__init__()
self.iterator = iter(iterable)
self.stack = []
def __iter__(self):
return self
def next(self):
if self.stack:
return self.stack.pop()
return self.iterator.next() # Raises StopIteration eventually
def undo(self, item):
self.stack.append(item)
</code></pre>
<pre><code>for i in MyIterator(xrange(5)): print i
0
1
2
3
4
</code></pre>
<pre><code>rng = MyIterator(xrange(5))
rng.next()
0
rng.next()
1
rng.undo(1)
rng.next()
1
</code></pre>
| 16 | 2009-01-07T02:27:28Z | [
"python",
"redo"
]
|
Pythonic equivalent of unshift or redo? | 418,915 | <p>I'm learning Python, and I have a situation where I want to consume items from an iterator. The tricky part is that under certain conditions, I want to "un-iterate." That is, put an item back onto the front of the iterator before I loop.</p>
<p>For example, suppose I'm picking apples from a tree. My fruit basket can only hold 10kg before it needs to be emptied. But I have to pick each apple before I can weigh it and determine if this apple would exceed the capacity of the basket.</p>
<p>In a language like Perl, I could <code>unshift()</code> the apple back onto the tree, and then let the loop expression re-pick the apple:</p>
<pre><code>while ($apple = shift(@tree)) {
$wt = weight($apple);
if ($wt + weight(@basket) > 10) {
send(@basket);
@basket = ();
unshift(@tree, $apple);
} else {
push(@basket, $element);
}
}
</code></pre>
<p>Or else I can also use <code>redo</code>, which resumes processing at the top of block, without evaluating the loop expression. So the same apple can be re-processed, after the basket has been emptied.</p>
<pre><code>while ($apple = shift(@tree)) {
$wt = weight($apple);
if ($wt + weight(@basket) > 10) {
send(@basket);
@basket = ();
redo;
} else {
push(@basket, $apple);
}
}
</code></pre>
<p>What would be the most <strong>pythonic</strong> solution for this kind of problem?</p>
| 12 | 2009-01-07T01:59:07Z | 418,996 | <p>While I was writing this @Patrick already suggested the same thing. But since I have written it I will paste the code anyways, with comments in code marking methods from Patrick.</p>
<pre><code>import random
apples=[random.randint(1,3) for j in range(10)]
print 'apples',apples
basket=[]
y=6
baskets=[]
for i in range(len(apples)):
if sum(basket+[apples[i]])>y:
#basket is full
baskets.append(basket)#basket.send()
basket=[]#basket.empty()
basket.append(apples[i])#add apple to basket
print 'baskets',baskets
</code></pre>
<p>though this does not pop() the apples from the original iterator. Please remark if that's a desired behavior too.</p>
<p>the output</p>
<pre><code>apples [1, 1, 3, 3, 1, 1, 3, 3, 2, 3]
baskets [[1, 1, 3], [3, 1, 1], [3, 3]]
</code></pre>
| 1 | 2009-01-07T02:36:02Z | [
"python",
"redo"
]
|
Pythonic equivalent of unshift or redo? | 418,915 | <p>I'm learning Python, and I have a situation where I want to consume items from an iterator. The tricky part is that under certain conditions, I want to "un-iterate." That is, put an item back onto the front of the iterator before I loop.</p>
<p>For example, suppose I'm picking apples from a tree. My fruit basket can only hold 10kg before it needs to be emptied. But I have to pick each apple before I can weigh it and determine if this apple would exceed the capacity of the basket.</p>
<p>In a language like Perl, I could <code>unshift()</code> the apple back onto the tree, and then let the loop expression re-pick the apple:</p>
<pre><code>while ($apple = shift(@tree)) {
$wt = weight($apple);
if ($wt + weight(@basket) > 10) {
send(@basket);
@basket = ();
unshift(@tree, $apple);
} else {
push(@basket, $element);
}
}
</code></pre>
<p>Or else I can also use <code>redo</code>, which resumes processing at the top of block, without evaluating the loop expression. So the same apple can be re-processed, after the basket has been emptied.</p>
<pre><code>while ($apple = shift(@tree)) {
$wt = weight($apple);
if ($wt + weight(@basket) > 10) {
send(@basket);
@basket = ();
redo;
} else {
push(@basket, $apple);
}
}
</code></pre>
<p>What would be the most <strong>pythonic</strong> solution for this kind of problem?</p>
| 12 | 2009-01-07T01:59:07Z | 419,100 | <p>You're looking for a generator, an iterator that can receive modifications to its internal state via the send() method</p>
<p><a href="https://docs.python.org/howto/functional.html#passing-values-into-a-generator" rel="nofollow">https://docs.python.org/howto/functional.html#passing-values-into-a-generator</a></p>
| 3 | 2009-01-07T03:29:59Z | [
"python",
"redo"
]
|
Pythonic equivalent of unshift or redo? | 418,915 | <p>I'm learning Python, and I have a situation where I want to consume items from an iterator. The tricky part is that under certain conditions, I want to "un-iterate." That is, put an item back onto the front of the iterator before I loop.</p>
<p>For example, suppose I'm picking apples from a tree. My fruit basket can only hold 10kg before it needs to be emptied. But I have to pick each apple before I can weigh it and determine if this apple would exceed the capacity of the basket.</p>
<p>In a language like Perl, I could <code>unshift()</code> the apple back onto the tree, and then let the loop expression re-pick the apple:</p>
<pre><code>while ($apple = shift(@tree)) {
$wt = weight($apple);
if ($wt + weight(@basket) > 10) {
send(@basket);
@basket = ();
unshift(@tree, $apple);
} else {
push(@basket, $element);
}
}
</code></pre>
<p>Or else I can also use <code>redo</code>, which resumes processing at the top of block, without evaluating the loop expression. So the same apple can be re-processed, after the basket has been emptied.</p>
<pre><code>while ($apple = shift(@tree)) {
$wt = weight($apple);
if ($wt + weight(@basket) > 10) {
send(@basket);
@basket = ();
redo;
} else {
push(@basket, $apple);
}
}
</code></pre>
<p>What would be the most <strong>pythonic</strong> solution for this kind of problem?</p>
| 12 | 2009-01-07T01:59:07Z | 419,365 | <p>I'd say that <a href="http://mail.python.org/pipermail/python-list/2004-March/253893.html">the most Pythonic solution is the simplest one</a>. Instead of trying to wrap an iterator in a generator expression that allows you to "backtrack" or something similarly complex, use a while loop, as you have in Perl! <strong><a href="http://stackoverflow.com/questions/299135/when-i-sort-a-list-what-happens-to-its-iterators">Iterators don't mix very nicely with mutation</a></strong>, anywho.</p>
<p>Simple translation of your implementation (ignoring <a href="http://stackoverflow.com/questions/418915/pythonic-equivalent-of-unshift-or-redo#418946">@Patrick</a>'s optimization):</p>
<pre><code>while tree:
apple = tree.pop(0)
if apple.weight + basket.weight > 10:
basket.send()
basket.clear()
tree.insert(0, apple) # Put it back.
else:
basket.append(apple)
</code></pre>
<p>Or, you could use a <code>peek</code>-like functionality with ordered sequence indices: </p>
<pre><code>while tree:
apple = tree[0] # Take a peek at it.
if apple.weight + basket.weight > 10:
basket.send()
basket.clear()
else:
basket.append(tree.pop(0))
</code></pre>
<p>If you don't like the "simple" argument, check out the <code>collections.deque</code> iterators mentioned in the above (linked) thread.</p>
| 6 | 2009-01-07T06:09:24Z | [
"python",
"redo"
]
|
Pythonic equivalent of unshift or redo? | 418,915 | <p>I'm learning Python, and I have a situation where I want to consume items from an iterator. The tricky part is that under certain conditions, I want to "un-iterate." That is, put an item back onto the front of the iterator before I loop.</p>
<p>For example, suppose I'm picking apples from a tree. My fruit basket can only hold 10kg before it needs to be emptied. But I have to pick each apple before I can weigh it and determine if this apple would exceed the capacity of the basket.</p>
<p>In a language like Perl, I could <code>unshift()</code> the apple back onto the tree, and then let the loop expression re-pick the apple:</p>
<pre><code>while ($apple = shift(@tree)) {
$wt = weight($apple);
if ($wt + weight(@basket) > 10) {
send(@basket);
@basket = ();
unshift(@tree, $apple);
} else {
push(@basket, $element);
}
}
</code></pre>
<p>Or else I can also use <code>redo</code>, which resumes processing at the top of block, without evaluating the loop expression. So the same apple can be re-processed, after the basket has been emptied.</p>
<pre><code>while ($apple = shift(@tree)) {
$wt = weight($apple);
if ($wt + weight(@basket) > 10) {
send(@basket);
@basket = ();
redo;
} else {
push(@basket, $apple);
}
}
</code></pre>
<p>What would be the most <strong>pythonic</strong> solution for this kind of problem?</p>
| 12 | 2009-01-07T01:59:07Z | 420,173 | <p>If you don't want to follow the other's suggestion of just removing the else clause, you can write your own <code>unshift</code> function that will work in a way similar to perl's with any iterable:</p>
<pre><code>class UnshiftableIterable(object):
def __init__(self, iterable):
self._iter = iter(iterable)
self._unshifted = [] # empty list of unshifted stuff
def __iter__(self):
while True:
if self._unshifted:
yield self._unshifted.pop()
else:
yield self._iter.next()
def unshift(self, item):
self._unshifted.append(item)
</code></pre>
<p>Then in your code:</p>
<pre><code>it = UnshiftableIterable(tree)
for apple in tree:
if weigth(basket) + weight(apple) > MAX_WEIGHT:
send(basket)
basket = []
it.unshift(apple)
else:
basket.append(apple)
</code></pre>
<p>Some testing of the <code>UnshiftableIterable</code>:</p>
<pre><code>it = UnshiftableIterable(xrange(5))
for i in it:
print '*',
if i == 2:
it.unshift(10)
else:
print i,
# output: * 0 * 1 * * 10 * 3 * 4
</code></pre>
| 4 | 2009-01-07T12:40:38Z | [
"python",
"redo"
]
|
Pythonic equivalent of unshift or redo? | 418,915 | <p>I'm learning Python, and I have a situation where I want to consume items from an iterator. The tricky part is that under certain conditions, I want to "un-iterate." That is, put an item back onto the front of the iterator before I loop.</p>
<p>For example, suppose I'm picking apples from a tree. My fruit basket can only hold 10kg before it needs to be emptied. But I have to pick each apple before I can weigh it and determine if this apple would exceed the capacity of the basket.</p>
<p>In a language like Perl, I could <code>unshift()</code> the apple back onto the tree, and then let the loop expression re-pick the apple:</p>
<pre><code>while ($apple = shift(@tree)) {
$wt = weight($apple);
if ($wt + weight(@basket) > 10) {
send(@basket);
@basket = ();
unshift(@tree, $apple);
} else {
push(@basket, $element);
}
}
</code></pre>
<p>Or else I can also use <code>redo</code>, which resumes processing at the top of block, without evaluating the loop expression. So the same apple can be re-processed, after the basket has been emptied.</p>
<pre><code>while ($apple = shift(@tree)) {
$wt = weight($apple);
if ($wt + weight(@basket) > 10) {
send(@basket);
@basket = ();
redo;
} else {
push(@basket, $apple);
}
}
</code></pre>
<p>What would be the most <strong>pythonic</strong> solution for this kind of problem?</p>
| 12 | 2009-01-07T01:59:07Z | 5,657,672 | <p>By the way, what you really want is list.insert(0,yourObject)</p>
| 0 | 2011-04-14T01:41:59Z | [
"python",
"redo"
]
|
Pythonic equivalent of unshift or redo? | 418,915 | <p>I'm learning Python, and I have a situation where I want to consume items from an iterator. The tricky part is that under certain conditions, I want to "un-iterate." That is, put an item back onto the front of the iterator before I loop.</p>
<p>For example, suppose I'm picking apples from a tree. My fruit basket can only hold 10kg before it needs to be emptied. But I have to pick each apple before I can weigh it and determine if this apple would exceed the capacity of the basket.</p>
<p>In a language like Perl, I could <code>unshift()</code> the apple back onto the tree, and then let the loop expression re-pick the apple:</p>
<pre><code>while ($apple = shift(@tree)) {
$wt = weight($apple);
if ($wt + weight(@basket) > 10) {
send(@basket);
@basket = ();
unshift(@tree, $apple);
} else {
push(@basket, $element);
}
}
</code></pre>
<p>Or else I can also use <code>redo</code>, which resumes processing at the top of block, without evaluating the loop expression. So the same apple can be re-processed, after the basket has been emptied.</p>
<pre><code>while ($apple = shift(@tree)) {
$wt = weight($apple);
if ($wt + weight(@basket) > 10) {
send(@basket);
@basket = ();
redo;
} else {
push(@basket, $apple);
}
}
</code></pre>
<p>What would be the most <strong>pythonic</strong> solution for this kind of problem?</p>
| 12 | 2009-01-07T01:59:07Z | 14,739,023 | <p>Back to the original question about impementing unshift, operator.delitem can be used to implement a simple non-OO function:</p>
<pre><code>from operator import delitem
def unshift(l,idx):
retval = l[0]
delitem(l,0)
return retval
x = [2,4,6,8]
firstval = unshift(x,0)
print firstval,x
</code></pre>
<p>2 [4, 6, 8]</p>
| 0 | 2013-02-06T21:20:56Z | [
"python",
"redo"
]
|
How to raise an exception on the version number of a module | 419,010 | <p>How can you raise an exception when you import a module that is less or greater than a given value for its __version__?</p>
<p>There are a lot of different ways you could do it, but I feel like there must be some really simple way that eludes me at the moment. In this case the version number is of the format x.x.x</p>
| 4 | 2009-01-07T02:39:56Z | 419,035 | <p>Like this?</p>
<pre><code>assert tuple(map(int,module.__version__.split("."))) >= (1,2), "Module not version 1.2.x"
</code></pre>
<p>This is wordy, but works pretty well.</p>
<p>Also, look into <a href="http://pypi.python.org/pypi/pip/" rel="nofollow">pip</a>, which provides more advanced functionality.</p>
| 1 | 2009-01-07T02:51:06Z | [
"python",
"versioning"
]
|
How to raise an exception on the version number of a module | 419,010 | <p>How can you raise an exception when you import a module that is less or greater than a given value for its __version__?</p>
<p>There are a lot of different ways you could do it, but I feel like there must be some really simple way that eludes me at the moment. In this case the version number is of the format x.x.x</p>
| 4 | 2009-01-07T02:39:56Z | 419,038 | <p>Python comes with this inbuilt as part of distutils. The module is called <code>distutils.version</code> and is able to compare several different version number formats.</p>
<pre><code>from distutils.version import StrictVersion
print StrictVersion('1.2.2') > StrictVersion('1.2.1')
</code></pre>
<p>For way more information than you need, see the documentation:</p>
<pre><code>>>> import distutils.version
>>> help(distutils.version)
</code></pre>
| 6 | 2009-01-07T02:52:13Z | [
"python",
"versioning"
]
|
How to raise an exception on the version number of a module | 419,010 | <p>How can you raise an exception when you import a module that is less or greater than a given value for its __version__?</p>
<p>There are a lot of different ways you could do it, but I feel like there must be some really simple way that eludes me at the moment. In this case the version number is of the format x.x.x</p>
| 4 | 2009-01-07T02:39:56Z | 419,089 | <p>If you know the exact formatting of the version string a plain comparison will work:</p>
<pre><code>>>> "1.2.2" > "1.2.1"
True
</code></pre>
<p>This will only work if each part of the version is in the single digits, though:</p>
<pre><code>>>> "1.2.2" > "1.2.10" # Bug!
True
</code></pre>
| -1 | 2009-01-07T03:24:51Z | [
"python",
"versioning"
]
|
How to raise an exception on the version number of a module | 419,010 | <p>How can you raise an exception when you import a module that is less or greater than a given value for its __version__?</p>
<p>There are a lot of different ways you could do it, but I feel like there must be some really simple way that eludes me at the moment. In this case the version number is of the format x.x.x</p>
| 4 | 2009-01-07T02:39:56Z | 419,108 | <p>If you are talking about modules installed with easy_install, this is what you need</p>
<pre><code>import pkg_resources
pkg_resources.require("TurboGears>=1.0.5")
</code></pre>
<p>this will raise an error if the installed module is of a lower version</p>
<pre><code>Traceback (most recent call last):
File "tempplg.py", line 2, in <module>
pkg_resources.require("TurboGears>=1.0.5")
File "/usr/lib/python2.5/site-packages/pkg_resources.py", line 626, in require
needed = self.resolve(parse_requirements(requirements))
File "/usr/lib/python2.5/site-packages/pkg_resources.py", line 528, in resolve
raise VersionConflict(dist,req) # XXX put more info here
pkg_resources.VersionConflict: (TurboGears 1.0.4.4 (/usr/lib/python2.5/site-packages/TurboGears-1.0.4.4-py2.5.egg), Requirement.parse('TurboGears>=1.0.5'))
</code></pre>
| 2 | 2009-01-07T03:34:59Z | [
"python",
"versioning"
]
|
How to raise an exception on the version number of a module | 419,010 | <p>How can you raise an exception when you import a module that is less or greater than a given value for its __version__?</p>
<p>There are a lot of different ways you could do it, but I feel like there must be some really simple way that eludes me at the moment. In this case the version number is of the format x.x.x</p>
| 4 | 2009-01-07T02:39:56Z | 420,029 | <p>You should be using setuptools: </p>
<p>It allows you to lock the dependancies of an application, so even if multiple versions of an egg or package exist on a system only the right one will ever be used. </p>
<p>This is a better way of working: Rather than fail if the wrong version of a dependancy is present it is better to ensure that the right version is present. </p>
<p>Setuptools provides an installer which guarantees that everything required to run the application is present at install-time. It also gives you the means to select which of the many versions of a package which may be present on your PC is the one that gets loaded when you issue an import statement.</p>
| 0 | 2009-01-07T11:51:04Z | [
"python",
"versioning"
]
|
Python Threads - Critical Section | 419,145 | <p>What is the "critical section" of a thread (in Python)?</p>
<blockquote>
<p>A thread enters the critical section
by calling the acquire() method, which
can either be blocking or
non-blocking. A thread exits the
critical section, by calling the
release() method.</p>
</blockquote>
<p>- <a href="http://linuxgazette.net/107/pai.html">Understanding Threading in Python, Linux Gazette</a></p>
<p>Also, what is the purpose of a lock?</p>
| 10 | 2009-01-07T03:58:18Z | 419,155 | <p>A critical section of code is one that can only be executed by one thread at a time. Take a chat server for instance. If you have a thread for each connection (i.e., each end user), one "critical section" is the spooling code (sending an incoming message to all the clients). If more than one thread tries to spool a message at once, you'll get BfrIToS mANtwD PIoEmesCEsaSges intertwined, which is obviously no good at all.</p>
<p>A lock is something that can be used to synchronize access to a critical section (or resources in general). In our chat server example, the lock is like a locked room with a typewriter in it. If one thread is in there (to type a message out), no other thread can get into the room. Once the first thread is done, he unlocks the room and leaves. Then another thread can go in the room (locking it). "Aquiring" the lock just means "I get the room."</p>
| 14 | 2009-01-07T04:07:50Z | [
"python",
"multithreading",
"language-agnostic"
]
|
Python Threads - Critical Section | 419,145 | <p>What is the "critical section" of a thread (in Python)?</p>
<blockquote>
<p>A thread enters the critical section
by calling the acquire() method, which
can either be blocking or
non-blocking. A thread exits the
critical section, by calling the
release() method.</p>
</blockquote>
<p>- <a href="http://linuxgazette.net/107/pai.html">Understanding Threading in Python, Linux Gazette</a></p>
<p>Also, what is the purpose of a lock?</p>
| 10 | 2009-01-07T03:58:18Z | 419,161 | <p>A <a href="http://en.wikipedia.org/wiki/Critical_section" rel="nofollow">"critical section"</a> is a chunk of code in which, for correctness, it is necessary to ensure that only one thread of control can be in that section at a time. In general, you need a critical section to contain references that <em>write</em> values into memory that can be shared among more than one concurrent process.</p>
| 0 | 2009-01-07T04:09:57Z | [
"python",
"multithreading",
"language-agnostic"
]
|
Python Threads - Critical Section | 419,145 | <p>What is the "critical section" of a thread (in Python)?</p>
<blockquote>
<p>A thread enters the critical section
by calling the acquire() method, which
can either be blocking or
non-blocking. A thread exits the
critical section, by calling the
release() method.</p>
</blockquote>
<p>- <a href="http://linuxgazette.net/107/pai.html">Understanding Threading in Python, Linux Gazette</a></p>
<p>Also, what is the purpose of a lock?</p>
| 10 | 2009-01-07T03:58:18Z | 419,213 | <p>Other people have given very nice definitions. Here's the classic example:</p>
<pre><code>import threading
account_balance = 0 # The "resource" that zenazn mentions.
account_balance_lock = threading.Lock()
def change_account_balance(delta):
global account_balance
with account_balance_lock:
# Critical section is within this block.
account_balance += delta
</code></pre>
<p>Let's say that the <code>+=</code> operator consists of three subcomponents:</p>
<ul>
<li>Read the current value</li>
<li>Add the RHS to that value</li>
<li>Write the accumulated value back to the LHS (technically <em>bind</em> it in Python terms)</li>
</ul>
<p>If you don't have the <code>with account_balance_lock</code> statement and you execute two <code>change_account_balance</code> calls in parallel you can end up interleaving the three subcomponent operations in a hazardous manner. Let's say you simultaneously call <code>change_account_balance(100)</code> (AKA pos) and <code>change_account_balance(-100)</code> (AKA neg). This could happen:</p>
<pre><code>pos = threading.Thread(target=change_account_balance, args=[100])
neg = threading.Thread(target=change_account_balance, args=[-100])
pos.start(), neg.start()
</code></pre>
<ul>
<li>pos: read current value -> 0</li>
<li>neg: read current value -> 0</li>
<li>pos: add current value to read value -> 100</li>
<li>neg: add current value to read value -> -100</li>
<li>pos: write current value -> account_balance = 100</li>
<li>neg: write current value -> account_balance = -100</li>
</ul>
<p>Because you didn't force the operations to happen in discrete chunks you can have three possible outcomes (-100, 0, 100).</p>
<p>The <code>with [lock]</code> statement is a single, indivisible operation that says, "Let me be the only thread executing this block of code. If something else is executing, it's cool -- I'll wait." This ensures that the updates to the <code>account_balance</code> are "thread-safe" (parallelism-safe).</p>
<p><strong>Note:</strong> There is a caveat to this schema: you have to remember to acquire the <code>account_balance_lock</code> (via <code>with</code>) every time you want to manipulate the <code>account_balance</code> for the code to remain thread-safe. There are ways to make this less fragile, but that's the answer to a whole other question.</p>
<p><strong>Edit:</strong> In retrospect, it's probably important to mention that the <code>with</code> statement implicitly calls a blocking <code>acquire</code> on the lock -- this is the "I'll wait" part of the above thread dialog. In contrast, a non-blocking acquire says, "If I can't acquire the lock right away, let me know," and then relies on you to check whether you got the lock or not.</p>
<pre><code>import logging # This module is thread safe.
import threading
LOCK = threading.Lock()
def run():
if LOCK.acquire(False): # Non-blocking -- return whether we got it
logging.info('Got the lock!')
LOCK.release()
else:
logging.info("Couldn't get the lock. Maybe next time")
logging.basicConfig(level=logging.INFO)
threads = [threading.Thread(target=run) for i in range(100)]
for thread in threads:
thread.start()
</code></pre>
<p>I also want to add that the lock's primary purpose is to guarantee the atomicity of acquisition (the indivisibility of the <code>acquire</code> across threads), which a simple boolean flag will not guarantee. The semantics of atomic operations are probably also the content of another question.</p>
| 8 | 2009-01-07T04:42:43Z | [
"python",
"multithreading",
"language-agnostic"
]
|
What does `if __name__ == "__main__":` do? | 419,163 | <p>What does the <code>if __name__ == "__main__":</code> do?</p>
<pre><code># Threading example
import time, thread
def myfunction(string, sleeptime, lock, *args):
while 1:
lock.acquire()
time.sleep(sleeptime)
lock.release()
time.sleep(sleeptime)
if __name__ == "__main__":
lock = thread.allocate_lock()
thread.start_new_thread(myfunction, ("Thread #: 1", 2, lock))
thread.start_new_thread(myfunction, ("Thread #: 2", 2, lock))
</code></pre>
| 2,184 | 2009-01-07T04:11:00Z | 419,174 | <p><code>if __name__ == "__main__"</code> is the part that runs when the script is run from (say) the command line using a command like <code>python myscript.py</code>.</p>
| 61 | 2009-01-07T04:14:23Z | [
"python",
"module",
"namespaces",
"main",
"idioms"
]
|
What does `if __name__ == "__main__":` do? | 419,163 | <p>What does the <code>if __name__ == "__main__":</code> do?</p>
<pre><code># Threading example
import time, thread
def myfunction(string, sleeptime, lock, *args):
while 1:
lock.acquire()
time.sleep(sleeptime)
lock.release()
time.sleep(sleeptime)
if __name__ == "__main__":
lock = thread.allocate_lock()
thread.start_new_thread(myfunction, ("Thread #: 1", 2, lock))
thread.start_new_thread(myfunction, ("Thread #: 2", 2, lock))
</code></pre>
| 2,184 | 2009-01-07T04:11:00Z | 419,185 | <p>When the Python interpreter reads a source file, it executes all of the code found in it. </p>
<p>Before executing the code, it will define a few special variables. For example, if the python interpreter is running that module (the source file) as the main program, it sets the special <code>__name__</code> variable to have a value <code>"__main__"</code>. If this file is being imported from another module, <code>__name__</code> will be set to the module's name.</p>
<p>In the case of your script, let's assume that it's executing as the main function, e.g. you said something like</p>
<pre><code>python threading_example.py
</code></pre>
<p>on the command line. After setting up the special variables, it will execute the <code>import</code> statement and load those modules. It will then evaluate the <code>def</code> block, creating a function object and creating a variable called <code>myfunction</code> that points to the function object. It will then read the <code>if</code> statement and see that <code>__name__</code> does equal <code>"__main__"</code>, so it will execute the block shown there.</p>
<p>One of the reasons for doing this is that sometimes you write a module (a <code>.py</code> file) where it can be executed directly. Alternatively, it can also be imported and used in another module. By doing the main check, you can have that code only execute when you want to run the module as a program and not have it execute when someone just wants to import your module and call your functions themselves.</p>
<p>See <a href="http://ibiblio.org/g2swap/byteofpython/read/module-name.html">this page</a> for some extra details.</p>
| 2,443 | 2009-01-07T04:26:43Z | [
"python",
"module",
"namespaces",
"main",
"idioms"
]
|
What does `if __name__ == "__main__":` do? | 419,163 | <p>What does the <code>if __name__ == "__main__":</code> do?</p>
<pre><code># Threading example
import time, thread
def myfunction(string, sleeptime, lock, *args):
while 1:
lock.acquire()
time.sleep(sleeptime)
lock.release()
time.sleep(sleeptime)
if __name__ == "__main__":
lock = thread.allocate_lock()
thread.start_new_thread(myfunction, ("Thread #: 1", 2, lock))
thread.start_new_thread(myfunction, ("Thread #: 2", 2, lock))
</code></pre>
| 2,184 | 2009-01-07T04:11:00Z | 419,189 | <p>When your script is run by passing it as a command to the Python interpreter,</p>
<pre><code>python myscript.py
</code></pre>
<p>all of the code that is at indentation level 0 gets executed. Functions and classes that are defined are, well, defined, but none of their code gets ran. Unlike other languages, there's no <code>main()</code> function that gets run automatically - the <code>main()</code> function is implicitly all the code at the top level.</p>
<p>In this case, the top-level code is an <code>if</code> block. <code>__name__</code> is a built-in variable which evaluate to the name of the current module. However, if a module is being run directly (as in <code>myscript.py</code> above), then <code>__name__</code> instead is set to the string <code>"__main__"</code>. Thus, you can test whether your script is being run directly or being imported by something else by testing</p>
<pre><code>if __name__ == "__main__":
...
</code></pre>
<p>If that code is being imported into another module, the various function and class definitions will be imported, but the <code>main()</code> code won't get run. As a basic example, consider the following two scripts:</p>
<pre><code># file one.py
def func():
print("func() in one.py")
print("top-level in one.py")
if __name__ == "__main__":
print("one.py is being run directly")
else:
print("one.py is being imported into another module")
# file two.py
import one
print("top-level in two.py")
one.func()
if __name__ == "__main__":
print("two.py is being run directly")
else:
print("two.py is being imported into another module")
</code></pre>
<p>Now, if you invoke the interpreter as</p>
<pre><code>python one.py
</code></pre>
<p>The output will be</p>
<pre><code>top-level in one.py
one.py is being run directly
</code></pre>
<p>If you run <code>two.py</code> instead:</p>
<pre><code>python two.py
</code></pre>
<p>You get</p>
<pre><code>top-level in one.py
one.py is being imported into another module
top-level in two.py
func() in one.py
two.py is being run directly
</code></pre>
<p>Thus, when module <code>one</code> gets loaded, its <code>__name__</code> equals <code>"one"</code> instead of <code>__main__</code>.</p>
| 697 | 2009-01-07T04:28:23Z | [
"python",
"module",
"namespaces",
"main",
"idioms"
]
|
What does `if __name__ == "__main__":` do? | 419,163 | <p>What does the <code>if __name__ == "__main__":</code> do?</p>
<pre><code># Threading example
import time, thread
def myfunction(string, sleeptime, lock, *args):
while 1:
lock.acquire()
time.sleep(sleeptime)
lock.release()
time.sleep(sleeptime)
if __name__ == "__main__":
lock = thread.allocate_lock()
thread.start_new_thread(myfunction, ("Thread #: 1", 2, lock))
thread.start_new_thread(myfunction, ("Thread #: 2", 2, lock))
</code></pre>
| 2,184 | 2009-01-07T04:11:00Z | 419,986 | <p>The simplest explanation for the <code>__name__</code> variable (imho) is the following:</p>
<p>Create the following files.</p>
<pre><code># a.py
import b
</code></pre>
<p>and</p>
<pre><code># b.py
print "Hello World from %s!" % __name__
if __name__ == '__main__':
print "Hello World again from %s!" % __name__
</code></pre>
<p>Running them will get you this output:</p>
<pre><code>$ python a.py
Hello World from b!
</code></pre>
<p>As you can see, when a module is imported, Python sets <code>globals()['__name__']</code> in this module to the module's name.</p>
<pre><code>$ python b.py
Hello World from __main__!
Hello World again from __main__!
</code></pre>
<p>As you can see, when a file is executed, Python sets <code>globals()['__name__']</code> in this file to <code>"__main__"</code>.</p>
| 337 | 2009-01-07T11:35:17Z | [
"python",
"module",
"namespaces",
"main",
"idioms"
]
|
What does `if __name__ == "__main__":` do? | 419,163 | <p>What does the <code>if __name__ == "__main__":</code> do?</p>
<pre><code># Threading example
import time, thread
def myfunction(string, sleeptime, lock, *args):
while 1:
lock.acquire()
time.sleep(sleeptime)
lock.release()
time.sleep(sleeptime)
if __name__ == "__main__":
lock = thread.allocate_lock()
thread.start_new_thread(myfunction, ("Thread #: 1", 2, lock))
thread.start_new_thread(myfunction, ("Thread #: 2", 2, lock))
</code></pre>
| 2,184 | 2009-01-07T04:11:00Z | 14,502,904 | <p>It is a special for when a Python file is called from the command line. This is typically used to call a "main()" function or execute other appropriate startup code, like commandline arguments handling for instance.</p>
<p>It could be written in several ways, another is:</p>
<pre><code>def main():
dosomething()
__name__ == '__main__' and main()
</code></pre>
<p>I am not saying you should use this in production code, but it serves to illustrate that there is nothing "magical" about <code>if __name__ == '__main__'</code>.</p>
| 6 | 2013-01-24T13:48:38Z | [
"python",
"module",
"namespaces",
"main",
"idioms"
]
|
What does `if __name__ == "__main__":` do? | 419,163 | <p>What does the <code>if __name__ == "__main__":</code> do?</p>
<pre><code># Threading example
import time, thread
def myfunction(string, sleeptime, lock, *args):
while 1:
lock.acquire()
time.sleep(sleeptime)
lock.release()
time.sleep(sleeptime)
if __name__ == "__main__":
lock = thread.allocate_lock()
thread.start_new_thread(myfunction, ("Thread #: 1", 2, lock))
thread.start_new_thread(myfunction, ("Thread #: 2", 2, lock))
</code></pre>
| 2,184 | 2009-01-07T04:11:00Z | 15,789,709 | <p>When there are certain statements in our module (<code>M.py</code>), we want to be executed when it 'll be running as main (not imported), in that case we can place those statements (test-cases, print statements) under this if block. As by default (when module running as main, not imported) the <code>__name__</code> variable is set to <code>"__main__"</code>, and when it'll be imported the <code>__name__</code> variable 'll get a different value, most probably the name of the module (<code>'M'</code>).
This is helpful in running different variants of a modules together, and seperating their specific input & output statements and also if any test-cases.</p>
<p><strong>In short</strong> , use this '<code>if __name__ == "main"</code> ' block to prevent (certain) code from being run when the module is imported.</p>
| 19 | 2013-04-03T14:09:11Z | [
"python",
"module",
"namespaces",
"main",
"idioms"
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.