title
stringlengths
12
150
question_id
int64
469
40.1M
question_score
int64
2
5.52k
question_date
stringdate
2008-08-02 15:11:16
2016-10-18 06:16:31
answer_id
int64
536
40.1M
answer_score
int64
7
8.38k
answer_date
stringdate
2008-08-02 18:49:07
2016-10-18 06:19:33
tags
listlengths
1
5
question_body_md
stringlengths
15
30.2k
answer_body_md
stringlengths
11
27.8k
How do I get python code to loop every x mins between the times y and z?
16,879,170
2
2013-06-02T02:18:48Z
16,879,198
8
2013-06-02T02:24:16Z
[ "python", "loops", "time", "delay" ]
This might be incredibly easy but how do I get python code to loop every x mins between the times y and z? For example if I wanted my script to run between midnight (00:00) through to 10 pm (22:00) looping every 5 minutes.
Try the *[sched](http://docs.python.org/2.7/library/sched.html#module-sched)* module in the standard library. Here's an example of calling a function once per second, starting five seconds in the future, and ending ten seconds in the future: ``` from sched import scheduler from time import time, sleep s = scheduler(t...
Django 1.5 + User model relationship
16,880,461
3
2013-06-02T06:47:20Z
16,880,533
11
2013-06-02T07:02:02Z
[ "python", "django", "django-models" ]
Django 1.5+ allows us to add custom fields to a User. I want to use this fact, but I don't necessarily know what is good practice. Here is a situation I am confused on how to handle the models. Given the option to add fields to `User`, if a project only has one type of `User`, lets say a `Student` model, can I simply ...
If you only have one type of user and are using Django 1.5+, I would recommend taking advantage of the new AbstractUser. [Extending Django's default user](https://docs.djangoproject.com/en/dev/topics/auth/customizing/#extending-django-s-default-user) As an example where you want to add date of birth and favorite color...
Creating list of individual list items multiplied n times
16,881,092
11
2013-06-02T08:32:04Z
16,881,101
10
2013-06-02T08:33:25Z
[ "python", "arrays", "list", "loops" ]
I'm fairly new to Python, and think this should be a fairly common problem, but can't find a solution. I've already looked at [this page](http://stackoverflow.com/questions/3459098/create-list-of-single-item-repeated-n-times-in-python) and found it helpful for one item, but I'm struggling to extend the example to multi...
You can use `zip` and a list comprehension here: ``` >>> a = ['x','y','z'] >>> b = [1,2,3] >>> [[x]*y for x,y in zip(a,b)] [['x'], ['y', 'y'], ['z', 'z', 'z']] ``` or: ``` >>> [[x for _ in xrange(y)] for x,y in zip(a,b)] [['x'], ['y', 'y'], ['z', 'z', 'z']] ``` `zip` will create the whole list in memory first, to g...
how do I get the subtrees of dendrogram made by scipy.cluster.hierarchy
16,883,412
10
2013-06-02T13:55:25Z
16,897,322
14
2013-06-03T12:58:52Z
[ "python", "python-2.7", "numpy", "scipy", "hierarchical-clustering" ]
I had a confusion regarding this module (scipy.cluster.hierarchy) ... and still have some ! For example we have the following dendrogram: ![hierarchical clustering](http://i.stack.imgur.com/3ieb4.png) My question is how can I extract the coloured subtrees (each one represent a cluster) in a nice format, say SIF form...
Answering the part of your question regarding tree manipulation... As explained in [aother answer](http://stackoverflow.com/q/11917779/832621), you can read the coordinates of the branches reading `icoord` and `dcoord` from the tree object. For each branch the coordinated are given from the left to the right. If you ...
Why does a class get "called" when not initiated? - Python
16,885,737
5
2013-06-02T18:09:36Z
16,885,769
7
2013-06-02T18:12:30Z
[ "python", "python-2.7" ]
For example, in the following code: ``` class test: print "Hi" ``` Python would automatically print 'hi'. Sorry if this is an obvious question, but I can't find out why Python would do that unless a 'test' object was initiated. \* I just started programming in general a few months ago and Python is my first langu...
You are building a class; the body of a class is executed as a function to build the definition. The local namespace of that 'function' forms the set of attributes that make up the class. See the [`class` statement](http://docs.python.org/2/reference/compound_stmts.html#class-definitions) documentation. Methods *in* t...
Python linspace limits from two arrays
16,887,148
2
2013-06-02T20:46:50Z
16,887,425
7
2013-06-02T21:18:43Z
[ "python", "arrays", "numpy" ]
I have two arrays: ``` a=np.array((1,2,3,4,5)) b=np.array((2,3,4,5,6)) ``` What I want is to use the values of a and b for the limits of linspace e.g. ``` c=np.linspace(a,b,11) ``` I get an error when I use this code. The answer should be for the first element of the array: ``` c=np.linspace(a,b,11) print c c=[1 1...
If you want to avoid explicit Python loops, you can do the following: ``` >>> a = np.array([1, 2, 3, 4, 5]).reshape(-1, 1) >>> b = np.array([2, 3, 4, 5, 6]).reshape(-1, 1) >>> c = np.linspace(0, 1, 11) >>> a + (b - a) * c array([[ 1. , 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2. ], [ 2. , 2.1, 2...
Suppress unicode prefix on strings when using pprint
16,888,409
3
2013-06-02T23:51:47Z
16,888,673
8
2013-06-03T00:38:45Z
[ "python", "pprint" ]
Is there any clean way to supress the unicode character prefix when printing an object using the pprint module? ``` >>> import pprint >>> pprint.pprint({u'foo': u'bar', u'baz': [u'apple', u'orange', u'pear', u'guava', u'banana'], u'hello': u'world'}) {u'baz': [u'apple', u'orange', u'pear', u'guava', u'banana'], u'foo...
It could be done by overriding the format method of the PrettyPrinter object, and casting any unicode object to string: ``` import pprint def my_safe_repr(object, context, maxlevels, level): typ = pprint._type(object) if typ is unicode: object = str(object) return pprint._safe_repr(object, context...
How to read a .xlsx file using the pandas Library in iPython?
16,888,888
25
2013-06-03T01:20:08Z
16,896,091
35
2013-06-03T11:52:16Z
[ "python", "pandas", "ipython", "ipython-notebook", "dataframe" ]
I want to read a .xlsx file using the Pandas Library of python and port the data to a postgreSQL table. All I could do up until now is: ``` import pandas as pd data = pd.ExcelFile("*File Name*") ``` Now I know that the step got executed successfully, but I want to know how i can parse the excel file that has been re...
I usually create a dictionary containing a `DataFrame` for every sheet: ``` xl_file = pd.ExcelFile(file_name) dfs = {sheet_name: xl_file.parse(sheet_name) for sheet_name in xl_file.sheet_names} ```
histogram in pylab from a dictionary
16,892,072
7
2013-06-03T07:41:07Z
16,893,056
15
2013-06-03T08:51:38Z
[ "python", "matplotlib" ]
I have been reading up about this. And I have been unable to find how the data for a histogram is mapped. The way I understand it: ``` A histogram has a name and a value for each bin. ``` This seems to be a pretty simple and intuitive way to look at it. I searched around and found this ques: [python: creating histog...
I have tried this and get a similiar histogram: ``` import pylab as pl import numpy as np d = {'CLOVER':4,'SPADE':6,'DIAMOND':7,'HEART':2} X = np.arange(len(d)) pl.bar(X, d.values(), align='center', width=0.5) pl.xticks(X, d.keys()) ymax = max(d.values()) + 1 pl.ylim(0, ymax) pl.show() ``` It is not the same but sim...
Should I use brew or pip for installing matplotlib?
16,895,282
4
2013-06-03T11:06:08Z
16,896,912
9
2013-06-03T12:38:29Z
[ "python", "osx", "homebrew" ]
I am using Mac OSX 10.8, previously I used macports, but I switched to brew. ``` Snows-MacBook-Pro:~ Mac$ brew search matplotlib samueljohn/python/matplotlib Snows-MacBook-Pro:~ Mac$ pip search matplotlib matplotlib - Python plotting package ``` So my question is easy. Should I use brew or pip for ins...
If brew works like MacPorts, it is best to go through it. Here are a few reasons why: * If you use your package manager (MacPorts, brew,…) to later install additional programs that depend on **Matplotlib**, the package manager **will install** it **regardless**. * **If you install a Python package via pip**, and pip...
Blocking certain ip's if exceeds 'tries per x'
16,895,950
2
2013-06-03T11:45:07Z
16,896,094
7
2013-06-03T11:52:21Z
[ "python" ]
Having a server that has to handle lots of TCP-requests from gprs-modules I think it is handy to set up something to protect this server from multiple requests from certain ip's. Now I want to make something(within python) that will check how much times a certain ip tries to connect and if this exceeds a given amount ...
Don't tackle this from your code - this is what a firewall is designed to do. Using iptables its trivial: ``` iptables -I INPUT -p tcp --dport $PORT -i eth0 -m state --state NEW -m recent --set iptables -I INPUT -p tcp --dport $PORT -i eth0 -m state --state NEW -m recent --update --seconds 600 --hitcount 2 -j DROP `...
change background *without* a frame with matplotlib
16,897,527
3
2013-06-03T13:09:35Z
16,897,848
7
2013-06-03T13:25:51Z
[ "python", "matplotlib" ]
Given this code, ``` from pylab import * ion() axes(frameon = 0, aspect = 1, polar = 1) grid (True) ``` I get the window, containing the axes, where I can plot what I need. I want to change the background of this window from the standard gray to another color. I do not want to use a frame.
You need to specify an argument to the `facecolor` parameter when calling `figure()`: ``` from pylab import * ion() figure(facecolor='white') # Or any other color axes(frameon = 0, aspect = 1, polar = 1) grid(True) ``` ![enter image description here](http://i.stack.imgur.com/Ybdfy.png)
Matplotlib streamplot arrows pointing the wrong way
16,897,585
4
2013-06-03T13:13:06Z
16,902,871
17
2013-06-03T17:57:00Z
[ "python", "matplotlib", "contour" ]
I am generating a groundwater elevation contour and a streamplot in matplotlib The contour indicates that the elevation is decreasing in many areas but the groundwater flow (streamplot) is pointed uphill. I have circled the arrows that seem to be pointed the wrong direction. The arrows toward the bottom of the map ap...
## Summary I'm guessing, but your problem is probably because you have an inherent transpose going on. 2D numpy arrays are indexed as row, column. "x, y" indexing is column, row. In this context, `numpy.gradient` is basically going to return dy, dx and not dx, dy. Try changing the line: ``` dx, dy = np.gradient(zi) ...
How can I decode a SSL certificate using python?
16,899,247
7
2013-06-03T14:33:40Z
17,669,661
16
2013-07-16T06:40:12Z
[ "python", "ssl", "cryptography", "certificate", "pem" ]
How can I decode a pem-encoded (base64) certificate with Python? For example this here from github.com: ``` -----BEGIN CERTIFICATE----- MIIHKjCCBhKgAwIBAgIQDnd2il0H8OV5WcoqnVCCtTANBgkqhkiG9w0BAQUFADBp MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3 d3cuZGlnaWNlcnQuY29tMSgwJgYDVQQDEx9EaWdpQ2VydCBIaWdoI...
You can use `pyasn1` and `pyasn1_modules` packages to parse this kind of data. For instance: ``` from pyasn1_modules import pem, rfc2459 from pyasn1.codec.der import decoder substrate = pem.readPemFromFile(open('cert.pem')) cert = decoder.decode(substrate, asn1Spec=rfc2459.Certificate())[0] print(cert.prettyPrint()) ...
How to make an abstract Haystack SearchIndex class
16,900,067
5
2013-06-03T15:14:07Z
16,913,708
11
2013-06-04T09:02:46Z
[ "python", "django", "django-haystack" ]
How do you make an abstract SearchIndex class, similar to how Django lets you make abstract base models? I have several SearchIndexes that I'd like to give the same basic fields (object\_id, timestamp, importance, etc). Currently, I'm duplicating all this code, so I'm trying to create a "BaseIndex" and simply have all...
Just don't include `indexes.Indexable` as a parent on anything you don't want indexing. So modifying your first example. ``` class BaseIndex(indexes.SearchIndex): text = indexes.CharField(document=True, use_template=True) object_id = indexes.IntegerField() timestamp = indexes.DateTimeField() class Me...
How to make 'access_type=offline' / server-only OAuth2 operations on GAE/Python?
16,900,919
4
2013-06-03T15:57:26Z
16,903,181
7
2013-06-03T18:16:27Z
[ "python", "google-app-engine", "google-api", "oauth-2.0", "google-api-python-client" ]
This post is a followup to *[How to do OAuth-requiring operations in a GAE cron job?](http://stackoverflow.com/questions/16863661/how-to-do-oauth-requiring-operations-in-a-gae-cron-job/16864183?noredirect=1#comment24330008_16864183)*, where I realized I'm mis-using the `@oauth_required` decorator from `OAuth2DecoratorF...
Offline access is the [default](https://code.google.com/p/google-api-python-client/source/browse/oauth2client/client.py?r=ae2ff74e239820776304fadcba8f9b476efd913b#1201) when retrieving tokens; you may have noticed this in the OAuth dialog that comes up: > Perform these operations when I'm not using the application Wh...
Did I install pip correctly?
16,902,805
7
2013-06-03T17:52:26Z
23,499,295
8
2014-05-06T15:48:28Z
[ "python", "python-2.7" ]
I'm new to python and the tutorial I'm using suggested for me to install four important packages (distribute, pip, nose and virtual env). I've installed the first two using setup.py in Windows PowerShell Problem is I can't figure out how to use pip. I've tried doing commands for pip in the cmd, python idle shell and ...
To add an answer to this question (it was provided in the comments by Joran Beasley), the issue here was that `pip` installs to the `python/Scipts` directory, but that was not in the path by default on Windows. Adding `C:\Python27\Scripts` to the path fixed the issue. [This answer describes adding a directory to the pa...
Meaning of 0x and \x in python hex strings?
16,903,192
11
2013-06-03T18:17:18Z
16,903,228
17
2013-06-03T18:19:01Z
[ "python", "numpy" ]
I'm doing some binary operations which are often shown as hex-es. I have seen both the `0x` and `\x`as prefixes. In which case is which used?
`0x` is used for literal numbers. `"\x"` is used inside strings to represent a character ``` >>> 0x41 65 >>> "\x41" 'A' >>> "\x01" # a non printable character '\x01' ```
Get ordered field names from peewee Model
16,903,319
6
2013-06-03T18:24:14Z
16,903,363
10
2013-06-03T18:26:39Z
[ "python", "orm", "peewee" ]
I'd like to use peewee to [create](http://peewee.readthedocs.org/en/latest/peewee/api.html#Model.create) records from a csv. It looks like the syntax requires keyword args: ``` user = User.create(username='admin', password='test') ``` If the rows in the csv look like `(admin, test)`, it would be convenient to know th...
Looks like it's `User._meta.get_field_names()` I just saw someone else mention it in [another question](http://stackoverflow.com/questions/13864940/python-dumping-database-data-with-peewee).
Logscale plots with zero values in matplotlib
16,904,755
5
2013-06-03T19:52:26Z
16,904,878
13
2013-06-03T20:00:52Z
[ "python", "matplotlib" ]
I am currently using logscale in order to have greater possibilities of plotting my data. Nevertheless, my data consists also of zero values. I know that these zero values will not work on logscale as log(0) is not defined. So e.g., ``` fig = plt.figure() ax = fig.add_subplot(111) ax.plot([0,1,2],[10,10,100],marker='...
It's easiest to use a "symlog" plot for this purpose. The interval near 0 will be on a linear scale, so 0 can be displayed. ``` import matplotlib.pyplot as plt fig, ax = plt.subplots() ax.plot([0,1,2],[10,10,100],marker='o',linestyle='-') ax.set_yscale('symlog') ax.set_xscale('symlog') plt.show() ``` ![enter image de...
Why is matplotlib plot produced from ipython notebook slightly different from terminal version?
16,905,028
6
2013-06-03T20:10:32Z
16,905,543
7
2013-06-03T20:46:02Z
[ "python", "matplotlib", "ipython-notebook" ]
I have a strange issue. Using IPython Notebook, I created a quite extensive script using pandas and matplotlib to create a number of charts. When my tinkering was finished, I copied (and cleaned) the code into a standalone python script (so that I can push it into the svn and my paper co-authors can create the charts a...
To complete Joe answer, the inlinebackend (IPython/kernel/zmq/pylab/backend\_inline.py) have some default matplotlib parameters : ``` # The typical default figure size is too large for inline use, # so we shrink the figure size to 6x4, and tweak fonts to # make that fit. rc = Dict({'figure.figsize': (6.0,4.0), # p...
How can I get the username of the logged-in user in Django?
16,906,515
16
2013-06-03T21:57:15Z
16,906,564
28
2013-06-03T22:00:31Z
[ "python", "django", "django-templates", "django-views", "models" ]
How can I get information about the logged-in user in a Django application? For example: I need to know the username of the logged-in user to say who posted a Review: ``` <form id='formulario' method='POST' action=''> <h2>Publica tu tuit, {{ usuario.username.title }} </h2> {% csrf_token %} {{formulario.a...
You can use the request object to find the logged in user ``` def my_view(request): username = None if request.user.is_authenticated(): username = request.user.username ```
How can I get the username of the logged-in user in Django?
16,906,515
16
2013-06-03T21:57:15Z
25,573,626
13
2014-08-29T17:51:06Z
[ "python", "django", "django-templates", "django-views", "models" ]
How can I get information about the logged-in user in a Django application? For example: I need to know the username of the logged-in user to say who posted a Review: ``` <form id='formulario' method='POST' action=''> <h2>Publica tu tuit, {{ usuario.username.title }} </h2> {% csrf_token %} {{formulario.a...
`request.user.get_username()` or `request.user.username`, former is preferred. [Django docs say:](https://docs.djangoproject.com/en/dev/ref/contrib/auth/#django.contrib.auth.models.User.get_username) > Since the User model can be swapped > out, you should use this method instead of referencing the username > attribut...
Double every letter in string
16,907,604
2
2013-06-03T23:45:43Z
16,907,614
9
2013-06-03T23:46:35Z
[ "python", "string" ]
What is the most efficient way in Python to double (or repeat n times) every letter in a string? ``` "abcd" -> "aabbccdd" ``` or ``` "abcd" -> "aaaabbbbccccdddd" ``` I have a long string that needs to be mutated in this fashion and the current solution involves a loop with `n` concatenations for every letter, which...
Use `str.join`: ``` >>> strs = "abcd" >>> "".join([x*2 for x in strs]) 'aabbccdd' >>> "".join([x*4 for x in strs]) 'aaaabbbbccccdddd' ``` From [docs](http://wiki.python.org/moin/PythonSpeed/PerformanceTips#String_Concatenation): ``` s = "" for substring in list: s += substring ``` Use `s = "".join(list)` instea...
How to execute Python inline from a bash shell
16,908,236
8
2013-06-04T01:03:02Z
16,908,265
19
2013-06-04T01:07:14Z
[ "python", "shell", "inline", "execution" ]
Is there a Python argument to execute code from the shell without starting up an interactive interpreter or reading from a file? Something similar to: ``` perl -e 'print "Hi"' ```
This works: ``` python -c 'print "Hi"' Hi ```
Flask Display Json in a Neat Way
16,908,943
5
2013-06-04T02:32:39Z
17,715,057
10
2013-07-18T05:18:10Z
[ "python", "json", "mongodb", "formatting", "flask" ]
I'm creating an API from a mongodb database using Flask and have the following code: ``` app.route('/<major>/') def major_res(major): course_list = list(client.db.course_col.find( {"major" : (major.encode("utf8", "ignore").upper())})) return json.dumps(course_list, sort_keys=True, indent=4, default=json...
Flask provides `jsonify()` as a convenience: ``` app.route('/<major>/') def major_res(major): course_list = list(client.db.course_col.find({"major": major.encode('utf8', 'ignore').upper() })) return flask.jsonify(**course_list) ``` This will return the kwargs of `jsonify` as a nicely formatted json response a...
Scrapy:In a request fails (eg 404,500), how to ask for another alternative request?
16,909,106
2
2013-06-04T02:54:25Z
16,985,389
12
2013-06-07T13:30:45Z
[ "python", "web-scraping", "scrapy", "http-status-code-404" ]
I have a problem with scrapy. In a request fails (eg 404,500), how to ask for another alternative request? Such as two links can obtain price info, the one failed, request another automatically.
Use "errback" in the Request like `errback=self.error_handler` where error\_handler is a function (just like callback function) in this function check the error code and make the alternative Request. see errback in the scrapy documentation: <http://doc.scrapy.org/en/latest/topics/request-response.html>
Any way to solve a system of coupled differential equations in python?
16,909,779
11
2013-06-04T04:22:27Z
16,909,889
8
2013-06-04T04:36:03Z
[ "python", "numpy", "scipy", "enthought", "sympy" ]
I've been working with sympy and scipy, but can't find or figure out how to solve a system of coupled differential equations (non-linear, first-order). So is there any way to solve coupled differential equations? The equations are of the form: ``` V11'(s) = -12*v12(s)**2 v22'(s) = 12*v12(s)**2 v12'(s) = 6*v11(s)*v12...
For the numerical solution of ODEs with scipy, see the function [scipy.integrate.odeint](http://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.odeint.html) or the class [scipy.integrate.ode](http://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.ode.html). Some examples are given in the [Sci...
Delete a group after pandas groupby
16,910,114
7
2013-06-04T05:00:12Z
16,916,611
9
2013-06-04T11:27:13Z
[ "python", "pandas" ]
Is it possible to delete a group (by group name) from a groupby object in pandas? That is, after performing a groupby, delete a resulting group based on its name.
Filtering a DataFrame groupwise has been [discussed](http://stackoverflow.com/questions/13446480/python-pandas-remove-entries-based-on-the-number-of-occurrences#comment18556837_13447176). And a future release of pandas may include [a more convenient way to do it](https://github.com/pydata/pandas/pull/3680). But curren...
Ubuntu add directory to Python path
16,913,086
4
2013-06-04T08:29:52Z
16,913,180
7
2013-06-04T08:34:42Z
[ "python", "ubuntu", "importerror" ]
I want to run third part tool written in python on my ubuntu machine ([corgy tool](https://github.com/pkerpedjiev/corgy)). However I don't know how to add additional modules to Python path. ``` cat doc/download.rst There is currently no setup.py, so you need to manually add the download directory to your PYT...
Create a `.bash_profile` in your home directory. Then, add the line ``` PYTHONPATH=$PYTHONPATH:new_dir EXPORT $PYTHONPATH ``` Or even better: ``` if [ -d "new_dir" ] ; then PYTHONPATH="$PYTHONPATH:new_dir" fi EXPORT $PYTHONPATH ``` The `.bash_profile` properties are loaded every time you log in. The `source` com...
python print vs __str__?
16,914,708
9
2013-06-04T09:50:35Z
16,914,713
7
2013-06-04T09:51:02Z
[ "python", "python-2.7" ]
can anyone enlighten me on the differences between `print sth` and `print str(sth)` ? E.g. in the example from the [official documentation for sqlite3](http://docs.python.org/2/library/sqlite3.html#row-objects), one can currently see the following code that creates a database and then uses a factory class to wrap data...
While I was writing this and looking for some references, I have actually found the most part of the answer: 1. the C implementation for a Python object may implement [PyObject\_Print()](http://docs.python.org/2/c-api/object.html#PyObject_Print) function, which defines the way the object will be printed to a file, inc...
How to test command line scripts with nose?
16,916,880
4
2013-06-04T11:40:48Z
16,916,992
10
2013-06-04T11:47:08Z
[ "python", "unit-testing", "nose", "pyunit" ]
I've created a Python library with some command-line scripts in a 'bin' directory (so that `setup.py` will install it into 'bin' when installing it with `pip`). Since this isn't a Python module, I can't work out how to test it with nose. How can I test a command line script that's part of a library using `nose`/`unitt...
Use the "[`if __name__ == "__main__":`](http://stackoverflow.com/questions/419163/what-does-if-name-main-do)" idiom in your scripts and encapsulate *all of* the *function*-ality in *function*-s. Then you can `import` your scripts into another script (such as a unit test script) without the body of it being executed. T...
How to make GPS-app for android using kivy, pyjnius?
16,917,149
5
2013-06-04T11:55:22Z
19,346,866
10
2013-10-13T15:27:44Z
[ "android", "python", "kivy" ]
Im new in KIVY, pyjnius and python-android. I need to make simple app for android, which shows GPS coordinates. But, as i said, i'm new in kivy and pyforandroid. Can somebody show/give me example,which shows my coordinates in simple kivy-label-widget? Thanks a lot! I ve tried to do something like this but... ``` ...
I did while ago a demo of accessing GPS within Kivy/pyjnius: ``` https://github.com/tito/android-demo ``` Look at the source code, everything is in it.
Filling above/below matplotlib line plot
16,917,919
8
2013-06-04T12:30:53Z
16,918,528
9
2013-06-04T12:58:57Z
[ "python", "matplotlib" ]
I'm using matplotlib to create a simple line plot. My plot is a simple time-series data set where I have time along the x-axis and the value of something I am measuring on the y-axis. y values can have postitive or negative values and I would like to fill in the area above and below my line with the color blue if the y...
The code snippet you provided should be corrected as follows: ``` plt.plot(x, y, marker='.', lw=1) d = scipy.zeros(len(y)) ax.fill_between(xs, ys, where=ys>=d, interpolate=True, color='blue') ax.fill_between(xs, ys, where=ys<=d, interpolate=True, color='red') ``` The [`fill_between`](http://matplotlib.org/api/pyplot_...
Merging two arrays under numpy
16,919,296
3
2013-06-04T13:33:31Z
16,919,461
7
2013-06-04T13:40:55Z
[ "python", "arrays", "numpy" ]
Using Numpy, I would like to achieve the result below, given b and c. I have looked into stacking functions, but I cannot get it to work. Could someone please help? ``` import numpy as np a=range(35,135) b=np.reshape(a,(10,10)) c=np.array([[5,5],[5,6],[5,7],[6,5],[6,6],[6,7],[7,5],[7,6],[7,7]]) ``` The result shoul...
Phew! This was a doosie. First, we use numpy's fancy indexing to pull out the items that you want.: ``` >>> b[tuple(c.T)] array([ 90, 91, 92, 100, 101, 102, 110, 111, 112]) ``` Then, the only thing that remains is to stack that array back against `c` using `column_stack`: ``` >>> np.column_stack((c,b[tuple(c.T)]))...
Encapsulating retries into `with` block
16,919,570
14
2013-06-04T13:46:35Z
16,919,782
7
2013-06-04T13:57:06Z
[ "python", "exception-handling", "with-statement", "contextmanager" ]
I'm looking to encapsulate logic for database transactions into a `with` block; wrapping the code in a transaction and handling various exceptions (locking issues). This is simple enough, however I'd like to also have the block encapsulate the retrying of the code block following certain exceptions. I can't see a way t...
> Is it possible to repeat the code within a `with` statement? [No.](http://mail.python.org/pipermail/python-ideas/2013-May/020633.html) As pointed out earlier in that mailing list thread, you can reduce a bit of duplication by making the decorator call the passed function: ``` def do_work(): ... # This is n...
Fetching data from the list
16,920,752
2
2013-06-04T14:42:54Z
16,920,847
7
2013-06-04T14:46:59Z
[ "python", "dictionary" ]
I have a dictionary with location and quantity, like ``` {'loc1': 1000.0,'loc2': 500.0, 'loc3': 200.0,'loc4': 100.0,'loc5': 50.0, } ``` Now when i'll make a order the scenario should be like below, * for `150 quantity` it should take product from `loc5` and `loc4` * for `210 quantity` it should take product from `lo...
Put the quantities in a list, sorted. [Use `bisect` to find an appropriate quantity.](http://docs.python.org/2/library/bisect.html#searching-sorted-lists) Calculate if the lower quantities can fulfill, and if not pick the next higher quantity. Subtract the selected quantity. If still greater than 0, go back to the `bis...
What is the maximum length for an attribute name in python?
16,920,835
7
2013-06-04T14:46:41Z
16,920,876
23
2013-06-04T14:48:10Z
[ "python", "python-2.7" ]
I'm writing a set of python functions that perform some sort of conformance checking on a source code project. I'd like to specify quite verbose names for these functions, e.g.: `check_5_theVersionOfAllVPropsMatchesTheVersionOfTheAutolinkHeader()` Could such excessively long names be a problem for python? Is there a m...
[2.3. Identifiers and keywords](https://docs.python.org/2/reference/lexical_analysis.html#identifiers) from The Python Language Reference: > Identifiers are unlimited in length. --- But you'll be violating [PEP-8](http://www.python.org/dev/peps/pep-0008/#maximum-line-length) most likely, which is not really cool: >...
Reading a text file and splitting it into single words in python
16,922,214
9
2013-06-04T15:50:32Z
16,922,328
32
2013-06-04T15:56:17Z
[ "python" ]
So I have this text file made up of numbers and words, for example like this - "09807754 18 n 03 aristocrat 0 blue\_blood 0 patrician" and I want to split it so that each word or number will come up as a new line. A whitespace separator would be ideal as I would like the words with the dashes to stay connected. This ...
If you do not have quotes around your data: ``` with open('words.txt','r') as f: for line in f: for word in line.split(): print(word) ```
Reading a text file and splitting it into single words in python
16,922,214
9
2013-06-04T15:50:32Z
16,922,527
9
2013-06-04T16:05:39Z
[ "python" ]
So I have this text file made up of numbers and words, for example like this - "09807754 18 n 03 aristocrat 0 blue\_blood 0 patrician" and I want to split it so that each word or number will come up as a new line. A whitespace separator would be ideal as I would like the words with the dashes to stay connected. This ...
``` f = open('words.txt') for word in f.read().split(): print(word) ```
Pandas writing dataframe to CSV file
16,923,281
120
2013-06-04T16:46:56Z
16,923,367
207
2013-06-04T16:52:17Z
[ "python", "csv", "pandas", "dataframe" ]
I have a dataframe in pandas which I would like to write to a CSV file. I am doing this using: ``` df.to_csv('out.csv') ``` And getting the error: ``` UnicodeEncodeError: 'ascii' codec can't encode character u'\u03b1' in position 20: ordinal not in range(128) ``` Is there any way to get around this easily (i.e. I h...
To delimit by a tab you can use the `sep` argument of [`to_csv`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_csv.html): ``` df.to_csv(file_name, sep='\t') ``` To use a specific encoding (e.g. 'utf-8') use the `encoding` argument: ``` df.to_csv(file_name, sep='\t', encoding='utf-8') ```
How to get the raw content of a response in requests with Python?
16,923,898
8
2013-06-04T17:25:03Z
16,924,225
7
2013-06-04T17:45:44Z
[ "python", "http", "web", "request", "python-requests" ]
Trying to get the raw data of the HTTP response content in `requests` in Python. I am interested in forwarding the response through another channel, which means that ideally the content should be as pristine as possible. What would be a good way to do this? Thanks very much!
If you are using a `requests.get` call to obtain your HTTP response, you can use the `raw` attribute of the response. Here is the code from the [`requests` docs](http://requests.readthedocs.org/en/latest/user/quickstart/#raw-response-content). ``` >>> r = requests.get('https://github.com/timeline.json', stream=True) >...
Difference between os.getenv and os.environ.get?
16,924,471
27
2013-06-04T17:59:42Z
16,924,553
21
2013-06-04T18:04:01Z
[ "python", "environment-variables" ]
Is there any difference at all between these two? When should I use one over the other? Is one of these deprecated? They seem to have the exact same functionality. ``` >>> os.getenv('TERM') 'xterm' >>> os.environ.get('TERM') 'xterm' >>> os.getenv('FOOBAR', "not found") == "not found" True >>> os.environ.get('FOOBAR',...
See [this related thread](http://stackoverflow.com/questions/10952507/when-would-os-environfoo-not-match-os-getenvfoo). Basically, `os.environ` is found on import, and `os.getenv` is a wrapper to `os.environ.get`, at least in CPython. EDIT: To respond to a comment, in CPython, `os.getenv` is basically a shortcut to `o...
Generate unique id in django from a model field
16,925,129
16
2013-06-04T18:38:59Z
16,925,164
27
2013-06-04T18:41:09Z
[ "python", "django", "django-models" ]
I want to generate different/unique id per request in django from models field. I did this but I keep getting the same id. ``` class Paid(models.Model): user=models.ForeignKey(User) eyw_transactionref=models.CharField(max_length=100, null=True, blank=True, unique=True, default=uuid.uuid4()) #want to generate...
Do it like this: ``` #note the uuid without parenthesis eyw_transactionref=models.CharField(max_length=100, blank=True, unique=True, default=uuid.uuid4) ``` The reason why is because with the parenthesis you **evaluate the function when the model is imported** and this will yield an uuid which will be used for every ...
Generate unique id in django from a model field
16,925,129
16
2013-06-04T18:38:59Z
30,637,668
35
2015-06-04T07:31:28Z
[ "python", "django", "django-models" ]
I want to generate different/unique id per request in django from models field. I did this but I keep getting the same id. ``` class Paid(models.Model): user=models.ForeignKey(User) eyw_transactionref=models.CharField(max_length=100, null=True, blank=True, unique=True, default=uuid.uuid4()) #want to generate...
since version 1.8 Django has `UUIDField` <https://docs.djangoproject.com/en/1.8/ref/models/fields/#django.db.models.UUIDField> ``` import uuid from django.db import models class MyUUIDModel(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) # other fields ```
Python raise child_exception OSError: [Errno 8] Exec format error
16,925,909
4
2013-06-04T19:28:11Z
16,926,079
14
2013-06-04T19:38:06Z
[ "python" ]
I have to move a python script from a server that use Python 2.6 to another on that uses 2.4. I had to make some modifications. now im stuck. i keep on getting this error ``` File "subprocess.py", line 975, in _execute_child raise child_exception OSError: [Errno 8] Exec format error ``` my log ouput: ``` Trace...
If `bin/fst2r2c` is a binary executable, is it the right format for the new server? (Have you moved from Linux to BSD, or 32-bit to 64-bit?) If `bin/fst2r2c` is a script, is its `#!` line intact? (Have you edited it on Windows and introduced a `\r`? Is the pathname of its executable different on the new machine, eg. `...
python convert to binary and keep leading zeros
16,926,130
53
2013-06-04T19:41:19Z
16,926,292
58
2013-06-04T19:50:51Z
[ "python", "binary", "formatting", "bitwise-operators" ]
I'm trying to convert an int to binary using the bin() function in python. However, it always removes the leading zeros, which I actually need, such that the result is always 8-bit: Example: ``` bin(1) -> 0b1 # what I would like: bin(1) -> 0b00000001 ``` Does anybody know a way of doing this?
``` >>> '{:08b}'.format(1) '00000001' ``` See: [Format Specification Mini-Language](https://docs.python.org/2/library/string.html#format-specification-mini-language) --- Note for Python 2.6: Prior to 2.7, you cannot omit the positional argument identifier before `:`, so use ``` >>> '{0:08b}'.format(1) '00000010' ``...
python convert to binary and keep leading zeros
16,926,130
53
2013-06-04T19:41:19Z
16,926,357
61
2013-06-04T19:54:38Z
[ "python", "binary", "formatting", "bitwise-operators" ]
I'm trying to convert an int to binary using the bin() function in python. However, it always removes the leading zeros, which I actually need, such that the result is always 8-bit: Example: ``` bin(1) -> 0b1 # what I would like: bin(1) -> 0b00000001 ``` Does anybody know a way of doing this?
Use the [`format()` function](http://docs.python.org/2/library/functions.html#format): ``` >>> format(14, '#010b') '0b00001110' ``` The `format()` function simply formats the input following the [Format Specification mini language](http://docs.python.org/2/library/string.html#format-specification-mini-language). The ...
Python: split on either a space or a hyphen?
16,926,870
4
2013-06-04T20:28:07Z
16,926,888
12
2013-06-04T20:29:06Z
[ "python", "string", "formatting" ]
In Python, how do I split on either a space or a hyphen? Input: ``` You think we did this un-thinkingly? ``` Desired output: ``` ["You", "think", "we", "did", "this", "un", "thinkingly"] ``` I can get as far as ``` mystr.split(' ') ``` But I don't know how to split on hyphens as well as spaces [and the Python de...
``` >>> import re >>> text = "You think we did this un-thinkingly?" >>> re.split(r'\s|-', text) ['You', 'think', 'we', 'did', 'this', 'un', 'thinkingly?'] ``` As @larsmans noted, to split by multiple spaces/hyphens (emulating `.split()` with no arguments) used `[...]` for readability: ``` >>> re.split(r'[\s-]+', text...
Python: split on either a space or a hyphen?
16,926,870
4
2013-06-04T20:28:07Z
16,926,952
9
2013-06-04T20:33:17Z
[ "python", "string", "formatting" ]
In Python, how do I split on either a space or a hyphen? Input: ``` You think we did this un-thinkingly? ``` Desired output: ``` ["You", "think", "we", "did", "this", "un", "thinkingly"] ``` I can get as far as ``` mystr.split(' ') ``` But I don't know how to split on hyphens as well as spaces [and the Python de...
If your pattern is simple enough for one (or maybe two) `replace`, use it: ``` mystr.replace('-', ' ').split(' ') ``` Otherwise, use RE as suggested by [@jamylak](http://stackoverflow.com/a/16926888/2289509).
How can I make Selenium/Python wait for the user to login before continuing to run?
16,927,354
4
2013-06-04T20:58:07Z
16,927,552
7
2013-06-04T21:11:14Z
[ "python", "selenium" ]
I'm trying to run a script in Selenium/Python that requires logins at different points before the rest of the script can run. Is there any way for me to tell the script to pause and wait at the login screen for the user to manually enter a username and password (maybe something that waits for the page title to change b...
Use [WebDriverWait](http://docs.seleniumhq.org/docs/04_webdriver_advanced.jsp). For example, this performs a google search and then waits for a certain element to be present before printing the result: ``` import contextlib import selenium.webdriver as webdriver import selenium.webdriver.support.ui as ui with contextl...
How to calculate precision, recall and F-score with libSVM in python
16,927,964
4
2013-06-04T21:40:33Z
16,964,420
9
2013-06-06T14:15:00Z
[ "python", "machine-learning", "libsvm", "precision-recall" ]
I want to calculate the `precision`, `recall` and `f-score` using **libsvm** in Python but I do not know how. I have found [this site](http://www.csie.ntu.edu.tw/~cjlin/libsvmtools/eval/index.html) but I have not understand how to call the function, if you can help me through example.
You can take advantage of [`scikit-learn`](http://scikit-learn.org/), which is one of the best packages for machine learning in Python. Its SVM implementation uses `libsvm`and you can work out precision, recall and f-score as shown in the following snippet: ``` from sklearn import svm from sklearn import metrics from ...
Create dictionary from list python
16,929,359
5
2013-06-04T23:56:04Z
16,929,371
7
2013-06-04T23:57:19Z
[ "python", "list", "dictionary" ]
I have many lists in this format: ``` ['1', 'O1', '', '', '', '0.0000', '0.0000', '', ''] ['2', 'AP', '', '', '', '35.0000', '105.0000', '', ''] ['3', 'EU', '', '', '', '47.0000', '8.0000', '', ''] ``` I need to create a dictionary with key as the first element in the list and value as the entire list. None of the ke...
``` >>> lists = [['1', 'O1', '', '', '', '0.0000', '0.0000', '', ''], ['2', 'AP', '', '', '', '35.0000', '105.0000', '', ''], ['3', 'EU', '', '', '', '47.0000', '8.0000', '', '']] >>> {x[0]: x for x in lists} {'1': ['1', 'O1', '', '', '', '0.0000', '0.0000', '', ''], '3': ['3', 'EU', '', '', '', '47.0000', '8.0000', ''...
Python logging from multiple threads
16,929,639
7
2013-06-05T00:25:36Z
16,929,729
25
2013-06-05T00:36:25Z
[ "python", "multithreading", "logging" ]
I have a `log.py` module, that is used in at least two other modules (`server.py` and `device.py`). It has these globals: ``` fileLogger = logging.getLogger() fileLogger.setLevel(logging.DEBUG) consoleLogger = logging.getLogger() consoleLogger.setLevel(logging.DEBUG) file_logging_level_switch = { 'debug': fil...
The good news is that you don't need to do anything extra for thread safety, and you either need nothing extra or something almost trivial for clean shutdown. I'll get to the details later. The bad news is that your code has a serious problem even before you get to that point: `fileLogger` and `consoleLogger` are the ...
Response time for urllib in python
16,931,280
3
2013-06-05T03:55:02Z
16,933,237
11
2013-06-05T06:44:19Z
[ "python", "urllib" ]
I want to get response time when I use `urllib`. I made below code, but it is more than response time. Can I get the time using `urllib` or have any other method? ``` import urllib import datetime def main(): urllist = [ "http://google.com", ] for url in urllist: opener = urllib.FancyURLo...
Save yourself some hassle and use the [requests](http://docs.python-requests.org/en/latest/user/quickstart/#response-content) module. In its responses it provides a [datetime.timedelta](http://docs.python.org/2/library/datetime.html) field called 'elapsed' that lets you know how long the request took. ``` >>> import r...
Why non-default arguments can't follows default argument?
16,932,825
32
2013-06-05T06:17:41Z
16,933,071
8
2013-06-05T06:33:46Z
[ "python", "language-agnostic", "default" ]
Why this piece of code throwing a Syntax Error ? ``` >>> def fun1(a="who is you", b="True", x, y): ... print a,b,x,y ... File "<stdin>", line 1 SyntaxError: non-default argument follows default argument ``` While following piece of code is correct... ``` >>> def fun1(x, y, a="who is you", b="True"): ... ...
``` SyntaxError: non-default argument follows default argument ``` If you were to allow this, the default arguments would be rendered useless because you would never be able to use their default values, since the non-default arguments come **after**. In Python 3 however, you may do the following: ``` def fun1(a="who...
Why non-default arguments can't follows default argument?
16,932,825
32
2013-06-05T06:17:41Z
16,933,624
44
2013-06-05T07:08:58Z
[ "python", "language-agnostic", "default" ]
Why this piece of code throwing a Syntax Error ? ``` >>> def fun1(a="who is you", b="True", x, y): ... print a,b,x,y ... File "<stdin>", line 1 SyntaxError: non-default argument follows default argument ``` While following piece of code is correct... ``` >>> def fun1(x, y, a="who is you", b="True"): ... ...
All required parameters must be placed before any default arguments. Simply because they are mandatory, whereas default arguments are not. Syntactically, it would be *impossible* for the interpreter to decide which values match which arguments if mixed modes were allowed. A `SyntaxError` is raised if the arguments are ...
How to avoid / prevent Max Redirects error with requests in Python?
16,933,835
5
2013-06-05T07:22:00Z
16,948,852
9
2013-06-05T20:05:29Z
[ "python", "http", "web", "request", "python-requests" ]
Trying to avoid getting a `Number of Redirects Exceeds 30` error with `python-requests`. Is there something I can do to avoid it, or is it purely server-side? I got this error while trying to `GET` `facebook.com`. Thanks very much!
The *server* is redirecting you in a loop. You'll need to figure out why you are being redirected so often. You could try to see what goes on by *not* allowing redirects (set `allow_redirects=False`), then resolving them using the [`.resolve_redirects()` API](http://www.python-requests.org/en/master/api/#requests.Sess...
Matlab filter not compatible with Python lfilter
16,936,558
3
2013-06-05T09:42:03Z
16,941,815
7
2013-06-05T13:52:56Z
[ "python", "matlab", "numpy", "filter", "scipy" ]
Good day, I have been fiddling around porting matlab code to python and I ran into this weird issue. I googled around a bit but found no information that indicates I am doing something wrong. The core of the issue is Matlab's filter(b, a, data) (which is built-in into matlab) is generating a different output when com...
This is not a bug. Matlab's `filter` operates on the *first* dimension of the array, while `scipy.signal.lfilter` by default operates on the the *last* dimension. From your question I see that your `data` array has a second dimension (perhaps empty?). When you use `lfilter` it defaults to `axis=-1`, which will give th...
Storing bools in SQLite database
16,936,608
3
2013-06-05T09:44:33Z
16,936,992
8
2013-06-05T10:01:28Z
[ "python", "sqlite" ]
In my table schema: ``` ... disabled BOOLEAN, ... ``` When connecting to db: ``` db = sqlite3.connect(f, detect_types=sqlite3.PARSE_DECLTYPES) sqlite3.register_converter("BOOLEAN", myfunc) ``` I insert a record like so: ``` INSERT INTO mytable (disabled, ...) VALUES (:disabled, ...) ``` Along with a parameter dic...
You want to use a combination of `register_adapter` and `register_converter` for the two directions: ``` sqlite3.register_adapter(bool, int) sqlite3.register_converter("BOOLEAN", lambda v: bool(int(v))) ``` SQLite uses a [dynamic type system](http://www.sqlite.org/datatype3.html) but for custom types it has no way of...
Extracting connected objects from an image in Python
16,937,158
7
2013-06-05T10:09:41Z
16,939,577
7
2013-06-05T12:08:47Z
[ "python", "image", "scipy" ]
I have a graysacle png image and I want to extract all the connected components from my image. Some of the components have same intensity but I want to assign a unique label to every object. here is my image ![enter image description here](http://i.stack.imgur.com/x0hhC.png) I tried this code: ``` img = imread(image...
[J.F. Sebastian shows a way](http://stackoverflow.com/a/5304140/190597) to identify objects in an image. It requires manually choosing a gaussian blur radius and threshold value, however: ``` import scipy from scipy import ndimage import matplotlib.pyplot as plt fname='index.png' blur_radius = 1.0 threshold = 50 img...
How to remove duplicate columns from a dataframe using python pandas
16,938,441
7
2013-06-05T11:13:38Z
16,939,512
14
2013-06-05T12:05:55Z
[ "python", "pandas" ]
By grouping two columns I made some changes. I generated a file using python, it resulted in 2 duplicate columns. How to remove duplicate columns from a dataframe?
It's probably easiest to use a groupby (assuming they have duplicate names too): ``` In [11]: df Out[11]: A B B 0 a 4 4 1 b 4 4 2 c 4 4 In [12]: df.T.groupby(level=0).first().T Out[12]: A B 0 a 4 1 b 4 2 c 4 ``` If they have different *names* you can `drop_duplicates` on the transpose: ``` I...
Quick way to extend a set if we know elements are unique
16,939,402
5
2013-06-05T12:00:23Z
16,939,538
11
2013-06-05T12:07:10Z
[ "python", "set", "union" ]
I am performing multiple iterations of the type: ``` masterSet=masterSet.union(setA) ``` As the set grows the length of time taken to perform these operations is growing (as one would expect, I guess). I expect that the time is taken up checking whether each element of setA is already in masterSet? My question is t...
You can use `set.update` to update your master set in place. This saves allocating a new set all the time so it should be a little faster than `set.union`... ``` >>> s = set(range(3)) >>> s.update(range(4)) >>> s set([0, 1, 2, 3]) ``` Of course, if you're doing this in a loop: ``` masterSet = set() for setA in itera...
Why is there no tuple comprehension in Python?
16,940,293
89
2013-06-05T12:44:24Z
16,940,351
157
2013-06-05T12:46:37Z
[ "python", "tuples", "list-comprehension", "dictionary-comprehension", "set-comprehension" ]
As we all know, there's list comprehension, like ``` [i for i in [1, 2, 3, 4]] ``` and there is dictionary comprehension, like ``` {i:j for i, j in {1: 'a', 2: 'b'}.items()} ``` but ``` (i for i in (1, 2, 3)) ``` will end up in a generator, not a `tuple` comprehension. Why is that? My guess is that a `tuple` is ...
You can use a generator expression: ``` tuple(i for i in (1, 2, 3)) ``` but parenthesis were already taken for.. generator expressions.
Why is there no tuple comprehension in Python?
16,940,293
89
2013-06-05T12:44:24Z
16,940,382
11
2013-06-05T12:47:33Z
[ "python", "tuples", "list-comprehension", "dictionary-comprehension", "set-comprehension" ]
As we all know, there's list comprehension, like ``` [i for i in [1, 2, 3, 4]] ``` and there is dictionary comprehension, like ``` {i:j for i, j in {1: 'a', 2: 'b'}.items()} ``` but ``` (i for i in (1, 2, 3)) ``` will end up in a generator, not a `tuple` comprehension. Why is that? My guess is that a `tuple` is ...
Comprehension works by looping or iterating over items and assigning them into a container, a Tuple is unable to receive assignments. Once a Tuple is created, it can not be appended to, extended, or assigned to. The only way to modify a Tuple is if one of its objects can itself be assigned to (is a non-tuple container...
Why is there no tuple comprehension in Python?
16,940,293
89
2013-06-05T12:44:24Z
16,941,245
27
2013-06-05T13:28:42Z
[ "python", "tuples", "list-comprehension", "dictionary-comprehension", "set-comprehension" ]
As we all know, there's list comprehension, like ``` [i for i in [1, 2, 3, 4]] ``` and there is dictionary comprehension, like ``` {i:j for i, j in {1: 'a', 2: 'b'}.items()} ``` but ``` (i for i in (1, 2, 3)) ``` will end up in a generator, not a `tuple` comprehension. Why is that? My guess is that a `tuple` is ...
Raymond Hettinger (one of the Python core developers) had this to say about tuples in a [recent tweet](https://twitter.com/raymondh/status/324664257004322817): > #python tip:Generally, lists are for looping; tuples for structs. Lists are homogeneous; tuples heterogeneous.Lists for variable length. This (to me) suppor...
NumPy array, change the values that are NOT in a list of indices
16,940,895
6
2013-06-05T13:12:50Z
16,941,004
10
2013-06-05T13:17:29Z
[ "python", "arrays", "numpy", "replace", "multidimensional-array" ]
I have a `numpy` array like: ``` a = np.arange(30) ``` I know that I can replace the values located at positions `indices=[2,3,4]` using for instance fancy indexing: ``` a[indices] = 999 ``` But how to replace the values at the positions that are not in `indices`? Would be something like below? ``` a[ not in indic...
I don't know of a clean way to do something like this: ``` mask = np.ones(a.shape,dtype=bool) #np.ones_like(a,dtype=bool) mask[indices] = False a[~mask] = 999 a[mask] = 888 ``` Of course, if you prefer to use the numpy data-type, you could use `dtype=np.bool_` -- There won't be any difference in the output. it's just...
Is there a way to read two files at the same time in python? (with the same loop?)
16,943,206
5
2013-06-05T14:57:54Z
16,943,239
8
2013-06-05T14:59:40Z
[ "python" ]
I am trying to read 2 files at the same time right now, but I get a "too many values to unpack error". Here is what I have: ``` for each_f, each_g in f, g : line_f = each_f.split() line_g = each_g.split() ``` I am a little new to python but I assumed I would be able to do this. If this is impossible, is there...
``` import itertools # ... for each_f, each_g in itertools.izip(f, g): # ... ```
Is "join" slower in 3.x?
16,943,265
10
2013-06-05T15:01:02Z
17,083,503
7
2013-06-13T09:22:01Z
[ "python", "python-2.7", "python-3.x" ]
I was just messing around when I came across this quirk. And I wanted to make sure I am not crazy. The following code (works in 2.x and 3.x): ``` from timeit import timeit print ('gen: %s' % timeit('"-".join(str(n) for n in range(1000))', number=10000)) print ('list: %s' % timeit('"-".join([str(n) for n in range(1000...
I haven't worked on python3.3 yet. All these I have stated below is based on observation. I used python disassembler for following code in python 3.3 and python 2.7.3. ``` s = """ ''.join([n for n in ('1', '2', '3')]) """ ``` I found there are changes in the upcodes. Python 2.7.3 ``` Python 2.7.3 (default, Apr 10 ...
South 'nothing to migrate' message after successful schema migration
16,943,319
2
2013-06-05T15:03:15Z
16,943,571
8
2013-06-05T15:13:44Z
[ "python", "django", "heroku", "django-south" ]
I have a Django app that I added South to, performed some migrations with, and runs as expected on my local machine. However, I have had nothing but database errors after pushing my project to Heroku. In trying to deal with one database error I am experiencing, I attempted a test where I deleted one of my models, push...
After you change the models, you need to do : ``` heroku run python manage.py schemamigration django_app --auto ``` if anything has changed and then run ``` heroku run python manage.py migrate django_app ``` South applies migrations based on the entries in this database table: `south_migrationhistory`. So if you w...
Python multiprocessing and handling exceptions in workers
16,943,404
10
2013-06-05T15:06:12Z
16,945,699
10
2013-06-05T16:57:23Z
[ "python", "exception", "error-handling", "parallel-processing", "multiprocessing" ]
I use python multiprocessing library for an algorithm in which I have many workers processing certain data and returning result to the parent process. I use multiprocessing.Queue for passing jobs to workers, and second to collect results. It all works pretty well, until worker fails to process some chunk of data. In t...
I changed your code slightly to make it work (see explanation below). ``` import multiprocessing as mp import random workers_count = 5 # Probability of failure, change to simulate failures fail_init_p = 0.5 fail_job_p = 0.4 #========= Worker ========= def do_work(job_state, arg): if random.random() < fail_job_p...
How to Access the Directory API in Admin SDK
16,943,788
11
2013-06-05T15:23:15Z
16,961,299
14
2013-06-06T11:45:46Z
[ "python", "google-api-python-client" ]
Trying in vain to access the Directory API in the Google Admin SDK ([Reference](https://google-developers.appspot.com/admin-sdk/directory/)). Upgrading the "google-api-python-client" package doesn't resolve it, as the Downloads > Installation > Python link instructs. I also don't see in the documentation where it list...
There's an issue where this new API isn't appearing in the list of supported APIs, but it is indeed there, you can access it from: ``` service = build('admin', 'directory_v1') ```
Python program to remove double entries from line
16,944,562
2
2013-06-05T15:58:00Z
16,944,618
7
2013-06-05T16:00:47Z
[ "python" ]
i have the following function built to sort through lines, then per line, it sorts the content within the line into numerical values. lines like this: ``` 67:1 45:1 67:1 89:1 31:1 89:5 45:1 23:1 ``` code: ``` with open("SVM/svm-pos-train.txt") as f, open("SVM/svm-pos-train2.txt", 'w') as out: for li...
Use [set](http://docs.python.org/2/library/sets.html) ``` line = line.split() line = list(set(line)) ``` `set` returns an un-ordered collection of unique elements, then convert it back to list and then sort the list. **Edit:** ``` line = line.split() line = list(set(line)) out.write(" ".join(sorted(line, x: (int(x....
Module Import Error running py.test with modules on Path
16,945,091
4
2013-06-05T16:24:52Z
16,954,982
13
2013-06-06T06:20:05Z
[ "python", "python-2.7", "pythonpath", "py.test" ]
I'm unable to import my module for testing in the way that I'd like. I'm running all of this in a virtualenv on 2.7.2 I have a directory structure like ``` /api /api __init__.py my_module.py /tests my_module_test.py ``` I have my PYTHONPATH set to /Path/api/. I CD into /Path/api and r...
I use **PYTHONPATH** as ``` PYTHONPATH=`pwd` py.test tests/my_module_test.py ```
Merging two time series in pandas
16,945,166
9
2013-06-05T16:28:18Z
16,945,410
12
2013-06-05T16:40:50Z
[ "python", "pandas", "time-series" ]
Apologies if this is obviously documented somewhere, but I'm having trouble discovering it. I have two TimeSeries with some overlapping dates/indices and I'd like to merge them. I assume I'll have to specify which of the two series to take the values from for the overlapping dates. For illustration I have: ``` s1: 200...
This can be achieved using [`combine_first`](http://pandas.pydata.org/pandas-docs/dev/merging.html#merging-together-values-within-series-or-dataframe-columns): ``` In [11]: s1.combine_first(s2) Out[11]: 2008-09-15 100.00 2008-10-15 101.00 2008-11-15 102.02 dtype: float64 ```
Python argmin/argmax: Finding the index of the value which is the min or max
16,945,518
8
2013-06-05T16:46:55Z
16,945,868
22
2013-06-05T17:06:51Z
[ "python" ]
I've got a structure of the form: ``` >>> items [([[0, 1], [2, 20]], 'zz', ''), ([[1, 3], [5, 29], [50, 500]], 'a', 'b')] ``` The first item in each tuple is a list of ranges, and I want to make a generator that provides me the ranges in ascending order based on the starting index. Since the range-lists are already ...
``` from operator import itemgetter index, element = max(enumerate(items), key=itemgetter(1)) ``` Return the index of the biggest element in `items` and the element itself.
Python argmin/argmax: Finding the index of the value which is the min or max
16,945,518
8
2013-06-05T16:46:55Z
26,726,185
16
2014-11-04T01:14:00Z
[ "python" ]
I've got a structure of the form: ``` >>> items [([[0, 1], [2, 20]], 'zz', ''), ([[1, 3], [5, 29], [50, 500]], 'a', 'b')] ``` The first item in each tuple is a list of ranges, and I want to make a generator that provides me the ranges in ascending order based on the starting index. Since the range-lists are already ...
This method finds the index of the maximum element of any iterable and does not require any external imports: ``` def argmax(iterable): return max(enumerate(iterable), key=lambda x: x[1])[0] ```
Python argmin/argmax: Finding the index of the value which is the min or max
16,945,518
8
2013-06-05T16:46:55Z
31,105,620
7
2015-06-28T22:57:07Z
[ "python" ]
I've got a structure of the form: ``` >>> items [([[0, 1], [2, 20]], 'zz', ''), ([[1, 3], [5, 29], [50, 500]], 'a', 'b')] ``` The first item in each tuple is a list of ranges, and I want to make a generator that provides me the ranges in ascending order based on the starting index. Since the range-lists are already ...
The index of the max of a list: ``` def argmax(lst): return lst.index(max(lst)) ```
how to separate string from unformed string
16,947,064
4
2013-06-05T18:16:45Z
16,947,229
11
2013-06-05T18:27:10Z
[ "python" ]
I have this format of string ``` 2013-06-05T11:01:02.955 LASTNAME=Jone FIRSTNAME=Jason PERSONNELID=salalm QID=231412 READER_NAME="CAZ.1 LOBBY LEFT TURNSTYLE OUT" ACCESS_TYPE="Access Granted" EVENT_TIME_UTC=1370480141.000 REGION=UTAH ``` some of them looks like this ``` 2013-06-05T11:15:48.670 LASTNAME=Ga FIRSTNAME...
One hack I've found useful in the past is to use [`shlex.split`](http://docs.python.org/2/library/shlex.html#shlex.split): ``` >>> s = '2013-06-05T11:01:02.955 LASTNAME=Jone FIRSTNAME=Jason PERSONNELID=salalm QID=231412 READER_NAME="CAZ.1 LOBBY LEFT TURNSTYLE OUT" ACCESS_TYPE="Access Granted" EVENT_TIME_UTC=1370480141...
Python logging across multiple modules
16,947,234
6
2013-06-05T18:27:30Z
16,947,462
11
2013-06-05T18:41:09Z
[ "python", "logging", "python-2.7" ]
I'm trying to add logging (to console rather than a file) to my a piece of code I've been working on for a while. Having read around a bit I have a pattern that I think should work, but I'm not quite sure where I'm going wrong. I have the following three files (simplified, obviously): controller.py ``` import my_mod...
According to the [documentation](http://docs.python.org/2/howto/logging.html#logging-from-multiple-modules) it looks like you might get away with an even simpler setup like so: > If your program consists of multiple modules, here’s an example of how > you could organize logging in it: ``` # myapp.py import logging ...
binning a dataframe in pandas in Python
16,947,336
24
2013-06-05T18:33:51Z
16,949,498
34
2013-06-05T20:42:45Z
[ "python", "numpy", "pandas" ]
given the following dataframe in pandas: ``` import numpy as np df = pandas.DataFrame({"a": np.random.random(100), "b": np.random.random(100), "id": np.arange(100)}) ``` where `id` is an id for each point consisting of an `a` and `b` value, how can I bin `a` and `b` into a specified set of bins (so that I can then ta...
There may be a more efficient way (I have a feeling `pandas.crosstab` would be useful here), but here's how I'd do it: ``` import numpy as np import pandas df = pandas.DataFrame({"a": np.random.random(100), "b": np.random.random(100), "id": np.arange(100)}) # Bin the dat...
binning a dataframe in pandas in Python
16,947,336
24
2013-06-05T18:33:51Z
16,949,500
17
2013-06-05T20:42:58Z
[ "python", "numpy", "pandas" ]
given the following dataframe in pandas: ``` import numpy as np df = pandas.DataFrame({"a": np.random.random(100), "b": np.random.random(100), "id": np.arange(100)}) ``` where `id` is an id for each point consisting of an `a` and `b` value, how can I bin `a` and `b` into a specified set of bins (so that I can then ta...
Not 100% sure if this is what you're looking for, but here's what I think you're getting at: ``` In [144]: df = DataFrame({"a": np.random.random(100), "b": np.random.random(100), "id": np.arange(100)}) In [145]: bins = [0, .25, .5, .75, 1] In [146]: a_bins = df.a.groupby(cut(df.a,bins)) In [147]: b_bins = df.b.gr...
binning a dataframe in pandas in Python
16,947,336
24
2013-06-05T18:33:51Z
23,691,692
9
2014-05-16T02:26:51Z
[ "python", "numpy", "pandas" ]
given the following dataframe in pandas: ``` import numpy as np df = pandas.DataFrame({"a": np.random.random(100), "b": np.random.random(100), "id": np.arange(100)}) ``` where `id` is an id for each point consisting of an `a` and `b` value, how can I bin `a` and `b` into a specified set of bins (so that I can then ta...
Joe Kington's answer was very helpful, however, I noticed that it does not bin all of the data. It actually leaves out the row with a = a.min(). Summing up `groups.size()` gave 99 instead of 100. To guarantee that all data is binned, just pass in the number of bins to cut() and that function will automatically pad the...
Cannot concatenate 'str' and 'float' objects?
16,948,256
9
2013-06-05T19:31:17Z
17,365,737
21
2013-06-28T13:23:01Z
[ "python", "string", "concatenation" ]
Our geometry teacher gave us an assignment asking us to create an example of when toy use geometry in real life, so I thought it would be cool to make a program that calculates how many gallons of water will be needed to fill a pool of a certain shape, and with certain dimensions. Here is the program so far: ``` impo...
All floats or non string data types must be casted to strings before concatenation This should work correctly: (notice the `str` cast for multiplication result) ``` easygui.msgbox=("You need "+ str(3.14*(float(radius)**2) * float(height)) + "gallons of water to fill this pool.") ``` straight from the interpreter: `...
Understanding Django's urlconf
16,948,959
4
2013-06-05T20:12:15Z
16,948,983
8
2013-06-05T20:13:50Z
[ "python", "regex", "django" ]
I'm trying to understand this line: `url(r'^(?P<poll_id>\d+)/$', views.detail, name='detail'),` from [Django's tutorial](https://docs.djangoproject.com/en/1.5/intro/tutorial03/) on how to create views. In particular, I don't understand the following: * ?P * \d+ * name='detail' **urls.py** ``` urlpatterns = patterns...
* `(?P<poll_id>...)` creates a [named group](https://docs.djangoproject.com/en/dev/topics/http/urls/#named-groups); you can now refer to whatever was matched in that group by name. The view will be passed a keyword parameter by that name when called. * `\d` is a character group, it matches numeric digits (`0` throug...
Python: Why is this invalid syntax?
16,950,394
66
2013-06-05T21:42:18Z
16,950,508
99
2013-06-05T21:50:41Z
[ "python", "syntax", "python-internals" ]
Why can't you use a trailing comma with `*args` in Python? In other words, this works ``` >>> f(1, 2, b=4,) ``` But this does not ``` >>> f(*(1, 2), b=4,) File "<stdin>", line 1 f(*(1, 2), b=4,) ^ SyntaxError: invalid syntax ``` This is the case with both Python 2 and Python 3.
Let's look at the [language specification](http://docs.python.org/2.7/reference/expressions.html#calls): ``` call ::= primary "(" [argument_list [","] | expression genexpr_for] ")" argument_list ::= positional_arguments ["," keyword_arguments] ...
How to format list and dictionary comprehensions
16,951,716
4
2013-06-05T23:54:26Z
16,951,717
11
2013-06-05T23:54:26Z
[ "python" ]
List and dictionary comprehensions are powerful and fast, but they can be hard to read. My mental read buffer quickly fills up, **especially** when they’re deeply nested. Is there a way to make these more readable?
You’re right. ;) They can be hard to read, which can also make them hard to compose and debug. Let’s take the following example dict comprehension: ``` current_team = dict((k,v) for k,v in list(team.items()) for player in v[‘player’] if player['year'] == 2013) ``` Too many years of C and Java programming have...
Using os.walk() to recursively traverse directories in Python
16,953,842
41
2013-06-06T04:47:00Z
16,974,952
74
2013-06-07T01:37:08Z
[ "python", "os.walk" ]
i want to navigate from the root directory to all other directories within and print the same. Here's my code: ``` #!/usr/bin/python import os import fnmatch for root, dir, files in os.walk("."): print root print "" for items in fnmatch.filter(files, "*"): print "..." + items...
This will give you the desired result ``` #!/usr/bin/python import os # traverse root directory, and list directories as dirs and files as files for root, dirs, files in os.walk("."): path = root.split('/') print((len(path) - 1) * '---', os.path.basename(root)) for file in files: print(len(path) ...
Encode Python list to UTF-8
16,957,226
5
2013-06-06T08:29:29Z
16,957,257
20
2013-06-06T08:30:54Z
[ "python", "list", "encode" ]
I have a python list that looks like that: ``` list = [u'a', u'b', u'c'] ``` Now I want to encode it in UTF-8. Therefore I though I should use: ``` list = list[0].encode("utf-8") ``` But print list gives only ``` a ``` meaning the first element of the list. Not even a list anymore. What am I doing wrong?
``` >>> items = [u'a', u'b', u'c'] >>> [x.encode('utf-8') for x in items] ['a', 'b', 'c'] ```
Python to JSON Serialization fails on Decimal
16,957,275
16
2013-06-06T08:32:15Z
16,957,370
49
2013-06-06T08:36:59Z
[ "python", "json" ]
I have a python object which includes some decimals. This is causing the json.dumps() to break. I got the following solution from SO (e.g. [Python JSON serialize a Decimal object](http://stackoverflow.com/questions/1960516/python-json-serialize-a-decimal-object)) but the recoomended solution still does not work. Pytho...
It is not (no longer) recommended you create a subclass; the `json.dump()` and `json.dumps()` functions take a `default` function: ``` def decimal_default(obj): if isinstance(obj, decimal.Decimal): return float(obj) raise TypeError json.dumps({'x': decimal.Decimal('5.5')}, default=decimal_default) ```...
Python to JSON Serialization fails on Decimal
16,957,275
16
2013-06-06T08:32:15Z
32,614,358
10
2015-09-16T16:49:07Z
[ "python", "json" ]
I have a python object which includes some decimals. This is causing the json.dumps() to break. I got the following solution from SO (e.g. [Python JSON serialize a Decimal object](http://stackoverflow.com/questions/1960516/python-json-serialize-a-decimal-object)) but the recoomended solution still does not work. Pytho...
I can't believe that no one here talked about using simplejson, which supports deserialization of Decimal out of the box. ``` import simplejson from decimal import Decimal simplejson.dumps({"salary": Decimal("5000000.00")}) '{"salary": 5000000.00}' simplejson.dumps({"salary": Decimal("1.1")+Decimal("2.2")-Decimal("3...
Style of addressing attributes in python
16,957,542
4
2013-06-06T08:46:28Z
16,957,625
11
2013-06-06T08:50:04Z
[ "python", "coding-style" ]
This question is one of style. Since the attributes are not private in python, is it good and common practice to address them directly outside the class using something like `my_obj.attr`? Or, maybe, it is still better to do it via member-functions like `get_attr()` that is an usual practice in c++?
Sounds like you want to use properties: ``` class Foo(object): def __init__(self, m): self._m = m @property def m(self): print 'accessed attribute' return self._m @m.setter def m(self, m): print 'setting attribute' self._m = m >>> f = Foo(m=5) >>> f.m = 6 s...
Showing Pandas data frame as a table
16,958,513
9
2013-06-06T09:30:43Z
16,958,896
17
2013-06-06T09:48:08Z
[ "python", "pandas" ]
since I have installed the updated version of pandas every time I type in the name of a dataframe, e.g. ``` df[0:5] ``` To see the first few rows, it gives me a summary of the columns, the number of values in them and the data types instead. How do I get to see the tabular view instead? (I am using iPython btw). Th...
*Note: To show the top few rows you can also use [`head`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.head.html).* However, pandas will show the summary view if there are more columns than `display.max_columns` or they are longer than `display.width` (analogously for rows), so you'll need to...
Showing Pandas data frame as a table
16,958,513
9
2013-06-06T09:30:43Z
19,229,741
7
2013-10-07T16:17:21Z
[ "python", "pandas" ]
since I have installed the updated version of pandas every time I type in the name of a dataframe, e.g. ``` df[0:5] ``` To see the first few rows, it gives me a summary of the columns, the number of values in them and the data types instead. How do I get to see the tabular view instead? (I am using iPython btw). Th...
Short answer: If your version is later that 0.11.0, try setting your display width with: ``` pd.set_option('display.width', 200) ``` Long answer: Granted, the thread is 4 months old, but I was having this same problem last night. An ipython notebook that worked fine at my job would not present html tables at home. F...
Dynamic default arguments in python functions
16,960,469
3
2013-06-06T11:03:11Z
16,960,503
7
2013-06-06T11:04:45Z
[ "python" ]
I have a need for functions with default arguments that have to be set at function runtime (such as empty lists, values derived from other arguments or data taken from the database) and I am currently using the following pattern to deal with this: ``` def foo(bar, baz=None): baz = baz if baz else blar() # Stuf...
No, that's pretty much it. Usually you test for `is None` so you can safely pass in falsey values like `0` or `""` etc. ``` def foo(bar, baz=None): baz = baz if baz is not None else blar() ``` The old fashioned way is the two liner. Some people may prefer this ``` def foo(bar, baz=None): if baz is None: ...
Python: Logging all of a class' methods without decorating each one
16,961,914
4
2013-06-06T12:19:17Z
16,962,026
8
2013-06-06T12:25:13Z
[ "python", "class", "logging" ]
I want to log every method call in some classes. I could have done ``` class Class1(object): @log def method1(self, *args): ... @log def method2(self, *args): ... ``` But I have a lot of methods in every class, and I don't want to decorate every one separately. Currently, I tried using...
Why don't you alter the class object? You can go through the methods in a class with `dir(MyClass)` and replace them with a wrapped version... something like: ``` def logify(klass): for member in dir(klass): if not callable(getattr(klass, method)) continue # skip attributes setattr(kla...
How to send periodic tasks to specific queue in Celery
16,962,449
18
2013-06-06T12:44:33Z
17,084,301
13
2013-06-13T10:03:01Z
[ "python", "celery", "django-celery" ]
By default Celery send all tasks to 'celery' queue, but you can change this behavior by adding extra parameter: ``` @task(queue='celery_periodic') def recalc_last_hour(): log.debug('sending new task') recalc_hour.delay(datetime(2013, 1, 1, 2)) # for example ``` Scheduler settings: ``` CELERYBEAT_SCHEDULE = {...
I found solution for this problem: 1) First of all I changed the way for configuring periodic tasks. I used **@periodic\_task** decorator like this: ``` @periodic_task(run_every=crontab(minute='5'), queue='celery_periodic', options={'queue': 'celery_periodic'}) def recalc_last_hour(): ...
How to send periodic tasks to specific queue in Celery
16,962,449
18
2013-06-06T12:44:33Z
27,857,767
16
2015-01-09T09:45:44Z
[ "python", "celery", "django-celery" ]
By default Celery send all tasks to 'celery' queue, but you can change this behavior by adding extra parameter: ``` @task(queue='celery_periodic') def recalc_last_hour(): log.debug('sending new task') recalc_hour.delay(datetime(2013, 1, 1, 2)) # for example ``` Scheduler settings: ``` CELERYBEAT_SCHEDULE = {...
Periodic are sent to queues by celerybeat.You can do every thing we do with Celery api. Here is the list of configurations comes with celerybeat. <http://celery.readthedocs.org/en/latest/userguide/periodic-tasks.html#available-fields> In your case ``` CELERYBEAT_SCHEDULE = { 'installer_recalc_hour': { 'ta...
Convert scientific notation to decimal - python
16,962,512
4
2013-06-06T12:47:08Z
16,962,569
7
2013-06-06T12:49:45Z
[ "python", "scientific-notation", "floating-point-conversion" ]
How do I convert a scientific notation to floating point number? Here is an example of what I want to avoid: ``` Python 2.7.3 (default, Apr 14 2012, 08:58:41) [GCC] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> a=[78.40816326530613, 245068094.16326532] >>> print a[0]/a[1] 3.19944...
Use string formatting: ``` >>> "{:.50f}".format(float(a[0]/a[1])) '0.00000031994439558937568872208504280885144055446290' ```
Decompress bz2 files
16,963,352
9
2013-06-06T13:25:31Z
16,964,073
10
2013-06-06T13:59:17Z
[ "python", "decompress" ]
I would like to decompress the files in different directories which are in different routes. And codes as below and the error is invalid data stream. Please help me out. Thank you so much. ``` import sys import os import bz2 from bz2 import decompress path = "Dir" for(dirpath,dirnames,files)in os.walk(path): for f...
bz2.compress/decompress work with binary data: ``` >>> import bz2 >>> compressed = bz2.compress(b'test_string') >>> compressed b'BZh91AY&SYJ|i\x05\x00\x00\x04\x83\x80\x00\x00\x82\xa1\x1c\x00 \x00"\x03h\x840" P\xdf\x04\x99\xe2\xeeH\xa7\n\x12\tO\x8d \xa0' >>> bz2.decompress(compressed) b'test_string' ``` In short - you...