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
Using Selenium in the background
16,389,938
8
2013-05-05T22:54:15Z
16,390,130
12
2013-05-05T23:18:29Z
[ "python", "selenium", "webdriver", "phantomjs", "ghostdriver" ]
I'm using Selenium and chrome webdriver but when I run scripts it opens a window. Is there any way that it can access the internet without the window popping up? ``` from selenium import webdriver from selenium.webdriver.common.keys import Keys driver = webdriver.Chrome() driver.get("https://ps.rsd.edu/public/") ele...
I would suggest try using headless PhantomJs GhostDriver (which is a relatively new thing). As this is the native Selenium Webdriver way of doing it. Download PhantomJs executables from <http://phantomjs.org/download.html>. ``` driver = webdriver.PhantomJS("./phantomjs") # path to phantomjs binary driver.get("https:/...
Scraping ajax pages using python
16,390,257
8
2013-05-05T23:38:57Z
16,395,938
21
2013-05-06T09:39:57Z
[ "python", "ajax", "web-scraping", "screen-scraping", "scrapy" ]
I've already seen [this question about scraping ajax](http://stackoverflow.com/questions/260540/how-do-you-screen-scrape-ajax-pages), but python isn't mentioned there. I considered using [scrapy](http://blog.scrapy.org/), i believe they have some docs on that subject, but as you can see the website is down. So i don't ...
First of all, scrapy docs are available at <https://scrapy.readthedocs.org/en/latest/>. Speaking about handling ajax while web scraping. Basically, the idea is rather simple: * open browser developer tools, network tab * go to the target site * click submit button and see what [`XHR` request](http://en.wikipedia.org/...
DatabaseError: ORA-01036: illegal variable name/number
16,392,288
4
2013-05-06T05:10:58Z
16,398,323
8
2013-05-06T12:01:23Z
[ "python", "python-2.7", "oracle10g", "cx-oracle" ]
I need to substitute the following values into select query. but i got the error as i mentioned below ``` self.jobNo = J-12060 qcActivity = C173 self.wrkArea = 1666339 cursor.execute("""SELECT A.MARKERID, D.COMMENTS,A.STATUS,A.X1,A.Y1,A.X2,A.Y2,C.ERRGROUP,C.ERRDESC,c.category FROM MDP_ERR_MASTER A,(SELECT ...
I think you have misunderstood how bind variables work with Oracle and cx\_Oracle. Oracle recognises an expression such as `:myvar` in a SQL query as a bind variable placeholder. When it encounters this, it will make a note that it needs a value for this variable before it can run the query, but it can still continue ...
Make more than one chart in same IPython Notebook cell
16,392,921
35
2013-05-06T06:10:36Z
16,393,023
34
2013-05-06T06:18:52Z
[ "python", "pandas", "ipython", "ipython-notebook" ]
I have started my IPython Notebook with ``` ipython notebook --pylab inline ``` This is my code in one cell ``` df['korisnika'].plot() df['osiguranika'].plot() ``` This is working fine, it will draw two lines, but on the same chart. I would like to draw each line on a separate chart. And it would be great if the c...
Make the multiple axes first and pass them to the Pandas plot function, like: ``` fig, axs = plt.subplots(1,2) df['korisnika'].plot(ax=axs[0]) df['osiguranika'].plot(ax=axs[1]) ``` It still gives you 1 figure, but with two different plots next to each other.
Make more than one chart in same IPython Notebook cell
16,392,921
35
2013-05-06T06:10:36Z
18,046,682
28
2013-08-04T19:21:25Z
[ "python", "pandas", "ipython", "ipython-notebook" ]
I have started my IPython Notebook with ``` ipython notebook --pylab inline ``` This is my code in one cell ``` df['korisnika'].plot() df['osiguranika'].plot() ``` This is working fine, it will draw two lines, but on the same chart. I would like to draw each line on a separate chart. And it would be great if the c...
You can also call the show() function after each plot. e.g ``` plot(a) show() plot(b) show() ``` see example at - <http://nbviewer.ipython.org/6151560>
XlsxWriter object save as http response to create download in Django
16,393,242
14
2013-05-06T06:35:46Z
16,596,719
28
2013-05-16T20:19:31Z
[ "python", "django", "excel", "httpresponse", "xlsxwriter" ]
XlsxWriter object save as http response to create download in Django?
I think you're asking about how to create an excel file in memory using `xlsxwriter` and return it via `HttpResponse`. Here's an example: ``` try: import cStringIO as StringIO except ImportError: import StringIO from django.http import HttpResponse from xlsxwriter.workbook import Workbook def your_view(req...
XlsxWriter object save as http response to create download in Django
16,393,242
14
2013-05-06T06:35:46Z
27,405,896
19
2014-12-10T16:20:00Z
[ "python", "django", "excel", "httpresponse", "xlsxwriter" ]
XlsxWriter object save as http response to create download in Django?
A little update on @alecxe response for Python 3 (**io.BytesIO** instead of **StringIO.StringIO**) and Django >= 1.5 (**content\_type** instead of **mimetype**), with the fully in-memory file assembly that has since been implemented by @jmcnamara (**{'in\_memory': True}**) ! Here is the full example : ``` import io ...
UnicodeEncodeError:'latin-1' codec can't encode characters in position 0-1: ordinal not in range(256)
16,394,332
5
2013-05-06T07:48:16Z
16,404,147
11
2013-05-06T17:40:45Z
[ "python", "django", "sqlalchemy", "mysql-python", "latin1" ]
i am a newer in python.Today when I write some search function I met an error.well, I use sqlalchemy orm to do that, in my function,I input a chinese word as the key word.The html page give me an UnicodeEncodeError at /user/search:'latin-1' codec can't encode characters in position 0-1: ordinal not in range(256). and m...
I'm assuming that you're using MySQL with the MySQLdb driver here. The default encoding used by the MySQLdb driver is latin-1, which does not support your character set. You'll need to use UTF-8 (or others, but UTF-8 is the most common) to be able to communicate with your database through MySQLdb (see <http://docs.sql...
Cannot get environment variables in Django settings file
16,395,491
8
2013-05-06T09:13:21Z
16,396,615
9
2013-05-06T10:18:48Z
[ "python", "linux", "django", "environment-variables", "django-settings" ]
I'm trying to read some environment variables in Django settings, which i have defined in /home/user/.bashrc (and latter in /etc/bash.bashrc ) , but all i get is a KeyError exception. I know my environment variables are set, because i can print them in the terminal (echo $VAR\_NAME). This should be trivial. This is th...
I've manage to solve my problem by using this solution: <http://drumcoder.co.uk/blog/2010/nov/12/apache-environment-variables-and-mod_wsgi/>
Python numpy 2D array indexing
16,396,141
15
2013-05-06T09:51:35Z
16,396,203
21
2013-05-06T09:55:27Z
[ "python", "numpy" ]
I am quite new to python and numpy. Can some one pls help me to understand how I can do the indexing of some arrays used as indices. I have the following six 2D arrays like this- ``` array([[2, 0], [3, 0], [3, 1], [5, 0], [5, 1], [5, 2]]) ``` I want to use these arrays as indices and put the value 10 i...
``` In [1]: import numpy as np In [2]: a = np.array([[2,0],[3,0],[3,1],[5,0],[5,1],[5,2]]) In [3]: b = np.zeros((6,3), dtype='int32') In [4]: b[a[:,0], a[:,1]] = 10 In [5]: b Out[5]: array([[ 0, 0, 0], [ 0, 0, 0], [10, 0, 0], [10, 10, 0], [ 0, 0, 0], [10, 10, 10]]) ``` --...
Bland-Altman plot in Python
16,399,279
3
2013-05-06T12:57:46Z
16,401,920
10
2013-05-06T15:22:15Z
[ "python", "matplotlib", "plot" ]
Is it possible to make a [Bland-Altman plot](http://en.wikipedia.org/wiki/Bland%E2%80%93Altman_plot) in Python? I can't seem to find anything about it. Another name for this type of plot is the *Tukey mean-difference plot*. **Example:** ![enter image description here](http://i.stack.imgur.com/0ZicM.png)
If I have understood the theory behind the plot correctly, this code should provide the basic plotting, whereas you can configure it to your own particular needs. ``` import matplotlib.pyplot as plt import numpy as np def bland_altman_plot(data1, data2, *args, **kwargs): data1 = np.asarray(data1) data2 ...
How to manually change a colormap in python/matplotlib
16,400,241
12
2013-05-06T13:52:42Z
16,401,183
21
2013-05-06T14:42:30Z
[ "python", "matplotlib", "color-mapping" ]
I want to use the colormap `rainbow` in an image using `imshow`. It works perfectly, but I want to redefine the color for the value `0`. Instead of violete, I want to use white. I want to do this only for the value zero, all other values can stay with the default values in the colormap. Any idea how to do this **with...
You can also use `set_under` which I think makes more semantic sense than using `set_bad` ``` my_cmap = matplotlib.cm.get_cmap('rainbow') my_cmap.set_under('w') imshow(np.arange(25).reshape(5, 5), interpolation='none', cmap=my_cmap, vmin=.001) ``` You can tweak the colorbar to also show the 'unde...
plot vlines with matplotlib.pyplot
16,401,783
4
2013-05-06T15:14:47Z
16,413,554
9
2013-05-07T07:30:24Z
[ "python", "matplotlib", "plot" ]
I'm trying to plot vertical lines in a log plot ``` xv1 = 10 plt.semilogy(t,P,'b') plt.semilogy(t,Pb,'r') plt.vlines(xv1,-1,1,color='k',linestyles='solid') plt.xlabel('Time [s]') plt.ylabel('P [Pa]') plt.grid() plt.show() ``` The vlines does not show up in the plot (it does for plt.plot) Any ideas? Thanks!
For plotting vertical lines that span the entire plot range, you may use `axvline`. Your code could then read ``` xv1 = 10 plt.semilogy(t, P, 'b') plt.semilogy(t, Pb, 'r') plt.axvline(xv1, color='k', linestyle='solid') plt.xlabel('Time [s]') plt.ylabel('P [Pa]') plt.grid() plt.show() ```
XML write to file UnicodeDecodeError Python 2.7.3
16,404,069
2
2013-05-06T17:36:16Z
16,404,355
7
2013-05-06T17:54:54Z
[ "python", "xml", "dom", "python-2.7" ]
I've searched the site and haven't found an answer that works for me. My problem is that I'm trying to write xml to a file and when I run the script from the terminal I get: ``` Traceback (most recent call last): File "fetchWiki.py", line 145, in <module> pageDictionary = qSQL(users_database) File "fetchWiki.py", line...
You should not encode the strings you use for attributes. The `minidom` library handles those for you when writing. Your error is caused by mixing bytestrings with unicode data, and your encoded bytestrings are not decodable as ASCII. If some of your data is encoded, and some of it is in `unicode`, try to avoid that ...
Using py.test with coverage doesn't include imports
16,404,716
25
2013-05-06T18:17:53Z
16,524,426
36
2013-05-13T14:23:27Z
[ "python", "py.test", "coverage.py" ]
For [Jedi](https://github.com/davidhalter/jedi) we want to generate our [test coverage](https://github.com/davidhalter/jedi/issues/196). There is a [related question](http://stackoverflow.com/q/8636828/727827) in stackoverflow, but it didn't help. We're using py.test as a test runner. However, we are unable to add the...
@hynekcer gave me the right idea. But basically the easiest solution lies somewhere else: **Get rid of `pytest-cov`!** Use ``` coverage run --source jedi -m py.test coverage report ``` instead!!! This way you're just running a coverage on your current py.test configuration, which works perfectly fine! It's also phi...
Regular expression for UK Mobile Number - Python
16,405,187
2
2013-05-06T18:48:34Z
16,405,304
7
2013-05-06T18:56:09Z
[ "python", "regex", "django" ]
I need a regular expression that only validates **UK mobile numbers**. A UK mobile number can be between `10-14` digits and either starts with `07`, or omits the `0` and starts with `447`. Importantly, if the user adds `+44` it should be rejected. So these would be valid: > 07111111111 > > 447111111111 and these w...
The following regex seems like it would fit your requirements, if I understand them correctly. Not allowing a + sign is very easy as you're only creating a whitelist of values, and the plus isn't among them. `^(07[\d]{8,12}|447[\d]{7,11})$` As was mentioned in the comments for this answer, the square brackets are no...
Remove characters before and including _ in python 2.7
16,405,601
13
2013-05-06T19:15:55Z
16,405,619
26
2013-05-06T19:16:48Z
[ "python", "string", "python-2.7", "split", "word-wrap" ]
The following code returns into a nice readable output. ``` def add_line_remove_special(ta_from,endstatus,*args,**kwargs): try: ta_to = ta_from.copyta(status=endstatus) infile = botslib.opendata(ta_from.filename,'r') tofile = botslib.opendata(str(ta_to.idta),'wb') start = infile.rea...
To get all text on a line after a underscore character, split on the first `_` character and take the last element of the result: ``` line.split('_', 1)[-1] ``` This will also work for lines that do *not* have an underscore character on the line. Demo: ``` >>> 'Grp25_QTY47 5'.split('_', 1)[-1] 'QTY47 ...
Python 2.7 on Windows, "assert main_name not in sys.modules, main_name" for all multiprocessing examples
16,405,687
6
2013-05-06T19:20:40Z
19,798,117
9
2013-11-05T20:17:55Z
[ "python", "windows", "python-2.7", "multiprocessing", "main" ]
There is following simple code: ``` from multiprocessing import Process, freeze_support def foo(): print 'hello' if __name__ == '__main__': freeze_support() p = Process(target=foo) p.start() ``` It works good on Linux or Windows with Python 3.3, but fails on Windows with Python 2.7. ``` Traceback (...
This is a known bug: <http://bugs.python.org/issue10845> Not sure if this will ever get ported to 2.7.X.
Is there an implication logical operator in python?
16,405,892
9
2013-05-06T19:34:50Z
16,405,931
12
2013-05-06T19:37:33Z
[ "python", "math", "logical-operators", "implication" ]
I would like to write a statement in python with logical implication. Something like: ``` if x => y: do_sth() ``` Of course, I know I could use: ``` if (x and y) or not x: do_sth() ``` But is there a logical operator for this in python?
`p => q` is the same as `not(p) or q`, so you could try that!
How to change json encoding behaviour for serializable python object?
16,405,969
37
2013-05-06T19:39:31Z
17,684,652
12
2013-07-16T18:49:46Z
[ "python", "json" ]
It is easy to change the format of an object which is not JSON serializable eg datetime.datetime. My requirement, for debugging purposes, is to alter the way some custom objects extended from base ones like `dict` and `list` , get serialized in json format . Code : ``` import datetime import json def json_debug_hand...
It seems that to achieve the behavior you want, with the given restrictions, you'll have to delve into the `JSONEncoder` class a little. Below I've written out a custom `JSONEncoder` that overrides the `iterencode` method to pass a custom `isinstance` method to `_make_iterencode`. It isn't the cleanest thing in the wor...
rendering forms with flask + wtform
16,406,496
5
2013-05-06T20:14:32Z
16,576,660
9
2013-05-15T23:30:04Z
[ "python", "flask", "wtforms" ]
code in question: ``` from flask import Blueprint, render_template, abort from flask.ext.wtf import Form import os from jinja2 import TemplateNotFound from models import Member from wtforms.ext.sqlalchemy.orm import model_form @simple_page.route('/register') def register(): form = model_form(Member, Form) retu...
You're passing a form **class** not a form **instance** to the template. The `model_form` method generates a new class dynamically, which can be re-used, extended, and otherwise used like any other form subclass. It's also quite un-necessary to generate this form class on every run of your view, so you can move this ca...
Python: building new list from existing by dropping every n-th element
16,406,772
2
2013-05-06T20:30:34Z
16,406,859
9
2013-05-06T20:36:11Z
[ "python", "list" ]
I want to build up a new list in which every n-th element of an initial list is left out, e.g.: from `['first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh']` make `['second', 'third', 'fifth', 'sixth'` because `n = 3` How to do that? Is it - first of all - correct to accomplish this by building up a new ...
``` >>> [s for (i,s) in enumerate(['first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh']) if i%3] ['second', 'third', 'fifth', 'sixth'] ``` The answer in a few steps: The `enumerate` function gives a list of tuples with the index followed by the item: ``` >>> list(enumerate(['first', 'second', 'third', ...
NumPy Matrix operation without copying
16,406,814
2
2013-05-06T20:32:52Z
16,406,968
9
2013-05-06T20:43:52Z
[ "python", "numpy" ]
How I can make, for example, matrix transpose, without making a copy of matrix object? As well, as other matrix operations ( subtract a matrix from the matrix, ...). Is it beneficial to do that?
Taking the transpose of an array does not make a copy: ``` >>> a = np.arange(9).reshape(3,3) >>> b = np.transpose(a) >>> a array([[0, 1, 2], [3, 4, 5], [6, 7, 8]]) >>> b array([[0, 3, 6], [1, 4, 7], [2, 5, 8]]) >>> b[0,1] = 100 >>> b array([[ 0, 100, 6], [ 1, 4, 7], [ ...
Python - ConfigParser - AttributeError: ConfigParser instance has no attribute '__getitem__'
16,407,329
4
2013-05-06T21:10:37Z
16,407,465
8
2013-05-06T21:19:54Z
[ "python", "ini", "configparser" ]
I am creating a quote of the day server. I am reading options from an INI file, whose text is below: ``` [Server] host = port = 17 [Quotes] file=quotes.txt ``` However, when I use ConfigParser, it gives me this error: ``` Traceback (most recent call last): File "server.py", line 59, in <module> Start() File...
After a quick read it seems like you're trying to read the data as if it's a dictionary, when you should use: `config.get(section, data)` EG: ``` ... config = ConfigParser() config.read(filename) ... configOptions.port = config.getint('Server', 'port') configOptions.host = config.get('Server', 'host') configOptions.q...
Extracting specific leaf value from nltk tree structure with Python
16,407,880
6
2013-05-06T21:51:42Z
16,408,655
10
2013-05-06T23:01:45Z
[ "python", "tree", "nltk" ]
I have some questions about NLTK's tree functions. I am trying to extract a certain word from the tree structure like the one given below. ``` test = Tree.parse('(ROOT(SBARQ(WHADVP(WRB How))(SQ(VBP do)(NP (PRP you))(VP(VB ask)(NP(DT a)(JJ total)(NN stranger))(PRT (RP out))(PP (IN on)(NP (DT a)(NN date)))))))') print ...
Although noun phrases can be nested inside other types of phrases, I believe most grammars always have nouns in noun phrases. So your question can probably be rephrased as: **How do you find the first and last nouns?** You can simply get all `tuple`s of words and POS tags and filter like this, ``` >>> [word for word,...
Psycopg2 image not found
16,407,995
45
2013-05-06T22:00:27Z
16,408,543
9
2013-05-06T22:48:30Z
[ "python", "osx", "postgresql", "psycopg2" ]
Trying to setup postgres with the postgres mac app and hit this error, which I haven't been able to solve. Any thoughts? ``` ImportError: dlopen(/Users/Craig/pyenv/mysite/lib/python2.7/site-packages/psycopg2/_psycopg.so, 2): Library not loaded: @executable_path/../lib/libssl.1.0.0.dylib Referenced from: /Applica...
In your bash environment before you load it, try this: ``` export DYLD_LIBRARY_PATH=/Library/PostgreSQL/x.y/lib ``` ..replacing the 'x.y' with the version on your system. ..be aware that setting this in your bash profile can interfere with other programs, as KindOfGuy noted. ..of course, if you're not running it fr...
Psycopg2 image not found
16,407,995
45
2013-05-06T22:00:27Z
16,634,121
71
2013-05-19T11:21:55Z
[ "python", "osx", "postgresql", "psycopg2" ]
Trying to setup postgres with the postgres mac app and hit this error, which I haven't been able to solve. Any thoughts? ``` ImportError: dlopen(/Users/Craig/pyenv/mysite/lib/python2.7/site-packages/psycopg2/_psycopg.so, 2): Library not loaded: @executable_path/../lib/libssl.1.0.0.dylib Referenced from: /Applica...
``` $ sudo ln -s /Library/PostgreSQL/9.2/lib/libssl.1.0.0.dylib /usr/lib $ sudo ln -s /Library/PostgreSQL/9.2/lib/libcrypto.1.0.0.dylib /usr/lib ``` I encountered this error while working on Django. I have it working on virtualenv with Django==1.3 but not on Django==1.5 where I have to issue the commands above. In OS...
Psycopg2 image not found
16,407,995
45
2013-05-06T22:00:27Z
16,740,552
16
2013-05-24T17:28:59Z
[ "python", "osx", "postgresql", "psycopg2" ]
Trying to setup postgres with the postgres mac app and hit this error, which I haven't been able to solve. Any thoughts? ``` ImportError: dlopen(/Users/Craig/pyenv/mysite/lib/python2.7/site-packages/psycopg2/_psycopg.so, 2): Library not loaded: @executable_path/../lib/libssl.1.0.0.dylib Referenced from: /Applica...
I found a solution that worked for me when dealing with a similar issue on rails. Add the following to your .bash\_profile, .bash\_rc, or equivalent: ``` export DYLD_FALLBACK_LIBRARY_PATH=/Applications/Postgres.app/Contents/MacOS/lib:$DYLD_LIBRARY_PATH ``` (Assuming you installed Postgres.app in the default location)...
Psycopg2 image not found
16,407,995
45
2013-05-06T22:00:27Z
25,042,979
9
2014-07-30T17:13:49Z
[ "python", "osx", "postgresql", "psycopg2" ]
Trying to setup postgres with the postgres mac app and hit this error, which I haven't been able to solve. Any thoughts? ``` ImportError: dlopen(/Users/Craig/pyenv/mysite/lib/python2.7/site-packages/psycopg2/_psycopg.so, 2): Library not loaded: @executable_path/../lib/libssl.1.0.0.dylib Referenced from: /Applica...
This problem cost me the whole morning to solve. I found the discussion on <http://initd.org/psycopg/articles/2010/11/11/links-about-building-psycopg-mac-os-x/> really helpful. Thanks to Jurie's answer, the solution to my problem (in Mac) is as below: 1. Install openssl 1.0.0 using brew: ``` brew install opens...
Is it possible to run native python code in chrome?
16,409,138
10
2013-05-06T23:59:26Z
16,409,167
12
2013-05-07T00:03:17Z
[ "javascript", "python", "google-chrome", "sandbox", "brython" ]
I was wondering if it is **possible to run native python code in chrome** instead of javascript. I have seen projects like [pyjs](http://pyjs.org/) or [brython](https://code.google.com/p/brython/), but what they do is compile python to javascript. While those are great projects a problem with this approach is always th...
Python is a programming language, you can't *run native code* of a programming language. You can however, run programs written in python in the browser. ### So can I run python code in the browser or not? **Update June 2013:** The Brython project is now available letting you run Python 3 code in your browser. You can...
How can I order a list of connections
16,409,486
9
2013-05-07T00:45:28Z
16,409,652
19
2013-05-07T01:06:39Z
[ "python", "algorithm", "graph-theory", "graph-traversal" ]
I currently have a list of connections stored in a list where each connection is a directed link that connects two points and no point ever links to more than one point or is linked to by more than one point. For example: ``` connections = [ (3, 7), (6, 5), (4, 6), (5, 3), (7, 8), (1, 2), (2, 1) ] ``` Should produce:...
## Algorithm for a Solution You're looking for a [topological sort](http://en.wikipedia.org/wiki/Topological_sorting) algorithm: ``` from collections import defaultdict def topological_sort(dependency_pairs): 'Sort values subject to dependency constraints' num_heads = defaultdict(int) # num arrows pointing...
keyboard interrupt with with python gtk?
16,410,852
12
2013-05-07T03:43:49Z
16,486,080
22
2013-05-10T15:48:49Z
[ "python", "python-3.x", "gtk", "try-catch" ]
So just like the question says, I'm trying to let keyboard interrupts happens while Gtk.main() is in progress, however, it just doesn't seem to notice that the keyboard interrupt happens until after the function is done. So I tried sticking Gtk.main() in a separate thread, and have the main thread find the keyboard in...
because of <https://bugzilla.gnome.org/show_bug.cgi?id=622084> gtk applications written using pygobject will not close themselves when using `Ctrl + C` on the terminal. to work around it, you can install a Unix signal handler like this: ``` if __name__ == '__main__': import signal signal.signal(signal.SIGINT,...
Parse a Pandas column to Datetime
16,412,099
17
2013-05-07T05:54:24Z
24,446,716
34
2014-06-27T07:53:45Z
[ "python", "python-2.7", "numpy", "scipy", "pandas" ]
I have a `DataFrame` with column named `date`. How can we convert/parse the 'date' column to a `DateTime` object? I loaded the date column from a Postgresql database using `sql.read_frame()`. An example of the `date` column is `2013-04-04`. What I am trying to do is to select all rows in a dataframe that has their da...
Pandas is aware of the object datetime but when you use some of the import functions it is taken as a string. So what you need to do is make sure the column is set as the datetime type not as a string. Then you can make your query. ``` df['date'] = pd.to_datetime(df['date']) df_masked = df[(df['date'] > datetime.date...
Python 2.7__unicode__(self) not working
16,412,358
3
2013-05-07T06:14:21Z
16,412,373
9
2013-05-07T06:15:35Z
[ "python", "django" ]
**unicode**(self) is not working for me. I can still see 'Name Object' in the admin. My code is as follows: ``` import datetime # standard python datetime module from django.db import models # Djangos time-zone-related utilities from django.utils import timezone class Name(models.Model): name = models.CharField(m...
The problem you have is that you need to define the `__unicode__` method within the class definition. ``` import datetime # standard python datetime module from django.db import models # Djangos time-zone-related utilities from django.utils import timezone class Name(models.Model): name = models.CharField(max_len...
Python: sorting dictionary of dictionaries
16,412,563
7
2013-05-07T06:29:08Z
16,412,601
16
2013-05-07T06:31:29Z
[ "python", "sorting", "dictionary" ]
I have a dict (which is also a key of a larger dict) of dicts that looks like ``` wd[wc][dist][True]={'course': {'#': 1, 'Fisher': 4.0}, 'i': {'#': 1, 'Fisher': -0.2222222222222222}, 'of': {'#': 1, 'Fisher': 2.0}, 'will': {'#': 1, 'Fisher': 3.5}} ``` I want to sort the key words (at the highest level) by their cor...
You can't sort a dict, but can get a sorted list of keys, values or (key,values) pairs. ``` >>> dic = {'i': {'Fisher': -0.2222222222222222, '#': 1}, 'of': {'Fisher': 2.0, '#': 1}, 'will': {'Fisher': 3.5, '#': 1}, 'course': {'Fisher': 4.0, '#': 1}} >>> sorted(dic.items(), key=lambda x: x[1]['Fisher'], reverse=True) [(...
Trying to use hex() without 0x
16,414,559
27
2013-05-07T08:28:37Z
16,414,603
60
2013-05-07T08:30:24Z
[ "python" ]
The `hex()` function in python, puts the leading characters `0x` in front of the number. Is there anyway to tell it NOT to put them? So `0xfa230` will be `fa230`. The code is ``` import fileinput f = open('hexa', 'w') for line in fileinput.input(['pattern0.txt']): f.write(hex(int(line))) f.write('\n') ```
``` >>> format(3735928559, 'x') 'deadbeef' ```
Trying to use hex() without 0x
16,414,559
27
2013-05-07T08:28:37Z
16,414,606
26
2013-05-07T08:30:30Z
[ "python" ]
The `hex()` function in python, puts the leading characters `0x` in front of the number. Is there anyway to tell it NOT to put them? So `0xfa230` will be `fa230`. The code is ``` import fileinput f = open('hexa', 'w') for line in fileinput.input(['pattern0.txt']): f.write(hex(int(line))) f.write('\n') ```
Use this code: ``` '{:x}'.format(int(line)) ``` it allows you to specify a number of digits too: ``` '{:06x}'.format(123) # '00007b' ``` For Python 2.6 use ``` '{0:x}'.format(int(line)) ``` or ``` '{0:06x}'.format(int(line)) ```
Set HTTP headers for all requests in a Flask test
16,416,001
3
2013-05-07T09:46:53Z
16,416,587
7
2013-05-07T10:18:12Z
[ "python", "flask" ]
I'm using Flask and have endpoints which require authorization (and occasionally other app-specific headers). In my tests use the `test_client` function to create a client and then do the various get, put, delete calls. All of these calls will require authorization, and other headers to be added. How can I setup the te...
The [`Client`](https://github.com/mitsuhiko/werkzeug/blob/master/werkzeug/test.py#L575) class takes the same arguments as the [`EnvironBuilder`](https://github.com/mitsuhiko/werkzeug/blob/master/werkzeug/test.py#L186) class, among which is the [`headers`](https://github.com/mitsuhiko/werkzeug/blob/master/werkzeug/test....
How can I modify Procfile to run Gunicorn process in a non-standard folder on Heroku?
16,416,172
28
2013-05-07T09:56:17Z
16,430,579
30
2013-05-08T00:05:09Z
[ "python", "django", "heroku", "wsgi", "gunicorn" ]
I'm new to heroku and gunicorn so I'm not sure how this works. But I've done some searching and I think I'm close to deploying my Django app (1.5.1). So I know I need a Procfile which has ``` web: gunicorn app.wsgi ``` Because my directories are a bit different. I can't run gunicorn in the root directory ``` app_pro...
Try: ``` web: gunicorn --pythonpath app app.wsgi ```
How can I modify Procfile to run Gunicorn process in a non-standard folder on Heroku?
16,416,172
28
2013-05-07T09:56:17Z
19,671,818
18
2013-10-30T00:44:42Z
[ "python", "django", "heroku", "wsgi", "gunicorn" ]
I'm new to heroku and gunicorn so I'm not sure how this works. But I've done some searching and I think I'm close to deploying my Django app (1.5.1). So I know I need a Procfile which has ``` web: gunicorn app.wsgi ``` Because my directories are a bit different. I can't run gunicorn in the root directory ``` app_pro...
As @Graham Dumpleton stated in his answer, the OP's problem could be solved by modifying his Procfile to the following: `web: gunicorn --pythonpath app app.wsgi` **Why this works:** * Remember, that the Procfile is simply used by Heroku to start processes. In this case, gunicorn processes. * Gunicorn's `--pythonpath...
Check if a value in a list is equal to some number
16,417,324
2
2013-05-07T10:58:43Z
16,417,355
7
2013-05-07T11:00:15Z
[ "python" ]
I've got a list of data: ``` [[0, 3], [1, 2], [2, 1], [3, 0]] ``` And I'm trying to check if any of the individual numers is equal to 3, and if so return which element, so list[0],list[3] e.t.c within the original list contains this value 3. I've gotten as far as: ``` for i in range(0, len(gcounter_selection)): f...
If I understood correctly, you're looking for list comprehensions: ``` value = 3 lst = [[0, 3], [1, 2], [2, 1], [3, 0]] items = [x for x in lst if value in x] print(items) #[[0, 3], [3, 0]] ``` To get elements' positions instead of just elements, add `enumerate`: ``` indexes = [n for n, x in enumerate(lst) if value ...
Matplotlib fill beetwen multiple lines
16,417,496
8
2013-05-07T11:08:38Z
16,421,444
10
2013-05-07T14:21:08Z
[ "python", "matplotlib" ]
I would like to fill between 3 lines in matplotlib.pyplot but unfortunately the `fill_between` gives me opportunity to fill between only two lines. Any ideas how to deal with this? Edit: Ok, I did not explain what I really mean since I cannot add the picture with my current reputation so maybe in that way: I try to ...
To use [`fill_between`](http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.fill_between), specify the X values first, than the two Y sets that you want to "fill between". An example is show below: ``` import pylab as plt import numpy as np X = np.linspace(0,3,200) Y1 = X**2 + 3 Y2 = np.exp(X) + 2 Y3 = np.co...
Matplotlib fill beetwen multiple lines
16,417,496
8
2013-05-07T11:08:38Z
16,426,194
16
2013-05-07T18:36:45Z
[ "python", "matplotlib" ]
I would like to fill between 3 lines in matplotlib.pyplot but unfortunately the `fill_between` gives me opportunity to fill between only two lines. Any ideas how to deal with this? Edit: Ok, I did not explain what I really mean since I cannot add the picture with my current reputation so maybe in that way: I try to ...
If you start the plot in point (0, 0), and therefore do not need to consider the area of the polygon not in the first quadrant, then this should do the trick in this particular situation: ``` import matplotlib.pyplot as plt import numpy as np x = np.arange(0,10,0.1) # The lines to plot y1 = 4 - 2*x y2 = 3 - 0.5*x y3...
How to speed up py.test
16,417,546
17
2013-05-07T11:11:51Z
19,675,357
8
2013-10-30T06:31:23Z
[ "python", "py.test" ]
Is there some way to speed up the repeated execution of `py.test`? It seems to spend a lot of time collecting tests, even if I specify which files to execute on the command line. I know it isn't a disk speed issue either since running pyflakes across all the .py files is very fast.
Using the `norecursedirs` option in pytest.ini or tox.ini can save a lot of collection time, depending on what other files you have in your working directory. My collection time is roughly halved for a suite of 300 tests when I have that in place (0.34s vs 0.64s). If you're already using [tox](http://tox.readthedocs.o...
Divide two lists in python
16,418,415
12
2013-05-07T11:57:06Z
16,418,472
10
2013-05-07T11:59:49Z
[ "python", "list" ]
I have 2 lists `a` and `b`: ``` a = [3, 6, 8, 65, 3] b = [34, 2, 5, 3, 5] c gets [3/34, 6/2, 8/5, 65/3, 3/5] ``` Is it possible to obtain their ratio in Python, like in variable `c` above? I tried to type: ``` a/b ``` And I get an error: ``` Traceback (most recent call last): File "<stdin...
``` >>> from __future__ import division # floating point division in Py2x >>> a=[3,6,8,65,3] >>> b=[34,2,5,3,5] >>> [x/y for x, y in zip(a, b)] [0.08823529411764706, 3.0, 1.6, 21.666666666666668, 0.6] ``` Or in `numpy` you can do `a/b` ``` >>> import numpy as np >>> a=np.array([3,6,8,65,3], dtype=np.float) >>> b=np.a...
Divide two lists in python
16,418,415
12
2013-05-07T11:57:06Z
16,418,739
13
2013-05-07T12:12:01Z
[ "python", "list" ]
I have 2 lists `a` and `b`: ``` a = [3, 6, 8, 65, 3] b = [34, 2, 5, 3, 5] c gets [3/34, 6/2, 8/5, 65/3, 3/5] ``` Is it possible to obtain their ratio in Python, like in variable `c` above? I tried to type: ``` a/b ``` And I get an error: ``` Traceback (most recent call last): File "<stdin...
The built-in [*map()*](http://docs.python.org/2.7/library/functions.html#map) function makes short work of these kinds of problems: ``` >>> from operator import truediv >>> a=[3,6,8,65,3] >>> b=[34,2,5,3,5] >>> map(truediv, a, b) [0.08823529411764706, 3.0, 1.6, 21.666666666666668, 0.6] ```
Increase distance between title and plot in matplolib?
16,419,670
5
2013-05-07T12:58:02Z
16,420,635
7
2013-05-07T13:43:09Z
[ "python", "matplotlib", "plot", "title", "margins" ]
I have a simple plot in matplotlib and I would like to increase the distance between the title and the plot (without using `suptitle` because it does not work on the version I use on a server). How to do that ?
There doesn't seem to be a clean way to set this directly (but might be worth a feature request to add that), however the title is just a `text` artist, so you can reach in and change it. ``` #ax = plt.gca() ttl = ax.title ttl.set_position([.5, 1.05]) #plt.draw() ``` should do the trick. Tune the `1.05` to your likin...
What do the three arrow (">>>") signs mean in python?
16,420,078
10
2013-05-07T13:16:11Z
16,421,806
16
2013-05-07T14:37:57Z
[ "python", "python-2.7" ]
So this is probably a dumb question, but I have now been searching for quite some time, and I haven't been able to figure out what they do even though I see them often in source-codes.
You won't see it in source code, it's probably documentation. It indicates an interactive session, and things typed into the 'interpreter' are marked with this. Output is shown without the arrows. In fact, the [python documentation](http://docs.python.org/2/tutorial/interpreter.html#interactive-mode) often has a butto...
What do the three arrow (">>>") signs mean in python?
16,420,078
10
2013-05-07T13:16:11Z
16,421,999
7
2013-05-07T14:45:59Z
[ "python", "python-2.7" ]
So this is probably a dumb question, but I have now been searching for quite some time, and I haven't been able to figure out what they do even though I see them often in source-codes.
'>>>' is the prompt of the interactive Python interpreter, meaning that the interpreter is ready to get Python statements typed in. It's occuring quite often in examples within the documentation of a Python program, in order to show which commands can be used and what will be the result of giving these commands to the ...
How to make Python script run as service?
16,420,092
18
2013-05-07T13:16:45Z
16,420,140
36
2013-05-07T13:19:17Z
[ "python", "linux", "python-2.7", "centos" ]
I want to run a python script in a CENTOS server: ``` #!/usr/bin/env python import socket try: import thread except ImportError: import _thread as thread #Py3K changed it. class Polserv(object): def __init__(self): self.numthreads = 0 self.tidcount = 0 self.port = 843 ...
I use [this](https://web.archive.org/web/20160305151936/http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/) code to daemonize my applications. It allows you `start/stop/restart` the script using the following commands. ``` python myscript.py start python myscript.py stop python myscript.py res...
How to make Python script run as service?
16,420,092
18
2013-05-07T13:16:45Z
16,420,472
37
2013-05-07T13:36:07Z
[ "python", "linux", "python-2.7", "centos" ]
I want to run a python script in a CENTOS server: ``` #!/usr/bin/env python import socket try: import thread except ImportError: import _thread as thread #Py3K changed it. class Polserv(object): def __init__(self): self.numthreads = 0 self.tidcount = 0 self.port = 843 ...
1) Install the `supervisor` package ([more verbose instructions here](http://supervisord.org/installing.html)): ``` sudo apt-get install supervisor ``` 2) Create a config file for your daemon at `/etc/supervisor/conf.d/flashpolicyd.conf`: ``` [program:flashpolicyd] directory=/path/to/project/root environment=ENV_VAR...
What is the difference between np.sum and np.add.reduce?
16,420,097
13
2013-05-07T13:17:04Z
16,421,245
11
2013-05-07T14:13:01Z
[ "python", "numpy" ]
What is the difference between `np.sum` and `np.add.reduce`? While [the docs](http://docs.scipy.org/doc/numpy/reference/generated/numpy.ufunc.reduce.html) are quite explicit: > For example, add.reduce() is equivalent to sum(). The performance of the two seems to be quite different: for relatively small array sizes ...
Short answer: when the argument is a numpy array, `np.sum` ultimately calls `add.reduce` to do the work. The overhead of handling its argument and dispatching to `add.reduce` is why `np.sum` is slower. Longer answer: `np.sum` is defined in [`numpy/core/fromnumeric.py`](https://github.com/numpy/numpy/blob/master/numpy/...
Python statsmodels OLS: how to save learned model to file
16,420,407
3
2013-05-07T08:53:00Z
16,513,935
9
2013-05-13T01:57:26Z
[ "python", "least-squares", "statsmodels" ]
I am trying to learn an ordinary least squares model using Python's statsmodels library, as described [here](http://statsmodels.sourceforge.net/stable/generated/statsmodels.regression.linear_model.OLS.html#statsmodels.regression.linear_model.OLS). sm.OLS.fit() returns the learned model. Is there a way to save it to th...
The models and results instances all have a save and load method, so you don't need to use the pickle module directly. **Edit** to add an example: ``` import statsmodels.api as sm data = sm.datasets.longley.load_pandas() data.exog['constant'] = 1 results = sm.OLS(data.endog, data.exog).fit() results.save("longley_...
Parallelism in Julia. Features and Limitations
16,420,792
35
2013-05-07T13:50:32Z
16,423,573
51
2013-05-07T16:01:05Z
[ "python", "multithreading", "parallel-processing", "julia-lang" ]
In their [arXiv paper](http://arxiv.org/abs/1209.5145), the original authors of Julia mention the following: > `2.14 Parallelism`. > Parallel execution is provided by a message-based multi-processing system implemented in Julia in the standard library. > The language design supports the implementation of such librarie...
"Native threads" are separate contexts of execution, managed by the operating system kernel, accessing a shared memory space and potentially executing concurrently on separate cores. Compare this with separate processes, which may execute concurrently on multiple cores but have separate memory spaces. Making sure that ...
Multiply all columns in a Pandas dataframe together
16,423,736
5
2013-05-07T16:09:59Z
16,423,791
12
2013-05-07T16:12:53Z
[ "python", "python-2.7", "numpy", "scipy", "pandas" ]
Is it possible to multiply all the columns in a `Pandas.DataFrame` together to get a single value for every row in the DataFrame? As an example, using ``` df = pd.DataFrame(np.random.randn(5,3)*10) ``` I want a new `DataFrame` `df2` where `df2.ix[x,0]` will have the value of `df.ix[x,0] * df.ix[x,1] * df.ix[x,2]`. ...
You could use [`DataFrame.prod()`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.prod.html#pandas.DataFrame.prod): ``` >>> df = pd.DataFrame(np.random.randint(1, 10, (5, 3))) >>> df 0 1 2 0 7 7 5 1 1 8 6 2 4 8 4 3 2 9 5 4 3 8 7 >>> df.prod(axis=1) 0 245 1 48 2 128...
string representation of a numpy array with commas separating its elements
16,423,774
12
2013-05-07T16:11:46Z
16,423,805
22
2013-05-07T16:13:35Z
[ "python", "numpy" ]
I have a numpy array, for example: ``` points = np.array([[-468.927, -11.299, 76.271, -536.723], [-429.379, -694.915, -214.689, 745.763], [ 0., 0., 0., 0. ]]) ``` if I print it or turn it into a string with str() I get: ``` print w_points [[-468.927 -1...
Try using `repr` ``` >>> import numpy as np >>> points = np.array([[-468.927, -11.299, 76.271, -536.723], ... [-429.379, -694.915, -214.689, 745.763], ... [ 0., 0., 0., 0. ]]) >>> print repr(points) array([[-468.927, -11.299, 76.271, -536.723], ...
Putting gif image in a canvas with Tkinter
16,424,091
13
2013-05-07T16:30:03Z
16,424,553
22
2013-05-07T16:56:04Z
[ "python", "image", "tkinter", "tkinter-canvas" ]
This code works: ``` import tkinter root = tkinter.Tk() canvas = tkinter.Canvas(root) canvas.grid(row = 0, column = 0) photo = tkinter.PhotoImage(file = './test.gif') canvas.create_image(0,0, image=photo) root.mainloop() ``` It shows me the image. Now, this code compiles, but doesn't show me the image, and I don't ...
The variable `photo` is a local variable which gets garbage collected after the class is instantiated. Save a reference to the photo, for example: ``` self.photo = tkinter.PhotoImage(...) ``` If you do a Google search on "tkinter image doesn't display", the first result is this: <http://effbot.org/pyfaq/why-do-my-tk...
Pandas: Setting no. of max rows
16,424,493
27
2013-05-07T16:52:02Z
16,433,953
54
2013-05-08T06:20:24Z
[ "python", "formatting", "pandas", "ipython-notebook" ]
I have a problem viewing the following `DataFrame`: ``` n = 100 foo = DataFrame(index=range(n)) foo['floats'] = np.random.randn(n) foo ``` the problem is that it does not print all rows per default in ipython notebook, but I have to slice to view the resulting rows. Even the following option does not change the outpu...
For version 0.11.0 you need to change both display.heigth and display.max\_rows. ``` pd.set_option('display.height', 500) pd.set_option('display.max_rows', 500) ``` See also `pd.describe_option('display')`
Overriding __setattr__ at runtime
16,426,141
12
2013-05-07T18:26:05Z
16,426,447
19
2013-05-07T18:52:44Z
[ "python" ]
I am trying to override the `__setattr__` method of a Python class, since I want to call another function each time an instance attribute changes its value. However, I don't want this behaviour in the `__init__` method, because during this initialization I set some attributes which are going to be used later: So far I...
Unfortunately, there's no way to "override, after init" python special methods; as a side effect of how that lookup works. The crux of the problem is that python doesn't actually look at the instance; except to get its class; before it starts looking up the special method; so there's no way to get the object's state to...
How can I test if a number is a square number in Python?
16,426,396
3
2013-05-07T18:49:24Z
16,426,418
13
2013-05-07T18:50:43Z
[ "python" ]
My code is ``` if graph == square_grid and type(math.sqrt(nodes)) is not int: print "Your netork can't have that number of nodes" ``` Of course this doesn't work because math.sqrt always returns a float. How can I do this?
One way is ``` int(math.sqrt(x)) ** 2 == x ```
How can I test if a number is a square number in Python?
16,426,396
3
2013-05-07T18:49:24Z
16,426,443
7
2013-05-07T18:52:32Z
[ "python" ]
My code is ``` if graph == square_grid and type(math.sqrt(nodes)) is not int: print "Your netork can't have that number of nodes" ``` Of course this doesn't work because math.sqrt always returns a float. How can I do this?
Because math.sqrt always returns a float, you can use the built in `is_integer` method ``` def is_square(x): answer = math.sqrt(x) return answer.is_integer() ``` this will return `True` if `x` is a square and `False` if it's not ``` >>> is_square(25) True >>> is_square(14) False ```
Python, best way to write a sum of two for loops
16,427,663
9
2013-05-07T20:08:52Z
16,427,744
10
2013-05-07T20:13:59Z
[ "python", "for-loop", "coding-style" ]
Normally I know we can do `sum([func(x,x) for x in i])`, but I got an if check and two for loops, so what is the most pythonic way to write the code bellow. you can assume that similarity will return a number regardless of what type you give it. You can also assume that it will really only get ints and chars. ``` x = ...
Maybe something like this: ``` x=0 if isinstance(a,(dict,list,tuple)): x=sum(similarity(i,j) for i in a for j in b) ``` Or: ``` x=(sum(similarity(i,j) for i in a for j in b) if isinstance(a,(dict,list,tuple)) else 0) ``` Or (assuming that a string, set or some other iterable type does not break your functio...
Python, best way to write a sum of two for loops
16,427,663
9
2013-05-07T20:08:52Z
16,427,779
9
2013-05-07T20:16:05Z
[ "python", "for-loop", "coding-style" ]
Normally I know we can do `sum([func(x,x) for x in i])`, but I got an if check and two for loops, so what is the most pythonic way to write the code bellow. you can assume that similarity will return a number regardless of what type you give it. You can also assume that it will really only get ints and chars. ``` x = ...
You probably want something like: ``` if isinstance(a, (dict, list, tuple)): x = sum(similarity(i, j) for i in a for j in b) else: x = 0 ```
Python, best way to write a sum of two for loops
16,427,663
9
2013-05-07T20:08:52Z
16,427,897
7
2013-05-07T20:22:29Z
[ "python", "for-loop", "coding-style" ]
Normally I know we can do `sum([func(x,x) for x in i])`, but I got an if check and two for loops, so what is the most pythonic way to write the code bellow. you can assume that similarity will return a number regardless of what type you give it. You can also assume that it will really only get ints and chars. ``` x = ...
You could use some functions from `itertools`, perhaps: ``` from itertools import starmap, product x = sum(starmap(similarity, product(a, b))) ``` and as others noted, may as well pass a tuple of types to `isinstance()` if you really need to check.
A good way to make long strings wrap to newline in Python? (3.x)
16,430,200
11
2013-05-07T23:22:44Z
16,430,216
25
2013-05-07T23:25:11Z
[ "python", "string" ]
In my project, I have a bunch of strings that are read in from a file. Most of them, when printed in the command console, exceed 80 characters in length and wrap around, looking ugly. I want to be able to have Python read the string, then test if it is over 75 characters in length. If it is, then split the string up i...
You could use `textwrap` module: ``` >>> import textwrap >>> strs = "In my project, I have a bunch of strings that are read in from a file. Most of them, when printed in the command console, exceed 80 characters in length and wrap around, looking ugly." >>> print(textwrap.fill(strs, 20)) In my project, I have a bunch ...
virtualenv and subprocess.call() in mixed Python 2.7/3.3 environment
16,430,609
8
2013-05-08T00:08:40Z
16,430,813
16
2013-05-08T00:32:36Z
[ "python", "subprocess", "virtualenv", "travis-ci" ]
For some functional tests, I invoke a couple of utilities directly from the project directory, using Python's `subprocess.call` (or `check_call` which invokes the latter). This works well when the libraries (PyYAML in particular) are installed globally. Running in a virtualenv, such as under Travis-CI, causes problems,...
If you pass in a copy of your environment variables and use the current Python interpreter as the target of the subprocess, the virtualenv environment should be preserved. Something like this: ``` subprocess.call([sys.executable, 'yourscript.py'], env=os.environ.copy()) ```
How to check in Python if string is in a text file and print the line?
16,432,203
3
2013-05-08T03:30:04Z
16,432,228
7
2013-05-08T03:34:34Z
[ "python", "string", "text", "syntax" ]
What I am trying to do is to check whether this string is found in the text file. If it does, I want it to printout that line, else printout a message. I have implemented this code so far: ``` def check_string(string): w = raw_input("Input the English word: ") if w in open('example.txt').read(): ...
You should try something like this: ``` import re def check_string(): #no need to pass arguments to function if you're not using them w = raw_input("Input the English word: ") #open the file using `with` context manager, it'll automatically close the file for you with open("example.txt") as f: ...
SocketServer: getting rid of '[Errno 98] Address already in use'
16,433,522
10
2013-05-08T05:47:31Z
16,641,793
15
2013-05-20T02:41:38Z
[ "python", "python-2.7", "socketserver" ]
I've been looking at the documentation for [`SocketServer`](http://docs.python.org/2/library/socketserver.html). I copied the TCP server code from the documentation and it runs fine. However, I noticed that whenever I ctrl-c'ed out of the program in my terminal, and then tried to run it again, I would get the following...
``` ... SocketServer.TCPServer.allow_reuse_address = True server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler) ... ``` `allow_reuse_address` should be on the class, not on the instance.
In the Pyramid web framework, how do I source sensitive settings into development.ini / production.ini from an external file?
16,435,274
11
2013-05-08T07:44:48Z
16,446,566
17
2013-05-08T17:17:33Z
[ "python", "version-control", "configuration-files", "pyramid" ]
I'd like to keep `development.ini` and `production.ini` under version control, but for security reason would not want the `sqlalchemy.url` connection string to be stored, as this would contain the username and password used for the database connection. What's the canonical way, in Pyramid, of sourcing this setting fro...
I looked into this a lot and played with a lot of different approaches. However, Pyramid is so flexible, and the `.ini` config parser is so minimal in what it does for you, that there doesn't seem to be a de facto answer. In my scenario, I tried having a `production.example.ini` in version control at first that got co...
Pandas: Get label for value in Series Object
16,435,697
7
2013-05-08T08:11:56Z
16,435,752
8
2013-05-08T08:15:39Z
[ "python", "pandas", "series" ]
How is it possible to retrieve the labe of a particular value in a pandas Series object: For example: ``` labels = ['a', 'b', 'c', 'd', 'e'] s = Series (arange(5) * 4 , labels) ``` Which produces the Series: ``` a 0 b 4 c 8 d 12 e 16 dtype: int64 ``` How is it possible to get the label of value '...
You can get the subseries by: ``` In [90]: s[s==12] Out[90]: d 12 dtype: int64 ``` Moreover, you can get those labels by ``` In [91]: s[s==12].index Out[91]: Index([d], dtype=object) ```
How can i create the empty json object in python
16,436,133
3
2013-05-08T08:38:08Z
16,436,166
10
2013-05-08T08:40:14Z
[ "python", "json" ]
I have this code ``` json.loads(request.POST.get('mydata',dict())) ``` But i get this error ``` No JSON object could be decoded ``` I just want that if don't have `mydata` in POST then i don't get that error
Simply: ``` json.loads(request.POST.get('mydata', '{}')) ``` Or: ``` data = json.loads(request.POST['mydata']) if 'mydata' in request.POST else {} ``` Or: ``` if 'mydata' in request.POST: data = json.loads(request.POST['mydata']) else: data = {} # or data = None ```
Generate all possible numbers with mask
16,437,159
2
2013-05-08T09:30:41Z
16,437,297
10
2013-05-08T09:37:45Z
[ "python", "combinations", "mask" ]
Let's say I have a string like: ``` a = "123**7*9" ``` And I need to generate all possible combination of it: ``` 12300709...12399799 ``` How to do that with Python?
You could use `itertools.product` and string formatting: ``` >>> from itertools import product >>> strs = "123**7*9" >>> c = strs.count("*") #count the number of "*"'s >>> strs = strs.replace("*","{}") #replace '*'s with '{}' for formatting >>> for x in product("0123456789",repeat=c): ... print str...
Is it possible to print without new line or space?
16,438,744
4
2013-05-08T10:49:46Z
16,438,781
10
2013-05-08T10:51:49Z
[ "python", "printing" ]
Let's say that I want to print 'hello' by 2 different print statements. Like: ``` print "hel" print "lo" ``` But python automatically prints new line so if we want it in the same line we need to - ``` print "hel"**,** ``` Here's the problem - the , makes a space and I want it connected. Thanks.
You can use the `print` *function* ``` >>> from __future__ import print_function >>> print('hel', end=''); print('lo', end='') hello ``` Obviously the semicolon is in the code only to show the result in the interactive interpreter. The `end` keyword parameter to the `print` function specifies what you want to print ...
Can't pickle defaultdict
16,439,301
27
2013-05-08T11:20:00Z
16,439,531
9
2013-05-08T11:30:44Z
[ "python", "pickle", "defaultdict" ]
I have a defaultdict that looks like this: ``` dict1 = defaultdict(lambda: defaultdict(int)) ``` The problem is, I can't pickle it using cPickle. One of the solution that I found here is to use module-level function instead of a lambda. My question is, what is module-level function? How can I use the dictionary with ...
Pickle wants to store all the instance attributes, and `defaultdict` instances store a reference to the `default` callable. Pickle recurses over each instance attribute. Pickle cannot handle lambdas; pickle only ever handles data, not code, and lambdas contain code. Functions *can* be pickled, but just like class defi...
Can't pickle defaultdict
16,439,301
27
2013-05-08T11:20:00Z
16,439,720
33
2013-05-08T11:40:01Z
[ "python", "pickle", "defaultdict" ]
I have a defaultdict that looks like this: ``` dict1 = defaultdict(lambda: defaultdict(int)) ``` The problem is, I can't pickle it using cPickle. One of the solution that I found here is to use module-level function instead of a lambda. My question is, what is module-level function? How can I use the dictionary with ...
In addition to [Martijn's explanation](http://stackoverflow.com/a/16439531/142637): A module-level function is a function which is defined at module level, that means it is not an instance method of a class, it's not nested within another function, and it is a "real" function with a name, not a lambda function. So, t...
Python 2.7: test if characters in a string are all Chinese characters
16,441,633
7
2013-05-08T13:10:32Z
16,442,115
10
2013-05-08T13:32:51Z
[ "python", "python-2.7" ]
The following code tests if characters in a string are all Chinese characters. It works for Python 3 but not for Python 2.7. How do I do it in Python 2.7? ``` for ch in name: if ord(ch) < 0x4e00 or ord(ch) > 0x9fff: return False ```
``` # byte str (you probably get from GAE) In [1]: s = """Chinese (汉语/漢語 Hànyǔ or 中文 Zhōngwén) is a group of related language varieties, several of which are not mutually intelligible,""" # unicode str In [2]: us = u"""Chinese (汉语/漢語 Hànyǔ or 中文 Zhōngwén) is a group of related...
Using generators to read two files in time priority
16,442,190
2
2013-05-08T13:36:14Z
16,442,444
10
2013-05-08T13:48:13Z
[ "python", "time", "generator" ]
I just read up on generators and was wondering how you would use generators in this: Say there are two files and each file has a time column. Each file is sorted by ascending time, and I'm looking to grab lines in these files using time priority. Instead of writing an unsophisticated expression(see below) I was wonde...
Use [heapq.merge](http://docs.python.org/2/library/heapq.html) ``` def generate_timeline(file): for line in file: time1 = extract_time_from_line(line) yield time1, line for (time1, line) in heapq.merge(generate_timeline(file1), generate_timeline(file2)): process(line) ```
flask application timeout with amazon load balancer
16,444,190
8
2013-05-08T15:09:41Z
17,648,222
7
2013-07-15T06:48:08Z
[ "python", "flask", "gunicorn", "werkzeug" ]
I'm trying to use a Flask application behind an Amazon Load Balancer and the Flask threads keep timing out. It appears that the load balancer is sending a `Connection: keep-alive` header and this is causing the Flask process to never return (or takes a long time). With gunicorn in front the processes are killed and new...
The solution I have now is using gunicorn as a wrapper around the flask application. For the `worker_class` I am using `eventlet` with several workers. This combination seems stable and responsive. Gunicorn is also configured for HTTPS. *I assume it is a defect in Flask that causes the problem and this is an effective...
Python Numpy - Complex Numbers - Is there a function for Polar to Rectangular conversion?
16,444,719
7
2013-05-08T15:36:19Z
16,445,006
7
2013-05-08T15:51:16Z
[ "python", "numpy", "complex-numbers" ]
Is there a built-in Numpy function to convert a complex number in polar form, a magnitude and an angle (degrees) to one in real and imaginary components? Clearly I could write my own but it seems like the type of thing for which there is an optimised version included in some module? More specifically, I have an array...
There isn't a function to do exactly what you want, but there is **[angle](http://docs.scipy.org/doc/numpy/reference/generated/numpy.angle.html#numpy.angle)**, which does the hardest part. So, for example, one could define two functions: ``` def P2R(radii, angles): return radii * exp(1j*angles) def R2P(x): re...
Binary representation of float in Python (bits not hex)
16,444,726
26
2013-05-08T15:37:09Z
16,444,778
26
2013-05-08T15:40:01Z
[ "python", "binary", "floating-point" ]
How to get the string as binary IEEE 754 representation of a 32 bit float? **Example** 1.00 -> '00111111100000000000000000000000'
You can do that with the `struct` package: ``` import struct def binary(num): return ''.join(bin(ord(c)).replace('0b', '').rjust(8, '0') for c in struct.pack('!f', num)) ``` That packs it as a network byte-ordered float, and then converts each of the resulting bytes into an 8-bit binary representation and concate...
Binary representation of float in Python (bits not hex)
16,444,726
26
2013-05-08T15:37:09Z
16,444,786
16
2013-05-08T15:40:24Z
[ "python", "binary", "floating-point" ]
How to get the string as binary IEEE 754 representation of a 32 bit float? **Example** 1.00 -> '00111111100000000000000000000000'
Here's an ugly one ... ``` >>> import struct >>> bin(struct.unpack('!i',struct.pack('!f',1.0))[0]) '0b111111100000000000000000000000' ``` Basically, I just used the struct module to convert the float to an int ... --- Here's a slightly better one using `ctypes`: ``` >>> import ctypes >>> bin(ctypes.c_int.from_buff...
Binary representation of float in Python (bits not hex)
16,444,726
26
2013-05-08T15:37:09Z
16,445,458
7
2013-05-08T16:18:47Z
[ "python", "binary", "floating-point" ]
How to get the string as binary IEEE 754 representation of a 32 bit float? **Example** 1.00 -> '00111111100000000000000000000000'
This problem is more cleanly handled by breaking it into two parts. The first is to convert the float into an int with the equivalent bit pattern: ``` def float32_bit_pattern(value): return sum(ord(b) << 8*i for i,b in enumerate(struct.pack('f', value))) ``` Next convert the int to a string: ``` def int_to_bina...
Binary representation of float in Python (bits not hex)
16,444,726
26
2013-05-08T15:37:09Z
17,021,422
7
2013-06-10T10:10:16Z
[ "python", "binary", "floating-point" ]
How to get the string as binary IEEE 754 representation of a 32 bit float? **Example** 1.00 -> '00111111100000000000000000000000'
Found another solution using the [bitstring](http://pythonhosted.org/bitstring/creation.html) module. ``` import bitstring f1 = bitstring.BitArray(float=1.0, length=32) print f1.read('bin') ``` Output: ``` 00111111100000000000000000000000 ```
live updating with matplotlib
16,446,443
9
2013-05-08T17:10:42Z
16,446,688
23
2013-05-08T17:25:27Z
[ "python", "graph", "matplotlib" ]
So I have some phone accelerometry data and I would like to basically make a video of what the motion of the phone looked like. So I used matplotlib to create a 3D graph of the data: ``` from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import pandas as pd import pickle def pickleLoad(pickleFile)...
Here is a bare-bones example that updates as fast as it can: ``` import pylab as plt import numpy as np X = np.linspace(0,2,1000) Y = X**2 + np.random.random(X.shape) plt.ion() graph = plt.plot(X,Y)[0] while True: Y = X**2 + np.random.random(X.shape) graph.set_ydata(Y) plt.draw() ``` The trick is **not...
C Code for Python's property function?
16,447,280
4
2013-05-08T18:01:20Z
16,447,342
8
2013-05-08T18:05:06Z
[ "python", "c", "properties", "python-3.x" ]
I am really curious as to **how** Python's interpreter makes an attribute `x` out of a method `x` through `x=property(x)`. If I could take a look at the `C` code, I would feel much better.
The type is defined in the [`descrobject.c` file](http://hg.python.org/cpython/file/tip/Objects/descrobject.c#l1228). You can locate Python types like these by first looking for the function name in [`bltinmodule.c`](http://hg.python.org/cpython/file/tip/Python/bltinmodule.c); in this case the following line defines t...
How to execute Python script from Java?
16,447,410
8
2013-05-08T18:10:40Z
16,447,648
10
2013-05-08T18:26:31Z
[ "java", "python", "linux" ]
I can execute Linux commands like `ls` or `pwd` from Java without problems but couldn't get a Python script executed. This is my code: ``` Process p; try{ System.out.println("SEND"); String cmd = "/bash/bin -c echo password| python script.py '" + packet.toString() + "'"; //System.out.println(cmd); p =...
You cannot use the PIPE inside the `Runtime.getRuntime().exec()` as you do in your example. PIPE is part of the shell. You could do either * Put your command to a shell script and execute that shell script with `.exec()` or * You can do something similar to the following ``` String[] cmd = { "/bin/bash...
How to execute Python script from Java?
16,447,410
8
2013-05-08T18:10:40Z
16,448,213
8
2013-05-08T18:59:49Z
[ "java", "python", "linux" ]
I can execute Linux commands like `ls` or `pwd` from Java without problems but couldn't get a Python script executed. This is my code: ``` Process p; try{ System.out.println("SEND"); String cmd = "/bash/bin -c echo password| python script.py '" + packet.toString() + "'"; //System.out.println(cmd); p =...
@Alper's answer should work. Better yet, though, don't use a shell script and redirection at all. You can write the password directly to the process' stdin using the (confusingly named) `Process.getOutputStream()`. ``` Process p = Runtime.exec(new String[]{"python", "script.py", packet.toString()}); BufferWriter write...
Accessing remote MySQL database with peewee
16,448,198
9
2013-05-08T18:58:46Z
16,450,559
18
2013-05-08T21:31:22Z
[ "python", "amazon-rds", "peewee" ]
I'm trying to connect to a MySQL database on Amazon's RDS using peewee and I can't get it to work. I'm new to databases so I'm probably doing something stupid, but this is what I'm trying: ``` import peewee as pw myDB = pw.MySQLDatabase(host="mydb.crhauek3cxfw.us-west-2.rds.amazonaws.com",port=3306,user="user",passwd...
I changed it to be like this and it worked: ``` import peewee as pw myDB = pw.MySQLDatabase("mydb", host="mydb.crhauek3cxfw.us-west-2.rds.amazonaws.com", port=3306, user="user", passwd="password") class MySQLModel(pw.Model): """A base model that will use our MySQL database""" class Meta: database = m...
How to get python-dev for windows?
16,448,710
9
2013-05-08T19:29:24Z
24,163,212
7
2014-06-11T12:40:41Z
[ "python", "django" ]
We are trying to install PIL and getting the error `error: command 'gcc' failed with exit status 1` Many similar questions, including this one ([installing Reportlab (error: command 'gcc' failed with exit status 1 )](http://stackoverflow.com/questions/7325305/installing-reportlab-error-command-gcc-failed-with-exit-st...
It seems there is no `python-dev` package for Windows. But the Python installer for Windows will normally install a sub directory `include` inside the main Python dir. So with Python in `C:\Python` you would get: * C:\Python * C:\Python\DLLs * C:\Python\Doc * **C:\Python\include** * C:\Python\Lib * C:\Python\libs * C...
Counting number of columns in text file with Python
16,448,912
2
2013-05-08T19:41:50Z
16,449,052
7
2013-05-08T19:50:48Z
[ "python", "python-3.x", "multiple-columns" ]
I have two text files composed of spaced-separated columns. These are excerpts of these two files: FileA ``` 1 1742.420 -0.410 20.1530 0.4190 1.7080 0.5940 2 1872.060 0.070 21.4710 0.2950 0.0670 0.3380 3 1918.150 0.150 18.9220 0.0490 1.4240 0.1150 4 1265.760 0.170 19.0850 0.0720...
``` import csv with open('filename') as f: reader = csv.reader(f, delimiter=' ', skipinitialspace=True) first_row = next(reader) num_cols = len(first_row) ```
Python converting string to tuple without splitting characters
16,449,184
11
2013-05-08T20:00:12Z
16,449,189
30
2013-05-08T20:00:45Z
[ "python", "list", "python-2.7", "python-3.x", "tuples" ]
I am striving to convert a string to a tuple without splitting the characters of the string in the process. Can somebody suggest an easy method to do this. Need a one liner. **Fails** ``` a = 'Quattro TT' print tuple(a) ``` **Works** ``` a = ['Quattro TT'] print tuple(a) ``` Since my input is a string,...
You can just do `(a,)`. No need to use a function. (Note that the comma is necessary.) Essentially, `tuple(a)` means to make a tuple of the *contents* of `a`, not a tuple consisting of just `a` itself. The "contents" of a string (what you get when you iterate over it) are its characters, which is why it is split into ...
Python converting string to tuple without splitting characters
16,449,184
11
2013-05-08T20:00:12Z
16,449,462
10
2013-05-08T20:18:43Z
[ "python", "list", "python-2.7", "python-3.x", "tuples" ]
I am striving to convert a string to a tuple without splitting the characters of the string in the process. Can somebody suggest an easy method to do this. Need a one liner. **Fails** ``` a = 'Quattro TT' print tuple(a) ``` **Works** ``` a = ['Quattro TT'] print tuple(a) ``` Since my input is a string,...
Have a look at the [Python tutorial on tuples](http://docs.python.org/2/tutorial/datastructures.html#tuples-and-sequences): > A special problem is the construction of tuples containing 0 or 1 items: the syntax has some extra quirks to accommodate these. Empty tuples are constructed by an empty pair of parentheses; a t...
Python nested if-else statements
16,449,634
3
2013-05-08T20:29:17Z
16,449,668
8
2013-05-08T20:31:38Z
[ "python", "python-2.7" ]
I have a statement like this ``` for word in tweet_text: if word in new_words: if new_words[word] == 0: new_words[word] = sent_count else: new_words[word] = (new_words[word] + sent_count) / 2 ``` And I am very suspicious that the else block is executed every time when the...
The `else` clause corresponds to the `if` on the same level of indentation, as you expect. The problem you see may be due to the fact that you are mixing tabs and spaces, so the apparent level of indentation is not the same as the one your interpreter sees. Change all tabs into spaces and check if the problem goes aw...
How to display 2 thumbnails of span6 per row in Bootstrap with Django?
16,450,124
2
2013-05-08T21:02:18Z
16,450,378
9
2013-05-08T21:18:03Z
[ "python", "django", "twitter-bootstrap" ]
I would like to display 2 thumbnails per row. It would be pretty trivial to just hard-code it using multiple rows and each row has 2 `span6` div's. But how would I do this in Django using a template for-loop? *Example:* ``` {% for image in images %} <div class="row"> <div class="span6">*image goes here*</div> ...
Well it could be done by css only, but if you want to use the provided grid, you could create a generator and use it on your view's queryset or directly in a template by using a tag, e.g. ``` def grouped(l, n): # Yield successive n-sized chunks from l. for i in xrange(0, len(l), n): yield l[i:i+n] ``` ...
Using exception to control code flow
16,451,257
2
2013-05-08T22:25:22Z
16,451,285
8
2013-05-08T22:28:10Z
[ "python", "exception" ]
afaik using exceptions to handle code flow is wrong. I'm working in a code that has a method named getEntity(id) and getEntity throws a DoesNotExist exception when entity is not found. There is no entityExists(id) method. To check if a entity exists, code usually does: ``` try: getEntity(id) catch DoesNotExist as ...
This is known as [EAFP](http://docs.python.org/2/glossary.html#term-eafp) or *Easier to ask for forgiveness than permission*. From [The Python Glossary](http://docs.python.org/2/glossary.html): > This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption ...
Tornado request.body
16,451,660
14
2013-05-08T23:03:55Z
16,478,621
14
2013-05-10T09:02:05Z
[ "python", "python-2.7", "tornado" ]
My Tornado application accepts POST data through http body request In my handler I am able to get the request ``` def post(self): data = self.request.body ``` The data I am getting is in the from of str(dictionary) Is there a way to receive this data in the form of a Python dictionary? I don't want to use `eva...
You are receiving a JSON string. Decode it with the JSON module ``` import json def post(self): data = json.loads(self.request.body) ``` For more info: <http://docs.python.org/2/library/json.html>
Tornado request.body
16,451,660
14
2013-05-08T23:03:55Z
28,140,966
16
2015-01-25T20:13:24Z
[ "python", "python-2.7", "tornado" ]
My Tornado application accepts POST data through http body request In my handler I am able to get the request ``` def post(self): data = self.request.body ``` The data I am getting is in the from of str(dictionary) Is there a way to receive this data in the form of a Python dictionary? I don't want to use `eva...
As an alternative to Eloim's answer, Tornado provides [tornado.escape](http://tornado.readthedocs.org/en/latest/escape.html) for "Escaping/unescaping HTML, JSON, URLs, and others". Using it should give you exactly what you want: ``` data = tornado.escape.json_decode(self.request.body) ```
How to convert signed 32-bit int to unsigned 32-bit int in python?
16,452,232
5
2013-05-09T00:04:32Z
16,452,899
10
2013-05-09T01:27:02Z
[ "python", "integer", "unsigned", "signed", "data-type-conversion" ]
This is what I have, currently. Is there any nicer way to do this? ``` import struct def int32_to_uint32(i): return struct.unpack_from("I", struct.pack("i", i))[0] ```
Not sure if it's "nicer" or not... ``` import ctypes def int32_to_uint32(i): return ctypes.c_uint32(i).value ```
multi-column factorize in pandas
16,453,465
8
2013-05-09T02:39:55Z
16,457,573
10
2013-05-09T08:30:39Z
[ "python", "pandas", "enumeration", "data-cleansing" ]
The pandas `factorize` function assigns each unique value in a series to a sequential, 0-based index, and calculates which index each series entry belongs to. I'd like to accomplish the equivalent of `pandas.factorize` on multiple columns: ``` import pandas as pd df = pd.DataFrame({'x': [1, 1, 2, 2, 1, 1], 'y':[1, 2,...
You need to create a ndarray of tuple first, `pandas.lib.fast_zip` can do this very fast in cython loop. ``` import pandas as pd df = pd.DataFrame({'x': [1, 1, 2, 2, 1, 1], 'y':[1, 2, 2, 2, 2, 1]}) print pd.factorize(pd.lib.fast_zip([df.x, df.y]))[0] ``` the output is: ``` [0 1 2 2 1 0] ```
Regression with Date variable using Scikit-learn
16,453,644
6
2013-05-09T03:02:10Z
16,525,456
7
2013-05-13T15:13:44Z
[ "python", "python-2.7", "numpy", "pandas", "scikit-learn" ]
I have a Pandas DataFrame with a `date` column (eg: `2013-04-01`) of dtype `datetime.date`. When I include that column in `X_train` and try to fit the regression model, I get the error `float() argument must be a string or a number`. Removing the `date` column avoided this error. What is the proper way to take the `da...
The best way is to explode the date into a set of categorical features encoded in boolean form using the 1-of-K encoding (e.g. as done by [DictVectorizer](http://scikit-learn.org/stable/modules/feature_extraction.html#loading-features-from-dicts)). Here are some features that can be extracted from a date: * hour of th...