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
Chunking Stanford Named Entity Recognizer (NER) outputs from NLTK format
27,629,130
9
2014-12-23T22:46:15Z
27,629,409
8
2014-12-23T23:17:14Z
[ "python", "nlp", "nltk", "stanford-nlp", "named-entity-recognition" ]
I am using NER in NLTK to find persons, locations, and organizations in sentences. I am able to produce the results like this: ``` [(u'Remaking', u'O'), (u'The', u'O'), (u'Republican', u'ORGANIZATION'), (u'Party', u'ORGANIZATION')] ``` Is that possible to chunk things together by using it? What I want is like this: ...
It looks long but it does the work: ``` ner_output = [(u'Remaking', u'O'), (u'The', u'O'), (u'Republican', u'ORGANIZATION'), (u'Party', u'ORGANIZATION')] chunked, pos = [], "" for i, word_pos in enumerate(ner_output): word, pos = word_pos if pos in ['PERSON', 'ORGANIZATION', 'LOCATION'] and pos == prev_tag: ...
Python - metaclass - adding properties
27,629,944
5
2014-12-24T00:23:02Z
27,630,089
7
2014-12-24T00:47:37Z
[ "python", "metaclass" ]
I would like to define metaclass that will enable me to create properties (i.e. setter, getter) in new class on the base of the class's attributes. For example, I would like to define the class: ``` class Person(metaclass=MetaReadOnly): name = "Ketty" age = 22 def __str__(self): return ("Name: " ...
Bind the *current* value of `key` to the parameter in your `fget` and `fset` definitions: ``` fget = lambda self, k=key: getattr(self, "__%s" % k) fset = lambda self, value, k=key: setattr(self, "__" + k, value) ``` --- This is a classic Python pitfall. When you define ``` fget = lambda self: getattr(self, "__%s" %...
Matplotlib issue on OS X ("ImportError: cannot import name _thread")
27,630,114
53
2014-12-24T00:51:32Z
27,634,264
123
2014-12-24T09:06:30Z
[ "python", "osx", "python-2.7", "matplotlib", "python-dateutil" ]
At some point in the last few days, Matplotlib stopped working for me on OS X. Here's the error I get when trying to `import matplotlib`: ``` Traceback (most recent call last): File "/my/path/to/script/my_script.py", line 15, in <module> import matplotlib.pyplot as plt File "/Library/Python/2.7/site-packages/m...
``` sudo pip uninstall python-dateutil sudo pip install python-dateutil==2.2 ``` I had the same error message this afternoon as well, although I did recently upgrade to Yosemite. I'm not totally sure I understand why reverting dateutil to a previous version works for me, but since running the above I'm having no troub...
Matplotlib issue on OS X ("ImportError: cannot import name _thread")
27,630,114
53
2014-12-24T00:51:32Z
29,613,835
7
2015-04-13T19:49:41Z
[ "python", "osx", "python-2.7", "matplotlib", "python-dateutil" ]
At some point in the last few days, Matplotlib stopped working for me on OS X. Here's the error I get when trying to `import matplotlib`: ``` Traceback (most recent call last): File "/my/path/to/script/my_script.py", line 15, in <module> import matplotlib.pyplot as plt File "/Library/Python/2.7/site-packages/m...
Installing the `python-dateutil==2.2` did not work for me. But a quick-and-dirty workaround did work! I replace `six.py` in python 2.7 with the `six.py` from python 3.4 (virtualenv). Since, I have the problem in 2.7 but not 3.4. **UPDATE** I had the same problem again after reinstalling python (and after upgrading t...
Matplotlib issue on OS X ("ImportError: cannot import name _thread")
27,630,114
53
2014-12-24T00:51:32Z
31,140,136
29
2015-06-30T13:50:42Z
[ "python", "osx", "python-2.7", "matplotlib", "python-dateutil" ]
At some point in the last few days, Matplotlib stopped working for me on OS X. Here's the error I get when trying to `import matplotlib`: ``` Traceback (most recent call last): File "/my/path/to/script/my_script.py", line 15, in <module> import matplotlib.pyplot as plt File "/Library/Python/2.7/site-packages/m...
This problem is fixed in the latest `six` and `dateutil` versions. However, in OS X, even if you update your `six` to the latest version, you might not actually update it correctly. This is what happened to me: After doing a `pip2 install six -U`, the new `six` module was installed in `/Library/Python/2.7/site-package...
Python/Selenium incognito/private mode
27,630,190
13
2014-12-24T01:06:34Z
27,630,230
19
2014-12-24T01:12:39Z
[ "python", "selenium", "browser", "selenium-webdriver", "incognito-mode" ]
I can not seem to find any documentation on how to make Selenium open the browser in incognito mode. Do I have to setup a custom profile in the browser or?
First of all, since `selenium` by default starts up a browser with a clean, brand-new profile, *you are actually already browsing privately*. Referring to: * [Python - Start firefox with Selenium in private mode](http://stackoverflow.com/questions/27425116/python-start-firefox-with-selenium-in-private-mode) * [How mig...
Django REST Framework - CurrentUserDefault use
27,632,385
6
2014-12-24T06:15:55Z
27,641,015
8
2014-12-24T18:39:08Z
[ "python", "django", "django-rest-framework" ]
I'm trying to use the `CurrentUserDefault` class for one serializer. ``` user = serializers.HiddenField(default=serializers.CurrentUserDefault()) ``` The docs says: > In order to use this, the 'request' must have been provided as part of > the context dictionary when instantiating the serializer. I'm not sure how t...
Django REST Framework handles the serialization and deserialization of objects using a central serializer. In order to help deserialize and serialize sometimes, it needs a bit of context like the current `view` or `request` that is being used. You typically don't have to worry about it because the generic views handle ...
ImportError while installing pip in virtualenv
27,634,895
4
2014-12-24T09:50:42Z
27,806,506
8
2015-01-06T20:16:10Z
[ "python", "python-2.7", "installation", "pip", "virtualenv" ]
I have a rhel machine with python2.6 installed on it. I've been trying to have an alternate install of python2.7 and set up a virtualenv for using 2.7. I installed python2.7 by building from source as follows: ``` ./configure --prefix=/usr/local --enable-unicode=ucs4 --enable-shared LDFLAGS="-Wl,-rpath /usr/local/lib"...
I was in a situation similar to yours, and I eventually found the fix. At least in my case the root problem was that when I compiled python 2.7.8 the build process didn't find the proper OpenSSL libraries (because they were not installed on my system). After make finished running it showed a summary similar to this: `...
Best way to store python datetime.time in a sqlite3 column?
27,640,857
6
2014-12-24T18:21:22Z
27,641,141
8
2014-12-24T18:53:05Z
[ "python", "datetime", "sqlite3" ]
I'm trying to replace my use of SAS with python + sqlite3; I'm trying to move my data from SAS datasets to SQLite databases. I have many time fields that are properly represented in python as datetime.time objects. Since SQLite is "lightly typed", I'm looking for advice about what format to use to store times in column...
There is a general recipe for storing any serializable Python object in an sqlite table. * Use [`sqlite3.register_adapter`](https://docs.python.org/2/library/sqlite3.html#sqlite3.register_adapter) to register a function for converting the Python object to int, long, float, str (UTF-8 encoded), unicode or buffer. * U...
How to test an API endpoint with Django-rest-framework using Django-oauth-toolkit for authentication
27,641,703
9
2014-12-24T20:02:38Z
27,650,168
16
2014-12-25T19:36:49Z
[ "python", "django", "testing", "oauth-2.0", "django-rest-framework" ]
I have a Django-rest-framework viewset/router to define an API endpoint. The viewset is defined as such: ``` class DocumentViewSet(viewsets.ModelViewSet): permission_classes = [permissions.IsAuthenticated, TokenHasReadWriteScope] model = Document ``` And the router is defined as ``` router = DefaultRouter() ...
When you are writing tests, you should aim to extract anything you are not testing from the test itself, typically putting any setup code in the `setUp` method of the test. In the case of API tests with OAuth, this usually includes the test user, OAuth application, and the active access token. For `django-oauth-toolki...
Python psycopg2 timeout
27,641,740
7
2014-12-24T20:07:47Z
27,641,996
11
2014-12-24T20:43:06Z
[ "python", "postgresql", "connection", "timeout", "psycopg2" ]
I have a huge problem: There seems to be some hardware problems on the router of the server my python software runs on. The connection to the database only is successfull about every third time. So a psycopg2.connect() can take up to 5 minutes before I get an timeout exception. ``` 2014-12-23 15:03:12,461 - ERROR - co...
When using the keyword arguments syntax to the `connect` function it is possible to use any of the `libpd` supported connection parameters. Among those there is `connect_timeout` in seconds: ``` db = psycopg2.connect ( host=dhost, database=ddatabase, user=duser, password=dpassword, connect_timeout=3 ) ``` ...
Can't run example code referenced in Flask docs
27,644,868
5
2014-12-25T06:46:01Z
27,648,826
7
2014-12-25T16:13:27Z
[ "python", "flask" ]
I am reading the Flask docs and want to use the examples they reference that are in the git repo. However, the tutorials don't match the code in the repository, and I can't run them; I get the following error: ``` @app.cli.command('initdb') AttributeError: 'Flask' object has no attribute 'cli' ``` I used `pip insta...
You are reading the development docs, but using the latest stable release (0.10.1). The current builds include many changes, including a cli. To try out the latest code, use: ``` pip install https://github.com/mitsuhiko/flask/tarball/master ``` To get something similar in the latest stable release, you either need to...
Can't connect to S3 buckets with periods in their name, when using Boto on Heroku
27,652,318
12
2014-12-26T02:34:36Z
27,652,348
31
2014-12-26T02:39:43Z
[ "python", "heroku", "amazon-web-services", "amazon-s3", "boto" ]
We're getting a certificate error when trying to connect to our S3 bucket using Boto. Strangely, this only manifests itself when accessing a bucket with periods in its name WHILE running on Heroku. ``` from boto.s3.connection import S3Connection conn = S3Connection({our_s3_key}, {our_s3_secret}) bucket = conn.get_buck...
According to the [relevant github issue](https://github.com/boto/boto/issues/2836), add this to the configuration: ``` [s3] calling_format = boto.s3.connection.OrdinaryCallingFormat ``` Or, specify the `calling_format` while instantiating an [`S3Connection`](http://boto.readthedocs.org/en/latest/ref/s3.html#boto.s3.c...
python: flatten to a list of lists but no more
27,652,422
6
2014-12-26T03:00:16Z
27,652,557
7
2014-12-26T03:31:38Z
[ "python" ]
I have a list of lists which is nested in multiple layers of lists. possible inputs: `[[[[1,2,3] , [a,b,c]]]]` or `[[[1,2,3] , [a,b,c]]]` or `[[[1,2,3]] , [[a,b,c]]]` when I use `flat()` it will just flatten everything which is not what I want. `[1,2,3,a,b,c]` What I need instead is `[[1,2,3] , [a,b,c]]` as the ...
``` import collections def is_listlike(x): return isinstance(x, collections.Iterable) and not isinstance(x, basestring) def flat(S): result = [] for item in S: if is_listlike(item) and len(item) > 0 and not is_listlike(item[0]): result.append(item) else: result.exten...
How to use Python requests to fake a browser visit?
27,652,543
18
2014-12-26T03:29:02Z
27,652,558
41
2014-12-26T03:31:57Z
[ "python", "html", "web-scraping", "python-requests", "wget" ]
I want to get the content from the below website. If I use a browser like Firefox or Chrome I could get the real website page I want, but if I use the Python requests package (or `wget` command) to get it, it returns a totally different HTML page. I thought the developer of the website had made some blocks for this, so...
Provide a [`User-Agent` header](http://en.wikipedia.org/wiki/User_agent): ``` import requests url = 'http://www.ichangtou.com/#company:data_000008.html' headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'} response = requ...
member variable string gets treated as Tuple in Python
27,654,671
13
2014-12-26T08:25:37Z
27,654,685
16
2014-12-26T08:27:10Z
[ "python", "class" ]
I am currently learning Python with the help of CodeAcademy. My problem may be related to their web application, but my suspicion is I am just wrong on a very fundamental level here. If you want to follow along I am referring to CodeAcademy.com -> Python -> Classes 6/11 My code looks like this: ``` class Car(object)...
In your `__init__`, you have: ``` self.model = model, self.color = color, ``` which is how you define a tuple. Change the lines to ``` self.model = model self.color = color ``` without the comma: ``` >>> a = 2, >>> a (2,) ``` vs ``` >>> a = 2 >>> a 2 ```
issues with six under django?
27,656,510
6
2014-12-26T11:29:16Z
31,116,425
9
2015-06-29T13:00:36Z
[ "python", "django" ]
I'm trying to use a package called vcrpy to accelerate the execution of my django application test suite. I'm using django 1.7 on Mac, with Python 2.7. I added the following couple of lines to one of my tests: ``` import vcr with vcr.use_cassette('recording.yaml'): ``` The result is an import error: ``` import ...
Maybe a little bit too late for the original question, but I came here trough Google so for future reference, here's my solution: ### Problem The problem I found is that mac os comes with not only python but also some packages pre-installed. Six is one of those packages and therein lies the conflict. The pre-installe...
downloading error using nltk.download()
27,658,409
6
2014-12-26T14:35:06Z
27,660,379
13
2014-12-26T18:04:28Z
[ "python", "python-2.7", "ubuntu", "nltk", "spyder" ]
I am experimenting NLTK package using Pyton. I tried to downloaded NLTK using `nltk.download()`. I got this kind of error message. How to solve this problem? Thanks. The system I used is Ubuntu installed under VMware. The IDE is Spyder. ![enter image description here](http://i.stack.imgur.com/JF6RT.png) After using ...
try the command-line version instead of the IDE: ``` >>> import nltk >>> nltk.download('all') ``` Ensure that you've the latest version of `NLTK` because it's always improving and constantly maintain: ``` $ pip install --upgrade nltk ```
Python: lists and copy of them
27,658,877
11
2014-12-26T15:24:56Z
27,658,942
11
2014-12-26T15:32:10Z
[ "python", "list" ]
I can not explain the following behaviour: ``` l1 = [1, 2, 3, 4] l1[:][0] = 888 print(l1) # [1, 2, 3, 4] l1[:] = [9, 8, 7, 6] print(l1) # [9, 8, 7, 6] ``` It seems to be that `l1[:][0]` refers to a copy, whereas `l1[:]` refers to the object itself.
This is caused by python's feature that allows you to *assign a list to a slice of another list*, i.e. ``` l1= [1,2,3,4] l1[:2] = [9, 8] print l1 ``` will set `l1`'s first two values to `9` and `8` respectively. Similarly, ``` l1[:]= [9, 8, 7, 6] ``` assigns new values to all elements of `l1`. --- More info about...
How to group similar items in a list?
27,659,153
9
2014-12-26T15:54:54Z
27,659,180
7
2014-12-26T15:57:14Z
[ "python", "list", "group" ]
I am looking to group similar items in a list based on the first three characters in the string. For example: ``` test = ['abc_1_2', 'abc_2_2', 'hij_1_1', 'xyz_1_2', 'xyz_2_2'] ``` How can I group the above list items into groups based on the first grouping of letters (e.g. `'abc'`)? The following is the intended out...
The `.split("_")[0]` part should be inside a single-argument function that you pass as the second argument to `itertools.groupby`. ``` >>> import os, itertools >>> test = ['abc_1_2', 'abc_2_2', 'hij_1_1', 'xyz_1_2', 'xyz_2_2'] >>> [list(g) for _, g in itertools.groupby(test, lambda x: x.split('_')[0])] [['abc_1_2', 'a...
Lambda Within Filter Function?
27,659,524
2
2014-12-26T16:34:23Z
27,659,544
7
2014-12-26T16:35:52Z
[ "python", "python-3.x" ]
I found [***this***](http://www.secnetix.de/olli/Python/lambda_functions.hawk) tutorial on using lambda within python. Upon attempting to do the 3rd example I've discovered the results are not the same as in the tutorial. I'm 99% sure my code is correct, but here it is nonetheless. ``` my_list = [2,9,10,15,21,30,33,45...
The difference in output is caused by the fact that `filter` returns an [iterator](https://docs.python.org/3/glossary.html#term-iterator) in Python 3.x. So, you need to manually call `list()` on it in order to get a list: ``` >>> my_list = [2,9,10,15,21,30,33,45] >>> filter(lambda x: x % 3 == 0, my_list) <filter objec...
How to add package data recursively in Python setup.py?
27,664,504
11
2014-12-27T04:58:35Z
27,664,856
12
2014-12-27T06:04:33Z
[ "python", "distutils", "setup.py" ]
I have a new library that has to include a lot of subfolders of small datafiles, and I'm trying to add them as package data. Imagine I have my library as so: ``` library - foo.py - bar.py data subfolderA subfolderA1 subfolderA2 subfolderB subfolderB1 .... ``` I want to add all...
1. Use [Setuptools](https://packaging.python.org/en/latest/projects.html#setuptools) instead of distutils. 2. Use [data files](https://packaging.python.org/en/latest/distributing.html#data-files) instead of package data. These do not require `__init__.py`. 3. Generate the lists of files and directories using standard P...
How to add package data recursively in Python setup.py?
27,664,504
11
2014-12-27T04:58:35Z
36,693,250
7
2016-04-18T11:54:08Z
[ "python", "distutils", "setup.py" ]
I have a new library that has to include a lot of subfolders of small datafiles, and I'm trying to add them as package data. Imagine I have my library as so: ``` library - foo.py - bar.py data subfolderA subfolderA1 subfolderA2 subfolderB subfolderB1 .... ``` I want to add all...
The problem with the `glob` answer is that it only does so much. I.e. it's not fully recursive. The problem with the `copy_tree` answer is that the files that are copied will be left behind on an uninstall. The proper solution is a recursive one which will let you set the `package_data` parameter in the setup call. I...
pydot.InvocationException: GraphViz's executables not found
27,666,846
4
2014-12-27T11:37:34Z
31,082,036
9
2015-06-26T20:57:37Z
[ "python", "scipy", "graphviz", "pydot" ]
I try to run [this example](http://scikit-learn.org/stable/modules/tree.html) for decision tree learning, but get the following error message: > File "coco.py", line 18, in > graph.write\_pdf("iris.pdf") File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pydot.py", > line 1602, in > la...
cel, answered this in the comment: > Graphviz is not a python tool. The python packages at pypi provide a > convenient way of using Graphviz in python code. You still have to > install the Graphviz executables, which are not pythonic, thus not > shipped with these packages. You can install those e.g. with a > general-...
Convert a list to a string list python
27,666,929
3
2014-12-27T11:49:27Z
27,666,940
7
2014-12-27T11:51:31Z
[ "python", "string", "list" ]
I'm Python beginner can't get my head around. How do I change for example `a = [[1,2],[3,4],[5,6]]` into `"12\n34\n56"` string format. This is as far as i got but it goes into newline with each number. ``` def change(a): c = "" for r in a: for b in r: c += str(b) + "\n" return c ```
Using [`str.join`](http://docs.python.org/3/library/stdtypes.html#str.join) with [generator expression](https://docs.python.org/3/tutorial/classes.html#generator-expressions): ``` >>> a = [[1,2], [3,4], [5,6]] >>> '\n'.join(''.join(map(str, xs)) for xs in a) '12\n34\n56' ```
Convert a list to a string list python
27,666,929
3
2014-12-27T11:49:27Z
27,667,036
12
2014-12-27T12:03:10Z
[ "python", "string", "list" ]
I'm Python beginner can't get my head around. How do I change for example `a = [[1,2],[3,4],[5,6]]` into `"12\n34\n56"` string format. This is as far as i got but it goes into newline with each number. ``` def change(a): c = "" for r in a: for b in r: c += str(b) + "\n" return c ```
> but it goes into newline with each number That’s because you add the newline after *each number* instead of after each sublist `r`. If you want that instead, you should append the newline there: ``` c = '' for r in a: for b in r: c += str(b) c += '\n' return c ``` But note that appending to a str...
TypeError: list indices must be integers, not str Python
27,667,531
8
2014-12-27T13:08:53Z
27,667,545
10
2014-12-27T13:10:57Z
[ "python", "mapreduce" ]
`list[s]` is a string. Why doesn't this work? The following error appears: > TypeError: list indices must be integers, not str ``` list = ['abc', 'def'] map_list = [] for s in list: t = (list[s], 1) map_list.append(t) ```
When you iterate over a list, the loop variable receives the actual list elements, not their indices. Thus, in your example `s` is a string (first `abc`, then `def`). It looks like what you're trying to do is essentially this: ``` orig_list = ['abc', 'def'] map_list = [(el, 1) for el in orig_list] ``` This is using ...
Is .ix() always better than .loc() and .iloc() since it is faster and supports integer and label access?
27,667,759
32
2014-12-27T13:35:22Z
27,667,801
28
2014-12-27T13:40:37Z
[ "python", "pandas" ]
I'm learning the Python pandas library. Coming from an R background, the indexing and selecting functions seem more complicated than they need to be. My understanding it that .loc() is only label based and .iloc() is only integer based. **Why should I ever use .loc() and .iloc() if .ix() is faster and supports integer...
Please refer to the doc [Different Choices for Indexing](http://pandas.pydata.org/pandas-docs/stable/indexing.html#different-choices-for-indexing), it states clearly when and why you should use **.loc, .iloc** over **.ix**, it's about explicit use case: > .ix supports mixed integer and label based access. It is primar...
Show entire toctree in Read The Docs sidebar
27,669,376
5
2014-12-27T16:52:10Z
27,767,165
8
2015-01-04T15:39:21Z
[ "python", "python-sphinx", "read-the-docs" ]
It's my understanding the new Read The Docs theme [generates the sidebar from the toctree](http://read-the-docs.readthedocs.org/en/latest/theme.html#how-the-table-of-contents-builds) with a depth of 2. My documentation is relatively deep, and a depth of 2 is not enough for it to be useful. How can I increase this limit...
Looking at the [source for the theme on Github](https://github.com/snide/sphinx_rtd_theme), it seems the ToC depth is hard-coded on [line 93 in sphinx\_rtd\_theme/layout.html](https://github.com/snide/sphinx_rtd_theme/blob/master/sphinx_rtd_theme/layout.html#L93). As such, there is no configuration you can make to the ...
read matlab v7.3 file into python list of numpy arrays via h5py
27,670,149
2
2014-12-27T18:18:15Z
27,670,480
7
2014-12-27T18:54:46Z
[ "python", "matlab", "numpy", "h5py" ]
I know this has been asked before but in my opinion there are still no answers that explain what is going on and don't happen to work for my case. I have a matlab v7.3 file that is structured like so, ``` ---> rank <1x454 cell> ---> each element is <53x50 double> f.mat ---> compare <1x454 c...
Well I found the solution to my problem. If anyone else has a better solution or can better explain I'd still like to hear it. Basically, the `<HDF5 object reference>` needed to be used to index the h5py file object to get the underlying array that is being referenced. After we are referring to the array that is neede...
How to print Y axis label horizontally in a matplotlib / pylab chart?
27,671,748
12
2014-12-27T21:46:32Z
27,671,918
19
2014-12-27T22:12:12Z
[ "python", "matplotlib", "label" ]
I'm creating very simple charts with matplotlib / pylab Python module. The letter "y" that labels the Y axis is on its side. You would expect this if the label was longer, such as a word, so as not to extend the outside of the graph to the left too much. But for a one letter label, this doesn't make sense, the label sh...
It is very simple. After plotting the label, you can simply change the rotation: ``` from matplotlib import pyplot as plt plt.ion() plt.plot([1,2,3]) h = plt.ylabel('y') h.set_rotation(0) plt.draw() ``` Alternatively, you can pass the rotation as an argument, i.e ``` plt.ylabel('y',rotation=0) ```
Using bisect.insort with key
27,672,494
6
2014-12-27T23:43:30Z
27,673,073
7
2014-12-28T01:45:31Z
[ "python", "bisect" ]
Doc's are lacking an example.... How do you use `bisect.insort_left` based on key. Trying to insert based on key. ``` bisect.insort_left(data, ('brown', 7)) ``` this puts insert at data[0]. From docs.... ``` bisect.insort_left(list, item[, lo[, hi]]) Insert item in list in sorted order. This is equivalent to ...
This does essentially the same thing the [`SortedCollection` recipe](http://code.activestate.com/recipes/577197-sortedcollection/) does that the [`bisect` documentation](https://docs.python.org/2/library/bisect.html?highlight=sortedcollection) mentions at the end that supports a key-function. What's being done is a se...
How should data attributes of a class be used as default arguments in methods of the class?
27,673,137
2
2014-12-28T02:02:49Z
27,673,152
7
2014-12-28T02:05:26Z
[ "python", "class", "methods", "arguments", "self" ]
Let's say I want to set the default value of an argument of a method of a class to the value of some data attribute of the class. What is an appropriate way to do this? Is there a way to do this using lambda functions? Here is some example code: ``` class A(object): def __init__( self ): ...
If I understood your question, I usually do it with: ``` def report(self, text = None): if text is None: text = self._defaultReportText return(text) ``` (Edit: changed `if not text` to `if text is None` after Warren Weckesser's suggestion.)
Smallest enclosing circle in Python, error in the code
27,673,463
8
2014-12-28T03:30:08Z
27,676,635
10
2014-12-28T13:05:12Z
[ "python", "algorithm", "runtime-error", "circle", "computational-geometry" ]
I have a set of points that represent the vertices (x, y) of a polygon. ``` points= [(421640.3639270504, 4596366.353552659), (421635.79361391126, 4596369.054192241), (421632.6774913164, 4596371.131607305), (421629.14588570886, 4596374.870954419), (421625.6142801013, 4596377.779335507), (421624.99105558236, 4596382.141...
Without understanding anything about your algorithm, I noticed one thing: the ratio between your coordinates and your radius is very large, about 2e5. Maybe, your algorithm is ill conditioned when trying to find a circle around points which are so far away from the origin. Especially in your `_make_circumcircle` functi...
Hide traceback unless a debug flag is set
27,674,602
9
2014-12-28T07:52:44Z
27,674,608
10
2014-12-28T07:53:59Z
[ "python", "error-handling", "user-experience" ]
What is the idiomatic python way to hide traceback errors unless a verbose or debug flag is set? Example code: ``` their_md5 = 'c38f03d2b7160f891fc36ec776ca4685' my_md5 = 'c64e53bbb108a1c65e31eb4d1bb8e3b7' if their_md5 != my_md5: raise ValueError('md5 sum does not match!') ``` Existing output now, but only desi...
The short way is using the `sys` module and use this command: ``` sys.tracebacklimit = 0 ``` Use your flag to determine the behaviour. Example: ``` >>> import sys >>> sys.tracebacklimit=0 >>> int('a') ValueError: invalid literal for int() with base 10: 'a' ``` The nicer way is to use and [exception hook](https://d...
Non-blocking I/O with asyncio
27,676,954
11
2014-12-28T13:42:33Z
27,682,150
7
2014-12-29T00:49:56Z
[ "python", "python-3.x", "pygame", "python-asyncio" ]
I'm trying to write a networked game with Pygame and asyncio, but I can't work out how to avoid hanging on reads. Here is my code for the client: ``` @asyncio.coroutine def handle_client(): print("Connected!") reader, writer = yield from asyncio.open_connection('localhost', 8000) while True: mouse_...
The point of `yield from` is to switch the execution to the asyncio's event loop *and* to block the current coroutine until the result is available. To schedule a task without blocking the current coroutine, you could use `asyncio.async()`. To print read-so-far data without blocking the pygame loop: ``` @asyncio.coro...
How to count by twos with Python's 'range'
27,678,156
4
2014-12-28T16:10:10Z
27,678,169
28
2014-12-28T16:11:29Z
[ "python", "range" ]
So imagine I want to go over a loop from 0 to 100, but skipping the odd numbers (so going "two by two"). ``` for x in range(0,100): if x%2 == 0: print x ``` This fixes it. But imagine I want to do so jumping two numbers? And what about three? Isn't there a way?
Use the step argument (the last, optional): ``` for x in range(0, 100, 2): print x ``` Note that if you actually want to **keep** the odd numbers, it becomes: ``` for x in range(1, 100, 2): print x ``` **[Range](https://docs.python.org/3.4/library/stdtypes.html#typesseq-range)** is a **[very](http://www.pyt...
Why does `if Exception` work in Python
27,681,145
12
2014-12-28T22:17:19Z
27,681,156
28
2014-12-28T22:18:59Z
[ "python", "exception", "exception-handling", "boolean" ]
In this answer <http://stackoverflow.com/a/27680814/3456281>, the following construct is presented ``` a=[1,2] while True: if IndexError: print ("Stopped.") break print(a[2]) ``` which actually prints "Stopped." and breaks (tested with Python 3.4.1). Why?! Why is `if IndexError` even legal? W...
All objects have a boolean value. If not otherwise defined, that boolean value is True. So this code is simply the equivalent of doing `if True`; so execution reaches the `break` statement immediately and the `print` is never reached.
os.urandom() decoding Issue
27,681,823
2
2014-12-28T23:51:10Z
27,681,852
8
2014-12-28T23:56:47Z
[ "python", "windows", "python-3.x", "decode", "python-3.4" ]
Im trying to get a *private\_key* so, I tried this: ``` private_key = os.urandom(32).encode('hex') ``` But it throws this error: ``` AttributeError: 'bytes' object has no attribute 'encode' ``` So I check questions and solved that, in Python3x bytes can be only **decode.** Then I change it to: ``` private_key = os...
Use [`binascii.hexlify`](https://docs.python.org/3/library/binascii.html#binascii.hexlify). It works both in Python 2.x and Python 3.x. ``` >>> import binascii >>> binascii.hexlify(os.urandom(32)) b'daae7948824525c1b8b59f9d5a75e9c0404e46259c7b1e17a4654a7e73c91b87' ``` If you need a string object instead of a bytes ob...
Calculate Mahalanobis distance using NumPy only
27,686,240
2
2014-12-29T09:22:59Z
27,691,752
7
2014-12-29T15:37:30Z
[ "python", "numpy" ]
I am looking for NumPy way of calculating Mahalanobis distance between two numpy arrays (x and y). The following code can correctly calculate the same using cdist function of Scipy. Since this function calculates unnecessary matix in my case, I want more straight way of calculating it using NumPy only. ``` import nump...
I think your problem lies in the construction of your covariance matrix. Try: ``` X = np.vstack([xx,yy]) V = np.cov(X.T) VI = np.linalg.inv(V) print np.diag(np.sqrt(np.dot(np.dot((xx-yy),VI),(xx-yy).T))) ``` Output: ``` [ 2.28765854 2.75165028 2.75165028 2.75165028 0. 2.75165028 2.75165028 2.75165028...
Python calculator - Implicit math module
27,688,425
9
2014-12-29T11:58:08Z
27,688,492
11
2014-12-29T12:01:44Z
[ "python", "bash", "calculator", "command-line-interface" ]
Every now and then I need to get the answer to a calculation. As I usually have a terminal screen open that is a natural place for me to ask such mathematical questions. The Python interactive shell is good for this purpose, provided you want to enter yet another shell only to have to exit out of it later on. Sometim...
You can use ``` from math import * ``` to import all constants and functions from the math module into your global scope.
Logging in Django and gunicorn
27,696,154
8
2014-12-29T21:18:13Z
27,712,391
10
2014-12-30T20:52:53Z
[ "python", "django", "logging", "gunicorn" ]
I'm running django application with gunicorn, and I can't see any log messages I'm wriging. Here is the code that writes the logs: ``` logger = logging.getLogger(__name__) def home_page(request): logger.warning('in home page') ``` (note: this code definitely runs, since this is a view that leads to the homepage...
I have solved my problem. Providing the details so it might help somebody with similar issue. Decided not to mix up with gunicorn and django logs and to create separate log file for django. ``` LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'lev...
Custom unique_together key name
27,696,216
17
2014-12-29T21:23:09Z
27,773,901
7
2015-01-05T05:30:17Z
[ "python", "mysql", "django", "django-models", "unique-constraint" ]
I have a model with a [`unique_together`](https://docs.djangoproject.com/en/dev/ref/models/options/#unique-together) defined for 3 fields to be unique together: ``` class MyModel(models.Model): clid = models.AutoField(primary_key=True, db_column='CLID') csid = models.IntegerField(db_column='CSID') cid = mo...
Its not well documented, but depending on if you are using Django 1.6 or 1.7 there are two ways you can do this: [In Django 1.6 you can override the `unique_error_message`, like so](http://chriskief.com/2013/11/20/customize-djangos-unique_together-error-message/): ``` class MyModel(models.Model): clid = models.Au...
Understanding min_df and max_df in scikit CountVectorizer
27,697,766
4
2014-12-29T23:57:13Z
35,615,151
12
2016-02-24T23:12:57Z
[ "python", "machine-learning", "scikit-learn" ]
I have five text files that I input to a CountVectorizer. When specifying min\_df and max\_df to the CountVectorizer instance what does the min/max document frequency exactly means? Is it the frequency of a word in its particular text file or is it the frequency of the word in the entire overall corpus (5 txt files)? ...
`max_df` is used for removing terms that appear **too frequently**, also known as "corpus-specific stop words". For example: * `max_df = 0.50` means "ignore terms that appear in **more than 50% of the documents**". * `max_df = 25` means "ignore terms that appear in **more than 25 documents**". The default `max_df` is...
How do I make sans serif superscript or subscript text in matplotlib?
27,698,377
8
2014-12-30T01:16:01Z
27,700,375
9
2014-12-30T06:02:42Z
[ "python", "matplotlib", "fonts", "latex" ]
I want to use a subscript in an axis label in a matplotlib figure. Using LaTeX I would set it as `$N_i$`, which gives me the italic serif font. I know I can get non-italic mathfont with `\mathrm`. But I would like to get the text in the default matplotlib sans-serif font so it matches the rest of the text in the figure...
Use `\mathregular` to use the font used for regular text outside of mathtext: ``` $\mathregular{N_i}$ ``` Take a look [here](http://matplotlib.org/users/mathtext.html) for more information.
How do I make sans serif superscript or subscript text in matplotlib?
27,698,377
8
2014-12-30T01:16:01Z
27,708,102
8
2014-12-30T15:26:18Z
[ "python", "matplotlib", "fonts", "latex" ]
I want to use a subscript in an axis label in a matplotlib figure. Using LaTeX I would set it as `$N_i$`, which gives me the italic serif font. I know I can get non-italic mathfont with `\mathrm`. But I would like to get the text in the default matplotlib sans-serif font so it matches the rest of the text in the figure...
You can do it by customizing `rcParams`. If you have multiple elements to customize, you can store them as a `dict` and the update the `rcParams': ``` params = {'mathtext.default': 'regular' } plt.rcParams.update(params) ``` If you want to do a single modification, you can simply type: ``` plt.rcParams.upd...
Should I unittest private/protected method
27,701,183
5
2014-12-30T07:18:38Z
28,341,497
7
2015-02-05T10:26:43Z
[ "python", "unit-testing", "oop", "language-agnostic", "private" ]
This is actually language agnostic. But I'll give you context in python. I have this parent class ``` class Mammal(object): def __init__(self): """ do some work """ def eat(self, food): """Eat the food""" way_to_eat = self._eating_method() self._consume(food) def _eating_...
**From a theoretical point of view**, you only need to test public methods of your instantiable classes (in standard OOP languages). There is no point in testing the internal behaviour because all you want is "which output for that input" (for a particular method, or for the entire class). You should try to respect it ...
Interactive pixel information of an image in Python?
27,704,490
10
2014-12-30T11:19:52Z
27,707,723
23
2014-12-30T15:01:17Z
[ "python", "image", "image-processing", "matplotlib", "scikit-image" ]
**Short version:** is there a Python method for displaying an image which shows, in real time, the pixel indices and intensities? So that as I move the cursor over the image, I have a continually updated display such as `pixel[103,214] = 198` (for grayscale) or `pixel[103,214] = (138,24,211)` for rgb? **Long version:*...
There a couple of different ways to go about this. You can monkey-patch `ax.format_coord`, similar to [this official example](http://matplotlib.org/examples/api/image_zcoord.html). I'm going to use a slightly more "pythonic" approach here that doesn't rely on global variables. (Note that I'm assuming no `extent` kwarg...
How to find all ordered pairs of elements in array of integers whose sum lies in a given range of value
27,705,359
9
2014-12-30T12:19:25Z
27,705,519
13
2014-12-30T12:29:35Z
[ "python", "arrays", "algorithm" ]
Given an array of integers find the number of all ordered pairs of elements in the array whose sum lies in a given range [a,b] Here is an O(n^2) solution for the same ``` ''' counts all pairs in array such that the sum of pair lies in the range a and b ''' def countpairs(array, a, b): num_of_pairs = 0 for i ...
1. Sort the array (say in increasing order). 2. For each element x in the array: * Consider the array slice *after* the element. * Do a binary search on this array slice for [a - x], call it y0. If no exact match is found, consider the closest match *bigger* than [a - x] as y0. * Output all elements (x, y) fro...
How to find all ordered pairs of elements in array of integers whose sum lies in a given range of value
27,705,359
9
2014-12-30T12:19:25Z
27,707,722
10
2014-12-30T15:01:14Z
[ "python", "arrays", "algorithm" ]
Given an array of integers find the number of all ordered pairs of elements in the array whose sum lies in a given range [a,b] Here is an O(n^2) solution for the same ``` ''' counts all pairs in array such that the sum of pair lies in the range a and b ''' def countpairs(array, a, b): num_of_pairs = 0 for i ...
Sort the array first and count the pairs by two indexes. The two indexes approach is similar to the one in [2-sum problem](http://stackoverflow.com/questions/11928091/linear-time-algorithm-for-2-sum), which avoids the binary-search for `N` times. The time consuming of the algorithm is `Sort Complexity + O(N)`, typicall...
Is it possible to use a function in an SQLAlchemy filter?
27,707,443
3
2014-12-30T14:44:51Z
27,708,991
7
2014-12-30T16:28:50Z
[ "python", "sqlalchemy" ]
I have a function that checks an object for some properties and returns boolean values depending on the result. It's too complex to write it in filter, but it works and returns the right value. Now I want to use sqlalchemy to return all objects that this function returns True for. I tried: ``` DBSession.query(MyObjec...
As I said in my comment hybrid\_method/hybrid\_property is the appropriate pattern for your use case. It may at first seem complicated but it's actually quite simple. The first version of the function operates exactly like a python method or property and the second part acts as a class method. SQLAlchemy filters work o...
Why does a pandas Series of DataFrame mean fail, but sum does not, and how to make it work
27,709,433
4
2014-12-30T16:59:28Z
27,709,994
7
2014-12-30T17:40:47Z
[ "python", "pandas" ]
There may be a smarter way to do this in Python Pandas, but the following example should, but doesn't work: ``` import pandas as pd import numpy as np df1 = pd.DataFrame([[1, 0], [1, 2], [2, 0]], columns=['a', 'b']) df2 = df1.copy() df3 = df1.copy() idx = pd.date_range("2010-01-01", freq='H', periods=3) s = pd.Serie...
You could (as suggested by @unutbu) use a hierarchical index but when you have a three dimensional array you should consider using a "[pandas Panel](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Panel.html)". Especially when one of the dimensions represents time as in this case. The **Panel** is oft ove...
Is there an analysis speed or memory usage advantage to using HDF5 for large array storage (instead of flat binary files)?
27,710,245
26
2014-12-30T18:00:27Z
27,713,489
55
2014-12-30T22:26:40Z
[ "python", "numpy", "hdf5", "pytables", "h5py" ]
I am processing large 3D arrays, which I often need to slice in various ways to do a variety of data analysis. A typical "cube" can be ~100GB (and will likely get larger in the future) It seems that the typical recommended file format for large datasets in python is to use HDF5 (either h5py or pytables). My question i...
## HDF5 Advantages: Organization, flexibility, interoperability Some of the main advantages of HDF5 are its hierarchical structure (similar to folders/files), optional arbitrary metadata stored with each item, and its flexibility (e.g. compression). This organizational structure and metadata storage may sound trivial,...
Convert string to modified digit
27,713,354
2
2014-12-30T22:13:24Z
27,713,368
11
2014-12-30T22:14:55Z
[ "python" ]
I have the following numbers, which I want to convert: ``` '2.44' --> '2.44' '12.83' --> '2.83' '121.834' --> '1.83' ``` In other words, I want 1 digit to the left of the decimal point and two digits to the right. What would be the best way to do this? My current method is using: ``` number = '41.33' index = number....
``` result = number[index - 1: index + 3] ``` that is all
Convert string to modified digit
27,713,354
2
2014-12-30T22:13:24Z
27,713,379
8
2014-12-30T22:16:12Z
[ "python" ]
I have the following numbers, which I want to convert: ``` '2.44' --> '2.44' '12.83' --> '2.83' '121.834' --> '1.83' ``` In other words, I want 1 digit to the left of the decimal point and two digits to the right. What would be the best way to do this? My current method is using: ``` number = '41.33' index = number....
You can use regex. ``` >>> print re.search('\d\.\d\d', '121.834').group() 1.83 ```
Test if value exists in several lists
27,715,213
4
2014-12-31T01:57:01Z
27,715,222
10
2014-12-31T01:58:15Z
[ "python", "list", "list-comprehension", "boolean-logic" ]
I would like to check if a value exists in every list. The following returns `True` as expected, but seems un-pythonic. What is the correct/more elegant way to do this? ``` a = [1 ,2] b = [1, 3] c = [1, 4] d = [2, 5] False in [True if 1 in l else False for l in [a, b, c, d] ] ```
You can use [`all`](https://docs.python.org/3/library/functions.html#all) and a [generator expression](https://docs.python.org/3/reference/expressions.html#grammar-token-generator_expression): ``` all(1 in x for x in (a, b, c, d)) ``` Demo: ``` >>> a = [1 ,2] >>> b = [1, 3] >>> c = [1, 4] >>> d = [2, 5] >>> all(1 in...
simple web crawler i need to eliminate the duplicate URL that present in the array
27,716,765
3
2014-12-31T05:51:39Z
27,716,774
7
2014-12-31T05:52:25Z
[ "python", "web-scraping", "web-crawler" ]
i am using the array to store the URL and i need to eliminate the URL the are present more than once in array because i don't need to crawl the same URL again: ``` self.level = [] # array where the URL are present for link in self.soup.find_all('a'): self.level.append(link.get('href')) print(self.level) ``` ...
Maintain a [`set`](https://docs.python.org/2/library/sets.html) of urls: ``` self.level = set() for link in self.soup.find_all('a'): self.level.add(link.get('href')) ```
Which is more efficient in Python: list.index() or dict.get()
27,718,318
3
2014-12-31T08:27:07Z
27,718,347
7
2014-12-31T08:29:43Z
[ "python" ]
I'm trying to solve [a problem on LeetCode.](https://oj.leetcode.com/problems/two-sum/) I'm using Python and I made an attempt as follows: ``` def twoSum(self, num, target): index0 = 0 index1 = -1 for item in num: index0 += 1 other = target - item try: index1 = num[inde...
> Is `list.index()` slower than `dict.get()`? In a word, yes: `list.index()` has to scan the list to look for the element, whereas `dict.get()` can do its job in [constant time](http://en.wikipedia.org/wiki/Time_complexity#Constant_time) (i.e. in time that's independent of the size of the dictionary). Thus the first ...
Same Python code returns different results for same input string
27,721,710
2
2014-12-31T13:17:09Z
27,721,740
10
2014-12-31T13:19:59Z
[ "python", "python-3.x" ]
Below code is supposed to return the most common letter in the TEXT string in the format: * always lowercase * ignoring punctuation and spaces * in the case of words such as "One" - where there is no 2 letters the same - return the first letter in the alphabet Each time I run the code using the same string, e.g. "One...
`Counter` uses a dictionary: ``` >>> Counter('one') Counter({'e': 1, 'o': 1, 'n': 1}) ``` Dictionaries are not ordered, hence the behavior.
Iterate through multiple sorted lists in order
27,725,835
4
2014-12-31T20:01:05Z
27,725,863
10
2014-12-31T20:04:11Z
[ "python", "list", "iterator", "order" ]
Suppose I have a number of lists of pairs (int, str), not necessarily of the same length. The only constraint here is that the lists are sorted in ascending order by their integer parts: ``` a = [(1, 'a'), (4, 'a'), (6, 'b'), (7, 'c'), (12, 'a')] b = [(5, 'd'), (10, 'c'), (11,'e')] c = [(0, 'b'), (3, 'd')] ``` What I...
Since the lists are already sorted, you can use [`heapq.merge`](https://docs.python.org/3/library/heapq.html#heapq.merge): ``` >>> import heapq >>> a = [(1, 'a'), (4, 'a'), (6, 'b'), (7, 'c'), (12, 'a')] >>> b = [(5, 'd'), (10, 'c'), (11,'e')] >>> c = [(0, 'b'), (3, 'd')] >>> for i in heapq.merge(a, b, c): ... i ....
Python glob but against a list of strings rather than the filesystem
27,726,545
7
2014-12-31T21:41:08Z
29,725,346
14
2015-04-19T03:09:06Z
[ "python", "regex", "python-2.7", "glob" ]
I want to be able to match a pattern in [`glob`](https://docs.python.org/2/library/glob.html) format to a list of strings, rather than to actual files in the filesystem. Is there any way to do this, or convert a `glob` pattern easily to a regex?
The `glob` module uses the [`fnmatch` module](https://docs.python.org/2/library/fnmatch.html) for *individual path elements*. That means the path is split into the directory name and the filename, and if the directory name contains meta characters (contains any of the characters `[`, `*` or `?`) then these are expande...
Django REST: How to use Router in application level urls.py?
27,728,989
7
2015-01-01T07:16:45Z
27,735,254
8
2015-01-01T22:24:24Z
[ "python", "django", "django-rest-framework" ]
My Django project structure: ``` mysite/ mysite/ ... urls.py scradeweb/ ... models.py serializers.py views.py urls.py manage.py ``` If I use Django REST `router` in the project level urls.py (`mysite/urls.py`) like below, everything works fine: ``` ...
The problem here is that you are using Django REST Framework with a namespace. Many components do not work well with them, which **doesn't mean they can't be used**, so you need to work around the issues by doing a lot of manual work. The main problem is with hyperlinked relations (`Hyperlinked*Field`s), because they h...
Unable to load files using pickle and multipile modules
27,732,354
5
2015-01-01T16:05:00Z
27,733,727
8
2015-01-01T19:05:16Z
[ "python", "multithreading", "login", "pyqt4", "pickle" ]
I'm trying to create a user system, which uses a setting and Gui module, and when the gui module requests for the file to load up using pickle, I keep getting an attribute error. this is from the settings module: ``` import pickle import hashlib class User(object): def __init__(self, fname, lname, dob, gender...
The issue is that you're **pickling objects defined in Settings by actually running the 'Settings' module**, then you're trying to unpickle the objects from the `GUI` module. Remember that pickle doesn't actually store information about how a class/object is constructed, and needs access to the class when unpickling. ...
What is a better way to define a class' __init__ method with optional keyword arguments?
27,732,506
3
2015-01-01T16:26:15Z
27,732,520
9
2015-01-01T16:28:20Z
[ "python", "python-3.x" ]
I want the class to do the same as the following: ``` class Player: def __init__(self, **kwargs): try: self.last_name = kwargs['last_name'] except: pass try: self.first_name = kwargs['first_name'] except: pass try: ...
If you only have 3 arguments, then Bhargav Rao's solution is more appropriate, but if you have a lot of potential arguments then try: ``` class Player: def __init__(self, **kwargs): self.last_name = kwargs.get('last_name') # .. etc. ``` `kwargs.get('xxx')` will return the `xxx` key if it exists, a...
What is a better way to define a class' __init__ method with optional keyword arguments?
27,732,506
3
2015-01-01T16:26:15Z
27,732,540
11
2015-01-01T16:31:57Z
[ "python", "python-3.x" ]
I want the class to do the same as the following: ``` class Player: def __init__(self, **kwargs): try: self.last_name = kwargs['last_name'] except: pass try: self.first_name = kwargs['first_name'] except: pass try: ...
If you have only only 3 keyword args, Then this would be better. ``` class Player: def __init__(self, last_name=None, first_name=None, score=None): self.last_name = last_name self.first_name = first_name self.score = score ```
How `pip install` a package that has non-Python dependencies?
27,734,053
19
2015-01-01T19:44:52Z
27,736,612
10
2015-01-02T02:07:25Z
[ "python", "pip" ]
Many python packages have build dependencies on non-Python packages. I'm specifically thinking of lxml and cffi, but this dilemma applies to a lot of packages on PyPI. Both of these packages have unadvertised build dependencies on non-Python packages like libxml2-dev, libxslt-dev, zlib1g-dev, and libffi-dev. The websit...
This is actually a comment about the answer suggesting using `apt-get` but I don't have enough reputation points to leave one. If you use [virtualenv](https://virtualenv.readthedocs.org/en/latest/) a lot, then installing the python-packages through `apt-get` can become a pain, as you can get mysterious errors when the...
Prevent a function from becoming an instancemethod in Python 2
27,735,009
4
2015-01-01T21:50:42Z
27,735,369
8
2015-01-01T22:40:41Z
[ "python", "python-3.x", "portability", "python-2.x" ]
I'm writing some code that works in Python 3 but not Python 2. ``` foo = lambda x: x + "stuff" class MyClass(ParentClass): bar = foo def mymethod(self): return self.bar(self._private_stuff) ``` I would want it to simply print the private stuff, but if I try to run mymethod, I get: ``` TypeError: un...
Simplest: ``` class MyClass(ParentClass): bar = staticmethod(foo) ``` with the rest of your code staying the same. While `staticmethod` is most often used as a "decorator", there is no requirement to do so (thus, no requirement for a further level of indirection to have `bar` be a decorated method calling `foo`).
Python Itertools permutations only letters and numbers
27,735,409
4
2015-01-01T22:48:31Z
27,735,582
7
2015-01-01T23:12:28Z
[ "python", "permutation", "itertools" ]
I need to get only the permutations that have letters and numbers (The permutation can not be. "A, B, C, D" I need it like this: "A, B, C, 1") In short, the permutations can not contain only letters, not just numbers. Must be a combination of both. My code: ``` import itertools print list(itertools.combinations([0,1...
Using set intersection: ``` import itertools import string numbers = set(range(10)) letters = set(string.ascii_letters) print([x for x in itertools.combinations([0,1,2,3,4,'a','b','c','d'], 4) if set(x) & letters and set(x) & numbers]) ```
How to make python random.random() incorporate negatives
27,735,478
2
2015-01-01T22:59:47Z
27,735,505
8
2015-01-01T23:02:55Z
[ "python", "random", "numbers" ]
I'm trying to generate a pair of random numbers between -1 and 1. I can make it go negative OR positive...but not generate a random number for x and y that may turn out negative as well as positive. Below is what I have (it's a dart throw simulation game from a website). randx and randy are where the random number gen...
I assume you want a floating point number. In that case, use ``` x = random.uniform(-1,1) ```
Cannot reset Pandas index
27,736,267
2
2015-01-02T01:05:51Z
27,736,280
9
2015-01-02T01:08:25Z
[ "python", "pandas", "indexing" ]
I'm not sure where I am astray but I cannot seem to reset the index on a dataframe. When I run `test.head()`, I get the output below: ![test.head](http://i.stack.imgur.com/ijPPJ.png) As you can see, the dataframe is a slice, so the index is out of bounds. What I'd like to do is to reset the index for this dataframe....
`reset_index` by default does not modify the DataFrame; it returns a *new* DataFrame with the reset index. If you want to modify the original, use the `inplace` argument: `df.reset_index(drop=True, inplace=True)`. Alternatively, assign the result of `reset_index` by doing `df = df.reset_index(drop=True)`.
Expected conditions in protractor
27,737,333
7
2015-01-02T04:22:56Z
27,867,319
12
2015-01-09T18:55:53Z
[ "python", "testing", "selenium", "selenium-webdriver", "protractor" ]
While writing selenium tests in Python, I got used to using [Explicit Waits](http://selenium-python.readthedocs.org/en/latest/waits.html) a lot for waiting for a page to load, or for waiting for an element to become visible, or clickable etc: ``` from selenium.webdriver.common.by import By from selenium.webdriver.supp...
Once [feat(expectedConditions)](https://github.com/angular/protractor/pull/1703) is in (probably protractor 1.7), you can do: ``` var EC = protractor.ExpectedConditions; var e = element(by.id('xyz')); browser.wait(EC.presenceOf(e), 10000); expect(e.isPresent()).toBeTruthy(); ``` Please note though, if you're working ...
Django 1.7 makemigrations freezing/hanging
27,739,668
10
2015-01-02T09:02:30Z
28,161,264
7
2015-01-27T00:24:16Z
[ "python", "django", "django-1.7", "django-migrations" ]
I'm finally upgrading from Django 1.6 to 1.7, and removing South in the process. I followed the [official Django instructions](https://docs.djangoproject.com/en/1.7/topics/migrations/#upgrading-from-south) and removed all my old numbered migrations. Now I'm trying to run `python manage.py makemigrations` to get the new...
You should try disabling all of your installed\_apps and seeing if that solves the problem. If it does, isolate the one causing the issues. Then set debugging traces.
pip cffi package installation failed on osx
27,740,044
18
2015-01-02T09:37:43Z
29,467,964
21
2015-04-06T08:42:28Z
[ "python", "osx", "pip", "python-cffi" ]
I am installing cffi package for cryptography and Jasmin installation. I did some research before posting question, so I found following option but which is seems not working: ## System > Mac OSx 10.9.5 > > python2.7 ## Error ``` c/_cffi_backend.c:13:10: fatal error: 'ffi.h' file not found #include <ffi.h> ...
In your terminal try and run: ``` xcode-select --install ``` After that try installing the package again. By default, XCode installs itself as the IDE and does not set up the environment for the use by command line tools; for example, the `/usr/include` folder will be missing. Running the above command will install...
pip cffi package installation failed on osx
27,740,044
18
2015-01-02T09:37:43Z
29,682,918
11
2015-04-16T18:17:41Z
[ "python", "osx", "pip", "python-cffi" ]
I am installing cffi package for cryptography and Jasmin installation. I did some research before posting question, so I found following option but which is seems not working: ## System > Mac OSx 10.9.5 > > python2.7 ## Error ``` c/_cffi_backend.c:13:10: fatal error: 'ffi.h' file not found #include <ffi.h> ...
Install libffi package ``` $ brew install pkg-config libffi ``` and then install cffi ``` $ pip install cffi ``` Source: [Error installing bcrypt with pip on OS X: cant find ffi.h (libffi is installed)](http://stackoverflow.com/questions/22875270/error-installing-bcrypt-with-pip-on-os-x-cant-find-ffi-h-libffi-is-in...
Check if key exists in a Python dict in Jinja2 templates
27,740,153
13
2015-01-02T09:45:48Z
27,740,206
10
2015-01-02T09:50:29Z
[ "python", "django", "jinja2" ]
I have a python dictionary: ``` settings = { "foo" : "baz", "hello" : "world" } ``` This variable `settings` is then available in the Jinja2 template. I want to check if a key `myProperty` exists in the `settings` dict within my template, and if so take some action: ``` {% if settings.hasKey(myProperty) %} ...
This works fine `{% if settings.myProperty %}`
Check if key exists in a Python dict in Jinja2 templates
27,740,153
13
2015-01-02T09:45:48Z
34,839,762
15
2016-01-17T14:59:20Z
[ "python", "django", "jinja2" ]
I have a python dictionary: ``` settings = { "foo" : "baz", "hello" : "world" } ``` This variable `settings` is then available in the Jinja2 template. I want to check if a key `myProperty` exists in the `settings` dict within my template, and if so take some action: ``` {% if settings.hasKey(myProperty) %} ...
Like Mihai and karelv have noted, this works: ``` {% if 'blabla' in item %} ... {% endif %} ``` I get a `'dict object' has no attribute 'blabla'` if I use `{% if item.blabla %}` and `item` does not contain a `blabla` key
Python-pdb skip code (as in "not execute")
27,741,387
4
2015-01-02T11:24:35Z
27,741,817
8
2015-01-02T11:56:05Z
[ "python", "debugging", "pdb" ]
Is there a way to skip a line or two altogether in pdb? Say I have a pdb session: ``` > print 10 import pdb; pdb.set_trace() destroy_the_universe() # side effect useful_line() ``` And I want to go straight to useful\_line() WITHOUT invoking pdb() once again, or destroying the universe. Is there a way to skip (...
Use the `j`/`jump` command: test.py contains: ``` def destroy_the_universe(): raise RuntimeError("Armageddon") def useful_line(): print("Kittens-r-us") print(10) import pdb; pdb.set_trace() destroy_the_universe() useful_line() ``` Then: ``` C:\Temp>c:\python34\python test.py 10 > c:\temp\test.py(9)<module...
Can I speedup YAML?
27,743,711
5
2015-01-02T14:28:15Z
27,744,056
8
2015-01-02T14:56:39Z
[ "python", "json", "yaml" ]
I made a little test case to compare YAML and JSON speed : ``` import json import yaml from datetime import datetime from random import randint NB_ROW=1024 print 'Does yaml is using libyaml ? ',yaml.__with_libyaml__ and 'yes' or 'no' dummy_data = [ { 'dummy_key_A_%s' % i: i, 'dummy_key_B_%s' % i: i } for i in xrang...
You've probably noticed that Python's syntax for data structures is **very** similar to JSON's syntax. What's happening is Python's `json` library encodes Python's builtin datatypes [directly into text chunks](https://github.com/python-git/python/blob/master/Lib/json/decoder.py), replacing `'` into `"` and deleting `,...
Is Python's == an equivalence relation on the floats?
27,743,917
34
2015-01-02T14:44:28Z
27,743,974
34
2015-01-02T14:50:09Z
[ "python", "floating-point", "arithmetic-expressions" ]
In native Python, without using NumPy (for which `numpy.nan != numpy.nan`) there is no NaN, so am I right in thinking that Python's floating point `==` is reflexive? Then since it is symmetric (`a == b` implies `b == a`) and transitive (if `a==b` and `b==c` then `a==c`), can we say that Python's `==` is an equivalence ...
`float('nan')` exists in native Python and `float('nan') != float('nan')`. So no, `==` is not an [equivalence relation](http://en.wikipedia.org/wiki/Equivalence_relation#Definition) since it lacks reflexivity: ``` In [40]: float('nan') == float('nan') Out[40]: False ```
Is Python's == an equivalence relation on the floats?
27,743,917
34
2015-01-02T14:44:28Z
27,744,584
45
2015-01-02T15:39:33Z
[ "python", "floating-point", "arithmetic-expressions" ]
In native Python, without using NumPy (for which `numpy.nan != numpy.nan`) there is no NaN, so am I right in thinking that Python's floating point `==` is reflexive? Then since it is symmetric (`a == b` implies `b == a`) and transitive (if `a==b` and `b==c` then `a==c`), can we say that Python's `==` is an equivalence ...
`==` is reflexive for all numbers, zero, -zero, ininity, and -infinity, but not for nan. You can get `inf`, `-inf`, and `nan` in native Python just by arithmetic operations on literals, like below. These behave correctly, as in IEEE 754 and without math domain exception: ``` >>> 1e1000 == 1e1000 True >>> 1e1000/1e10...
Reshaping a pandas dataframe into stacked/record/database/long format
27,744,276
3
2015-01-02T15:14:32Z
27,744,390
7
2015-01-02T15:23:29Z
[ "python", "numpy", "pandas", "scientific-computing" ]
What is the best way to convert a pandas dataframe from wide format into stacked/record/database/long format? Here's a small code example: Wide format: ``` date hour1 hour2 hour3 hour4 2012-12-31 9.18 -0.10 -7.00 -64.92 2012-12-30 13.91 0.09 -0.96 0.08 2012-12-29 12.97 11.82 11.65 10.20 2012-...
You can use [`melt`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.melt.html) to convert a DataFrame from wide format to long format: ``` import pandas as pd df = pd.DataFrame({'date': ['2012-12-31', '2012-12-30', '2012-12-29', '2012-12-28', '2012-12-27'], 'hour1': [9.18, 13.91, 12.97...
Finding consecutive consonants in a word
27,744,882
13
2015-01-02T16:03:13Z
27,744,905
20
2015-01-02T16:04:37Z
[ "python", "string" ]
I need a code that will show me the consecutive consonants in a word. for example for `suiteConsonnes("concertation")` I need to obtain `["c","nc","rt","t","n"]` here is my code: ``` def SuiteConsonnes(mot): consonnes=[] for x in mot: if x in "bcdfghjklmnprstvyz": consonnes += x + '' re...
You can use regular expressions, implemented in the [**`re` module**](https://docs.python.org/2/library/re.html) **Better solution** ``` >>> re.findall(r'[bcdfghjklmnpqrstvwxyz]+', "concertation", re.IGNORECASE) ['c', 'nc', 'rt', 't', 'n'] ``` * `[bcdfghjklmnprstvyz]+` matches any sequence of one or more characters ...
Finding consecutive consonants in a word
27,744,882
13
2015-01-02T16:03:13Z
27,744,910
10
2015-01-02T16:05:04Z
[ "python", "string" ]
I need a code that will show me the consecutive consonants in a word. for example for `suiteConsonnes("concertation")` I need to obtain `["c","nc","rt","t","n"]` here is my code: ``` def SuiteConsonnes(mot): consonnes=[] for x in mot: if x in "bcdfghjklmnprstvyz": consonnes += x + '' re...
You could do this with regular expressions and the `re` module's `split` function: ``` >>> import re >>> re.split(r"[aeiou]+", "concertation", flags=re.I) ['c', 'nc', 'rt', 't', 'n'] ``` This method splits the string whenever one or more consecutive vowels are matched. To explain the regular expression `"[aeiou]+"`:...
Finding consecutive consonants in a word
27,744,882
13
2015-01-02T16:03:13Z
27,745,028
9
2015-01-02T16:13:38Z
[ "python", "string" ]
I need a code that will show me the consecutive consonants in a word. for example for `suiteConsonnes("concertation")` I need to obtain `["c","nc","rt","t","n"]` here is my code: ``` def SuiteConsonnes(mot): consonnes=[] for x in mot: if x in "bcdfghjklmnprstvyz": consonnes += x + '' re...
If you are up for a non-regex solution, `itertools.groupby` would work perfectly fine here, like this ``` >>> from itertools import groupby >>> is_vowel = lambda char: char in "aAeEiIoOuU" >>> def suiteConsonnes(in_str): ... return ["".join(g) for v, g in groupby(in_str, key=is_vowel) if not v] ... >>> suiteConso...
Redis Pubsub and Message Queueing
27,745,842
14
2015-01-02T17:13:17Z
27,746,701
29
2015-01-02T18:23:24Z
[ "python", "redis", "redis-cli" ]
My overall question is: *Using Redis for PubSub, what happens to messages when publishers push messages into a channel faster than subscribers are able to read them?* For example, let's say I have: * A simple publisher publishing messages at the rate of 2 msg/sec. * A simple subscriber reading messages at the rate of...
The tests are valid, but the conclusions are partially wrong. Redis does not queue anything on pub/sub channels. On the contrary, it tends to read the item from the publisher socket, and write the item in all the subscriber sockets, ideally in the same iteration of the event loop. Nothing is kept in Redis data structu...
How do I inform PyCharm of the location of custom modules?
27,746,248
5
2015-01-02T17:43:04Z
27,781,932
9
2015-01-05T14:49:08Z
[ "python", "pycharm" ]
I have an application at work that is set up with the following structure. ``` /project_root /applications /app1 __init__.py /app2 __init__.py ... /appN /pkg /database __init__.py /toolbox __init__.py ... ...
The solution to this was a two step process: 1. Add the `pkg` directory as a source root. Do this by selecting `File` -> `Settings` -> `Project` -> (select the project) -> `Project Structure` then select the `pkg` directory and add by clicking the `Sources` button. Click Ok. 2. Then select `File` -> `Invalidate Caches...
Python name 'os' is not defined even though it is explicitly imported
27,747,288
8
2015-01-02T19:11:02Z
27,747,434
13
2015-01-02T19:22:47Z
[ "python", "python-3.x" ]
I have a module called `imtools.py` that contains the following function: ``` import os def get_imlist(path): return[os.path.join(path,f) for f in os.listdir(path) if f.endswith('.jpg')] ``` When I attempt to call the function `get_imlist` from the console using `import imtools` and `imtools.get_imlist(path)`, ...
Based on small hints, I'm going to guess that your code didn't originally have the `import os` line in it but you corrected this in the source and re-imported the file. The problem is that Python caches modules. If you `import` more than once, each time you get back the same module - it isn't re-read. The mistake you ...
Python3.4 can't install mysql-python
27,748,556
6
2015-01-02T21:06:49Z
27,748,679
13
2015-01-02T21:18:39Z
[ "python", "mysql", "django", "python-3.x" ]
``` # pip3.4 install mysql-python Downloading/unpacking mysql-python Downloading MySQL-python-1.2.5.zip (108kB): 108kB downloaded Running setup.py (path:/tmp/pip_build_root/mysql-python/setup.py) egg_info for package mysql-python Traceback (most recent call last): File "<string>", line 17, in <module> ...
[MySQL-python 1.2.5](https://pypi.python.org/pypi/MySQL-python/1.2.5) does not support Python 3. The [Django 1.7 docs](https://docs.djangoproject.com/en/1.7/ref/databases/#mysql-db-api-drivers) recommend the fork [mysqlclient](https://pypi.python.org/pypi/mysqlclient).
What is the difference between random.normalvariate() and random.gauss() in python?
27,749,133
10
2015-01-02T22:02:12Z
27,749,440
7
2015-01-02T22:36:16Z
[ "python", "random", "gaussian", "normal-distribution" ]
What is the difference between [`random.normalvariate()`](http://docs.python.org/library/random.html#random.normalvariate) and [`random.gauss()`](https://docs.python.org/2/library/random.html#random.gauss)? They take the same parameters and return the same value, performing essentially the same function. I understand...
This is an interesting question. In general, the best way to know the difference between two python implementations is to *inspect the code yourself*: ``` import inspect, random str_gauss = inspect.getsource(random.gauss) str_nv=inspect.getsource(random.normalvariate) ``` and then you print each of the strings to see...
Python matplotlib Cairo error
27,749,664
14
2015-01-02T22:57:13Z
34,064,777
21
2015-12-03T11:24:57Z
[ "python", "matplotlib", "plot", "python-3.4" ]
I'm using something simpler than the sample code on the [pyplot tutorial](http://matplotlib.org/users/pyplot_tutorial.html) website: ``` import matplotlib.pyplot as plt plt.plot([1,2,3,4,5]) plt.show() ``` but when I run it, I get the error: `TypeError: Couldn't find foreign struct converter for 'cairo.Context'` I'...
This is in case someone is having the same problem on Ubuntu 14.04, as I did using Python 3.4.3. By using bits and hints from JDong's answer, I've solved the problem as follows. (Basically change the MatPlotLib backend to `qt5agg`.) 1. Install `python3-pyqt5`. `sudo apt-get install python3-pyqt5` 2. Find out where ...
How can I strip the file extension from a list full of filenames?
27,750,611
4
2015-01-03T00:51:16Z
27,750,632
7
2015-01-03T00:53:48Z
[ "python", "list", "path", "file-extension" ]
I am using the following to get a list with all the files inside a directory called `tokens`: ``` import os accounts = next(os.walk("tokens/"))[2] ``` Output: ``` >>> print accounts ['.DS_Store', 'AmieZiel.py', 'BrookeGianunzio.py', 'FayPinkert.py', 'JoieTrevett.py', 'KaroleColinger.py', 'KatheleenCaban.py', 'La...
You can actually do this in one line with a [list comprehension](https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions): ``` lst = [os.path.splitext(x)[0] for x in accounts] ``` But if you want/need a for-loop, the equivalent code would be: ``` lst = [] for x in accounts: lst.append(os.path....
How to replace negative numbers in Pandas Data Frame by zero
27,759,084
4
2015-01-03T20:14:14Z
27,759,140
11
2015-01-03T20:20:54Z
[ "python", "replace", "pandas" ]
I would like to know if there is someway of replacing all DataFrame negative numbers by zeros?
If all your columns are numeric, you can use boolean indexing: ``` In [1]: import pandas as pd In [2]: df = pd.DataFrame({'a': [0, -1, 2], 'b': [-3, 2, 1]}) In [3]: df Out[3]: a b 0 0 -3 1 -1 2 2 2 1 In [4]: df[df < 0] = 0 In [5]: df Out[5]: a b 0 0 0 1 0 2 2 2 1 ``` --- For the more general ...
Why is hardcoding this list slower than calculating it?
27,762,547
46
2015-01-04T04:57:48Z
27,762,852
11
2015-01-04T05:56:42Z
[ "python", "performance", "python-3.x", "python-internals" ]
I want to assign the first 1024 terms of [this sequence](http://oeis.org/A007814) to a list. I initially guessed that hardcoding this list would be the fastest way. I also tried generating the list algorithmically and found this to be faster than hardcoding. I therefore tested various compromise approaches, using incre...
It looks like loading/copying a pre-created list, and performing an in-place addition of those lists, is three python bytecode operations (two LOAD\_FASTs and one INPLACE\_ADD) that probably gets ultra-optimized in the bowels of the CPython interpreter's C code, while individually specifying each component requires a s...
Why is hardcoding this list slower than calculating it?
27,762,547
46
2015-01-04T04:57:48Z
27,763,902
43
2015-01-04T08:48:19Z
[ "python", "performance", "python-3.x", "python-internals" ]
I want to assign the first 1024 terms of [this sequence](http://oeis.org/A007814) to a list. I initially guessed that hardcoding this list would be the fastest way. I also tried generating the list algorithmically and found this to be faster than hardcoding. I therefore tested various compromise approaches, using incre...
Firstly, your timing is done in a high overhead way. You should use this instead: ``` def hardcoded(): m = [0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,5,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,6,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,5,0,1,0,2,0,1,0,3...
Pandas to_sql with parameterized data types like NUMERIC(10,2)
27,766,283
3
2015-01-04T14:03:24Z
27,769,930
8
2015-01-04T20:21:08Z
[ "python", "postgresql", "pandas", "sqlalchemy" ]
Pandas has a lovely `to_sql` method for writing dataframes to any RDBMS supported by SQLAlchemy. Say I have a dataframe generated thusly: ``` df = pd.DataFrame([-1.04, 0.70, 0.11, -0.43, 1.0], columns=['value']) ``` If I try to write it to the database without any special behavior, I get a column type of double prec...
Update: this bug is fixed for pandas >= 0.16.0 --- This is post about a recent pandas bug with the same error with 0.15.2. <https://github.com/pydata/pandas/issues/9083> A Collaborator suggests a to\_sql monkey patch as a way to solve it ``` from pandas.io.sql import SQLTable def to_sql(self, frame, name, if_exis...
Switching from SQLite to MySQL with Flask SQLAlchemy
27,766,794
6
2015-01-04T14:59:22Z
28,391,385
9
2015-02-08T06:51:00Z
[ "python", "mysql", "database", "sqlite", "flask-sqlalchemy" ]
I have a site that I've built with Flask SQLAlchemy and SQLite, and need to switch to MySQL. I have migrated the database itself and have it running under MySQL, but 1. Can't figure out how to connect to the MySQL database (that is, what the `SQLALCHEMY_DATABASE_URI` should be) and 2. Am unclear if any of my existing ...
The tutorial pointed by you shows the right way of connecting to MySQL using SQLAlchemy. Below is your code with very little changes: My assumptions are your MySQL server is running on the same machine where Flask is running and the database name is db\_name. In case your server is not same machine, put the server IP ...
anonymous function assignment using a one line if statement
27,770,145
5
2015-01-04T20:41:33Z
27,770,177
11
2015-01-04T20:45:08Z
[ "python" ]
When assigning a variable to an anonymous function using a one line if statement, the 'else' case does not behave as expected. Instead of assigning the anonymous function listed after the 'else', a *different* anonymous function is assigned. This function returns the *expected* anonymous function. ``` >> fn = lambda x...
`lambda` has a weaker binding than the conditional expression. In fact, it has the least operator precedence in the language. From the [documentation](https://docs.python.org/3/reference/expressions.html#operator-precedence)1: ![enter image description here](http://i.stack.imgur.com/MrvXx.png) So, this line: ``` fn ...
Using Scrapy to crawl a public FTP server
27,770,610
2
2015-01-04T21:36:57Z
27,895,155
8
2015-01-12T04:06:14Z
[ "python", "ftp", "web-scraping", "scrapy", "twisted" ]
How can I make Scrapy crawl a FTP server that doesn't require a username and password? I've tried adding the url to the start urls, but Scrapy requires a username and password for FTP access. I've overridden `start_requests()` to provide a default one (the username 'anonymous' and a blank password works when I try it w...
It is not documented, but Scrapy has this functionality built-in. There is an [`FTPDownloadHandler`](https://github.com/scrapy/scrapy/blob/master/scrapy/core/downloader/handlers/ftp.py) which handles FTP download using twisted's `FTPClient`. You don't need to call it directly, it would [automagically turn on](https://g...
Why are lil_matrix and dok_matrix so slow compared to common dict of dicts?
27,770,906
6
2015-01-04T22:09:23Z
27,771,335
7
2015-01-04T23:03:54Z
[ "python", "numpy", "scipy" ]
I want to iteratively build sparse matrices, and noticed that there are two suitable options for this according to the SciPy documentation: [LiL matrix](http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.sparse.lil_matrix.html#scipy.sparse.lil_matrix): > class scipy.sparse.lil\_matrix(arg1, shape=None, ...
When I change your `+=` to just `=` for your 2 sparse arrays: ``` for row, col in zip(rows, cols): #freqs[row,col] += 1 freqs[row,col] = 1 ``` their respective times are cut in half. What's consuming the most time is the indexing. With `+=` it is has to do both a `__getitem__` and a `__setitem__`. When the d...
Django template convert to string
27,771,000
4
2015-01-04T22:18:37Z
27,771,117
14
2015-01-04T22:33:44Z
[ "python", "django" ]
Is there a way to convert a number to a string in django's template? Or do I need to make a custom template tag. Something like: ``` {{ 1|stringify }} # '1' ```
You can use [`stringformat`](https://docs.djangoproject.com/en/dev/ref/templates/builtins/#stringformat) to convert a variable to a string: ``` {{ value|stringformat:"i" }} ``` See [documentation](https://docs.python.org/2/library/stdtypes.html#string-formatting-operations) for formatting options (the leading `%` sho...