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
How to convert a MultiDict to nested dictionary
9,058,233
6
2012-01-30T00:52:05Z
9,058,366
8
2012-01-30T01:15:07Z
[ "python", "nested", "nested-forms", "webob" ]
I would like to convert a POST from Webob [MultiDict](http://docs.webob.org/en/latest/reference.html#query-post-variables) to nested dictionary. E.g. So from a POST of: ``` 'name=Kyle&phone.number=1234&phone.type=home&phone.number=5678&phone.type=work' ``` to a multidict; ``` [('name', 'Kyle'), ('phone.number', '12...
If you have formencode installed or can install it, checkout out their [variabledecode module](http://www.formencode.org/en/latest/modules/variabledecode.html)
Getting attributes of a class
9,058,305
28
2012-01-30T01:03:09Z
9,058,322
40
2012-01-30T01:07:59Z
[ "python", "python-2.7" ]
I want to get the attributes of a class, say: ``` class MyClass(): a = "12" b = "34" def myfunc(self): return self.a ``` using `MyClass.__dict__` gives me a list of attributes and functions, and even functions like `__module__` and `__doc__`. While `MyClass().__dict__` gives me an empty dict unless I expli...
Try the [inspect](http://docs.python.org/library/inspect.html#inspect.getmembers) module. `getmembers` and the various tests should be helpful. EDIT: For example, ``` class MyClass(object): a = '12' b = '34' def myfunc(self): return self.a >>> import inspect >>> inspect.getmembers(MyClass, lambd...
Getting attributes of a class
9,058,305
28
2012-01-30T01:03:09Z
9,058,426
10
2012-01-30T01:26:45Z
[ "python", "python-2.7" ]
I want to get the attributes of a class, say: ``` class MyClass(): a = "12" b = "34" def myfunc(self): return self.a ``` using `MyClass.__dict__` gives me a list of attributes and functions, and even functions like `__module__` and `__doc__`. While `MyClass().__dict__` gives me an empty dict unless I expli...
`myfunc` **is** an attribute of `MyClass`. That's how it's found when you run: ``` myinstance = MyClass() myinstance.myfunc() ``` It looks for an attribute on `myinstance` named `myfunc`, doesn't find one, sees that `myinstance` is an instance of `MyClass` and looks it up there. So the *complete* list of attributes ...
Getting attributes of a class
9,058,305
28
2012-01-30T01:03:09Z
17,249,228
12
2013-06-22T09:31:05Z
[ "python", "python-2.7" ]
I want to get the attributes of a class, say: ``` class MyClass(): a = "12" b = "34" def myfunc(self): return self.a ``` using `MyClass.__dict__` gives me a list of attributes and functions, and even functions like `__module__` and `__doc__`. While `MyClass().__dict__` gives me an empty dict unless I expli...
``` def props(cls): return [i for i in cls.__dict__.keys() if i[:1] != '_'] properties = props(MyClass) ```
whose regex is faster? python or perl
9,059,033
3
2012-01-30T03:34:36Z
9,059,695
17
2012-01-30T05:21:16Z
[ "python", "regex", "perl" ]
I saw in the wiki page <http://en.wikipedia.org/wiki/Comparison_of_regular_expression_engines> that python use non-recursive implementation as grep and sed while perl one uses the simple cursive impl. does this indicate that python's regex performance is faster than perl's?
This is not a direct answer because the answer to the Python v. Perl regex question seems to be "it depends". If you are concerned about regex speed, there are a few things you should look into. One is to use plain search and replace, where possible, instead of regex. The other is to use [Google's re2 module](http://...
What is the purpose in Python's itertools.repeat?
9,059,173
12
2012-01-30T03:57:19Z
9,059,241
13
2012-01-30T04:08:59Z
[ "python", "python-3.x", "itertools" ]
Every use I can think of for Python's [`itertools.repeat()`](http://docs.python.org/py3k/library/itertools.html?highlight=repeat#itertools.repeat) class, I can think of another equally (possibly more) acceptable solution to achieve the same effect. For example: ``` >>> (i for i in itertools.repeat('example', 5)) ('exa...
Your example of `foo * 5` looks superficially similar to `itertools.repeat(foo, 5)`, but it is actually quite different. If you write `foo * 100000`, the interpreter must create 100,000 copies of `foo` before it can give you an answer. It is thus a very expensive and memory-unfriendly operation. But if you write `ite...
What is the purpose in Python's itertools.repeat?
9,059,173
12
2012-01-30T03:57:19Z
9,059,268
12
2012-01-30T04:14:57Z
[ "python", "python-3.x", "itertools" ]
Every use I can think of for Python's [`itertools.repeat()`](http://docs.python.org/py3k/library/itertools.html?highlight=repeat#itertools.repeat) class, I can think of another equally (possibly more) acceptable solution to achieve the same effect. For example: ``` >>> (i for i in itertools.repeat('example', 5)) ('exa...
The `itertools.repeat` function is lazy; it only uses the memory required for one item. On the other hand, the `(a) * n` and `[a] * n` idioms create n copies of the object in memory. For five items, the multiplication idiom is probably better, but you might notice a resource problem if you had to repeat something, say,...
What is the purpose in Python's itertools.repeat?
9,059,173
12
2012-01-30T03:57:19Z
9,098,860
7
2012-02-01T15:51:04Z
[ "python", "python-3.x", "itertools" ]
Every use I can think of for Python's [`itertools.repeat()`](http://docs.python.org/py3k/library/itertools.html?highlight=repeat#itertools.repeat) class, I can think of another equally (possibly more) acceptable solution to achieve the same effect. For example: ``` >>> (i for i in itertools.repeat('example', 5)) ('exa...
The purpose of *itertools.repeat* is to supply a stream of constant values to be used with *map* or *zip*: ``` >>> list(map(pow, range(10), repeat(2))) # list of squares [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] ```
Equivalent C++ to Python generator pattern
9,059,187
49
2012-01-30T03:58:56Z
9,060,689
38
2012-01-30T07:34:31Z
[ "c++", "python", "generator", "yield", "coroutine" ]
I've got some example Python code that I need to mimic in C++. I do not require any specific solution (such as co-routine based yield solutions, although they would be acceptable answers as well), I simply need to reproduce the semantics in some manner. ## Python This is a basic sequence generator, clearly too large ...
Generators exist in C++, just under another name: *Input Iterators*. For example, reading from `std::cin` is similar to having a generator of `char`. You simply need to understand what a generator does: * there is a blob of data: the local variables define a *state* * there is an init method * there is a "next" metho...
Equivalent C++ to Python generator pattern
9,059,187
49
2012-01-30T03:58:56Z
12,735,970
29
2012-10-04T21:08:43Z
[ "c++", "python", "generator", "yield", "coroutine" ]
I've got some example Python code that I need to mimic in C++. I do not require any specific solution (such as co-routine based yield solutions, although they would be acceptable answers as well), I simply need to reproduce the semantics in some manner. ## Python This is a basic sequence generator, clearly too large ...
In C++ there are iterators, but implementing an iterator isn't straightforward: one has to consult the [iterator concepts](http://en.cppreference.com/w/cpp/concept/Iterator) and carefully design the new iterator class to implement them. Thankfully, Boost has an [iterator\_facade](http://www.boost.org/doc/libs/1_55_0/li...
Can I get the local variables of a Python function from which an exception was thrown?
9,059,349
11
2012-01-30T04:28:01Z
9,059,407
15
2012-01-30T04:39:48Z
[ "python", "exception-handling" ]
I'm writing a custom logging system for a project. If a function throws an exception, I want to log its local variables. Is it possible to access the raising function's local variables from the except block that caught the exception? For example: ``` def myfunction(): v1 = get_a_value() raise Exception() try:...
It's generally cleaner design to pass the value to the exception, if you know that your exception handling code is going to need it. However, if you're writing a debugger or something like that, where you will need to access variables without knowing which ones they are in advance, you *can* access an arbitrary variabl...
(Python) Use a library locally instead of installing it
9,059,699
27
2012-01-30T05:21:37Z
9,059,783
39
2012-01-30T05:32:51Z
[ "python", "import", "module" ]
**Script:** I've written a script in python that occasionally sends tweets to twitter It only uses one library called: [tweepy](https://github.com/tweepy/tweepy) after installing the library it works, great. **Problem:** I would like to host the script on a server where I do not have privileges to install anyt...
There are a few possibilities: If you already know how to install Python modules, the default `distutils` setup already includes a per-user installation option. Just run `python setup.py install --user` instead of `python setup.py install`. This is the easiest, since this does not necessitate the addition of any sourc...
List comprehension without [ ] in Python
9,060,653
44
2012-01-30T07:29:48Z
9,060,686
33
2012-01-30T07:34:03Z
[ "python", "list-comprehension" ]
Joining a list: ``` >>> ''.join([ str(_) for _ in xrange(10) ]) '0123456789' ``` `join` must take an iterable. Apparently, `join`'s argument is `[ str(_) for _ in xrange(10) ]`, and it's a [list comprehension](https://en.wikipedia.org/wiki/List_comprehension). Look at this: ``` >>>''.join( str(_) for _ in xrange(1...
``` >>>''.join( str(_) for _ in xrange(10) ) ``` This is called a *generator expression*, and is explained in [PEP 289](http://www.python.org/dev/peps/pep-0289/). The main difference between generator expressions and list comprehensions is that the former don't create the list in memory. Note that there's a third wa...
List comprehension without [ ] in Python
9,060,653
44
2012-01-30T07:29:48Z
9,061,024
78
2012-01-30T08:13:54Z
[ "python", "list-comprehension" ]
Joining a list: ``` >>> ''.join([ str(_) for _ in xrange(10) ]) '0123456789' ``` `join` must take an iterable. Apparently, `join`'s argument is `[ str(_) for _ in xrange(10) ]`, and it's a [list comprehension](https://en.wikipedia.org/wiki/List_comprehension). Look at this: ``` >>>''.join( str(_) for _ in xrange(1...
The other respondents were correct in answering that you had discovered a [generator expression](http://www.python.org/dev/peps/pep-0289/) (which has a notation similar to list comprehensions but without the surrounding square brackets). In general, genexps (as they are affectionately known) are more memory efficient ...
How to read aloud Python List Comprehensions?
9,061,760
18
2012-01-30T09:30:23Z
9,061,815
29
2012-01-30T09:34:50Z
[ "python", "list-comprehension" ]
My question is about Python **List Comprehension** readability. When I come across code with complex/nested list comprehensions, I find that I have to re-read them several times in order to understand the intent. Is there an intuitive way to read aloud list comprehensions? Seems like I should start "reading" from the ...
I usually unfold it in my mind into a generating loop, so for example ``` [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y] ``` is the list comprehension for the generator ``` for x in [1,2,3]: for y in [3,1,4]: if x != y: yield (x, y) ``` --- ## Example #1 `[x for b in a for x in b]` i...
Counterpart to PHP’s preg_match in Python
9,061,844
7
2012-01-30T09:37:20Z
9,061,866
10
2012-01-30T09:39:32Z
[ "php", "python", "regex", "preg-match" ]
I am planning to move one of my scrapers to Python. I am comfortable using `preg_match` and `preg_match_all` in PHP. I am not finding a suitable function in Python similar to `preg_match`. Could anyone please help me in doing so? For example, if I want to get the content between `<a class="title"` and `</a>`, I use th...
You looking for python's [re module](http://docs.python.org/library/re.html). Take a look at [re.findall](http://docs.python.org/library/re.html#re.findall) and [re.search](http://docs.python.org/library/re.html#re.search). And as you have mentioned you are trying to parse html use `html parsers` for that. There are ...
python's re: replace regex to regex
9,062,141
2
2012-01-30T10:02:12Z
9,062,228
7
2012-01-30T10:09:09Z
[ "python", "regex" ]
I have to replace text with text which was found. Smth like this: ``` regex = u'barbar' oldstring = u'BarBaR barbarian BarbaRONt' pattern = re.compile(regex, re.UNICODE | re.DOTALL | re.IGNORECASE) newstring = pattern.sub(.....) print(newstring) # And here is what I want to see >>> u'TEXT1BarBaRTEXT2 TEXT1barbarTEXT2i...
You can use capturing group for that: ``` regex = u'(barbar)' ... pattern.sub('TEXT1\\1TEXT2', oldstring) # => u'TEXT1BarBaRTEXT2 TEXT1barbarTEXT2ian TEXT1BarbaRTEXT2ONt' ``` Taking `barbar` into parenthesis makes regexp to capture every part of the string that matches this part of the regexp into a group. As it's th...
Why does python use both reference counting and mark-and-sweep for gc?
9,062,209
14
2012-01-30T10:08:00Z
9,062,281
12
2012-01-30T10:13:43Z
[ "python", "garbage-collection" ]
My question is why does python use both reference counting and mark-and-sweep for gc? Why not only mark-and-sweep? My initial guess is that using reference counting can easily remove non-cyclic referenced objects, this may somewhat speed up mark-and-sweep and gain memory immediately. Don't know if my guess is right? ...
**Reference counting deallocates objects sooner than garbage collection.** But as reference counting can't handle reference cycles between unreachable objects, Python uses a garbage collector (really just a cycle collector) to collect those cycles when they exist.
Why does python use both reference counting and mark-and-sweep for gc?
9,062,209
14
2012-01-30T10:08:00Z
9,063,805
10
2012-01-30T12:22:03Z
[ "python", "garbage-collection" ]
My question is why does python use both reference counting and mark-and-sweep for gc? Why not only mark-and-sweep? My initial guess is that using reference counting can easily remove non-cyclic referenced objects, this may somewhat speed up mark-and-sweep and gain memory immediately. Don't know if my guess is right? ...
Python (the language) doesn't say which form of garbage collection it uses. The main implementation (often known as CPython) acts as you describe. Other versions such as Jython or IronPython use a purely garbage collected system. Yes, there is a benefit of earlier collection with reference counting, but the main reaso...
What is the internal precision of numpy.float128?
9,062,562
18
2012-01-30T10:38:41Z
9,064,080
7
2012-01-30T12:45:24Z
[ "python", "c", "numpy" ]
What precision does numpy.float128 map to internally? Is it \_\_float128 or long double? (or something else entirely!?) A potential follow on question if anybody knows: is it safe in C to cast a \_\_float128 to a (16 byte) long double, with just a loss in precision? (this is for interfacing with a C lib that operates ...
It's quite recommendend to use [longdouble instead of float128](http://mail.scipy.org/pipermail/scipy-dev/2008-March/008562.html), since it's quite [a mess](http://comments.gmane.org/gmane.comp.python.numeric.general/46380), ATM. Python will cast it to float64 during initialisation. Inside numpy, it can be a double or...
What is the internal precision of numpy.float128?
9,062,562
18
2012-01-30T10:38:41Z
17,023,995
27
2013-06-10T12:33:05Z
[ "python", "c", "numpy" ]
What precision does numpy.float128 map to internally? Is it \_\_float128 or long double? (or something else entirely!?) A potential follow on question if anybody knows: is it safe in C to cast a \_\_float128 to a (16 byte) long double, with just a loss in precision? (this is for interfacing with a C lib that operates ...
`numpy.longdouble` refers to whatever type your C compiler calls [`long double`](https://en.wikipedia.org/wiki/Long_double). Currently, this is the *only* extended precision floating point type that numpy supports. On x86-32 and x86-64, this is an [80-bit floating point type](https://en.wikipedia.org/wiki/Extended_pre...
os.walk() in reverse?
9,062,601
9
2012-01-30T10:41:23Z
9,062,668
14
2012-01-30T10:47:57Z
[ "python" ]
When I run `os.walk()`, I get my results in alphanumeric order; starting from 0, ending at z. Is it possible to reverse this? So if I have 3 directories; `apple/`, `bananas/`, `pears/`, I would want `pears/`, `bananas/` and `apples/` returned. Obviously I could store all the dirs as a list and then `.reverse()` but t...
First of all, [`os.walk()`](http://docs.python.org/library/os.html#os.walk) does not specify the order in which the directories are returned, so if I were you I wouldn't rely on the alphabetic order. Having said that, you can choose the order in which the subdirectories are traversed by leaving [`topdown`](http://docs...
Why does Python segfault when attempting to call environ using ctypes on libc?
9,062,638
6
2012-01-30T10:44:36Z
9,062,779
7
2012-01-30T10:57:56Z
[ "python", "linux", "ctypes" ]
Tested this both on Ubuntu and ArchLinux, I get ``` from ctypes import * libc = CDLL('libc.so.6') libc.environ() Segmentation fault ``` Why?
If i read the manpage correctly, `environ` is a `char**`, not a function. If you want to get the environ var, according to [this post](http://stackoverflow.com/questions/544173/mapping-a-global-variable-from-a-shared-library-with-ctypes), you could do: ``` from ctypes import * libc = CDLL('libc.so.6') environ = c_char...
Matplotlib - labelling points (x,y) on a line with a value z
9,063,419
6
2012-01-30T11:49:20Z
9,067,421
21
2012-01-30T16:44:35Z
[ "python", "label", "matplotlib" ]
I'm trying to make a 2d plot using pyplot. I'm reading in a file with several columns, each of which contains around 100 values between 1 and 10. I'm plotting column 5 against column 6, which is fine. What I also want to do is label the resulting line with integer values from column 0. So the line will have 11 points ...
From your question, I'm not 100% clear exactly what you're wanting to do. Do you just want to label every vertex in a line? Or do you only want to label vertices that are integers? Or do you want to interpolate where integer "crossings" would line along the line and label those? First off, for loading your text file,...
Python Twisted proxy - how to intercept packets
9,063,583
7
2012-01-30T12:03:30Z
9,065,590
9
2012-01-30T14:41:47Z
[ "python", "http", "twisted", "packet", "intercept" ]
I'm trying to print out the body of a HTTP response using Python. Here is my code sofar: ``` from twisted.web import proxy, http from twisted.internet import reactor from twisted.python import log import sys log.startLogging(sys.stdout) class ProxyFactory(http.HTTPFactory): protocol=proxy.Proxy reactor.listenTCP...
Override the [dataReceived](http://twistedmatrix.com/documents/current/api/twisted.internet.protocol.Protocol.html#dataReceived) method of a protocol (proxy.Proxy in your case) and handle the data modification in that method: ``` from twisted.web import proxy, http from twisted.internet import reactor from twisted.pyt...
How to debug: Internal Error current transaction is aborted, commands ignored until end of transaction block
9,064,018
12
2012-01-30T12:41:31Z
9,064,582
26
2012-01-30T13:25:39Z
[ "python", "django", "postgresql", "postgis", "geodjango" ]
Hi Stackoverflow people, I do my first steps with GeoDjango and I am looking for better options to check faulty sql statements. So far, I simply wanted to safe a lng+lat point in my postgresql table. The model is defined with: ``` geolocation = models.PointField(_('Geo Location'), geography=Tru...
In most cases this means that the **previous** SQL statement failed to execute. In this case you should: 1. **Enable SQL [logging](https://docs.djangoproject.com/en/dev/topics/logging/#id1)**, see the following snippet to paste in settings.py 2. **Set DEBUG=1**, or SQL won't be logged 3. **Run runserver again**, and y...
Installing PyGtk in virtualenv
9,064,289
30
2012-01-30T13:01:52Z
17,126,095
11
2013-06-15T17:22:29Z
[ "python", "matplotlib", "pygtk", "virtualenv" ]
So I am trying to run a simple matplotlib example in my virtualenv (in the console). Here's the code: ``` import matplotlib matplotlib.use('GTKAgg') import matplotlib.pyplot as plt radius = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0] area = [3.14159, 12.56636, 28.27431, 50.26544, 78.53975, 113.09724] plt.plot(radius, area) plt.sho...
The trick is to manually set the correct paths and then run configure inside the virtualenv. This is quite basic, but it worked for me. Install cairo in the virtual env: ``` wget http://cairographics.org/releases/py2cairo-1.10.0.tar.bz2 tar -xf py2cairo-1.10.0.tar.bz2 cd py2cairo* ./waf configure --prefix=/home/PATH/...
Why do hyphens in module names generate syntax error?
9,064,324
3
2012-01-30T13:04:39Z
9,064,377
7
2012-01-30T13:10:18Z
[ "python", "syntax" ]
I'm using python 2.6 and get the following when importing a module: ``` File "./test-nmea-uploader.py", line 11 import nmea-uploader as sut ^ SyntaxError: invalid syntax ``` Why is that so? The python style guide seems to hold no mention about using hyphens in names, although it suggest the use o...
Identifiers cannot contain hyphens. This is not a question of style, but a part of the language syntax, see <http://docs.python.org/reference/lexical_analysis.html#identifiers> > Identifiers (also referred to as names) are described by the following lexical definitions: ``` identifier ::= (letter|"_") (letter | digi...
Why do hyphens in module names generate syntax error?
9,064,324
3
2012-01-30T13:04:39Z
9,064,413
8
2012-01-30T13:13:26Z
[ "python", "syntax" ]
I'm using python 2.6 and get the following when importing a module: ``` File "./test-nmea-uploader.py", line 11 import nmea-uploader as sut ^ SyntaxError: invalid syntax ``` Why is that so? The python style guide seems to hold no mention about using hyphens in names, although it suggest the use o...
According to <http://docs.python.org/reference/lexical_analysis.html#identifiers>, any identifier must **start** with a lowercase/uppercase letter or an underscore and **contain** lowercase/uppercase letters, numbers or an underscore. Package names are identifiers, so they are bound to the same rules. In addition, `n...
How do I simulate an AJAX request with Flask test client?
9,064,725
12
2012-01-30T13:37:30Z
9,065,860
18
2012-01-30T14:59:09Z
[ "python", "ajax", "unit-testing", "flask" ]
Testing Flask applications is done with: ``` # main.py from flask import Flask, request app = flask.Flask(__name__) @app.route('/') def index(): s = 'Hello world!', 'AJAX Request: {0}'.format(request.is_xhr) print s return s if __name__ == '__main__': app.run() ``` Then here is my test script: ```...
Try this:- ``` def test_index(): tester = app.test_client() response = tester.get('/', headers=[('X-Requested-With', 'XMLHttpRequest')]) assert 'Hello world!' in response.data ```
How to separate a Python list into two lists, according to some aspect of the elements
9,065,340
3
2012-01-30T14:26:42Z
9,065,395
8
2012-01-30T14:30:20Z
[ "python" ]
I have a list like this: ``` [[8, "Plot", "Sunday"], [1, "unPlot", "Monday"], [12, "Plot", "Monday"], [10, "Plot", "Tuesday"], [4, "unPlot", "Tuesday"], [14, "Plot", "Wednesday"], [6, "unPlot", "Wednesday"], [1, "unPlot", "Thursday"], [19, "Plot", "Thursday"], [28, "Plot", "Friday"], [10, "unPlot", "Friday"], [3, "unP...
Try with basic list comprehension: ``` >>> [ x for x in l if x[1] == "Plot" ] [[8, 'Plot', 'Sunday'], [12, 'Plot', 'Monday'], [10, 'Plot', 'Tuesday'], [14, 'Plot', 'Wednesday'], [19, 'Plot', 'Thursday'], [28, 'Plot', 'Friday']] >>> [ x for x in l if x[1] == "unPlot" ] [[1, 'unPlot', 'Monday'], [4, 'unPlot', 'Tuesday']...
python replace list values using a tuple
9,067,043
3
2012-01-30T16:18:40Z
9,067,205
10
2012-01-30T16:29:03Z
[ "python", "list" ]
If I have a list: ``` my_list = [3,2,2,3,4,1,3,4] ``` and a tuple ``` my_tuple = (3,5) ``` What's the best way of replacing elements in `my_list` using the tuple: ``` result = [5,2,2,5,4,1,5,4] ``` e.g. ``` for item in my_list: if(item == my_tuple[0]): item = my_tuple[1] ``` More generally, I would ...
The more natural data structure for `my_tuple` is a dictionary. Consider something like this and use the `.get()` method: ``` >>> my_lists = [[3,2,2,3,4,1,3,4], [1,2,3,4,5,6]] >>> my_tuple_list = [(3,5), (6, 7)] >>> my_dict = dict(my_tuple_list) >>> my_dict {3: 5, 6: 7} >>> my_lists = [[my_dict.get(x,x) for x in somel...
Python: File doesn't read whole file, io.FileIO does - why?
9,068,980
6
2012-01-30T18:39:45Z
9,069,009
11
2012-01-30T18:41:38Z
[ "python", "io" ]
The following code, executed in python 2.7.2 *on windows*, only reads in a fraction of the underlying file: ``` import os in_file = open(os.path.join(settings.BASEPATH,'CompanyName.docx')) incontent = in_file.read() in_file.close() ``` while this code works just fine: ``` import io import os in_file = io.FileIO(os...
You need to open the file in binary mode, or the `read()` will stop at the first EOF character it finds. And a `docx` is a ZIP file which is guaranteed to contain such a character somewhere. Try ``` in_file = open(os.path.join(settings.BASEPATH,'CompanyName.docx'), "rb") ``` `FileIO` reads [raw bytestreams](http://d...
Does passing reverse=True when sorting a list in Python affect efficiency?
9,069,298
10
2012-01-30T19:06:32Z
9,069,429
7
2012-01-30T19:17:09Z
[ "python", "performance", "sorting", "reverse", "time-complexity" ]
When calling `sort()` on a list in Python, passing `cmp=f` slows down the sort. Does passing `reverse=True` affect the efficiency of the sort in any way (or is it identical to sorting without reversing)?
From my benchmarks, there appears to be a small difference: ``` import timeit setup = """ import random random.seed(1) l = range(10000) random.shuffle(l) """ run1 = """ sorted(l) """ run2 = """ sorted(l, reverse=True) """ n1 = timeit.timeit(run1, setup, number=10000) n2 = timeit.timeit(run2, setup, number=10000) ...
Learn Python the Hard Way: Exercise 46
9,069,465
2
2012-01-30T19:20:44Z
9,069,484
7
2012-01-30T19:22:25Z
[ "python" ]
I am having trouble setting up my project skeleton because now the guide is asking me to use Linux only commands and I'm on Windows. This entire guide up until this project has had no compatibility issues with Windows until a line of code in exercise 46. I was able to do this: ``` $ mkdir -p projects $ cd projects/ $...
To `touch` a file is to simply create an empty file with that name. Use notepad and save a file with the name with no contents in it, making sure that you are in the proper directory. For an answer to why would you want the `__init__.py` file in the first place, see [this question](http://stackoverflow.com/questions/4...
Python-style collections in F#
9,069,560
3
2012-01-30T19:28:49Z
9,069,844
9
2012-01-30T19:49:55Z
[ "python", "collections", "f#" ]
I'm trying to refactor some python code which I'm using for financial analytics processing into F#, and I'm having difficulty in replicating some of my beloved Python datatypes. For instance in Python I could happily declare a variable like this: ``` timeSeries = { "20110131":1.5, "20110228":1.5, "20110331":1.5, ...
To be honest, your dictionary declaration in Python doesn't look much different from what you can declare in F#: ``` let timeSeries = dict [ "20110131", 1.5; // ',' is tuple delimiter and ';' is list delimiter "20110228", 1.5; "20110331", 1.5; "20110431", 1.5; ...
How can I install PIL on mac os x 10.7.2 Lion
9,070,074
38
2012-01-30T20:07:48Z
9,070,549
84
2012-01-30T20:47:38Z
[ "python", "osx", "python-imaging-library" ]
I've tried googling & looking up some other people's questions. However, I still couldn't find a clear/simple recipe to install PIL (for python 2.6 or 2.7) on mac os x 10.7.2 Lion.
If you use [homebrew](http://brew.sh/), you can install the PIL with just `brew install pil`. You may then need to add the install directory (`$(brew --prefix)/lib/python2.7/site-packages`) to your PYTHONPATH, or add the location of PIL directory itself in a file called `PIL.pth` file in any of your site-packages direc...
How can I install PIL on mac os x 10.7.2 Lion
9,070,074
38
2012-01-30T20:07:48Z
11,368,029
24
2012-07-06T18:50:33Z
[ "python", "osx", "python-imaging-library" ]
I've tried googling & looking up some other people's questions. However, I still couldn't find a clear/simple recipe to install PIL (for python 2.6 or 2.7) on mac os x 10.7.2 Lion.
This is something I wrote for the folks at work. It's a full workup for getting a clean OSX Lion working virtualenv using django + git + some other stuff: <https://gist.github.com/1781374> The most important lines for you are: Install libjpeg (PIL req) ``` curl -O http://www.ijg.org/files/jpegsrc.v8c.tar.gz tar -xv...
How can I install PIL on mac os x 10.7.2 Lion
9,070,074
38
2012-01-30T20:07:48Z
11,368,030
12
2012-07-06T18:50:36Z
[ "python", "osx", "python-imaging-library" ]
I've tried googling & looking up some other people's questions. However, I still couldn't find a clear/simple recipe to install PIL (for python 2.6 or 2.7) on mac os x 10.7.2 Lion.
One way is via [Macports](http://www.macports.org/) Install the base macports as per the [installation guide](http://www.macports.org/install.php) Then install the py27-pil port by `port install py27-pil` You will then need to use the python installed by macports by using `port select --set python python27` I find ...
store each class in a separate file python
9,070,081
4
2012-01-30T20:08:37Z
9,070,173
7
2012-01-30T20:15:28Z
[ "python", "import", "module" ]
I'm looking into organizing my modules and classes. All the time I collect my related classes in a relevant module so I can do things like: ``` from vehicles.car import engine ``` In directory vehicles there is a file named car which contains class engine. Clear. Now I'm looking into the possibility that I can store...
Create a directory called `filters`, and files `filters/__init__.py` and `filters/air.py`. In `filters/__init__.py`, have: `from air import air`, and in `filters/air.py`, define the class `air`. Then: ``` $ python Python 2.7.1+ (r271:86832, Apr 11 2011, 18:05:24) [GCC 4.5.2] on linux2 Type "help", "copyright", "cre...
Error when trying to install pylibmc on Mac OSX Lion
9,070,218
15
2012-01-30T20:19:24Z
9,074,361
18
2012-01-31T04:25:16Z
[ "python", "osx-lion", "pip", "easy-install", "llvm-gcc" ]
I've tried pip and easy\_install, but I keep getting the following error: error: command '/usr/bin/llvm-gcc' failed with exit status 1 I'm running OSX Lion and the install runs inside a virtualenv, with Python 2.7.2. Thanks in advance.
First a question: is libmemcached installed? If not, install it and retry. It probably is but just in case.... If pylibmc still doesn't install the problem is probably that libmemcached is not installed in a directory where gcc can discover it (this was a macports symptom in my case), in which case you can store the l...
Error when trying to install pylibmc on Mac OSX Lion
9,070,218
15
2012-01-30T20:19:24Z
9,530,311
22
2012-03-02T08:43:02Z
[ "python", "osx-lion", "pip", "easy-install", "llvm-gcc" ]
I've tried pip and easy\_install, but I keep getting the following error: error: command '/usr/bin/llvm-gcc' failed with exit status 1 I'm running OSX Lion and the install runs inside a virtualenv, with Python 2.7.2. Thanks in advance.
it may caused by the libmemcached is not installed. You should install libevent & memcache & libmemcached first before you are trying install the pylibmc. If you are using homebrew, you can use it to finish the progress of install the dependency of the libmemcached. like this: > ``` > brew install libmemcached > ```
numpy/scipy/ipython:Failed to interpret file as a pickle
9,070,306
6
2012-01-30T20:26:14Z
9,070,381
9
2012-01-30T20:33:31Z
[ "python", "numpy", "matplotlib", "scipy", "ipython" ]
I have the file in following format: ``` 0,0.104553357966 1,0.213014562052 2,0.280656379048 3,0.0654249076288 4,0.312223429689 5,0.0959008911106 6,0.114207780917 7,0.105294501195 8,0.0900673766572 9,0.23941317105 10,0.0598239513149 11,0.541701803956 12,0.093929580526 ``` I want to plot these point using ipython plot ...
The [`numpy.load`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.load.html) routine is for loading pickled `.npy` or `.npz` binary files, which can be created using [`numpy.save`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.save.html) and [`numpy.savez`](http://docs.scipy.org/doc/numpy/referen...
What does var,_ = something mean in Python? String concatenation?
9,070,323
5
2012-01-30T20:28:27Z
9,070,347
12
2012-01-30T20:30:30Z
[ "python", "variables" ]
I am learning Python and am reading through an example script that includes some variable definitions that look like: ``` output,_ = call_command('git status') output,_ = call_command('pwd') def call_command(command): process = subprocess.Popen(command.split(' '), stdout=subprocess.PIPE, stderr=su...
The general form ``` a, b = x, y ``` is *tuple assignment*. The corresponding parts are assigned, so the above is equivalent to: ``` a = x b = y ``` In your case, `call_command()` returns a tuple of two elements (which is what `process.communicate()` returns). You're assigning the first one to `output` and the seco...
ssh first with mysqldb in python
9,070,708
4
2012-01-30T21:01:33Z
9,071,002
8
2012-01-30T21:27:00Z
[ "python", "mysql", "ssh", "mysql-python" ]
I'm trying to connect to a MySQL database on a remote server using MySQLdb in python. The problem is that first I need to SSH into the host, and then from there, I need to connect to the MySQL server. The problem I'm having, though, is that MySQLdb does not seem to have a way of establishing an SSH connection before co...
Setup an ssh tunnel before you use MySQLdb.connect. The tunnel will make it appear as though you have the mysql running locally, set it up something like this ``` ssh user@host.com -L 9990:localhost:3306 ``` here your local port 9990 will bind to 3306 on the remote host, -L stands for local, then 9990:localhost:3306 ...
Polar contour plot in matplotlib - best (modern) way to do it?
9,071,084
13
2012-01-30T21:33:58Z
9,083,017
15
2012-01-31T16:20:59Z
[ "python", "numpy", "matplotlib" ]
**Update:** I've done a full write-up of the way I found to do this on my blog at <http://blog.rtwilson.com/producing-polar-contour-plots-with-matplotlib/> - you may want to check there first. I'm trying to plot a polar contour plot in matplotlib. I've found various resources on the internet, (a) I can't seem to get m...
You should just be able to use `ax.contour` or `ax.contourf` with polar plots just as you normally would... You have a few bugs in your code, though. You convert things to radians, but then use the values in degrees when you plot. Also, you're passing in `r, theta` to contour when it expects `theta, r`. As a quick exa...
How can I check if a string contains ANY letters from the alphabet?
9,072,844
28
2012-01-31T00:29:55Z
9,072,862
38
2012-01-31T00:31:50Z
[ "python" ]
What is best pure Python implementation to check if a string contains ANY letters from the alphabet? ``` string_1 = "(555).555-5555" string_2 = "(555) 555 - 5555 ext. 5555 ``` Where `string_1` would return `False` for having no letters of the alphabet in it and `string_2` would return `True` for having letter.
How about: ``` >>> string_1 = "(555).555-5555" >>> string_2 = "(555) 555 - 5555 ext. 5555" >>> any(c.isalpha() for c in string_1) False >>> any(c.isalpha() for c in string_2) True ```
How can I check if a string contains ANY letters from the alphabet?
9,072,844
28
2012-01-31T00:29:55Z
9,072,937
37
2012-01-31T00:42:18Z
[ "python" ]
What is best pure Python implementation to check if a string contains ANY letters from the alphabet? ``` string_1 = "(555).555-5555" string_2 = "(555) 555 - 5555 ext. 5555 ``` Where `string_1` would return `False` for having no letters of the alphabet in it and `string_2` would return `True` for having letter.
Regex should be a fast approach: ``` re.search('[a-zA-Z]', the_string) ```
IOError: "decoder zip not available" using matplotlib PNG in ReportLab on Linux, works on Windows
9,073,455
6
2012-01-31T01:55:00Z
9,073,732
12
2012-01-31T02:44:34Z
[ "python", "png", "python-imaging-library", "reportlab" ]
I'm using ReportLab to print a chart produced by matplotlib. I'm able to do this on my Windows development machine without trouble. When I deploy to a Ubuntu server, however, the rendering fails with the error described. I assume I'm missing a Python module, but I don't know which one. I believe the versions of Python...
Apparently PIL setup.py doesn't know how to find libz.so. PIL expects `libz.so` to be located in `/usr/lib` not `/usr/lib/i386-linux-gnu/libz.so`. To fix the problem 1) Find the location of your systems libz.so using `find . -name libz.so`. 2) Create a soft link from libz.so to /usr/lib using `sudo ln -s /usr/lib/i3...
All tkinter functions run when program starts
9,073,817
2
2012-01-31T02:59:47Z
9,073,868
7
2012-01-31T03:09:09Z
[ "python", "function", "tkinter" ]
I am having a very weird problem that I've never had before when using tkinter. Anywhere that I set a command for a widget such as a button or a menu item, the command runs when the application starts up. Basically the command doesn't wait until the widget is clicked to run. In my code, I know that I did not pack the b...
``` filemenu.add_command(label="Open...", command=self.open()) filemenu.add_command(label="New...", command=self.new()) filemenu.add_command(label="Open...", command=self.open()) filemenu.add_command(label="Save", command=self.save()) ``` In these lines, you have to pass the reference to the functions. You are actuall...
All tkinter functions run when program starts
9,073,817
2
2012-01-31T02:59:47Z
9,073,872
12
2012-01-31T03:09:53Z
[ "python", "function", "tkinter" ]
I am having a very weird problem that I've never had before when using tkinter. Anywhere that I set a command for a widget such as a button or a menu item, the command runs when the application starts up. Basically the command doesn't wait until the widget is clicked to run. In my code, I know that I did not pack the b...
Remove the `()`s in your command definitions. Right now, you are calling the function and binding the return values to `command` parameter whereas you need to bind the functions itself so that later on they could be called. So a line like this: ``` filemenu.add_command(label="New...", command=self.new()) ``` should ...
matplotlib: how to annotate point on a scatter automatically placed arrow?
9,074,996
19
2012-01-31T05:46:01Z
9,082,675
29
2012-01-31T16:00:09Z
[ "python", "numpy", "matplotlib", "scipy" ]
if I make a scatter plot with matplotlib: ``` plt.scatter(randn(100),randn(100)) # set x, y lims plt.xlim([...]) plt.ylim([...]) ``` I'd like to annotate a given point `(x, y)` with an arrow pointing to it and a label. I know this can be done with `annotate`, but I'd like the arrow and its label to be placed "optimal...
Basically, no, there isn't. Layout engines that handle placing map labels similar to this are surprisingly complex and beyond the scope of matplotlib. (Bounding box intersections are actually a rather poor way of deciding where to place labels. What's the point in writing a ton of code for something that will only wor...
Using INSERT with a PostgreSQL Database using Python
9,075,349
13
2012-01-31T06:28:17Z
9,075,548
15
2012-01-31T06:49:06Z
[ "python", "postgresql", "psycopg2" ]
I am trying to insert data into a PostgreSQL database table using Python. I don't see any syntax errors but, for some reason, my data isn't getting inserted into the database. ``` conn = psycopg2.connect(connection) cursor = conn.cursor() items = pickle.load(open(pickle_file,"rb")) for item in items: city = item[...
You have to commit the transaction. ``` conn.commit() ``` If there's no reason to think the transaction will fail, it's faster to commit after the for loop finishes.
How to use __call__?
9,075,771
3
2012-01-31T07:14:40Z
9,075,801
8
2012-01-31T07:17:05Z
[ "python" ]
For example, I need for class calling returns string. ``` class Foo(object): def __init__(self): self.bar = 'bar' def __call__(self): return self.bar ``` `Foo` calling returns `Foo object`. ``` Foo() <__main__.Foo object at 0x8ff6a8c> ``` What should I do to class returns string or other? H...
With your example (of limited usefulness), you have a class of callable objects. You can do now, as you have done, ``` >>> o = Foo() >>> o <__main__.Foo object at 0x8ff6a8c> >>> o() 'bar' ``` I. e., `__call__()` does not make your class callable (as it is already), but it gives you a callable object.
Qt/PyQt: How do I create a drop down widget, such as a QLabel, QTextBrowser, etc.?
9,076,332
4
2012-01-31T08:12:35Z
9,084,583
12
2012-01-31T18:02:02Z
[ "python", "qt", "drop-down-menu", "widget", "pyqt" ]
How do I create a drop-down widget, such as a drop-down QLabel, drop-down QTextBrowser, etc.? For example, I log information in a QTextBrowser, but I don't want it taking up space on the screen. So I want to be able to click a QToolbutton and have a scrollable QTextBrowser drop-down. (A QComboBox would work too, but I...
Create a [QWidgetAction](http://developer.qt.nokia.com/doc/qt-4.8/qwidgetaction.html) for the drop-down widget, and add it to the tool-button's [menu](http://developer.qt.nokia.com/doc/qt-4.8/qtoolbutton.html#setMenu): ``` from PyQt4 import QtGui, QtCore class Window(QtGui.QWidget): def __init__(self): Qt...
Should I use a class? (Python)
9,076,348
3
2012-01-31T08:14:10Z
9,076,432
7
2012-01-31T08:22:57Z
[ "python", "oop", "class" ]
I'm trying to write a small Python module which contain some mathematical functions. For example, it might contain a function like: ``` def quad(x, a, b, c): return a*x**2 + b*x + c ``` As you may notice it contains several parameters (viz. `a, b, c`) apart from the variable `x`. Now if I were to put this in a fi...
That seems like a perfectly reasonable use of a class. Essentially you should consider using a class when your program involves things that can be modelled as objects with state. Here, the "state" of your polynomial is just the coefficients `a`, `b`, and `c`. You can also use Python's `__call__` special method to allo...
Why use Celery instead of RabbitMQ?
9,077,687
17
2012-01-31T10:08:39Z
9,077,760
12
2012-01-31T10:14:26Z
[ "python", "message-queue", "rabbitmq", "celery" ]
From my understanding, Celery is a distributed task queue, which means the only thing that it should do is dispatching tasks/jobs to others servers and get the result back. RabbitMQ is a message queue, and nothing more. However, a worker could just listen to the MQ and execute the task when a message is received. This ...
Celery basically provides a nice interface to doing just what you said, and deals with all the configuration for you. Yes you could do it by hand, but you'd just be rewriting celery.
Why use Celery instead of RabbitMQ?
9,077,687
17
2012-01-31T10:08:39Z
9,287,371
19
2012-02-15T03:10:11Z
[ "python", "message-queue", "rabbitmq", "celery" ]
From my understanding, Celery is a distributed task queue, which means the only thing that it should do is dispatching tasks/jobs to others servers and get the result back. RabbitMQ is a message queue, and nothing more. However, a worker could just listen to the MQ and execute the task when a message is received. This ...
You are right, you don't need Celery at all. When you are designing a distributed system there are a lot of options and there is no right way to do things that fits all situations. Many people find that it is more flexible to have pools of message consumers waiting for a message to appear on their queue, doing some wo...
How to expose a property (virtual field) on a Django Model as a field in a TastyPie ModelResource
9,078,035
23
2012-01-31T10:33:50Z
9,078,225
32
2012-01-31T10:47:40Z
[ "python", "django", "django-models", "tastypie" ]
I have a property in a Django Model that I'd like to expose via a TastyPie ModelResource. My Model is ``` class UserProfile(models.Model): _genderChoices = ((u"M", u"Male"), (u"F", u"Female")) user = Models.OneToOneField(User, editable=False) gender = models.CharField(max_length=2, choices = _genderChoic...
You should be able to define it as a [field](http://readthedocs.org/docs/django-tastypie/en/latest/fields.html?highlight=fields) try: ``` class UserProfileResource(ModelResource): fullname = fields.CharField(attribute='_get_full_name', readonly=True) class Meta: queryset = models.UserProfile.objects.al...
Python module for storing and querying geographical coordinates
9,078,776
16
2012-01-31T11:31:44Z
9,078,861
14
2012-01-31T11:36:37Z
[ "python", "geolocation", "coordinates", "geospatial", "geographic-distance" ]
Is there a Python module where I can create objects with a geographical location coordinate (latitude and longitude), and query all the objects for ones which are within a 5km distance (i.e. radius) of a given coordinate? I've been trying to store the latitude and longitude as keys in dictionaries (as they're indexed ...
Yes, try [geopy](https://github.com/geopy/geopy). ``` import geopy import geopy.distance pt1 = geopy.Point(48.853, 2.349) pt2 = geopy.Point(52.516, 13.378) dist = geopy.distance.distance(pt1, pt2).km # 878.25 ``` afterwards you can query your lists of points: ``` [pt for pt in points if geopy.distance.distance(ori...
Plone 4: Passing arguments to view class (BrowserView)
9,079,019
6
2012-01-31T11:48:49Z
9,079,823
7
2012-01-31T12:52:11Z
[ "python", "plone" ]
I have been following [this URL](http://plone.org/documentation/kb/creating-a-custom-template-for-a-plone-content-type) to help me create template views using BrowserView. So far, it works OK and I am able to create a template with a view class. What I need to know is whether it is possible to pass arguments to method...
Yes. ``` <p tal:content="python:view.still_dreaming(item.publication_date)" /> ``` You can use TAL traversing syntax (default), Python syntax or String syntax in TAL expressions. <http://collective-docs.readthedocs.org/en/latest/functionality/expressions.html>
Detect Python version at runtime
9,079,036
26
2012-01-31T11:50:01Z
9,079,062
46
2012-01-31T11:52:08Z
[ "python" ]
I have a Python file which might have to support Python versions `< 3.x and > 3.x`. Is there a way to introspect the Python runtime to know the version in which it is running (for example, `2.6 or 3.2.x`)?
Sure, take a look at [`sys.version`](http://docs.python.org/library/sys.html#sys.version) and [`sys.version_info`](http://docs.python.org/library/sys.html#sys.version_info). For example, to check that you are running Python 3.x, use ``` import sys if sys.version_info[0] < 3: raise "Must be using Python 3" ``` He...
how to get around "Single '}' encountered in format string" when using .format and formatting in printing
9,079,540
5
2012-01-31T12:32:16Z
9,079,587
9
2012-01-31T12:35:24Z
[ "python" ]
I am currently trying to print a tabulated format (using left alignment and padding) for headings in a table however I keep getting the following error. ``` ValueError: Single '}' encountered in format string ``` Here's the line: ``` print("{0}:<15}{1}:<15}{2}:<8}".format("1", "2", "3")) ``` Required output is some...
Works: ``` >>> print("{0}:<15}}{1}:<15}}{2}:<8}}".format("1", "2", "3")) 1:<15}2:<15}3:<8} ``` **Edit:** Now I understand you. Do this: ``` print("{0:<15}{1:<15}{2:<8}".format("1", "2", "3")) ``` Details: <http://www.python.org/dev/peps/pep-3101/>
Detect repetitions in string
9,079,797
18
2012-01-31T12:49:56Z
9,079,897
33
2012-01-31T12:57:44Z
[ "python", "regex" ]
I have a simple problem, but can't come with a simple solution :) Let's say I have a string. I want to detect if there is a repetition in it. I'd like: ``` "blablabla" # => (bla, 3) "rablabla" # => (bla, 2) ``` The thing is I don't know what pattern I am searching for (I don't have "bla" as input). Any idea? **...
``` import re def repetitions(s): r = re.compile(r"(.+?)\1+") for match in r.finditer(s): yield (match.group(1), len(match.group(0))/len(match.group(1))) ``` finds all non-overlapping repeating matches, using the shortest possible unit of repetition: ``` >>> list(repetitions("blablabla")) [('bla', 3)] >>...
Python scatter plot. Size and style of the marker
9,081,553
25
2012-01-31T14:50:00Z
9,082,596
19
2012-01-31T15:56:09Z
[ "python", "plot", "matplotlib", "scatter" ]
I have a set of data that I want to show as a scatter plot. I want each point to be plotted as a square of size `dx`. ``` x = [0.5,0.1,0.3] y = [0.2,0.7,0.8] z = [10.,15.,12.] dx = [0.05,0.2,0.1] scatter(x,y,c=z,s=dx,marker='s') ``` The problem is that the size `s` t...
If you want markers that resize with the figure size, you can use patches: ``` from matplotlib import pyplot as plt from matplotlib.patches import Rectangle x = [0.5, 0.1, 0.3] y = [0.2 ,0.7, 0.8] z = [10, 15, 12] dx = [0.05, 0.2, 0.1] cmap = plt.cm.hot fig = plt.figure() ax = fig.add_subplot(111, aspect='equal') f...
Python scatter plot. Size and style of the marker
9,081,553
25
2012-01-31T14:50:00Z
9,082,655
23
2012-01-31T15:58:48Z
[ "python", "plot", "matplotlib", "scatter" ]
I have a set of data that I want to show as a scatter plot. I want each point to be plotted as a square of size `dx`. ``` x = [0.5,0.1,0.3] y = [0.2,0.7,0.8] z = [10.,15.,12.] dx = [0.05,0.2,0.1] scatter(x,y,c=z,s=dx,marker='s') ``` The problem is that the size `s` t...
Translate from **user data** coordinate system to **display** coordinate system. and use edgecolors='none' to plot faces with no outlines. ``` import numpy as np fig = figure() ax = fig.add_subplot(111) dx_in_points = np.diff(ax.transData.transform(zip([0]*len(dx), dx))) scatter(x,y,c=z,s=dx_in_points**2,marker='s'...
Python scatter plot. Size and style of the marker
9,081,553
25
2012-01-31T14:50:00Z
24,567,352
17
2014-07-04T05:38:00Z
[ "python", "plot", "matplotlib", "scatter" ]
I have a set of data that I want to show as a scatter plot. I want each point to be plotted as a square of size `dx`. ``` x = [0.5,0.1,0.3] y = [0.2,0.7,0.8] z = [10.,15.,12.] dx = [0.05,0.2,0.1] scatter(x,y,c=z,s=dx,marker='s') ``` The problem is that the size `s` t...
I think we can do it better with a collection of patches. According to documents: > This (PatchCollection) makes it easier to assign a **color map** to a heterogeneous > collection of patches. > > This also may improve **plotting speed**, since PatchCollection will > draw faster than a large number of patches. Suppos...
How to upload files to Soundcloud using Python?
9,082,550
6
2012-01-31T15:53:16Z
9,252,094
7
2012-02-12T19:48:19Z
[ "python", "soundcloud" ]
I am building an application that would record what people say, generate an audio file and upload it to SoundCloud and get the URL of the uploaded track using Python. I used PyAudio to record and generate an audio file - a wave file. But I need to know how to upload the file to SoundCloud. By research I found there i...
We just released a new Python API wrapper. You can get it on [PyPi](http://pypi.python.org/pypi/soundcloud/) or from our [Github account](https://github.com/soundcloud/soundcloud-python). To upload a track, you'll want to first get an access token using one of the supported OAuth2 auth flows. You can read about that in...
Creating 2D coordinates map in Python
9,082,829
8
2012-01-31T16:09:22Z
9,082,878
11
2012-01-31T16:12:42Z
[ "python", "iterator", "coordinates" ]
I'm not looking for solution, I'm looking for a better solution or just a different way to do this by using some other kind of list comprehension or something else. I need to generate a list of tuples of 2 integers to get map coordinates like [(1, 1), (1, 2), ..., (x, y)] So I have the following: ``` width, height =...
Using [`itertools.product()`](http://docs.python.org/library/itertools.html#itertools.product): ``` from itertools import product coordinates = list(product(xrange(width), xrange(height))) ```
Leave arguments untouched with argparse
9,084,080
5
2012-01-31T17:28:12Z
9,085,530
11
2012-01-31T19:19:18Z
[ "python", "argparse" ]
I would like use argparse to parse the arguments that it knows and then leave the rest untouched. For example I want to be able to run ``` performance -o output other_script.py -a opt1 -b opt2 ``` Which uses the `-o` option and leaves the rest untouched. The module profiler.py does a similar thing with optparse, but...
You could also add a positional argument to your parser with `nargs=argparse.REMAINDER`, to capture the script and its options: ``` # In script 'performance'... p = argparse.ArgumentParser() p.add_argument("-o") p.add_argument("command", nargs=argparse.REMAINDER) args = p.parse_args() print args ``` Running the above...
Is wrapping C++ library with ctypes a bad idea?
9,084,111
8
2012-01-31T17:30:22Z
9,088,768
9
2012-01-31T23:43:33Z
[ "python", "ctypes", "boost-python" ]
I read through the following two threads on [wrapping C library](http://stackoverflow.com/questions/1942298/wrapping-a-c-library-in-python-c-cython-or-ctypes) and [C++ library](http://stackoverflow.com/questions/3100554/wrapping-c-dynamic-array-with-pythonctypes-segfault), I am not sure I get it yet. The C++ library I ...
For C++ a library to be accessible from Python it must use C export names, which basically means that a function named `foo` will be accessible from ctypes as `foo`. This can be achieved *only* by enclosing the public interface with `export C {}`, which in turn disallows function overloading and templates therein (onl...
Is wrapping C++ library with ctypes a bad idea?
9,084,111
8
2012-01-31T17:30:22Z
9,193,224
13
2012-02-08T12:22:41Z
[ "python", "ctypes", "boost-python" ]
I read through the following two threads on [wrapping C library](http://stackoverflow.com/questions/1942298/wrapping-a-c-library-in-python-c-cython-or-ctypes) and [C++ library](http://stackoverflow.com/questions/3100554/wrapping-c-dynamic-array-with-pythonctypes-segfault), I am not sure I get it yet. The C++ library I ...
In defence of `boost::python`, given Alexander's answer on ctypes: Boost python provides a *very* "c++" interface between c++ and python code - even doing things like allowed python subclasses of c++ classes to override virtual methods is relatively straightforward. Here's a potted list of good features: * Allow virt...
Sorting by multiple params in pyes and elasticsearch
9,084,536
7
2012-01-31T17:58:22Z
9,742,761
11
2012-03-16T18:38:26Z
[ "python", "sorting", "elasticsearch" ]
I can pass a single **sort** parameter to the search query in pyes like this: ``` s = MatchAllQuery() conn.search(query=Search(s), indexes=["test"], sort='_score') ``` But I need to pass an extra parameter to sort the docs with the same score, like this: ``` { "sort": [ "_score", { "extra_param": { ...
If you'd like the results in the result set with the same score to be ordered by price, append price to the sort string: ``` s = MatchAllQuery() conn.search(query=Search(s), indexes=["test"], sort='_score,price') ``` By default the sort order is ascending. To pass the sort order append **:asc** or **:desc** to the so...
How to copy a image region using opencv in python?
9,084,609
6
2012-01-31T18:04:13Z
9,085,008
31
2012-01-31T18:37:51Z
[ "python", "opencv" ]
I am trying to implement a license plate recognition software using the ideas from <http://iamabhik.wordpress.com/category/opencv/>. I implemented the plate location using opencv in python, using "import cv2". It works okay and now I need to copy the plate region to another image to do the segmentation of the characte...
Both cv.GetSubRect and ROI functions are available in Python, but in old `import cv` mode or `import cv2.cv`. ie use `cv2.cv.GetSubRect()` or `cv2.cv.SetImageROI` if you are familier with them. On the other hand, it is simple to set ROI without these functions due to numpy integration in new cv2. If (x1,y1) and (x2,y...
Symbol Table in Python
9,085,450
8
2012-01-31T19:13:10Z
9,085,562
7
2012-01-31T19:21:33Z
[ "python", "symbol-table" ]
How can we see the Symbol-Table of a python source code??? I mean , Python makes a symbol table for each program before actually running it,, So my question is how can I get that symbol-table as output???
Python is dynamic rather than static in nature. Rather than a symbol table as in compiled object code, the virtual machine has an addressible namespace for your variables. The `dir()` or `dir(module)` function returns the effective namespace at that point in the code. It's mainly used in the interactive interpreter bu...
Python regex match text between quotes
9,085,558
4
2012-01-31T19:21:21Z
9,085,630
9
2012-01-31T19:26:39Z
[ "python", "regex" ]
In the following script I would like to pull out text between the double quotes ("). However, the python interpreter is not happy and I can't figure out why... ``` import re text = 'Hello, "find.me-_/\\" please help with python regex' pattern = r'"([A-Za-z0-9_\./\\-]*)"' m = re.match(pattern, text) print m.group() `...
[`match`](http://docs.python.org/library/re.html#re.match) starts searching from the beginning of the text. Use [`search`](http://docs.python.org/library/re.html#re.search) instead: ``` #!/usr/bin/env python import re text = 'Hello, "find.me-_/\\" please help with python regex' pattern = r'"([A-Za-z0-9_\./\\-]*)"' ...
Most efficient way to parse a large .csv in python?
9,087,039
12
2012-01-31T21:13:26Z
9,087,864
15
2012-01-31T22:19:16Z
[ "python", "csv" ]
I tried to look on other answers but I am still not sure the right way to do this. I have a number of really large .csv files (could be a gigabyte each), and I want to first get their column labels, cause they are not all the same, and then according to user preference extract some of this columns with some criteria. B...
As pointed out several other times, the first two methods do no actual string parsing, they just read a line at a time without extracting fields. I imagine the majority of the speed difference seen in CSV is due to that. The CSV module is invaluable if you include any textual data that may include more of the 'standar...
Amazon SES SMTP Python Usage
9,087,158
8
2012-01-31T21:23:44Z
12,358,203
10
2012-09-10T19:28:44Z
[ "python", "smtp", "amazon-web-services", "amazon-ses" ]
I am trying to diagnose why sending email through Amazon SES is not working via python. The following example demonstrates the problem, where `user` and `pass` are set to the appropriate credentials. ``` >>> import smtplib >>> s = smtplib.SMTP_SSL("email-smtp.us-east-1.amazonaws.com", 465) >>> s.login(user, pw) Trace...
I don't think SMTP\_SSL works anymore with SES. One must use starttls() ``` smtp = smtplib.SMTP("email-smtp.us-east-1.amazonaws.com") smtp.starttls() smtp.login(SESSMTPUSERNAME, SESSMTPPASSWORD) smtp.sendmail(me, you, msg) ```
Show all possible groupings of a list, given only the amount of sublists (lengths are variable)
9,088,321
12
2012-01-31T22:59:06Z
9,088,578
7
2012-01-31T23:23:11Z
[ "python", "list", "math", "grouping" ]
## Problem *Step 1*: Given a list of numbers, generate all possible groupings (in order) given only the final number of desired groups. For example, if my list of numbers were 1 to 4, and I wanted 2 final groups, the possibilities would be: ``` [1], [2,3,4] [1,2], [3,4] [1,2,3], [4] ``` *Step 2*: Perform arithmet...
[Raymond Hettinger has written a recipe](http://code.activestate.com/recipes/576795/) for finding all partitions of an iterable into `n` groups: ``` import itertools import operator def partition_indices(length, groups, chain = itertools.chain): first, middle, last = [0], range(1, length), [length] for di...
SQLAlchemy cannot find a class name
9,088,957
16
2012-02-01T00:08:09Z
9,089,671
13
2012-02-01T01:48:23Z
[ "python", "sqlalchemy", "relationships" ]
Simplified, I have the following class structure (in a single file): ``` Base = declarative_base() class Item(Base): __tablename__ = 'item' id = Column(BigInteger, primary_key=True) # ... skip other attrs ... class Auction(Base): __tablename__ = 'auction' id = Column(BigInteger, primary_key=Tr...
This all turned out to be because of the way I've set SQLAlchemy up in Pyramid. Essentially you need to follow [this section](http://docs.pylonsproject.org/projects/pyramid_cookbook/en/latest/database/sqlalchemy.html#importing-all-sqlalchemy-models) to the letter and make sure you use the same `declarative_base` instan...
Get list item by attribute in Python
9,089,043
10
2012-02-01T00:18:53Z
9,089,058
7
2012-02-01T00:21:27Z
[ "python", "list" ]
I need to load a list of database row objects into memory, and then grab one of those rows by its unique ID. Is there a clean, pythonic way of finding an single object from a list by an attribute value? Or do I just loop and compare?
Yes, you loop and compare: ``` items = [item for item in container if item.attribute == value] ``` And you get back a list which can be tested to see how many you found. If you will be doing this a lot, consider using a dictionary, where the key is the attribute you're interested in.
Get list item by attribute in Python
9,089,043
10
2012-02-01T00:18:53Z
18,586,533
7
2013-09-03T07:31:53Z
[ "python", "list" ]
I need to load a list of database row objects into memory, and then grab one of those rows by its unique ID. Is there a clean, pythonic way of finding an single object from a list by an attribute value? Or do I just loop and compare?
If you do this it only gives the very first match, instead of comparing the whole list: [find first list item that matches criteria](http://stackoverflow.com/questions/9868653/find-first-list-item-that-matches-criteria). If you do something like this, you don't have to catch the exception but get `None` instead: ``` ...
var = [[0]*5]*5 Help understanding python lists?
9,089,124
4
2012-02-01T00:29:44Z
9,089,173
7
2012-02-01T00:35:48Z
[ "python", "coding-style" ]
I came across a piece of python list decclaration. I am bit confused about the behavior of it. Can somone please explain this. Appreciate your help. ``` >>> v = [[0]*2]*2 >>> v [[0, 0], [0, 0]] >>> v[1][1] = 23 >>> v [[0, 23], [0, 23]] >>> v[1][1] = 44 >>> v [[0, 44], [0, 44]] ...
The `*` operator for lists repeats their contents, as you can clearly see in the output. However, it does not copy elements, it just copies object references. So in this case, both `[0,0 ]`s have the same underlying list object, which should explain the phenomenon. To verify this, try `v[0] = [0,44]` to assign a new ...
Numpy: How to randomly split/select an matrix into n-different matrices
9,089,156
12
2012-02-01T00:33:48Z
9,089,886
16
2012-02-01T02:21:43Z
[ "python", "random", "numpy", "scipy", "scikits" ]
* I have a numpy matrix with shape of (4601, 58). * I want to split the matrix randomly as per 60%, 20%, 20% split based on number of rows * This is for Machine Learning task I need * Is there a numpy function that randomly selects rows?
you can use numpy.random.shuffle ``` import numpy as np N = 4601 data = np.arange(N*58).reshape(-1, 58) np.random.shuffle(data) a = data[:int(N*0.6)] b = data[int(N*0.6):int(N*0.8)] c = data[int(N*0.8):] ```
Numpy: How to randomly split/select an matrix into n-different matrices
9,089,156
12
2012-02-01T00:33:48Z
9,092,726
7
2012-02-01T08:18:21Z
[ "python", "random", "numpy", "scipy", "scikits" ]
* I have a numpy matrix with shape of (4601, 58). * I want to split the matrix randomly as per 60%, 20%, 20% split based on number of rows * This is for Machine Learning task I need * Is there a numpy function that randomly selects rows?
A complement to HYRY's answer if you want to shuffle consistently several arrays x, y, z with same first dimension: `x.shape[0] == y.shape[0] == z.shape[0] == n_samples`. You can do: ``` rng = np.random.RandomState(42) # reproducible results with a fixed seed indices = np.arange(n_samples) rng.shuffle(indices) x_shu...
Python set "in" operator: uses equality or identity?
9,089,400
23
2012-02-01T01:10:59Z
9,089,433
12
2012-02-01T01:16:18Z
[ "python", "set", "identity", "operator-keyword", "equality" ]
``` class A(object): def __cmp__(self): print '__cmp__' return object.__cmp__(self) def __eq__(self, rhs): print '__eq__' return True a1 = A() a2 = A() print a1 in set([a1]) print a1 in set([a2]) ``` Why does first line prints True, but second prints False? And neither enters o...
You need to define [`__hash__`](https://docs.python.org/2/reference/datamodel.html#object.__hash__) too. For example ``` class A(object): def __hash__(self): print '__hash__' return 42 def __cmp__(self): print '__cmp__' return object.__cmp__(self) def __eq__(self, rhs): ...
Python set "in" operator: uses equality or identity?
9,089,400
23
2012-02-01T01:10:59Z
9,089,451
7
2012-02-01T01:19:32Z
[ "python", "set", "identity", "operator-keyword", "equality" ]
``` class A(object): def __cmp__(self): print '__cmp__' return object.__cmp__(self) def __eq__(self, rhs): print '__eq__' return True a1 = A() a2 = A() print a1 in set([a1]) print a1 in set([a2]) ``` Why does first line prints True, but second prints False? And neither enters o...
Sets and dictionaries gain their speed by using *hashing* as a fast approximation of full equality checking. If you want to redefine equality, you usually need to redefine the hash algorithm so that it is consistent. The default hash function uses the identity of the object, which is pretty useless as a fast approxima...
Python set "in" operator: uses equality or identity?
9,089,400
23
2012-02-01T01:10:59Z
9,091,138
10
2012-02-01T05:15:36Z
[ "python", "set", "identity", "operator-keyword", "equality" ]
``` class A(object): def __cmp__(self): print '__cmp__' return object.__cmp__(self) def __eq__(self, rhs): print '__eq__' return True a1 = A() a2 = A() print a1 in set([a1]) print a1 in set([a2]) ``` Why does first line prints True, but second prints False? And neither enters o...
Set \_\_contains\_\_ makes checks in the following order: ``` 'Match' if hash(a) == hash(b) and (a is b or a==b) else 'No Match' ``` The relevant C source code is in Objects/setobject.c::set\_lookkey() and in Objects/object.c::PyObject\_RichCompareBool().
Python IDLE. Auto-complete/Show completions not working
9,089,476
10
2012-02-01T01:22:30Z
9,478,704
8
2012-02-28T08:36:01Z
[ "python", "autocomplete", "codeblocks", "python-idle" ]
IDLE is being very dodgy as to when it will actually show an Auto-complete menu. As of late it hasn't been working at all, or, more specifically, only works during an interactive session. I've been using Code Blocks for C, and have gotten really used to the very nice auto-complete features, so it's a bit frustrating n...
The only thing i found so far is that if an editing session of IDLE is connected with python shell (called "interactive mode" in the question, i.e. after an attempt to run the edited script) then "non-interactive" IDLE can autocomplete based on values in interactive window. For example, if I type ``` a = []; a.appen `...
Matplotlib pcolor
9,089,991
3
2012-02-01T02:38:46Z
9,987,504
7
2012-04-03T05:18:59Z
[ "python", "matplotlib" ]
I am using Matplotlib to create an image based on some data. All of the data falls in the range of 0 through to 1 and I am trying to color the data based on its value using a colormap and this works perfectly in Matlab, however when converting the code across to Python I simply get a black square as the output. I belie...
Although you have resolved your original issue and have code that works, I wanted to point out that both python and numpy provide several tools that make code like this much simpler to write. Here are a few examples: ## Loading data Instead of building up lists by appending to the end of an empty one, it is often eas...
In python, how to import filename starts with a number
9,090,079
34
2012-02-01T02:51:30Z
9,090,136
37
2012-02-01T02:59:23Z
[ "python", "import" ]
Basically there is a file called `8puzzle.py` and I want to import the file into another file (in the same folder and I cannot change the file name as the file is provided). Is there anyway to do this in Python? I tried usual way `from 8puzzle import *`, it gives me an error. Error is: ``` >>> import 8puzzle File "...
You could do ``` puzzle = __import__('8puzzle') ``` Very interesting problem. I'll remember not to name anything with a number. If you'd like to `import *` -- you should [check out this question and answer](http://stackoverflow.com/questions/147507/how-does-one-do-the-equivalent-of-import-from-module-with-pythons-im...
Understanding Python Numerology
9,090,281
4
2012-02-01T03:17:43Z
9,090,331
9
2012-02-01T03:24:49Z
[ "python" ]
We can not declare an integer which start with 0. ``` >>> n = 08 SyntaxError: invalid token ``` But we do declare a variable that contains all zeros. ``` >>> n = 00000 >>> print n >>> 0 ``` So the question is in first case why python just not consider value of variable to `n = 8` by ignoring the zero on left side i...
Numbers beginning with 0 and containing no decimal point are interpreted as octal (using digits 0-7). 08 is not a valid octal number. According to the PEP Index, "the ability to specify an octal number by using a leading zero will be removed from the language in Python 3.0 (and the Python 3.0 preview mode of 2.6), and ...
Scipy/Numpy/scikits - calculating precision/recall scores based on two arrays
9,091,374
5
2012-02-01T05:47:56Z
9,092,866
18
2012-02-01T08:31:09Z
[ "python", "numpy", "scipy", "precision", "scikit-learn" ]
* I fit a Logistic Regression Model and train the model based on training dataset using the following > ``` > import scikits as sklearn > from sklearn.linear_model import LogisticRegression > lr = LogisticRegression(C=0.1, penalty='l1') > model = lr.fit(training[:,0:-1], training[:,-1) > ``` * I have a cross validati...
Yes there are, see the documentation: <http://scikit-learn.org/stable/modules/classes.html#classification-metrics> You should also have a look at the `sklearn.metrics.classification_report` utility: ``` >>> from sklearn.metrics import classification_report >>> from sklearn.linear_model import SGDClassifier >>> from s...
SQLAlchemy: SQL Expression with multiple where conditions
9,091,668
3
2012-02-01T06:19:34Z
9,092,406
7
2012-02-01T07:39:21Z
[ "python", "sqlalchemy" ]
I'm having difficulties writing what should be a simple SQL update statement in SQLAlchemy Core. However, I can't find any documentation, examples or tutorials that show how to combine multiple where conditions. I'm sure it's there - just can't find it. Here's the table: ``` self.struct = Table('struct', ...
It looks to me like you are using the Python "and" operation, which will evaluate to a only one of the clauses surrounding it. You should try using the "and\_" function from SQLAlchemy instead. Put those two clauses inside the "and\_" function.
Why isn't __new__ in Python new-style classes a class method?
9,092,072
30
2012-02-01T07:04:16Z
9,092,767
17
2012-02-01T08:22:27Z
[ "python", "new-operator", "language-design", "new-style-class" ]
The Changelog for Python 2.2 (where new-style classes were introduced) says the following about the `__new__` function: > `__new__` is a static method, not a class method. I initially thought it would have to be a class method, and that's why I added the `classmethod` primitive. Unfortunately, with class methods, upca...
`__new__` being static method allows a use-case when you create an instance of a subclass in it: ``` return super(<currentclass>, cls).__new__(subcls, *args, **kwargs) ``` If `new` is a class method then the above is written as: ``` return super(<currentclass>, cls).new(*args, **kwargs) ``` and there is no place to...
Implementing full RSA in Python
9,093,046
10
2012-02-01T08:50:34Z
9,093,232
8
2012-02-01T09:09:34Z
[ "python", "encryption", "rsa", "pycrypto" ]
I am currently working on a project using python to implement p2p communication between two (or more) computers. Although I am pretty proficient with python, I am by no means an expert; programming and encryption are by no means my profession, simply a hobby. However, in working on this project I have been attempting t...
Take a look at Raymond Hettinger recipe: [Public Key Encryption (RSA)](http://code.activestate.com/recipes/577737-public-key-encryption-rsa/)
Creating Python pip bundle with my projects
9,093,124
17
2012-02-01T08:58:58Z
9,355,968
31
2012-02-20T03:51:12Z
[ "python", "installation", "bundle", "distribution", "pip" ]
I am developing some apps which depends on one of them. I see pip can create bundles. I have all my projects source in one dir. How to create bundle for these projects and then install in other Ubuntu system? probably I should use virtualenv. Is it possible to have one virtualenv for all of them?
To create a bundle, use something like: ``` pip bundle <name of bundle>.pybundle -r requirements.txt ``` where requirements.txt contains your list of apps to install. Or you can create a bundle with a single app (why?): ``` pip bundle <name of bundle>.pybundle <my app> ``` Then, on the other system, to install your...
How to print particular JSON value in Python?
9,093,684
5
2012-02-01T09:45:59Z
9,093,748
7
2012-02-01T09:50:41Z
[ "python", "json" ]
So I have a Python code wich returns a JSON string like this one: ``` '{"X": "value1", "Y": "value2", "Z": [{"A": "value3", "B": "value4"}]}' ``` What I want to do is to print and/or return (in Python) `"value 3"` in order to use it. Also assign it to a variable so I can work with it later on. How can I do this?
``` >>> import json >>> a = json.loads('{"X":"value1","Y":"value2","Z":[{"A":"value3","B":"value4"}]}') >>> a {'Y': 'value2', 'X': 'value1', 'Z': [{'A': 'value3', 'B': 'value4'}]} >>> a["Z"][0]["A"] 'value3' ```
rendering of textfield and charfield chomps out extra whitespace (Django/Python)
9,095,379
5
2012-02-01T11:58:33Z
9,095,434
12
2012-02-01T12:02:11Z
[ "python", "django", "rendering", "textfield" ]
I've noticed that my template is rendering my model.CharField and model.TextField without any excess whitespace. For example, if I enter data such as... ``` This is a test to see what happens. ``` The rendered object field will appear as... ``` This is a test to see what happens. ``` Is this an in...
As you can see even in StackOverflow your spaces do not display, this is from the source of your question: ``` This is a test to see what happens. ``` Will save in the database as: ``` This is a test\n\n\nto see what happens. ``` You have to problems when rendering as html: 1. Extra...
Django Unittest doesn't load fixtures
9,095,398
2
2012-02-01T11:59:44Z
9,096,143
10
2012-02-01T12:52:43Z
[ "python", "django", "unit-testing", "django-unittest" ]
Django testrunner is not loading fixtures out of media app fixtures/ directory. How can I debug it - find if it's looking for my fixtures and where? (Python 2.7.1, Django 1.3.1) My app (app\_label=media) directory structure: ``` media/fixtures/ media/fixtures/media.json media/fixtures/auth.json media/tests/ media/te...
Use `django.test.TestCase` instead of `unittest.TestCase`.