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
Python XLWT adjusting column widths
3,154,270
13
2010-06-30T23:57:59Z
3,154,308
19
2010-07-01T00:06:41Z
[ "python", "xlwt" ]
I am enormously impressed with the ease of use of XLWT, but there is one thing I have not figured out how to do. I am trying to adjust certain rows to the minimum width they would need to display all characters (in other words, what excel would do if you double clicked on the divider between cells). I know how to adju...
Width is 1/256 the width of the zero character for the default font. A good enough approximation is: ``` def get_width(num_characters): return int((1+num_characters) * 256) ```
What should itertools.product() yield when supplied an empty list?
3,154,301
8
2010-07-01T00:04:54Z
3,154,629
7
2010-07-01T01:49:03Z
[ "python", "itertools", "cross-product" ]
I guess it's an academic question, but the second result does not make sense to me. Shouldn't it be as thoroughly empty as the first? What is the rationale for this behavior? ``` from itertools import product one_empty = [ [1,2], [] ] all_empty = [] print [ t for t in product(*one_empty) ] # [] print [ t for t in p...
From a mathematical point of view the product over no elements should yield the neutral element of the operation *product*, whatever that is. For example on integers the neutral element of multiplication is *1*, since *1 ⋅ a = a* for all integers *a*. So an empty product of integers should be *1*. When implementing a ...
ctypes initializing c_int array by reading file
3,154,439
3
2010-07-01T00:48:39Z
3,158,036
7
2010-07-01T13:03:19Z
[ "python", "arrays", "initialization", "ctypes" ]
Using a Python array, I can initialize a 32,487,834 integer array (found in a file HR.DAT) using the following (not perfectly Pythonic, of course) commands: ``` F = open('HR.DAT','rb') HR = array('I',F.read()) F.close() ``` I need to do the same in ctypes. So far the best I have is: ``` HR = c_int * 32487834 ``` I'...
File objects have a 'readinto(..)' method that can be used to fill objects that support the buffer interface. So, something like this should work: ``` f = open('hr.dat', 'rb') array = (c_int * 32487834)() f.readinto(array) ```
How to mock a free function in python?
3,154,441
8
2010-07-01T00:49:46Z
3,154,466
8
2010-07-01T00:57:05Z
[ "python", "mocking" ]
I have a python program with a global function that is painful to test (it needs a large dataset to work properly). *What is the best way to get around this while testing functions that call it?* I've found that the following works (but it make me feel dirty to use it). module foo: ``` def PainLiesHere(): return 4...
This is a perfectly fine way to do it. As long as you know that `BlissLiesHere` does not change the overall behavior of the unit you are testing... EDIT: This is what is being done, under all the nice extras they provide, by different kinds of mocking libraries, such as [Mock](http://python-mock.sourceforge.net/), [M...
PyCrypto problem using AES+CTR
3,154,998
6
2010-07-01T03:55:53Z
3,155,175
9
2010-07-01T04:55:32Z
[ "python", "cryptography", "aes", "encryption-symmetric", "pycrypto" ]
I'm writing a piece of code to encrypt a text using symmetric encryption. But it's not coming back with the right result... ``` from Crypto.Cipher import AES import os crypto = AES.new(os.urandom(32), AES.MODE_CTR, counter = lambda : os.urandom(16)) encrypted = crypto.encrypt("aaaaaaaaaaaaaaaa") print crypto.decrypt(...
The `counter` must return the same on decryption as it did on encryption, as you intuit, so, one way to do it is: ``` >>> secret = os.urandom(16) >>> crypto = AES.new(os.urandom(32), AES.MODE_CTR, counter=lambda: secret) >>> encrypted = crypto.encrypt("aaaaaaaaaaaaaaaa") >>> print crypto.decrypt(encrypted) aaaaaaaaaaa...
Python packages installation in Windows
3,155,128
14
2010-07-01T04:38:17Z
3,172,454
11
2010-07-03T18:34:45Z
[ "python", "pip", "packages", "setuptools", "distutils" ]
I recently began learning Python, and I am a bit confused about how packages are distributed and installed. I understand that the official way of installing packages is **distutils**: you download the source tarball, unpack it, and run: `python setup.py install`, then the module will automagically install itself I al...
I use pip, and not on Windows, so I can't provide comparison with the Windows-installer option, just some information about pip: * Pip is built on top of setuptools, and requires it to be installed. * Pip is a replacement (improvement) for setuptools' easy\_install. It does everything easy\_install does, plus a lot mo...
__getattr__ for static/class variables in python
3,155,436
31
2010-07-01T06:09:07Z
3,155,493
36
2010-07-01T06:24:20Z
[ "python", "class-method", "getattr" ]
I have a class like: ``` class MyClass: Foo = 1 Bar = 2 ``` Whenever `MyClass.Foo` or `MyClass.Bar` is invoked, I need a custom method to be invoked before the value is returned. Is it possible in Python? I know it is possible if I create an instance of the class and I can define my own `__getattr__` method...
`__getattr__()` and `__str__()` for an object are found on its class, so if you want to customize those things for a class, you need the class-of-a-class. A metaclass. ``` class FooType(type): def _foo_func(cls): return 'foo!' def _bar_func(cls): return 'bar!' def __getattr__(cls, key): ...
__getattr__ for static/class variables in python
3,155,436
31
2010-07-01T06:09:07Z
3,155,505
9
2010-07-01T06:26:07Z
[ "python", "class-method", "getattr" ]
I have a class like: ``` class MyClass: Foo = 1 Bar = 2 ``` Whenever `MyClass.Foo` or `MyClass.Bar` is invoked, I need a custom method to be invoked before the value is returned. Is it possible in Python? I know it is possible if I create an instance of the class and I can define my own `__getattr__` method...
For the first, you'll need to create a metaclass, and define `__getattr__()` on that. ``` class MyMetaclass(type): def __getattr__(self, name): return '%s result' % name class MyClass(object): __metaclass__ = MyMetaclass print MyClass.Foo ``` For the second, no. Calling `str(MyClass.Foo)` invokes `MyClass.F...
__getattr__ for static/class variables in python
3,155,436
31
2010-07-01T06:09:07Z
22,729,414
8
2014-03-29T09:43:06Z
[ "python", "class-method", "getattr" ]
I have a class like: ``` class MyClass: Foo = 1 Bar = 2 ``` Whenever `MyClass.Foo` or `MyClass.Bar` is invoked, I need a custom method to be invoked before the value is returned. Is it possible in Python? I know it is possible if I create an instance of the class and I can define my own `__getattr__` method...
(I know this is an old question, but since all the other answers use a metaclass...) You can use the following simple `classproperty` descriptor: ``` class classproperty(object): """ @classmethod+@property """ def __init__(self, f): self.f = classmethod(f) def __get__(self, *a): return sel...
Is Django admin difficult to customize?
3,155,624
16
2010-07-01T06:52:22Z
3,156,217
14
2010-07-01T08:43:13Z
[ "python", "django", "django-admin", "customization" ]
I have been playing for a couple of days with Django Admin to explore it, but I am still clueless of how it can be customized in the way we need. Every time I look for any help for the customization in the admin panel, what I find is, a bunch of articles on various communities and forums, explaining how to customize t...
You are not providing enough details on what you want to achieve, so it's difficult to say how complex the task is. You might also want to consider not modifying the admin site at all and building your own views where appropriate. However, here are some good links to get you started: * [Customizing the Django Admin](...
Integration testing in python, suggested tools and practices?
3,156,421
11
2010-07-01T09:12:10Z
3,157,823
8
2010-07-01T12:39:18Z
[ "python", "integration-testing" ]
I've some hard time understanding Integration testing in general, I want to do some integration testing in python expecially for network programming in twisted (but I want to know something more in general). There are any good resource I must read, and tools (python tools if possible), practices that introduces me in ...
The recent Pycon had *many* talks on testing. All of the videos are available on Vimeo and the slides can be downloaded.: <http://us.pycon.org/2010/conference/talks/?filter=testing> Specifically, I recommend the talk by [Ned Batchelder](http://blip.tv/pycon-us-videos-2009-2010-2011/pycon-2010-tests-and-testability-188...
how to add dozen of test cases to a test suite automatically in python
3,156,782
6
2010-07-01T10:06:05Z
3,156,827
10
2010-07-01T10:13:00Z
[ "python", "unit-testing", "testcase" ]
i have dozen of test cases in different folders. In the root directory there is a test runner. ``` unittest\ package1\ test1.py test2.py package2\ test3.py test4.py testrunner.py ``` Currently I added the four test cases manually into a test suite ``` import unittest from package1.test1 import ...
In my opinion you should switch to [unittest2](http://docs.python.org/dev/library/unittest.html) or other test frameworks with discovery features. Discovery tests is a really sane way to run them. Most known are: * [nosetests](http://somethingaboutorange.com/mrl/projects/nose/0.11.3/) * [py.test](http://codespeak.net...
How do you 'remove' a numpy array from a list of numpy arrays?
3,157,374
7
2010-07-01T11:41:48Z
3,160,274
9
2010-07-01T17:38:55Z
[ "python", "numpy" ]
If I have a list of numpy arrays, then using remove method returns a value error. For example: ``` import numpy as np l = [np.array([1,1,1]),np.array([2,2,2]),np.array([3,3,3])] l.remove(np.array([2,2,2])) ``` Would give me > ValueError: The truth value of an array with more than one element is ambiguous. Use a.a...
The problem here is that when two numpy arrays are compared with ==, as in the remove() and index() methods, a numpy array of boolean values (the element by element comparisons) is returned which is interpretted as being ambiguous. A good way to compare two numpy arrays for equality is to use numpy's array\_equal() fun...
Loop Java HashMap like Python Dictionary?
3,157,558
7
2010-07-01T12:06:48Z
3,157,589
20
2010-07-01T12:11:31Z
[ "java", "python", "hashmap", "equivalent" ]
In Python, you can have key,value pairs in a dictionary where you can loop through them, as shown below: ``` for k,v in d.iteritems(): print k,v ``` Is there a way to do this with Java HashMaps?
Yes - for example: ``` Map<String, String> map = new HashMap<String, String>(); // add entries to the map here for (Map.Entry<String, String> entry : map.entrySet()) { String k = entry.getKey(); String v = entry.getValue(); System.out.printf("%s %s\n", k, v); } ```
How can I achieve layout similar to Google Image search in QT (PyQT)?
3,157,766
2
2010-07-01T12:31:57Z
3,160,725
12
2010-07-01T18:43:03Z
[ "python", "qt", "qt4", "pyqt" ]
I'm new to QT. I'm using PyQT for GUI development in my project. I want to achieve this layout in my application. This application searches images from an image database. Google image search layout is ideal for my purpose. ![alt text](http://img821.imageshack.us/img821/8379/window2.png) I'm following the book "Rapid ...
**1/2**. For displaying the images and labels use a [QListWidget](http://doc.qt.nokia.com/4.6/qlistwidgetitem.html) with view mode set to QListView::IconMode. However, if you need to customize the display beyond what the QListWidget/QListWidgetItem api can provide you will need to create your own [QAbstractListModel](h...
Logging activity on Django's admin - Django
3,157,875
17
2010-07-01T12:45:13Z
3,157,915
8
2010-07-01T12:50:10Z
[ "python", "django", "logging", "django-admin" ]
I need to track/log activity on the Django admin. I know there are messages stored by admin somewhere, but I don't know how to access them in order to use them as a simple log. --- I'm trying to track the following: * User performing the action * Action committed * Datetime of action Thanks guys.
Log is in django\_admin\_log table in database used by django.
Logging activity on Django's admin - Django
3,157,875
17
2010-07-01T12:45:13Z
3,159,392
14
2010-07-01T15:45:10Z
[ "python", "django", "logging", "django-admin" ]
I need to track/log activity on the Django admin. I know there are messages stored by admin somewhere, but I don't know how to access them in order to use them as a simple log. --- I'm trying to track the following: * User performing the action * Action committed * Datetime of action Thanks guys.
I had to do something similar and I used something like this: ``` from django.contrib.admin.models import LogEntry logs = LogEntry.objects.all() #or you can filter, etc. for l in logs: #perform action ``` You can see [all of the attributes for LogEntry](http://code.djangoproject.com/browser/django/trunk/django/c...
Python in terminal
3,158,291
2
2010-07-01T13:37:18Z
3,158,336
7
2010-07-01T13:43:03Z
[ "python", "osx", "terminal" ]
This question concerns running python files in terminal that are not stored in the home directory. I think I have solved the first bit of this puzzle by modifying my path so that it includes the directory where my python programs are stored. So where as initially `echo $PATH` would yield the following: `/usr/bin:/bin:...
Including the directory where a command lives in your $PATH means you can run commands in that directory from anywhere. But in your first example, you are running the command "python" with recap.py as an argument. So your shell does not search your $PATH to find where recap.py lives. To make recap.py runnable as a comm...
Creating/making directories in python (complex)
3,158,921
3
2010-07-01T14:51:06Z
3,159,016
17
2010-07-01T15:00:38Z
[ "python", "directory", "mkdir" ]
I am trying to create a bunch of directories/subdirectories that I can copy files into. I am working with Python and I can't seem to find a good way to do this. I have a main path that I will branch off of. Then after that, I have Weights and No\_Weights. Male and Female following. Within each of Male and Female folder...
``` import itertools import os dirs = [["Weights", "No_Weights"], ["Male", "Female"], ["Caucasian", "African-American", "Asian", "Hispanic", "Indo", "Other", "Unknown"], ["B20", "20", "30", "40", "50", "60", "70"]] for item in itertools.product(*dirs): os.makedirs(os.path.join(*item)) ```...
Is it ok to use map to apply function to arguments list and ignore the results?
3,159,120
3
2010-07-01T15:12:51Z
3,159,130
8
2010-07-01T15:14:02Z
[ "python" ]
Do you think that it is OK to use map for an applying function to arguments list and ignore the results? ``` map(foo, bar) ``` It may appears as bug to person who is reading code.
When you want the result using map is a perfectly fine way to apply a function to each item in a list, although many find it clearer to write it as a list comprehension or generator: ``` result = [foo(x) for x in bar] ``` However if you don't intend to use the result of the function call and are interested only in th...
How to remove all integer values from a list in python
3,159,155
6
2010-07-01T15:16:43Z
3,159,166
15
2010-07-01T15:17:59Z
[ "python", "string" ]
I am just a beginner in python and I want to know is it possible to remove all the integer values from a list? For example the document goes like ``` ['1','introduction','to','molecular','8','the','learning','module','5'] ``` After the removal I want the document to look like: ``` ['introduction','to','molecular','t...
To remove all integers, do this: ``` no_integers = [x for x in mylist if not isinstance(x, int)] ``` However, your example list does not actually contain integers. It contains only strings, some of which are composed only of digits. To filter those out, do the following: ``` no_integers = [x for x in mylist if not (...
How to remove all integer values from a list in python
3,159,155
6
2010-07-01T15:16:43Z
3,159,442
9
2010-07-01T15:49:26Z
[ "python", "string" ]
I am just a beginner in python and I want to know is it possible to remove all the integer values from a list? For example the document goes like ``` ['1','introduction','to','molecular','8','the','learning','module','5'] ``` After the removal I want the document to look like: ``` ['introduction','to','molecular','t...
You can do this, too: ``` def int_filter( someList ): for v in someList: try: int(v) continue # Skip these except ValueError: yield v # Keep these list( int_filter( items )) ``` Why? Because `int` is better than trying to write rules or regular expressions to r...
How to unit test a form with a captcha field in django?
3,159,284
7
2010-07-01T15:31:06Z
19,937,142
10
2013-11-12T18:31:34Z
[ "python", "django", "unit-testing", "captcha" ]
I would like to unit test a django view by sumitting a form. The problem is that this form has a captcha field (based on django-simple-captcha). ``` from django import forms from captcha.fields import CaptchaField class ContactForm(forms.forms.Form): """ The information needed for being able to download "...
I know this is an old post, but django-simple-captcha now has a setting CAPTCHA\_TEST\_MODE which makes the captcha succeed if you supply the value 'PASSED'. You just have to make sure to send something for both of the captcha input fields: ``` post_data['captcha_0'] = 'dummy-value' post_data['captcha_1'] = 'PASSED' s...
Why doesn't finite repetition in lookbehind work in some flavors?
3,159,524
3
2010-07-01T15:58:29Z
3,159,581
13
2010-07-01T16:05:32Z
[ "c#", "java", "python", "regex", "lookbehind" ]
I want to parse the 2 digits in the middle from a date in `dd/mm/yy` format but also allowing single digits for day and month. This is what I came up with: ``` (?<=^[\d]{1,2}\/)[\d]{1,2} ``` I want a 1 or 2 digit number `[\d]{1,2}` with a 1 or 2 digit number and slash `^[\d]{1,2}\/` before it. This doesn't work on ...
## On lookbehind support Major regex flavors have varying supports for lookbehind differently; some imposes certain restrictions, and some doesn't even support it at all. * Javascript: not supported * Python: fixed length only * Java: finite length only * .NET: no restriction ### References * [regular-expressions.i...
Iterating through model fields - Django
3,159,614
13
2010-07-01T16:08:58Z
3,159,649
21
2010-07-01T16:14:33Z
[ "python", "django", "django-models" ]
I'm trying to **iterate through fields as they are written down within my model**: currently I'm using this: ``` def attrs(self): for attr, value in self.__dict__.iteritems(): yield attr, value ``` but the order seems pretty much **random** :( --- Any ideas?
The `_meta` attribute on `Model` classes and instances is a `django.db.models.options.Options` which provides access to all sorts of useful information about the `Model` in question. For fields, it will give you them in the order they were created (i.e. the same order they were declared). ``` def attrs(self): for...
Is there a way to get python's nose module to work the same in __main__ and on the command line?
3,160,551
8
2010-07-01T18:21:10Z
4,103,832
7
2010-11-05T05:44:33Z
[ "python", "nose", "nosetests" ]
I'm not sure of how to get the nose module's `__main__` handler to work. I have this at the end of my test module: ``` if __name__ == "__main__": import nose nose.main() ``` Which gives me: ``` ---------------------------------------------------------------------- Ran 0 tests in 0.002s OK ``` but it I run ...
``` if __name__ == '__main__': import nose nose.run(defaultTest=__name__) ```
Is there a way to get python's nose module to work the same in __main__ and on the command line?
3,160,551
8
2010-07-01T18:21:10Z
12,094,865
8
2012-08-23T15:14:00Z
[ "python", "nose", "nosetests" ]
I'm not sure of how to get the nose module's `__main__` handler to work. I have this at the end of my test module: ``` if __name__ == "__main__": import nose nose.main() ``` Which gives me: ``` ---------------------------------------------------------------------- Ran 0 tests in 0.002s OK ``` but it I run ...
For posterity's sake, this is what I use: ``` if __name__ == '__main__': import nose nose.run(argv=[__file__, '--with-doctest', '-vv']) ``` The `--with-doctests` will also execute your doctests in the same file.
Python regex confused by brackets ([])?
3,160,590
3
2010-07-01T18:26:22Z
3,160,606
7
2010-07-01T18:28:34Z
[ "python", "regex", "brackets" ]
Is python confused, or is the programmer? I've got a lot of lines of this: ``` some_dict[0x2a] = blah some_dict[0xab] = blah, blah ``` What I'd like to do is to convert the hex codes into all uppercase to look like this: ``` some_dict[0x2A] = blah some_dict[0xAB] = blah, blah ``` So I decided to call in the regula...
`re.match` matches from the *start* of the string. Use `re.search` instead to "match the first occurrence anywhere in the string". The key bit about this in the docs is [here](https://docs.python.org/2/library/re.html#search-vs-match).
Python Progress Bar
3,160,699
82
2010-07-01T18:39:36Z
3,160,819
90
2010-07-01T18:57:19Z
[ "python" ]
How do I use a progress bar when my script is doing some task that is likely to take time? For example, a function which takes some time to complete and returns `True` when done. How can I display a progress bar during the time the function is being executed? Note that I need this to be in real time, so I can't figur...
There are specific libraries ([like this one here](http://pypi.python.org/pypi/progressbar2)) but maybe something very simple would do: ``` import time import sys toolbar_width = 40 # setup toolbar sys.stdout.write("[%s]" % (" " * toolbar_width)) sys.stdout.flush() sys.stdout.write("\b" * (toolbar_width+1)) # return...
Python Progress Bar
3,160,699
82
2010-07-01T18:39:36Z
7,932,247
16
2011-10-28T16:45:58Z
[ "python" ]
How do I use a progress bar when my script is doing some task that is likely to take time? For example, a function which takes some time to complete and returns `True` when done. How can I display a progress bar during the time the function is being executed? Note that I need this to be in real time, so I can't figur...
for a similar application (keeping track of the progress in a loop) I simply used the [python-progressbar](http://code.google.com/p/python-progressbar/): Their example goes something like this, ``` from progressbar import * # just a simple progress bar widgets = ['Test: ', Percentage(), ' ', Bar(marke...
Python Progress Bar
3,160,699
82
2010-07-01T18:39:36Z
15,860,757
44
2013-04-07T09:11:59Z
[ "python" ]
How do I use a progress bar when my script is doing some task that is likely to take time? For example, a function which takes some time to complete and returns `True` when done. How can I display a progress bar during the time the function is being executed? Note that I need this to be in real time, so I can't figur...
The above suggestions are pretty good, but I think most people just want a ready made solution, with no dependencies on external packages, but is also reusable. I got the best points of all the above, and made it into a function, along with a test cases. To use it, just copy the lines under "def update\_progress(prog...
Python Progress Bar
3,160,699
82
2010-07-01T18:39:36Z
26,761,413
38
2014-11-05T15:52:59Z
[ "python" ]
How do I use a progress bar when my script is doing some task that is likely to take time? For example, a function which takes some time to complete and returns `True` when done. How can I display a progress bar during the time the function is being executed? Note that I need this to be in real time, so I can't figur...
With [tqdm](https://github.com/tqdm/tqdm) you can add a progress meter to your loops in a second: ``` In [20]: import time In [21]: from tqdm import * In [23]: for i in tqdm(range(10)): ....: time.sleep(3) 60%|██████ | 6/10 [00:18<00:12, 0.33 it/s] ```
Removing backslashes from a string in Python
3,160,752
8
2010-07-01T18:46:56Z
3,160,772
15
2010-07-01T18:49:20Z
[ "python", "regex", "escaping" ]
How do I remove all the backslashes from a string in Python? This is not working for me: ``` result = result.replace("\\", result) ``` Do I need to treat result as a raw string?
Your code is saying to replace each instance of `'\'` with `result`. Have you tried changing it to `result.replace("\\", "")` ?
Django order_by sum of fields
3,160,798
7
2010-07-01T18:53:07Z
3,161,067
16
2010-07-01T19:34:07Z
[ "python", "django" ]
Is it possible to use the django ORM to order a queryset by the sum of two different fields? For example, I have a model that looks like this: ``` class Component(models.Model): material_cost = CostField() labor_cost = CostField() ``` and I want to do something like this: ``` component = Component.objects.o...
You can use `extra` for this. ``` Component.objects.extra( select={'fieldsum':'material_cost + labor_cost'}, order_by=('fieldsum',) ) ``` See [the documentation](https://docs.djangoproject.com/en/1.9/ref/models/querysets/#django.db.models.query.QuerySet.extra).
None value returned
3,160,863
2
2010-07-01T19:03:39Z
3,160,913
8
2010-07-01T19:09:32Z
[ "python" ]
The code below is used in a function: ``` def print_query(x): h = open('/home/rv/data.txt', 'r') read = h.readlines() for line in read: return line ``` When the value "line" is retunred it should print but instead i get the value "None"
Try this: ``` with open('/home/rv/data.txt','r') as fh: for line in fh: print line ``` If you're on Python 2.5 you might need a `from __future__ import with_statement` on top. Also: why do you `return` the line when you want to `print` it?
Iterate a format string over a list
3,161,544
9
2010-07-01T20:47:56Z
3,161,663
10
2010-07-01T21:03:42Z
[ "python", "formatting", "iteration", "language-comparisons" ]
In Lisp, you can have something like this: ``` (setf my-stuff '(1 2 "Foo" 34 42 "Ni" 12 14 "Blue")) (format t "~{~d ~r ~s~%~}" my-stuff) ``` What would be the most Pythonic way to iterate over that same list? The first thing that comes to mind is: ``` mystuff = [1, 2, "Foo", 34, 42, "Ni", 12, 14, "Blue"] for x in xr...
``` mystuff = [1, 2, "Foo", 34, 42, "Ni", 12, 14, "Blue"] for x in zip(*[iter(mystuff)]*3): print "%d %d %s"%x ``` Or using `.format` ``` mystuff = [1, 2, "Foo", 34, 42, "Ni", 12, 14, "Blue"] for x in zip(*[iter(mystuff)]*3): print "{0} {1} {2}".format(*x) ``` If the format string is not hardcoded, you can p...
What am I doing wrong? Python object instantiation keeping data from previous instantiation?
3,161,827
4
2010-07-01T21:29:28Z
3,161,845
7
2010-07-01T21:32:03Z
[ "python", "instantiation" ]
Can someone point out to me what I'm doing wrong or where my understanding is wrong? To me, it seems like the code below which instantiates two objects should have separate data for each instantiation. ``` class Node: def __init__(self, data = []): self.data = data def main(): a = Node() a.data.a...
You can't use an mutable object as a default value. All objects will share the same mutable object. Do this. ``` class Node: def __init__(self, data = None): self.data = data if data is not None else [] ``` When you create the class definition, it creates the `[]` list object. Every time you create an in...
A Faster way of Directory walking instead of os.listdir?
3,162,002
11
2010-07-01T22:02:45Z
4,739,544
14
2011-01-19T19:10:43Z
[ "python", "file-io", "directory", "performance" ]
I am trying to improve performance of elfinder , an ajax based file manager(elRTE.ru) . It uses os.listdir in a recurisve to walk through all directories recursively and having a performance hit (like listing a dir with 3000 + files takes 7 seconds ) .. I am trying to improve performance for it here is it's walking f...
I was just trying to figure out how to speed up os.walk on a largish file system (350,000 files spread out within around 50,000 directories). I'm on a linux box usign an ext3 file system. I discovered that there is a way to speed this up for MY case. Specifically, Using a top-down walk, any time os.walk returns a list...
A Faster way of Directory walking instead of os.listdir?
3,162,002
11
2010-07-01T22:02:45Z
33,695,518
7
2015-11-13T14:55:23Z
[ "python", "file-io", "directory", "performance" ]
I am trying to improve performance of elfinder , an ajax based file manager(elRTE.ru) . It uses os.listdir in a recurisve to walk through all directories recursively and having a performance hit (like listing a dir with 3000 + files takes 7 seconds ) .. I am trying to improve performance for it here is it's walking f...
Did you check out [scandir](https://github.com/benhoyt/scandir) (previously [betterwalk](https://github.com/benhoyt/betterwalk))? Did not try it myself, but there's a [discussion about it here](http://grokbase.com/t/python/python-ideas/12bp4c4ndf/betterwalk-a-better-and-faster-os-walk-for-python) and [another one here]...
Python binary file reading problem
3,162,191
3
2010-07-01T22:37:15Z
3,162,230
7
2010-07-01T22:45:48Z
[ "python", "matlab", "file-io", "binary" ]
I'm trying to read a binary file (which represents a matrix in Matlab) in Python. But I am having trouble reading the file and converting the bytes to the correct values. The binary file consists of a sequence of 4-byte numbers. The first two numbers are the number of rows and columns respectively. My friend gave me a...
``` rows = f.read(4) cols = f.read(4) ``` both names are now bound to 4-byte strings. To turn them into integers instead, ``` import struct rowsandcols = f.read(8) rows, cols = struct.unpack('=ii', rowsandcols) ``` See [the docs](http://docs.python.org/library/struct.html?highlight=struct.unpack#struct.unpack) for ...
Get loop count inside a Python FOR loop
3,162,271
122
2010-07-01T22:59:27Z
3,162,287
284
2010-07-01T23:02:52Z
[ "python", "for-loop" ]
In a Python `for` loop that iterates over a list we can write: ``` for item in list: print item ``` and it neatly goes through all the elements in the list. Is there a way to know within the loop how many times I've been looping so far? For instance, I want to take a list and after I've processed ten elements I w...
The pythonic way is to use [`enumerate`](http://docs.python.org/library/functions.html#enumerate): ``` for idx,item in enumerate(list): ```
Get loop count inside a Python FOR loop
3,162,271
122
2010-07-01T22:59:27Z
19,398,650
22
2013-10-16T08:34:39Z
[ "python", "for-loop" ]
In a Python `for` loop that iterates over a list we can write: ``` for item in list: print item ``` and it neatly goes through all the elements in the list. Is there a way to know within the loop how many times I've been looping so far? For instance, I want to take a list and after I've processed ten elements I w...
Agree with Nick. Here is more elaborated code. ``` #count=0 for idx, item in enumerate(list): print item #count +=1 #if count % 10 == 0: if idx % 10 == 0: print 'did ten' ``` I have commented out the count variable in your code.
Add headers to a file
3,162,314
3
2010-07-01T23:09:45Z
3,162,361
7
2010-07-01T23:23:16Z
[ "python", "file-io", "header" ]
I have a file containing data like below: ``` 88_NPDJ 565 789 3434 54454 98HGJDN 945 453 3453 23423 ... ... ... ``` whats the best way to add headers to the file? After data has been entered into the file. The data is tab delimited.
Best way to get the effect of `altering a file in place` is with [fileinput](http://docs.python.org/library/fileinput.html?highlight=fileinput#module-fileinput): ``` import fileinput headers = 'a b c d e'.split() for line in fileinput.input(['thefile.blah'], inplace=True): if fileinput.isfirstline(): prin...
Python "List" object is not callable
3,162,588
2
2010-07-02T00:42:42Z
3,162,605
9
2010-07-02T00:45:17Z
[ "python" ]
I'm writing a program that looks through CSVs in a directory and appends the contents of each CSV to a list. Here's a snippet of the offending code: ``` import glob import re c = glob.glob("*.csv") print c archive = [] for element in c: look = open(element, "r").read() open = re.split("\n+", look) for ...
I think it's because you redefine `open` as a list and call it in the next loop iteration. Just give the list another name. Note that strings have a `split()` method for when you don't need a regex.
Python search and replace in binary file
3,162,614
8
2010-07-02T00:47:23Z
3,162,660
10
2010-07-02T01:04:11Z
[ "python", "replace", "binary-data" ]
I am trying to search and replace some of the text (eg 'Smith, John') in this pdf form file (header.fdf, I presumed this is treated as binary file): ``` '%FDF-1.2\n%\xe2\xe3\xcf\xd3\n1 0 obj\n<</FDF<</Fields[<</V(M)/T(PatientSexLabel)>><</V(24-09-1956 53)/T(PatientDateOfBirth)>><</V(Fisher)/T(PatientLastNameLabel)>><...
``` f=open("header.fdf","rb") s=str(f.read()) f.close() s=s.replace(b'PatientName',name) ``` or ``` f=open("header.fdf","rb") s=f.read() f.close() s=s.replace(b'PatientName',bytes(name)) ``` probably the latter, as I don't think you are going to be able to use unicode names with this type of substitution anyway
What does [[]]*2 do in python?
3,162,698
8
2010-07-02T01:16:29Z
3,162,717
16
2010-07-02T01:21:32Z
[ "python" ]
``` A = [[]]*2 A[0].append("a") A[1].append("b") B = [[], []] B[0].append("a") B[1].append("b") print "A: "+ str(A) print "B: "+ str(B) ``` Yields: ``` A: [['a', 'b'], ['a', 'b']] B: [['a'], ['b']] ``` One would expect that the A list would be the same as the B list, this is not the case, both append statements ...
`A = [[]]*2` creates a list with 2 identical elements: `[[],[]]`. The elements are the same exact list. So ``` A[0].append("a") A[1].append("b") ``` appends both `"a"` and `"b"` to the same list. `B = [[], []]` creates a list with 2 distinct elements. ``` In [220]: A=[[]]*2 In [221]: A Out[221]: [[], []] ``` This...
Python dictionary - binary search for a key?
3,162,882
11
2010-07-02T02:11:36Z
3,162,915
13
2010-07-02T02:21:57Z
[ "python" ]
I want to write a container class that acts like a dictionary (actually derives from a dict), The keys for this structure will be dates. When a key (i.e. date) is used to retrieve a value from the class, if the date does not exist then the next available date that preceeds the key is used to return the value. The fol...
You really don't want to subclass `dict` because you can't really reuse any of its functionality. Rather, subclass the abstract base class [`collections.Mapping`](http://docs.python.org/library/collections.html?highlight=collections#abcs-abstract-base-classes) (or `MutableMapping` if you want to also be able to modify ...
Method to save networkx graph to json graph?
3,162,909
12
2010-07-02T02:21:19Z
8,681,020
11
2011-12-30T15:28:13Z
[ "python", "json", "graph", "networkx" ]
Seems like there should be a method in networkx to export the json graph format, but I don't see it. I imagine this should be easy to do with nx.to\_dict\_of\_dicts(), but would require a bit of manipulation. Anyone know of a simple and elegant solution?
The documentation is at: <http://networkx.lanl.gov/reference/readwrite.json_graph.html> A simple example is this: ``` import networkx as nx from networkx.readwrite import json_graph DG = nx.DiGraph() DG.add_edge('a', 'b') print json_graph.dumps(DG) ``` You can also take a look at the [Javascript/SVG/D3](https://net...
Escape arguments for paramiko.SSHClient().exec_command
3,163,236
3
2010-07-02T04:29:23Z
13,786,877
7
2012-12-09T11:09:54Z
[ "python", "paramiko" ]
What is the best way to escape a string for safe usage as a command-line argument? I know that using `subprocess.Popen` takes care of this using `list2cmdline()`, but that doesn't seem to work correctly for paramiko. Example: ``` from subprocess import Popen Popen(['touch', 'foo;uptime']).wait() ``` This creates a fi...
Assuming the remote user has a POSIX shell, this should work: ``` def shell_escape(arg): return "'%s'" % (arg.replace(r"'", r"'\''"), ) ``` # Why does this work? [POSIX shell single quotes](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_02_02) are defined as: > Enclosing charact...
Better Way to Write This List Comprehension?
3,163,391
2
2010-07-02T05:20:25Z
3,163,406
7
2010-07-02T05:25:05Z
[ "python", "list-comprehension" ]
I'm parsing a string that doesn't have a delimiter but does have specific indexes where fields start and stop. Here's my list comprehension to generate a list from the string: ``` field_breaks = [(0,2), (2,10), (10,13), (13, 21), (21, 32), (32, 43), (43, 51), (51, 54), (54, 55), (55, 57), (57, 61), (61, 63), (63, 113)...
You can cut your `field_breaks` list in half by doing: ``` field_breaks = [0, 2, 10, 13, 21, 32, 43, ..., 250, 300] s = ... data = [s[x[0]:x[1]].strip() for x in zip(field_breaks[:-1], field_breaks[1:])] ```
Better Way to Write This List Comprehension?
3,163,391
2
2010-07-02T05:20:25Z
3,163,519
7
2010-07-02T05:53:04Z
[ "python", "list-comprehension" ]
I'm parsing a string that doesn't have a delimiter but does have specific indexes where fields start and stop. Here's my list comprehension to generate a list from the string: ``` field_breaks = [(0,2), (2,10), (10,13), (13, 21), (21, 32), (32, 43), (43, 51), (51, 54), (54, 55), (55, 57), (57, 61), (61, 63), (63, 113)...
You can use tuple unpacking for cleaner code: ``` data = [s[a:b].strip() for a,b in field_breaks] ```
Can't build readline when trying to install Python 2.6.5 in Debian 4.3.2
3,163,573
3
2010-07-02T06:07:42Z
3,163,704
7
2010-07-02T06:37:46Z
[ "python", "linux", "debian", "readline" ]
I am trying to install Python 2.6.5 on my web server running Debian 4.3.2.1-1. I unpacked the tarball, ran "./configure --prefix /usr/", then ran "make". I saw this message. ``` Failed to find the necessary bits to build these modules: _bsddb _hashlib _ssl _tkinter bsddb185 ...
You'll probably need to install the [libreadline-dev](http://packages.debian.org/etch/libreadline-dev) virtual package for Debian 4 (`etch`) to be able to build python with `libreadline` support. Check the package dependencies for the Debian python2.6 source package [here](http://packages.debian.org/source/squeeze/pyth...
Fast lookup for dictionary vector to a given vector. High dimensions
3,163,854
6
2010-07-02T07:08:53Z
3,164,039
8
2010-07-02T07:49:37Z
[ "python", "algorithm", "math", "vector" ]
I'm looking for an answer that scales, but for my specific purpose, I have a 48th dimension vector. This could be represented as an array of 48 integers all between 0 and 255. I have a large dictionary of these vectors, approximately 25 thousand of them. I need to be able to take a vector that may or may not be in my...
I would suggest implementing a [kd-tree](http://en.wikipedia.org/wiki/Kd-tree) on which you can perform [Nearest neighbour search](http://en.wikipedia.org/wiki/Kd-tree#Nearest_neighbor_search). The worst case search time for N points in k dimensions is `O(k.N^(1-1/k))` so it should scale sublinearly in N. If I have ti...
Django 'resolve' : get the url name instead of the view_function
3,165,037
14
2010-07-02T10:49:15Z
10,842,650
25
2012-05-31T23:34:09Z
[ "python", "django", "django-urls" ]
My problem is simple, I have an url, I would like to resolve it, but get the `url` name instead of the view function associated with it ... For example... this is urlconf : ``` urlpatterns = patterns('', ... url('^/books/$', book_list, name="overview_books"), ... ) ``` And this is what I would like : ``` >>> re...
In Django 1.3 and newer you can use [resolve](https://docs.djangoproject.com/en/dev/ref/urlresolvers/#resolve) function: ``` from django.core.urlresolvers import resolve print resolve('/books/').url_name ```
Can ( s is "" ) and ( s == "" ) ever give different results in Python 2.6.2?
3,165,300
5
2010-07-02T11:39:06Z
3,165,376
12
2010-07-02T11:50:47Z
[ "python", "string", "identity", "equality" ]
As any Python programmer knows, you should use `==` instead of `is` to compare two strings for equality. However, are there actually any cases where `( s is "" )` and `( s == "" )` will give different results in Python 2.6.2? I recently came across code that used `( s is "" )` in code review, and while pointing out th...
Python `is` tests the objects identity and not equality. Here is an example where using `is` and `==` gives a different result: ``` >>> s=u"" >>> print s is "" False >>> print s=="" True ```
Can ( s is "" ) and ( s == "" ) ever give different results in Python 2.6.2?
3,165,300
5
2010-07-02T11:39:06Z
3,165,414
7
2010-07-02T11:56:19Z
[ "python", "string", "identity", "equality" ]
As any Python programmer knows, you should use `==` instead of `is` to compare two strings for equality. However, are there actually any cases where `( s is "" )` and `( s == "" )` will give different results in Python 2.6.2? I recently came across code that used `( s is "" )` in code review, and while pointing out th...
You shouldn't care. Unlike `None` which is defined to be a singleton, there is no rule that says there is only one empty string object. So the result of `s is ""` is implementation-dependent and using `is` is a NO-NO whether you can find an example or not.
Can ( s is "" ) and ( s == "" ) ever give different results in Python 2.6.2?
3,165,300
5
2010-07-02T11:39:06Z
3,166,348
11
2010-07-02T13:59:04Z
[ "python", "string", "identity", "equality" ]
As any Python programmer knows, you should use `==` instead of `is` to compare two strings for equality. However, are there actually any cases where `( s is "" )` and `( s == "" )` will give different results in Python 2.6.2? I recently came across code that used `( s is "" )` in code review, and while pointing out th...
As everyone else has said, don't rely on undefined behaviour. However, since you asked for a specific counterexample for Python 2.6, here it is: ``` >>> s = u"\xff".encode('ascii', 'ignore') >>> s '' >>> id(s) 10667744 >>> id("") 10666064 >>> s == "" True >>> s is "" False >>> type(s) is type("") True ``` The only ti...
How to use OR using Django's model filter system?
3,166,361
22
2010-07-02T14:00:17Z
3,166,377
44
2010-07-02T14:02:35Z
[ "python", "sql", "django" ]
It seems that Django's object model filter method automatically uses the AND SQL keyword. For example: ``` >>> Publisher.objects.filter(name__contains="press", country__contains="U.S.A" ``` will automatically translate into something like: ``` SELECT ... FROM publisher WHERE name LIKE '%press%' AND country LIKE '%...
You can use [Q objects](http://docs.djangoproject.com/en/dev/topics/db/queries/#complex-lookups-with-q-objects) to do what you want, by bitwise OR-ing them together: ``` from django.db.models import Q Publisher.objects.filter(Q(name__contains="press") | Q(country__contains="U.S.A")) ```
python regex: match a string with only one instance of a character
3,166,619
6
2010-07-02T14:31:59Z
3,166,673
8
2010-07-02T14:38:47Z
[ "python", "regex", "string" ]
Suppose there are two strings: ``` $1 off delicious ham. $1 off delicious $5 ham. ``` In Python, can I have a regex that matches when there is only one $ in the string? I.e., I want the RE to match on the first phrase, but not on the second. I tried something like: ``` re.search(r"\$[0-9]+.*!(\$)","$1 off delicious ...
``` >>> import re >>> onedollar = re.compile(r'^[^\$]*\$[^\$]*$') >>> onedollar.match('$1 off delicious ham.') <_sre.SRE_Match object at 0x7fe253c9c4a8> >>> onedollar.match('$1 off delicious $5 ham.') >>> ``` Breakdown of regexp: `^` Anchor at start of string `[^\$]*` Zero or more characters that are not `$` `\$...
python regex: match a string with only one instance of a character
3,166,619
6
2010-07-02T14:31:59Z
3,166,716
7
2010-07-02T14:44:38Z
[ "python", "regex", "string" ]
Suppose there are two strings: ``` $1 off delicious ham. $1 off delicious $5 ham. ``` In Python, can I have a regex that matches when there is only one $ in the string? I.e., I want the RE to match on the first phrase, but not on the second. I tried something like: ``` re.search(r"\$[0-9]+.*!(\$)","$1 off delicious ...
``` >>> '$1 off delicious $5 ham.'.count('$') 2 >>> '$1 off delicious ham.'.count('$') 1 ```
Python: How to make object attribute refer call a method
3,166,773
10
2010-07-02T14:51:53Z
3,166,780
10
2010-07-02T14:53:14Z
[ "python", "attributes" ]
I'd like for an attribute call like `object.x` to return the results of some method, say `object.other.other_method()`. How can I do this? Edit: I asked a bit soon: it looks like I can do this with ``` object.__dict__['x']=object.other.other_method() ``` Is this an OK way to do this?
Have a look at the built-in [property](http://docs.python.org/library/functions.html#property) function.
Python: How to make object attribute refer call a method
3,166,773
10
2010-07-02T14:51:53Z
3,166,802
20
2010-07-02T14:55:26Z
[ "python", "attributes" ]
I'd like for an attribute call like `object.x` to return the results of some method, say `object.other.other_method()`. How can I do this? Edit: I asked a bit soon: it looks like I can do this with ``` object.__dict__['x']=object.other.other_method() ``` Is this an OK way to do this?
Use the property decorator ``` class Test(object): # make sure you inherit from object @property def x(self): return 4 p = Test() p.x # returns 4 ``` Mucking with the \_\_dict\_\_ is dirty, especially when @property is available.
How to split a dos path into its components in Python
3,167,154
50
2010-07-02T15:41:56Z
3,167,392
11
2010-07-02T16:15:06Z
[ "python" ]
I have a string variable which represents a dos path e.g: `var = "d:\stuff\morestuff\furtherdown\THEFILE.txt"` I want to split this string into: `[ "d", "stuff", "morestuff", "furtherdown", "THEFILE.txt" ]` I have tried using `split()` and `replace()` but they either only process the first backslash or they insert ...
The problem here starts with how you're creating the string in the first place. ``` a = "d:\stuff\morestuff\furtherdown\THEFILE.txt" ``` Done this way, Python is trying to special case these: `\s`, `\m`, `\f`, and `\T`. In your case, `\f` is being treated as a formfeed (0x0C) while the other backslashes are handled c...
How to split a dos path into its components in Python
3,167,154
50
2010-07-02T15:41:56Z
3,167,684
74
2010-07-02T17:01:24Z
[ "python" ]
I have a string variable which represents a dos path e.g: `var = "d:\stuff\morestuff\furtherdown\THEFILE.txt"` I want to split this string into: `[ "d", "stuff", "morestuff", "furtherdown", "THEFILE.txt" ]` I have tried using `split()` and `replace()` but they either only process the first backslash or they insert ...
I've been bitten loads of times by people writing their own path fiddling functions and getting it wrong. Spaces, slashes, backslashes, colons -- the possibilities for confusion are not endless, but mistakes are easily made anyway. So I'm a stickler for the use of `os.path`, and recommend it on that basis. (However, t...
How to split a dos path into its components in Python
3,167,154
50
2010-07-02T15:41:56Z
14,334,768
52
2013-01-15T09:38:30Z
[ "python" ]
I have a string variable which represents a dos path e.g: `var = "d:\stuff\morestuff\furtherdown\THEFILE.txt"` I want to split this string into: `[ "d", "stuff", "morestuff", "furtherdown", "THEFILE.txt" ]` I have tried using `split()` and `replace()` but they either only process the first backslash or they insert ...
You can simply use the most Pythonic approach (IMHO): ``` import os your_path = r"d:\stuff\morestuff\furtherdown\THEFILE.txt" path_list = your_path.split(os.sep) print path_list ``` Which will give you: ``` ['d:', 'stuff', 'morestuff', 'furtherdown', 'THEFILE.txt'] ``` The clue here is to use `os.sep` instead of `...
How to split a dos path into its components in Python
3,167,154
50
2010-07-02T15:41:56Z
15,050,936
8
2013-02-24T10:43:00Z
[ "python" ]
I have a string variable which represents a dos path e.g: `var = "d:\stuff\morestuff\furtherdown\THEFILE.txt"` I want to split this string into: `[ "d", "stuff", "morestuff", "furtherdown", "THEFILE.txt" ]` I have tried using `split()` and `replace()` but they either only process the first backslash or they insert ...
For a somewhat more concise solution, consider the following: ``` def split_path(p): a,b = os.path.split(p) return (split_path(a) if len(a) and len(b) else []) + [b] ```
How to split a dos path into its components in Python
3,167,154
50
2010-07-02T15:41:56Z
16,595,356
45
2013-05-16T19:00:26Z
[ "python" ]
I have a string variable which represents a dos path e.g: `var = "d:\stuff\morestuff\furtherdown\THEFILE.txt"` I want to split this string into: `[ "d", "stuff", "morestuff", "furtherdown", "THEFILE.txt" ]` I have tried using `split()` and `replace()` but they either only process the first backslash or they insert ...
Thanks I would do ``` import os path = os.path.normpath(path) path.split(os.sep) ``` First normalize the path string into a proper string for the OS. Then os.sep must be safe to use as a delimiter in string function split.
How often does python flush to a file?
3,167,494
92
2010-07-02T16:30:41Z
3,167,526
9
2010-07-02T16:37:16Z
[ "python", "file", "flush" ]
1. How often does Python flush to a file? 2. How often does Python flush to stdout? I'm unsure about (1). As for (2), I believe Python flushes to stdout after every new line. But, if you overload stdout to be to a file, does it flush as often?
I don't know if this applies to python as well, but I think it depends on the operating system that you are running. On Linux for example, output to terminal flushes the buffer on a newline, whereas for output to files it only flushes when the buffer is full (by default). This is because it is more efficient to flush ...
How often does python flush to a file?
3,167,494
92
2010-07-02T16:30:41Z
3,168,436
141
2010-07-02T19:02:27Z
[ "python", "file", "flush" ]
1. How often does Python flush to a file? 2. How often does Python flush to stdout? I'm unsure about (1). As for (2), I believe Python flushes to stdout after every new line. But, if you overload stdout to be to a file, does it flush as often?
For file operations, Python uses the operating system's default buffering unless you configure it do otherwise. You can specify a buffer size, unbuffered, or line buffered. For example, the open function takes a buffer size argument. <http://docs.python.org/library/functions.html#open> "The optional buffering argume...
How often does python flush to a file?
3,167,494
92
2010-07-02T16:30:41Z
5,255,743
73
2011-03-10T05:13:15Z
[ "python", "file", "flush" ]
1. How often does Python flush to a file? 2. How often does Python flush to stdout? I'm unsure about (1). As for (2), I believe Python flushes to stdout after every new line. But, if you overload stdout to be to a file, does it flush as often?
You can also force flush the buffer to a file programmatically with the flush() method. ``` f = open('out.log', 'w+') f.write('output is ') # some work s = 'OK.' f.write(s) f.write('\n') f.flush() # some other work f.write('done\n') f.flush() f.close() ``` I have found this useful when tailing an output file with tai...
Change Django ModelChoiceField to show users' full names rather than usernames
3,167,824
23
2010-07-02T17:24:03Z
3,167,840
44
2010-07-02T17:27:49Z
[ "python", "django", "django-forms", "django-authentication" ]
I have a form in my Django app (not in admin) that allows staff members to select a user from a dropdown. ``` forms.ModelChoiceField(queryset = User.objects.filter(is_staff=False), required = False) ``` The problem is that the dropdown shows users by usernames whereas I'd rather it show their full name from user.get\...
You can setup a custom `ModelChoiceField` that will return whatever label you'd like. Place something like this within a fields.py or wherever applicable. ``` class UserModelChoiceField(ModelChoiceField): def label_from_instance(self, obj): return obj.get_full_name() ``` Then when creating your form, si...
Change Django ModelChoiceField to show users' full names rather than usernames
3,167,824
23
2010-07-02T17:24:03Z
15,841,236
12
2013-04-05T18:43:17Z
[ "python", "django", "django-forms", "django-authentication" ]
I have a form in my Django app (not in admin) that allows staff members to select a user from a dropdown. ``` forms.ModelChoiceField(queryset = User.objects.filter(is_staff=False), required = False) ``` The problem is that the dropdown shows users by usernames whereas I'd rather it show their full name from user.get\...
When working with a ModelForm, I found the following most useful so that I didn't have to redefine my queryset - in particular because I used limit\_choices\_to in the model definition: ``` class MyModelForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(MyModelForm, self).__init__(*args, **k...
Getting computer's UTC offset in Python
3,168,096
28
2010-07-02T18:09:00Z
3,168,139
17
2010-07-02T18:15:32Z
[ "python", "timezone", "utc" ]
In Python, how do you find what UTC time offset the computer is set to?
`gmtime()` will return the UTC time and `localtime()` will return the local time so subtracting the two should give you the utc offset.
Getting computer's UTC offset in Python
3,168,096
28
2010-07-02T18:09:00Z
3,168,394
45
2010-07-02T18:55:53Z
[ "python", "timezone", "utc" ]
In Python, how do you find what UTC time offset the computer is set to?
[time.timezone](http://docs.python.org/library/time.html#time.timezone): ``` import time print -time.timezone ``` It prints UTC offset in seconds (to take into account Daylight Saving Time (DST) see [time.altzone](http://docs.python.org/library/time.html#time.altzone): ``` is_dst = time.daylight and time.localtime(...
How can I open a website with urllib via proxy in Python?
3,168,171
11
2010-07-02T18:19:48Z
3,168,244
17
2010-07-02T18:30:54Z
[ "python", "proxy" ]
I have this program that check a website, and I want to know how can I check it via proxy in Python... this is the code, just for example ``` while True: try: h = urllib.urlopen(website) break except: print '['+time.strftime('%Y/%m/%d %H:%M:%S')+'] '+'ERROR. Trying again in a few secon...
By default, `urlopen` uses the environment variable `http_proxy` to determine which HTTP proxy to use: ``` $ export http_proxy='http://myproxy.example.com:1234' $ python myscript.py # Using http://myproxy.example.com:1234 as a proxy ``` If you instead want to specify a proxy inside your application, you can give a `...
inspect.getmembers in order?
3,169,014
12
2010-07-02T20:47:12Z
3,169,148
10
2010-07-02T21:16:27Z
[ "python", "python-2.6" ]
``` inspect.getmembers(object[, predicate]) ``` > Return all the members of an object in a list of (name, value) pairs sorted by name. I want to use this method, but I don't want the members to be sorted. I want them returned in the same order they were defined. Is there an alternative to this method? --- **Use cas...
You can dig around to find the line number for methods, not sure about other members: ``` import inspect class A: def one(self): pass def two(self): pass def three(self): pass def four(self): pass def linenumber_of_member(m): try: return m[1].im_func.fun...
PyQt4 global shortcuts?
3,169,233
6
2010-07-02T21:34:40Z
10,785,329
9
2012-05-28T13:18:06Z
[ "python", "pyqt", "pyqt4" ]
I have an application that opens multiple children widgets as separate windows, something like this: window1 opens window 2 which opens window 3 (simplified form). In the main window I have set CTRL+Q as the quit shortcut. Below is a stripped down example of the main class. ``` class MainWindow(QtGui.QMainWindow): ...
Here is what I have used in `__init__` function: `QtGui.QShortcut(QtGui.QKeySequence("Ctrl+Q"), self, self.close)` It works smoothly!
Dynamically add base class?
3,169,502
2
2010-07-02T22:37:59Z
3,235,491
7
2010-07-13T08:44:51Z
[ "python", "inheritance", "syntax", "python-2.6" ]
Let's say I have a base class defined as follows: ``` class Form(object): class Meta: model = None method = 'POST' ``` Now a developer comes a long and defines his subclass like: ``` class SubForm(Form): class Meta: model = 'User' ``` Now suddenly the `method` attribute is lost. How ...
As long as they won't override your `__init__`, or it will be called (ie by `super`), you can monkey-patch the `Meta` inner class: ``` class Form(object): class Meta: model = None method = "POST" def __init__(self, *args, **kwargs): if self.__class__ != Form: self.Meta.__ba...
Determining the minimum of a list of n elements
3,169,711
4
2010-07-02T23:42:33Z
3,169,733
7
2010-07-02T23:50:44Z
[ "python", "algorithm" ]
I'm having some trouble developing an algorithm to determine the minimum of a list of n elements. It's not the case of finding the minimum of an array of length n, that's simple: ``` min = A[0] for i in range(1, len(A)): if min > A[i]: min = A[i] print min ``` But my list contains objects: ``` class Object: ...
``` filtered = [obj for obj in lst if obj.classification == 'A' and obj.type = 'x'] min(filtered, key=lambda x: x.last - x.first) ``` Note: don't name your variable `list`: it shadows built-in.
Python Error Catching & FTP
3,169,725
4
2010-07-02T23:48:08Z
3,169,751
13
2010-07-02T23:57:18Z
[ "python", "ftp" ]
Trying to get a handle on the FTP library in Python. :) Got this so far. ``` from ftplib import FTP server = '127.0.0.1' port = '57422' print 'FTP Client (' + server + ') port: ' + port try: ftp = FTP() ftp.connect(server, port, 3) print 'Connected! Welcome msg is \"' + ftp.getwelcome() + '\"' ftp...
> I can't do ``` except: ftplib.all_errors ``` Of course not, that's simply bad syntax! But of course you can do it with proper syntax: ``` except ftblib.all_errors: ``` i.e., the colon *after* the tuple of exceptions. > How can I retrieve more specific > information on the error? Perhaps the > error code? ``` ex...
Printing HTML in Python CGI
3,169,781
2
2010-07-03T00:12:51Z
3,169,803
9
2010-07-03T00:21:22Z
[ "python", "html", "cgi", "printing" ]
I've been teaching myself python and cgi scripting, and I know that your basic script looks like ``` #!/usr/local/bin/python import cgi print "Content-type: text/html" print print "<HTML>" print "<BODY>" print "HELLO WORLD!" print "</BODY>" print "</HTML>" ``` My question is, if I have a big HTML file I want to dis...
If that big html file is called (for example) `'foo.html'` and lives in the current directory for your CGI script, then all you need as your script's body is: ``` print "Content-type: text/html" print with open('foo.html') as f: print f.read() ``` If you're stuck with Python 2.5, add `from __future__ import with_st...
Printing HTML in Python CGI
3,169,781
2
2010-07-03T00:12:51Z
3,169,817
7
2010-07-03T00:28:49Z
[ "python", "html", "cgi", "printing" ]
I've been teaching myself python and cgi scripting, and I know that your basic script looks like ``` #!/usr/local/bin/python import cgi print "Content-type: text/html" print print "<HTML>" print "<BODY>" print "HELLO WORLD!" print "</BODY>" print "</HTML>" ``` My question is, if I have a big HTML file I want to dis...
Python supports multiline strings, so you can print out your text in one big blurb. ``` print '''<html> <head><title>My first Python CGI app</title></head> <body> <p>Hello, 'world'!</p> </body> </html>''' ``` They support all string operations, including methods (`.upper()`, `.translate()`, etc.) and formatting (`%`)...
Generating Combinations in python
3,169,825
6
2010-07-03T00:34:25Z
3,169,853
17
2010-07-03T00:48:11Z
[ "python", "arrays", "multidimensional-array", "combinations", "matrix" ]
I am not sure how to go about this in Python, if its even possible. What I need to do is create an array (or a matrix, or vector?) from 3 separate arrays. Each array as 4 elements as such, they return this: Class1 = [1,2,3,4] Class2 = [1,2,3,4] Class3 = [1,2,3,4] Now what I would like to do is return all possible com...
What you want is called a [Cartesian product](http://docs.python.org/library/itertools.html#itertools.product): ``` import itertools iterables = [ [1,2,3,4], [88,99], ['a','b'] ] for t in itertools.product(*iterables): print t ```
Test if lists share any items in python
3,170,055
32
2010-07-03T02:15:15Z
3,170,067
23
2010-07-03T02:21:39Z
[ "list", "python", "intersection" ]
I want to check if *any* of the items in one list are present in another list. I can do it simply with the code below, but I suspect there might be a library function to do this. If not, is there a more pythonic method of achieving the same result. ``` In [78]: a = [1, 2, 3, 4, 5] In [79]: b = [8, 7, 6] In [80]: c =...
``` def lists_overlap3(a, b): return bool(set(a) & set(b)) ``` Note: the above assumes that you want a boolean as the answer. If all you need is an expression to use in an `if` statement, just use `if set(a) & set(b):`
Test if lists share any items in python
3,170,055
32
2010-07-03T02:15:15Z
3,170,109
10
2010-07-03T02:40:59Z
[ "list", "python", "intersection" ]
I want to check if *any* of the items in one list are present in another list. I can do it simply with the code below, but I suspect there might be a library function to do this. If not, is there a more pythonic method of achieving the same result. ``` In [78]: a = [1, 2, 3, 4, 5] In [79]: b = [8, 7, 6] In [80]: c =...
``` def lists_overlap(a, b): sb = set(b) return any(el in sb for el in a) ``` This is asymptotically optimal (worst case O(n + m)), and might be better than the intersection approach due to `any`'s short-circuiting. E.g.: ``` lists_overlap([3,4,5], [1,2,3]) ``` will return True as soon as it gets to `3 in sb` ...
Test if lists share any items in python
3,170,055
32
2010-07-03T02:15:15Z
17,735,466
57
2013-07-18T23:06:05Z
[ "list", "python", "intersection" ]
I want to check if *any* of the items in one list are present in another list. I can do it simply with the code below, but I suspect there might be a library function to do this. If not, is there a more pythonic method of achieving the same result. ``` In [78]: a = [1, 2, 3, 4, 5] In [79]: b = [8, 7, 6] In [80]: c =...
**Short answer**: use `set(a).isdisjoint(b)`, it's generally the fastest. There are four common ways to test if two lists `a` and `b` share any items. The first option is to convert both to sets and check their intersection, as such: ``` bool(set(a) & set(b)) ``` Because **sets are stored using a hash table in Pytho...
Why declare unicode by string in python?
3,170,211
76
2010-07-03T03:28:14Z
3,170,216
10
2010-07-03T03:31:45Z
[ "python", "encoding", "utf-8" ]
I'm still learning python and I have a doubt: In python 2.6.x I usually declare encoding in the file header like this (as in [PEP 0263](http://www.python.org/dev/peps/pep-0263/)) ``` # -*- coding: utf-8 -*- ``` After that, my strings are written as usual: ``` a = "A normal string without declared Unicode" ``` But ...
That doesn't set the format of the string; it sets the format of the file. Even with that header, `"hello"` is a byte string, not a Unicode string. To make it Unicode, you're going to have to use `u"hello"` everywhere. The header is just a hint of what format to use when reading the `.py` file.
Why declare unicode by string in python?
3,170,211
76
2010-07-03T03:28:14Z
3,170,331
116
2010-07-03T04:34:17Z
[ "python", "encoding", "utf-8" ]
I'm still learning python and I have a doubt: In python 2.6.x I usually declare encoding in the file header like this (as in [PEP 0263](http://www.python.org/dev/peps/pep-0263/)) ``` # -*- coding: utf-8 -*- ``` After that, my strings are written as usual: ``` a = "A normal string without declared Unicode" ``` But ...
Those are two different things, as others have mentioned. **When you specify `# -*- coding: utf-8 -*-`**, you're telling Python the source file you've saved is `utf-8`. The default for Python 2 is ASCII (for Python 3 it's `utf-8`). This just affects how the interpreter reads the characters in the file. In general, it...
Why declare unicode by string in python?
3,170,211
76
2010-07-03T03:28:14Z
3,170,647
16
2010-07-03T07:11:24Z
[ "python", "encoding", "utf-8" ]
I'm still learning python and I have a doubt: In python 2.6.x I usually declare encoding in the file header like this (as in [PEP 0263](http://www.python.org/dev/peps/pep-0263/)) ``` # -*- coding: utf-8 -*- ``` After that, my strings are written as usual: ``` a = "A normal string without declared Unicode" ``` But ...
As others have said, `# coding:` specifies the encoding the source file is saved in. Here are some examples to illustrate this: **A file saved on disk as cp437 (my console encoding), but no encoding declared** ``` b = 'über' u = u'über' print b,repr(b) print u,repr(u) ``` **Output:** ``` File "C:\ex.py", line 1...
Splitting a hex string into a list in Python - How?
3,170,718
2
2010-07-03T07:43:41Z
3,170,728
10
2010-07-03T07:48:24Z
[ "python", "string" ]
If I have this string: ``` hexstring = '001122334455' ``` How can I split that into a list so the result is: hexlist = ['00', '11', '22', '33', '44', '55'] I can't think of a nice, pythonic way to do this :/
``` >>> [hexstring[i:i+2] for i in range(0,len(hexstring), 2)] ['00', '11', '22', '33', '44', '55'] ```
Splitting a hex string into a list in Python - How?
3,170,718
2
2010-07-03T07:43:41Z
3,170,743
7
2010-07-03T07:54:42Z
[ "python", "string" ]
If I have this string: ``` hexstring = '001122334455' ``` How can I split that into a list so the result is: hexlist = ['00', '11', '22', '33', '44', '55'] I can't think of a nice, pythonic way to do this :/
Alternatively: ``` >>> hexstring = "01234567" >>> it=iter(hexstring); [a+b for a,b in zip(it, it)] ['01', '23', '45', '67'] ``` Use [`itertools.izip`](http://docs.python.org/library/itertools.html#itertools.izip) instead of `zip` if you're targeting Python 2.x. This method is a specific version of `grouper` in the i...
Use of a deprecated module 'string'
3,170,839
15
2010-07-03T08:29:36Z
3,170,856
17
2010-07-03T08:36:06Z
[ "python", "string" ]
I just ran `pylint` on my code and it shows up this message: `Uses of a deprecated module 'string'` I am using the module `string` for join / split mainly. ``` >>> names = ['Pulp', 'Fiction'] >>> import string >>> fullname = string.join(names) >>> print fullname Pulp Fiction ``` Above is an example. In my code I ha...
Equivalent to your code would be: ``` ' '.join(names) ``` `string` is not deprecated, deprecated are certain functions that were duplicates of `str` methods. For `split` you could also use: ``` >>> 'Pulp Fiction'.split() ['Pulp', 'Fiction'] ``` In docs there is a [full list of deprecated functions with suggested re...
Python: how do you remember the order of `super`'s arguments?
3,171,824
7
2010-07-03T14:40:02Z
3,171,850
11
2010-07-03T14:49:09Z
[ "python", "super" ]
As the title says, how do you remember the order of `super`'s arguments? Is there a mnemonic somewhere I've missed? After years of Python programming, I still have to look it up :( (for the record, it's `super(Type, self)`)
Inheritance makes me think of a classification **hierarchy**. And the order of the arguments to `super` is hierarchical: first the class, then the instance. Another idea, inspired by the answer from ~unutbu: ``` class Fubb(object): def __init__(self, *args, **kw): # Crap, I can't remember how super() goes...
Python: how do you remember the order of `super`'s arguments?
3,171,824
7
2010-07-03T14:40:02Z
3,171,872
10
2010-07-03T14:59:26Z
[ "python", "super" ]
As the title says, how do you remember the order of `super`'s arguments? Is there a mnemonic somewhere I've missed? After years of Python programming, I still have to look it up :( (for the record, it's `super(Type, self)`)
Simply remember that the `self` is *optional* - `super(Type)` gives access to unbound superclass methods - and optional arguments always come last.
Most Efficient way to calculate Frequency of values in a Python list?
3,172,173
16
2010-07-03T17:04:35Z
3,172,198
29
2010-07-03T17:12:41Z
[ "python", "list", "frequency" ]
I am looking for a fast and efficient way to calculate the frequency of `list` items in python: ``` list = ['a','b','a','b', ......] ``` I want a frequency counter which would give me an output like this: ``` [ ('a', 10),('b', 8) ...] ``` The items should be arranged in descending order of frequency as shown above...
Python2.7+ ``` >>> from collections import Counter >>> L=['a','b','a','b'] >>> print(Counter(L)) Counter({'a': 2, 'b': 2}) >>> print(Counter(L).items()) dict_items([('a', 2), ('b', 2)]) ``` python2.5/2.6 ``` >>> from collections import defaultdict >>> L=['a','b','a','b'] >>> d=defaultdict(int) >>> for item in L: >>>...
Actual meaning of 'shell=True' in subprocess
3,172,470
85
2010-07-03T18:39:55Z
3,172,488
68
2010-07-03T18:46:48Z
[ "python", "subprocess" ]
I am calling different processes with the `subprocess` module. However, I have a question. In the following codes: ``` callProcess = subprocess.Popen(['ls', '-l'], shell=True) ``` and ``` callProcess = subprocess.Popen(['ls', '-l']) # without shell ``` Both work. After reading the docs, I came to know that `shell=...
The benefit of not calling via the shell is that you are not invoking a 'mystery program.' On POSIX, the environment variable `SHELL` controls which binary is invoked as the "shell." On Windows, there is no bourne shell descendent, only cmd.exe. So invoking the shell invokes a program of the user's choosing and is pla...
Actual meaning of 'shell=True' in subprocess
3,172,470
85
2010-07-03T18:39:55Z
3,172,690
23
2010-07-03T19:50:19Z
[ "python", "subprocess" ]
I am calling different processes with the `subprocess` module. However, I have a question. In the following codes: ``` callProcess = subprocess.Popen(['ls', '-l'], shell=True) ``` and ``` callProcess = subprocess.Popen(['ls', '-l']) # without shell ``` Both work. After reading the docs, I came to know that `shell=...
Executing programs through the shell means that all user input passed to the program is interpreted according to the syntax and semantic rules of the invoked shell. At best, this only causes inconvenience to the user, because the user has to obey these rules. For instance, paths containing special shell characters like...
Actual meaning of 'shell=True' in subprocess
3,172,470
85
2010-07-03T18:39:55Z
29,023,432
13
2015-03-13T01:36:25Z
[ "python", "subprocess" ]
I am calling different processes with the `subprocess` module. However, I have a question. In the following codes: ``` callProcess = subprocess.Popen(['ls', '-l'], shell=True) ``` and ``` callProcess = subprocess.Popen(['ls', '-l']) # without shell ``` Both work. After reading the docs, I came to know that `shell=...
An example where things could go wrong with Shell=True is shown here ``` >>> from subprocess import call >>> filename = input("What file would you like to display?\n") What file would you like to display? non_existent; rm -rf / # THIS WILL DELETE EVERYTHING IN ROOT PARTITION!!! >>> call("cat " + filename, shell=True) ...
numpy convert categorical string arrays to an integer array
3,172,509
9
2010-07-03T18:53:54Z
3,217,929
14
2010-07-10T05:12:10Z
[ "python", "statistics", "numpy", "machine-learning" ]
I'm trying to convert a string array of categorical variables to an integer array of categorical variables. Ex. ``` import numpy as np a = np.array( ['a', 'b', 'c', 'a', 'b', 'c']) print a.dtype >>> |S1 b = np.unique(a) print b >>> ['a' 'b' 'c'] c = a.desired_function(b) print c, c.dtype >>> [1,2,3,1,2,3] int32 ``...
One way is to use the [`categorical`](http://statsmodels.sourceforge.net/stable/generated/statsmodels.tools.tools.categorical.html) function from [scikits.statsmodels](http://scikits.appspot.com/statsmodels). For example: ``` In [60]: from scikits.statsmodels.tools import categorical In [61]: a = np.array( ['a', 'b',...
numpy convert categorical string arrays to an integer array
3,172,509
9
2010-07-03T18:53:54Z
3,250,172
15
2010-07-14T20:24:54Z
[ "python", "statistics", "numpy", "machine-learning" ]
I'm trying to convert a string array of categorical variables to an integer array of categorical variables. Ex. ``` import numpy as np a = np.array( ['a', 'b', 'c', 'a', 'b', 'c']) print a.dtype >>> |S1 b = np.unique(a) print b >>> ['a' 'b' 'c'] c = a.desired_function(b) print c, c.dtype >>> [1,2,3,1,2,3] int32 ``...
np.unique has some optional returns return\_inverse gives the integer encoding, which I use very often ``` >>> b, c = np.unique(a, return_inverse=True) >>> b array(['a', 'b', 'c'], dtype='|S1') >>> c array([0, 1, 2, 0, 1, 2]) >>> c+1 array([1, 2, 3, 1, 2, 3]) ``` it can be used to recreate the original array ...