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
Looking for a more pythonic logical solution
10,816,816
6
2012-05-30T12:59:51Z
10,816,890
8
2012-05-30T13:04:59Z
[ "python", "logic" ]
I was doing some practice problems in [Coding Bat](http://codingbat.com/python), and came across this one.. ``` Given 3 int values, a b c, return their sum. However, if one of the values is the same as another of the values, it does not count towards the sum. lone_sum(1, 2, 3) → 6 lone_sum(3, 2, 3) → 2 lone_sum(...
A more general solution for any number of arguments is ``` def lone_sum(*args): seen = set() summands = set() for x in args: if x not in seen: summands.add(x) seen.add(x) else: summands.discard(x) return sum(summands) ```
Looking for a more pythonic logical solution
10,816,816
6
2012-05-30T12:59:51Z
10,816,965
13
2012-05-30T13:09:10Z
[ "python", "logic" ]
I was doing some practice problems in [Coding Bat](http://codingbat.com/python), and came across this one.. ``` Given 3 int values, a b c, return their sum. However, if one of the values is the same as another of the values, it does not count towards the sum. lone_sum(1, 2, 3) → 6 lone_sum(3, 2, 3) → 2 lone_sum(...
Another possibility that works for an arbitrary number of arguments: ``` from collections import Counter def lone_sum(*args): return sum(x for x, c in Counter(args).items() if c == 1) ``` Note that in Python 2, you should use `iteritems` to avoid building a temporary list.
Looking for a more pythonic logical solution
10,816,816
6
2012-05-30T12:59:51Z
10,818,038
7
2012-05-30T14:12:13Z
[ "python", "logic" ]
I was doing some practice problems in [Coding Bat](http://codingbat.com/python), and came across this one.. ``` Given 3 int values, a b c, return their sum. However, if one of the values is the same as another of the values, it does not count towards the sum. lone_sum(1, 2, 3) → 6 lone_sum(3, 2, 3) → 2 lone_sum(...
How about: ``` def lone_sum(*args): return sum(v for v in args if args.count(v) == 1) ```
Finding index of nearest point in numpy arrays of x and y coordinates
10,818,546
30
2012-05-30T14:39:27Z
10,818,976
20
2012-05-30T15:03:48Z
[ "python", "algorithm", "numpy" ]
I have two 2d numpy arrays: x\_array contains positional information in the x-direction, y\_array contains positions in the y-direction. I then have a long list of x,y points. For each point in the list, I need to find the array index of the location (specified in the arrays) which is closest to that point. I have n...
`scipy.spatial` also has a k-d tree implementation: [`scipy.spatial.KDTree`](http://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.KDTree.html#scipy.spatial.KDTree). The approach is generally to first use the point data to build up a k-d tree. The computational complexity of that is on the order of N log N...
Finding index of nearest point in numpy arrays of x and y coordinates
10,818,546
30
2012-05-30T14:39:27Z
32,781,737
7
2015-09-25T11:59:48Z
[ "python", "algorithm", "numpy" ]
I have two 2d numpy arrays: x\_array contains positional information in the x-direction, y\_array contains positions in the y-direction. I then have a long list of x,y points. For each point in the list, I need to find the array index of the location (specified in the arrays) which is closest to that point. I have n...
Here is a `scipy.spatial.KDTree` example ``` In [1]: from scipy import spatial In [2]: import numpy as np In [3]: A = np.random.random((10,2))*100 In [4]: A Out[4]: array([[ 68.83402637, 38.07632221], [ 76.84704074, 24.9395109 ], [ 16.26715795, 98.52763827], [ 70.99411985, 67.31740151], ...
How to set a files owner in python?
10,818,824
5
2012-05-30T14:55:35Z
10,818,843
15
2012-05-30T14:56:37Z
[ "python", "file-permissions" ]
Firstly is it possible to set a file's owner with python? And if so how do you set a file's owner with python?
``` os.chown(path, uid, gid) ``` <http://docs.python.org/library/os.html> The uid and gid can be retrieved from a string by ``` import pwd import grp import os uid = pwd.getpwnam("nobody").pw_uid gid = grp.getgrnam("nogroup").gr_gid ``` Reference: [How to change the user and group permissions for a directory, by n...
SQLAlchemy result for UTF-8 column is of type 'str', why?
10,819,192
14
2012-05-30T15:15:06Z
10,819,357
24
2012-05-30T15:24:24Z
[ "python", "mysql", "string", "encoding", "sqlalchemy" ]
I have a SQL query that I execute like this with an SQLAlchemy engine: ``` result = engine.execute('SELECT utf_8_field FROM table') ``` The database is MySQL and the column type is TEXT with UTF-8 encoding. The type of the returned utf\_8\_field is "str", even if I set the option convert\_unicode=True when creating t...
If you want the data converted automatically, you should [specify the charset](http://docs.sqlalchemy.org/en/rel_0_7/dialects/mysql.html#unicode) when you create the engine: ``` create_engine('mysql+mysqldb:///mydb?charset=utf8') ``` Setting `use_unicode` alone won't tell sqlalchemy which charset to use.
Numpy genfromtxt Column Names
10,819,330
6
2012-05-30T15:22:47Z
10,819,607
11
2012-05-30T15:39:50Z
[ "python", "numpy" ]
How can I have genfromtxt to return me its list of column names which were automatically retrieved by names=True? When I do ``` data = np.genfromtxt("test.csv",names=True,delimiter=",",dtype=None) print data['col1'] ``` It prints the entire column values for col1. But I need to traverse all column names; how can I do...
`genfromtxt`returns a [numpy.ndarray](http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.html). You can get the data type with ``` data.dtype ``` or just the names with ``` data.dtype.names ``` which is a tuple you can iterate over and access the columns as you want to.
Finding exception in python multiprocessing
10,819,447
5
2012-05-30T15:29:46Z
10,831,178
10
2012-05-31T09:47:54Z
[ "python", "multithreading", "multiprocessing", "stack-trace" ]
I have a bit of python code that looks like this: ``` procs = cpu_count()-1 if serial or procs == 1: results = map(do_experiment, experiments) else: pool = Pool(processes=procs) results = pool.map(do_experiment, experiments) ``` It runs fine when I set the `serial` flag, but it gives the following er...
I went back in my git history until I found a commit where things were still working. I added a class to my code that extends `dict` so that keys can be accessed with a `.` (so `dict.foo` in stead of `dict["foo"]`. Multiprocessing did not take kindly to this, using an ordinary dict solved the problem.
Comparing NumPy arrays so that NaNs compare equal
10,819,715
12
2012-05-30T15:46:03Z
10,821,108
8
2012-05-30T17:18:02Z
[ "python", "numpy", "comparison", null ]
Is there an idiomatic way to compare two NumPy arrays that would treat NaNs as being equal to each other (but not equal to anything *other* than a NaN). For example, I want the following two arrays to compare equal: ``` np.array([1.0, np.NAN, 2.0]) np.array([1.0, np.NAN, 2.0]) ``` and the following two arrays to com...
*Disclaimer: I don't recommend this for regular use, and I wouldn't use it myself, but I could imagine rare circumstances under which it might be useful.* If the arrays have the same shape and dtype, you could consider using the low-level `memoryview`: ``` >>> import numpy as np >>> >>> a0 = np.array([1.0, np.NAN, 2...
Comparing NumPy arrays so that NaNs compare equal
10,819,715
12
2012-05-30T15:46:03Z
10,821,267
14
2012-05-30T17:29:18Z
[ "python", "numpy", "comparison", null ]
Is there an idiomatic way to compare two NumPy arrays that would treat NaNs as being equal to each other (but not equal to anything *other* than a NaN). For example, I want the following two arrays to compare equal: ``` np.array([1.0, np.NAN, 2.0]) np.array([1.0, np.NAN, 2.0]) ``` and the following two arrays to com...
If you really care about memory use (e.g. have very large arrays), then you should use numexpr and the following expression will work for you: ``` np.all(numexpr.evaluate('(a==b)|((a!=a)&(b!=b))')) ``` I've tested it on very big arrays with length of 3e8, and the code has the same performance on my machine as ``` np...
Read random lines from huge CSV file in Python
10,819,911
21
2012-05-30T15:56:58Z
10,820,002
19
2012-05-30T16:03:29Z
[ "python", "file", "csv", "random" ]
I have this quite big CSV file (15 Gb) and I need to read about 1 million random lines from it. As far as I can see - and implement - the CSV utility in Python only allows to iterate sequentially in the file. It's very memory consuming to read the all file into memory to use some random choosing and it's very time con...
``` import random filesize = 1500 #size of the really big file offset = random.randrange(filesize) f = open('really_big_file') f.seek(offset) #go to random position f.readline() # discard - bound to be partial line random_line = f.readline() # bingo! # extra t...
Read random lines from huge CSV file in Python
10,819,911
21
2012-05-30T15:56:58Z
10,820,199
7
2012-05-30T16:17:13Z
[ "python", "file", "csv", "random" ]
I have this quite big CSV file (15 Gb) and I need to read about 1 million random lines from it. As far as I can see - and implement - the CSV utility in Python only allows to iterate sequentially in the file. It's very memory consuming to read the all file into memory to use some random choosing and it's very time con...
> I have this quite big CSV file (15 Gb) and I need to read about 1 million random lines from it Assuming you don't need **exactly** 1 million lines and know then number of lines in your CSV file beforehand, you can use [reservoir sampling](http://en.wikipedia.org/wiki/Reservoir_sampling) to retrieve your random subse...
Pythonic equivalent of this function?
10,820,069
4
2012-05-30T16:08:32Z
10,820,194
7
2012-05-30T16:16:52Z
[ "python" ]
I have a function to port from another language, could you please help me make it "pythonic"? Here the function ported in a "non-pythonic" way (this is a bit of an artificial example - every task is associated with a project or "None", we need a list of distinct projects, distinct meaning no duplication of the .identi...
There's nothing massively unPythonic about this code. A couple of possible improvements: * `project_identifiers_seen` could be a set, rather than a dictionary. * `foo.has_key(bar)` is better spelled `bar in foo` * I'm suspicious that this is a `staticmethod` of a class. Usually there's no need for a class in Python un...
Writing nicely formatted text in Python
10,821,083
6
2012-05-30T17:16:16Z
10,821,162
9
2012-05-30T17:21:56Z
[ "python", "file", "text" ]
In Python, I'm writing to a text file with code like: ``` f.write(filename + type + size + modified) ``` And of course the output looks really ugly: ``` C:/Config/ControlSet/__db.006 file 56 KB 2012-Apr-30 10:00:46.467 AM C:/Config/ControlSet dir 68881 KB 2012-Apr-30 10:00:46.396 AM C:/Config/Da...
I think what you're looking for is the [str.ljust()](http://docs.python.org/library/stdtypes.html#str.ljust) method and maybe [str.rjust()](http://docs.python.org/library/stdtypes.html#str.rjust) too. As it says in the docs, the original string is returned if it's too long, so you will never truncate away any data, bu...
Writing nicely formatted text in Python
10,821,083
6
2012-05-30T17:16:16Z
10,821,260
13
2012-05-30T17:28:56Z
[ "python", "file", "text" ]
In Python, I'm writing to a text file with code like: ``` f.write(filename + type + size + modified) ``` And of course the output looks really ugly: ``` C:/Config/ControlSet/__db.006 file 56 KB 2012-Apr-30 10:00:46.467 AM C:/Config/ControlSet dir 68881 KB 2012-Apr-30 10:00:46.396 AM C:/Config/Da...
If you can get a list of all filenames first, then you could do something like: ``` max_width = max(len(filename) for filename in filenames) for filename in filenames: f.write(filename.ljust(max_width+1)+..whatever else..) ``` If you can't get a list of all filenames first, then there's no way to make sure that e...
Performing operations on all values of a numpy array, referencing i and j
10,821,477
3
2012-05-30T17:43:23Z
10,821,656
7
2012-05-30T17:55:02Z
[ "python", "arrays", "performance", "numpy", "indexing" ]
I am trying to improve numpy performance by applying operations on a 2d array, the problem is that the value at each element in the array depends on the i,j location of that element. Obviously the easy way to do this is to use a nested for-loop, but I was wondering if there might be a better way by referencing np.indi...
Since you're doing multiplication among your two arrays, you can use the [outer](http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.outer.html) function, after using `arange` to get arrays of your sin/cos. Something like this (use numpy's trig functions, since they're vectorized) ``` PSI_i = numpy.sin((...
How to kill Django runserver sub processes from a bash script?
10,821,597
12
2012-05-30T17:51:35Z
10,821,880
13
2012-05-30T18:11:28Z
[ "python", "django", "bash", "shell" ]
I'm working on a Django website where I have various compilation programs that need to run (Compass/Sass, coffeescript, hamlpy), so I made this shell script for convenience: ``` #!/bin/bash SITE=/home/dev/sites/rmx echo "RMX using siteroot=$SITE" $SITE/rmx/manage.py runserver & PIDS[0]=$! compass watch $SITE/media/co...
**SOLVED** Thanks to [this SO question](http://stackoverflow.com/questions/392022/best-way-to-kill-all-child-processes), I've changed my script to this: ``` #!/bin/bash SITE=/home/dev/sites/rmx echo "RMX using siteroot=$SITE" $SITE/rmx/manage.py runserver & compass watch $SITE/media/compass/ & coffee -o $SITE/media/...
Given a list of integers, determine if 70% of the values are within 20% of one of the values
10,821,753
2
2012-05-30T18:01:51Z
10,821,805
7
2012-05-30T18:05:53Z
[ "python", "arrays", "algorithm", "list", "array-algorithms" ]
I want to check if the list values have some level of "closeness". Is there a good algorithm to do this? Bonus points for the most pythonic way. Valid ``` [1,7,8,9] [3,4,100,101,102,103,104,105] ``` Not Valid ``` [1,8,9] [1,10] [100,200,300,400,500] ```
Look up variance: <http://en.wikipedia.org/wiki/Variance>
python - Is it a bad practice to do I/O in unitest
10,821,859
2
2012-05-30T18:09:33Z
10,821,897
7
2012-05-30T18:12:21Z
[ "python", "unit-testing" ]
I have some unitest is doing something like: ``` _files = ('test1.txt','test2.txt'......) setUp(){ //create test files for f in _files: f = open(f, 'w') f.close() } tearDown(){ for f in _files: if os.path.exists(f): os.remove(f) } ``` But some people told me it's not a good pr...
> But some people told me it's not a good practice to do I/O in unitest, is it true? I don't think it's necessarily bad to perform I/O in a unit test. The only caveat is that if your unit test relies on some pre-existing data files in order to do its thing, then the files should be considered part of the unit test (a...
Get the number of rows in table using SQLAlchemy
10,822,635
19
2012-05-30T19:06:22Z
10,822,842
28
2012-05-30T19:20:16Z
[ "python", "sql", "sqlalchemy" ]
I am using SQLAlchemy in Python, and I want to know how to get the total number of rows in a column. I have variables defined: ``` engine = sqlalchemy.create_engine(url, ehco=False) Session = sqlalchemy.orm.sessionmaker(bind=engine) Session = session() metadata = sqlalchemy.MetaData(engine) Base = declarative_base(met...
This should work ``` rows = session.query(Congress).count() ``` **EDIT:** Another way related to my first try ``` from sqlalchemy import func rows = session.query(func.count(Congress.id)).scalar() ```
Python simple naked objects
10,823,610
13
2012-05-30T20:17:09Z
10,823,655
19
2012-05-30T20:20:38Z
[ "python", "oop" ]
What's the easiest way to create a naked object that I can assign attributes to? The specific use case is: I'm doing various operations on a Django object instance, but sometimes the instance is None (there is on instance). In this case I'd like to create the simplest possible fake object such that I can assign values...
You need to create a simple class first: ``` class Foo(object): pass myobject = Foo() myobject.foo = 'bar' ``` You can make it a one-liner like this: ``` myobject = type("Foo", (object,), {})() myobject.foo = 'bar' ``` The call to `type` functions identically to the previous `class` statement. If you want to ...
Python Database
10,823,918
5
2012-05-30T20:40:27Z
10,823,962
10
2012-05-30T20:43:29Z
[ "python" ]
My question is how to create a simple database in python. My example is: ``` User = { 'Name' : {'Firstname', 'Lastname'}, 'Address' : {'Street','Zip','State'}, 'CreditCard' : {'CCtype','CCnumber'}, } ``` Now I can update this User's information just fine, but how do I 1. Add more users to this data structure. A dict...
You might be interested in [SQLAlchemy](http://www.sqlalchemy.org/). It makes an actual database, such as SQLite or MySQL, work more like Python classes.
matplotlib legend location numbers
10,824,156
13
2012-05-30T20:57:37Z
10,824,512
18
2012-05-30T21:26:39Z
[ "python", "matplotlib" ]
I am beginning to use Python for my scientific computing, and I am really liking it a lot, however I am confused by a feature of the matplotlib.pylab.legend function. In particular, the location feature allows one to specifiy the location of their legend using numbers, following this scheme: * best -- 0 * upper right ...
The [docs](http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.legend) show this example: ``` legend( ('label1', 'label2', 'label3'), loc='upper left') ``` Presumably, you could write `loc=2`, but why would you? It's much more readable to use the English word. As to why they didn't enumerate the ...
Python: How to convert a string containing hex bytes to a hex string
10,824,319
8
2012-05-30T21:10:00Z
10,824,333
15
2012-05-30T21:11:36Z
[ "python", "string", "hex" ]
I'm thinking binascii is the module I'm looking for, but I can't quite seem to get the exact results for which I am looking. Here's what I want to do. I want to convert: ``` >>> s = '356a192b7913b04c54574d18c28d46e6395428ab' >>> print len(s) 40 ``` to ``` >>> hs = '\x35\x6a\x19\x2b\x79\x13\xb0\x4c\x54\x57\x4d\x18\x...
Easiest solution in Python 2.x: ``` >>> s = '356a192b7913b04c54574d18c28d46e6395428ab' >>> s.decode("hex") '5j\x19+y\x13\xb0LTWM\x18\xc2\x8dF\xe69T(\xab' ``` The second line is equivalent to ``` binascii.a2b_hex(s) ```
Does sqlite3 compress data?
10,824,347
10
2012-05-30T21:12:48Z
10,824,421
15
2012-05-30T21:18:07Z
[ "python", "sqlite" ]
I've got an 7.4Gb csv file. After converting it to a sqlite database with a [python script](https://gist.github.com/2838964) the output DB is 4.7Gb, around 60% of the original size. The csv has around 150,000,000 rows. It has header: ``` tkey,ipaddr,healthtime,numconnections,policystatus,activityflag ``` And each ro...
SQLite is not running a compression algorithm, but it will store data in a binary file instead of a text file. Which means that the data can be stored more efficiently, for example using a 32-bit (4 byte) number to represent `10,000,000` instead of storing it as 8 bytes of text (or more if the file is unicode). Here a...
Does sqlite3 compress data?
10,824,347
10
2012-05-30T21:12:48Z
20,365,251
10
2013-12-04T01:40:56Z
[ "python", "sqlite" ]
I've got an 7.4Gb csv file. After converting it to a sqlite database with a [python script](https://gist.github.com/2838964) the output DB is 4.7Gb, around 60% of the original size. The csv has around 150,000,000 rows. It has header: ``` tkey,ipaddr,healthtime,numconnections,policystatus,activityflag ``` And each ro...
SQLite, by default, does not compress data it writes to the disk; however, SQLite does have a set of "Proprietary Extensions" for that and other purposes. Look for `ZIPVFS` in the links as follows. <http://www.sqlite.org/support.html> and <http://www.hwaci.com/sw/sqlite/prosupport.html> You can achieve a lot of "comp...
Python 3.x rounding behavior
10,825,926
60
2012-05-31T00:11:09Z
10,825,998
68
2012-05-31T00:24:15Z
[ "python", "python-3.x", "rounding" ]
I was just re-reading [What’s New In Python 3.0](http://docs.python.org/py3k/whatsnew/3.0.html) and it states: > The round() function rounding strategy and return type have changed. > Exact halfway cases are now rounded to the nearest even result instead > of away from zero. (For example, round(2.5) now returns 2 ra...
Python 3.0's way is considered the standard rounding method these days, though some language implementations aren't on the bus yet. The simple "always round 0.5 up" technique results in a slight bias toward the higher number. With large numbers of calculations, this can be significant. The Python 3.0 approach eliminat...
Python 3.x rounding behavior
10,825,926
60
2012-05-31T00:11:09Z
10,826,537
14
2012-05-31T01:59:12Z
[ "python", "python-3.x", "rounding" ]
I was just re-reading [What’s New In Python 3.0](http://docs.python.org/py3k/whatsnew/3.0.html) and it states: > The round() function rounding strategy and return type have changed. > Exact halfway cases are now rounded to the nearest even result instead > of away from zero. (For example, round(2.5) now returns 2 ra...
You can control the rounding you get in Py3000 using the [Decimal module](http://docs.python.org/library/decimal.html#decimal-faq): ``` >>> decimal.Decimal('3.5').quantize(decimal.Decimal('1'), rounding=decimal.ROUND_HALF_UP) >>> Decimal('4') >>> decimal.Decimal('2.5').quantize(decimal.Decimal('1'), roun...
Database migrations on django production
10,826,266
13
2012-05-31T01:12:34Z
10,860,413
13
2012-06-02T06:45:14Z
[ "python", "mysql", "django", "migration", "django-south" ]
From someone who has a django application in a non-trivial production environment, how do you handle database migrations? I know there is `south`, but it seems like that would miss quite a lot if anything substantial is involved. The other two options (that I can think of or have used) is doing the changes on a test d...
I think there are two parts to this problem. First is managing the database schema and it's changes. We do this using South, keeping both the working models and the migration files in our SCM repository. For safety (or paranoia), we take a dump of the database before (and if we are really scared, after) running any mi...
Override module method where from...import is used
10,829,200
8
2012-05-31T07:30:14Z
10,829,381
16
2012-05-31T07:44:47Z
[ "python" ]
I have problem to override method where from...import statement is used. Some example to illustrate the problem: ``` # a.py module def print_message(msg): print(msg) # b.py module from a import print_message def execute(): print_message("Hello") # c.py module which will be executed import b b.execute() ``` ...
With your `a` and `b` modules untouched you could try implementing `c` as follows: ``` import a def _new_print_message(message): print "NEW:", message a.print_message = _new_print_message import b b.execute() ``` You have to first import `a`, then override the function and then import `b` so that it would use ...
How to unset a timer set by python gobject.timeout_add ? threads?
10,829,341
2
2012-05-31T07:41:31Z
11,121,928
8
2012-06-20T14:34:45Z
[ "python", "multithreading", "timer", "pygobject" ]
I want to set timer in a thread and kill that thread when I want to unset the timer set by gobject.timeout\_add, is this a good way to do this? basically I want to run a function for every 180 seconds but I want to be able to stop it whenever I want to(called from another function). How to achieve this properly? I ha...
According to the [docs](http://www.pygtk.org/pygtk2reference/gobject-functions.html#function-gobject--timeout-add) when you call `gobject.timeout_add` it returns a `int` which is unique for that timeout source. And then also farther down in the [docs](http://www.pygtk.org/pygtk2reference/gobject-functions.html#function...
How to upload a file to Google Drive using a Python script?
10,830,820
10
2012-05-31T09:25:05Z
10,837,529
10
2012-05-31T16:24:54Z
[ "python", "backup", "google-docs-api", "google-drive-sdk" ]
I need to backup various file types to GDrive (not just those convertible to GDocs formats) from some linux server. What would be the simplest, most elegant way to do that with a python script? Would any of the solutions pertaining to GDocs be applicable?
You can use the Documents List API to write a script that writes to Drive: <https://developers.google.com/google-apps/documents-list/> Both the Documents List API and the Drive API interact with the same resources (i.e. same documents and files). This sample in the Python client library shows how to upload an unconv...
Python object persistence
10,830,869
9
2012-05-31T09:28:23Z
10,831,281
10
2012-05-31T09:54:29Z
[ "python", "persistence" ]
I'm seeking advice about methods of implementing object persistence in Python. To be more precise, I wish to be able to link a Python object to a file in such a way that any Python process that opens a representation of that file shares the same information, any process can change its object and the changes will propag...
Use the [`ZODB`](http://zodb.org/) (the Zope Object Database) instead. Backed with ZEO it fulfills your requirements: * Transparent persistence for Python objects ZODB uses pickles underneath so anything that is pickle-able can be stored in a ZODB object store. * Full ACID-compatible transaction support (including ...
Matplotlib plots not displaying in sublimetext
10,831,882
8
2012-05-31T10:33:12Z
10,832,619
10
2012-05-31T11:23:17Z
[ "python", "matplotlib", "sublimetext2" ]
I've recently started using sublimetext 2, however I noticed today that the `plt.show()` function doesn't seem to work when run within sublimetext. If for example I create the following script: ``` import matplotlib.pyplot as plt plt.plot([1,2,3,4]) plt.show() ``` Running this with IDLE generates a plot, however usi...
My guess would be that Sublime Text 2 launches your code in its own environment, and only traps and displays the console output. The same problem exists when using GUI's, such as wxPython. Another work around is to open the command prompt and launch it manually (python file.py). **EDIT:** [Here](http://sublimetext.in...
python dictionary match key values in two dictionaries
10,832,373
4
2012-05-31T11:05:25Z
10,832,405
13
2012-05-31T11:08:15Z
[ "python" ]
In the below shown dictionaries i want to check whether the key in aa matches the key in bb and also the value corresponding to it matches in bb or not.Is there a better way to write this code ``` aa = {'a': 1, 'c': 3, 'b': 2} bb = {'a': 1, 'b': 2} for k in aa: if k in bb: if aa[k] == bb[k]: ...
Use sets to find all equivalents: ``` for (key, value) in set(aa.items()) & set(bb.items()): print '%s: %s is present in both aa and bb' % (key, value) ``` The `&` operator here gives you the [intersection of both sets](http://docs.python.org/library/stdtypes.html#set.intersection); alternatively you could write:...
Windows explorer context menus with sub-menus using pywin32
10,833,710
11
2012-05-31T12:33:48Z
10,911,471
11
2012-06-06T09:25:43Z
[ "python", "contextmenu", "pywin32", "shell-extensions" ]
I'm trying add some shell extensions using python with icons and a sub menu but I'm struggling to get much further than the demo in pywin32. I can't seem to come up with anything by searching google, either. I believe I need to register a com server to be able to change the options in submenu depending on where the ri...
I found out how to do this after a lot of trial and error and googling. The example below shows a menu with a submenu and icons. ``` # A sample context menu handler. # Adds a menu item with sub menu to all files and folders, different options inside specified folder. # When clicked a list of selected items is displa...
Any equivalent of * style in Bash for acting on mutliple files NOT matching the same pattern
10,834,054
3
2012-05-31T12:54:52Z
10,834,087
9
2012-05-31T12:57:02Z
[ "python" ]
I'm looking to iterate a script over all files in the present working directory *without* iterating over scripts (so any extension `.py`). I was prevously using this ``` for fileName in os.listdir('.'): if fileName != 'autocorrelation1.py': with open(fileName, "r") as input: REST OF SCRIPT HERE ``...
I recommend using the [fnmatch](http://docs.python.org/library/fnmatch.html#module-fnmatch) module: ``` for fileName in os.listdir('.'): if not fnmatch.fnmatch(fileName, '*.py'): print fileName ``` --- The [glob](http://docs.python.org/library/glob.html) module could help you find matching files, if that...
How to do multiple arguments to map function where one remains the same in python?
10,834,960
42
2012-05-31T13:48:48Z
10,834,979
21
2012-05-31T13:50:03Z
[ "python" ]
Lets say we have a function add as follows ``` def add(x, y): return x + y ``` we want to apply map function for an array ``` map(add, [1, 2, 3], 2) ``` The semantics are I want to add 2 to the every element of the array. But the `map` function requires a list in the third argument as well. **Note:** I am putt...
Use a list comprehension. ``` [x + 2 for x in [1, 2, 3]] ``` If you *really*, *really*, *really* want to use `map`, give it an anonymous function as the first argument: ``` map(lambda x: x + 2, [1,2,3]) ```
How to do multiple arguments to map function where one remains the same in python?
10,834,960
42
2012-05-31T13:48:48Z
10,834,984
67
2012-05-31T13:50:19Z
[ "python" ]
Lets say we have a function add as follows ``` def add(x, y): return x + y ``` we want to apply map function for an array ``` map(add, [1, 2, 3], 2) ``` The semantics are I want to add 2 to the every element of the array. But the `map` function requires a list in the third argument as well. **Note:** I am putt...
One option is a list comprehension: ``` [add(x, 2) for x in [1, 2, 3]] ``` More options: ``` a = [1, 2, 3] import functools map(functools.partial(add, y=2), a) import itertools map(add, a, itertools.repeat(2, len(a))) ```
How to do multiple arguments to map function where one remains the same in python?
10,834,960
42
2012-05-31T13:48:48Z
10,835,067
9
2012-05-31T13:55:51Z
[ "python" ]
Lets say we have a function add as follows ``` def add(x, y): return x + y ``` we want to apply map function for an array ``` map(add, [1, 2, 3], 2) ``` The semantics are I want to add 2 to the every element of the array. But the `map` function requires a list in the third argument as well. **Note:** I am putt...
If you have it available, I would consider using numpy. It's very fast for these types of operations: ``` >>> import numpy >>> numpy.array([1,2,3]) + 2 array([3, 4, 5]) ``` This is assuming your real application is doing mathematical operations (that can be vectorized).
How to do multiple arguments to map function where one remains the same in python?
10,834,960
42
2012-05-31T13:48:48Z
27,025,330
11
2014-11-19T19:28:42Z
[ "python" ]
Lets say we have a function add as follows ``` def add(x, y): return x + y ``` we want to apply map function for an array ``` map(add, [1, 2, 3], 2) ``` The semantics are I want to add 2 to the every element of the array. But the `map` function requires a list in the third argument as well. **Note:** I am putt...
The docs explicitly suggest this is the main use for `itertools.repeat`: > Make an iterator that returns object over and over again. Runs indefinitely unless the times argument is specified. Used as argument to [`map()`](https://docs.python.org/3/library/functions.html#map) for invariant parameters to the called funct...
Find element by text with XPath in ElementTree
10,836,205
7
2012-05-31T15:04:23Z
10,836,343
23
2012-05-31T15:12:55Z
[ "python", "xml", "xpath", "elementtree" ]
Given an XML like the following: ``` <root> <element>A</element> <element>B</element> </root> ``` How can I match the element with content A using ElementTree and its support for XPath? Thanks
AFAIK ElementTree does not support XPath. Has it changed? Anyway, you can use [lxml](http://lxml.de) and the following XPath expression: ``` import lxml.etree doc = lxml.etree.parse('t.xml') print doc.xpath('//element[text()="A"]')[0].text print doc.xpath('//element[text()="A"]')[0].tag ``` The result will be: ``` ...
Find element by text with XPath in ElementTree
10,836,205
7
2012-05-31T15:04:23Z
10,837,113
8
2012-05-31T15:58:00Z
[ "python", "xml", "xpath", "elementtree" ]
Given an XML like the following: ``` <root> <element>A</element> <element>B</element> </root> ``` How can I match the element with content A using ElementTree and its support for XPath? Thanks
If you want to use the standard library [ElementTree](http://docs.python.org/library/xml.etree.elementtree.html), rather than lxml, you can use iteration to find all sub elements with a particular text value. For example: ``` import sys import xml.etree.ElementTree as etree s = """<root> <element>A</element> ...
selecting a single field from a list of dictionaries in python
10,836,763
3
2012-05-31T15:36:31Z
10,836,834
8
2012-05-31T15:40:18Z
[ "python", "list", "dictionary", "for-loop" ]
Lets say I have a list of dictionaries like so: ``` dictionList = {1: {'Type': 'Cat', 'Legs': 4}, 2: {'Type': 'Dog', 'Legs': 4}, 3: {'Type': 'Bird', 'Legs': 2}} ``` Using a for loop I want to iterate through the list until I catch a dictionary with a `Type` field equal to `"Dog"`. My bes...
Use the `values` iterator for dictionaries: ``` for v in dictionList.values(): if v['Type']=='Dog': print "Found a dog!" ``` EDIT: I will say though that in your original question you are asking to check the `Type` of a value in a dictionary, which is somewhat misleading. What you are requesting is the c...
Shade 'cells' in polar plot with matplotlib
10,837,296
8
2012-05-31T16:09:36Z
10,838,501
10
2012-05-31T17:38:47Z
[ "python", "plot", "matplotlib" ]
I've got a bunch of regularly distributed points (θ = n\*π/6, r=1...8), each having a value in [0, 1]. I can plot them with their values in matplotlib using ``` polar(thetas, rs, c=values) ``` But rather then having just a meagre little dot I'd like to shade the corresponding 'cell' (ie. everything until halfway to...
Sure! Just use `pcolormesh` on a polar axes. E.g. ``` import matplotlib.pyplot as plt import numpy as np # Generate some data... # Note that all of these are _2D_ arrays, so that we can use meshgrid # You'll need to "grid" your data to use pcolormesh if it's un-ordered points theta, r = np.mgrid[0:2*np.pi:20j, 0:1:1...
Shade 'cells' in polar plot with matplotlib
10,837,296
8
2012-05-31T16:09:36Z
10,848,538
9
2012-06-01T10:22:56Z
[ "python", "plot", "matplotlib" ]
I've got a bunch of regularly distributed points (θ = n\*π/6, r=1...8), each having a value in [0, 1]. I can plot them with their values in matplotlib using ``` polar(thetas, rs, c=values) ``` But rather then having just a meagre little dot I'd like to shade the corresponding 'cell' (ie. everything until halfway to...
This can be done quite nicely by treating it as a polar stacked barchart: ``` import matplotlib.pyplot as plt import numpy as np from random import choice fig = plt.figure() ax = fig.add_axes([0.1, 0.1, 0.8, 0.8], polar=True) for i in xrange(12*8): color = choice(['navy','maroon','lightgreen']) ax.bar(i * 2 ...
Django ORM on Standalone Applications
10,837,863
4
2012-05-31T16:49:13Z
10,852,095
8
2012-06-01T14:25:24Z
[ "python", "django", "orm" ]
I followed this [link](http://stackoverflow.com/questions/937742/use-django-orm-as-standalone) to use Django's ORM on my stand alone application in python. manage.py sql 'application\_name' and manage.py syncdb is working well and tables were created when I performed syncdb. The problem I am encountering is when I am r...
Looking at the code of `django.utils.importlib.py` where the execption is raised you see that your settings file name is causing the problem: ``` if name.startswith('.'): if not package: raise TypeError("relative imports require the 'package' argument") ``` Don't use `.settings.py` as the name for your se...
extract last two fields from split
10,837,917
5
2012-05-31T16:54:04Z
10,837,941
12
2012-05-31T16:55:45Z
[ "python" ]
I want to extract last two field values from a variable of varying length. For example, consider the three values below: ``` fe80::e590:1001:7d11:1c7e ff02::1:ff1f:fb6 fe80::7cbe:e61:f5ab:e62 ff02::1:ff1f:fb6 ``` These three lines are of variable lengths. I want to extract only the last two field values if i split ...
If `s` is the string containing the IPv6 address, use ``` s.split(":")[-2:] ``` to get the last two components. The `split()` method will return a list of all components, and the `[-2:]` will slice this list to return only the last two elements.
extract last two fields from split
10,837,917
5
2012-05-31T16:54:04Z
10,838,083
7
2012-05-31T17:06:28Z
[ "python" ]
I want to extract last two field values from a variable of varying length. For example, consider the three values below: ``` fe80::e590:1001:7d11:1c7e ff02::1:ff1f:fb6 fe80::7cbe:e61:f5ab:e62 ff02::1:ff1f:fb6 ``` These three lines are of variable lengths. I want to extract only the last two field values if i split ...
You can use `str.rsplit()` to split from the right: ``` >>> ipaddress = 'fe80::e590:1001:7d11:1c7e' >>> ipaddress.rsplit(':', 2) # splits at most 2 times from the right ['fe80::e590:1001', '7d11', '1c7e'] ``` This avoids the unnecessary splitting of the first part of the address.
UnicodeDecodeError: 'utf8' codec can't decode byte
10,838,016
6
2012-05-31T17:01:15Z
10,839,898
7
2012-05-31T19:18:04Z
[ "python", "google-app-engine" ]
When I launch my app, I get this error UnicodeDecodeError: 'utf8' codec can't decode byte 0xe9 in position 2566: invalid continuation byte. I use UTF8 in my HTML file ``` <meta charset="utf-8" /> ``` and in my Python file ``` # -*- coding: utf-8 -*- self.response.headers['Content-Type'] = 'text/html; charset=UTF-8' ...
If you are using Notepad++ make sure the "encoding" (in the menu) of all your files is set to "UTF-8". I don't know for other editors but that might be the problem.
Python class--Super variable
10,838,596
6
2012-05-31T17:45:47Z
10,838,707
11
2012-05-31T17:54:03Z
[ "python" ]
The below piece of code is giving me a error for some reason, Can someone tell me what would be the problem.. Basically, I create 2 classes Point & Circle..THe circle is trying to inherit the Point class. ``` Code: class Point(): x = 0.0 y = 0.0 def __init__(self, x, y): self.x = x sel...
It looks like you already may have fixed the original error, which was caused by `super().__init__(x,y)` as the error message indicates, although your fix was slightly incorrect, instead of `super(Point, self)` from the `Circle` class you should use `super(Circle, self)`. Note that there is another place that calls `s...
Python class--Super variable
10,838,596
6
2012-05-31T17:45:47Z
10,838,759
7
2012-05-31T17:57:59Z
[ "python" ]
The below piece of code is giving me a error for some reason, Can someone tell me what would be the problem.. Basically, I create 2 classes Point & Circle..THe circle is trying to inherit the Point class. ``` Code: class Point(): x = 0.0 y = 0.0 def __init__(self, x, y): self.x = x sel...
`super(..)` takes only new-style classes. To fix it, extend Point class from `object`. Like this: ``` class Point(object): ``` Also the correct way of using super(..) is like: ``` super(Circle,self).__init__(x,y) ```
How to disable translations during unit tests in django?
10,839,408
7
2012-05-31T18:44:27Z
10,884,827
10
2012-06-04T16:37:20Z
[ "python", "django", "unit-testing" ]
I'm using [Django Internationalization](https://docs.djangoproject.com/en/1.3/topics/i18n/internationalization/) tools to translate some strings from my application. The code looks like this: ``` from django.utils.translation import ugettext as _ def my_view(request): output = _("Welcome to my site.") return H...
Calling `.get()` or `.post()` on the test client will run all the configured middlewares. This means it will also run `LocaleMiddleware`, which will call `translation.get_language_from_request()` followed by `translation.activate(language)`. What this means is that the currently active language is ignored and thrown a...
How to set "step" on axis X in my figure in matplotlib python 2.6.6?
10,839,719
11
2012-05-31T19:05:46Z
10,839,788
17
2012-05-31T19:10:26Z
[ "python", "matplotlib" ]
I have some code: ``` #!/usr/bin/env python import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt x = [1,2,3,4,5] y = [1.2,1.9,3.1,4.2,4.8] plt.plot(x,y) plt.xlabel('OX') plt.ylabel('OY') plt.savefig('figure1.png') plt.close() ``` And it gives me that figure: [my figure](http://i.stack.img...
``` plt.xticks([1, 2, 3, 4, 5]) ``` [xticks documentation.](http://matplotlib.sourceforge.net/api/pyplot_api.html?highlight=xticks#matplotlib.pyplot.xticks) ![Five x-ticks.](http://i.stack.imgur.com/7hCLf.png)
Python SL4A Development
10,839,879
8
2012-05-31T19:16:47Z
10,894,075
8
2012-06-05T08:37:37Z
[ "android", "python", "sl4a" ]
Ok - I'm feeling like a frustrated idiot. I want to state that upfront. I'm trying to get a Python/Android setup going so I can develop Python applications for Android. I've got both SL4A and the Python interpreter installed on my Android device and can write an application on the phone that runs. The issue is how ca...
# 1. Start Server ## On Device First, connect your device with USB. Then for remote debugging, you need to start a server on your device: ``` SL4A -> Interpreters -> Menu -> Start Server ``` The *private* one is preferable. Then you can look up the port for the server in the Android notification area (with SL4A r5...
Django post_save preventing recursion without overriding model save()
10,840,030
15
2012-05-31T19:27:44Z
10,840,234
13
2012-05-31T19:43:25Z
[ "python", "django", "django-signals" ]
There are many Stack Overflow posts about recursion using the `post_save` signal, to which the comments and answers are overwhelmingly: "why not override save()" or a save that is only fired upon `created == True`. Well I believe there's a good case for not using `save()` - for example, I am adding a temporary applica...
How about disconnecting then reconnecting the signal within your `post_save` function: ``` def my_post_save_handler(sender, instance, **kwargs): post_save.disconnect(my_post_save_handler, sender=sender) instance.do_stuff() instance.save() post_save.connect(my_post_save_handler, sender=sender) post_save...
Django post_save preventing recursion without overriding model save()
10,840,030
15
2012-05-31T19:27:44Z
10,840,333
51
2012-05-31T19:51:21Z
[ "python", "django", "django-signals" ]
There are many Stack Overflow posts about recursion using the `post_save` signal, to which the comments and answers are overwhelmingly: "why not override save()" or a save that is only fired upon `created == True`. Well I believe there's a good case for not using `save()` - for example, I am adding a temporary applica...
you can use update instead of save in the signal handler ``` quersyset.filter(pk=instance.pk).update(....) ```
Django post_save preventing recursion without overriding model save()
10,840,030
15
2012-05-31T19:27:44Z
19,706,581
13
2013-10-31T12:28:37Z
[ "python", "django", "django-signals" ]
There are many Stack Overflow posts about recursion using the `post_save` signal, to which the comments and answers are overwhelmingly: "why not override save()" or a save that is only fired upon `created == True`. Well I believe there's a good case for not using `save()` - for example, I am adding a temporary applica...
I think creating a `save_without_signals()` method on the model is more explicit: ``` class MyModel() def __init__(): # Call super here. self._disable_signals = False def save_without_signals(self): """ This allows for updating the model from code running inside post_save() ...
Django post_save preventing recursion without overriding model save()
10,840,030
15
2012-05-31T19:27:44Z
19,936,271
27
2013-11-12T17:47:05Z
[ "python", "django", "django-signals" ]
There are many Stack Overflow posts about recursion using the `post_save` signal, to which the comments and answers are overwhelmingly: "why not override save()" or a save that is only fired upon `created == True`. Well I believe there's a good case for not using `save()` - for example, I am adding a temporary applica...
Don't disconnect signals. If any new model of the same type is generated while the signal is disconnected the handler function won't be fired. Signals are global across Django and several requests can be running concurrently, making some fail while others run their post\_save handler.
Django post_save preventing recursion without overriding model save()
10,840,030
15
2012-05-31T19:27:44Z
28,369,908
11
2015-02-06T16:07:09Z
[ "python", "django", "django-signals" ]
There are many Stack Overflow posts about recursion using the `post_save` signal, to which the comments and answers are overwhelmingly: "why not override save()" or a save that is only fired upon `created == True`. Well I believe there's a good case for not using `save()` - for example, I am adding a temporary applica...
What you think about this solution? ``` @receiver(post_save, sender=Article) def generate_thumbnails(sender, instance=None, created=False, **kwargs): if not instance: return if hasattr(instance, '_dirty'): return do_something() try: instance._dirty = True instance.sa...
String literal with triple quotes in function definitions
10,840,357
19
2012-05-31T19:52:52Z
10,840,407
7
2012-05-31T19:56:11Z
[ "python", "string", "literals" ]
I am following the Python tutorial and at some point they talk about how the 1st statement of a function can be a String Literal. As far as the example goes, this String Literal seems to be done with three ", giving in the [example](http://docs.python.org/release/2.7.3/tutorial/controlflow.html#defining-functions) `"""...
A string literal is simply a string given literally in the source code. Whether it is a docstring or another string does not matter. See the [Python language documentation section on string literals](http://docs.python.org/reference/lexical_analysis.html#string-literals) for all the details, but you probably don't need...
String literal with triple quotes in function definitions
10,840,357
19
2012-05-31T19:52:52Z
10,840,410
22
2012-05-31T19:56:24Z
[ "python", "string", "literals" ]
I am following the Python tutorial and at some point they talk about how the 1st statement of a function can be a String Literal. As far as the example goes, this String Literal seems to be done with three ", giving in the [example](http://docs.python.org/release/2.7.3/tutorial/controlflow.html#defining-functions) `"""...
What you're talking about (I think) are called [docstrings](http://docs.python.org/tutorial/controlflow.html#documentation-strings) (Thanks Boud for the link). ``` def foo(): """This function does absolutely nothing""" pass ``` Now, if you type `help(foo)` from the interpreter, you'll get to see the string th...
Most pythonic way to delete a file which may not exist
10,840,533
169
2012-05-31T20:06:14Z
10,840,573
32
2012-05-31T20:09:44Z
[ "python" ]
I want to delete the file `filename` if it exists. Is it proper to say ``` if os.path.exists(filename): os.remove(filename) ``` Is there a better way? A one-line way?
[`os.path.exists`](https://docs.python.org/2/library/os.path.html#os.path.exists) returns `True` for folders as well as files. Consider using [`os.path.isfile`](https://docs.python.org/2/library/os.path.html#os.path.isfile) to check for whether the file exists instead.
Most pythonic way to delete a file which may not exist
10,840,533
169
2012-05-31T20:06:14Z
10,840,586
253
2012-05-31T20:10:42Z
[ "python" ]
I want to delete the file `filename` if it exists. Is it proper to say ``` if os.path.exists(filename): os.remove(filename) ``` Is there a better way? A one-line way?
A more pythonic way would be: ``` try: os.remove(filename) except OSError: pass ``` Although this takes even more lines and looks very ugly, it avoids the unnecessary call to `os.path.exists()` and follows the python convention of overusing exceptions. It may be worthwhile to write a function to do this for ...
Most pythonic way to delete a file which may not exist
10,840,533
169
2012-05-31T20:06:14Z
21,103,794
17
2014-01-14T00:02:39Z
[ "python" ]
I want to delete the file `filename` if it exists. Is it proper to say ``` if os.path.exists(filename): os.remove(filename) ``` Is there a better way? A one-line way?
In the spirit of Andy Jones' answer, how about an authentic ternary operation: ``` os.remove(fn) if os.path.exists(fn) else None ```
Most pythonic way to delete a file which may not exist
10,840,533
169
2012-05-31T20:06:14Z
27,045,091
31
2014-11-20T16:49:55Z
[ "python" ]
I want to delete the file `filename` if it exists. Is it proper to say ``` if os.path.exists(filename): os.remove(filename) ``` Is there a better way? A one-line way?
I prefer to suppress an exception rather than checking for the file's existence, to avoid a [TOCTTOU](http://en.wikipedia.org/wiki/TOCTTOU) bug. Matt's answer is a good example of this, but we can simplify it slightly under Python 3, using [`contextlib.suppress()`](https://docs.python.org/3/library/contextlib.html#cont...
Regex, find first - Python
10,840,926
4
2012-05-31T20:38:07Z
10,840,944
7
2012-05-31T20:39:56Z
[ "python", "regex", "string" ]
``` i="<wx._controls.Button; proxy of <Swig Object of type 'wxButton *' at 0x2887828> >]], [[[41, 183], 'Button', <wx._controls.Button; proxy of <Swig Object of type 'wxButton *' at 0x28879d0> >]]]" m = re.findall("<wx.(.*)> >", i) ``` will give me ``` ["<wx._controls.Button; proxy of <Swig Object of type 'wxButton ...
the `*` operator is greedy by default. You can change this by adding a `?` after it. Also remember to quote the literal dot. I also made the group non-matching, otherwise you wouldn't get the desired output (this seems to be a problem with your original code as well): ``` re.findall(r"<wx\.(?:.*?)> >", i) ``` Anothe...
Pandas: List of Column names in a pivot table
10,841,538
4
2012-05-31T21:28:05Z
10,872,241
7
2012-06-03T17:02:25Z
[ "python", "pivot", "pandas" ]
I got stuck trying to get the resulting names of a pivot table. The table printed using to\_string() looks as below. I want to create a list with the names of the columns('a\_Zero', 'b\_Inst') I've been looking for a couple of days but I am still stuck trying to do that. I am using pandas 0.7 ``` ...
You can use pivot.columns.tolist()
Pickle with custom classes
10,842,553
4
2012-05-31T23:21:08Z
10,842,615
7
2012-05-31T23:29:10Z
[ "python", "pickle" ]
Suppose I have a simple python class definition in a file myClass.py ``` class Test: A = [] ``` And I also have two test scripts. The first script creates an object of type Test, populates the array A, and pickles the result to a file. It immediately unpickles it from the file and the array is still populated. Th...
It is because you are setting `Test.A` as a class attribute instead of an instance attribute. Really what is happening is that with the test1.py, the object being read back from the pickle file is the same as test2.py, but its using the class in memory where you had originally assigned `x.A`. When your data is being u...
shorthand way to create dictionary key if it does not exist
10,843,466
5
2012-06-01T01:52:16Z
10,843,487
9
2012-06-01T01:55:32Z
[ "python" ]
I have a dictionary of zoo animals. I want to put it into the dictionary in a nested dictionary but get a KeyError because that particular species has not been added to the dictionary. ``` def add_to_world(self, species, name, zone = 'retreat'): self.object_attr[species][name] = {'zone' : zone} ``` Is there a sho...
Autovivification of dictionary values can be performed by [`collections.defaultdict`](http://docs.python.org/dev/library/collections.html#collections.defaultdict).
shorthand way to create dictionary key if it does not exist
10,843,466
5
2012-06-01T01:52:16Z
10,843,494
12
2012-06-01T01:57:22Z
[ "python" ]
I have a dictionary of zoo animals. I want to put it into the dictionary in a nested dictionary but get a KeyError because that particular species has not been added to the dictionary. ``` def add_to_world(self, species, name, zone = 'retreat'): self.object_attr[species][name] = {'zone' : zone} ``` Is there a sho...
``` def add_to_world(self, species, name, zone = 'retreat'): self.object_attr.setdefault(species, {})[name] = {'zone' : zone} ```
shorthand way to create dictionary key if it does not exist
10,843,466
5
2012-06-01T01:52:16Z
10,843,511
9
2012-06-01T01:59:40Z
[ "python" ]
I have a dictionary of zoo animals. I want to put it into the dictionary in a nested dictionary but get a KeyError because that particular species has not been added to the dictionary. ``` def add_to_world(self, species, name, zone = 'retreat'): self.object_attr[species][name] = {'zone' : zone} ``` Is there a sho...
Here's an example of using defaultdict with a dictionary as a value. ``` >>> from collections import defaultdict >>> d = defaultdict(dict) >>> d["species"]["name"] = {"zone": "1"} >>> d defaultdict(<type 'dict'>, {'species': {'name': {'zone': '1'}}}) >>> ``` If you want further nesting you'll need to make a function ...
Items in JSON object are out of order using "json.dumps"?
10,844,064
51
2012-06-01T03:34:45Z
10,844,608
14
2012-06-01T04:55:41Z
[ "python", "json" ]
I'm using json.dumps to convert into json like ``` countries.append({"id":row.id,"name":row.name,"timezone":row.timezone}) print json.dumps(countries) ``` The result i have is: ``` [{"timezone": 4, "id": 1, "name": "Mauritius"}, {"timezone": 2, "id": 2, "name": "France"}, {"timezone": 1, "id": 3, "name": "England"},...
As others have mentioned the underlying dict is unordered. However there are OrderedDict objects in python. ( They're built in in recent pythons, or you can use this: <http://code.activestate.com/recipes/576693/> ). I believe that newer pythons json implementations correctly handle the built in OrderedDicts, but I'm n...
Items in JSON object are out of order using "json.dumps"?
10,844,064
51
2012-06-01T03:34:45Z
23,820,416
61
2014-05-23T03:14:57Z
[ "python", "json" ]
I'm using json.dumps to convert into json like ``` countries.append({"id":row.id,"name":row.name,"timezone":row.timezone}) print json.dumps(countries) ``` The result i have is: ``` [{"timezone": 4, "id": 1, "name": "Mauritius"}, {"timezone": 2, "id": 2, "name": "France"}, {"timezone": 1, "id": 3, "name": "England"},...
Both Python `dict` and JSON object are unordered collections. You could pass `sort_keys` parameter, to sort the keys: ``` >>> import json >>> json.dumps({'a': 1, 'b': 2}) '{"b": 2, "a": 1}' >>> json.dumps({'a': 1, 'b': 2}, sort_keys=True) '{"a": 1, "b": 2}' ``` If you need a particular order; you could [use `collecti...
Python: What is the difference between Call-by-Value and Call-by-Object?
10,844,088
4
2012-06-01T03:38:36Z
10,844,102
7
2012-06-01T03:41:27Z
[ "python", "arguments", "parameter-passing", "pass-by-value" ]
Many people say that in Python arguments to functions are passed using a call-by-value model. As I understand it, it is not actually a call-by-value language, but a call-by-object or call-by-sharing model. What are the differences between a call-by-value model and a call-by-object model? What is an example in Python t...
Variables in Python aren't values, they're object references. When you call a Python function the arguments are copies of the references to the original object. I don't know how this relates to the terminology you posed in the question. For example consider the following Python code: ``` def foo(bar, baz): bar = ...
Appending values to a key if key already exists (python/jython)
10,844,282
2
2012-06-01T04:08:38Z
10,844,313
9
2012-06-01T04:13:16Z
[ "python", "dictionary", "jython", "key" ]
I have a list that I need to make into a dictionary. The list has duplicate (soon to be) keys which have different values. How do I find these keys and append the new values to it? ``` list=[q:1,w:2,q:7] dictionary= q:1,7 w:2 ``` Thanks in advance
Make the values in your dictionary lists, so that you have: ``` dictionary = {'q': [1, 7], 'w': [2] } ``` etc. ie, your one-item values are one-item lists. This means when you have another `'q'`, you can do this: ``` dictionary['q'].append(5) ``` Except that `dictionary['q']` will be a `KeyError` the ...
DataFrame.apply in python pandas alters both original and duplicate DataFrames
10,844,493
2
2012-06-01T04:40:16Z
10,844,760
9
2012-06-01T05:13:47Z
[ "python", "pandas" ]
I'm having a bit of trouble altering a duplicated pandas DataFrame and not having the edits apply to both the duplicate *and* the original DataFrame. Here's an example. Say I create an arbitrary DataFrame from a list of dictionaries: ``` In [67]: d = [{'a':3, 'b':5}, {'a':1, 'b':1}] In [68]: d = DataFrame(d) In [69...
This is not a pandas-specific issue. In Python, assignment never copies anything: ``` >>> a = [1,2,3] >>> b = a >>> b[0] = 'WHOA!' >>> a ['WHOA!', 2, 3] ``` If you want a new DataFrame, make a copy with `e = d.copy()`. Edit: I should clarify that assignment *to a bare name* never copies anything. Assignment to an it...
Python: Counting frequency of pairs of elements in a list of lists
10,844,556
5
2012-06-01T04:50:48Z
10,844,775
7
2012-06-01T05:16:01Z
[ "python", "csv" ]
Actually, I have a dataset about a "meeting". For example, A,B,C have a meeting, then the list would be [A,B,C]. Like this, each list would contain a list of members who participated in the meeting. Therefore: line1= (A,B,C) line2= (A,C,D,E) line3 = (D,F,G) ... I just would like to count the number how many times ...
Rather than manually summing frequencies, use [`collections.counter`](http://docs.python.org/library/collections.html#collections.counter) along with [`itertools`](http://docs.python.org/library/itertools.html): ``` from collections import Counter from itertools import chain, combinations meets = Counter(chain.from_i...
How do I pass integer items of a list to a function as string arguments in Python?
10,845,038
2
2012-06-01T05:46:34Z
10,845,060
11
2012-06-01T05:49:05Z
[ "python", "string", "list", "arguments" ]
I have a Python list consisting of integers: ``` a = [1, 2, 3] ``` I want to pass the items of this list as arguments to a function, and they must be strings: ``` myfunc("1", "2", "3") ``` How can I do it?
So... we use the `*` operator to use a sequence as multiple arguments for a function call; and we want to convert each argument to a string. The conversion is most obviously and simply done by just passing the value to the builtin `str`; we can then just `map` that conversion function onto the list. These are all eleme...
Django template comparing string
10,845,738
9
2012-06-01T06:56:14Z
16,995,256
17
2013-06-08T01:56:32Z
[ "python", "django", "django-templates" ]
I'm new with django. I'm stuck with the problem of comparing string in the template. I have use ifnotequal tag to compare string. But it is not working. I have try to output the variable: ``` {{ request.user.username }} {{ article.creator }} ``` Here I compare: ``` {% ifnotequal request.user.username article.crea...
Try this: ``` {% ifnotequal article.creator|stringformat:"s" request.user.username %} ```
Django template comparing string
10,845,738
9
2012-06-01T06:56:14Z
23,104,289
8
2014-04-16T08:45:10Z
[ "python", "django", "django-templates" ]
I'm new with django. I'm stuck with the problem of comparing string in the template. I have use ifnotequal tag to compare string. But it is not working. I have try to output the variable: ``` {{ request.user.username }} {{ article.creator }} ``` Here I compare: ``` {% ifnotequal request.user.username article.crea...
For string compare in template use ``` {% if name == "someone" %} ............ ............ {% endif %} ``` and for not equal ``` {% if name != "someone" %} ............ ............ {% endif %} ```
Use "byte-like object" from urlopen.read with json?
10,846,112
24
2012-06-01T07:24:15Z
13,845,329
29
2012-12-12T17:29:35Z
[ "python", "python-3.x", "urlopen" ]
Just trying to test out very simple Python json commands, but having some trouble. ``` urlopen('http://www.similarsitesearch.com/api/similar/ebay.com').read() ``` should output ``` '{"num":20,"status":"ok","r0":"http:\\/\\/www.propertyroom.com\\/","r1":"http:\\/\\/www.ubid.com\\/","r2":"http:\\/\\/www.bidcactus.com\...
The content from read() is of type *bytes* so you need to convert it to a string before trying to decode it into a json object. To convert *bytes* to a string, change your code to: `urlopen('http://similarsitesearch.com/api/similar/ebay.com').read().decode("utf-8")`
ordering shuffled points that can be joined to form a polygon (in python)
10,846,431
6
2012-06-01T07:49:31Z
10,847,911
12
2012-06-01T09:39:57Z
[ "python", "python-2.7", "matplotlib", "geometry" ]
I have a collection of points that join to form a polygon in 2D cartesian space. It is in the form of a python list of tuples ``` [(x1, y1), (x2, y2), ... , (xn, yn)] ``` the problem is the join them and form a polygon in a graph. (I'm using matplotlib.path) I made a function to do this. It works as follows: it goe...
This sorts your points according to polar coordinates: ``` import math import matplotlib.patches as patches import pylab pp=[(-0.500000050000005, -0.5), (-0.499999950000005, 0.5), (-0.500000100000005, -1.0), (-0.49999990000000505, 1.0), (0.500000050000005, -0.5), (-1.0000000250000025, -0.5), (1.0000000250000025, -0.5)...
Subsampling/averaging over a numpy array
10,847,660
5
2012-06-01T09:23:16Z
10,847,914
12
2012-06-01T09:40:04Z
[ "python", "arrays", "numpy", "subsampling" ]
I have a numpy array with floats. What I would like to have (if it is not already existing) is a function that gives me a new array of the average of every x points in the given array, like sub sampling (and opposite of interpolation(?)). E.g. sub\_sample(numpy.array([1, 2, 3, 4, 5, 6]), 2) gives [1.5, 3.5, 5.5] E.g...
Using NumPy routines you could try something like ``` import numpy x = numpy.array([1, 2, 3, 4, 5, 6]) numpy.mean(x.reshape(-1, 2), 1) # Prints array([ 1.5, 3.5, 5.5]) ``` and just replace the `2` in the `reshape` call with the number of items you want to average over. **Edit**: This assumes that `n` divides int...
Can I do a "string contains X" with a percentage accuracy in python?
10,849,141
12
2012-06-01T11:09:33Z
10,849,452
20
2012-06-01T11:31:59Z
[ "python", "string", "comparison", "ocr" ]
I need to do some OCR on a large chunk of text and check if it contains a certain string but due to the inaccuracy of the OCR I need it to check if it contains something like a ~85% match for the string. For example I may OCR a chunk of text to make sure it doesn't contain `no information available` but the OCR might ...
As posted by `gauden`, `SequenceMatcher` in `difflib` is an easy way to go. Using `ratio()`, returns a value between `0` and `1` corresponding to the similarity between the two strings, from the docs: > Where T is the total number of elements in both sequences, and M is > the number of matches, this is 2.0\*M / T. Not...
Python: Write to next empty line
10,851,175
4
2012-06-01T13:24:26Z
10,851,207
9
2012-06-01T13:27:11Z
[ "python" ]
I'm trying to write the output of something that is being done over three big iterations and each time I'm opening and closing the outfile. Counters get reset and things like this after the iterations and I'm a massive newb and would struggle to work around this with the shoddy code I've written. So even if it's slower...
Open with "a" instead of "w" will write at the end of the file. That's the way to not overwrite.
Splitting a string by list of indices
10,851,445
6
2012-06-01T13:43:22Z
10,851,479
10
2012-06-01T13:45:36Z
[ "python", "split" ]
I want to split a string by a list of indices, where the split segments begin with one indice and end before the next one. **Example:** ``` s = 'long string that I want to split up' indices = [0,5,12,17] parts = [s[index:] for index in indices] for part in parts: print part ``` **This will return:** > long stri...
``` s = 'long string that I want to split up' indices = [0,5,12,17] parts = [s[i:j] for i,j in zip(indices, indices[1:]+[None])] ``` returns ``` ['long ', 'string ', 'that ', 'I want to split up'] ``` which you can print using: ``` print '\n'.join(parts) ``` Another possibility (without copying `indices`) would be...
Python - Batch convert GPS positions to Lat Lon decimals
10,852,955
7
2012-06-01T15:16:15Z
10,854,324
16
2012-06-01T16:46:22Z
[ "python", "gps", "coordinates", "coordinate-transformation" ]
Hi I have a legacy db with some positional data. The fields are just text fields with strings like this `0°25'30"S, 91°7'W`. Is there some way I can convert these to two floating point numbers for `Decimal Latitude` and `Decimal Longitude`? EDIT: So an example would be: `0°25'30"S, 91°7'W` -> `0.425`, `91.116667`...
This approach can deal with seconds and minutes being absent, and I think handles the compass directions correctly: ``` # -*- coding: latin-1 -*- def conversion(old): direction = {'N':-1, 'S':1, 'E': -1, 'W':1} new = old.replace(u'°',' ').replace('\'',' ').replace('"',' ') new = new.split() new_dir =...
Creating multiple variables / strings within loops in Python
10,853,016
2
2012-06-01T15:19:45Z
10,853,118
7
2012-06-01T15:25:59Z
[ "python", "string", "loops" ]
I'm trying to create a program that, well, looks something like this: ``` self.b1 = Checkbutton(self, variable=self.b1v, text="1.") self.b1.grid() self.b2v = IntVar() self.b2 = Checkbutton(self, variable=self.b2v, text="2.") self.b2.grid() self.b3v = IntVar()...
Something like this? ``` num_buttons = 3 self.b_vars = [IntVar() for i in range(num_buttons)] self.b = [CheckButton(self, variable=self.b_vars[i], text="%d." % (i + 1)) for i in range(num_buttons)] for button in self.b: button.grid() ```
unit testing in tornado
10,853,288
12
2012-06-01T15:36:41Z
11,140,186
12
2012-06-21T14:16:59Z
[ "python", "unit-testing", "tornado" ]
I'm building a simple web application in tornado.web using mongodb as the backend. 90% of the server-side codebase lives in a set of RequestHandlers, and 90% of the data objects are json. As a result, the basic use case for testing handlers is: ``` "Given Request Y and DB in state X, verify that handler method Z retu...
I would typically mock out the inputs and just test the output. This is a contrived example using this mocking library - <http://www.voidspace.org.uk/python/mock/>. You would have to mock out the correct mongodb query function. I'm not sure what you are using. ``` from mock import Mock, patch import json @patch('my_...
Python: Decimals with trigonometric functions
10,854,229
4
2012-06-01T16:39:04Z
10,854,279
13
2012-06-01T16:42:40Z
[ "python", "math", "floating-point", "decimal", "trigonometry" ]
I'm having a little problem, take a look: ``` >>> import math >>> math.sin(math.pi) 1.2246467991473532e-16 ``` This is not what I learnt in my Calculus class (It was 0, actually) So, now, my question: I need to perform some heavy trigonometric calculus with Python. What library can I use to get correct values? Can...
`1.2246467991473532e-16` is close to 0 -- there are 16 zeroes between the decimal point and the first significant digit -- much as `3.1415926535897931` (the value of `math.pi`) is close to pi. The answer is correct to sixteen decimal places! So if you want `sin(pi)` to equal 0, simply round it to a reasonable number o...
Python: Decimals with trigonometric functions
10,854,229
4
2012-06-01T16:39:04Z
10,854,308
9
2012-06-01T16:45:17Z
[ "python", "math", "floating-point", "decimal", "trigonometry" ]
I'm having a little problem, take a look: ``` >>> import math >>> math.sin(math.pi) 1.2246467991473532e-16 ``` This is not what I learnt in my Calculus class (It was 0, actually) So, now, my question: I need to perform some heavy trigonometric calculus with Python. What library can I use to get correct values? Can...
Pi is an [irrational number](http://en.wikipedia.org/wiki/Irrational_number) so it can't be represented exactly using a finite number of bits. However, you can use some library for symbolic computation such as [sympy](http://code.google.com/p/sympy/). ``` >>> sympy.sin(sympy.pi) 0 ``` Regarding the second part of you...
How do I find the path for a failed python import?
10,856,632
6
2012-06-01T20:00:56Z
10,856,716
14
2012-06-01T20:09:17Z
[ "python", "exception-handling", "module" ]
Let's say I have a module which fails to import (there is an exception when importing it). eg. `test.py` with the following contents: ``` print 1/0 ``` *[Obviously, this isn't my actual file, but it will stand in as a good proxy]* Now, at the python prompt: ``` >>> import test Traceback (most recent call last): ...
Use the [imp](http://docs.python.org/library/imp.html) module. It has a function, [`imp.find_module()`](http://docs.python.org/library/imp.html#imp.find_module), which receives as a parameter the name of a module and returns a tuple, whose second item is the path to the module: ``` >>> import imp >>> imp.find_module('...
Python name space issues with ipython parallel
10,857,250
10
2012-06-01T20:59:29Z
10,859,394
15
2012-06-02T02:40:16Z
[ "python", "python-2.7", "parallel-processing", "ipython" ]
I'm starting to experiment with the IPython parallel tools and have an issue. I start up my python engines with: ``` ipcluster start -n 3 ``` Then the following code runs fine: ``` from IPython.parallel import Client def dop(x): rc = Client() dview = rc[:] dview.block=True dview.execute('a = 5') ...
Quick answer: decorate your function with `@interactive` from `IPython.parallel.util`[1] if you want it to have access to the engine's global namespace: ``` from IPython.parallel.util import interactive f = interactive(lambda x: a+b+x) ack = dview.apply(f, x) ``` The actual explanation: the IPython user namespace is...
Python assigning multiple variables to same list value?
10,857,654
11
2012-06-01T21:34:56Z
10,857,677
51
2012-06-01T21:37:41Z
[ "python", "list" ]
I'm writing a function to calculate calendar dates. While cutting down on lines, I've found that I am unable to *assign multiple variables to the same range*. ``` Jan, Mar, May, Jul, Aug, Oct, Dec = range(1,32) ``` Would there be an efficient way to assign these values and why does python give a ValueError?
Use ``` Jan = Mar = May = ... = range(1, 32) ```
reverse keys (consisting of lists) and values in Python dictionary
10,857,907
2
2012-06-01T22:03:13Z
10,857,959
7
2012-06-01T22:11:07Z
[ "python", "dictionary", "list-comprehension", "finite-state-machine" ]
I have been trying to figure this out from other posts here, but couldn't. I have a Python dictionary ``` old_dict = { (1,'a') : [2], (2,'b') : [3,4], (3,'x') : [5], (4,'y') : [5], (5,'b') : [3,4], (5,'c') : [6], } ``` I need to reverse this so that as a r...
This is complex enough that I wouldn't bother with list comprehensions. Also, I'm assuming you aren't looking for the value lists to be in any strict order. ``` new_dict = {} for k, vals in old_dict.items(): k_num, k_char = k for num in vals: new_dict.setdefault((num, k_char), []).append(k_num) ``` Or...
Remove NULL columns in a dataframe Pandas?
10,857,924
28
2012-06-01T22:05:44Z
10,859,883
48
2012-06-02T04:52:48Z
[ "python", "pandas" ]
I have a dataFrame in pandas and several of the columns have all null values. Is there a built in function which will let me remove those columns? Thank you!
Yes, `dropna`. See <http://pandas.pydata.org/pandas-docs/stable/missing_data.html> and the `DataFrame.dropna` docstring: ``` Definition: DataFrame.dropna(self, axis=0, how='any', thresh=None, subset=None) Docstring: Return object with labels on given axis omitted where alternately any or all of the data are missing P...
Find object by its member inside a List in python
10,858,575
11
2012-06-01T23:36:09Z
10,858,586
24
2012-06-01T23:39:21Z
[ "python", "list", "search", "find" ]
lets assume the following simple Object: ``` class Mock: def __init__(self, name, age): self.name = name self.age = age ``` then I have a list with some Objects like this: ``` myList = [Mock("Dan", 34), Mock("Jack", 30), Mock("Oli", 23)...] ``` Is there some built-in feature where I can get all ...
You could try a [filter()](http://docs.python.org/library/functions.html#filter): ``` filter(lambda x: x.age == 30, myList) ``` This would return a list with only those objects satisfying the lambda expression.
Find object by its member inside a List in python
10,858,575
11
2012-06-01T23:36:09Z
10,858,589
14
2012-06-01T23:40:30Z
[ "python", "list", "search", "find" ]
lets assume the following simple Object: ``` class Mock: def __init__(self, name, age): self.name = name self.age = age ``` then I have a list with some Objects like this: ``` myList = [Mock("Dan", 34), Mock("Jack", 30), Mock("Oli", 23)...] ``` Is there some built-in feature where I can get all ...
List comprehensions can pick these up: ``` new_list = [x for x in myList if x.age == 30] ```