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
Define a Custom Form for use in Django's ModelAdmin Add View
4,682,665
3
2011-01-13T16:47:05Z
4,682,776
7
2011-01-13T16:55:49Z
[ "python", "django", "django-admin" ]
I'm trying to expose a Django model in admin using the ModelAdmin class. ModelAdmin seems to assume you use the same form for add and change. I'd like the add\_view to use a simplified form that only lists a handful of required fields. After submission, it'll redirect to the change\_view and use ModelForm's default for...
`get_form()` is passed an `obj` parameter when called during `change_view`. Simply detect that return the new form/tweak parameters as needed. For example: ``` class MyModelAdmin(admin.ModelAdmin): def get_form(self, request, obj=None, **kwargs): # hide every other field apart from url # if we are...
Fixing '../../' paths in python
4,684,520
7
2011-01-13T19:48:11Z
4,684,549
11
2011-01-13T19:50:51Z
[ "python" ]
Is there an easy way in Python to resolve path operators like `..`? For instance is there a function call that will convert: `/../../test/../path` to `/path`?
You can use [`os.path.realpath()`](http://docs.python.org/library/os.path.html#os.path.realpath) to get the canonical path. To get a normalised relative path, use [`os.path.normpath()`](http://docs.python.org/library/os.path.html#os.path.normpath).
Parse raw HTTP Headers
4,685,217
18
2011-01-13T21:02:40Z
4,685,559
7
2011-01-13T21:37:04Z
[ "python", "http-headers" ]
I have a string of raw HTTP and I would like to represent the fields in an object. Is there any way to parse the individual headers from an HTTP string? ``` 'GET /search?sourceid=chrome&ie=UTF-8&q=ergterst HTTP/1.1\r\nHost: www.google.com\r\nConnection: keep-alive\r\nAccept: application/xml,application/xhtml+xml,text/...
This seems to work fine if you strip the `GET` line: ``` import mimetools from StringIO import StringIO he = "Host: www.google.com\r\nConnection: keep-alive\r\nAccept: application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5\r\nUser-Agent: Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10...
Parse raw HTTP Headers
4,685,217
18
2011-01-13T21:02:40Z
5,955,949
58
2011-05-10T20:18:35Z
[ "python", "http-headers" ]
I have a string of raw HTTP and I would like to represent the fields in an object. Is there any way to parse the individual headers from an HTTP string? ``` 'GET /search?sourceid=chrome&ie=UTF-8&q=ergterst HTTP/1.1\r\nHost: www.google.com\r\nConnection: keep-alive\r\nAccept: application/xml,application/xhtml+xml,text/...
There are excellent tools in the Standard Library both for parsing RFC 821 headers, and also for parsing entire HTTP requests. Here is an example request string (note that Python treats it as one big string, even though we are breaking it across several lines for readability) that we can feed to my examples: ``` requ...
smarter "reverse" of a dictionary in python (acc for some of values being the same)?
4,685,320
5
2011-01-13T21:12:32Z
4,685,402
8
2011-01-13T21:20:33Z
[ "python", "dictionary" ]
``` def revert_dict(d): rd = {} for key in d: val = d[key] if val in rd: rd[val].append(key) else: rd[val] = [key] return rd >>> revert_dict({'srvc3': '1', 'srvc2': '1', 'srvc1': '2'}) {'1': ['srvc3', 'srvc2'], '2': ['srvc1']} ``` This obviously isn't simpl...
That looks pretty good. You could simplify it a little bit by using [`defaultdict`](http://docs.python.org/library/collections.html#collections.defaultdict): ``` import collections def revert_dict(d): rd = collections.defaultdict(list) for key, value in d.iteritems(): rd[value].append(key) retur...
python - add cookie to cookiejar
4,685,337
10
2011-01-13T21:14:03Z
12,682,437
9
2012-10-01T23:17:55Z
[ "python", "cookies" ]
How do I create a cookie and add it to a CookieJar instance in python? I have all the info for the cookie (name, value, domain, path, etc) and I don't want to extract a new cookie with a http request. I tried this but it looks like SimpleCookie class is not compatible with CookieJar (is there another Cookie class?) `...
Looking at cookielib, you get: ``` from cookielib import Cookie, CookieJar cj = CookieJar() # Cookie(version, name, value, port, port_specified, domain, # domain_specified, domain_initial_dot, path, path_specified, # secure, discard, comment, comment_url, rest) c = Cookie(None, 'asdf', None, '80', '80', 'www.foo.bar...
Importing file with unknown encoding from Python into MongoDB
4,685,568
6
2011-01-13T21:38:04Z
4,685,857
7
2011-01-13T22:05:29Z
[ "python", "character-encoding", "mongodb" ]
Working on importing a tab-delimited file over HTTP in Python. Before inserting a row's data into MongoDB, I'm removing slashes, ticks and quotes from the string. Whatever the encoding of the data is, MongoDB is throwing me the exception: ``` bson.errors.InvalidStringData: strings in documents must be valid UTF-8 ``...
Try these in order: (0) Check that your removal of the slashes/ticks/etc is not butchering the data. What's a tick? Please show your code. Please show a sample of the raw data ... use `print repr(sample_raw data)` and copy/paste the output into an edit of your question. (1) There's an old maxim: "If the encoding of a...
Generic reverse of list items in Python
4,685,571
4
2011-01-13T21:38:16Z
4,685,588
8
2011-01-13T21:39:57Z
[ "python", "sequences" ]
``` >>> b=[('spam',0), ('eggs',1)] >>> [reversed(x) for x in b] [<reversed object at 0x7fbf07de7090>, <reversed object at 0x7fbf07de70d0>] ``` Bummer. I expected to get a list of reversed tuples! Sure I can do: ``` >>> [tuple(reversed(x)) for x in b] [(0, 'spam'), (1, 'eggs')] ``` But I hoped for something generic?...
[Extended slicing](http://docs.python.org/release/2.3/whatsnew/section-slices.html). ``` [x[::-1] for x in b] ```
Equivalent of a python generator in C++ for buffered reads
4,685,862
3
2011-01-13T22:06:14Z
4,686,030
7
2011-01-13T22:24:34Z
[ "c++", "python", "algorithm", "file", "io" ]
Guido Van Rossum demonstrates the simplicity of Python in this [article](http://neopythonic.blogspot.com/2008/10/sorting-million-32-bit-integers-in-2mb.html) and makes use of this function for buffered reads of a file of unknown length: ``` def intsfromfile(f): while True: a = array.array('i') a.fr...
In order to disguise an `ifstream` (or really, any input stream) in a form that acts like an iterator, you want to use the `istream_iterator` or the `istreambuf_iterator` template class. The former is useful for files where the formatting is of concern. For example, a file full of whitespace-delimited integers can be r...
Python: Why can't I use `super` on a class?
4,686,241
7
2011-01-13T22:49:09Z
4,686,279
8
2011-01-13T22:53:22Z
[ "python", "class", "python-3.x", "super" ]
Why can't I use `super` to get a method of a class's superclass? Example: ``` Python 3.1.3 >>> class A(object): ... def my_method(self): pass >>> class B(A): ... def my_method(self): pass >>> super(B).my_method Traceback (most recent call last): File "<pyshell#2>", line 1, in <module> super(B).my_method...
It looks as though you need an instance of B to pass in as the second argument. <http://www.artima.com/weblogs/viewpost.jsp?thread=236275>
Python: Why can't I use `super` on a class?
4,686,241
7
2011-01-13T22:49:09Z
4,686,400
7
2011-01-13T23:11:51Z
[ "python", "class", "python-3.x", "super" ]
Why can't I use `super` to get a method of a class's superclass? Example: ``` Python 3.1.3 >>> class A(object): ... def my_method(self): pass >>> class B(A): ... def my_method(self): pass >>> super(B).my_method Traceback (most recent call last): File "<pyshell#2>", line 1, in <module> super(B).my_method...
According to [this](http://www.artima.com/weblogs/viewpost.jsp?thread=236278) it seems like I just need to call `super(B, B).my_method`: ``` >>> super(B, B).my_method <function my_method at 0x00D51738> >>> super(B, B).my_method is A.my_method True ```
Load python module not from a file
4,686,893
3
2011-01-14T00:28:51Z
4,686,955
7
2011-01-14T00:39:39Z
[ "python", "unit-testing", "module", "import" ]
I've got some python code in a library that attempts to load a simple value from a module that will exist for the applications that use this library ``` from somemodule import simplevalue ``` Normally, the application that uses the library will have the module file and everything works fine. However, in the unit test...
It is. Use `types.ModuleType` to create a new module object, then add it to `sys.modules`: ``` sys.modules["somename"] = types.ModuleType("somename") ``` You can then do `import somename`. If you need to add classes or functions to it, import it before calling your test script, and just add functions to it: ``` def ...
How to insert item into c_char_p array
4,687,170
5
2011-01-14T01:26:48Z
4,687,435
11
2011-01-14T02:29:12Z
[ "python", "ctypes" ]
I want to pass **an array of char pointer** to a C function. I refer to <http://docs.python.org/library/ctypes.html#arrays> I write the following code. ``` from ctypes import * names = c_char_p * 4 # A 3 times for loop will be written here. # The last array will assign to a null pointer. # So that C function knows ...
What you did was to create an array *type*, not an actual array, so basically: ``` import ctypes array_type = ctypes.c_char_p * 4 names = array_type() ``` You can then do something along the lines of: ``` names[0] = "foo" names[1] = "bar" ``` ...and proceed to call your C function with the `names` array as paramete...
Django: DatabaseError column does not exist
4,687,275
6
2011-01-14T01:46:37Z
4,703,754
9
2011-01-16T04:12:55Z
[ "python", "database", "django", "models" ]
I'm having a problem with Django 1.2.4. Here is a model: ``` class Foo(models.Model): # ... ftw = models.CharField(blank=True) bar = models.ForeignKey(Bar, blank=True) ``` Right after flushing the database, I use the shell: ``` Python 2.6.6 (r266:84292, Sep 15 2010, 15:52:39) [GCC 4.4.5] on linux2 Type...
Try completely dropping/wiping the database before running syncdb. I remember needing to do that a while back when I had made changes to foreign key fields.
Assigning values to variables in a list using a loop
4,687,364
7
2011-01-14T02:12:07Z
4,687,672
7
2011-01-14T03:20:12Z
[ "python", "list", "variables", "loops" ]
``` var_list = [one, two, three] num = 1 for var in var_list: var = num num += 1 ``` The above gives me an error that 'one' doesn't exist. Can you not assign in this way? I want to assign an incrementing number for each var in the list.
You can access the dictionary of global variables with the `globals()` built-in function. The dictionary uses strings for keys, which means, you can create variables with names given as strings at run-time, like this: ``` >>> var_names = ["one", "two", "three"] >>> count = 1 >>> for name in var_names: ... globals()[n...
Using an iterator to print integers
4,687,657
3
2011-01-14T03:17:55Z
4,687,702
7
2011-01-14T03:24:41Z
[ "python", "list", "printing", "iterator" ]
What I want to do is print the integers 0 through 5 in the code below but all I get is an address of the iterator? ``` def main(): l = [] for i in range(0,5): l.append(i) it = iter(l) for i in range(0,5): print it it.next() if __name__ == '__main__': main() ```
To access the values returned by an iterator, you use the [next()](http://docs.python.org/library/functions.html#next) method of the iterator like so: ``` try: while True: val = it.next() print(val) except StopIteration: print("Iteration done.") ``` next() has both the purpose of advancing the...
find time shift between two similar waveforms
4,688,715
9
2011-01-14T07:06:25Z
4,688,875
7
2011-01-14T07:34:20Z
[ "python", "numpy", "signal-processing", "correlation" ]
I have to compare two time-vs-voltage waveforms. Because of the peculiarity of the sources of these waveforms, one of them can be a time shifted version of the other. How can i find whether there is a time shift? and if yes, how much is it. I am doing this in Python and wish to use numpy/scipy libraries.
If one is time-shifted by the other, you will see a peak in the correlation. Since calculating the correlation is expensive, it is better to use FFT. So, something like this should work: ``` af = scipy.fft(a) bf = scipy.fft(b) c = scipy.ifft(af * scipy.conj(bf)) time_shift = argmax(abs(c)) ```
find time shift between two similar waveforms
4,688,715
9
2011-01-14T07:06:25Z
4,690,225
18
2011-01-14T10:47:53Z
[ "python", "numpy", "signal-processing", "correlation" ]
I have to compare two time-vs-voltage waveforms. Because of the peculiarity of the sources of these waveforms, one of them can be a time shifted version of the other. How can i find whether there is a time shift? and if yes, how much is it. I am doing this in Python and wish to use numpy/scipy libraries.
scipy provides a correlation function which will work fine for small input and also if you want non-circular correlation meaning that the signal will not wrap around. note that in `mode='full'` , the size of the array returned by signal.correlation is the sum of the input signal sizes - 1, so the value from `argmax` is...
Stack data structure in python
4,688,859
14
2011-01-14T07:32:00Z
4,688,885
24
2011-01-14T07:35:39Z
[ "python" ]
I have 2 issues with the code below: 1. push(o) throws an exception *TypeError: can only assign an iterable*. 2. Should I throw an exception if pop() is invoked on an empty stack ? ``` class Stack(object): def __init__(self): self.storage = [] def isEmpty(self): return len(...
No need to jump through these loops, See [5.1.1 Using Lists as Stacks](https://docs.python.org/3/tutorial/datastructures.html#using-lists-as-stacks) If you insist on having methods `isEmpty()` and `push()` you can do: ``` class stack(list): def push(self, item): self.append(item) def isEmpty(self): ...
Stack data structure in python
4,688,859
14
2011-01-14T07:32:00Z
4,690,033
10
2011-01-14T10:21:30Z
[ "python" ]
I have 2 issues with the code below: 1. push(o) throws an exception *TypeError: can only assign an iterable*. 2. Should I throw an exception if pop() is invoked on an empty stack ? ``` class Stack(object): def __init__(self): self.storage = [] def isEmpty(self): return len(...
You are right to use composition instead of inheritance, because inheritance brings methods in that you don't want to expose. ``` class Stack: def __init__(self): self.__storage = [] def isEmpty(self): return len(self.__storage) == 0 def push(self,p): self.__storage.append(p) def pop(self): ...
What to reference in the shebang python26 or python2.6
4,689,233
2
2011-01-14T08:34:32Z
4,689,297
8
2011-01-14T08:42:52Z
[ "python", "shebang" ]
For a Python script I need a specific Python version. Now my installation of Python 2.6 contains both python26 and python2.6 Which one should I put in the shebang? Option 1: ``` #!/usr/bin/env python2.6 ``` Option 2: ``` #!/usr/bin/env python26 ``` **EDIT**: Yes, there is a reason not to use plain python. In some...
You can't always guarantee that the shebang will be used (or even that the user will have that version). You shouldn't really limit to a specific version exactly. It's best to require *at least* a given version (if your code works on Python 2.6, why wouldn't it work on Python 2.7? I might not have Python 2.6 installed...
python multiple imports for a common module
4,689,252
6
2011-01-14T08:37:14Z
4,689,273
17
2011-01-14T08:39:40Z
[ "python" ]
I am working on a project wherein I need to use a third party module in different project files(.py files). The situation is like this. I have a file "abc.py" which imports third party module "common.py". There are couple of other files which also import "common.py". All these files are also imported in main project f...
Importing only ever *loads* a module once. Any imports after that simply add it to the current namespace. Just import things in the files you need them to be available and let Python to the heavy lifting of figuring out loading the modules.
Implementing a callback in Python - passing a callable reference to the current function
4,689,984
20
2011-01-14T10:15:20Z
4,690,014
36
2011-01-14T10:18:49Z
[ "python", "design-patterns", "functional-programming", "callback", "observer-pattern" ]
I want to implement the `Observable` pattern in Python for a couple of workers, and came across this helpful snippet: ``` class Event(object): pass class Observable(object): def __init__(self): self.callbacks = [] def subscribe(self, callback): self.callbacks.append(callback) def fire(...
Any defined function can be passed by simply using its name, without adding the `()` on the end that you would use to invoke it: ``` def my_callback_func(event): # do stuff o = Observable() o.subscribe(my_callback_func) ``` --- Other example usages: ``` class CallbackHandler(object): @staticmethod def ...
Sorting dictionary keys based on their values
4,690,094
10
2011-01-14T10:29:23Z
4,690,134
9
2011-01-14T10:35:19Z
[ "python", "sorting" ]
I have a python dictionary setup like so ``` mydict = { 'a1': ['g',6], 'a2': ['e',2], 'a3': ['h',3], 'a4': ['s',2], 'a5': ['j',9], 'a6': ['y',7] } ``` I need to write a function which returns the ordered keys in a list, depending on which column your sorting on s...
``` >>> L = sorted(d.items(), key=lambda (k, v): v[1]) >>> L [('a2', ['e', 2]), ('a4', ['s', 2]), ('a3', ['h', 3]), ('a1', ['g', 6]), ('a6', ['y', 7]), ('a5', ['j', 9])] >>> map(lambda (k,v): k, L) ['a2', 'a4', 'a3', 'a1', 'a6', 'a5'] ``` Here you sort the dictionary items (key-value pairs) using a *key* - callable w...
Sorting dictionary keys based on their values
4,690,094
10
2011-01-14T10:29:23Z
4,690,265
27
2011-01-14T10:55:13Z
[ "python", "sorting" ]
I have a python dictionary setup like so ``` mydict = { 'a1': ['g',6], 'a2': ['e',2], 'a3': ['h',3], 'a4': ['s',2], 'a5': ['j',9], 'a6': ['y',7] } ``` I need to write a function which returns the ordered keys in a list, depending on which column your sorting on s...
Wouldn't it be much easier to use ``` sorted(d, key=lambda k: d[k][1]) ``` (with `d` being the dictionary)?
Sorting dictionary using operator.itemgetter
4,690,416
16
2011-01-14T11:11:24Z
4,690,469
29
2011-01-14T11:18:24Z
[ "python", "sorting", "dictionary" ]
[A question was asked here on SO](http://stackoverflow.com/questions/4690094/sorting-dictionary-keys-based-on-their-values), a few minutes ago, on sorting dictionary keys based on their values. I just read about the `operator.itemgetter` method of sorting a few days back and decided to try that, but it doesn't seem to...
``` In [6]: sorted(mydict.iteritems(), key=lambda (k,v): operator.itemgetter(1)(v)) Out[6]: [('a2', ['e', 2]), ('a4', ['s', 2]), ('a3', ['h', 3]), ('a1', ['g', 6]), ('a6', ['y', 7]), ('a5', ['j', 9])] ``` The key parameter is always a function that is fed one item from the iterable (`mydict.iteritems()`) at a ti...
Get formula from Excel cell with python xlrd
4,690,423
19
2011-01-14T11:12:04Z
4,695,498
16
2011-01-14T20:16:46Z
[ "python", "excel", "formula", "xls", "xlrd" ]
I have to **port an algorithm from an Excel sheet to python code** but I have to **reverse engineer the algorithm from the Excel file**. The Excel sheet is quite complicated, it contains many cells in which there are formulas that refer to other cells (that can also contains a formula or a constant). My idea is to an...
[Dis]claimer: I'm the author/maintainer of `xlrd`. The documentation references to formula text are about "name" formulas; read the section "Named references, constants, formulas, and macros" near the start of the docs. These formulas are associated sheet-wide or book-wide to a name; they are not associated with indiv...
Get formula from Excel cell with python xlrd
4,690,423
19
2011-01-14T11:12:04Z
6,518,681
10
2011-06-29T09:48:11Z
[ "python", "excel", "formula", "xls", "xlrd" ]
I have to **port an algorithm from an Excel sheet to python code** but I have to **reverse engineer the algorithm from the Excel file**. The Excel sheet is quite complicated, it contains many cells in which there are formulas that refer to other cells (that can also contains a formula or a constant). My idea is to an...
**Update**: I have gone and implemented a little library to do exactly what you describe: extracting the cells & dependencies from an Excel spreadsheet and converting them to python code. Code [is on github](https://github.com/dgorissen/pycel), patches welcome :) --- Just to add that you can always interact with exce...
Is there a matplotlib flowable for ReportLab?
4,690,585
11
2011-01-14T11:32:00Z
13,870,512
18
2012-12-13T23:41:45Z
[ "python", "matplotlib", "reportlab" ]
I want to embed matplotlib charts into PDFs generated by ReportLab directly - i.e. not saving as a PNG first and then embedding the PNG into the PDF (i think I'll get better quality output). Does anyone know if there's a matplotlib flowable for ReportLab? Thanks
Here's a solution using pdfrw: ``` #!/usr/bin/env python # encoding: utf-8 """matplotlib_example.py An simple example of how to insert matplotlib generated figures into a ReportLab platypus document. """ import matplotlib matplotlib.use('PDF') import matplotlib.pyplot as plt import cStringIO from pdfrw import ...
python exception message capturing
4,690,600
75
2011-01-14T11:33:50Z
4,690,655
110
2011-01-14T11:40:46Z
[ "python", "exception", "logging", "except" ]
``` import ftplib import urllib2 import os import logging logger = logging.getLogger('ftpuploader') hdlr = logging.FileHandler('ftplog.log') formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s') hdlr.setFormatter(formatter) logger.addHandler(hdlr) logger.setLevel(logging.INFO) FTPADDR = "some ftp addre...
You have to define which type of exception you want to catch. So write `except Exception, e:` instead of `except, e:` for a general exception (that will be logged anyway). Other possibility is to write your whole try/except code this way: ``` try: with open(filepath,'rb') as f: con.storbinary('STOR '+ fil...
python exception message capturing
4,690,600
75
2011-01-14T11:33:50Z
14,529,489
76
2013-01-25T20:02:31Z
[ "python", "exception", "logging", "except" ]
``` import ftplib import urllib2 import os import logging logger = logging.getLogger('ftpuploader') hdlr = logging.FileHandler('ftplog.log') formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s') hdlr.setFormatter(formatter) logger.addHandler(hdlr) logger.setLevel(logging.INFO) FTPADDR = "some ftp addre...
The syntax is no longer supported in python 3. Use the following instead. ``` try: do_something() except BaseException as e: logger.error('Failed to do something: ' + str(e)) ```
python exception message capturing
4,690,600
75
2011-01-14T11:33:50Z
19,101,737
10
2013-09-30T18:58:37Z
[ "python", "exception", "logging", "except" ]
``` import ftplib import urllib2 import os import logging logger = logging.getLogger('ftpuploader') hdlr = logging.FileHandler('ftplog.log') formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s') hdlr.setFormatter(formatter) logger.addHandler(hdlr) logger.setLevel(logging.INFO) FTPADDR = "some ftp addre...
If you really wanted to catch all the errors, you can do the following: ``` import sys, traceback def catchEverything(): try: ... some operation(s) ... except: exc_type, exc_value, exc_traceback = sys.exc_info() ... exception handling ... ``` exc\_value is the error message.
python exception message capturing
4,690,600
75
2011-01-14T11:33:50Z
28,431,302
7
2015-02-10T12:09:03Z
[ "python", "exception", "logging", "except" ]
``` import ftplib import urllib2 import os import logging logger = logging.getLogger('ftpuploader') hdlr = logging.FileHandler('ftplog.log') formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s') hdlr.setFormatter(formatter) logger.addHandler(hdlr) logger.setLevel(logging.INFO) FTPADDR = "some ftp addre...
You can use `logger.exception("msg")` for logging exception with traceback: ``` try: #your code except Exception as e: logger.exception('Failed: ' + str(e)) ```
How to analyze memory usage from a core dump?
4,690,851
7
2011-01-14T12:05:11Z
4,783,576
11
2011-01-24T15:12:51Z
[ "python", "linux", "memory-leaks", "coredump" ]
I have a core dump under Linux. The process went on memory allocation rampage and I need to find at least which library this happens in. What tool do you suggest to get broad overview of where the memory is going? I know the problem is hard/unsolvable fully. Any tool that could at least give some clues would help. [i...
After not getting any straight answers, I've tried a few different tools: - straight gdb - gdb + libpython - gdbheap - custom .gdbinit I've described by experiences in <http://blog.zemanta.com/blog/python-gdb-large-core-dump/> Hopefully this might help someone in the future stumbling across this question.
How to print source code lines in python logger
4,691,575
8
2011-01-14T13:36:37Z
4,691,853
12
2011-01-14T14:03:31Z
[ "python", "debugging", "logging" ]
Is there some relatively simple way to programmatically include source code lines to python logger report. For example... ``` import logging def main(): something_is_not_right = True logging.basicConfig(level=logging.DEBUG, format=('%(filename)s: ' '...
``` import inspect import logging import linecache def main(): something_is_not_right = True logging.basicConfig(level=logging.DEBUG, format=('%(filename)s: ' '%(levelname)s: ' '%(funcName)s(): ' ...
In python how to get name of a class inside its static method
4,691,925
15
2011-01-14T14:13:09Z
4,691,963
25
2011-01-14T14:17:29Z
[ "python" ]
how to get name of a class inside static method, i have inheritance and want name of derived class IN following example what shall be there in place of **XXX** in method my\_name() ``` class snake() @staticmethod def my_name(): print XXX.__name___ class python (snake) pass class cobra (snake) pas...
I'm pretty sure that this is impossible for a static method. Use a class method instead: ``` class Snake(object): @classmethod def my_name(cls): print cls.__name__ ```
"Operation not permitted" while dropping privileges using setuid() function
4,692,720
3
2011-01-14T15:32:50Z
4,692,777
15
2011-01-14T15:37:22Z
[ "python", "operating-system", "privileges", "setuid" ]
Why this simple programs that use os.setuid()/gid() fails? Is written in python but I think that is not a language relative problem (at the end are all the same posix system call): ``` import os, pwd if os.getenv("SUDO_UID") and os.getenv("SUDO_GID"): orig_uid=int(os.getenv("SUDO_UID")) orig_gid=int(os.getenv("SU...
Only the superuser or processes with the `CAP_SETGID` capability are allowed to set the GID. After the `setuid()` call, the effective UID isn't 0 any more, so you are not allowed to call `setgid()`. Try to reorder the two calls.
Autodoc params?
4,692,865
8
2011-01-14T15:46:34Z
4,692,947
13
2011-01-14T15:55:03Z
[ "python", "python-sphinx" ]
I'm newbie using sphinx. It looks pretty good. I have almost documented all my project using autodoc, but I want to change one behavior. Reading the documentation, I've seen this: <http://sphinx.pocoo.org/ext/autodoc.html#confval-autodoc_member_order>, and want to change to 'bysource' value, the point is, where is supp...
put ``` autodoc_member_order = 'bysource' ``` at the bottom of the config file. Of course you need version 1.0, as the docs you linked in the question mention: > *Changed in version 1.0: Support for `'bysource'`.*
Use of "global" keyword in Python
4,693,120
120
2011-01-14T16:11:03Z
4,693,158
7
2011-01-14T16:14:36Z
[ "python", "global-variables" ]
What I understand from reading the documentation is that Python has a separate namespace for functions, and if I want to use a global variable in that function, I need to use `global`. I'm using Python 2.7 and I tried this little test ``` >>> sub = ['0', '0', '0', '0'] >>> def getJoin(): ... return '.'.join(sub) ...
Accessing a name and assigning a name are different. In your case, you are just accessing a name. If you assign to a variable within a function, that variable is assumed to be local unless you declare it global. In the absence of that, it is assumed to be global. ``` >>> x = 1 # global >>> def foo(): ...
Use of "global" keyword in Python
4,693,120
120
2011-01-14T16:11:03Z
4,693,170
106
2011-01-14T16:15:40Z
[ "python", "global-variables" ]
What I understand from reading the documentation is that Python has a separate namespace for functions, and if I want to use a global variable in that function, I need to use `global`. I'm using Python 2.7 and I tried this little test ``` >>> sub = ['0', '0', '0', '0'] >>> def getJoin(): ... return '.'.join(sub) ...
While you can access global variables without the `global` keyword, if you want to assign to them you have to use the `global` keyword. For example: ``` foo = 1 def test(): foo = 2 # new local foo def blub(): global foo foo = 3 # changes the value of the global foo ``` In your case, you're just accessing...
Use of "global" keyword in Python
4,693,120
120
2011-01-14T16:11:03Z
4,693,385
188
2011-01-14T16:33:12Z
[ "python", "global-variables" ]
What I understand from reading the documentation is that Python has a separate namespace for functions, and if I want to use a global variable in that function, I need to use `global`. I'm using Python 2.7 and I tried this little test ``` >>> sub = ['0', '0', '0', '0'] >>> def getJoin(): ... return '.'.join(sub) ...
The keyword `global` is only useful to change or create global variables in a local context, although creating global variables is seldom considered a good solution. ``` def bob(): me = "locally defined" # Defined only in local context print me bob() print me # Asking for a global variable ``` The abo...
Use of "global" keyword in Python
4,693,120
120
2011-01-14T16:11:03Z
4,693,392
42
2011-01-14T16:33:53Z
[ "python", "global-variables" ]
What I understand from reading the documentation is that Python has a separate namespace for functions, and if I want to use a global variable in that function, I need to use `global`. I'm using Python 2.7 and I tried this little test ``` >>> sub = ['0', '0', '0', '0'] >>> def getJoin(): ... return '.'.join(sub) ...
This is the difference between accessing the name and [binding](http://docs.python.org/reference/executionmodel.html) it within a scope. If you're just looking up a variable to read its value, you've got access to global as well as local scope. However if you assign to a variable who's name isn't in local scope, you ...
Use of "global" keyword in Python
4,693,120
120
2011-01-14T16:11:03Z
4,694,310
31
2011-01-14T18:01:08Z
[ "python", "global-variables" ]
What I understand from reading the documentation is that Python has a separate namespace for functions, and if I want to use a global variable in that function, I need to use `global`. I'm using Python 2.7 and I tried this little test ``` >>> sub = ['0', '0', '0', '0'] >>> def getJoin(): ... return '.'.join(sub) ...
The other answers answer your question. Another important thing to know about names in Python is that they are either local or global on a per-scope basis. Consider this, for example: ``` value = 42 def doit(): print value value = 0 doit() print value ``` You can probably guess that the `value = 0` stateme...
has Python 3 been widely adopted yet?
4,693,352
11
2011-01-14T16:30:24Z
4,693,383
11
2011-01-14T16:33:04Z
[ "python", "python-3.x" ]
I know that when it launched, a lot of people didn't think it would be picked up very easily. I was wondering if thats changed at all. Do many of the major modules and libraries support Python 3 yet? Is it gaining acceptance or are people mostly sticking with 2.x?
If you [go to `python.org` and click on **Download**](http://python.org/download/), there's this message: > *If you don't know which version to use, start with Python 2.7; more existing third party software is compatible with Python 2 than Python 3 right now.* I think that's the case. Python 2 is still more ***useful...
has Python 3 been widely adopted yet?
4,693,352
11
2011-01-14T16:30:24Z
4,704,594
8
2011-01-16T09:13:53Z
[ "python", "python-3.x" ]
I know that when it launched, a lot of people didn't think it would be picked up very easily. I was wondering if thats changed at all. Do many of the major modules and libraries support Python 3 yet? Is it gaining acceptance or are people mostly sticking with 2.x?
The answer to all your questions are "Yes". :) > Do many of the major modules and libraries support Python 3 yet? Yes. > Is it gaining acceptance Yes. > or are people mostly sticking with 2.x? Yes. Your question is a bit fuzzy, namely. If you are wondering if you should use Python 2 or Python 3, then the answer ...
Find path of module without importing in Python
4,693,608
22
2011-01-14T16:51:28Z
4,693,681
42
2011-01-14T16:58:01Z
[ "python" ]
I've seen several approaches for finding the path of a module by first importing it. Is there a way to do this without importing the module?
Using [pkgutil](http://docs.python.org/library/pkgutil.html) module: ``` >>> import pkgutil >>> package = pkgutil.get_loader("pip") >>> package.filename '/usr/local/lib/python2.6/dist-packages/pip-0.7.1-py2.6.egg/pip' >>> package = pkgutil.get_loader("threading") >>> package.filename '/usr/lib/python2.6/threading.py' ...
Workflow using virtualenv and pip
4,693,814
12
2011-01-14T17:09:42Z
4,693,891
9
2011-01-14T17:18:24Z
[ "python", "django", "virtualenv" ]
I have python2.6 and django1.2.3 already installed on my system (Ubuntu 10.x). This is the setup i use for most of my projects. But for some projects I need sandboxed environments, different django version, some extra python modules and sometimes even different python version. So, I am trying to use pip and virtuale...
You want to do: ``` virtualenv --python=/path/to/python/version --no-site-packages ENV_NAME ``` For example: ``` virtualenv --python=/usr/bin/python2.6 --no-site-packages my_project_env ``` If you follow this for your projects you should be able to have a separate configuration for each one.
Actual SQL statement after bind variables specified
4,693,926
2
2011-01-14T17:22:21Z
4,694,048
7
2011-01-14T17:34:51Z
[ "python", "sql", "oracle", "cx-oracle" ]
I am trying to log every SQL statement executed from my scripts. However I contemplate one problem I can not overcome. Is there a way to compute actual SQL statement after bind variables were specified. In SQLite I had to compute the statement to be executed manually, using code below: ``` def __sql_to_str__(self, va...
The query is **never** computed as a single string. The actual text of the query and the params are *never* interpolated and **don't** produce a real full string with both. That's the whole point of using parameterized queries - you separate the query from the data - preventing sql injections and limitations all in on...
Center origin in matplotlib
4,694,478
11
2011-01-14T18:20:24Z
4,718,438
30
2011-01-17T22:06:34Z
[ "python", "matplotlib", "plot" ]
I need help customizing my plots. I want the canvas to look approximately like the default 2D-graph template from MacOS's Grapher (see screenshot). ![](http://i.stack.imgur.com/KNLRO.jpg) To clarify - I need * a centered axis * a grid (preferably with an additional darker grid every 1 unit) * axislines with arrows *...
This definitely falls under the category of more trouble than it's worth with matplotlib, but here you go. Also, for the basic case, have a look at the [centering spines demo in the documentation](http://matplotlib.org/examples/pylab_examples/spine_placement_demo.html). You can do this in a few different ways, but for...
Django: Encapsulate the whole template in the spaceless tag?
4,694,573
2
2011-01-14T18:31:23Z
4,711,310
7
2011-01-17T08:42:53Z
[ "python", "django", "django-templates" ]
It would eliminate whitespace. But, other than poor readability, any potential risks I should be aware of? Here is [the Django doc](http://docs.djangoproject.com/en/dev/ref/templates/builtins/#spaceless) for the tag.
The filter will parse the whole output, which might slow down rendering a bit. Given the reduced readability and potential performance woes, I would refrain from filtering whitespaces. The question is what you want to achieve by filtering white spaces. If you are concerned about traffic or transfer speed, check if yo...
expanding (adding a row or column) a scipy.sparse matrix
4,695,337
19
2011-01-14T19:58:59Z
17,457,226
16
2013-07-03T20:08:53Z
[ "python", "scipy", "sparse-matrix" ]
Suppose I have a NxN matrix M (lil\_matrix or csr\_matrix) from scipy.sparse, and I want to make it (N+1)xN where M\_modified[i,j] = M[i,j] for 0 <= i < N (and all j) and M[N,j] = 0 for all j. Basically, I want to add a row of zeros to the bottom of M and preserve the remainder of the matrix. Is there a way to do this ...
Scipy doesn't have a way to do this without copying the data but you can do it yourself by changing the attributes that define the sparse matrix. There are 4 attributes that make up the csr\_matrix: data: An array containing the actual values in the matrix indices: An array containing the column index corresponding ...
Checking date against date range in Python
4,695,609
19
2011-01-14T20:29:30Z
4,695,647
7
2011-01-14T20:33:54Z
[ "python", "datetime", "date", "time", "boolean" ]
I have a date variable: `2011-01-15` and I would like to get a boolean back if said date is within 3 days from TODAY. Im not quite sure how to construct this in Python. Im only dealing with date, not datetime. My working example is a "grace period". A user logs into my site and if the grace period is within 3 days of ...
Subtracting two `date` objects gives you a `timedelta` object, which you can compare to other `timedelta` objects. For example: ``` >>> from datetime import date, timedelta >>> date(2011, 1, 15) - date.today() datetime.timedelta(1) >>> date(2011, 1, 15) - date.today() < timedelta(days = 3) True >>> date(2011, 1, 18) ...
Checking date against date range in Python
4,695,609
19
2011-01-14T20:29:30Z
4,695,663
54
2011-01-14T20:35:49Z
[ "python", "datetime", "date", "time", "boolean" ]
I have a date variable: `2011-01-15` and I would like to get a boolean back if said date is within 3 days from TODAY. Im not quite sure how to construct this in Python. Im only dealing with date, not datetime. My working example is a "grace period". A user logs into my site and if the grace period is within 3 days of ...
In Python to check a range you can use `a <= x <= b`: ``` >>> import datetime >>> today = datetime.date.today() >>> margin = datetime.timedelta(days = 3) >>> today - margin <= datetime.date(2011, 1, 15) <= today + margin True ```
Efficient way to iterate throught xml elements
4,695,826
12
2011-01-14T20:52:57Z
4,696,030
8
2011-01-14T21:15:10Z
[ "python", "lxml" ]
i have a xml like this: ``` <a> <b>hello<b> <b>world<b> </a> <x> <y></y> </x> <a> <b>first<b> <b>second<b> <b>third<b> </a> ``` i need to iterate through all `<a>` and `<b>` tags, but i don't know how many of them are in document. So i use `xpath` to handle that: ``` from lxml import etree d...
How about [iter](http://codespeak.net/lxml/tutorial.html#tree-iteration)? ``` >>> for tags in root.iter('b'): # root is the ElementTree object ... print tags.tag, tags.text ... b hello b world b first b second b third ```
Efficient way to iterate throught xml elements
4,695,826
12
2011-01-14T20:52:57Z
4,696,161
15
2011-01-14T21:31:16Z
[ "python", "lxml" ]
i have a xml like this: ``` <a> <b>hello<b> <b>world<b> </a> <x> <y></y> </x> <a> <b>first<b> <b>second<b> <b>third<b> </a> ``` i need to iterate through all `<a>` and `<b>` tags, but i don't know how many of them are in document. So i use `xpath` to handle that: ``` from lxml import etree d...
XPath should be fast. You can reduce the number of XPath calls to one: ``` doc = etree.fromstring(xml) btags = doc.xpath('//a/b') for b in btags: print b.text ``` If that is not fast enough, you could try [Liza Daly's fast\_iter](http://www.ibm.com/developerworks/xml/library/x-hiperfparse/). This has the advantag...
ftp.retrbinary() help python
4,696,413
9
2011-01-14T21:58:43Z
4,696,572
17
2011-01-14T22:15:56Z
[ "python", "ftp", "binary", "ascii" ]
I have created a python script to connect to a remserver. ``` datfile = [] for dk in range(len(files)): dfnt=files[dk] dpst=dfnt.find('.dat') if dpst == 15: dlist = dfnt[:] datfile.append(dlist) assert datfile == ['a.dat','b.dat'] # True ``` which as you can see create a list. now I am passing this list to ``` ftp....
It's telling you that you aren't supplying enough arguments to the `retrbinary` method. The [documentation specifies](http://docs.python.org/library/ftplib.html#ftplib.FTP.retrbinary) that you must also supply a 'callback' function that gets called for every block of data received. You'll want to write a callback func...
Python: Split string by list of separators
4,697,006
5
2011-01-14T23:24:57Z
4,697,047
11
2011-01-14T23:35:56Z
[ "python", "regex", "split", "separator" ]
In Python, I'd like to split a string using a list of separators. The separators could be either commas or semicolons. Whitespace should be removed unless it is in the middle of non-whitespace, non-separator characters, in which case it should be preserved. Test case 1: `ABC,DEF123,GHI_JKL,MN OP` Test case 2: `ABC;D...
This should be much faster then regex and you can pass a list of seperators as you wanted: ``` def split(txt, seps): default_sep = seps[0] # we skip seps[0] because that's the default seperator for sep in seps[1:]: txt = txt.replace(sep, default_sep) return [i.strip() for i in txt.split(defaul...
how can i check if a letter in a string is capialized using python?
4,697,535
11
2011-01-15T01:29:41Z
4,697,553
32
2011-01-15T01:33:23Z
[ "python", "capitalization" ]
i have a string like "asdfHRbySFss" and i want to go through one char at a time and see which letters are capitalized, is this possible in python?
Use [string.isupper()](http://docs.python.org/library/stdtypes.html#str.isupper) ``` letters = "asdfHRbySFss" uppers = [l for l in letters if l.isupper()] ``` if you want to bring that back into a string you can do: ``` print "".join(uppers) ```
Get the value of specific JSON element in Python
4,697,626
7
2011-01-15T01:56:56Z
4,697,636
11
2011-01-15T02:33:16Z
[ "python", "json" ]
I'm new to Python and JSON, so I'm sorry if I sound clueless. I'm getting the following result from the Google Translate API and want to parse out the value of "translatedText": ``` { "data": { "translations": [ { "translatedText": "Toute votre base sont appartiennent à nous" } ] } } ``` This respons...
You can parse the text into an object using the `json` module in Python >= 2.6: ``` >>> import json >>> translation = json.loads("""{ ... "data": { ... "translations": [ ... { ... "translatedText": "Toute votre base sont appartiennent nous" ... }, ... { ... "translate": "¡Qué bien!" ... } ......
python 3.1 - Creating normal distribution
4,697,836
6
2011-01-15T03:39:46Z
4,697,952
8
2011-01-15T04:13:46Z
[ "python" ]
very new to python. I have scipy and numpy, Python v3.1 I need to create a 1D array of length 3million, using random numbers between (and including) 100-60,000. It has to fit a normal distribution. Using 'a = numpy.random.standard\_normal(3000000)', I get a normal distribution for that required length; not sure how t...
A standard normal distribution has mean 0 and standard deviation 1. What I understand from your requirements is that you need a ((60000-100)/2, (60000-100)/2) one. Take each value from `standard_normal()` result, [multiply it by the new variance, and add the new mean](http://en.wikipedia.org/wiki/Normal_distribution#St...
How can I find all matches to a regular expression in Python?
4,697,882
118
2011-01-15T03:53:07Z
4,697,884
208
2011-01-15T03:54:37Z
[ "python", "regex", "search", "recursion" ]
In a program I'm writing i have python use the `re.search()` function to find matches in a block of text and print the results. However, once the program finds the first match in the block of text, it exits. How do i do this repeatedly where the program doesn't stop until ALL matches have been found? Is there a separat...
Use `re.findall` or `re.finditer` instead. [`re.findall(pattern, string)`](http://docs.python.org/library/re.html#re.findall) returns a list of matching strings. [`re.finditer(pattern, string)`](http://docs.python.org/library/re.html#re.finditer) returns an iterator over [`MatchObject`](http://docs.python.org/library...
Django Template - Convert a Python list into a JavaScript object
4,698,220
8
2011-01-15T05:38:07Z
4,698,226
20
2011-01-15T05:40:01Z
[ "javascript", "python", "django", "django-templates" ]
I am working on a Django / Python website. I have a page where I want to display a table of search results. The list of results is passed in to the template as normal. I also want to make this list of objects accessible to the JavaScript code. My first solution was just create another view that returned [JSON](http:/...
How about a filter that dumps a Python value to JSON? Here's a sample implementation: <http://djangosnippets.org/snippets/201/> Since a JSON value also happens to be a valid right-hand side for a Javascript assignment, you can simply put something like... ``` var results = {{results|jsonify}}; ``` inside your scrip...
Django Template - Convert a Python list into a JavaScript object
4,698,220
8
2011-01-15T05:38:07Z
4,699,069
16
2011-01-15T10:23:08Z
[ "javascript", "python", "django", "django-templates" ]
I am working on a Django / Python website. I have a page where I want to display a table of search results. The list of results is passed in to the template as normal. I also want to make this list of objects accessible to the JavaScript code. My first solution was just create another view that returned [JSON](http:/...
**Solution** I created a custom template filter, see *[custom template tags and filters](http://docs.djangoproject.com/en/dev/howto/custom-template-tags/)*. ``` from django.core.serializers import serialize from django.db.models.query import QuerySet from django.utils import simplejson from django.utils.safestring im...
Can I add custom methods/attributes to built-in Python types?
4,698,493
38
2011-01-15T07:27:10Z
4,698,550
35
2011-01-15T07:47:38Z
[ "python", "custom-attributes", "built-in-types" ]
For example—say I want to add a `helloWorld()` method to Python's dict type. Can I do this? JavaScript has a prototype object that behaves this way. Maybe it's bad design and I should subclass the dict object, but then it only works on the subclasses and I want it to work on any and all future dictionaries. Here's ho...
You can't directly add the method to the original type. However, you can subclass the type then substitute it in the built-in/global namespace, which achieves most of the effect desired. Unfortunately, objects created by literal syntax will continue to be of the vanilla type and won't have your new methods/attributes. ...
Is it possible to create a Python list and fake populating it?
4,698,755
3
2011-01-15T08:56:18Z
4,698,760
10
2011-01-15T08:57:59Z
[ "python", "neo4j" ]
I am working with Neo4j graph database, and would like to adapt one of the current REST libraries. Imagine a case with a database with 20 nodes. ``` >>> db = Database("http://localhost:7474") ``` I would like the API to be as simple as possible, so that it would be possible to get the 14th node with something similar...
Yes, you can write a custom class that implements `__getitem__` and generates a result dynamically. ``` >>> class MyDatabase(object): ... def __getitem__(self, x): ... if 10 <= x <= 15: ... return "foo" ... else: ... raise IndexError('key not in database') ... >>> db = MyDat...
What command to use to introspect instances in scala REPL?
4,698,831
4
2011-01-15T09:19:55Z
4,699,128
8
2011-01-15T10:38:08Z
[ "python", "scala" ]
In python: ``` >>> s = "abc" >>> dir(s) ['__add__', '__class__', '__contains__', '__delattr__', ... ``` Is there an equivalent way - i.e. dir() function - to do this with instances in the scala REPL ?
When you press the tabulator-key the REPL shows you the methods which you can call on an object: ``` scala> val s = "abc" s: java.lang.String = abc scala> s.<tab> + asInstanceOf charAt codePointAt codePointBefore codePointCount compareTo compareToIgnoreCase ...
One-line expression to map dictionary to another
4,698,932
5
2011-01-15T09:49:38Z
4,698,948
13
2011-01-15T09:52:16Z
[ "python" ]
I have dictionary like ``` d = {'user_id':1, 'user':'user1', 'group_id':3, 'group_name':'ordinary users'} ``` and "mapping" dictionary like: ``` m = {'user_id':'uid', 'group_id':'gid', 'group_name':'group'} ``` All i want to "replace" keys in first dictionary with keys from second (e.g. replace 'user\_id' with 'uid...
Sure: ``` d = dict((m.get(k, k), v) for (k, v) in d.items()) ```
One-line expression to map dictionary to another
4,698,932
5
2011-01-15T09:49:38Z
4,699,251
11
2011-01-15T11:16:00Z
[ "python" ]
I have dictionary like ``` d = {'user_id':1, 'user':'user1', 'group_id':3, 'group_name':'ordinary users'} ``` and "mapping" dictionary like: ``` m = {'user_id':'uid', 'group_id':'gid', 'group_name':'group'} ``` All i want to "replace" keys in first dictionary with keys from second (e.g. replace 'user\_id' with 'uid...
Let's take the excellent code from @karlknechtel and see what it does: ``` >>> d = dict((m.get(k, k), v) for (k, v) in d.items()) {'gid': 3, 'group': 'ordinary users', 'uid': 1, 'user': 'user1'} ``` But how does it work? To build a dictionary, you can use the `dict()` function. It expects a list of tuples. In 3.x an...
Django model field choices - wouldn't a dict be better?
4,698,972
9
2011-01-15T09:56:41Z
4,699,079
13
2011-01-15T10:24:52Z
[ "python", "django", "django-models" ]
Given a field; ``` domain_status_choices = ( (1,'Live') (2,'Offline') (3,'Dev') ) status = models.SmallIntegerField( choices=domain_status_choices ) ``` I know I can get and set numeric representation and use `get_status_display()` to get the text label. But if a user posts `status=Offline` how can I get ...
I believe the keys of a dict are not guaranteed to be sorted (unless you use `OrderedDict` obviously). That is, you "might" get "Offline", "Dev", "Live" choices with your version. Implementation note on [dict.items](http://docs.python.org/library/stdtypes.html#dict.items): > Keys and values are listed in an arbitrary...
Django - post_init signal is called on Model instance save & before instance is even created. Why?
4,700,209
10
2011-01-15T14:55:05Z
4,701,353
11
2011-01-15T18:23:26Z
[ "python", "django", "signals" ]
I am trying to write a small application that receives video files, and convert them to a uniform format after they have been uploaded (thus added to the database). I have searched the web for the best solution for this, and have decided to use Django's signals with [Celery](http://celeryproject.org/). But for now I'm ...
You seem to have a bit of confusion over what it means to instantiate an object. It has nothing whatever to do with the database. This instantiates a model object without saving it to the database, in which case its pk will be None: ``` MyObject(field1='foo', field2='bar') ``` and this (indirectly) instantiates an ob...
Using RabbitMQ is there a way to look at the queue contents without a dequeue?
4,700,292
26
2011-01-15T15:13:55Z
9,286,914
27
2012-02-15T01:56:17Z
[ "python", "rabbitmq", "esb", "amqp" ]
As a way to learn RabbitMQ and python I'm working on a project that allows me to distribute h264 encodes between a number of computers. The basics are done, I have a daemon that runs on Linux or Mac that attaches to queue, accepts jobs and encodes them using HandBrakeCLI and acks the message once the encode is complete...
Queue browsing is not supported directly, but if you declare a queue with NO auto acknowledgements and do not ACK the messages that you receive, then you can see everything in it. After you have had a look, send a CANCEL on the channel, or disconnect and reconnect to cause all the messages to be requeued. This does inc...
Python: Comparing specific columns in two csv files
4,700,441
4
2011-01-15T15:39:56Z
4,700,471
7
2011-01-15T15:46:09Z
[ "python", "csv" ]
Say that I have two CSV files (file1 and file2) with contents as shown below: file1: ``` fred,43,Male,"23,45",blue,"1, bedrock avenue" ``` file2: ``` fred,39,Male,"23,45",blue,"1, bedrock avenue" ``` I would like to compare these two CSV records to see if columns 0,2,3,4, and 5 are the same. I don't care about col...
I suppose the best ways is to use Python library: <http://docs.python.org/library/csv.html>. **UPDATE (example added)**: ``` import csv reader1 = csv.reader(open('data1.csv', 'rb'), delimiter=',', quotechar='"')) row1 = reader1.next() reader2 = csv.reader(open('data2.csv', 'rb'), delimiter=',', quotechar='"')) row2 =...
How to put the legend out of the plot
4,700,614
309
2011-01-15T16:10:03Z
4,700,674
56
2011-01-15T16:21:37Z
[ "python", "matplotlib", "legend" ]
I have a series of 20 plots (not subplots) to be made in a single figure. I want the legend to be outside of the box. At the same time, I do not want to change the axes, as the size of the figure gets reduced. Kindly help me for the following queries: 1. I want to keep the legend box outside the plot area. (I want the...
Create font properties ``` from matplotlib.font_manager import FontProperties fontP = FontProperties() fontP.set_size('small') legend([plot1], "title", prop = fontP) ```
How to put the legend out of the plot
4,700,614
309
2011-01-15T16:10:03Z
4,700,762
22
2011-01-15T16:41:50Z
[ "python", "matplotlib", "legend" ]
I have a series of 20 plots (not subplots) to be made in a single figure. I want the legend to be outside of the box. At the same time, I do not want to change the axes, as the size of the figure gets reduced. Kindly help me for the following queries: 1. I want to keep the legend box outside the plot area. (I want the...
To place the legend outside the plot area, use loc and bbox\_to\_anchor keywords of legend(). For example, the following code will place the legend to the right of the plot area: ``` legend(loc="upper left", bbox_to_anchor=(1,1)) ``` For more info, see the [legend guide](http://matplotlib.org/users/legend_guide.html#...
How to put the legend out of the plot
4,700,614
309
2011-01-15T16:10:03Z
4,701,285
852
2011-01-15T18:12:27Z
[ "python", "matplotlib", "legend" ]
I have a series of 20 plots (not subplots) to be made in a single figure. I want the legend to be outside of the box. At the same time, I do not want to change the axes, as the size of the figure gets reduced. Kindly help me for the following queries: 1. I want to keep the legend box outside the plot area. (I want the...
There are a number of ways to do what you want. To add to what @inalis and @Navi already said, you can use the `bbox_to_anchor` keyword argument to place the legend partially outside the axes and/or decrease the font size. Before you consider decreasing the font size (which can make things awfully hard to read), try p...
How to put the legend out of the plot
4,700,614
309
2011-01-15T16:10:03Z
14,988,532
39
2013-02-20T19:41:10Z
[ "python", "matplotlib", "legend" ]
I have a series of 20 plots (not subplots) to be made in a single figure. I want the legend to be outside of the box. At the same time, I do not want to change the axes, as the size of the figure gets reduced. Kindly help me for the following queries: 1. I want to keep the legend box outside the plot area. (I want the...
**Short Answer**: Invoke draggable on the legend and interactively move it wherever you want: ``` ax.legend().draggable() ``` **Long Answer**: If you rather prefer to place the legend interactively/manually rather than programmatically, you can toggle the draggable mode of the legend so that you can drag it to wherev...
How to put the legend out of the plot
4,700,614
309
2011-01-15T16:10:03Z
21,659,899
7
2014-02-09T13:55:14Z
[ "python", "matplotlib", "legend" ]
I have a series of 20 plots (not subplots) to be made in a single figure. I want the legend to be outside of the box. At the same time, I do not want to change the axes, as the size of the figure gets reduced. Kindly help me for the following queries: 1. I want to keep the legend box outside the plot area. (I want the...
As noted, you could also place the legend in the plot, or slightly off it to the edge as well. Here is an example using the [Plotly Python API](http://plot.ly/api/python), made with an [IPython Notebook](http://nbviewer.ipython.org/github/plotly/IPython-plotly/blob/master/Plotly%20gets%20LaTeXy.ipynb). I'm on the team....
How to put the legend out of the plot
4,700,614
309
2011-01-15T16:10:03Z
23,139,642
8
2014-04-17T17:27:24Z
[ "python", "matplotlib", "legend" ]
I have a series of 20 plots (not subplots) to be made in a single figure. I want the legend to be outside of the box. At the same time, I do not want to change the axes, as the size of the figure gets reduced. Kindly help me for the following queries: 1. I want to keep the legend box outside the plot area. (I want the...
Not exactly what you asked for, but I found it's an alternative for the same problem. Make the legend semi-transparant, like so: ![matplotlib plot with semi transparent legend and semitransparent text box](http://i.stack.imgur.com/foCZw.png) Do this with: ``` fig = pylab.figure() ax = fig.add_subplot(111) ax.plot(x,y...
How to put the legend out of the plot
4,700,614
309
2011-01-15T16:10:03Z
24,544,116
59
2014-07-03T02:43:20Z
[ "python", "matplotlib", "legend" ]
I have a series of 20 plots (not subplots) to be made in a single figure. I want the legend to be outside of the box. At the same time, I do not want to change the axes, as the size of the figure gets reduced. Kindly help me for the following queries: 1. I want to keep the legend box outside the plot area. (I want the...
If you are using Pandas `plot()` wrapper function and want to place legend outside then here's very easy way: ``` df.myCol.plot().legend(loc='center left', bbox_to_anchor=(1, 0.5)) ``` We just chain `legend()` call after the `plot()`. Results would look something like this: ![enter image description here](http://i....
How to put the legend out of the plot
4,700,614
309
2011-01-15T16:10:03Z
25,344,713
45
2014-08-16T22:49:37Z
[ "python", "matplotlib", "legend" ]
I have a series of 20 plots (not subplots) to be made in a single figure. I want the legend to be outside of the box. At the same time, I do not want to change the axes, as the size of the figure gets reduced. Kindly help me for the following queries: 1. I want to keep the legend box outside the plot area. (I want the...
Short answer: you can use `bbox_to_anchor` + `bbox_extra_artists` + `bbox_inches='tight'`. --- Longer answer: You can use `bbox_to_anchor` to manually specify the location of the legend box, as some other people have pointed out in the answers. However, the usual issue is that the legend box is cropped, e.g.: ``` i...
How to put the legend out of the plot
4,700,614
309
2011-01-15T16:10:03Z
27,355,247
27
2014-12-08T09:46:40Z
[ "python", "matplotlib", "legend" ]
I have a series of 20 plots (not subplots) to be made in a single figure. I want the legend to be outside of the box. At the same time, I do not want to change the axes, as the size of the figure gets reduced. Kindly help me for the following queries: 1. I want to keep the legend box outside the plot area. (I want the...
In addition to all the excellent answers here, newer versions of `matplotlib` and `pylab` can **automatically determine where to put the legend without interfering with the plots**. ``` pylab.legend(loc='best') ``` This will automatically place the legend outside the plot! ![Compare the use of loc='best'](http://i.st...
Django Serialization of DateTime Objects within Dictionary
4,702,044
6
2011-01-15T20:45:05Z
4,702,277
28
2011-01-15T21:34:10Z
[ "python", "django", "datetime", "serialization" ]
My Django view method is below. I want to pass place\_data as a response from an HTTPRequest (within a getJSON call on the client side, but that's irrelevant to the issue). I can pass the dictionary fine until I include the **event\_occurrences**, which is doing some behind the scenes work to pass a dictionary of even...
Django's serialization framework is for QuerySets, not dicts. If you want to just dump a dictionary to JSON, just use `json.dumps`. It can easily be made to serialize objects by passing in a custom serialization class - there's one included with Django that deals with datetimes already: ``` from django.core.serializer...
Can Python be used as an effective script language for Windows Server environment?
4,702,133
8
2011-01-15T21:06:18Z
4,702,227
8
2011-01-15T21:20:39Z
[ "python", "ironpython", "windows-server" ]
I'm currently working on a strategy for managing multiple Windows Server 2003 to 2008 running SQL Server 2000 - 2008 and I want/need a unified scripting platform for automating tasks. I'm becoming a big fan of Python and as such I'd like to know if Python has been used effectively as a scripting language for administer...
Notwithstanding my love of `Python`, I think `PowerShell` fits more. From Wikipedia *`Windows PowerShell is Microsoft's task automation framework, consisting of a command-line shell and associated scripting language built on top of, and integrated with the .NET Framework. PowerShell provides full access to COM and WM...
Is there a way in Python to return value via output parameter?
4,702,249
19
2011-01-15T21:25:56Z
4,702,280
31
2011-01-15T21:35:00Z
[ "python" ]
Is there a way in Python to return a value via output parameter?
There is no reason to, since Python can return multiple values: ``` def func(): return 1,2,3 a,b,c = func() ``` But you can also pass a mutable parameter, and return values as well: ``` def func(a): a.append(1) a.append(2) a.append(3) L=[] func(L) print L ```
Python 3.1: Syntax Error for Everything! (Mac OS X)
4,702,556
3
2011-01-15T22:42:11Z
4,702,564
10
2011-01-15T22:43:06Z
[ "python", "osx", "shell", "syntax-error", "python-idle" ]
I updated to Python 3.1.3 (I've got OS X 10.6). If I type `python` in Terminal, I get a working 2.6.1 environment. If I type `python3` in Terminal, I get a 3.1.3 environment. Everything looks fine until I do something. If I try to run `print "hello"`, I get a syntax error. This problem is the same in IDLE. I trie...
In Python 3.x, [`print` is a function](http://docs.python.org/py3k/whatsnew/3.0.html#print-is-a-function), so use ``` print("Hello") ``` instead.
Python 3.1: Syntax Error for Everything! (Mac OS X)
4,702,556
3
2011-01-15T22:42:11Z
4,702,566
8
2011-01-15T22:43:33Z
[ "python", "osx", "shell", "syntax-error", "python-idle" ]
I updated to Python 3.1.3 (I've got OS X 10.6). If I type `python` in Terminal, I get a working 2.6.1 environment. If I type `python3` in Terminal, I get a 3.1.3 environment. Everything looks fine until I do something. If I try to run `print "hello"`, I get a syntax error. This problem is the same in IDLE. I trie...
In Python 3, you need to use Print as a function: ``` print("Hello") ```
How to write string literals in python without having to escape them?
4,703,516
37
2011-01-16T02:47:29Z
4,703,526
50
2011-01-16T02:51:31Z
[ "python", "string", "escaping" ]
Is there a way to declare a string variable in python such that everything inside of it is automatically escaped, or has its literal character value? I'm *not* asking how to escape the quotes with slashes, that's obvious. What I'm asking for is a general purpose way for making everything in a string literal so that I ...
Raw string literals: ``` >>> r'abc\dev\t' 'abc\\dev\\t' ```
How to write string literals in python without having to escape them?
4,703,516
37
2011-01-16T02:47:29Z
4,703,567
29
2011-01-16T03:04:35Z
[ "python", "string", "escaping" ]
Is there a way to declare a string variable in python such that everything inside of it is automatically escaped, or has its literal character value? I'm *not* asking how to escape the quotes with slashes, that's obvious. What I'm asking for is a general purpose way for making everything in a string literal so that I ...
If you're dealing with very large strings, specifically multiline strings, be aware of the *triple-quote* syntax: ``` a = r"""This is a multiline string with more than one line in the source code.""" ```
python-nose: assertion library?
4,703,961
7
2011-01-16T05:22:44Z
4,704,113
10
2011-01-16T06:15:08Z
[ "python", "nosetests", "assertion" ]
Is there a library which of nose-friendly assertions things like membership and identity (eg, `assert_contains(x, y)`, `assert_is(a, b)`)?
Nose provides stand-alone versions of the stdlib assertions: ``` from nose.tools import assert_in, assert_is ``` For older Pythons, the unittest2 versions can likely be wrapped using a technique similar to what's in tools.py.
Module subprocess has no attribute 'STARTF_USESHOWWINDOW'
4,703,983
7
2011-01-16T05:31:15Z
4,901,601
10
2011-02-04T18:30:47Z
[ "python", "python-3.x", "subprocess" ]
Hi Stack Overflow users, I've encountered a frustrating problem, can't find the answer to it. Yesterday I was trying to find a way to HIDE a subprocess.Popen. So for example, if i was opening the cmd. I would like it to be hidden, permanently. I found this code: ``` kwargs = {} if subprocess.mswindows: su = su...
You can recreate or check the described problem in your Python installation: ``` import subprocess subprocess.STARTF_USESHOWWINDOW ``` If the problem persists you should receive error message ending with line like this: ``` AttributeError: 'module' object has no attribute 'STARTF_USESHOWWINDOW' ``` Possible solutio...
Python script as linux service/daemon
4,705,564
56
2011-01-16T13:20:57Z
4,706,394
71
2011-01-16T16:03:29Z
[ "python", "linux", "service", "daemon" ]
Hallo, I'm trying to let a python script run as service (daemon) on (ubuntu) linux. On the web there exist several solutions like: <http://pypi.python.org/pypi/python-daemon/> > A well-behaved Unix daemon process is tricky to get right, but the required steps are much the same for every daemon program. A DaemonCont...
Assuming your daemon has some way of continually running (some event loop, twisted, whatever), you can try to use `upstart`. Here's an example upstart config for a hypothetical Python service: ``` description "My service" author "Some Dude <blah@foo.com>" start on runlevel [234] stop on runlevel [0156] chdir /some...
How to get value from form field in django framework?
4,706,255
42
2011-01-16T15:40:57Z
4,706,278
56
2011-01-16T15:44:23Z
[ "python", "django" ]
How to get value from form field in django framework? I mean, in views not in templates...
[Using a form in a view](http://docs.djangoproject.com/en/dev/topics/forms/#using-a-form-in-a-view) pretty much explains it. > The standard pattern for processing a form in a view looks like this: ``` def contact(request): if request.method == 'POST': # If the form has been submitted... form = ContactForm...
How to get value from form field in django framework?
4,706,255
42
2011-01-16T15:40:57Z
4,706,280
16
2011-01-16T15:44:27Z
[ "python", "django" ]
How to get value from form field in django framework? I mean, in views not in templates...
You can do this after you validate your data. ``` if myform.is_valid(): data = myform.cleaned_data field = data['field'] ``` Also, read the django docs. They are perfect.
How do you append to a file in Python?
4,706,499
734
2011-01-16T16:20:33Z
4,706,519
94
2011-01-16T16:23:51Z
[ "python", "file", "append" ]
How do you append to the file instead of overwriting it? Is there a special function that appends to the file?
You need to open the file in append mode, by setting "a" or "ab" as the mode. See *[open()](https://docs.python.org/2/library/functions.html#open)*. When you open with "a" mode, the write position will **always** be at the end of the file (an append). You can open with "a+" to allow reading, seek backwards and read (b...
How do you append to a file in Python?
4,706,499
734
2011-01-16T16:20:33Z
4,706,520
1,237
2011-01-16T16:24:05Z
[ "python", "file", "append" ]
How do you append to the file instead of overwriting it? Is there a special function that appends to the file?
``` with open("test.txt", "a") as myfile: myfile.write("appended text") ```
How do you append to a file in Python?
4,706,499
734
2011-01-16T16:20:33Z
4,706,565
18
2011-01-16T16:31:38Z
[ "python", "file", "append" ]
How do you append to the file instead of overwriting it? Is there a special function that appends to the file?
You probably want to pass `"a"` as the mode argument. See the docs for [open()](http://docs.python.org/library/functions.html#open). ``` with open("foo", "a") as f: f.write("cool beans...") ``` There are other permutations of the mode argument for updating (+), truncating (w) and binary (b) mode but starting with...
How do you append to a file in Python?
4,706,499
734
2011-01-16T16:20:33Z
26,833,243
15
2014-11-09T20:57:02Z
[ "python", "file", "append" ]
How do you append to the file instead of overwriting it? Is there a special function that appends to the file?
I always do this, ``` f = open('filename.txt', 'a') f.write("stuff") f.close() ``` It's simple, but very useful.
How does the get_or_create function in Django return two values?
4,706,697
18
2011-01-16T16:57:48Z
4,706,714
28
2011-01-16T17:00:27Z
[ "python", "django" ]
I have used the `get_or_create` function on my models in Django. This function returns two values. One is the object itself and the other a boolean flag that indicates whether an existing object was retrieved or a new one created. Normally, a function can return a single value or a collection of values like a `tuple`,...
`get_or_create()` simply returns a tuple of the two values. You can then use [sequence unpacking](http://docs.python.org/tutorial/datastructures.html#tuples-and-sequences) to bind the two tuple entries to two names, like in the [documentation](https://docs.djangoproject.com/en/1.4/ref/models/querysets/#get-or-create) e...
Global variable with imports
4,706,879
16
2011-01-16T17:30:32Z
4,706,889
12
2011-01-16T17:31:49Z
[ "python", "global" ]
## first.py ``` myGlobal = "hello" def changeGlobal(): myGlobal="bye" ``` ## second.py ``` from first import * changeGlobal() print myGlobal ``` The output I get is > hello although I thought it should be > bye Why doesn't the global variable `myGlobal` changes after the call to the `changeGlobal()` functi...
Try: ``` def changeGlobal(): global myGlobal myGlobal = "bye" ``` Actually, that doesn't work either. When you `import *`, you create a new local module global `myGlobal` that is immune to the change you intend (as long as you're not mutating the variable, see below). You can use this instead: ``` import nic...
how to get the number of elements in a python list?
4,706,989
23
2011-01-16T17:51:14Z
4,707,001
51
2011-01-16T17:52:55Z
[ "python", "list", "count" ]
I'm new to python. i've the following code: ``` liste = 'asdfasfasd:asdfafaergasde' # example, how the string looks like liste = str.split(':'); if liste.count()>2 : print "NOT YET SUPPORTED!" ``` According to the doc <http://docs.python.org/library/stdtypes.html> , python can just return number of i‘s for which...
It's the `len()` stand-alone function, `if len(listen_addr)>2:`