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
timeit versus timing decorator
1,622,943
33
2009-10-26T03:23:34Z
1,624,688
11
2009-10-26T13:10:14Z
[ "python", "timing", "timeit" ]
I'm trying to time some code. First I used a timing decorator: ``` #!/usr/bin/env python import time from itertools import izip from random import shuffle def timing_val(func): def wrapper(*arg, **kw): '''source: http://www.daniweb.com/code/snippet368.html''' t1 = time.time() res = func(*...
Use timeit. Running the test more than once gives me much better results. ``` func_list=[locals()[key] for key in locals().keys() if callable(locals()[key]) and key.startswith('time')] alist=range(1000000) times=[] for f in func_list: n = 10 times.append( min( t for t,_,_ in (f(alist,31) for i in...
timeit versus timing decorator
1,622,943
33
2009-10-26T03:23:34Z
15,136,422
13
2013-02-28T13:10:30Z
[ "python", "timing", "timeit" ]
I'm trying to time some code. First I used a timing decorator: ``` #!/usr/bin/env python import time from itertools import izip from random import shuffle def timing_val(func): def wrapper(*arg, **kw): '''source: http://www.daniweb.com/code/snippet368.html''' t1 = time.time() res = func(*...
I would use a timing decorator, because you can use annotations to sprinkle the timing around your code rather than making you code messy with timing logic. ``` import time def timeit(f): def timed(*args, **kw): ts = time.time() result = f(*args, **kw) te = time.time() print 'fu...
timeit versus timing decorator
1,622,943
33
2009-10-26T03:23:34Z
27,737,385
11
2015-01-02T04:30:10Z
[ "python", "timing", "timeit" ]
I'm trying to time some code. First I used a timing decorator: ``` #!/usr/bin/env python import time from itertools import izip from random import shuffle def timing_val(func): def wrapper(*arg, **kw): '''source: http://www.daniweb.com/code/snippet368.html''' t1 = time.time() res = func(*...
Use wrapping from `functools` to improve Matt Alcock's answer. ``` from functools import wraps from time import time def timing(f): @wraps(f) def wrap(*args, **kw): ts = time() result = f(*args, **kw) te = time() print 'func:%r args:[%r, %r] took: %2.4f sec' % \ (f.__...
Fastest way to zero out low values in array?
1,623,849
22
2009-10-26T09:24:02Z
1,623,939
49
2009-10-26T09:49:08Z
[ "python", "arrays", "floating-point", "max", "min" ]
So, lets say I have 100,000 float arrays with 100 elements each. I need the highest X number of values, BUT only if they are greater than Y. Any element not matching this should be set to 0. What would be the fastest way to do this in Python? Order must be maintained. Most of the elements are already set to 0. sample ...
This is a typical job for [NumPy](http://www.scipy.org/Tentative_NumPy_Tutorial), which is very fast for these kinds of operations: ``` array_np = numpy.asarray(array) low_values_indices = array_np < lowValY # Where values are low array_np[low_values_indices] = 0 # All low values set to 0 ``` Now, if you only need ...
Fastest way to zero out low values in array?
1,623,849
22
2009-10-26T09:24:02Z
22,291,243
11
2014-03-10T02:42:55Z
[ "python", "arrays", "floating-point", "max", "min" ]
So, lets say I have 100,000 float arrays with 100 elements each. I need the highest X number of values, BUT only if they are greater than Y. Any element not matching this should be set to 0. What would be the fastest way to do this in Python? Order must be maintained. Most of the elements are already set to 0. sample ...
``` from scipy.stats import threshold thresholded = threshold(array, 0.5) ``` :)
Django or similar for composite primary keys
1,624,257
14
2009-10-26T11:19:28Z
1,624,291
18
2009-10-26T11:27:24Z
[ "python", "django", "web-applications", "django-models" ]
I am writing a web application for my engineering company (warning: I am a programmer only by hobby) and was planning on using Django until I hit this snag. The models I want to use naturally have multi-column primary keys. Per <http://code.djangoproject.com/ticket/373>, I can't use Django, at least not a released vers...
A work around is to create a surrogate key (an auto increment column) as the primary key column and place a unique index on your domain composite key. Foreign keys will then refer to the surrogate primary key column.
Django or similar for composite primary keys
1,624,257
14
2009-10-26T11:19:28Z
1,624,298
23
2009-10-26T11:29:19Z
[ "python", "django", "web-applications", "django-models" ]
I am writing a web application for my engineering company (warning: I am a programmer only by hobby) and was planning on using Django until I hit this snag. The models I want to use naturally have multi-column primary keys. Per <http://code.djangoproject.com/ticket/373>, I can't use Django, at least not a released vers...
Why not add a normal primary key, and then specify that `part_number` and `part_revision` as [`unique_together`](http://docs.djangoproject.com/en/dev/ref/models/options/#unique-together)? This essentially is the Djangoish (Djangonic?) way of doing what Mitch Wheat said.
Django or similar for composite primary keys
1,624,257
14
2009-10-26T11:19:28Z
1,624,560
13
2009-10-26T12:37:23Z
[ "python", "django", "web-applications", "django-models" ]
I am writing a web application for my engineering company (warning: I am a programmer only by hobby) and was planning on using Django until I hit this snag. The models I want to use naturally have multi-column primary keys. Per <http://code.djangoproject.com/ticket/373>, I can't use Django, at least not a released vers...
I strongly suggest using a surrogate key. Not because it is "Djangoesque". Suppose that you use a composite key that includes part\_number. What if some time later your company decides to change the format (and therefore values) of that field? Or in general terms, any field? You would not want to deal with changing pri...
Django model fields validation
1,624,782
49
2009-10-26T13:27:15Z
1,625,760
49
2009-10-26T16:27:12Z
[ "python", "django", "django-models" ]
Where should the validation of *model fields* go in django? I could name at least two possible choices: in the overloaded .save() method of the model or in the .to\_python() method of the models.Field subclass (obviously for that to work you must write custom fields). Possible use cases: * when it is absolutely necc...
Django has a [model validation](https://docs.djangoproject.com/en/dev/ref/models/instances/#validating-objects) system in place since version 1.2. In comments sebpiq says "Ok, now there is a place to put model validation ... except that it is run only when using a ModelForm! So the question remains, when it is necessa...
Django model fields validation
1,624,782
49
2009-10-26T13:27:15Z
5,177,410
7
2011-03-03T06:24:40Z
[ "python", "django", "django-models" ]
Where should the validation of *model fields* go in django? I could name at least two possible choices: in the overloaded .save() method of the model or in the .to\_python() method of the models.Field subclass (obviously for that to work you must write custom fields). Possible use cases: * when it is absolutely necc...
I think you want this -> ``` from django.db.models.signals import pre_save def validate_model(sender, **kwargs): if 'raw' in kwargs and not kwargs['raw']: kwargs['instance'].full_clean() pre_save.connect(validate_model, dispatch_uid='validate_models') ``` (Copied from <http://djangosnippets.org/snippets...
Is there an easy way to create derived attributes in Django Model/Python classes?
1,626,155
4
2009-10-26T17:30:44Z
1,626,216
8
2009-10-26T17:40:48Z
[ "python", "django", "django-models", "oop" ]
Every Django model has a default primary-key `id` created automatically. I want the model objects to have another attribute `big_id` which is calculated as: `big_id = id * SOME_CONSTANT` I want to access `big_id` as `model_obj.big_id` without the corresponding database table having a column called `big_id`. Is this...
Well, django model instances are just python objects, or so I've been told anyway :P That is how I would do it: ``` class MyModel(models.Model): CONSTANT = 1234 id = models.AutoField(primary_key=True) # not really needed, but hey @property def big_id(self): return self.pk * MyModel.CONSTANT `...
How to manage local vs production settings in Django?
1,626,326
178
2009-10-26T18:00:26Z
1,626,371
12
2009-10-26T18:07:20Z
[ "python", "django", "deployment" ]
What is the recommended way of handling settings for local development and the production server? Some of them (like constants, etc) can be changed/accessed in both, but some of them (like paths to static files) need to remain different, and hence should not be overwritten every time the new code is deployed. Currentl...
I use a settings\_local.py and a settings\_production.py. After trying several options I've found that it's easy to waste time with complex solutions when simply having two settings files feels easy and fast. When you use mod\_python/mod\_wsgi for your Django project you need to point it to your settings file. If you ...
How to manage local vs production settings in Django?
1,626,326
178
2009-10-26T18:00:26Z
1,626,529
12
2009-10-26T18:34:04Z
[ "python", "django", "deployment" ]
What is the recommended way of handling settings for local development and the production server? Some of them (like constants, etc) can be changed/accessed in both, but some of them (like paths to static files) need to remain different, and hence should not be overwritten every time the new code is deployed. Currentl...
I use a slightly modified version of the "if DEBUG" style of settings that Harper Shelby posted. Obviously depending on the environment (win/linux/etc.) the code might need to be tweaked a bit. I was in the past using the "if DEBUG" but I found that occasionally I needed to do testing with DEUBG set to False. What I r...
How to manage local vs production settings in Django?
1,626,326
178
2009-10-26T18:00:26Z
1,629,770
90
2009-10-27T10:01:08Z
[ "python", "django", "deployment" ]
What is the recommended way of handling settings for local development and the production server? Some of them (like constants, etc) can be changed/accessed in both, but some of them (like paths to static files) need to remain different, and hence should not be overwritten every time the new code is deployed. Currentl...
In `settings.py`: ``` try: from local_settings import * except ImportError as e: pass ``` You can override what needed in `local_settings.py`; it should stay out of your version control then. But since you mention copying I'm guessing you use none ;)
How to manage local vs production settings in Django?
1,626,326
178
2009-10-26T18:00:26Z
15,315,143
49
2013-03-09T19:48:26Z
[ "python", "django", "deployment" ]
What is the recommended way of handling settings for local development and the production server? Some of them (like constants, etc) can be changed/accessed in both, but some of them (like paths to static files) need to remain different, and hence should not be overwritten every time the new code is deployed. Currentl...
Instead of `settings.py`, use this layout: ``` . └── settings/    ├── __init__.py <= not versioned    ├── common.py    ├── dev.py    └── prod.py ``` `common.py` is where most of your configuration lives. `prod.py` imports everything from common, and overrides whatever it ne...
How to manage local vs production settings in Django?
1,626,326
178
2009-10-26T18:00:26Z
15,325,966
184
2013-03-10T18:34:25Z
[ "python", "django", "deployment" ]
What is the recommended way of handling settings for local development and the production server? Some of them (like constants, etc) can be changed/accessed in both, but some of them (like paths to static files) need to remain different, and hence should not be overwritten every time the new code is deployed. Currentl...
[Two Scoops of Django: Best Practices for Django 1.5](http://twoscoopspress.org/products/two-scoops-of-django-1-5) suggests using version control for your settings files and storing the files in a separate directory: ``` project/ app1/ app2/ project/ __init__.py settings/ __init...
Generating Separate Output files in Hadoop Streaming
1,626,786
7
2009-10-26T19:17:29Z
1,690,092
7
2009-11-06T20:14:35Z
[ "python", "streaming", "hadoop", "mapreduce" ]
Using only a mapper (a Python script) and no reducer, how can I output a separate file with the key as the filename, for each line of output, rather than having long files of output?
The input and outputformat classes can be replaced by use of the -inputformat and -outputformat commandline parameters. One example of how to do this can be found in the [dumbo project](http://dumbotics.com "Dumbo"), which is a python framework for writing streaming jobs. It has a feature for writing to multiple files...
Python mkdir giving me wrong permissions
1,627,198
6
2009-10-26T20:38:34Z
1,627,222
17
2009-10-26T20:42:58Z
[ "python", "windows", "filesystems", "mkdir" ]
I'm trying to create a folder and create a file within it. Whenever i create that folder (via Python), it creates a folder that gives me no permissions at all and read-only mode. When i try to create the file i get an IOError. ``` Error: <type 'exceptions.IOError'> ``` I tried creating (and searching) for a descri...
After you create the folder you can set the permissions with `os.chmod` The mod is written in base 8, if you convert it to binary it would be ``` 000 111 111 000 rwx rwx rwx ``` The first `rwx` is for owner, the second is for the group and the third is for world r=read,w=write,x=execute The permissions you see...
Python Infinity - Any caveats?
1,628,026
133
2009-10-27T00:12:06Z
1,628,105
79
2009-10-27T00:31:36Z
[ "python" ]
So Python has positive and negative infinity: ``` float("inf"), float("-inf") ``` This just seems like the type of feature that has to have some caveat. Is there anything I should be aware of?
You can still get not-a-number (NaN) values from simple arithmetic involving `inf`: ``` >>> 0 * float("inf") nan ``` Note that you will normally *not* get an `inf` value through usual arithmetic calculations: ``` >>> 2.0**2 4.0 >>> _**2 16.0 >>> _**2 256.0 >>> _**2 65536.0 >>> _**2 4294967296.0 >>> _**2 1.8446744073...
Python Infinity - Any caveats?
1,628,026
133
2009-10-27T00:12:06Z
1,628,113
76
2009-10-27T00:33:01Z
[ "python" ]
So Python has positive and negative infinity: ``` float("inf"), float("-inf") ``` This just seems like the type of feature that has to have some caveat. Is there anything I should be aware of?
[Python's implementation](https://docs.python.org/2/library/decimal.html) follows the [IEEE-754 standard](http://en.wikipedia.org/wiki/IEEE_754-1985) pretty well, which you can use as a guidance, but it relies on the underlying system it was compiled on, so [platform differences](http://www.python.org/dev/peps/pep-0754...
python attribute lookup without any descriptor magic?
1,628,137
2
2009-10-27T00:38:26Z
1,629,912
9
2009-10-27T10:27:14Z
[ "python", "python-datamodel", "descriptor" ]
I've started to use the python descriptor protocol more extensively in the code I've been writing. Typically, the default python lookup magic is what I want to happen, but sometimes I'm finding I want to get the descriptor object itself instead the results of its `__get__` method. Wanting to know the type of the descri...
Most descriptors do their job when accessed as instance attribute only. So it's convenient to return itself when it's accessed for class: ``` class FixedValueProperty(object): def __init__(self, value): self.value = value def __get__(self, inst, cls): if inst is None: return self ...
The advantages of having static function like len(), max(), and min() over inherited method calls
1,628,222
8
2009-10-27T01:02:37Z
1,628,300
15
2009-10-27T01:30:53Z
[ "python", "language-design" ]
i am a python newbie, and i am not sure why python implemented len(obj), max(obj), and min(obj) as a static like functions (i am from the java language) over obj.len(), obj.max(), and obj.min() what are the advantages and disadvantages (other than obvious inconsistency) of having len()... over the method calls? why g...
The big advantage is that built-in functions (and operators) can apply extra logic when appropriate, beyond simply calling the special methods. For example, `min` can look at several arguments and apply the appropriate inequality checks, or it can accept a single iterable argument and proceed similarly; `abs` when call...
To find first N prime numbers in python
1,628,949
8
2009-10-27T05:44:35Z
1,629,068
28
2009-10-27T06:38:26Z
[ "python", "primes" ]
I am new to the programming world. I was just writing this code in python to generate N prime numbers. User should input the value for N which is the total number of prime numbers to print out. I have written this code but it doesn't throw the desired output. Instead it prints the prime numbers till the Nth number. For...
using a regexp :) ``` #!/usr/bin/python import re, sys def isPrime(n): # see http://www.noulakaz.net/weblog/2007/03/18/a-regular-expression-to-check-for-prime-numbers/ return re.match(r'^1?$|^(11+?)\1+$', '1' * n) == None N = int(sys.argv[1]) # number of primes wanted (from command-line) M = 100 ...
To find first N prime numbers in python
1,628,949
8
2009-10-27T05:44:35Z
1,638,415
12
2009-10-28T16:31:43Z
[ "python", "primes" ]
I am new to the programming world. I was just writing this code in python to generate N prime numbers. User should input the value for N which is the total number of prime numbers to print out. I have written this code but it doesn't throw the desired output. Instead it prints the prime numbers till the Nth number. For...
For reference, there's a pretty significant speed difference between the various stated solutions. Here is some comparison code. The solution pointed to by Lennart is called "historic", the one proposed by Ants is called "naive", and the one by RC is called "regexp." ``` from sys import argv from time import time def...
To find first N prime numbers in python
1,628,949
8
2009-10-27T05:44:35Z
2,212,923
11
2010-02-06T11:28:37Z
[ "python", "primes" ]
I am new to the programming world. I was just writing this code in python to generate N prime numbers. User should input the value for N which is the total number of prime numbers to print out. I have written this code but it doesn't throw the desired output. Instead it prints the prime numbers till the Nth number. For...
Super quick sieve implementation by [David Eppstein](http://code.activestate.com/recipes/117119/) - takes 0.146s for the first 1000 primes on my PC: ``` def gen_primes(): """ Generate an infinite sequence of prime numbers. """ # Maps composites to primes witnessing their compositeness. # This is memory...
Is it possible exclude test directories from coverage.py reports?
1,628,996
13
2009-10-27T06:08:06Z
1,629,194
14
2009-10-27T07:19:37Z
[ "python", "testing", "software-quality", "code-coverage", "coverage.py" ]
I'm kind of a rookie with python unit testing, and particularly coverage.py. Is it desirable to have coverage reports include the coverage of your actual test files? Here's a screenshot of my [HTML report](http://kylefox-awesome-stuff.s3.amazonaws.com/coverage.png) as an example. You can see that the report includes ...
It's a good idea to see the coverage of your tests as it can point to problems. If your test code isn't being run then there wasn't much point in writing it! The one I always get is when I give two unit test functions the same name - I add a new test several months after the original and just happen to pick the same n...
Is it possible exclude test directories from coverage.py reports?
1,628,996
13
2009-10-27T06:08:06Z
20,738,918
12
2013-12-23T07:30:08Z
[ "python", "testing", "software-quality", "code-coverage", "coverage.py" ]
I'm kind of a rookie with python unit testing, and particularly coverage.py. Is it desirable to have coverage reports include the coverage of your actual test files? Here's a screenshot of my [HTML report](http://kylefox-awesome-stuff.s3.amazonaws.com/coverage.png) as an example. You can see that the report includes ...
`coverage html --omit="*/test*" -d tests/coverage`
How to find length of an element in a list?
1,629,728
2
2009-10-27T09:50:33Z
1,629,777
14
2009-10-27T10:02:29Z
[ "python", "list" ]
I'm just starting with programming. I have a list of a few strings and now I need to print the biggest (in length) one. So I first want to just print the lengths of elements. I was trying things like this: ``` l = ("xxxxxxxxx", "yyyy","zz") for i in range(len(l): ``` So how do I do it?
``` l = ("xxxxxxxxx", "yyyy","zz") print(max(l, key=len)) ``` First of all you don't have a list, you have a tuple. this code will work for any sequence, however; both lists and tuples are sequences (as well as strings, sets, etc). So, the `max` function takes a `key` argument, that is used to sort the elements of an ...
Python string formatting special characters
1,629,755
3
2009-10-27T09:57:44Z
1,629,861
7
2009-10-27T10:19:23Z
[ "python", "string-formatting" ]
How do you make the following code work? ``` example = "%%(test)%" % {'test':'name',} print example ``` Where the desired output is "%name%" Thanks
An alternative is to use the new [Advanced String Formatting](http://www.python.org/dev/peps/pep-3101/) ``` >>> example = "%{test}%".format(test="name") >>> print example %name% ```
What is the pythonic way to detect the last element in a python 'for' loop?
1,630,320
69
2009-10-27T11:54:33Z
1,630,350
65
2009-10-27T12:02:28Z
[ "for-loop", "python", "idioms", "fencepost" ]
I'd like to know the best way (more compact and "pythonic" way) to do a special treatment for the last element in a for loop. There is a piece of code that should be called only *between* elements, being suppressed in the last one. Here is how I currently do it: ``` for i, data in enumerate(data_list): code_that_...
Most of the times it is easier (and cheaper) to make the *first* iteration the special case instead of the last one: ``` first = True for data in data_list: if first: first = False else: between_items() item() ``` This will work for any iterable, even for those that have no `len()`: ``` ...
What is the pythonic way to detect the last element in a python 'for' loop?
1,630,320
69
2009-10-27T11:54:33Z
1,630,359
11
2009-10-27T12:05:19Z
[ "for-loop", "python", "idioms", "fencepost" ]
I'd like to know the best way (more compact and "pythonic" way) to do a special treatment for the last element in a for loop. There is a piece of code that should be called only *between* elements, being suppressed in the last one. Here is how I currently do it: ``` for i, data in enumerate(data_list): code_that_...
If you're simply looking to modify the last element in `data_list` then you can simply use the notation: ``` L[-1] ``` However, it looks like you're doing more than that. There is nothing really wrong with your way. I even took a quick glance at some [Django code](http://code.djangoproject.com/browser/django/trunk/dj...
What is the pythonic way to detect the last element in a python 'for' loop?
1,630,320
69
2009-10-27T11:54:33Z
1,630,853
13
2009-10-27T13:38:36Z
[ "for-loop", "python", "idioms", "fencepost" ]
I'd like to know the best way (more compact and "pythonic" way) to do a special treatment for the last element in a for loop. There is a piece of code that should be called only *between* elements, being suppressed in the last one. Here is how I currently do it: ``` for i, data in enumerate(data_list): code_that_...
The 'code between' is an example of the **Head-Tail** pattern. You have an item, which is followed by a sequence of ( between, item ) pairs. You can also view this as a sequence of (item, between) pairs followed by an item. It's generally simpler to take the first element as special and all the others as the "standard...
What is the pythonic way to detect the last element in a python 'for' loop?
1,630,320
69
2009-10-27T11:54:33Z
1,633,483
8
2009-10-27T20:32:51Z
[ "for-loop", "python", "idioms", "fencepost" ]
I'd like to know the best way (more compact and "pythonic" way) to do a special treatment for the last element in a for loop. There is a piece of code that should be called only *between* elements, being suppressed in the last one. Here is how I currently do it: ``` for i, data in enumerate(data_list): code_that_...
This is similar to Ants Aasma's approach but without using the itertools module. It's also a lagging iterator which looks-ahead a single element in the iterator stream: ``` def last_iter(it): # Ensure it's an iterator and get the first field it = iter(it) prev = next(it) for item in it: # Lag b...
Best practice in python for return value on error vs. success
1,630,706
27
2009-10-27T13:11:15Z
1,630,737
16
2009-10-27T13:17:10Z
[ "python", "return" ]
In **general**, let's say you have a method like the below. ``` def intersect_two_lists(self, list1, list2): if not list1: self.trap_error("union_two_lists: list1 must not be empty.") return False if not list2: self.trap_error("union_two_lists: list2 must not be empty.") return ...
It'd be better to [raise an exception](http://en.wikibooks.org/wiki/Python%5FProgramming/Exceptions) than return a special value. This is exactly what exceptions were designed for, to replace error codes with a more robust and structured error-handling mechanism. ``` class IntersectException(Exception): def __init...
Best practice in python for return value on error vs. success
1,630,706
27
2009-10-27T13:11:15Z
1,630,760
38
2009-10-27T13:20:40Z
[ "python", "return" ]
In **general**, let's say you have a method like the below. ``` def intersect_two_lists(self, list1, list2): if not list1: self.trap_error("union_two_lists: list1 must not be empty.") return False if not list2: self.trap_error("union_two_lists: list2 must not be empty.") return ...
First, whatever you do don't return a result and an error message. That's a really bad way to handle errors and will cause you endless headaches. **If you need to indicate an error always raise an exception**. I usually tend to avoid raising errors unless it is necessary. In your example throwing an error is not reall...
Best practice in python for return value on error vs. success
1,630,706
27
2009-10-27T13:11:15Z
1,631,148
11
2009-10-27T14:19:50Z
[ "python", "return" ]
In **general**, let's say you have a method like the below. ``` def intersect_two_lists(self, list1, list2): if not list1: self.trap_error("union_two_lists: list1 must not be empty.") return False if not list2: self.trap_error("union_two_lists: list2 must not be empty.") return ...
Exceptions are definitely better (and more Pythonic) than status returns. For much more on this: [Exceptions vs. status returns](http://nedbatchelder.com/text/exceptions-vs-status.html)
Python File Slurp
1,631,897
33
2009-10-27T16:08:07Z
1,631,916
80
2009-10-27T16:10:00Z
[ "python", "file-io" ]
Is there a one-liner to read all the lines of a file in Python, rather than the standard: ``` f = open('x.txt') cts = f.read() f.close() ``` Seems like this is done so often that there's got to be a one-liner. Any ideas?
``` f = open('x.txt').read() ``` if you want a single string, or ``` f = open('x.txt').readlines() ``` if you want a list of lines. Both don't guarantee the file is immediately closed (in practice it will be immediately closed in current CPython, but closed "only when the garbage collector gets around to it" in Jyth...
List running processes on 64-bit Windows
1,632,234
4
2009-10-27T16:55:38Z
1,632,274
12
2009-10-27T17:06:08Z
[ "python", "windows", "process" ]
I amm writing a little python script that will grab information from VMs of Windows that I am running. At the moment I can list the processes on a 32bit XP machine with the following method: <http://code.activestate.com/recipes/305279/> Is it possible to somehow detect the version of windows running and excute a dif...
There is another recipe on activestate that does a similar thing, but uses the Performance Data Helper library (PDH) instead. I have tested this on my Windows 7 64bit machine and it works there - so presumably the same function will work on both 32bit and 64 bit windows. You can find the recipe here: <http://code.act...
List running processes on 64-bit Windows
1,632,234
4
2009-10-27T16:55:38Z
8,111,814
15
2011-11-13T13:22:10Z
[ "python", "windows", "process" ]
I amm writing a little python script that will grab information from VMs of Windows that I am running. At the moment I can list the processes on a 32bit XP machine with the following method: <http://code.activestate.com/recipes/305279/> Is it possible to somehow detect the version of windows running and excute a dif...
If you don't want to rely on any extra installed modules then you can parse the output of [wmic](http://technet.microsoft.com/en-us/library/bb742610.aspx), e.g.: ``` c:\> wmic process get description,executablepath ... explorer.exe C:\Windows\explorer.exe cmd.exe C:\Windows\SysWOW6...
Python File Slurp w/ endian conversion
1,632,673
5
2009-10-27T18:11:43Z
1,633,525
7
2009-10-27T20:42:17Z
[ "python", "struct", "numpy", "endianness", "mmap" ]
It was recently asked [how to do a file slurp in python](http://stackoverflow.com/questions/1631897/python-file-slurp), and the accepted answer suggested something like: ``` with open('x.txt') as x: f = x.read() ``` How would I go about doing this to read the file in and convert the endian representation of the data?...
Slightly modified [@Alex Martelli's answer](http://stackoverflow.com/questions/1632673/python-file-slurp-w-endian-conversion/1633412#1633412): ``` arr = numpy.fromfile(filename, numpy.dtype('>f4')) # no byteswap is needed regardless of endianess of the machine ```
Is a Python closure a good replacement for `__all__`?
1,632,739
3
2009-10-27T18:21:19Z
1,633,108
7
2009-10-27T19:25:52Z
[ "python", "closures" ]
Is it a good idea to use a closure instead of `__all__` to limit the names exposed by a Python module? This would prevent programmers from accidentally using the wrong name for a module (`import urllib; urllib.os.getlogin()`) as well as avoiding "`from x import *`" namespace pollution as `__all__`. ``` def _init_modul...
I am a fan of writing code that is absolutely as brain-dead simple as it can be. `__all__` is a feature of Python, added explicitly to solve the problem of limiting what names are made visible by a module. When you use it, people immediately understand what you are doing with it. Your closure trick is very nonstandar...
lambda versus list comprehension performance
1,632,902
11
2009-10-27T18:51:22Z
1,632,994
23
2009-10-27T19:05:46Z
[ "python", "lambda", "set", "list-comprehension" ]
I recently posted a question using a lambda function and in a reply someone had mentioned lambda is going out of favor, to use list comprehensions instead. I am relatively new to Python. I ran a simple test: ``` import time S=[x for x in range(1000000)] T=[y**2 for y in range(300)] # # time1 = time.time() N=[x for x ...
Your tests are doing very different things. With S being 1M elements and T being 300: ``` [x for x in S for y in T if x==y]= 54.875 ``` This option does 300M equality comparisons. ### ``` filter(lambda x:x in S,T)= 0.391000032425 ``` This option does 300 linear searches through S. ### ``` [val for val in S if ...
lambda versus list comprehension performance
1,632,902
11
2009-10-27T18:51:22Z
1,633,079
18
2009-10-27T19:19:22Z
[ "python", "lambda", "set", "list-comprehension" ]
I recently posted a question using a lambda function and in a reply someone had mentioned lambda is going out of favor, to use list comprehensions instead. I am relatively new to Python. I ran a simple test: ``` import time S=[x for x in range(1000000)] T=[y**2 for y in range(300)] # # time1 = time.time() N=[x for x ...
When I fix your code so that the list comprehension and the call to `filter` are actually doing the same work things change a whole lot: ``` import time S=[x for x in range(1000000)] T=[y**2 for y in range(300)] # # time1 = time.time() N=[x for x in T if x in S] time2 = time.time() print 'time diff [x for x in T if x...
lambda versus list comprehension performance
1,632,902
11
2009-10-27T18:51:22Z
1,633,738
12
2009-10-27T21:15:51Z
[ "python", "lambda", "set", "list-comprehension" ]
I recently posted a question using a lambda function and in a reply someone had mentioned lambda is going out of favor, to use list comprehensions instead. I am relatively new to Python. I ran a simple test: ``` import time S=[x for x in range(1000000)] T=[y**2 for y in range(300)] # # time1 = time.time() N=[x for x ...
Q: Why is lambda etc being pushed aside? A: List comprehensions and generator expressions are generally considered to be a nice mix of power and readability. The pure functional-programming style where you use `map()`, `reduce()`, and `filter()` with functions (often `lambda` functions) is considered not as clear. Als...
Difference in python between basestring and types.StringType?
1,633,082
9
2009-10-27T19:19:36Z
1,633,094
12
2009-10-27T19:22:47Z
[ "python" ]
What's the difference between: ``` isinstance(foo, types.StringType) ``` and ``` isinstance(foo, basestring) ``` ? Thanks, /YGA PS I know I shouldn't use `isinstance` at all, blah blah blah.
`basestring` is the base class for both `str` and `unicode`, while `types.StringType` *is* `str`. If you want to check if something is a string, use `basestring`. If you want to check if something is a bytestring, use `str` and forget about `types`.
Difference in python between basestring and types.StringType?
1,633,082
9
2009-10-27T19:19:36Z
1,633,178
8
2009-10-27T19:38:28Z
[ "python" ]
What's the difference between: ``` isinstance(foo, types.StringType) ``` and ``` isinstance(foo, basestring) ``` ? Thanks, /YGA PS I know I shouldn't use `isinstance` at all, blah blah blah.
This stuff is completely different in Python3 `types` not longer has `StringType` `str` is always unicode `basestring` no longer exists So try not to sprinkle that stuff through your code too much if you might ever need to port it
creating a MIME email template with images to send with python / django
1,633,109
10
2009-10-27T19:26:10Z
1,633,493
21
2009-10-27T20:34:55Z
[ "python", "django", "email", "mime" ]
In my web application I send emails occasionally using a reusable mailer application like this: ``` user - self.user subject = ("My subject") from = "[email protected]" message = render_to_string("welcomeEmail/welcome.eml", { "user" : user, }) send_mail(subject, message, from, [email], p...
**Update** Many thanks to [Saqib Ali](http://stackoverflow.com/users/1742777/saqib-ali) for resurrecting this old question nearly 5 years after my reply. The instructions I gave at the time no longer work. I suspect there have been some improvements to Django in the intervening years which mean that `send_mail()` enf...
Getting a Python library listed in easy_setup and pip?
1,633,180
9
2009-10-27T19:38:59Z
1,633,188
8
2009-10-27T19:40:49Z
[ "python" ]
Every Python developer is familiar with easy\_install and setup tools. If I want to install a library that's well known, all I have to do is this: sudo easy\_setup install django Now I have a library that I've written and would love to see widespread. How do you get added to this library list?
Upload it to [PyPI](http://pypi.python.org/pypi). See the [tutorial](http://wiki.python.org/moin/CheeseShopTutorial).
How to put parameterized sql query into variable and then execute in Python?
1,633,332
4
2009-10-27T20:02:48Z
1,633,589
10
2009-10-27T20:51:47Z
[ "python", "sql" ]
I understand that the correct way to format a sql query in Python is like this: ``` cursor.execute("INSERT INTO table VALUES (%s, %s, %s)", var1, var2, var3) ``` so that it prevents sql injection. My question is if there is a way to put the query in a variable and then execute it? I have tried the example below but r...
Here is the call signature for cursor.execute: ``` Definition: cursor.execute(self, query, args=None) query -- string, query to execute on server args -- optional sequence or mapping, parameters to use with query. ``` So execute expects at most 3 arguments (args is optional). If args is given, it is expected...
Unix paths: officially work in Python for any platform?
1,633,643
8
2009-10-27T21:01:05Z
1,633,725
11
2009-10-27T21:13:19Z
[ "python", "path", "portability", "relative-path" ]
Can all paths in a Python program use ".." (for the parent directory) and / (for separating path components), and still work *whatever the platform*? On one hand, I have never seen such a claim in the documentation (I may have missed it), and the os and os.path modules do provide facilities for handling paths in a pla...
I've never had any problems with using `..`, although it might be a good idea to convert it to an absolute path using [os.path.abspath](http://docs.python.org/library/os.path.html#os.path.abspath). Secondly, I would recommend always using os.path.join whereever possible. There are a lot of corner cases (aside from port...
Slice a string after a certain phrase?
1,633,932
5
2009-10-27T22:03:44Z
1,634,000
15
2009-10-27T22:21:03Z
[ "python" ]
I've got a batch of strings that I need to cut down. They're basically a descriptor followed by codes. I only want to keep the descriptor. ``` 'a descriptor dps 23 fd' 'another 23 fd' 'and another fd' 'and one without a code' ``` The codes above are `dps`, `23` and `fd`. They can come in any order, are unrelated to e...
The short answer, as @THC4K points out in a comment: ``` string.split(pattern, 1)[0] ``` where `string` is your original string, `pattern` is your "break" pattern, `1` indicates to split no more than 1 time, and `[0]` means take the first element returned by split. In action: ``` >>> s = "a descriptor 23 fd" >>> s....
Python, lambda, find minimum
1,634,054
5
2009-10-27T22:37:03Z
1,634,143
11
2009-10-27T22:54:27Z
[ "python", "lambda" ]
I have foreach function which calls specified function on every element which it contains. I want to get minimum from thise elements but I have no idea how to write lambda or function or even a class that would manage that. Thanks for every help. --- I use my foreach function like this: ``` o.foreach( lambda i: i.ca...
Python has built-in [support for finding minimums](http://docs.python.org/library/functions.html#min): ``` >>> min([1, 2, 3]) 1 ``` If you need to process the list with a function first, you can do that with [map](http://docs.python.org/library/functions.html#map): ``` >>> def double(x): ... return x * 2 ... >>>...
How do I blit a PNG with some transparency onto a surface in Pygame?
1,634,208
6
2009-10-27T23:09:30Z
1,634,607
15
2009-10-28T00:57:06Z
[ "python", "png", "pygame", "alpha", "blit" ]
I'm trying to blit a PNG image onto a surface, but the transparent part of the image turns black for some reason, here's the simple code: ``` screen = pygame.display.set_mode((800, 600), pygame.DOUBLEBUF, 32) world = pygame.Surface((800, 600), pygame.SRCALPHA, 32) treeImage = pygame.image.load("tree.png") world.blit...
<http://www.pygame.org/docs/ref/image.html> recommends: > For alpha transparency, like in .png images use the `convert_alpha()` method after loading so that the image has per pixel transparency.
What's the simplest cross-platform way to pop up graphical dialogs in Python?
1,635,027
26
2009-10-28T03:20:38Z
1,635,040
11
2009-10-28T03:24:51Z
[ "python", "cross-platform", "dialog", "zenity" ]
I want the simplest possible way to pop up simple dialogs in Python scripts. Ideally, the solution would: * Work on Windows, OS X, Gnome, KDE * Look like a native dialog on any OS * Require minimal code To pop up a simple standard dialog should require only minimal code. Essentially you're just saying "Pop up a stand...
[TkInter](http://wiki.python.org/moin/TkInter) is usually supplied with Python ``` # File: hello1.py from Tkinter import * root = Tk() w = Label(root, text="Hello, world!") w.pack() root.mainloop() ``` If you want something more native looking, you'll have to install something like wxpython
What's the simplest cross-platform way to pop up graphical dialogs in Python?
1,635,027
26
2009-10-28T03:20:38Z
1,635,043
17
2009-10-28T03:25:49Z
[ "python", "cross-platform", "dialog", "zenity" ]
I want the simplest possible way to pop up simple dialogs in Python scripts. Ideally, the solution would: * Work on Windows, OS X, Gnome, KDE * Look like a native dialog on any OS * Require minimal code To pop up a simple standard dialog should require only minimal code. Essentially you're just saying "Pop up a stand...
[EasyGUI](http://easygui.sourceforge.net/) is a single file, and provides a simple way to work with Tkinter dialogs, but they're still ugly non-native Tkinter dialogs. ``` from easygui import msgbox msgbox('Stuff') ``` ![Tkinter is ugly on Ubuntu](http://farm3.static.flickr.com/2627/4052101866_b9af33718d_o.png) ![TKi...
What's the simplest cross-platform way to pop up graphical dialogs in Python?
1,635,027
26
2009-10-28T03:20:38Z
1,635,047
8
2009-10-28T03:26:48Z
[ "python", "cross-platform", "dialog", "zenity" ]
I want the simplest possible way to pop up simple dialogs in Python scripts. Ideally, the solution would: * Work on Windows, OS X, Gnome, KDE * Look like a native dialog on any OS * Require minimal code To pop up a simple standard dialog should require only minimal code. Essentially you're just saying "Pop up a stand...
[Zenity](http://en.wikipedia.org/wiki/Zenity) works under Linux and [Windows](http://www.placella.com/software/zenity/), and can be called from Python directly: ``` import os os.system('zenity --info --text="Stuff"') ``` The return values from question boxes need to be captured for acting on, though, which is more co...
What's the simplest cross-platform way to pop up graphical dialogs in Python?
1,635,027
26
2009-10-28T03:20:38Z
5,059,990
8
2011-02-20T21:03:23Z
[ "python", "cross-platform", "dialog", "zenity" ]
I want the simplest possible way to pop up simple dialogs in Python scripts. Ideally, the solution would: * Work on Windows, OS X, Gnome, KDE * Look like a native dialog on any OS * Require minimal code To pop up a simple standard dialog should require only minimal code. Essentially you're just saying "Pop up a stand...
To extend on endolith's tkMessageBox answer with the ugly empty window in the background... The code below pops up the box without the background window. ``` import Tkinter, tkMessageBox root = Tkinter.Tk() root.withdraw() tkMessageBox.showinfo("my dialog title", "my dialog message") ``` This is lifted directly from...
What's the simplest cross-platform way to pop up graphical dialogs in Python?
1,635,027
26
2009-10-28T03:20:38Z
25,655,555
7
2014-09-04T00:24:43Z
[ "python", "cross-platform", "dialog", "zenity" ]
I want the simplest possible way to pop up simple dialogs in Python scripts. Ideally, the solution would: * Work on Windows, OS X, Gnome, KDE * Look like a native dialog on any OS * Require minimal code To pop up a simple standard dialog should require only minimal code. Essentially you're just saying "Pop up a stand...
The PyMsgBox module does almost exactly this. It uses the built-in tkinter module for its message box functions that follow the naming conventions of JavaScript: alert(), confirm(), prompt() and password() (which is prompt() but uses \* when you type). These function calls block until the user clicks an OK/Cancel butto...
Terminate a multi-thread python program
1,635,080
52
2009-10-28T03:41:20Z
1,635,084
68
2009-10-28T03:47:06Z
[ "python", "multithreading" ]
How to make a multi-thread python program response to Ctrl+C key event? **Edit:** The code is like this: ``` import threading current = 0 class MyThread(threading.Thread): def __init__(self, total): threading.Thread.__init__(self) self.total = total def stop(self): self._Thread__stop...
Make every thread except the main one a daemon (`t.daemon = True` in 2.6 or better, `t.setDaemon(True)` in 2.6 or less, for every thread object `t` before you start it). That way, when the main thread receives the KeyboardInterrupt, if it doesn't catch it or catches it but decided to terminate anyway, the whole process...
Terminate a multi-thread python program
1,635,080
52
2009-10-28T03:41:20Z
1,635,089
14
2009-10-28T03:49:05Z
[ "python", "multithreading" ]
How to make a multi-thread python program response to Ctrl+C key event? **Edit:** The code is like this: ``` import threading current = 0 class MyThread(threading.Thread): def __init__(self, total): threading.Thread.__init__(self) self.total = total def stop(self): self._Thread__stop...
There're two main ways, one clean and one easy. The clean way is to catch KeyboardInterrupt in your main thread, and set a flag your background threads can check so they know to exit; here's a simple/slightly-messy version using a global: ``` exitapp = False if __name__ == '__main__': try: main() exce...
How would one implement Lazy Evaluation in C?
1,635,827
17
2009-10-28T08:22:44Z
1,636,156
19
2009-10-28T09:44:31Z
[ "python", "c" ]
Take for example, The follow python code: ``` def multiples_of_2(): i = 0 while True: i = i + 2 yield i ``` How do we translate this into C code? Edit: I am looking to translate this python code into a similar generator in C, with next() function. What I am not looking for is how to create a function in...
You could try to encapsulate this in a `struct`: ``` typedef struct s_generator { int current; int (*func)(int); } generator; int next(generator* gen) { int result = gen->current; gen->current = (gen->func)(gen->current); return result; } ``` Then you define you multiples with: ``` int next_mult...
I am downloading a file using Python urllib2. How do I check how large the file size is?
1,636,637
9
2009-10-28T11:19:24Z
1,636,707
7
2009-10-28T11:36:19Z
[ "python", "file", "download", "urllib2" ]
And if it is large...then stop the download? I don't want to download files that are larger than 12MB. ``` request = urllib2.Request(ep_url) request.add_header('User-Agent',random.choice(agents)) thefile = urllib2.urlopen(request).read() ```
You could say: ``` maxlength= 12*1024*1024 thefile= urllib2.urlopen(request).read(maxlength+1) if len(thefile)==maxlength+1: raise ThrowToysOutOfPramException() ``` but then of course you've still read 12MB of unwanted data. If you want to minimise the risk of this happening you can check the HTTP Content-Length ...
I am downloading a file using Python urllib2. How do I check how large the file size is?
1,636,637
9
2009-10-28T11:19:24Z
1,639,765
19
2009-10-28T20:04:35Z
[ "python", "file", "download", "urllib2" ]
And if it is large...then stop the download? I don't want to download files that are larger than 12MB. ``` request = urllib2.Request(ep_url) request.add_header('User-Agent',random.choice(agents)) thefile = urllib2.urlopen(request).read() ```
There's no need as [bobince](http://stackoverflow.com/users/18936/bobince) did and drop to httplib. You can do all that with urllib directly: ``` >>> import urllib2 >>> f = urllib2.urlopen("http://dalkescientific.com") >>> f.headers.items() [('content-length', '7535'), ('accept-ranges', 'bytes'), ('server', 'Apache/2....
Method to peek at a Python program running right now
1,637,198
13
2009-10-28T13:20:36Z
1,637,277
26
2009-10-28T13:35:40Z
[ "python", "debugging" ]
Is it possible to find any information about what a Python program *running right now* is doing without interrupting it? Also, if it isn't possible, is there anyway to crash a running Python program so that I can at least get a stacktrace (using PyDev on Ubuntu)? I know I should have used logs or run it in debug mode...
If you place ``` import code code.interact(local=locals()) ``` at any point in your script, python will instantiate a python shell at exactly that point that has access to everything in the state of the script at that point. ^D exits the shell and resumes execution past that point. You can even modify the state at t...
Method to peek at a Python program running right now
1,637,198
13
2009-10-28T13:20:36Z
1,639,943
8
2009-10-28T20:33:20Z
[ "python", "debugging" ]
Is it possible to find any information about what a Python program *running right now* is doing without interrupting it? Also, if it isn't possible, is there anyway to crash a running Python program so that I can at least get a stacktrace (using PyDev on Ubuntu)? I know I should have used logs or run it in debug mode...
If you have a running Python, which wasn't built with any sort of trace or logging mechanism, and you want to see what it's doing internally, then two options are: * On a Solaris or Mac, if you are using the system-provided Python then use dtrace * use [gdb to attach to a running Python process](http://wiki.python.org...
Is there a way to generate pdf containing non-ascii symbols with pisa from django template?
1,637,229
18
2009-10-28T13:26:48Z
1,789,319
29
2009-11-24T10:57:55Z
[ "python", "django", "pdf", "pisa" ]
I'm trying to generate a pdf from template using this snippet: ``` def write_pdf(template_src, context_dict): template = get_template(template_src) context = Context(context_dict) html = template.render(context) result = StringIO.StringIO() pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("UT...
This does work for me: ``` pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("UTF-8")), result, encoding='UTF-8') ```
Python/Django: Which authorize.net library should I use?
1,637,902
17
2009-10-28T15:10:17Z
2,541,903
9
2010-03-29T23:20:34Z
[ "python", "django", "payment-gateway", "authorize.net" ]
I need authorize.net integration for subscription payments, likely using CIM. The requirements are simple - recurring monthly payments, with a few different price points. Customer credit card info will be stored a authorize.net . There are quite a few libraries and code snippets around, I'm looking for recommendations...
Edit: <https://github.com/agiliq/merchant/blob/master/billing/gateways/authorize_net_gateway.py> looks pretty nice, haven't tried it yet. Edit: [For the next project I have that uses authorize.net, I'm going to take a close look at: <http://github.com/zen4ever/django-authorizenet> It looks pretty nice. I don't think t...
Python/Django: Which authorize.net library should I use?
1,637,902
17
2009-10-28T15:10:17Z
12,017,060
15
2012-08-18T08:16:19Z
[ "python", "django", "payment-gateway", "authorize.net" ]
I need authorize.net integration for subscription payments, likely using CIM. The requirements are simple - recurring monthly payments, with a few different price points. Customer credit card info will be stored a authorize.net . There are quite a few libraries and code snippets around, I'm looking for recommendations...
Long story short, none of the existing solutions met my needs. They were either unmaintained, uncommented, untested, or lacked saved cards. So of course I built my own solution and open-sourced it: AuthorizeSauce: <https://github.com/jeffschenck/authorizesauce> It handles basic transactions (the AIM API), saved cards...
Python Class with integer emulation
1,638,229
5
2009-10-28T16:02:57Z
1,638,307
7
2009-10-28T16:14:38Z
[ "python", "floating-point", "integer", "emulation" ]
Given is the following example: ``` class Foo(object): def __init__(self, value=0): self.value=value def __int__(self): return self.value ``` I want to have a class *Foo*, which acts as an integer (or float). So I want to do the following things: ``` f=Foo(3) print int(f)+5 # is working prin...
In Python 2.4+ inheriting from int works: ``` class MyInt(int):pass f=MyInt(3) assert f + 5 == 8 ```
Creating class instance properties from a dictionary in Python
1,639,174
30
2009-10-28T18:28:19Z
1,639,197
46
2009-10-28T18:31:01Z
[ "class", "python", "komodo" ]
I'm importing from a CSV and getting data roughly in the format ``` { 'Field1' : 3000, 'Field2' : 6000, 'RandomField' : 5000 } ``` The names of the fields are dynamic. (Well, they're dynamic in that there might be more than Field1 and Field2, but I know Field1 and Field2 are always going to be there. I'd like to be ...
You can use [`setattr`](http://docs.python.org/3.1/library/functions.html#setattr) (be careful though: not every string is a valid attribute name!): ``` >>> class AllMyFields: ... def __init__(self, dictionary): ... for k, v in dictionary.items(): ... setattr(self, k, v) ... >>> o = AllMyField...
Creating class instance properties from a dictionary in Python
1,639,174
30
2009-10-28T18:28:19Z
1,639,215
17
2009-10-28T18:32:56Z
[ "class", "python", "komodo" ]
I'm importing from a CSV and getting data roughly in the format ``` { 'Field1' : 3000, 'Field2' : 6000, 'RandomField' : 5000 } ``` The names of the fields are dynamic. (Well, they're dynamic in that there might be more than Field1 and Field2, but I know Field1 and Field2 are always going to be there. I'd like to be ...
``` >>> q = { 'Field1' : 3000, 'Field2' : 6000, 'RandomField' : 5000 } >>> q = type('allMyFields', (object,), q) >>> q.Field1 3000 ``` docs for [`type`](http://docs.python.org/library/functions.html#type) explain well what's going here (see use as a constructor). *edit*: in case you need instance variables, the follo...
matplotlib border width
1,639,463
7
2009-10-28T19:14:57Z
1,646,208
12
2009-10-29T20:01:47Z
[ "python", "width", "matplotlib", "border" ]
I use matplotlib 0.99. I am not able to change width of border of `subplot`, how can I do it? Code is as follows: ``` fig = plt.figure(figsize = (4.1, 2.2)) ax = fig.add_subplot(111) ax.patch.set_ linewidth(0.1) ax.get_frame().set_linewidth(0.1) ``` The last two lines do not work, but the following works fine: `...
You want to adjust the border line size? You need to use ax.spines[side].set\_linewidth(size). So something like: ``` [i.set_linewidth(0.1) for i in ax.spines.itervalues()] ```
python: how to generate a bitmap?
1,639,470
3
2009-10-28T19:15:57Z
1,639,478
7
2009-10-28T19:17:09Z
[ "python", "bitmap" ]
What's the easiest way to generate a bitmap using Python? Text support would be nice but not required. (On Mac, I was trying to use Quartz through Python, but Snow Leopard seems to have broken its functionality. Therefore I've decided to look for a solid, simple, cross-platform solution that won't break each time the...
Use the [Python Imaging Library](http://www.pythonware.com/products/pil/): *"The Python Imaging Library (PIL) adds image processing capabilities to your Python interpreter. This library supports many file formats, and provides powerful image processing and graphics capabilities."* I'm not a Mac person so I can't help...
POS tagging in German
1,639,855
19
2009-10-28T20:17:48Z
1,640,001
18
2009-10-28T20:46:26Z
[ "python", "nlp", "nltk" ]
I am using NLTK to extract nouns from a text-string starting with the following command: ``` tagged_text = nltk.pos_tag(nltk.Text(nltk.word_tokenize(some_string))) ``` It works fine in English. **Is there an easy way to make it work for German as well?** (I have no experience with natural language programming, but I...
Natural language software does its magic by leveraging corpora and the statistics they provide. You'll need to tell nltk about some German corpus to help it tokenize German correctly. I believe the [EUROPARL](http://www.statmt.org/europarl/) corpus might help get you going. See [nltk.corpus.europarl.german](http://nlt...
POS tagging in German
1,639,855
19
2009-10-28T20:17:48Z
15,278,298
9
2013-03-07T17:53:59Z
[ "python", "nlp", "nltk" ]
I am using NLTK to extract nouns from a text-string starting with the following command: ``` tagged_text = nltk.pos_tag(nltk.Text(nltk.word_tokenize(some_string))) ``` It works fine in English. **Is there an easy way to make it work for German as well?** (I have no experience with natural language programming, but I...
The [Pattern library](http://www.clips.ua.ac.be/pages/pattern-de) includes a function for parsing German sentences and the result includes the part-of-speech tags. The following is copied from their documentation: ``` from pattern.de import parse, split s = parse('Die Katze liegt auf der Matte.') s = split(s) print s....
Running multiple commands simultaneously from python
1,639,912
2
2009-10-28T20:28:21Z
1,639,925
8
2009-10-28T20:30:09Z
[ "python" ]
I want to run three commands at the same time from python. The command format is query.pl -args Currently I am doing ``` os.system("query.pl -results '10000' -serverName 'server1' >> log1.txt") os.system("query.pl -results '10000' -serverName 'server2' >> log2.txt") os.system("query.pl -results '10000' -serverName ...
You could use the [subprocess](http://docs.python.org/library/subprocess.html) module and have all three running independently: use subprocess.Popen. Take care in setting the "shell" parameter correctly. Use the wait() or poll() method to determine when the subprocesses are finished.
Multiple CouchDB Document fetch with couchdb-python
1,640,054
11
2009-10-28T20:52:25Z
1,803,546
19
2009-11-26T13:01:38Z
[ "python", "couchdb" ]
How to fetch multiple documents from CouchDB, in particular with couchdb-python?
Easiest way is to pass a include\_docs=True arg to Database.view. Each row of the results will include the doc. e.g. ``` >>> db = couchdb.Database('http://localhost:5984/test') >>> rows = db.view('_all_docs', keys=['docid1', 'docid2', 'missing'], include_docs=True) >>> docs = [row.doc for row in rows] >>> docs [<Docum...
C# or Python for my app
1,640,080
3
2009-10-28T20:57:55Z
1,640,101
12
2009-10-28T21:02:32Z
[ "c#", "python", "excel" ]
I have the task of developing an application to pull data from remote REST services and generating Excel reports. This application will be used by a handful of users at the company (10-15). The data load can reach 10,000-200,000 records. I have been debating whether to use Python or C#... The only reason I am consider...
Why not [IronPython](http://www.codeplex.com/IronPython) which merges the two worlds together?
python string replacement with % character/**kwargs weirdness
1,640,487
4
2009-10-28T22:19:15Z
1,640,500
14
2009-10-28T22:22:00Z
[ "python", "string-formatting" ]
Following code: ``` def __init__(self, url, **kwargs): for key in kwargs.keys(): url = url.replace('%%s%' % key, str(kwargs[key])) ``` Throws the following exception: ``` File "/home/wells/py-mlb/lib/fetcher.py", line 25, in __init__ url = url.replace('%%s%' % key, str(kwargs[key])) ValueError: incomplete f...
You probably want the format string `%%%s%%` instead of `%%s%`. Two consecutive `%` signs are interpreted as a literal `%`, so in your version, you have a literal `%`, a literal `s`, and then a lone `%`, which is expecting a format specifier after it. You need to double up each literal `%` to not be interpreted as a f...
Get json data via url and use in python (simplejson)
1,640,715
38
2009-10-28T23:09:46Z
1,640,736
43
2009-10-28T23:13:24Z
[ "python", "json", "urllib2", "simplejson" ]
I imagine this must have a simple answer, but I am struggling: I want to take a url (which outputs json) and get the data in a usable dictionary in python. I am stuck on the last step. ``` >>> import urllib2 >>> import simplejson >>> req = urllib2.Request("http://vimeo.com/api/v2/video/38356.json", None, {'user-agent'...
Try ``` f = opener.open(req) simplejson.load(f) ``` without running f.read() first. When you run f.read(), the filehandle's contents are slurped so there is nothing left when your call `simplejson.load(f)`
Get json data via url and use in python (simplejson)
1,640,715
38
2009-10-28T23:09:46Z
1,640,752
10
2009-10-28T23:17:30Z
[ "python", "json", "urllib2", "simplejson" ]
I imagine this must have a simple answer, but I am struggling: I want to take a url (which outputs json) and get the data in a usable dictionary in python. I am stuck on the last step. ``` >>> import urllib2 >>> import simplejson >>> req = urllib2.Request("http://vimeo.com/api/v2/video/38356.json", None, {'user-agent'...
The first line reads the entire file. The second line then tries to read more from the file, but there's nothing left: ``` >>> f.read() # this works blah blah blah >>> simplejson.load(f) ``` Either just omit the f.read() line, or save the value from read, and use it in loads: ``` json = f.read() simplejs...
post_save in django to update instance immediately
1,640,744
9
2009-10-28T23:15:36Z
1,641,021
17
2009-10-29T00:41:56Z
[ "python", "django", "django-models" ]
I'm trying to immediately update a record after it's saved. This example may seem pointless but imagine we need to use an API after the data is saved to get some extra info and update the record: ``` def my_handler(sender, instance=False, **kwargs): t = Test.objects.filter(id=instance.id) t.blah = 'hello' ...
When you find yourself using a post\_save signal to update an object of the sender class, chances are you should be overriding the save method instead. In your case, the model definition would look like: ``` class Test(models.Model): title = models.CharField('title', max_length=200) blah = models.CharField('bl...
Does Python have “private” variables in classes?
1,641,219
273
2009-10-29T01:54:18Z
1,641,236
577
2009-10-29T02:01:29Z
[ "python", "class", "private" ]
I'm coming from the Java world and reading Bruce Eckels' *Python 3 Patterns, Recipes and Idioms*. While reading about classes, it goes on to say that in Python there is no need to declare instance variables. You just use them in the constructor, and boom, they are there. So for example: ``` class Simple: def __i...
It's cultural. In Python, you don't write to other classes' instance or class variables. In Java, nothing prevents you from doing the same if you *really* want to - after all, you can always edit the source of the class itself to achieve the same effect. Python drops that pretence of security and encourages programmers...
Does Python have “private” variables in classes?
1,641,219
273
2009-10-29T01:54:18Z
1,641,305
40
2009-10-29T02:28:33Z
[ "python", "class", "private" ]
I'm coming from the Java world and reading Bruce Eckels' *Python 3 Patterns, Recipes and Idioms*. While reading about classes, it goes on to say that in Python there is no need to declare instance variables. You just use them in the constructor, and boom, they are there. So for example: ``` class Simple: def __i...
"In java, we have been taught about public/private/protected variables" "Why is that not required in python?" For the same reason it's not *required* in Java. You're free to use -- or not use `private` and `protected`. As a Python and Java programmer, I've found that `private` and `protected` are very, very importa...
Does Python have “private” variables in classes?
1,641,219
273
2009-10-29T01:54:18Z
26,965,993
11
2014-11-17T05:17:25Z
[ "python", "class", "private" ]
I'm coming from the Java world and reading Bruce Eckels' *Python 3 Patterns, Recipes and Idioms*. While reading about classes, it goes on to say that in Python there is no need to declare instance variables. You just use them in the constructor, and boom, they are there. So for example: ``` class Simple: def __i...
As correctly mentioned by many of the comments above, let's not forget the main goal of Access Modifiers: To help users of code understand what is supposed to change and what is supposed not to. When you see a private field you don't mess around with it. So it's mostly syntactic sugar which is easily achieved in Python...
Does Python have “private” variables in classes?
1,641,219
273
2009-10-29T01:54:18Z
32,802,486
20
2015-09-26T22:06:06Z
[ "python", "class", "private" ]
I'm coming from the Java world and reading Bruce Eckels' *Python 3 Patterns, Recipes and Idioms*. While reading about classes, it goes on to say that in Python there is no need to declare instance variables. You just use them in the constructor, and boom, they are there. So for example: ``` class Simple: def __i...
private variables in python is more or less a hack, which means the interpreter intentionally rename the variable ``` class A: def __int__(self): self.__var1 = 123 def printVar1(self): print self.__var1 ``` and now if you try to access **\_\_var1** outside the class definition, it will fail `...
Python - Working around memory leaks
1,641,231
24
2009-10-29T01:58:58Z
1,641,280
41
2009-10-29T02:19:30Z
[ "python", "memory-leaks" ]
I have a Python program that runs a series of experiments, with no data intended to be stored from one test to another. My code contains a memory leak which I am completely unable to find (I've look at the [other threads](http://stackoverflow.com/questions/1435415/python-memory-leaks/1641009) on memory leaks). Due to t...
You can use something like this to help track down memory leaks ``` >>> from collections import defaultdict >>> from gc import get_objects >>> before = defaultdict(int) >>> after = defaultdict(int) >>> for i in get_objects(): ... before[type(i)] += 1 ... ``` now suppose the tests leaks some memory ``` >>> leake...
How to permanently append a path to Python for Linux?
1,641,418
4
2009-10-29T03:11:42Z
1,641,426
11
2009-10-29T03:16:03Z
[ "python" ]
I know there are multiple solutions online, but some are for windows, some are environmental variable, etc.. What is the best way?
Find your site-packages directory and create a new file called `myproj.pth` Inside that file, put each directory you want to add, one per line like so: ``` /home/myuser/svn-repos/myproject /home/myuser/svn-repos/SomeOtherProject ``` Python loads `*.pth` every time it runs, and imports all paths in each of those file...
Why am I getting this error in Django?
1,641,444
20
2009-10-29T03:23:08Z
1,641,451
16
2009-10-29T03:26:35Z
[ "python", "django" ]
I have a script that imports a models.py from an app, but it will not import! I don't believe I am supposed to manually create an "export DJANGO..." environment variable...I'm doing something else wrong. ``` Traceback (most recent call last): File "parse.py", line 8, in ? from butterfly.flower.models im...
> I don't believe I am supposed to > manually create an "export DJANGO..." > environment variable... Manually or otherwise, you *are* supposed to ensure that variable is in the environment before you import a Django models file -- not sure what the causes are for your disbelief, but, whatever they may be, that disbeli...
Why am I getting this error in Django?
1,641,444
20
2009-10-29T03:23:08Z
1,641,457
38
2009-10-29T03:29:11Z
[ "python", "django" ]
I have a script that imports a models.py from an app, but it will not import! I don't believe I am supposed to manually create an "export DJANGO..." environment variable...I'm doing something else wrong. ``` Traceback (most recent call last): File "parse.py", line 8, in ? from butterfly.flower.models im...
You need to properly import your settings file. If you don't import the django environment variables first, your import will fail as you've noticed. You need to code something like: ``` import os # Set the DJANGO_SETTINGS_MODULE environment variable. os.environ['DJANGO_SETTINGS_MODULE'] = "myproject.settings" #do yo...
Why am I getting this error in Django?
1,641,444
20
2009-10-29T03:23:08Z
5,461,393
15
2011-03-28T15:35:37Z
[ "python", "django" ]
I have a script that imports a models.py from an app, but it will not import! I don't believe I am supposed to manually create an "export DJANGO..." environment variable...I'm doing something else wrong. ``` Traceback (most recent call last): File "parse.py", line 8, in ? from butterfly.flower.models im...
from command line ran "python manage.py shell" should include the right settings for you and give you the python prompt.
General programming question. When to use OOP?
1,641,470
2
2009-10-29T03:33:54Z
1,641,627
7
2009-10-29T04:33:46Z
[ "python", "oop", "function" ]
My program needs to do 2 things. 1. Extract stuff from a webpage. 2. Do stuff with a webpage. However, there are many webpages, such as Twitter and Facebook. should I do this? ``` def facebookExtract(): code here def twitterExtract(): code here def myspaceExtract(): code here def facebookProcess(): ...
My favorite rule of thumb: if you're in doubt (unspoken assumption: "and you're a reasonable person rather than a fanatic";-), make and use some classes. I've often found myself refactoring code originally written as simple functions into classes -- for example, any time the simple functions' best way to communicating ...
General programming question. When to use OOP?
1,641,470
2
2009-10-29T03:33:54Z
1,642,752
9
2009-10-29T10:25:33Z
[ "python", "oop", "function" ]
My program needs to do 2 things. 1. Extract stuff from a webpage. 2. Do stuff with a webpage. However, there are many webpages, such as Twitter and Facebook. should I do this? ``` def facebookExtract(): code here def twitterExtract(): code here def myspaceExtract(): code here def facebookProcess(): ...
"My program needs to do 2 things." When you start out like that, the objects cannot be seen. You're perspective isn't right. Change your thinking. **"My program works with stuff"** That's OO thinking. What "stuff" does your program work with? Define the stuff. Those are your basic classes. There's a class for each ...
Manual garbage collection in Python
1,641,717
15
2009-10-29T05:06:02Z
1,641,762
24
2009-10-29T05:25:14Z
[ "python", "garbage-collection" ]
Is there any way to manually remove an object which the garbage collection refuses to get rid of even when I call `gc.collect()`? Working in Python 3.0
Per [the docs](http://docs.python.org/library/gc.html?highlight=gc#gc.get_referrers), `gc.get_referrers(thatobject)` will tell you *why* the object is still alive (do it right after a `gc.collect()` to make sure the undesired "liveness" is gonna be persistent). After that, it's somehow of a black art;-). You'll often f...
Simplest way to solve mathematical equations in Python
1,642,357
16
2009-10-29T08:48:29Z
1,642,398
22
2009-10-29T08:58:09Z
[ "python", "math", "numpy", "scipy", "equation" ]
I want to solve a set of equations, linear, or sometimes quadratic. I don't have a specific problem, but often, I have been in this situation often. It is simple to use [wolframalpha.com](http://www.wolframalpha.com/), the web equivalent of Mathematica, to solve them. But that doesn't provide the comfort and convenien...
You discount the best answer as unacceptable. Your question is "I want a free Computer Algebra System that I can use in Python." The answer is "SAGE does that." Have you looked at maxima/macsyma? SAGE provides bindings for it, and that's one of the more powerful free ones. <http://maxima.sourceforge.net/>
Simplest way to solve mathematical equations in Python
1,642,357
16
2009-10-29T08:48:29Z
1,642,479
40
2009-10-29T09:19:37Z
[ "python", "math", "numpy", "scipy", "equation" ]
I want to solve a set of equations, linear, or sometimes quadratic. I don't have a specific problem, but often, I have been in this situation often. It is simple to use [wolframalpha.com](http://www.wolframalpha.com/), the web equivalent of Mathematica, to solve them. But that doesn't provide the comfort and convenien...
[sympy](http://sympy.org/) is exactly what you're looking for.
Simplest way to solve mathematical equations in Python
1,642,357
16
2009-10-29T08:48:29Z
3,507,336
10
2010-08-17T22:02:57Z
[ "python", "math", "numpy", "scipy", "equation" ]
I want to solve a set of equations, linear, or sometimes quadratic. I don't have a specific problem, but often, I have been in this situation often. It is simple to use [wolframalpha.com](http://www.wolframalpha.com/), the web equivalent of Mathematica, to solve them. But that doesn't provide the comfort and convenien...
Here is how to solve your original question using Python (via Sage). This basically clarifies the remark Paul McMillan makes above. ``` sage: a,b,c = var('a,b,c') sage: solve([a+b+c==1000, a^2+b^2==c^2], a,b,c) [[a == 1000*(r1 + sqrt(r1^2 + 2000*r1 - 1000000))/(r1 + sqrt(r1^2 + 2000*r1 - 1000000) + 1000), b == -1/2*r1...
Why do so many apps/frameworks keep their configuration files in an un-executed format?
1,642,413
2
2009-10-29T09:01:19Z
1,642,424
12
2009-10-29T09:03:45Z
[ "python", "configuration", "settings", "yaml" ]
Many frameworks keep their configuration files in a language different from the rest of the program. Eg, Appengine keeps the configuration in yaml format. to compare, DJango settings.py is a python module. There are many disadvantages I can see with this. If its in same language as rest of the program, I can Do inter...
Some framework designers feel that the configuration files are inappropriate places for heavy logic. Just as the MVC framework prevents you from putting logic where it does not belong, the configuration file prevents you from putting programming where it does not belong. It's a matter of taste and philosophy. That sa...
How to delete columns in numpy.array
1,642,730
24
2009-10-29T10:21:34Z
1,643,457
10
2009-10-29T12:44:05Z
[ "python", "numpy", "scipy" ]
I would like to delete selected columns in a numpy.array . This is what I do: ``` n [397]: a = array([[ NaN, 2., 3., NaN], .....: [ 1., 2., 3., 9]]) In [398]: print a [[ NaN 2. 3. NaN] [ 1. 2. 3. 9.]] In [399]: z = any(isnan(a), axis=0) In [400]: print z [ True False False True] In...
Another way is to use masked arrays: ``` import numpy as np a = np.array([[ np.nan, 2., 3., np.nan], [ 1., 2., 3., 9]]) print(a) # [[ NaN 2. 3. NaN] # [ 1. 2. 3. 9.]] ``` The np.ma.masked\_invalid method returns a masked array with nans and infs masked out: ``` print(np.ma.masked_invalid(a)) [[...
How to delete columns in numpy.array
1,642,730
24
2009-10-29T10:21:34Z
5,034,558
26
2011-02-17T20:57:37Z
[ "python", "numpy", "scipy" ]
I would like to delete selected columns in a numpy.array . This is what I do: ``` n [397]: a = array([[ NaN, 2., 3., NaN], .....: [ 1., 2., 3., 9]]) In [398]: print a [[ NaN 2. 3. NaN] [ 1. 2. 3. 9.]] In [399]: z = any(isnan(a), axis=0) In [400]: print z [ True False False True] In...
Given its name, I think the standard way should be `delete`: ``` A = scipy.delete(A, 1, 0) # delete second row of A B = scipy.delete(B, 2, 0) # delete third row of B C = scipy.delete(C, 1, 1) # delete second column of C ```