title
stringlengths
12
150
question_id
int64
469
40.1M
question_score
int64
2
5.52k
question_date
stringdate
2008-08-02 15:11:16
2016-10-18 06:16:31
answer_id
int64
536
40.1M
answer_score
int64
7
8.38k
answer_date
stringdate
2008-08-02 18:49:07
2016-10-18 06:19:33
tags
listlengths
1
5
question_body_md
stringlengths
15
30.2k
answer_body_md
stringlengths
11
27.8k
Iterating through a range of dates in Python
1,060,279
172
2009-06-29T20:16:02Z
23,853,523
13
2014-05-25T08:44:46Z
[ "python", "datetime", "iteration" ]
I have the following code to do this, but how can I do it better? Right now I think it's better than nested loops, but it starts to get Perl-one-linerish when you have a generator in a list comprehension. ``` day_count = (end_date - start_date).days + 1 for single_date in [d for d in (start_date + timedelta(n) for n i...
Pandas is great for time series in general, and has direct support for date ranges. ``` import pandas as pd daterange = pd.date_range(start_date, end_date) ``` You can then loop over the daterange to print the date: ``` for single_date in daterange: print (single_date.strftime("%Y-%m-%d")) ``` It also has lots ...
How do I include a PHP script in Python?
1,060,436
6
2009-06-29T20:44:02Z
1,060,515
9
2009-06-29T20:58:16Z
[ "php", "python", "scripting", "integration", "execution" ]
I have a PHP script (news-generator.php) which, when I include it, grabs a bunch of news items and prints them. Right now, I'm using Python for my website (CGI). When I was using PHP, I used something like this on the "News" page: ``` <?php print("<h1>News and Updates</h1>"); include("news-generator.php"); print("</bo...
``` import subprocess def php(script_path): p = subprocess.Popen(['php', script_path], stdout=subprocess.PIPE) result = p.communicate()[0] return result # YOUR CODE BELOW: page_html = "<h1>News and Updates</h1>" news_script_output = php("news-generator.php") print page_html + news_script_output ```
Difference between type(obj) and obj.__class__
1,060,499
33
2009-06-29T20:55:52Z
1,060,537
28
2009-06-29T21:02:10Z
[ "python", "new-style-class" ]
What is the difference between `type(obj)` and `obj.__class__`? Is there ever a possibility of `type(obj) is not obj.__class__`? I want to write a function that works generically on the supplied objects, using a default value of 1 in the same type as another parameter. Which variation, #1 or #2 below, is going to do t...
Old-style classes are the problem, sigh: ``` >>> class old: pass ... >>> x=old() >>> type(x) <type 'instance'> >>> x.__class__ <class __main__.old at 0x6a150> >>> ``` Not a problem in Python 3 since all classes are new-style now;-). In Python 2, a class is new-style only if it inherits from another new-style class ...
Difference between type(obj) and obj.__class__
1,060,499
33
2009-06-29T20:55:52Z
1,060,547
12
2009-06-29T21:04:00Z
[ "python", "new-style-class" ]
What is the difference between `type(obj)` and `obj.__class__`? Is there ever a possibility of `type(obj) is not obj.__class__`? I want to write a function that works generically on the supplied objects, using a default value of 1 in the same type as another parameter. Which variation, #1 or #2 below, is going to do t...
`type(obj)` and `type.__class__` do not behave the same for old style classes: ``` >>> class a(object): ... pass ... >>> class b(a): ... pass ... >>> class c: ... pass ... >>> ai=a() >>> bi=b() >>> ci=c() >>> type(ai) is ai.__class__ True >>> type(bi) is bi.__class__ True >>> type(ci) is ci.__class__ False...
Difference between type(obj) and obj.__class__
1,060,499
33
2009-06-29T20:55:52Z
10,633,356
21
2012-05-17T09:50:40Z
[ "python", "new-style-class" ]
What is the difference between `type(obj)` and `obj.__class__`? Is there ever a possibility of `type(obj) is not obj.__class__`? I want to write a function that works generically on the supplied objects, using a default value of 1 in the same type as another parameter. Which variation, #1 or #2 below, is going to do t...
This is an old question, but none of the answers seems to mention that. in the general case, it **IS** possible for a new-style class to have different values for `type(instance)` and `instance.__class__`: ``` class ClassA(object): def display(self): print("ClassA") class ClassB(object): __class__ = C...
Callable modules
1,060,796
33
2009-06-29T22:01:09Z
1,060,862
24
2009-06-29T22:18:56Z
[ "python", "module" ]
Why doesn't Python allow modules to have a `__call__`? (Beyond the obvious that it wouldn't be easy to import directly.) Specifically, why doesn't using `a(b)` syntax find the `__call__` attribute like it does for functions, classes, and objects? (Is lookup just incompatibly different for modules?) ``` >>> print open(...
Special methods are only guaranteed to be called implicitly when they are defined on the type, not on the instance. (`__call__` is an attribute of the module instance `mod_call`, not of `<type 'module'>`.) You can't add methods to built-in types. <http://docs.python.org/reference/datamodel.html#special-method-lookup-f...
Callable modules
1,060,796
33
2009-06-29T22:01:09Z
1,060,872
62
2009-06-29T22:20:06Z
[ "python", "module" ]
Why doesn't Python allow modules to have a `__call__`? (Beyond the obvious that it wouldn't be easy to import directly.) Specifically, why doesn't using `a(b)` syntax find the `__call__` attribute like it does for functions, classes, and objects? (Is lookup just incompatibly different for modules?) ``` >>> print open(...
Python doesn't allow modules to override or add *any* magic method, because keeping module objects simple, regular and lightweight is just too advantageous considering how rarely strong use cases appear where you could use magic methods there. When such use cases *do* appear, the solution is to make a class instance m...
__lt__ instead of __cmp__
1,061,283
73
2009-06-30T00:55:45Z
1,061,323
8
2009-06-30T01:13:02Z
[ "python", "operator-overloading" ]
Python 2.x has two ways to overload comparison operators, [`__cmp__`](http://docs.python.org/2.6/reference/datamodel.html#object.__cmp__) or the "rich comparison operators" such as [`__lt__`](http://docs.python.org/2.6/reference/datamodel.html#object.__lt__). **The rich comparison overloads are said to be preferred, bu...
This is covered by [PEP 207 - Rich Comparisons](http://www.python.org/dev/peps/pep-0207/) Also, `__cmp__` goes away in python 3.0. ( Note that it is not present on <http://docs.python.org/3.0/reference/datamodel.html> but it IS on <http://docs.python.org/2.7/reference/datamodel.html> )
__lt__ instead of __cmp__
1,061,283
73
2009-06-30T00:55:45Z
1,061,350
68
2009-06-30T01:28:10Z
[ "python", "operator-overloading" ]
Python 2.x has two ways to overload comparison operators, [`__cmp__`](http://docs.python.org/2.6/reference/datamodel.html#object.__cmp__) or the "rich comparison operators" such as [`__lt__`](http://docs.python.org/2.6/reference/datamodel.html#object.__lt__). **The rich comparison overloads are said to be preferred, bu...
Yep, it's easy to implement everything in terms of e.g. `__lt__` with a mixin class (or a metaclass, or a class decorator if your taste runs that way). For example: ``` class ComparableMixin: def __eq__(self, other): return not self<other and not other<self def __ne__(self, other): return self<other or ot...
__lt__ instead of __cmp__
1,061,283
73
2009-06-30T00:55:45Z
10,312,447
25
2012-04-25T09:01:11Z
[ "python", "operator-overloading" ]
Python 2.x has two ways to overload comparison operators, [`__cmp__`](http://docs.python.org/2.6/reference/datamodel.html#object.__cmp__) or the "rich comparison operators" such as [`__lt__`](http://docs.python.org/2.6/reference/datamodel.html#object.__lt__). **The rich comparison overloads are said to be preferred, bu...
To simplify this case there's a class decorator in Python 2.7+/3.2+, [functools.total\_ordering](http://docs.python.org/library/functools.html#functools.total_ordering), that can be used to implement what Alex suggests. Example from the docs: ``` @total_ordering class Student: def __eq__(self, other): retu...
What's the easiest way to escape HTML in Python?
1,061,697
93
2009-06-30T04:15:54Z
1,061,702
133
2009-06-30T04:18:11Z
[ "python", "html" ]
cgi.escape seems like one possible choice. Does it work well? Is there something that is considered better?
[`cgi.escape`](http://docs.python.org/library/cgi.html#cgi.escape) is fine. It escapes: * `<` to `&lt;` * `>` to `&gt;` * `&` to `&amp;` That is enough for all HTML. EDIT: If you have non-ascii chars you also want to escape, for inclusion in another encoded document that uses a different encoding, like *Craig* says,...
What's the easiest way to escape HTML in Python?
1,061,697
93
2009-06-30T04:15:54Z
1,061,747
7
2009-06-30T04:35:26Z
[ "python", "html" ]
cgi.escape seems like one possible choice. Does it work well? Is there something that is considered better?
[`cgi.escape`](https://docs.python.org/2/library/cgi.html#cgi.escape) should be good to escape HTML in the limited sense of escaping the HTML tags and character entities. But you might have to also consider encoding issues: if the HTML you want to quote has non-ASCII characters in a particular encoding, then you would...
What's the easiest way to escape HTML in Python?
1,061,697
93
2009-06-30T04:15:54Z
5,072,031
55
2011-02-21T22:31:07Z
[ "python", "html" ]
cgi.escape seems like one possible choice. Does it work well? Is there something that is considered better?
In Python 3.2 a new `html` module was introduced, which is used for escaping reserved characters from HTML markup. It has one function `escape()`: ``` >>> import html >>> html.escape('x > 2 && x < 7') 'x &gt; 2 &amp;&amp; x &lt; 7' ```
Django with system timezone setting vs user's individual timezones
1,061,911
15
2009-06-30T05:45:08Z
1,064,928
7
2009-06-30T17:24:47Z
[ "python", "django", "timezone" ]
How well does Django handle the case of different timezones for each user? Ideally I would like to run the server in the UTC timezone (eg, in settings.py set TIME\_ZONE="UTC") so all datetimes were stored in the database as UTC. Stuff like [this](http://stackoverflow.com/questions/689831/changing-timezone-on-an-existin...
**Update, January 2013**: Django 1.4 now has [time zone support](https://docs.djangoproject.com/en/1.4/topics/i18n/timezones/)!! --- Old answer for historical reasons: I'm going to be working on this problem myself for my application. My first approach to this problem would be to go with django core developer Malcom...
Modifying list contents in Python
1,061,937
3
2009-06-30T05:55:24Z
1,061,957
11
2009-06-30T06:00:08Z
[ "python", "list" ]
I have a list like: ``` list = [[1,2,3],[4,5,6],[7,8,9]] ``` I want to append a number at the start of every value in the list programmatically, say the number is 9. I want the new list to be like: ``` list = [[9,1,2,3],[9,4,5,6],[9,7,8,9]] ``` How do I go about doing this in Python? I know it is a very trivial que...
``` >>> someList = [[1,2,3],[4,5,6],[7,8,9]] >>> someList = [[9] + i for i in someList] >>> someList [[9, 1, 2, 3], [9, 4, 5, 6], [9, 7, 8, 9]] ``` (someList because list is already used by python)
Modifying list contents in Python
1,061,937
3
2009-06-30T05:55:24Z
1,061,960
16
2009-06-30T06:01:22Z
[ "python", "list" ]
I have a list like: ``` list = [[1,2,3],[4,5,6],[7,8,9]] ``` I want to append a number at the start of every value in the list programmatically, say the number is 9. I want the new list to be like: ``` list = [[9,1,2,3],[9,4,5,6],[9,7,8,9]] ``` How do I go about doing this in Python? I know it is a very trivial que...
``` for sublist in thelist: sublist.insert(0, 9) ``` **don't** use built-in names such as `list` for your own stuff, that's just a stupid accident in the making -- call YOUR stuff `mylist` or `thelist` or the like, **not** `list`. **Edit**: as the OP aks how to insert > 1 item at the start of each sublist, let me p...
python decimal comparison
1,062,008
12
2009-06-30T06:18:56Z
1,062,030
22
2009-06-30T06:26:26Z
[ "python", "comparison", "decimal" ]
python decimal comparison ``` >>> from decimal import Decimal >>> Decimal('1.0') > 2.0 True ``` I was expecting it to convert 2.0 correctly, but after reading thru [PEP 327](http://www.python.org/dev/peps/pep-0327) I understand there were some reason for not implictly converting float to Decimal, but shouldn't in tha...
Re 1, it's indeed the behavior we designed -- right or wrong as it may be (sorry if that trips your use case up, but we were trying to be general!). Specifically, it's long been the case that every Python object could be subject to inequality comparison with every other -- objects of types that aren't really comparabl...
Python NotImplemented constant
1,062,096
22
2009-06-30T06:52:12Z
1,062,124
25
2009-06-30T07:00:04Z
[ "python" ]
Looking through `decimal.py`, it uses `NotImplemented` in many special methods. e.g. ``` class A(object): def __lt__(self, a): return NotImplemented def __add__(self, a): return NotImplemented ``` The [Python docs say](http://docs.python.org/library/constants.html): > **NotImplemented** > > ...
`NotImplemented` allows you to indicate that a comparison between the two given operands has not been implemented (rather than indicating that the comparison is valid, but yields `False`, for the two operands). From the [Python Language Reference](http://www.network-theory.co.uk/docs/pylang/Coercionrules.html): > For...
Python win32 com : how to handle 'out' parameter?
1,062,129
5
2009-06-30T07:00:50Z
1,062,295
7
2009-06-30T07:48:48Z
[ "python", "com" ]
I need to access a third-party COM server with following interface definition (idl): ``` interface IDisplay : IDispatch { HRESULT getFramebuffer ( [in] ULONG aScreenId, [out] IFramebuffer * * aFramebuffer, [out] LONG * aXOrigin, [out] LONG * aYOrigin ); }; ``` As you can see, it returns 3 values via...
Since those are out parameters, can't you simply do the following? ``` Framebuffer, XOrigin, YOrigin = display.getFrameBuffer(ScreenId) ``` There is some good references in [Python Programming on Win32 Chapter 12 Advanced Python and COM](http://oreilly.com/catalog/pythonwin32/chapter/ch12.html) And they indicate tha...
Python Script Executed with Makefile
1,062,436
7
2009-06-30T08:28:39Z
1,062,466
14
2009-06-30T08:38:17Z
[ "python", "makefile" ]
I am writing python scripts and execute them in a Makefile. The python script is used to process data in a pipeline. I would like Makefile to execute the script every time I make a change to my python scripts. Does anyone have an idea of how to do this?
That's not a lot of information, so this answer is a bit vague. The basic principle of Makefiles is to list dependencies for each target; in this case, your target (let's call it foo) depends on your python script (let's call it do-foo.py): ``` foo: do-foo.py python do-foo.py > foo ``` Now foo will be rerun whene...
Reversible dictionary for python
1,063,319
6
2009-06-30T12:15:07Z
1,063,356
7
2009-06-30T12:22:31Z
[ "python", "dictionary", "hashtable" ]
I'd like to store some data in Python in a similar form to a dictionary: `{1:'a', 2:'b'}`. Every value will be unique, not just among other values, but among keys too. Is there a simple data structure that I can use to get the corresponding object no matter if I ask using the 'key' or the 'value'? For example: ``` >>...
Related posts: [Python mapping inverse](http://stackoverflow.com/questions/483666/python-reverse-inverse-a-mapping/483833) [Python 1:1 mappings](http://stackoverflow.com/questions/863935/a-data-structure-for-11-mappings-in-python) Of course, if all values and keys are unique, couldn't you just use a single dictionar...
Reversible dictionary for python
1,063,319
6
2009-06-30T12:15:07Z
1,063,393
9
2009-06-30T12:30:19Z
[ "python", "dictionary", "hashtable" ]
I'd like to store some data in Python in a similar form to a dictionary: `{1:'a', 2:'b'}`. Every value will be unique, not just among other values, but among keys too. Is there a simple data structure that I can use to get the corresponding object no matter if I ask using the 'key' or the 'value'? For example: ``` >>...
If your keys and values are non-overlapping, one obvious approach is to simply store them in the same dict. ie: ``` class BidirectionalDict(dict): def __setitem__(self, key, val): dict.__setitem__(self, key, val) dict.__setitem__(self, val, key) def __delitem__(self, key): dict.__delit...
how to use french letters in a django template?
1,063,626
5
2009-06-30T13:14:59Z
1,063,665
7
2009-06-30T13:23:52Z
[ "python", "django", "unicode" ]
I have some french letters (é, è, à...) in a django template but when it is loaded by django, an UnicodeDecodeError exception is raised. If I don't load the template but directly use a python string. It works ok. Is there something to do to use unicode with django template?
You are probably storing the template in a non-unicode encoding, such as latin-1. I believe Django assumes that templates are in UTF-8 by default (though there is a setting to override this). Your editor should be capable of saving the template file in the UTF-8 encoding (probably via a dropdown on the save as page, t...
Adding encoding alias to python
1,064,086
3
2009-06-30T14:47:20Z
1,064,308
7
2009-06-30T15:24:13Z
[ "python", "unicode", "character-encoding" ]
Is there a way that I can add alias to python for encoding. There are sites on the web that are using the encoding 'windows-1251' but have their charset set to win-1251, so I would like to have win-1251 be an alias to windows-1251
The `encodings` module is not well documented so I'd instead use `codecs`, which [is](http://docs.python.org/library/codecs.html): ``` import codecs def encalias(oldname, newname): old = codecs.lookup(oldname) new = codecs.CodecInfo(old.encode, old.decode, streamreader=old.streamreader, ...
In Python 2.5, how do I kill a subprocess?
1,064,335
26
2009-06-30T15:27:16Z
1,064,370
37
2009-06-30T15:32:06Z
[ "python", "subprocess" ]
I am using the subprocess package in Python to run a subprocess, which I later need to kill. However, the documentation of the subprocess package states that the terminate() function is only available from 2.6 We are running Linux with 2.5 and for backwards compatibility reasons I cannot upgrade to 2.6, what is the al...
You call os.kill on the process pid. ``` os.kill(process.pid, signal.SIGKILL) ``` You're OK because you're on on Linux. Windows users are out of luck.
In Python 2.5, how do I kill a subprocess?
1,064,335
26
2009-06-30T15:27:16Z
1,064,430
40
2009-06-30T15:41:43Z
[ "python", "subprocess" ]
I am using the subprocess package in Python to run a subprocess, which I later need to kill. However, the documentation of the subprocess package states that the terminate() function is only available from 2.6 We are running Linux with 2.5 and for backwards compatibility reasons I cannot upgrade to 2.6, what is the al...
To complete @Gareth's answer, on Windows you do: ``` import ctypes PROCESS_TERMINATE = 1 handle = ctypes.windll.kernel32.OpenProcess(PROCESS_TERMINATE, False, theprocess.pid) ctypes.windll.kernel32.TerminateProcess(handle, -1) ctypes.windll.kernel32.CloseHandle(handle) ``` not quite as elegant as `os.kill(theprocess....
What can you do with COM/ActiveX in Python?
1,065,844
23
2009-06-30T20:24:44Z
1,067,842
25
2009-07-01T07:59:48Z
[ "python", "com", "crystal-reports", "activex", "pywin32" ]
I'm thinking that I'm going to have to run monthly reports in Crystal Reports. I've read that you can automate this with COM/ActiveX but I'm not that advanced to understand what this is or what you can even do with it. I'm fairly familiar with Python and it looks like from what I've read, I might be able to open the r...
First you have to install the wonderful [pywin32](http://sourceforge.net/projects/pywin32/) module. It provides COM support. You need to run the makepy utility. It is located at C:...\Python26\Lib\site-packages\win32com\client. On Vista, it must be ran with admin rights. This utility will show all available COM objec...
How to reduce color palette with PIL
1,065,945
11
2009-06-30T20:43:32Z
1,074,680
22
2009-07-02T14:22:06Z
[ "python", "image", "colors", "python-imaging-library", "palette" ]
I'm not sure how I would go about reducing the color palette of a PIL Image. I would like to reduce an image's palette to the 5 prominent colors found in that image. My overall goal is to do some basic color sampling.
That's easy, just use the undocumented colors argument: ``` result = image.convert('P', palette=Image.ADAPTIVE, colors=5) ``` I'm using Image.ADAPTIVE to avoid dithering
find length of sequences of identical values in a numpy array
1,066,758
19
2009-07-01T00:19:18Z
1,066,838
22
2009-07-01T01:04:34Z
[ "python", "matlab", "numpy", "matplotlib" ]
In a pylab program (which could probably be a matlab program as well) I have a numpy array of numbers representing distances: `d[t]` is the *distance* at time `t` (and the timespan of my data is `len(d)` time units). The events I'm interested in are when the distance is below a certain threshold, and I want to compute...
While not `numpy` primitives, `itertools` functions are often very fast, so do give this one a try (and measure times for various solutions including this one, of course): ``` def runs_of_ones(bits): for bit, group in itertools.groupby(bits): if bit: yield sum(group) ``` If you do need the values in a list, jus...
How to extract top-level domain name (TLD) from URL
1,066,933
31
2009-07-01T01:42:03Z
1,066,947
35
2009-07-01T01:48:50Z
[ "python", "url", "parsing", "dns", "extract" ]
how would you extract the domain name from a URL, excluding any subdomains? My initial simplistic attempt was: ``` '.'.join(urlparse.urlparse(url).netloc.split('.')[-2:]) ``` This works for <http://www.foo.com>, but not <http://www.foo.com.au>. Is there a way to do this properly without using special knowledge about...
No, there is no "intrinsic" way of knowing that (e.g.) `zap.co.it` is a subdomain (because Italy's registrar DOES sell domains such as `co.it`) while `zap.co.uk` *isn't* (because the UK's registrar DOESN'T sell domains such as `co.uk`, but only like `zap.co.uk`). You'll just have to use an auxiliary table (or online s...
How to extract top-level domain name (TLD) from URL
1,066,933
31
2009-07-01T01:42:03Z
1,069,780
37
2009-07-01T15:23:52Z
[ "python", "url", "parsing", "dns", "extract" ]
how would you extract the domain name from a URL, excluding any subdomains? My initial simplistic attempt was: ``` '.'.join(urlparse.urlparse(url).netloc.split('.')[-2:]) ``` This works for <http://www.foo.com>, but not <http://www.foo.com.au>. Is there a way to do this properly without using special knowledge about...
using [this file of effective tlds](http://mxr.mozilla.org/mozilla/source/netwerk/dns/src/effective_tld_names.dat?raw=1) which [someone else](http://stackoverflow.com/questions/569137/how-to-get-domain-name-from-url/569176#569176) found on mozzila's website: ``` from __future__ import with_statement from urlparse impo...
How to extract top-level domain name (TLD) from URL
1,066,933
31
2009-07-01T01:42:03Z
7,388,904
33
2011-09-12T13:46:06Z
[ "python", "url", "parsing", "dns", "extract" ]
how would you extract the domain name from a URL, excluding any subdomains? My initial simplistic attempt was: ``` '.'.join(urlparse.urlparse(url).netloc.split('.')[-2:]) ``` This works for <http://www.foo.com>, but not <http://www.foo.com.au>. Is there a way to do this properly without using special knowledge about...
Here's a great python module someone wrote to solve this problem after seeing this question: <https://github.com/john-kurkowski/tldextract> The module looks up TLDs in the [Public Suffix List](https://www.publicsuffix.org/), mantained by Mozilla volunteers Quote: > `tldextract` on the other hand knows what all gTLDs...
How to extract top-level domain name (TLD) from URL
1,066,933
31
2009-07-01T01:42:03Z
16,580,707
16
2013-05-16T06:46:41Z
[ "python", "url", "parsing", "dns", "extract" ]
how would you extract the domain name from a URL, excluding any subdomains? My initial simplistic attempt was: ``` '.'.join(urlparse.urlparse(url).netloc.split('.')[-2:]) ``` This works for <http://www.foo.com>, but not <http://www.foo.com.au>. Is there a way to do this properly without using special knowledge about...
Using python tld <https://pypi.python.org/pypi/tld> pip install tld ``` from tld import get_tld print get_tld("http://www.google.co.uk") ``` # print out: google.co.uk
Translating Perl to Python
1,067,060
14
2009-07-01T02:50:40Z
1,067,151
45
2009-07-01T03:25:54Z
[ "python", "perl", "rewrite" ]
I found this Perl script while [migrating my SQLite database to mysql](http://stackoverflow.com/questions/18671/quick-easy-way-to-migrate-sqlite3-to-mysql/25860) I was wondering (since I don't know Perl) how could one rewrite this in Python? Bonus points for the shortest (code) answer :) **edit**: sorry I meant shor...
Here's a pretty literal translation with just the minimum of obvious style changes (putting all code into a function, using string rather than re operations where possible). ``` import re, fileinput def main(): for line in fileinput.input(): process = False for nope in ('BEGIN TRANSACTION','COMMIT', ...
Translating Perl to Python
1,067,060
14
2009-07-01T02:50:40Z
3,675,869
10
2010-09-09T10:55:41Z
[ "python", "perl", "rewrite" ]
I found this Perl script while [migrating my SQLite database to mysql](http://stackoverflow.com/questions/18671/quick-easy-way-to-migrate-sqlite3-to-mysql/25860) I was wondering (since I don't know Perl) how could one rewrite this in Python? Bonus points for the shortest (code) answer :) **edit**: sorry I meant shor...
[Alex Martelli's solution above](http://stackoverflow.com/questions/1067060/translating-perl-to-python/1067151#1067151) works good, but needs some fixes and additions: In the lines using regular expression substitution, the insertion of the matched groups must be double-escaped OR the replacement string must be prefix...
Python unittest: how to run only part of a test file?
1,068,246
44
2009-07-01T09:40:32Z
1,068,366
38
2009-07-01T10:23:27Z
[ "python", "unit-testing", "pyunit" ]
I have a test file that contains tests taking quite a lot of time (they send calculations to a cluster and wait for the result). All of these are in specific TestCase class. Since they take time and furthermore are not likely to break, I'd want to be able to choose whether this subset of tests does or doesn't run (the...
The default `unittest.main()` uses the default test loader to make a TestSuite out of the module in which main is running. You don't have to use this default behavior. You can, for example, make three [unittest.TestSuite](http://docs.python.org/library/unittest.html#unittest.TestSuite) instances. 1. The "fast" subse...
Python unittest: how to run only part of a test file?
1,068,246
44
2009-07-01T09:40:32Z
12,696,073
8
2012-10-02T18:28:18Z
[ "python", "unit-testing", "pyunit" ]
I have a test file that contains tests taking quite a lot of time (they send calculations to a cluster and wait for the result). All of these are in specific TestCase class. Since they take time and furthermore are not likely to break, I'd want to be able to choose whether this subset of tests does or doesn't run (the...
Actually, one can pass the names of the test case as sys.argv and only those cases will be tested. For instance, suppose you have ``` class TestAccount(unittest.TestCase): ... class TestCustomer(unittest.TestCase): ... class TestShipping(unittest.TestCase): ... account = TestAccount customer = TestCust...
Python unittest: how to run only part of a test file?
1,068,246
44
2009-07-01T09:40:32Z
17,817,391
59
2013-07-23T17:48:07Z
[ "python", "unit-testing", "pyunit" ]
I have a test file that contains tests taking quite a lot of time (they send calculations to a cluster and wait for the result). All of these are in specific TestCase class. Since they take time and furthermore are not likely to break, I'd want to be able to choose whether this subset of tests does or doesn't run (the...
To run only a single specific test you can use: ``` $ python -m unittest test_module.TestClass.test_method ``` More information [here](http://pythontesting.net/framework/specify-test-unittest-nosetests-pytest/)
Django way to do conditional formatting
1,068,573
5
2009-07-01T11:21:30Z
1,068,616
8
2009-07-01T11:30:08Z
[ "python", "django", "formatting", "django-templates" ]
What is the correct way to do conditional formatting in Django? I have a model that contains a date field, and I would like to display a list of records, but colour the rows depending on the value of that date field. For example, records that match today's date I want to be yellow, records that is before today I want ...
I'm a big fan of putting ALL "business" logic in the view function and ALL presentation in the templates/CSS. Option 1 is ideal. You return a list of pairs: ( date, state ), where the state is the class name ("past", "present", "future"). Your template then uses the state information as the class for a `<span>`. Your...
How to create "virtual root" with Python's ElementTree?
1,070,772
5
2009-07-01T19:02:08Z
1,070,796
7
2009-07-01T19:07:24Z
[ "python", "elementtree" ]
I am trying to use Python's ElementTree to generate an XHTML file. However, the ElementTree.Element() just lets me create a single tag (e.g., HTML). I need to create some sort of a virtual root or whatever it is called so that I can put the various , DOCTYPES, etc. How do I do that? Thanks
I don't know if there's a better way but I've seen this done: Create the base document as a string: ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html></html> ``` Then parse that string to start your new document.
Equivalent for inject() in Python?
1,070,926
8
2009-07-01T19:36:42Z
1,070,965
19
2009-07-01T19:45:01Z
[ "python", "functional-programming" ]
In Ruby, I'm used to using Enumerable#inject for going through a list or other structure and coming back with some conclusion about it. For example, ``` [1,3,5,7].inject(true) {|allOdd, n| allOdd && n % 2 == 1} ``` to determine if every element in the array is odd. What would be the appropriate way to accomplish the ...
To determine if every element is odd, I'd use [`all()`](http://docs.python.org/library/functions.html#all) ``` def is_odd(x): return x%2==1 result = all(is_odd(x) for x in [1,3,5,7]) ``` In general, however, Ruby's `inject` is most like Python's [`reduce()`](http://docs.python.org/library/functions.html#reduce)...
Writing a website in Python
1,070,999
19
2009-07-01T19:50:19Z
1,071,015
11
2009-07-01T19:54:00Z
[ "python" ]
I'm pretty proficient in PHP, but want to try something new. I'm also know a bit of Python, enough to do the basics of the basics, but haven't used in a web design type situation. I've just written this, which works: ``` #!/usr/bin/python def main(): print "Content-type: text/html" print print "<html><h...
As far as full frameworks go I believe Django is relatively small. If you *really* want lightweight, though, check out [web.py](http://webpy.org/), [CherryPy](http://www.cherrypy.org/), [Pylons](http://pylonshq.com/) and [web2py](http://www.web2py.com/). I think the crowd favorite from the above is Pylons, but I am a...
Writing a website in Python
1,070,999
19
2009-07-01T19:50:19Z
1,071,040
8
2009-07-01T19:59:03Z
[ "python" ]
I'm pretty proficient in PHP, but want to try something new. I'm also know a bit of Python, enough to do the basics of the basics, but haven't used in a web design type situation. I've just written this, which works: ``` #!/usr/bin/python def main(): print "Content-type: text/html" print print "<html><h...
There are a couple of web frameworks available in python, that will relieve you from most of the work 1. [Django](http://docs.djangoproject.com/en/dev/) 2. [Pylons](http://pylonshq.com/) (and the new TurboGears, based on it). 3. [Web2py](http://www.web2py.com/) 4. [CherryPy](http://www.cherrypy.org/) (and the old Turb...
Writing a website in Python
1,070,999
19
2009-07-01T19:50:19Z
1,071,129
24
2009-07-01T20:14:25Z
[ "python" ]
I'm pretty proficient in PHP, but want to try something new. I'm also know a bit of Python, enough to do the basics of the basics, but haven't used in a web design type situation. I've just written this, which works: ``` #!/usr/bin/python def main(): print "Content-type: text/html" print print "<html><h...
Your question was about basic CGI scripting, looking at your example, but it seems like everyone has chosen to answer it with "use my favorite framework". Let's try a different approach. If you're looking for a direct replacement for what you wrote above (ie. CGI scripting), then you're probably looking for the [cgi](...
Pylons: address already in use when trying to serve
1,071,071
3
2009-07-01T20:03:07Z
9,109,982
15
2012-02-02T09:35:17Z
[ "python", "nginx", "pylons", "paste", "paster" ]
I'm running pylons and I did this: paster server development.ini It's running on :5000 But when I try to run the command again: paster serve development.ini I get this message: socket.error: [Errno 98] Address already in use Any ideas?
I've found this trick in a forum: This will kill all programs listening to port 5000 ``` kill -9 `fuser -n tcp 5000` ```
Detect URLs in a string and wrap with "<a href..." tag
1,071,191
6
2009-07-01T20:22:25Z
1,071,294
7
2009-07-01T20:42:08Z
[ "python", "html", "regex" ]
I am looking to write something that seems like it should be easy enough, but for whatever reason I'm having a tough time getting my head around it. I am looking to write a python function that, when passed a string, will pass that string back with HTML encoding around URLs. ``` unencoded_string = "This is a link - h...
The "regex magic" you need is just `sub` (which does a substitution): ``` def encode_string_with_links(unencoded_string): return URL_REGEX.sub(r'<a href="\1">\1</a>', unencoded_string) ``` `URL_REGEX` could be something like: ``` URL_REGEX = re.compile(r'''((?:mailto:|ftp://|http://)[^ <>'"{}|\\^`[\]]*)''') ``` T...
Why does list comprehension using a zip object results in an empty list?
1,071,201
6
2009-07-01T20:24:37Z
1,071,239
17
2009-07-01T20:31:16Z
[ "python", "zip", "list-comprehension" ]
``` f = lambda x : 2*x g = lambda x : x ** 2 h = lambda x : x ** x funcTriple = ( f, g, h ) myZip = ( zip ( funcTriple, (1, 3, 5) ) ) k = lambda pair : pair[0](pair[1]) # Why do Output # 1 (2, 9, 3125) and Output # 2 ( [ ] ) differ? print ("\n\nOutput # 1: for pair in myZip: k(pair) ...") for pair in myZip : pri...
Works perfectly in Python 2.6 but fails in Python 3.0 because `zip` returns a generator-style object and the first loop exhausts it. Make a list instead: ``` myZip = list( zip ( funcTriple, (1, 3, 5) ) ) ``` and it works in Python 3.0
python class variable not visible in __init__?
1,071,469
5
2009-07-01T21:25:34Z
1,071,491
11
2009-07-01T21:30:21Z
[ "python" ]
This code produces an error message, which I found surprising: ``` class Foo(object): custom = 1 def __init__(self, custom=Foo.custom): self._custom = custom x = Foo() ``` Can anyone provide enlightenment?
It's `Foo` that isn't visible, because you're in the middle of building it. But since you're in the same scope as `custom`, you can just say `custom` rather than `Foo.custom`: ``` class Foo(object): custom = 1 def __init__(self, mycustom=custom): self._custom = mycustom ``` But note that changing `Foo...
I need a Python class that keep tracks of how many times it is instantiated
1,071,935
4
2009-07-02T00:12:36Z
1,071,939
11
2009-07-02T00:14:04Z
[ "python", "class", "instances" ]
I need a class that works like this: ``` >>> a=Foo() >>> b=Foo() >>> c=Foo() >>> c.i 3 ``` Here is my try: ``` class Foo(object): i = 0 def __init__(self): Foo.i += 1 ``` It works as required, but I wonder if there is a more pythonic way to do it.
Nope. That's pretty good. From The Zen of Python: "Simple is better than complex." That works fine and is clear on what you're doing, don't complicate it. Maybe name it `counter` or something, but other than that you're good to go as far as pythonic goes.
Python Language Question: attributes of object() vs Function
1,072,649
17
2009-07-02T05:27:25Z
1,072,669
22
2009-07-02T05:33:52Z
[ "python", "function", "object" ]
In python, it is illegal to create new attribute for an object instance like this ``` >>> a = object() >>> a.hhh = 1 ``` throws ``` Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'object' object has no attribute 'hhh' ``` However, for a function object, it is OK. ``` >>> d...
The reason function objects support arbitrary attributes is that, before we added that feature, several frameworks (e.g. parser generator ones) were abusing function docstrings (and other attribute of function objects) to stash away per-function information that was crucial to them -- the need for such association of a...
Python Language Question: attributes of object() vs Function
1,072,649
17
2009-07-02T05:27:25Z
1,072,763
7
2009-07-02T06:15:15Z
[ "python", "function", "object" ]
In python, it is illegal to create new attribute for an object instance like this ``` >>> a = object() >>> a.hhh = 1 ``` throws ``` Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'object' object has no attribute 'hhh' ``` However, for a function object, it is OK. ``` >>> d...
Alex Martelli posted an awesome answer to your question. For anyone who is looking for a good way to accomplish arbitrary attributes on an empty object, do this: ``` class myobject(object): pass o = myobject() o.anything = 123 ``` Or more efficient (and better documented) if you know the attributes: ``` class m...
Is modifying a class variable in python threadsafe?
1,072,821
13
2009-07-02T06:38:59Z
1,073,230
20
2009-07-02T08:48:52Z
[ "python", "multithreading" ]
I was reading [this question](http://stackoverflow.com/questions/1071935/i-need-a-python-class-that-keep-tracks-of-how-many-times-it-is-instanciated) (which you do not have to read because I will copy what is there... I just wanted to give show you my inspiration)... So, if I have a class that counts how many instance...
It's not threadsafe even on CPython. Try this to see for yourself: ``` import threading class Foo(object): instance_count = 0 def inc_by(n): for i in xrange(n): Foo.instance_count += 1 threads = [threading.Thread(target=inc_by, args=(100000,)) for thread_nr in xrange(100)] for thread in threads: thr...
Is modifying a class variable in python threadsafe?
1,072,821
13
2009-07-02T06:38:59Z
1,074,035
7
2009-07-02T12:17:09Z
[ "python", "multithreading" ]
I was reading [this question](http://stackoverflow.com/questions/1071935/i-need-a-python-class-that-keep-tracks-of-how-many-times-it-is-instanciated) (which you do not have to read because I will copy what is there... I just wanted to give show you my inspiration)... So, if I have a class that counts how many instance...
No it is not thread safe. I've faced a similar problem a few days ago and I choosed to implement the lock thanks to a decorator. The benefit is that it makes the code readable: ``` def threadsafe_function(fn): """decorator making sure that the decorated function is thread safe""" lock = threading.Lock() de...
How to convert XSD to Python Class
1,072,853
29
2009-07-02T06:49:23Z
1,072,989
24
2009-07-02T07:35:15Z
[ "python", "xml", "data-binding", "xsd", "xsd2code" ]
I just want to know if there is a program that can convert an XSD file to a Python class as **JAXB** does for Java?
[generateDS](http://pythonhosted.org/generateDS/) : I think this is the good tool I need Edit : Actually, generateDS does very well the job !! It generates the Python class with all methods (setters and getters, export to XML, import from XML). It works very well !
How to convert XSD to Python Class
1,072,853
29
2009-07-02T06:49:23Z
10,815,021
8
2012-05-30T11:06:22Z
[ "python", "xml", "data-binding", "xsd", "xsd2code" ]
I just want to know if there is a program that can convert an XSD file to a Python class as **JAXB** does for Java?
PyXB: <http://pyxb.sourceforge.net/>
Printing python modulus operator as it is over command line
1,072,951
3
2009-07-02T07:21:52Z
1,072,963
7
2009-07-02T07:25:29Z
[ "python", "operators", "modulo" ]
I want to print modulus operator as it is over the command line: E.g this is how the output should look like: 1%2 2%4 or 30% 40% I am using the print statement like this: > print 'computing %s % %s' % (num1, > num2) Its throwing the default error: > TypeError: not all arguments > converted during string fo...
Escape the % sign with another % sign, like this: ``` print 'computing %s %% %s' % (num1, num2) ```
Is generator.next() visible in python 3.0?
1,073,396
82
2009-07-02T09:29:44Z
1,073,407
49
2009-07-02T09:31:19Z
[ "python", "python-3.x", "iteration" ]
I have a generator that generates a series, for example: ``` def triangleNums(): '''generate series of triangle numbers''' tn = 0 counter = 1 while(True): tn = tn + counter yield tn counter = counter + 1 ``` in python 2.6 I am able to make the following calls: ``` g = triangle...
Try: ``` next(g) ``` Check out [this neat table](http://www.diveinto.org/python3/porting-code-to-python-3-with-2to3.html#next) that shows the differences in syntax between 2 and 3 when it comes to this.
Is generator.next() visible in python 3.0?
1,073,396
82
2009-07-02T09:29:44Z
1,073,582
143
2009-07-02T10:15:53Z
[ "python", "python-3.x", "iteration" ]
I have a generator that generates a series, for example: ``` def triangleNums(): '''generate series of triangle numbers''' tn = 0 counter = 1 while(True): tn = tn + counter yield tn counter = counter + 1 ``` in python 2.6 I am able to make the following calls: ``` g = triangle...
Correct, `g.next()` has been renamed to `g.__next__()`. The reason for this is to have consistence. Special methods like `__init__()` and `__del__` all have double underscores (or "dunder" as it is getting popular to call them now), and .next() is one of the few exceptions to that rule. Python 3.0 fixes that. [\*] But...
Why does SCons VariantDir() not put output in the given directory?
1,074,062
7
2009-07-02T12:26:40Z
1,074,587
7
2009-07-02T14:10:23Z
[ "python", "c", "makefile", "scons" ]
I'm thinking about using [SCons](http://www.scons.org/) for a new project. It looks really good, though I'm finding `VariantDir` quite confusing. I have a simple project with a handful of C source files in one directory, and I want to build in "normal" and in "profile" mode -- with two different sets of options to gcc...
Yes, VariantDir is confusing in scons. Although not well advertised, you can put both SConstruct and SConscript in the same directory, using the current directory as the source directory ``` # SConstruct SConscript('SConscript', build_dir='build', src='.') ``` and ``` # SConscript Program('main.c') ``` I have never...
Serve a dynamically generated image with Django
1,074,200
23
2009-07-02T12:59:55Z
1,074,277
22
2009-07-02T13:15:02Z
[ "python", "ajax", "django", "image" ]
How do I serve a dynamically generated image in Django? I have an html tag ``` <html> ... <img src="images/dynamic_chart.png" /> ... </html> ``` linked up to this request handler, which creates an in-memory image ``` def chart(request): img = Image.new("RGB", (300,300), "#FFFFFF") data = [(i,randint(100...
I assume you're using PIL (Python Imaging Library). You need to replace your last line with (for example, if you want to serve a PNG image): ``` response = HttpResponse(mimetype="image/png") img.save(response, "PNG") return response ``` See [here](http://effbot.org/zone/django-pil.htm) for more information.
CherryPy interferes with Twisted shutting down on Windows
1,075,351
7
2009-07-02T16:25:05Z
1,080,010
14
2009-07-03T16:14:12Z
[ "python", "windows", "linux", "twisted", "cherrypy" ]
I've got an application that runs Twisted by starting the reactor with `reactor.run()` in my main thread after starting some other threads, including the CherryPy web server. Here's a program that shuts down cleanly when Ctrl+C is pressed on Linux but not on Windows: ``` from threading import Thread from signal import...
CherryPy handles signals by default when you call quickstart. In your case, you should probably just unroll quickstart, which is only a few lines, and pick and choose. Here's basically what quickstart does in trunk: ``` if config: cherrypy.config.update(config) tree.mount(root, script_name, config) if hasattr(en...
Does python have hooks into EXT3
1,075,391
4
2009-07-02T16:32:54Z
1,075,459
7
2009-07-02T16:45:20Z
[ "python", "linux", "ext3" ]
We have several cron jobs that ftp proxy logs to a centralized server. These files can be rather large and take some time to transfer. Part of the requirement of this project is to provide a logging mechanism in which we log the success or failure of these transfers. This is simple enough. My question is, is there a w...
no need for ext3-specific hooks; just check `lsof`, or more exactly, `/proc/<pid>/fd/*` and `/proc/<pid>/fdinfo/*` (that's where `lsof` gets it's info, AFAICT). There you can check if the file is open, if it's writeable, and the 'cursor' position. That's not the whole picture; but any more is done in processpace by st...
Using the AND and NOT Operator in Python
1,075,652
36
2009-07-02T17:22:44Z
1,075,667
15
2009-07-02T17:27:17Z
[ "python", "operators" ]
Here is my custom class that I have that represents a triangle. I'm trying to write code that checks to see if `self.a`, `self.b`, and `self.c` are greater than 0, which would mean that I have Angle, Angle, Angle. Below you will see the code that checks for A and B, however when I use just `self.a != 0` then it works ...
Use the keyword "and", not &. & is a bit operator. Be careful with this... just so you know, in Java and C++, the "&" operator is ALSO a bit operator. The correct way to do a boolean comparison in those languages is "&&". Similarly "|" is a bit operator, and "||" is a boolean operator. In python "and", and "or" are us...
Using the AND and NOT Operator in Python
1,075,652
36
2009-07-02T17:22:44Z
1,075,700
70
2009-07-02T17:34:31Z
[ "python", "operators" ]
Here is my custom class that I have that represents a triangle. I'm trying to write code that checks to see if `self.a`, `self.b`, and `self.c` are greater than 0, which would mean that I have Angle, Angle, Angle. Below you will see the code that checks for A and B, however when I use just `self.a != 0` then it works ...
You should write : ``` if (self.a != 0) and (self.b != 0) : ``` "`&`" is the bit wise operator and does not suit for boolean operations. The equivalent of "`&&`" is "and" in Python. A shorter way to check what you want is to use the "in" operator : ``` if 0 not in (self.a, self.b) : ``` You can check if anything i...
Django template can't see CSS files
1,075,753
20
2009-07-02T17:45:34Z
1,075,769
13
2009-07-02T17:49:13Z
[ "python", "css", "django", "django-templates" ]
I'm building a django app and I can't get the templates to see the CSS files... My settings.py file looks like: ``` MEDIA_ROOT = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'media') MEDIA_URL = '/media/' ``` I've got the CSS files in /mysite/media/css/ and the template code contains: ``` <link rel="styl...
in the "development only" block in your urls.py you need to change ``` (r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': '/media'}), ``` to... ``` (r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}), ```
Extending Python with C/C++
1,076,300
4
2009-07-02T19:42:30Z
1,076,318
8
2009-07-02T19:45:43Z
[ "c++", "python", "c" ]
Can anyone please give me tips on the tools or sofware to use to extend Python with C/C++? Thanks.
We use SWIG to wrap our C/C++ libraries for use in Python. It works quite well. <http://www.swig.org/>
Extending Python with C/C++
1,076,300
4
2009-07-02T19:42:30Z
1,076,321
10
2009-07-02T19:46:35Z
[ "c++", "python", "c" ]
Can anyone please give me tips on the tools or sofware to use to extend Python with C/C++? Thanks.
The Python website itself has a great [set of examples](http://docs.python.org/extending/), as well as [API documentation](http://docs.python.org/c-api/). That's literally all I used when I needed to write C extensions.
Extending Python with C/C++
1,076,300
4
2009-07-02T19:42:30Z
1,076,328
13
2009-07-02T19:47:25Z
[ "c++", "python", "c" ]
Can anyone please give me tips on the tools or sofware to use to extend Python with C/C++? Thanks.
I'll add the obligatory reference to [Boost.Python](http://www.boost.org/doc/libs/1%5F39%5F0/libs/python/doc/index.html) for C++ stuff.
Replacing values in a Python list/dictionary?
1,076,536
19
2009-07-02T20:29:28Z
1,076,567
9
2009-07-02T20:38:05Z
[ "python", "list", "dictionary", "replace" ]
Ok, I am trying to filter a list/dictionary passed to me and "clean" it up a bit, as there are certain values in it that I need to get rid of. So, if it's looking like this: ``` "records": [{"key1": "AAA", "key2": "BBB", "key3": "CCC", "key4": "AAA"...}] ``` How would I quickly and easily run through it all and repl...
``` dic = root['records'][0] for i, j in dic.items(): # use iteritems in py2k if j == 'AAA': dic[i] = 'xxx' ```
Replacing values in a Python list/dictionary?
1,076,536
19
2009-07-02T20:29:28Z
1,076,577
26
2009-07-02T20:40:17Z
[ "python", "list", "dictionary", "replace" ]
Ok, I am trying to filter a list/dictionary passed to me and "clean" it up a bit, as there are certain values in it that I need to get rid of. So, if it's looking like this: ``` "records": [{"key1": "AAA", "key2": "BBB", "key3": "CCC", "key4": "AAA"...}] ``` How would I quickly and easily run through it all and repl...
``` DATA = {"records": [{"key1": "AAA", "key2": "BBB", "key3": "CCC", "key4": "AAA"}]} for name, datalist in DATA.iteritems(): # Or items() in Python 3.x for datadict in datalist: for key, value in datadict.items(): if value == "AAA": datadict[key] = "XXX" print (DATA) # Print...
Trouble using python PIL library to crop and save image
1,076,638
27
2009-07-02T20:54:04Z
1,076,648
46
2009-07-02T20:56:50Z
[ "python", "python-imaging-library" ]
Im attempting to crop a pretty high res image and save the result to make sure its completed. However I keep getting the following error regardless of how I use the save method: `SystemError: tile cannot extend outside image` ``` from PIL import Image # size is width/height img = Image.open('0_388_image1.jpeg') box =...
The box is (left, upper, right, lower) so maybe you meant (2407, 804, 2407+71, 804+796)? **Edit**: All four coordinates are measured from the top/left corner, and describe the distance from that corner to the left edge, top edge, right edge and bottom edge. Your code should look like this, to get a 300x200 area from ...
Trouble using python PIL library to crop and save image
1,076,638
27
2009-07-02T20:54:04Z
17,653,193
10
2013-07-15T11:28:06Z
[ "python", "python-imaging-library" ]
Im attempting to crop a pretty high res image and save the result to make sure its completed. However I keep getting the following error regardless of how I use the save method: `SystemError: tile cannot extend outside image` ``` from PIL import Image # size is width/height img = Image.open('0_388_image1.jpeg') box =...
Try this: it's a simple code to crop an image, and it works like a charm ;) ``` import Image def crop_image(input_image, output_image, start_x, start_y, width, height): """Pass input name image, output name image, x coordinate to start croping, y coordinate to start croping, width to crop, height to crop """ ...
Making a variable non-inheritable in python
1,076,718
3
2009-07-02T21:13:36Z
1,076,737
7
2009-07-02T21:17:31Z
[ "python", "inheritance" ]
Is there a way to make a variable non-inheritable in python? Like in the following example: B is a subclass of A, but I want it to have its own SIZE value. Could I get an Error to be raised (on \_\_init\_\_ or on getsize()) if B doesn't override SIZE? ``` class A: SIZE = 5 def getsize(self): return self.SIZE c...
Use a double-underscore prefix: (Double-underscore solution deleted after Emma's clarification) OK, you can do it like this: ``` class A: SIZE = 5 def __init__(self): if self.__class__ != A: del self.SIZE def getsize(self): return self.SIZE class B(A): pass a = A() prin...
urllib.urlopen isn't working. Is there a workaround?
1,076,958
2
2009-07-02T22:25:44Z
1,077,370
7
2009-07-03T00:40:01Z
[ "python", "url" ]
I'm getting a getaddress error and after doing some sleuthing, it looks like it might be my corporate intranet not allowing the connection (I'm assuming due to security, although it is strange that IE works but won't allow Python to open a url). Is there a safe way to get around this? Here's the exact error: ``` Trac...
You probably need to fill in proxy information. ``` import urllib2 proxy_handler = urllib2.ProxyHandler({'http': 'http://yourcorporateproxy:12345/'}) proxy_auth_handler = urllib2.HTTPBasicAuthHandler() proxy_auth_handler.add_password('realm', 'host', 'username', 'password') opener = urllib2.build_opener(proxy_handler...
python list comprehensions; compressing a list of lists?
1,077,015
35
2009-07-02T22:40:40Z
1,077,074
35
2009-07-02T22:50:47Z
[ "functional-programming", "python", "list-comprehension" ]
guys. I'm trying to find the most elegant solution to a problem and wondered if python has anything built-in for what I'm trying to do. What I'm doing is this. I have a list, `A`, and I have a function `f` which takes an item and returns a list. I can use a list comprehension to convert everything in `A` like so; ```...
You can find a good answer in [itertools' recipes:](http://docs.python.org/library/itertools.html#recipes) ``` def flatten(listOfLists): return list(chain.from_iterable(listOfLists)) ``` (Note: requires Python 2.6+)
python list comprehensions; compressing a list of lists?
1,077,015
35
2009-07-02T22:40:40Z
1,077,205
58
2009-07-02T23:32:56Z
[ "functional-programming", "python", "list-comprehension" ]
guys. I'm trying to find the most elegant solution to a problem and wondered if python has anything built-in for what I'm trying to do. What I'm doing is this. I have a list, `A`, and I have a function `f` which takes an item and returns a list. I can use a list comprehension to convert everything in `A` like so; ```...
You can have nested iterations in a single list comprehension: ``` [filename for path in dirs for filename in os.listdir(path)] ```
python list comprehensions; compressing a list of lists?
1,077,015
35
2009-07-02T22:40:40Z
1,077,220
11
2009-07-02T23:37:11Z
[ "functional-programming", "python", "list-comprehension" ]
guys. I'm trying to find the most elegant solution to a problem and wondered if python has anything built-in for what I'm trying to do. What I'm doing is this. I have a list, `A`, and I have a function `f` which takes an item and returns a list. I can use a list comprehension to convert everything in `A` like so; ```...
You could just do the straightforward: ``` subs = [] for d in dirs: subs.extend(os.listdir(d)) ```
python list comprehensions; compressing a list of lists?
1,077,015
35
2009-07-02T22:40:40Z
1,079,210
10
2009-07-03T12:47:57Z
[ "functional-programming", "python", "list-comprehension" ]
guys. I'm trying to find the most elegant solution to a problem and wondered if python has anything built-in for what I'm trying to do. What I'm doing is this. I have a list, `A`, and I have a function `f` which takes an item and returns a list. I can use a list comprehension to convert everything in `A` like so; ```...
You can concatenate lists using the normal addition operator: ``` >>> [1, 2] + [3, 4] [1, 2, 3, 4] ``` The built-in function `sum` will add the numbers in a sequence and can optionally start from a specific value: ``` >>> sum(xrange(10), 100) 145 ``` Combine the above to flatten a list of lists: ``` >>> sum([[1, 2...
python list comprehensions; compressing a list of lists?
1,077,015
35
2009-07-02T22:40:40Z
2,082,107
25
2010-01-17T18:32:30Z
[ "functional-programming", "python", "list-comprehension" ]
guys. I'm trying to find the most elegant solution to a problem and wondered if python has anything built-in for what I'm trying to do. What I'm doing is this. I have a list, `A`, and I have a function `f` which takes an item and returns a list. I can use a list comprehension to convert everything in `A` like so; ```...
``` >>> listOfLists = [[1, 2],[3, 4, 5], [6]] >>> reduce(list.__add__, listOfLists) [1, 2, 3, 4, 5, 6] ``` I'm guessing the itertools solution is more efficient than this, but this feel very pythonic and avoids having to import a library just for the sake of a single list operation.
python list comprehensions; compressing a list of lists?
1,077,015
35
2009-07-02T22:40:40Z
20,037,408
9
2013-11-17T23:07:11Z
[ "functional-programming", "python", "list-comprehension" ]
guys. I'm trying to find the most elegant solution to a problem and wondered if python has anything built-in for what I'm trying to do. What I'm doing is this. I have a list, `A`, and I have a function `f` which takes an item and returns a list. I can use a list comprehension to convert everything in `A` like so; ```...
The question proposed `flatmap`. Some implementations are proposed but they may unnecessary creating intermediate lists. Here is one implementation that's base on iterators. ``` def flatmap(func, *iterable): return itertools.chain.from_iterable(map(func, *iterable)) In [148]: list(flatmap(os.listdir, ['c:/mfg','c...
How to specify time zone (UTC) when converting to Unix time? (Python)
1,077,285
5
2009-07-03T00:00:45Z
1,077,362
12
2009-07-03T00:33:03Z
[ "python", "datetime", "iso8601", "unix-timestamp" ]
I have a utc timestamp in the IS8601 format and am trying to convert it to unix time. This is my console session: ``` In [9]: mydate Out[9]: '2009-07-17T01:21:00.000Z' In [10]: parseddate = iso8601.parse_date(mydate) In [14]: ti = time.mktime(parseddate.timetuple()) In [25]: datetime.datetime.utcfromtimestamp(ti) Ou...
You can create an `struct_time` in UTC with [`datetime.utctimetuple()`](http://docs.python.org/library/datetime.html#datetime.datetime.utctimetuple) and then convert this to a unix timestamp with [`calendar.timegm()`](http://docs.python.org/library/calendar.html#calendar.timegm): ``` calendar.timegm(parseddate.utctime...
Why is there no first(iterable) built-in function in Python?
1,077,307
54
2009-07-03T00:07:07Z
1,077,320
39
2009-07-03T00:18:22Z
[ "python", "iterator", "generator" ]
I'm wondering if there's a reason that there's no `first(iterable)` in the Python built-in functions, somewhat similar to `any(iterable)` and `all(iterable)` (it may be tucked in a stdlib module somewhere, but I don't see it in `itertools`). `first` would perform a short-circuit generator evaluation so that unnecessary...
If you have an iterator, you can just call its `next` method. Something like: ``` In [3]: (5*x for x in xrange(2,4)).next() Out[3]: 10 ```
Why is there no first(iterable) built-in function in Python?
1,077,307
54
2009-07-03T00:07:07Z
16,174,249
13
2013-04-23T16:11:47Z
[ "python", "iterator", "generator" ]
I'm wondering if there's a reason that there's no `first(iterable)` in the Python built-in functions, somewhat similar to `any(iterable)` and `all(iterable)` (it may be tucked in a stdlib module somewhere, but I don't see it in `itertools`). `first` would perform a short-circuit generator evaluation so that unnecessary...
There's a [Pypi package called “first”](https://pypi.python.org/pypi/first) that does this: ``` >>> from first import first >>> first([0, None, False, [], (), 42]) 42 ``` Here's how you would use to return the first odd number, for example: ``` >> first([2, 14, 7, 41, 53], key=lambda x: x % 2 == 1) 7 ``` If you...
Why is there no first(iterable) built-in function in Python?
1,077,307
54
2009-07-03T00:07:07Z
18,226,144
8
2013-08-14T07:58:09Z
[ "python", "iterator", "generator" ]
I'm wondering if there's a reason that there's no `first(iterable)` in the Python built-in functions, somewhat similar to `any(iterable)` and `all(iterable)` (it may be tucked in a stdlib module somewhere, but I don't see it in `itertools`). `first` would perform a short-circuit generator evaluation so that unnecessary...
I asked a [similar question](http://stackoverflow.com/questions/18208730/shortcut-or-chain-applied-on-list) recently (it got marked as a duplicate of this question by now). My concern also was that I'd liked to use built-ins *only* to solve the problem of finding the first true value of a generator. My own solution the...
Python Unix time doesn't work in Javascript
1,077,393
6
2009-07-03T00:55:59Z
1,077,403
11
2009-07-03T01:00:52Z
[ "javascript", "python", "datetime", "utc", "unix-timestamp" ]
In Python, using calendar.timegm(), I get a 10 digit result for a unix timestamp. When I put this into Javscript's setTime() function, it comes up with a date in 1970. It evidently needs a unix timestamp that is 13 digits long. How can this happen? Are they both counting from the same date? How can I use the same unix...
timegm is based on Unix's [gmtime()](http://linux.about.com/library/cmd/blcmdl3%5Fgmtime.htm) method, which return seconds since Jan 1, 1970. Javascripts [setTime()](http://www.w3schools.com/jsref/jsref%5FsetTime.asp) method is milliseconds since that date. You'll need to multiply your seconds times 1000 to convert to...
Python Unix time doesn't work in Javascript
1,077,393
6
2009-07-03T00:55:59Z
1,077,414
8
2009-07-03T01:07:04Z
[ "javascript", "python", "datetime", "utc", "unix-timestamp" ]
In Python, using calendar.timegm(), I get a 10 digit result for a unix timestamp. When I put this into Javscript's setTime() function, it comes up with a date in 1970. It evidently needs a unix timestamp that is 13 digits long. How can this happen? Are they both counting from the same date? How can I use the same unix...
Here are a couple of python methods I use to convert to and from javascript/datetime. ``` def to_datetime(js_timestamp): return datetime.datetime.fromtimestamp(js_timestamp/1000) def js_timestamp_from_datetime(dt): return 1000 * time.mktime(dt.timetuple()) ``` In javascript you would do: ``` var dt = new D...
Restarting a Django application running on Apache + mod_python
1,078,166
8
2009-07-03T07:23:55Z
1,078,282
15
2009-07-03T07:58:49Z
[ "python", "django", "mod-python" ]
I'm running a Django app on Apache + mod\_python. When I make some changes to the code, sometimes they have effect immediately, other times they don't, until I restart Apache. However I don't really want to do that since it's a production server running other stuff too. Is there some other way to force that? Just to m...
If possible, you should switch to mod\_wsgi. This is now the [recommended way](http://docs.djangoproject.com/en/dev/howto/deployment/modwsgi/) to serve Django anyway, and is much more efficient in terms of memory and server resources. In mod\_wsgi, each site has a `.wsgi` file associated with it. To restart a site, ju...
How do you extract a JAR in a UNIX filesystem with a single command and specify its target directory using the JAR command?
1,079,693
36
2009-07-03T14:50:06Z
1,079,726
47
2009-07-03T14:56:40Z
[ "java", "python", "linux", "unix", "jar" ]
I am creating a Python script within which I am executing UNIX system commands. I have a war archive named Binaries.war which is within an ear archive named Portal.ear The Portal ear file resides in, say /home/foo/bar/ ``` jar xf /home/foo/bar/Portal.ear Binaries.war ``` Will extract the Binaries.war file out of the...
I don't think the jar tool supports this natively, but you can just unzip a JAR file with "unzip" and specify the output directory with that with the "-d" option, so something like: ``` $ unzip -d /home/foo/bar/baz /home/foo/bar/Portal.ear Binaries.war ```
How do you extract a JAR in a UNIX filesystem with a single command and specify its target directory using the JAR command?
1,079,693
36
2009-07-03T14:50:06Z
1,079,803
48
2009-07-03T15:12:40Z
[ "java", "python", "linux", "unix", "jar" ]
I am creating a Python script within which I am executing UNIX system commands. I have a war archive named Binaries.war which is within an ear archive named Portal.ear The Portal ear file resides in, say /home/foo/bar/ ``` jar xf /home/foo/bar/Portal.ear Binaries.war ``` Will extract the Binaries.war file out of the...
If your jar file already has an absolute pathname as shown, it is particularly easy: ``` cd /where/you/want/it; jar xf /path/to/jarfile.jar ``` That is, you have the shell executed by Python change directory for you and then run the extraction. If your jar file does not already have an absolute pathname, then you ha...
Why do pythonistas call the current reference "self" and not "this"?
1,079,983
35
2009-07-03T16:06:00Z
1,079,995
18
2009-07-03T16:09:38Z
[ "python" ]
Python is the language I know the most, and strangely I still don't know why I'm typing "self" and not "this" like in Java or PHP. I know that Python is older than Java, but I can't figure out where does this come from. Especially since you can use any name instead of "self": the program will work fine. So where does...
Smalltalk, which predates Java of course.
Why do pythonistas call the current reference "self" and not "this"?
1,079,983
35
2009-07-03T16:06:00Z
1,080,001
27
2009-07-03T16:11:11Z
[ "python" ]
Python is the language I know the most, and strangely I still don't know why I'm typing "self" and not "this" like in Java or PHP. I know that Python is older than Java, but I can't figure out where does this come from. Especially since you can use any name instead of "self": the program will work fine. So where does...
Check the [history of Python](http://python-history.blogspot.com/2009/02/adding-support-for-user-defined-classes.html) for user defined classes: > Instead, one simply defines a function whose first argument corresponds to the instance, which by convention is named "self." For example: ``` def spam(self,y): print ...
Why do pythonistas call the current reference "self" and not "this"?
1,079,983
35
2009-07-03T16:06:00Z
1,080,192
61
2009-07-03T17:09:52Z
[ "python" ]
Python is the language I know the most, and strangely I still don't know why I'm typing "self" and not "this" like in Java or PHP. I know that Python is older than Java, but I can't figure out where does this come from. Especially since you can use any name instead of "self": the program will work fine. So where does...
Smalltalk-80, released by Xerox in 1980, used `self`. Objective-C (early 1980s) layers Smalltalk features over C, so it uses `self` too. Modula-3 (1988), Python (late 1980s), and Ruby (mid 1990s) also follow this tradition. C++, also dating from the early 1980s, chose `this` instead of `self`. Since Java was designed ...
Why do pythonistas call the current reference "self" and not "this"?
1,079,983
35
2009-07-03T16:06:00Z
1,081,454
7
2009-07-04T03:56:41Z
[ "python" ]
Python is the language I know the most, and strangely I still don't know why I'm typing "self" and not "this" like in Java or PHP. I know that Python is older than Java, but I can't figure out where does this come from. Especially since you can use any name instead of "self": the program will work fine. So where does...
The primary inspiration was Modula-3, which Guido was introduced to at DEC: > the Modula-3 final report was being > written there at about the same time. > What I learned there showed up in > Python's exception handling, modules, > and the fact that methods explicitly > contain “self” in their parameter > list. -...
Why do pythonistas call the current reference "self" and not "this"?
1,079,983
35
2009-07-03T16:06:00Z
8,620,042
14
2011-12-23T19:49:27Z
[ "python" ]
Python is the language I know the most, and strangely I still don't know why I'm typing "self" and not "this" like in Java or PHP. I know that Python is older than Java, but I can't figure out where does this come from. Especially since you can use any name instead of "self": the program will work fine. So where does...
With respect to python, there is nothing special about `self`. You can use `this` instead if you wanted: Here's an example: ``` >>> class A(object): ... def __init__(this): ... this.x = 3 ... >>> a = A() >>> a.x 3 ``` Although you could name it whatever you want, `self` is the convention for the first argu...
Why do pythonistas call the current reference "self" and not "this"?
1,079,983
35
2009-07-03T16:06:00Z
8,620,086
7
2011-12-23T19:54:24Z
[ "python" ]
Python is the language I know the most, and strangely I still don't know why I'm typing "self" and not "this" like in Java or PHP. I know that Python is older than Java, but I can't figure out where does this come from. Especially since you can use any name instead of "self": the program will work fine. So where does...
Python follows Smalltalk's footsteps in the aspect - self is used in Smalltalk as well. I guess the *real* question should be 'why did Bjarne decide to use `this` in C++'...
Is there a map without result in python?
1,080,026
15
2009-07-03T16:20:11Z
1,080,100
12
2009-07-03T16:45:26Z
[ "python", "iteration" ]
Sometimes, I just want to execute a function for a list of entries -- eg.: ``` for x in wowList: installWow(x, 'installed by me') ``` Sometimes I need this stuff for module initialization, so I don't want to have a footprint like x in global namespace. One solution would be to just use map together with lambda: `...
How about this? ``` for x in wowList: installWow(x, 'installed by me') del x ```
Is there a map without result in python?
1,080,026
15
2009-07-03T16:20:11Z
1,080,300
20
2009-07-03T17:45:30Z
[ "python", "iteration" ]
Sometimes, I just want to execute a function for a list of entries -- eg.: ``` for x in wowList: installWow(x, 'installed by me') ``` Sometimes I need this stuff for module initialization, so I don't want to have a footprint like x in global namespace. One solution would be to just use map together with lambda: `...
You could make your own "each" function: ``` def each(fn, items): for item in items: fn(item) # called thus each(lambda x: installWow(x, 'installed by me'), wowList) ``` Basically it's just map, but without the results being returned. By using a function you'll ensure that the "item" variable doesn't le...
retrieve links from web page using python and BeautifulSoup
1,080,411
70
2009-07-03T18:29:56Z
1,080,427
25
2009-07-03T18:37:53Z
[ "python", "hyperlink", "beautifulsoup" ]
How can I retrieve the links of a webpage and copy the url address of the links using Python?
``` import urllib2 import BeautifulSoup request = urllib2.Request("http://www.gpsbasecamp.com/national-parks") response = urllib2.urlopen(request) soup = BeautifulSoup.BeautifulSoup(response) for a in soup.findAll('a'): if 'national-park' in a['href']: print 'found a url with national-park in the link' ```
retrieve links from web page using python and BeautifulSoup
1,080,411
70
2009-07-03T18:29:56Z
1,080,472
108
2009-07-03T18:53:55Z
[ "python", "hyperlink", "beautifulsoup" ]
How can I retrieve the links of a webpage and copy the url address of the links using Python?
Here's a short snippet using the SoupStrainer class in BeautifulSoup: ``` import httplib2 from BeautifulSoup import BeautifulSoup, SoupStrainer http = httplib2.Http() status, response = http.request('http://www.nytimes.com') for link in BeautifulSoup(response, parseOnlyThese=SoupStrainer('a')): if link.has_attr(...
retrieve links from web page using python and BeautifulSoup
1,080,411
70
2009-07-03T18:29:56Z
1,223,008
38
2009-08-03T15:34:01Z
[ "python", "hyperlink", "beautifulsoup" ]
How can I retrieve the links of a webpage and copy the url address of the links using Python?
Others have recommended BeautifulSoup, but it's much better to use [lxml](http://lxml.de/index.html). Despite its name, it is also for parsing and scraping HTML. It's much, much faster than BeautifulSoup, and it even handles "broken" HTML better than BeautifulSoup (their claim to fame). It has a compatibility API for B...