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
Importing modules in Python - best practice
9,916,878
33
2012-03-28T22:58:43Z
9,916,925
14
2012-03-28T23:05:13Z
[ "python", "coding-style", "workflow" ]
I am new to Python as I want to expand skills that I learned using R. In R I tend to load a bunch of libraries, sometimes resulting in function name conflicts. What is best practice in Python. I have seen some specific variations that I do not see a difference between `import pandas`, `from pandas import *`, and `fro...
In general it is better to do explicit imports. As in: ``` import pandas frame = pandas.DataFrame() ``` Or: ``` from pandas import DataFrame frame = DataFrame() ``` Another option in Python, when you have conflicting names, is import x as y: ``` from pandas import DataFrame as PDataFrame from bears import DataFram...
Importing modules in Python - best practice
9,916,878
33
2012-03-28T22:58:43Z
15,780,908
9
2013-04-03T07:05:06Z
[ "python", "coding-style", "workflow" ]
I am new to Python as I want to expand skills that I learned using R. In R I tend to load a bunch of libraries, sometimes resulting in function name conflicts. What is best practice in Python. I have seen some specific variations that I do not see a difference between `import pandas`, `from pandas import *`, and `fro...
``` from A import B ``` essentially equals following three statements ``` import A B = A.B del A ``` That's it, that is it all.
Last element in OrderedDict
9,917,178
12
2012-03-28T23:35:30Z
9,917,213
25
2012-03-28T23:40:48Z
[ "python", "python-3.x", "ordereddictionary" ]
I have `od` of type `OrderedDict`. I want to access its most recently added (key, value) pair. `od.popitem(last = True)` would do it, but would also remove the pair from `od` which I don't want. What's a good way to do that? Can /should I do this: ``` class MyOrderedDict(OrderedDict): def last(self): return nex...
Using `next(reversed(od))` is a perfect way of accessing the most-recently added element. The class `OrderedDict` uses a doubly linked list for the dictionary items and implements [`__reversed__()`](http://docs.python.org/reference/datamodel.html#object.__reversed__), so this implementation gives you O(1) access to the...
Last element in OrderedDict
9,917,178
12
2012-03-28T23:35:30Z
9,917,479
8
2012-03-29T00:12:21Z
[ "python", "python-3.x", "ordereddictionary" ]
I have `od` of type `OrderedDict`. I want to access its most recently added (key, value) pair. `od.popitem(last = True)` would do it, but would also remove the pair from `od` which I don't want. What's a good way to do that? Can /should I do this: ``` class MyOrderedDict(OrderedDict): def last(self): return nex...
A little magic from timeit can help here... ``` from collections import OrderedDict class MyOrderedDict1(OrderedDict): def last(self): k=next(reversed(self)) return (k,self[k]) class MyOrderedDict2(OrderedDict): def last(self): out=self.popitem() self[out[0]]=out[1] return out class MyOrde...
What is the most Pythonic way to interleave text file contents?
9,917,334
2
2012-03-28T23:55:29Z
9,917,380
7
2012-03-29T00:01:00Z
[ "python" ]
Python question: If I have a list of files, how do I print line #1 from each file, then line #2, etc.? (I'm a Python newbie, obviously...) Example: ``` file1: foo1 bar1 file2: foo2 bar2 file3: foo3 bar3 ``` Function call: ``` names = ["file1", "file2", "file3"] myfct(names) ``` Desired output: ``` foo1 foo2 fo...
``` for lines in itertools.izip(*file_handlers): sys.stdout.write(''.join(lines)) ```
python csv write only certain fieldnames, not all
9,917,780
2
2012-03-29T00:55:25Z
9,917,862
9
2012-03-29T01:09:33Z
[ "python", "csv" ]
I must be missing something, but I don't get it. I have a csv, it has 1200 fields. I'm only interested in 30. How do you get that to work? I can read/write the whole shebang, which is ok, but i'd really like to just write out the 30. I have a list of the fieldnames and I'm kinda hacking the header. How would I transla...
Here's an example of using `DictWriter` to write out only fields you care about. I'll leave the porting work to you: ``` import csv headers = ['a','b','d','g'] with open('in.csv','rb') as _in, open('out.csv','wb') as out: reader = csv.DictReader(_in) writer = csv.DictWriter(out,headers,extrasaction='ignore')...
binary search in python weird behavior
9,918,348
2
2012-03-29T02:32:41Z
9,918,380
12
2012-03-29T02:37:13Z
[ "python", "binary-search" ]
Please look at this code: ``` def chop(array, search): lo = 0 high = len(array) - 1 while lo <= high: mid = (high + lo) /2 if array[mid] == search: return 'true' elif search > array[mid]: low = mid +...
I'm guessing this is your bug: ``` low = mid + 1 ``` Your while loop uses the variable `lo`, and you're defining a new variable called `low` within your while loop. In essence, you're never updating your `lo` variable. Change that line to: ``` lo = mid + 1 ``` and your algorithm should work.
how to convert xls to xlsx
9,918,646
6
2012-03-29T03:20:08Z
9,919,409
9
2012-03-29T05:11:08Z
[ "python", "excel", "xls", "xlsx", "uno" ]
I have some \*.xls(excel 2003) files, and I want to convert those files into xlsx(excel 2007). I use the uno python package, when I save the documents, I can set the Filter name: MS Excel 97 But there is no Filter name like 'MS Excel 2007', please help me, how can set the the filter name to convert xls to xlsx ?
I've had to do this before. The main idea is to use the **xlrd** module to open and parse a xls file and write the content to a **xlsx** file using the **openpyxl** module. Here's my code. ***Attention!*** It cannot handle complex xls files, you should add you own parsing logic if you are going to use it. ``` import ...
Python's SQLAlchemy doesn't clean out the secondary (many-to-many) table?
9,918,653
8
2012-03-29T03:20:57Z
9,927,719
11
2012-03-29T14:43:00Z
[ "python", "many-to-many", "sqlalchemy" ]
I have a many-to-many relationship between `User`s and `Task`s. I want the "secondary table" (meaning, the table that facilitates the many-to-many relation) to be cleaned out when I delete a `Task` or `User`. How can I configure SQLAlchemy for this? Here is some sample python code which demonstrates the problem I'm ha...
Here's the relevant docs ( <http://docs.sqlalchemy.org/en/latest/orm/query.html?highlight=query.delete#sqlalchemy.orm.query.Query.delete>): "The method does not offer in-Python cascading of relationships - it is assumed that ON DELETE CASCADE is configured for any foreign key references which require it. The Session n...
Sorting a dictionary by value then key
9,919,342
10
2012-03-29T05:03:58Z
9,919,379
22
2012-03-29T05:07:45Z
[ "python", "sorting", "dictionary" ]
I can sort by key or value, but I need it sorted by value, then key, in one line. To explain this better I can show you my problem: ``` dict = {'apple': 2, 'banana': 3, 'almond':2 , 'beetroot': 3, 'peach': 4} ``` I want my output to be sorted descending by their value and then ascending (A-Z) by their key (alphabetic...
You need to take advantage of the fact that the values are numbers. ``` >>> [v[0] for v in sorted(d.iteritems(), key=lambda(k, v): (-v, k))] ['peach', 'banana', 'beetroot', 'almond', 'apple'] ```
parsing HTML table using python - HTMLparser or lxml
9,919,493
10
2012-03-29T05:21:09Z
9,920,703
16
2012-03-29T07:16:11Z
[ "python", "html", "parsing", "lxml" ]
I have a html page which consist of a table & I want to fetch all the values in td, tr in that table. I have tried working with beautifulsoup but now i wanted to work on lxml or HML parser with python. I have attached the example. I want to fetch values as lists of tuple as ``` [ [( value of 2050 jan, value of ma...
Something like this should work: ``` >>> from lxml.html import parse >>> page = parse("test.html") >>> rows = page.xpath("body/table")[0].findall("tr") >>> data = list() >>> for row in rows: ... data.append([c.text for c in row.getchildren()]) ... >>> for row in data[4:]: print(row) ... ['2050', 'January', '0', ...
Efficiently calculate word frequency in a string
9,919,604
6
2012-03-29T05:32:54Z
9,919,663
15
2012-03-29T05:39:27Z
[ "python", "parsing", "lambda", "word-frequency" ]
I am parsing a long string of text and calculating the number of times each word occurs in Python. I have a function that works but I am looking for advice on whether there are ways I can make it more efficient(in terms of speed) and whether there's even python library functions that could do this for me so I'm not rei...
Use [`collections.Counter`](http://docs.python.org/library/collections.html#collections.Counter): ``` >>> from collections import Counter >>> test = 'abc def abc def zzz zzz' >>> Counter(test.split()).most_common() [('abc', 2), ('zzz', 2), ('def', 2)] ```
How do I add a link from the Django admin page of one object to the admin page of a related object?
9,919,780
25
2012-03-29T05:53:00Z
9,984,561
10
2012-04-02T22:11:45Z
[ "python", "django", "django-models", "django-admin", "django-templates" ]
To deal with the [lack of nested inlines](http://stackoverflow.com/questions/3681258/nested-inlines-in-the-django-admin) in django-admin, I've put special cases into two of the templates to create links between the admin change pages and inline admins of two models. **My question is: how do I create a link from the ad...
Use [readonly\_fields](https://docs.djangoproject.com/en/1.3/ref/contrib/admin/#django.contrib.admin.ModelAdmin.readonly_fields): ``` class MyInline(admin.TabularInline): model = MyModel readonly_fields = ['link'] def link(self, obj): url = reverse(...) return mark_safe("<a href='%s'>edit<...
How do I add a link from the Django admin page of one object to the admin page of a related object?
9,919,780
25
2012-03-29T05:53:00Z
10,011,307
10
2012-04-04T12:41:16Z
[ "python", "django", "django-models", "django-admin", "django-templates" ]
To deal with the [lack of nested inlines](http://stackoverflow.com/questions/3681258/nested-inlines-in-the-django-admin) in django-admin, I've put special cases into two of the templates to create links between the admin change pages and inline admins of two models. **My question is: how do I create a link from the ad...
This is my current solution, based on what was suggested by Pannu (in his edit) and Mikhail. I have a couple of top-level admin change view I need to link to a top-level admin change view of a related object, and a couple of inline admin change views I need to link to the top-level admin change view of the same object...
How do I add a link from the Django admin page of one object to the admin page of a related object?
9,919,780
25
2012-03-29T05:53:00Z
13,287,201
10
2012-11-08T10:30:23Z
[ "python", "django", "django-models", "django-admin", "django-templates" ]
To deal with the [lack of nested inlines](http://stackoverflow.com/questions/3681258/nested-inlines-in-the-django-admin) in django-admin, I've put special cases into two of the templates to create links between the admin change pages and inline admins of two models. **My question is: how do I create a link from the ad...
I think that agf's solution is pretty awesome -- lots of kudos to him. But I needed a couple more features: * to be able to have multiple links for one admin * to be able to link to model in different app Solution: ``` def add_link_field(target_model = None, field = '', app='', field_name='link', ...
How do I add a link from the Django admin page of one object to the admin page of a related object?
9,919,780
25
2012-03-29T05:53:00Z
31,673,867
8
2015-07-28T10:36:02Z
[ "python", "django", "django-models", "django-admin", "django-templates" ]
To deal with the [lack of nested inlines](http://stackoverflow.com/questions/3681258/nested-inlines-in-the-django-admin) in django-admin, I've put special cases into two of the templates to create links between the admin change pages and inline admins of two models. **My question is: how do I create a link from the ad...
New in Django 1.8 : [show\_change\_link for inline admin](https://docs.djangoproject.com/en/1.8/ref/contrib/admin/#django.contrib.admin.InlineModelAdmin.show_change_link). Set **show\_change\_link** to **True** (False by default) in your inline model, so that inline objects have a link to their change form (where they...
How should I expose read-only fields from Python classes?
9,920,677
20
2012-03-29T07:14:53Z
9,920,797
35
2012-03-29T07:22:15Z
[ "python" ]
I have many different small classes which have a few fields each, e.g. this: ``` class Article: def __init__(self, name, available): self.name = name self.available = available ``` What's the easiest and/or most idiomatic way to make the `name` field read only, so that ``` a = Article("Pineapple"...
I would use [`property`](http://docs.python.org/library/functions.html#property) as a decorator to manage your getter for `name` (see the example for the class `Parrot` in the documentation). Use, for example, something like: ``` class Article(object): def __init__(self, name, available): self._name = name...
How should I expose read-only fields from Python classes?
9,920,677
20
2012-03-29T07:14:53Z
9,921,290
7
2012-03-29T07:57:15Z
[ "python" ]
I have many different small classes which have a few fields each, e.g. this: ``` class Article: def __init__(self, name, available): self.name = name self.available = available ``` What's the easiest and/or most idiomatic way to make the `name` field read only, so that ``` a = Article("Pineapple"...
Based in the Chris answer, but arguably more pythonic: ``` def ro_property(field): return property(lambda self : self.__dict__[field]) class Article(object): name = ro_property('_name') def __init__(self): self._name = "banana" ``` If trying to modify the property it will raise an `AttributeErro...
How should I expose read-only fields from Python classes?
9,920,677
20
2012-03-29T07:14:53Z
9,925,468
11
2012-03-29T12:36:15Z
[ "python" ]
I have many different small classes which have a few fields each, e.g. this: ``` class Article: def __init__(self, name, available): self.name = name self.available = available ``` What's the easiest and/or most idiomatic way to make the `name` field read only, so that ``` a = Article("Pineapple"...
As pointed out in other answers, using a property is the way to go for read-only attributes. The solution in [Chris' answer](http://stackoverflow.com/a/9920797/279627) is the cleanest one: It uses the `property()` built-in in a straight-forward, simple way. Everyone familiar with Python will recognize this pattern, and...
Python list reversion: [::-1]?
9,920,728
4
2012-03-29T07:17:23Z
9,920,771
8
2012-03-29T07:20:13Z
[ "python", "list", "data-structures" ]
I can't find any information on `[::-1]`. In the [wikibooks python tutorial](https://en.wikibooks.org/wiki/Python_Programming/Lists), there is a section about non-continous lists, but there's no information on parameters < 0. Effects are clear, but how do you explain it? Example Usage: ``` >>> foo = [1, 2, 3] >>> foo...
The syntax is as follows: ``` foo[start:end:step] # begin with 'start' and proceed by step until you reach 'end'. ``` So `foo[::-1]` means `entire list with step=-1`, so actually reversing the list. See [this answer](http://stackoverflow.com/a/509295/342473) for detailed explanation.
python list iteration
9,921,976
3
2012-03-29T08:48:08Z
9,922,014
10
2012-03-29T08:50:42Z
[ "python", "list", "iteration" ]
I have a list iteration in python defined like this: ``` for i in range(5): for j in range(5): if i != j: print i , j ``` So for each element in my defined range [0..5] I want to get each element i, but also all other elements which are not i. This code does exactly as I expect, but is there ...
Use [`itertools.permutations`](http://docs.python.org/library/itertools.html#itertools.permutations): ``` import itertools as it for i, j in it.permutations(range(5), 2): print i, j ```
python numpy split array into unequal subarrays
9,922,395
4
2012-03-29T09:14:56Z
13,287,237
12
2012-11-08T10:32:23Z
[ "python", "list", "numpy", "split" ]
I am trying to split an array into n parts. Sometimes these parts are of the same size, sometimes they are of a different size. I am trying to use: ``` split = np.split(list, size) ``` This works fine when size divides equally into the list, but fails otherwise. Is there a way to do this which will 'pad' the final a...
Are you looking for np.array\_split? Here is the docstring: ``` Split an array into multiple sub-arrays. Please refer to the ``split`` documentation. The only difference between these functions is that ``array_split`` allows `indices_or_sections` to be an integer that does *not* equally divide the axis. See Also -...
Remove widget in gtk.Table?
9,922,805
3
2012-03-29T09:41:15Z
9,929,392
7
2012-03-29T16:21:37Z
[ "python", "table", "pygtk", "removechild" ]
I'm using gtk.Table in my python application. How can I remove a widget such a gtk.VBox, gtk.HBox or a gtk.Button that i attached in the table. I want to remove the widget in exactly position. Is there anyway to unattach a child widget from table ? Such like: ``` table.attach(button,1,2,1,2) table.unattach(button,1,2,...
``` table.remove(button) ``` This works in general for GTK containers, such as hboxes and vboxes, not just tables.
Build in function for computing covariance
9,923,267
10
2012-03-29T10:09:54Z
9,923,340
21
2012-03-29T10:14:30Z
[ "python", "numpy", "scipy", "covariance" ]
Is there a way in python to obtain the covariance matrix given the mean and sample data points Example: ``` mean = [3 3.6] data = [[1 2] [2 3] [3 3] [4 5] [5 5]] ``` I know how to calculate the same by substituting these values in the formula. But is there a build in function in pyth...
[`numpy.cov()`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.cov.html) can be used to compute the covariance matrix: ``` In [1]: import numpy as np In [2]: data = np.array([[1,2], [2,3], [3,3], [4,5], [5,5]]) In [3]: np.cov(data.T) Out[3]: array([[ 2.5, 2. ], [ 2. , 1.8]]) ``` By default, `np...
How to create SaaS application with Python and Django
9,924,169
12
2012-03-29T11:09:47Z
16,049,292
19
2013-04-17T00:07:19Z
[ "python", "django", "saas" ]
Can you advice me with some articles/applications that allows you create SaaS(Software as a Service) application with Python and Django. For the moment the general topics I do not understand are: 1. Do you have one working application for all clients or one app per client 2. How do you manage database access, permiss...
1. one project, this will make maintenance easier. I handle host resolution with middleware in django-ikari. 2. you don't. see #1 3. I use the following : * [django-ikari](https://github.com/airtonix/django-ikari) : anchored (sub)domains * [django-guardian](https://github.com/lukaszb/django-guardian) : per objec...
Handling rss redirects with Python/urllib2
9,926,023
13
2012-03-29T13:09:29Z
9,927,476
23
2012-03-29T14:31:21Z
[ "python", "redirect", "urllib2" ]
Calling `urrlib2.urlopen` on a link to an article fetched from an RSS feed leads to the following error: > urllib2.HTTPError: HTTP Error 301: The HTTP server returned a redirect > error tha t would lead to an infinite loop. The last 30x error message > was: Moved Permanently According to the documentation, urllib2 su...
Turns out you need to enable Cookies. The page redirects to itself after setting a cookie first. Because urllib2 does not handle cookies by default you have to do it yourself. ``` import urllib2 import urllib from cookielib import CookieJar cj = CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj...
How to check whether a str(variable) is empty or not?
9,926,446
11
2012-03-29T13:34:22Z
9,926,661
24
2012-03-29T13:46:16Z
[ "python", "string", "condition" ]
How do I make a: ``` if str(variable) == [contains text]: ``` condition? (or something, because I am pretty sure that what I just wrote is completely wrong) I am sort of trying to check if a `random.choice` from my list is `["",]` (blank) or contains `["text",]`.
You could just compare your string to the empty string: ``` if variable == "": etc. ``` But you can abbreviate that as follows: ``` if variable: etc. ``` Explanation: An `if` actually works by computing a value for the logical expression you give it: `True` or `False`. If you simply use a variable name (or ...
How can I protect my AWS access id and secret key in my python application
9,926,825
10
2012-03-29T13:54:39Z
9,928,535
9
2012-03-29T15:27:00Z
[ "python", "amazon-web-services" ]
I'm making an application in Python and using Amazon Web Services in some modules. I'm now hard coding my AWS access id and secret key in \*.py file. Or might move them out to an configuration file in future. But there's a problem, how can I protect AWS information form other people? As I know python is a language th...
There's no way to protect your keys if you're going to distribute your code. They're going to be accessible to anyone who has access to your server or source code. There are two things you can do to protect yourself against malicious use of your keys. 1. Use the amazon IAM service to create a set of keys that only ha...
min, max and mean over large NumPy arrays in Python
9,929,372
2
2012-03-29T16:20:06Z
9,929,472
7
2012-03-29T16:26:29Z
[ "python", "numpy", "max", "average", "min" ]
I have a very large NumPy array: `a = np.array`. From this array I want to get the min, max and average which can be easily done with `np.min(a)`, `np.max(a)` and `np.mean(a)`. However, I want also to have the min, max and average of a portion (begin part or end part) of this array. Are there some functions for this w...
> All arrays generated by basic slicing are always views of the original array. <http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html> So, yes, just use slices.
Seeking clarification on apparent contradictions regarding weakly typed languages
9,929,585
164
2012-03-29T16:34:24Z
9,929,697
195
2012-03-29T16:42:12Z
[ "c#", "java", "python", "perl", "weakly-typed" ]
I think I understand [strong typing](http://lucacardelli.name/Papers/OnUnderstanding.A4.pdf), but every time I look for examples for what is weak typing I end up finding examples of programming languages that simply coerce/convert types automatically. For instance, in this article named [Typing: Strong vs. Weak, Stati...
UPDATE: [This question was the subject of my blog on the 15th of October, 2012.](http://ericlippert.com/2012/10/15/is-c-a-strongly-typed-or-a-weakly-typed-language/) Thanks for the great question! --- > What does it really mean for a language to be "weakly typed"? It means "this language uses a type system that I fi...
Seeking clarification on apparent contradictions regarding weakly typed languages
9,929,585
164
2012-03-29T16:34:24Z
9,932,084
13
2012-03-29T19:25:25Z
[ "c#", "java", "python", "perl", "weakly-typed" ]
I think I understand [strong typing](http://lucacardelli.name/Papers/OnUnderstanding.A4.pdf), but every time I look for examples for what is weak typing I end up finding examples of programming languages that simply coerce/convert types automatically. For instance, in this article named [Typing: Strong vs. Weak, Stati...
A perfect example comes from [the wikipedia article of Strong Typing](http://en.wikipedia.org/wiki/Strong_typing): Generally strong typing implies that the programming language places severe restrictions on the intermixing that is permitted to occur. **Weak Typing** ``` a = 2 b = "2" concatenate(a, b) # returns "22...
Seeking clarification on apparent contradictions regarding weakly typed languages
9,929,585
164
2012-03-29T16:34:24Z
9,934,914
18
2012-03-29T23:12:38Z
[ "c#", "java", "python", "perl", "weakly-typed" ]
I think I understand [strong typing](http://lucacardelli.name/Papers/OnUnderstanding.A4.pdf), but every time I look for examples for what is weak typing I end up finding examples of programming languages that simply coerce/convert types automatically. For instance, in this article named [Typing: Strong vs. Weak, Stati...
In addition to what Eric has said, consider the following C code: ``` void f(void* x); f(42); f("hello"); ``` In contrast to languages such as Python, C#, Java or whatnot, the above is weakly typed because we *lose* type information. Eric correctly pointed out that in C# we can circumvent the compiler by casting, ef...
Seeking clarification on apparent contradictions regarding weakly typed languages
9,929,585
164
2012-03-29T16:34:24Z
9,939,476
59
2012-03-30T08:31:08Z
[ "c#", "java", "python", "perl", "weakly-typed" ]
I think I understand [strong typing](http://lucacardelli.name/Papers/OnUnderstanding.A4.pdf), but every time I look for examples for what is weak typing I end up finding examples of programming languages that simply coerce/convert types automatically. For instance, in this article named [Typing: Strong vs. Weak, Stati...
As others have noted, the terms "strongly typed" and "weakly typed" have so many different meanings that there's no single answer to your question. However, since you specifically mentioned Perl in your question, let me try to explain in what sense Perl is weakly typed. The point is that, in Perl, there is no such thi...
Python: What is the default handling of SIGTERM?
9,930,576
9
2012-03-29T17:42:40Z
9,930,829
11
2012-03-29T18:00:19Z
[ "python", "signals", "sigterm" ]
What does Python do under the covers by default if it receives a SIGTERM but there is no signal handler registered for it?
Nothing. Python itself does not register a signal handler for it. You can check this in the interactive interpreter: ``` >>> import signal >>> signal.signal(signal.SIGTERM, signal.SIG_DFL) 0 >>> signal.SIG_DFL 0 ``` That shows `signal.signal()` returning signal.SIG\_DFL for `signal.SIGTERM`. Contrast it with `signal....
Flask throwing 'working outside of request context' when starting sub thread
9,931,738
25
2012-03-29T19:02:21Z
9,932,189
34
2012-03-29T19:32:24Z
[ "python", "flask", "mongoengine" ]
I am trying to start a new thread in Python inside of a Flask application. I am doing background work that gets triggered by the request, but I don't need to wait for the work to be done to respond to the request. Is it possible to set the flask request in this sub-threat to the request that came in? Reason being, our...
Wrap your thread code in a `test_request_context` so you have access to [context locals](http://flask.pocoo.org/docs/quickstart/#context-locals): ``` @app.route('/my_endpoint', methods=['POST']) def my_endpoint_handler(): #do tracking in sub-thread so we don't hold up the page def handle_sub_view(req): ...
Flask throwing 'working outside of request context' when starting sub thread
9,931,738
25
2012-03-29T19:02:21Z
17,594,630
20
2013-07-11T13:25:48Z
[ "python", "flask", "mongoengine" ]
I am trying to start a new thread in Python inside of a Flask application. I am doing background work that gets triggered by the request, but I don't need to wait for the work to be done to respond to the request. Is it possible to set the flask request in this sub-threat to the request that came in? Reason being, our...
Since version 0.10 there is a supported way of doing this: <http://flask.pocoo.org/docs/api/#flask.copy_current_request_context> If you want the `before_request` hooks to run you must call `current_app.preprocess_request()` inside of the decorated function.
Matplotlib table formatting
9,932,072
19
2012-03-29T19:24:26Z
9,947,184
27
2012-03-30T16:46:59Z
[ "python", "table", "matplotlib" ]
![enter image description here](http://i.stack.imgur.com/XtUKQ.png) Can't seem to locate in the documentation how to **increase the line-height** of the cells, as the text itself is very cramped. Any help with code is appreciated! Table formatting doesn't seem to be well documented... ``` # Plot line width ma...
The matplotlib documentation says > Add a table to the current axes. Returns a matplotlib.table.Table instance. For finer grained control over tables, use the Table class and add it to the axes with add\_table(). You could do is the following, look at the properties of your table (it's and object belonging to that cl...
Is it possible to take an ordered "slice" of a dictionary in Python based on a list of keys?
9,932,549
5
2012-03-29T19:57:22Z
9,932,673
7
2012-03-29T20:05:32Z
[ "python" ]
Suppose I have the following dictionary and list: ``` my_dictionary = {1:"hello", 2:"goodbye", 3:"World", "sand":"box"} my_list = [1,2,3] ``` Is there a direct (Pythonic) way to get the key-value pairs out of the dictionary for which the keys are elements in the list, in an order defined by the list order? The naive...
Don't know if pythonic enough but this is working: ``` res = [(x, my_dictionary[x]) for x in my_list] ``` This is a [list comprehension](http://docs.python.org/tutorial/datastructures.html#list-comprehensions), but, if you need to iterate that list only once, you can also turn it into a generator expression, e.g. : ...
In Python, how do I efficiently return a boolean value without incurring copy costs?
9,933,975
2
2012-03-29T21:41:25Z
9,933,997
12
2012-03-29T21:43:15Z
[ "python" ]
Say I have a class that contains a few string variables and I want to declare an `is_valid` method that checks that all the string variables are not `None`/empty It could look like this: ``` class MyClass(object): var1 = None var2 = None var3 = None @property def is_valid(self): return se...
> ... a copy the string would be returned ... Incorrect. A reference to the string object would be returned. But you can call `bool()` to convert it to a "better" value. ``` return bool(var1 and var2 and var3) ```
In Python how do I use a class method without passing an instance to it?
9,934,134
3
2012-03-29T21:54:25Z
9,934,178
20
2012-03-29T21:58:21Z
[ "python", "methods", "module" ]
So I have a common module which contains processing functions for numbers and types of data I am using. I want to be able to include it like `from common import common` (or better yet just `import common`) and use functions like `common.howLongAgo(unixTimeStamp)` What is required to do this in my common module?. Commo...
Ways of exposing methods in a python module: module `foo.py`: ``` def module_method(): return "I am a module method" class ModClass: @staticmethod def static_method(): # the static method gets passed nothing return "I am a static method" @classmethod def class_method(cls): ...
remove element in list in a dictionary
9,934,479
3
2012-03-29T22:28:36Z
9,934,518
7
2012-03-29T22:31:08Z
[ "python", "list", "dictionary" ]
In a big dictionary, similar to ``` d = {} d['a']=[1,2,3,4] d['b']=[1,2,3,4,5,6] d['c']=[1,2] ...
Iterate over the values of the dictionary and remove the 4 from every list: ``` for a in d.itervalues(): try: a.remove(4) except ValueError: pass ``` This is not really efficient, since removing an element from a list is an O(n) operation. Use a different data type (e.g. a set) for better perf...
Popen error: [Errno 2] No such file or directory
9,935,151
15
2012-03-29T23:38:32Z
9,935,511
57
2012-03-30T00:29:05Z
[ "python", "subprocess", "popen" ]
I have some custom commands. ``` # works subprocess.Popen(['python'], stdout=subprocess.PIPE) ``` But if I have my own system commands like `deactivate`, I get that error ``` Traceback (most recent call last): File "runner2.py", line 21, in <module> main() File "runner2.py", line 18, in main subprocess...
Try add an extra parameter 'shell=True' to the `Popen` call.
Copying list in python: deep vs shallow copy: gotcha for me in python?
9,935,372
6
2012-03-30T00:09:43Z
9,935,399
9
2012-03-30T00:14:18Z
[ "python" ]
So this is what I tried to do. ``` vectorized = [0] * length for i,key in enumerate(foo_dict.keys()): vector = vectorized vector[i] = 1 print vector vector = vectorized print vectorized ``` So what I was hoping was for example the length is 4. So i create a 4 dimension vector: ``` vectorized=[0,0,0...
This line (these lines, really): ``` vector = vectorized ``` copies the list reference. You need to do a shallow copy of the sequence contents. ``` vector = vectorized[:] ```
Python: retrieve dictionary keys in order as added?
9,936,374
3
2012-03-30T02:51:38Z
9,936,388
9
2012-03-30T02:53:01Z
[ "python", "sorting", "dictionary", "key" ]
In Python, is there a way to retrieve the list of keys in the order in that the items were added? ``` String.compareMethods = {'equals': String.equals, 'contains': String.contains, 'startswith': String.startswith, 'endswith': String.endswith} `...
Use a [`collections.OrderedDict`](http://docs.python.org/library/collections.html#collections.OrderedDict) on Python 2.7+, or [`OrderedDict` from PyPI](http://pypi.python.org/pypi/ordereddict) for older versions of Python. You should be able to install it for Python 2.4-2.6 with `pip install ordereddict` or `easy_insta...
Unique lists from a list
9,936,840
7
2012-03-30T04:00:59Z
9,936,867
9
2012-03-30T04:04:42Z
[ "python" ]
Given a list I need to return a list of lists of unique items. I'm looking to see if there is a more Pythonic way than what I came up with: ``` def unique_lists(l): m = {} for x in l: m[x] = (m[x] if m.get(x) != None else []) + [x] return [x for x in m.values()] print(unique_lists([1,2,2,3,4,5...
``` >>> L=[1,2,2,3,4,5,5,5,6,7,8,8,9] >>> from collections import Counter >>> [[k]*v for k,v in Counter(L).items()] [[1], [2, 2], [3], [4], [5, 5, 5], [6], [7], [8, 8], [9]] ```
Can modules have properties?
9,937,279
5
2012-03-30T05:06:31Z
9,937,761
11
2012-03-30T06:03:37Z
[ "python", "properties", "module" ]
Is it possible to add properties and special methods to modules? I want to define a module such that importing it acts like a class instance, and the body acts as a class definition. Essentially, it's to avoid ugly syntax like this: ``` import game if game.Game().paused: print("The game is paused") ``` E.g. the g...
Python doesn't care that what's in `sys.modules` is actually a module. So you can just: ``` # game.py class Game(object): pass import sys sys.modules["game"] = Game() ``` Now other modules that `import game` will get the `Game` instance, not the original module. I'm not sure I recommend it, but it'll do what yo...
plotting stacked barplots on a panda data frame
9,938,130
5
2012-03-30T06:41:28Z
10,064,444
13
2012-04-08T16:37:48Z
[ "python", "pandas" ]
This is my first attempt at playing with Pandas library after attending Wesley's tutorial at pycon. After poking around a bit with the dataframe I am glad I was able to massage the data in the way I wanted but having trouble in plotting it. I guess it also points to my naiveness with the matplotlib library. What I ha...
I've just implemented a stacked bar plot function in the git repository for pandas, will be part of the upcoming 0.7.3 release: ``` In [7]: df Out[7]: a b c 0 0.425199 0.564161 0.727342 1 0.174849 0.071170 0.679178 2 0.224619 0.331846 0.468959 3 0.654766 0.189413 0.868011 4 0.61...
Python multiple inheritance function overriding and ListView in django
9,939,256
14
2012-03-30T08:14:26Z
9,939,867
10
2012-03-30T08:57:25Z
[ "python", "django", "listview", "multiple-inheritance", "django-generic-views" ]
I created a class that subclasses `ListView` and two custom mixins which have implemented a `get_context_data` function. I wanted to override this function on the child class: ``` from django.views.generic import ListView class ListSortedMixin(object): def get_context_data(self, **kwargs): print 'ListSort...
If what you're trying to do is to call overwritten methods in fixed order. Use this syntax: ``` class MyListView(ListSortedMixin, ListPaginatedMixin, ListView): def get_context_data(self, **context): ListSortedMixin.get_context_data(self, **context) ListPaginatedMixin.get_context_data(self, **context) re...
Python multiple inheritance function overriding and ListView in django
9,939,256
14
2012-03-30T08:14:26Z
17,773,221
14
2013-07-21T14:11:08Z
[ "python", "django", "listview", "multiple-inheritance", "django-generic-views" ]
I created a class that subclasses `ListView` and two custom mixins which have implemented a `get_context_data` function. I wanted to override this function on the child class: ``` from django.views.generic import ListView class ListSortedMixin(object): def get_context_data(self, **kwargs): print 'ListSort...
This is an old question, but I believe the answer is incorrect. There is a mistake in your code. It should read: ``` class MyListView(ListSortedMixin, ListPaginatedMixin, ListView): def get_context_data(self, **context): super(MyListView,self).get_context_data(**context) return context ``` The ord...
Counting comments per object in `models.py` with Django's comments framework
9,940,008
4
2012-03-30T09:06:59Z
9,940,184
7
2012-03-30T09:18:21Z
[ "python", "django", "django-models" ]
I know in templates you can easily count comments with [`get_comment_count`](https://docs.djangoproject.com/en/dev/ref/contrib/comments/#counting-comments), but how can you get the same count as a method inside a class in `models.py`? For example ``` class Blog( models.Model ) : def comment_count( self ) : ...
Comments are related to your Models via [generic relations](https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#generic-relations) so you can look up the comments for your object as you would any generic relation: ``` from django.conrtib.comments.models import Comment from django.contrib.contenttypes.model...
How uninstall pycharm and rubymine?
9,940,451
12
2012-03-30T09:36:53Z
9,940,553
12
2012-03-30T09:42:49Z
[ "python", "ruby", "ubuntu", "rubymine", "pycharm" ]
I installed pycharm and rubymine on linux mint, my trial has ended. how to remove them? can i just do ``` sudo apt-get remove --purge pycharm ``` or is there an `uninstall.sh` somewhere?
The standard tar.gz packages seem to be self contained directories with the application ala eclipse so to uninstall just delete the directories.
Django model manager objects.create where is the documentation?
9,940,674
72
2012-03-30T09:51:02Z
9,940,729
28
2012-03-30T09:55:04Z
[ "python", "django" ]
I always read that I should use ``` model = Model(a=5, b=6) model.save() ``` But I just saw there is a manager function create, because I saw an opensource django app using it. ``` model = Model.objects.create(a=5, b=6) print model.pk 1 ``` So is it suggested to use it? Or is it still preferred to use the .save met...
It's in the page ["QuerySet API reference"](https://docs.djangoproject.com/en/1.9/ref/models/querysets/#create), linked from the documentation index.
Django model manager objects.create where is the documentation?
9,940,674
72
2012-03-30T09:51:02Z
16,707,162
35
2013-05-23T06:38:50Z
[ "python", "django" ]
I always read that I should use ``` model = Model(a=5, b=6) model.save() ``` But I just saw there is a manager function create, because I saw an opensource django app using it. ``` model = Model.objects.create(a=5, b=6) print model.pk 1 ``` So is it suggested to use it? Or is it still preferred to use the .save met...
``` p = Person.objects.create(first_name="Bruce", last_name="Springsteen") ``` **equivalent to:** ``` p = Person(first_name="Bruce", last_name="Springsteen") p.save(force_insert=True) ``` > The force\_insert means that a new object will always be created. > Normally you won’t need to worry about this. However, ...
Fastest way to pack a list of floats into bytes in python
9,940,859
14
2012-03-30T10:03:52Z
9,941,024
33
2012-03-30T10:13:05Z
[ "python", "struct", "python-3.x" ]
I have a list of say 100k floats and I want to convert it into a bytes buffer. ``` buf = bytes() for val in floatList: buf += struct.pack('f', val) return buf ``` This is quite slow. How can I make it faster using only standard Python 3.x libraries.
Just tell `struct` how many `float`s you have. 100k floats takes about a 1/100th of a second on my slow laptop. ``` import random import struct floatlist = [random.random() for _ in range(10**5)] buf = struct.pack('%sf' % len(floatlist), *floatlist) ```
When storing phone numbers in Django, should I store them as an raw digits or use django.contrib.localflavor?
9,940,908
5
2012-03-30T10:06:24Z
9,941,334
9
2012-03-30T10:34:19Z
[ "python", "django", "django-models", "django-forms", "django-contrib" ]
The title may have been confusing, but please let me explain: Currently when I am storing phone number with raw digits like `5554441234`. Then in my template I was going to "format" the number into something like `555-444-1234`. I realized in Django's [`localflavor`](https://docs.djangoproject.com/en/1.4/ref/contrib/...
Store them as entered, only strip surrounding white space if necessary. The way a user formats its number stores semantic information that you do not want to lose by normalizing it. In the US the format `XXX-XXX-XXXX` is very common, but other locales use totally different formats. For example, where I live some common...
subprocess.Popen with a unicode path
9,941,064
4
2012-03-30T10:15:08Z
9,951,851
9
2012-03-31T00:14:00Z
[ "python", "unicode", "subprocess", "popen" ]
I have a unicode filename that I would like to open. The following code: ``` cmd = u'cmd /c "C:\\Pok\xe9mon.mp3"' cmd = cmd.encode('utf-8') subprocess.Popen(cmd) ``` returns ``` >>> 'C:\Pokיmon.mp3' is not recognized as an internal or external command, operable program or batch file. ``` even though the file do ex...
It looks like you're using Windows and Python 2.X. Use [os.startfile](http://docs.python.org/library/os.html#os.startfile): ``` >>> import os >>> os.startfile(u'Pokémon.mp3') ``` Non-intuitively, getting the command shell to do the same thing is: ``` >>> import subprocess >>> import locale >>> subprocess.Popen(u'Po...
How to fake/proxy a class in Python
9,942,536
17
2012-03-30T12:01:40Z
9,942,607
16
2012-03-30T12:07:26Z
[ "python" ]
I wrote some wrapper which has another object as an attribute. This wrapper proxies (forwards) all attribute requests with `__getattr__` and `__setattr__` to the object stored as the attribute. What else do I need to provide for my proxy so that the wrapper looks like the wrapped class under usual circumstances? I sup...
This problem is reasonably well addressed by this recipe: > [Object Proxying (Python recipe)](http://code.activestate.com/recipes/496741-object-proxying/) The general idea you have to follow is that most methods on classes are accessed through some combination of `__getattr__` and `__getattribute__` either on the cla...
UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 20: ordinal not in range(128)
9,942,594
479
2012-03-30T12:06:41Z
9,942,822
547
2012-03-30T12:21:31Z
[ "python", "unicode", "beautifulsoup", "python-2.x", "python-unicode" ]
I'm having problems dealing with unicode characters from text fetched from different web pages (on different sites). I am using BeautifulSoup. The problem is that the error is not always reproducible; it sometimes works with some pages, and sometimes, it barfs by throwing a `UnicodeEncodeError`. I have tried just abou...
You need to read the Python [Unicode HOWTO](http://docs.python.org/howto/unicode.html). This error is the [very first example](http://docs.python.org/howto/unicode.html#the-unicode-type). Basically, stop using `str` to convert from unicode to encoded text / bytes. Instead, properly use [`.encode()`](http://docs.pytho...
UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 20: ordinal not in range(128)
9,942,594
479
2012-03-30T12:06:41Z
9,942,885
221
2012-03-30T12:25:08Z
[ "python", "unicode", "beautifulsoup", "python-2.x", "python-unicode" ]
I'm having problems dealing with unicode characters from text fetched from different web pages (on different sites). I am using BeautifulSoup. The problem is that the error is not always reproducible; it sometimes works with some pages, and sometimes, it barfs by throwing a `UnicodeEncodeError`. I have tried just abou...
This is a classic python unicode pain point! Consider the following: ``` a = u'bats\u00E0' print a => batsà ``` All good so far, but if we call str(a), let's see what happens: ``` str(a) Traceback (most recent call last): File "<stdin>", line 1, in <module> UnicodeEncodeError: 'ascii' codec can't encode characte...
UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 20: ordinal not in range(128)
9,942,594
479
2012-03-30T12:06:41Z
19,727,991
16
2013-11-01T13:44:36Z
[ "python", "unicode", "beautifulsoup", "python-2.x", "python-unicode" ]
I'm having problems dealing with unicode characters from text fetched from different web pages (on different sites). I am using BeautifulSoup. The problem is that the error is not always reproducible; it sometimes works with some pages, and sometimes, it barfs by throwing a `UnicodeEncodeError`. I have tried just abou...
I've actually found that in most of my cases, just stripping out those characters is much simpler: ``` s = mystring.decode('ascii', 'ignore') ```
UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 20: ordinal not in range(128)
9,942,594
479
2012-03-30T12:06:41Z
20,334,767
27
2013-12-02T17:58:15Z
[ "python", "unicode", "beautifulsoup", "python-2.x", "python-unicode" ]
I'm having problems dealing with unicode characters from text fetched from different web pages (on different sites). I am using BeautifulSoup. The problem is that the error is not always reproducible; it sometimes works with some pages, and sometimes, it barfs by throwing a `UnicodeEncodeError`. I have tried just abou...
A subtle problem causing even print to fail is having your environment variables set wrong, eg. here LC\_ALL set to "C". In Debian they discourage setting it: [Debian wiki on Locale](https://wiki.debian.org/Locale) ``` $ echo $LANG en_US.utf8 $ echo $LC_ALL C $ python -c "print (u'voil\u00e0')" Traceback (most recent...
UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 20: ordinal not in range(128)
9,942,594
479
2012-03-30T12:06:41Z
25,402,141
66
2014-08-20T10:13:15Z
[ "python", "unicode", "beautifulsoup", "python-2.x", "python-unicode" ]
I'm having problems dealing with unicode characters from text fetched from different web pages (on different sites). I am using BeautifulSoup. The problem is that the error is not always reproducible; it sometimes works with some pages, and sometimes, it barfs by throwing a `UnicodeEncodeError`. I have tried just abou...
I found elegant work around for me to remove symbols and continue to keep string as string in follows: ``` yourstring = yourstring.encode('ascii', 'ignore').decode('ascii') ``` It's important to notice that using the ignore option is **dangerous** because it silently drops any unicode(and internationalization) suppor...
UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 20: ordinal not in range(128)
9,942,594
479
2012-03-30T12:06:41Z
28,152,554
15
2015-01-26T14:53:34Z
[ "python", "unicode", "beautifulsoup", "python-2.x", "python-unicode" ]
I'm having problems dealing with unicode characters from text fetched from different web pages (on different sites). I am using BeautifulSoup. The problem is that the error is not always reproducible; it sometimes works with some pages, and sometimes, it barfs by throwing a `UnicodeEncodeError`. I have tried just abou...
For me, what worked was: ``` BeautifulSoup(html_text,from_encoding="utf-8") ``` Hope this helps someone.
python 2.7 lowercase
9,943,169
15
2012-03-30T12:41:56Z
9,943,237
20
2012-03-30T12:45:36Z
[ "python", "python-2.7", "unicode", "lowercase", "python-unicode" ]
When I use `.lower()` in Python 2.7, string is not converted to lowercase for letters `ŠČŽ`. I read data from dictionary. I tried using `str(tt["code"]).lower()`, `tt["code"].lower()`. Any suggestions ?
Use unicode strings: ``` drostie@signy:~$ python Python 2.7.2+ (default, Oct 4 2011, 20:06:09) [GCC 4.6.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> print "ŠČŽ" ŠČŽ >>> print "ŠČŽ".lower() ŠČŽ >>> print u"ŠČŽ".lower() ščž ``` See that little `u`? That mea...
Right-to-left string replace in Python?
9,943,504
22
2012-03-30T13:00:38Z
9,943,534
22
2012-03-30T13:02:42Z
[ "python" ]
I want to do a string replace in Python, but only do the first instance going from right to left. In an ideal world I'd have: ``` myStr = "mississippi" print myStr.rreplace("iss","XXX",1) > missXXXippi ``` What's the best way of doing this, given that `rreplace` doesn't exist?
``` >>> myStr[::-1].replace("iss"[::-1], "XXX"[::-1], 1)[::-1] 'missXXXippi' ```
Right-to-left string replace in Python?
9,943,504
22
2012-03-30T13:00:38Z
9,943,613
11
2012-03-30T13:07:45Z
[ "python" ]
I want to do a string replace in Python, but only do the first instance going from right to left. In an ideal world I'd have: ``` myStr = "mississippi" print myStr.rreplace("iss","XXX",1) > missXXXippi ``` What's the best way of doing this, given that `rreplace` doesn't exist?
``` >>> re.sub(r'(.*)iss',r'\1XXX',myStr) 'missXXXippi' ``` The regex engine cosumes all the string and then starts backtracking untill `iss` is found. Then it replaces the found string with the needed pattern. --- **Some speed [tests](http://ideone.com/xdQKh)** The solution with `[::-1]` turns out to be faster. T...
Right-to-left string replace in Python?
9,943,504
22
2012-03-30T13:00:38Z
9,943,875
35
2012-03-30T13:24:08Z
[ "python" ]
I want to do a string replace in Python, but only do the first instance going from right to left. In an ideal world I'd have: ``` myStr = "mississippi" print myStr.rreplace("iss","XXX",1) > missXXXippi ``` What's the best way of doing this, given that `rreplace` doesn't exist?
`rsplit` and `join` could be used to simulate the effects of an `rreplace` ``` >>> 'XXX'.join('mississippi'.rsplit('iss', 1)) 'missXXXippi' ```
How do I close the files from tempfile.mkstemp?
9,944,135
14
2012-03-30T13:40:47Z
9,944,239
11
2012-03-30T13:47:02Z
[ "python", "ulimit" ]
On my machine Linux machine `ulimit -n` gives `1024`. This code: ``` from tempfile import mkstemp for n in xrange(1024 + 1): f, path = mkstemp() ``` fails at the last line loop with: ``` Traceback (most recent call last): File "utest.py", line 4, in <module> File "/usr/lib/python2.7/tempfile.py", line 300, ...
``` import tempfile import os for idx in xrange(1024 + 1): outfd, outsock_path = tempfile.mkstemp() outsock = os.fdopen(outfd,'w') outsock.close() ```
How do I close the files from tempfile.mkstemp?
9,944,135
14
2012-03-30T13:40:47Z
9,944,253
19
2012-03-30T13:47:59Z
[ "python", "ulimit" ]
On my machine Linux machine `ulimit -n` gives `1024`. This code: ``` from tempfile import mkstemp for n in xrange(1024 + 1): f, path = mkstemp() ``` fails at the last line loop with: ``` Traceback (most recent call last): File "utest.py", line 4, in <module> File "/usr/lib/python2.7/tempfile.py", line 300, ...
Since `mkstemp()` returns a raw file descriptor, you can use [os.close()](http://docs.python.org/library/os.html#os.close): ``` import os from tempfile import mkstemp for n in xrange(1024 + 1): f, path = mkstemp() # Do something with 'f'... os.close(f) ```
Python: get key with the least value from a dictionary BUT multiple minimum values
9,944,963
9
2012-03-30T14:30:27Z
9,945,031
10
2012-03-30T14:33:50Z
[ "python", "dictionary", "multiple-instances", "minimum" ]
I'm trying to do the same as [Python: get key with the least value from a dictionary](http://stackoverflow.com/questions/3282823/python-get-key-with-the-least-value-from-a-dictionary), where we want to get the key corresponding to the minimum value in a dictionary. The best way appears to be: ``` min(d, key=d.get) ``...
One simple option is to first determine the minimum value, and then select all keys mapping to that minimum: ``` min_value = min(d.itervalues()) min_keys = [k for k in d if d[k] == min_value] ``` For Python 3 use `d.values()` instead of `d.itervalues()`. This needs two passes through the dictionary, but should be on...
Flask, blue_print, current_app
9,946,136
7
2012-03-30T15:37:10Z
9,975,320
7
2012-04-02T11:10:39Z
[ "python", "flask", "jinja2" ]
I am trying to add a function in the jinja environment from a blue print ( a function that I will use into a template). **Main.py** ``` app = Flask(__name__) app.register_blueprint(heysyni) ``` **MyBluePrint.py** ``` heysyni = Blueprint('heysyni', __name__) @heysyni.route('/heysyni'): return render_template('he...
The message error was actually pretty clear : > *working outside of request context* In my blueprint, I was trying to get my application outside the 'request' function : ``` heysyni = Blueprint('heysyni', __name__) app = current_app._get_current_object() print app @heysyni.route('/heysyni/') def aheysyni(): re...
How can I match the start and end in Python's regex?
9,947,038
7
2012-03-30T16:37:27Z
9,947,065
12
2012-03-30T16:39:30Z
[ "python", "regex" ]
I have a string and I want to match something at the start *and* end with a single search pattern. How can this be done? Let's say we have a string like: ``` string = "ftp://www.somewhere.com/over/the/rainbow/image.jpg" ``` I want to do something like this: ``` re.search("^ftp:// & .jpg$" ,string) ``` Obviously,...
How about not using a regular expression at all? ``` if string.startswith("ftp://") and string.endswith(".jpg"): ``` Don't you think this reads nicer? You can also support multiple options for start and end: ``` if (string.startswith(("ftp://", "http://")) and string.endswith((".jpg", ".png"))): ```
How can I match the start and end in Python's regex?
9,947,038
7
2012-03-30T16:37:27Z
9,947,093
7
2012-03-30T16:41:22Z
[ "python", "regex" ]
I have a string and I want to match something at the start *and* end with a single search pattern. How can this be done? Let's say we have a string like: ``` string = "ftp://www.somewhere.com/over/the/rainbow/image.jpg" ``` I want to do something like this: ``` re.search("^ftp:// & .jpg$" ,string) ``` Obviously,...
[`re.match`](http://docs.python.org/library/re.html#re.match) will [match the string at the beginning](http://docs.python.org/library/re.html#matching-vs-searching), in contrast to `re.search`: ``` re.match(r'(ftp|http)://.*\.(jpg|png)$', s) ``` Two things to note here: * `r''` is used for the string literal to make...
Convert Python None to JavaScript null
9,947,262
5
2012-03-30T16:53:53Z
9,947,311
12
2012-03-30T16:59:08Z
[ "javascript", "python", "django" ]
In a Django view I am generating a data set something like this: ``` data = [22, 23, 18, 19, 21, None, 22, 20] ``` I am passing this data to a JavaScript variable using: ``` data_json = simplejson.dumps(data) ``` For use in a High Charts script. Unfortunately JavaScript is stumbling when it encounters the `None` v...
If you're using Python 2.6 or later, you can use the built-in json module: ``` >>> import json >>> json.dumps([1, 2, 3, None, 4]) '[1, 2, 3, null, 4]' ``` See <http://docs.python.org/library/json.html>
Numpy: How to elementwise-multiply two vectors, shape (n,1) and (n,)?
9,948,042
6
2012-03-30T17:53:01Z
9,948,100
13
2012-03-30T17:57:29Z
[ "python", "arrays", "numpy" ]
Elementwise multiplication of two vectors is no problem if they both have the same shape, say both (n,1) or both (n,). If one vector has shape (n,1) and the other (n,), though, the `*`-operator returns something funny. ``` a = np.ones((3,1)) b = np.ones((3,)) print a * b ``` The resulting nxn-matrix contains A\_{i,j}...
Slice the vectors in a way that makes their shape match: ``` a[:, 0] * b ``` or ``` a * b[:, None] ```
How to configure setup.py to have pip install from GitHub master?
9,949,420
8
2012-03-30T19:37:55Z
10,051,109
9
2012-04-07T01:56:53Z
[ "python", "github", "pip", "setuptools", "distutils" ]
Rather than pushing a release to PyPi and GitHub, it would be easier to have PyPi use the latest GitHub master. Is there are proper way to do this? I know you can list dependencies as GitHub repos in install\_requires, but is there a way to do this for the primary package? For example, when you use easy\_install to i...
If I recall correctly you can use `download_url` to point to the lastest tarball at GitHub. **Do not send any sdist/bdist to PyPI, only register the package** and change `setup.py` to something like: ``` setup(..., download_url='https://github.com/USER/PROJECT/tarball/master') ``` The reason those pages are re...
How to change the dtype of a numpy recarray?
9,949,427
8
2012-03-30T19:38:23Z
9,949,519
11
2012-03-30T19:45:26Z
[ "python", "numpy" ]
There a number of posts that nearly answer this but either I don't understand them or they don't answer the question: I have a recarray made using numpy.rec.fromrecords. Say I want to convert certain columns to floats. How do I do this? Should I change to an ndarray and them back to a recarray?
Here is an example using `astype` to perform the conversion: ``` import numpy as np recs = [('Bill', '31', 260.0), ('Fred', 15, '145.0')] r = np.rec.fromrecords(recs, formats = 'S30,i2,f4', names = 'name, age, weight') print(r) # [('Bill', 31, 260.0) ('Fred', 15, 145.0)] ``` The `age` is of dtype `<i2`: ``` print(r....
How to change the dtype of a numpy recarray?
9,949,427
8
2012-03-30T19:38:23Z
10,030,747
9
2012-04-05T14:42:05Z
[ "python", "numpy" ]
There a number of posts that nearly answer this but either I don't understand them or they don't answer the question: I have a recarray made using numpy.rec.fromrecords. Say I want to convert certain columns to floats. How do I do this? Should I change to an ndarray and them back to a recarray?
There are basically two steps. My stumbling block was in finding how to modify an existing dtype. This is how I did it: ``` # change dtype by making a whole new array dt = data.dtype dt = dt.descr # this is now a modifiable list, can't modify numpy.dtype # change the type of the first col: dt[0] = (dt[0][0], 'float64'...
python eval vs ast.literal_eval vs JSON decode
9,949,533
8
2012-03-30T19:47:03Z
9,949,553
14
2012-03-30T19:49:17Z
[ "python" ]
I am converting 2 MB of data as a string into a dict. The input is serialized in JSON. Anyways I am currently using ast.literal\_eval and I get the dictionary I want, but then when I tried just running eval it seems to run faster, and also returns the same result. Is there any reason to use the ast module or the json...
Yes, there's definitely a reason: `eval()` is evil. Your code might read untrusted data one day, an this would allow an attacker to run arbitrary code on your machine. You shouldn't use `ast.literal_eval()` to decode JSON either. It cannot decode every valid JSON string and is not meant to be used for this purpose. Si...
python eval vs ast.literal_eval vs JSON decode
9,949,533
8
2012-03-30T19:47:03Z
9,949,575
13
2012-03-30T19:50:36Z
[ "python" ]
I am converting 2 MB of data as a string into a dict. The input is serialized in JSON. Anyways I am currently using ast.literal\_eval and I get the dictionary I want, but then when I tried just running eval it seems to run faster, and also returns the same result. Is there any reason to use the ast module or the json...
No. Unless you hit one of two scenarios: 1. That's not JSON! Someone puts `__import__('os').system('rm -rf /')` in the file instead. You are boned. 2. It's JSON, but not the Python-like part! Someone puts `true`, `false`, `null`, or a Unicode escape somewhere in it. Happy birthday.
python eval vs ast.literal_eval vs JSON decode
9,949,533
8
2012-03-30T19:47:03Z
20,276,991
10
2013-11-29T01:17:05Z
[ "python" ]
I am converting 2 MB of data as a string into a dict. The input is serialized in JSON. Anyways I am currently using ast.literal\_eval and I get the dictionary I want, but then when I tried just running eval it seems to run faster, and also returns the same result. Is there any reason to use the ast module or the json...
I don't really like this attitude on stackoverflow (and elsewhere) telling people without any context that what they are doing is insecure and they shouldn't do it. Maybe it's just a throwaway script to import some data, in that case why not choose the fastest or most convenient way? In this case, however, `json.loads...
suppressing print as stdout python
9,949,633
7
2012-03-30T19:57:02Z
9,949,683
14
2012-03-30T20:01:14Z
[ "python" ]
Ok.. So probably an example is a good way to explain this problem So I have something like this: ``` if __name__=="__main__" result = foobar() sys.stdout.write(str(result)) sys.stdout.flush() sys.exit(0) ``` Now this script is being called from a ruby script.. and basically it parses the result there...
You want to shadow (or otherwise hide) the stdout temporarily. Something like this: ``` actualstdout = sys.stdout sys.stdout = StringIO() result = foobar() sys.stdout = actualstdout sys.stdout.write(str(result)) sys.stdout.flush() sys.exit(0) ``` You need to assign something that is file-like to sys.stdout so that ot...
Delete Characters in Python Printed Line
9,949,887
3
2012-03-30T20:18:30Z
9,949,905
9
2012-03-30T20:19:43Z
[ "python" ]
I'm writing a program where I want the cursor to print letters on the same line, but then delete them as well, as if a person was typing, made a mistake, deleted back to the mistake, and kept typing from there. All I have so far is the ability to write them on the same line: ``` import sys, time write = sys.stdout.wr...
``` write('\b') # <-- backup 1-character ```
How do I create Python eggs from distutils source packages?
9,950,362
12
2012-03-30T21:01:42Z
9,950,477
9
2012-03-30T21:12:01Z
[ "python", "setuptools", "distutils" ]
I vaguely remember some sort of setuptools wrapper that would generate .egg files from distutils source. Can someone jog my memory?
Have you tried ``` python setup.py bdist_egg ``` Here I assume you are using setuptools instead of distutils i.e. in setup.py instead of ``` from distutils.core import setup ``` use ``` from setuptools import setup ```
How do I create Python eggs from distutils source packages?
9,950,362
12
2012-03-30T21:01:42Z
9,960,426
22
2012-03-31T22:56:12Z
[ "python", "setuptools", "distutils" ]
I vaguely remember some sort of setuptools wrapper that would generate .egg files from distutils source. Can someone jog my memory?
setuptools monkey-patches some parts of distutils when it is imported. When you use easy\_install to get a distutils-based project from PyPI, it will create an egg (pip may do that too). To do the same thing locally (i.e. in a directory that’s a code checkout or an unpacked tarball), use this trick: `python -c "impor...
Real Hierarchical Builds with SCons?
9,950,474
10
2012-03-30T21:11:45Z
9,955,722
8
2012-03-31T12:08:37Z
[ "python", "build", "scons", "build-script" ]
So I've read the questions on here about hierarchical builds like: [Creating a Hierarchical Build with SCons](http://stackoverflow.com/questions/3709321/creating-a-hierarchical-build-with-scons) I want to do real hierarchical construction of two standalone repos that both use scons that I set up as sub-repos using mer...
Im not sure why you would need to make a custom builder, if I understand you correctly, I think everything you need can be done with SCons and its builtin builders. To do what you explain, you would indeed need 3 Seperate SConsctruct files, to be able to do 3 seperate builds. I would also add 3 SConscript files and ma...
Merging background with transparent image in PIL
9,950,634
5
2012-03-30T21:26:59Z
9,958,440
10
2012-03-31T18:17:27Z
[ "python", "python-imaging-library" ]
I have a png image as background and I want to add a transparent mesh to this background but this doesn't work as expected. The background image is converted to transparent on places where I apply transparent mesh. I am doing: ``` from PIL import Image, ImageDraw map_background = Image.open(MAP_BACKGROUND_FILE).conv...
What you are trying to do is to composite the grid onto the background, and for that you need to use [`Image.blend`](http://www.pythonware.com/library/pil/handbook/image.htm#blend) or [`Image.composite`](http://www.pythonware.com/library/pil/handbook/image.htm#composite). Here's an example using the latter to composite...
Django PIL : IOError Cannot identify image file
9,950,745
7
2012-03-30T21:39:51Z
9,954,425
18
2012-03-31T08:47:46Z
[ "python", "django", "image", "python-imaging-library" ]
I'm learning Python and Django. An image is provided by the user using forms.ImageField(). Then I have to process it in order to create two different sized images. When I submit the form, Django returns the following error: ``` IOError at /add_event/ cannot identify image file ``` I call the resize function: ``` d...
As [ilvar asks](http://stackoverflow.com/questions/9950745/django-pil-ioerror-cannot-identify-image-file#comment12709667_9950745) in the comments, what kind of object is `image`? I'm going to assume for the purposes of this answer that it's the `file` property of a Django `ImageField` that comes from a file uploaded by...
Is it alright to call len() in a loop's conditional statement?
9,953,152
4
2012-03-31T05:01:15Z
9,953,232
8
2012-03-31T05:17:33Z
[ "python", "arrays", "list" ]
In C, it is considered bad practice to call strlen like this: ``` for ( i = 0; strlen ( str ) != foo; i++ ) { // stuff } ``` The reason, of course, is that it is inefficient since it "counts" the characters in a string multiple times. However, in Python, I see code like this quite often: ``` for i in range ( 0,...
In Python, a `for` loop iterates through a list-like object, it doesn't have a conditional statement that is checked each time. To illustrate, the following two loops are functionally equivalent; the `while` loop is a direct translation of `for (i=0; i< n; i++) { ... }`, while the `for` loop is the Pythonic way of doin...
Django Custom Save Model
9,953,427
5
2012-03-31T05:59:53Z
9,953,914
10
2012-03-31T07:21:30Z
[ "python", "django" ]
I'm trying to perform a basic date calculation in a save model in django, see below code: ``` class Purchase(models.Model): purchase_date = models.DateField() purchase_place = models.CharField(verbose_name='Place of Purchase', max_length=255) purchaseCategory = models.ForeignKey(PurchaseCategory, verbose...
timedelta doesnot accept years, so ``` from datetime import timedelta # custom save model def save(self, *args, **kwargs): # figure out warranty end date if self.warranty_period_type == 'm': self.warranty_end_date = self.purchase_date + timedelta(days=self.warranty_period_number*31) else: s...
Technique to remove common words(and their plural versions) from a string
9,953,619
9
2012-03-31T06:29:15Z
9,953,667
7
2012-03-31T06:38:06Z
[ "python", "parsing", "processing-efficiency" ]
I am attempting to find tags(keywords) for a recipe by parsing a long string of text. The text contains the recipe ingredients, directions and a short blurb. **What do you think would be the most efficient way to remove common words from the tag list?** *By common words, I mean words like: 'the', 'at', 'there', 'thei...
Your problem domain is "[Natural Language Processing](http://en.wikipedia.org/wiki/Natural_language_processing)". If you don't want to reinvent the wheel, use [NLTK](http://www.nltk.org/), search for [stemming](http://en.wikipedia.org/wiki/Stemming) in the docs. Given that [NLP](http://en.wikipedia.org/wiki/Natural_l...
Technique to remove common words(and their plural versions) from a string
9,953,619
9
2012-03-31T06:29:15Z
10,059,286
16
2012-04-07T23:45:04Z
[ "python", "parsing", "processing-efficiency" ]
I am attempting to find tags(keywords) for a recipe by parsing a long string of text. The text contains the recipe ingredients, directions and a short blurb. **What do you think would be the most efficient way to remove common words from the tag list?** *By common words, I mean words like: 'the', 'at', 'there', 'thei...
I'd just do something like this: ``` from nltk.corpus import stopwords s=set(stopwords.words('english')) txt="a long string of text about him and her" print filter(lambda w: not w in s,txt.split()) ``` which prints ``` ['long', 'string', 'text'] ``` and in terms of complexity should be O(n) in number of words in t...
Initializing 2D array in Python
9,954,183
4
2012-03-31T08:04:57Z
9,954,255
13
2012-03-31T08:16:28Z
[ "python", "list", "python-3.x" ]
I have a problem with initialzing a 2D array in python. I want a 6x6 array, I did ``` arr = [[None]*6]*6 ``` But when I do: ``` >>> arr[1][2]=10 >>> arr [[None, None, 10, None, None, None], [None, None, 10, None, None, None], [None, None, 10, None, None, None], [None, None, 10, None, None, None], [None, None, 10, No...
Using list comprehensions, you can say: ``` arr = [[None for x in range(6)] for y in range(6)] ``` Then you will have `arr[1][2] = 10` working as expected. This is not a very normal thing to do, however. What are you going to use the nested lists for? There may be a better way. For example, working with arrays is mad...
Initializing 2D array in Python
9,954,183
4
2012-03-31T08:04:57Z
9,956,306
12
2012-03-31T13:31:56Z
[ "python", "list", "python-3.x" ]
I have a problem with initialzing a 2D array in python. I want a 6x6 array, I did ``` arr = [[None]*6]*6 ``` But when I do: ``` >>> arr[1][2]=10 >>> arr [[None, None, 10, None, None, None], [None, None, 10, None, None, None], [None, None, 10, None, None, None], [None, None, 10, None, None, None], [None, None, 10, No...
@Cameron is correct in suggesting that you use NumPy to deal with arrays of numerical data. And for the second part of your question, ~Niklas B. is spot on with his suggestion to use `defaultdict`. What hasn't been covered is *why* `[[None]*6]*6` behaves strangely. The answer is that `[None]*6` creates a list with si...
Django datefield and timefield to python datetime
9,954,498
6
2012-03-31T08:59:06Z
9,954,513
8
2012-03-31T09:01:36Z
[ "python", "django", "datetime" ]
I have a Django model with separate Datefield and Timefield for an event. Is there a way to convert it to a python datetime object so I can query for the upcoming events with some precision? Currently I get only the upcoming of the following day. models.py ``` event_time = models.TimeField() event_date = models.DateF...
Use a `DateTimeField` instead (see [this section](https://docs.djangoproject.com/en/dev/ref/forms/fields/#datetimefield) in the docs). Conversion to a `datetime.datetime` is handled for you by Django automatically. A `DateField` results in a `datetime.date` and a `datetime.time` object. You can use `replace` to merge ...
S3 boto list keys sometimes returns directory key
9,954,521
11
2012-03-31T09:03:33Z
9,960,280
15
2012-03-31T22:32:38Z
[ "python", "amazon-s3", "amazon-web-services", "boto" ]
I've noticed a difference between the returns from boto's api depending on the bucket location. I have the following code: ``` con = S3Connection(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) bucket = con.get_bucket(S3_BUCKET_NAME) keys = bucket.list(path) for key in keys: print key ``` which im running against two buc...
Thanks to Steffen, who suggested looking at how the keys are created. With further investigation I think I've got a handle on whats happening here. My original suposition that it was linked to the bucket region was a red herring. It appears to be due to what the management console does when you manipulate keys. If you...
Django Transaction managed block ended with pending COMMIT/ROLLBACK
9,955,321
4
2012-03-31T11:03:57Z
9,955,857
17
2012-03-31T12:28:34Z
[ "python", "django", "sqlite3", "django-orm" ]
I have a view function which needs to be manually transaction managed, but when I apply the `@transaction.commit_manually` decorator, django ALWAYS raises the below exception. As you can see from the code trace below, the transaction is committed right before return from the view. I am using sqlite, both on windows a...
It turns out that during template rendering, there was database access, so the usual pattern like: ``` return render_to_response('mainapp/templates/incorporate.html', RequestContext(request, form_params)) ``` was the cause of the problem. I needed to replace that with: ``` retval = render_t...
Why is only the innermost of these nested while loops working?
9,956,315
3
2012-03-31T13:33:02Z
9,956,364
7
2012-03-31T13:40:36Z
[ "python", "while-loop" ]
I'm newbie in Python. I have this simple code ``` a = 0 b = 0 c = 0 while a <= 5: while b <=3: while c <= 8: print a , b , c c += 1 b += 1 a += 1 ``` And work only while with C ``` 0 0 0 0 0 1 0 0 2 0 0 3 0 0 4 0 0 5 0 0 6 0 0 7 0 0 8 ``` Why? How to fix it? Thanks!
# First way Your way will work, but you have to remember to reset the loop counters on each iteration. ``` a = 0 b = 0 c = 0 while a <= 5: while b <=3: while c <= 8: print a , b , c c += 1 b += 1 c = 0 # reset a += 1 b = 0 # reset c = 0 # reset ``` # S...
How to install multiple python packages at once using pip
9,956,741
33
2012-03-31T14:29:46Z
9,956,808
25
2012-03-31T14:35:56Z
[ "python", "pip" ]
I know it's an easy way of doing it but i didn't find it neither here nor on google. So i was curious if there is a way to install multiple packages using pip. Something like: ``` pip install progra1 , progra2 ,progra3 ,progra4 . ``` or: ``` pip install (command to read some txt containing the name of the modules) `...
`pip install -r requirements.txt` and in the requirements.txt file you put your modules in a list, with one item per line. * Django=1.3.1 * South>=0.7 * django-debug-toolbar
How to install multiple python packages at once using pip
9,956,741
33
2012-03-31T14:29:46Z
9,956,813
60
2012-03-31T14:36:39Z
[ "python", "pip" ]
I know it's an easy way of doing it but i didn't find it neither here nor on google. So i was curious if there is a way to install multiple packages using pip. Something like: ``` pip install progra1 , progra2 ,progra3 ,progra4 . ``` or: ``` pip install (command to read some txt containing the name of the modules) `...
For installing multiple packages on the command line, just pass them as a space-delimited list, e.g.: ``` pip install wsgiref boto ``` For installing from a text file, then, from `pip install --help`: > -r FILENAME, --requirement=FILENAME > > Install all the packages listed in the given requirements file. This optio...