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
Python 3.3.2 check that object is of type file
18,880,948
5
2013-09-18T19:42:22Z
18,880,992
8
2013-09-18T19:44:25Z
[ "python", "file", "types", "python-3.x" ]
I'm porting from Python 2.7 to Python 3.3.2. In Python 2.7, I used to be able to do something like `assert(type(something) == file)`, but it seems that in Python 3.3.2 this is wrong. How do I do a similar thing in Python 3.3.2?
Python 3 file objects are part of the [`io` module](http://docs.python.org/3/library/io.html), test against [ABC classes](http://docs.python.org/3/library/io.html#class-hierarchy) in that module: ``` from io import IOBase if isinstance(someobj, IOBase): ``` Don't use `type(obj) == file` in Python 2; you'd use `isins...
What's wrong with Pandas plot?
18,881,540
5
2013-09-18T20:15:47Z
18,881,626
13
2013-09-18T20:20:15Z
[ "python", "matplotlib", "plot", "pandas" ]
I'm following a book by Wes McKinney and in the section introducing pandas, he's given a simple example of plotting a pandas Data Frame. Here're the lines I wrote: ``` tz_counts = frame['tz'].value_counts() # frame is a Data Frame tz_counts[:10] # works fine till here. I can see the key-value I wanted tz_counts[:10].p...
Matplotlib doesn't show the plot until you tell it to, unless you're in "interactive" mode. *Short Answer*: Call `plt.show()` when you're ready to display the plot. This starts the gui mainloop of whatever backend you're using, so it is blocking. (i.e. execution will stop until you close the window) If you want it t...
How to change UserDoesNotExist SELECT behavior in Flask-peewee - python & mysql
18,881,926
4
2013-09-18T20:38:15Z
18,882,658
7
2013-09-18T21:28:11Z
[ "python", "mysql", "json", "flask", "peewee" ]
Im using [flask-peewee](http://flask-peewee.readthedocs.org/en/latest/) to make an API and I'd like to return back a 404 json if user doesn't exist in the table but seems like it's throwing 500 error instead of 404 error json: Here is the **Error** I'm getting: ``` UserDoesNotExist: instance matching query does not e...
``` active = User.select().where(User.active == True) try: user = active.where(User.username == request.form['username']).get() except User.DoesNotExist: return make_response(jsonify({'error': 'Bad request'}), 400) else: if not user.check_password(...) ```
flask-mail gmail: connection refused
18,881,929
4
2013-09-18T20:38:21Z
18,882,402
14
2013-09-18T21:09:38Z
[ "python", "python-2.7", "flask", "flask-mail" ]
I'm getting the following error when I attempt to use flask-mail to send an email through my gmail account. > error: [Errno 10061] No connection could be made because the target machine actively refused it I've tried configuring flask-mail in various ways, but so far I always get this error. Here are some sample con...
As far as I can tell there is nothing wrong with this configuration. The only problem is that your application is not using it. You should update configuration before you initialize `Mail`: ``` app = Flask(__name__) app.config.update(dict( DEBUG = True, MAIL_SERVER = 'smtp.gmail.com', MAIL_PORT = 587, ...
Wrapping arrays in Boost Python
18,882,089
13
2013-09-18T20:48:23Z
18,902,363
13
2013-09-19T18:30:16Z
[ "c++", "python", "boost", "boost-python" ]
I have a series of C++ structures I am trying to wrap using boost python. I've run into difficulties when these structures contain arrays. I am trying to do this with minimal overhead and unfortunately I can't make any modifications to the structs themselves. So for instance say I have ``` struct Foo { int vals[3]...
For such a relatively simple question, the answer becomes rather involved. Before providing the solution, lets first examine the depth of the problem: ``` f = Foo() f.vals[0] = 10 ``` `f.vals` returns an intermediate object that provides `__getitem__` and `__setitem__` methods. For Boost.Python to support this, aux...
Assigning multiple column values to a python pandas DataFrame in one line
18,882,501
5
2013-09-18T21:16:43Z
18,882,571
12
2013-09-18T21:21:57Z
[ "python", "pandas", "dataframe" ]
I'm trying to Assign multiple values to a single row in a DataFrame and I need the correct syntax. See the code below. ``` import pandas as pd df = pd.DataFrame({ 'A': range(10), 'B' : '', 'C' : 0.0, 'D' : 0.0, 'E': 0.0, }) #Works fine df['A'][2] = 'tst' #Is there a way to assign multiple values in a single line a...
Use [`loc`](http://pandas.pydata.org/pandas-docs/stable/indexing.html#selection-by-label) (and avoid chaining): ``` In [11]: df.loc[3] = ['V1', 4.3, 2.2, 2.2, 20.2] ``` *This ensures the assigning is done inplace on the DataFrame, rather than on a copy (and garbage collected).* You can specify only certain columns: ...
Python: is there a way to import a variable using timeit.timeit()?
18,882,747
6
2013-09-18T21:34:42Z
18,882,784
9
2013-09-18T21:36:48Z
[ "python", "time", "timeit" ]
Suppose I have some function that takes an array and changes every element to be 0. ``` def function(array): for i in range(0,len(array)): array[i] = 0 return array ``` I want to test how long this function takes to run on a random array, which I wish to generate OUTSIDE of the timeit test. In other words...
Import `x` from `__main__` *as well*: ``` timeit.timeit("function(x)", setup="from __main__ import function, x") ``` Just like `function`, `x` is a name in the `__main__` module, and can be imported into the `timeit` setup.
Python: is there a way to import a variable using timeit.timeit()?
18,882,747
6
2013-09-18T21:34:42Z
18,882,807
9
2013-09-18T21:38:39Z
[ "python", "time", "timeit" ]
Suppose I have some function that takes an array and changes every element to be 0. ``` def function(array): for i in range(0,len(array)): array[i] = 0 return array ``` I want to test how long this function takes to run on a random array, which I wish to generate OUTSIDE of the timeit test. In other words...
You can avoid this problem entirely if you pass `timeit` a function instead of a string. In that case, the function executes in its normal globals and closure environment. So: ``` timeit.timeit(lambda: function(x)) ``` Or, if you prefer: ``` timeit.timeit(partial(function, x)) ``` (See [here](http://docs.python.org...
Enthought Canopy: Where do os.environ variables come from?
18,883,201
2
2013-09-18T22:09:55Z
18,883,351
7
2013-09-18T22:25:30Z
[ "python", "environment-variables", "osx-mountain-lion", "enthought", "canopy" ]
I have the following problem. I wanted to use the matplotlib package animation to save an mp4 video file. The save function has a dependency for generating the mp4 file, the ffmpeg external library. So I installed ffmpeg on a Mac osx 10.8 via Macports, and it got installed in `/opt/local/bin` . But now, running the sc...
The problem here has nothing to do with Enthought; it's that OS X doesn't run bash when you launch things from Finder, LaunchDaemons, etc., and therefore doesn't access your `.bash_profile`. Instead, it runs them from `launchd`. If you want to add some environment variables to affect anything run by `launchd` for the ...
Trouble installing private github repository using pip
18,883,430
18
2013-09-18T22:33:20Z
18,922,464
24
2013-09-20T17:23:15Z
[ "python", "git", "github", "virtualenv", "pip" ]
To preface, I have already seen this question [Is it possible to use pip to install a package from a private github repository?](http://stackoverflow.com/questions/4830856/is-it-possible-to-use-pip-to-install-a-package-from-a-private-github-repository) I am trying to install a package from a private repository that I ...
It worked by using oxyum's suggestion of changing it to: ``` pip install git+ssh://[email protected]/matherbk/django-messages.git ```
How to check in python if I'm in certain range of times of the day?
18,884,017
3
2013-09-18T23:29:51Z
18,884,062
8
2013-09-18T23:34:05Z
[ "python", "datetime" ]
I want to check in python if the current time is between two endpoints (say, 8:30 a.m. and 3:00 p.m.), irrespective of the actual date. As in, I don't care what the full date is; just the hour. When I created `datetime` objects using `strptime` to specify a time, it threw in a dummy date (I think the year 1900?) which ...
`datetime` objects have a method called `time()` which returns a `time` object (with no date information). You can then compare the `time` objects using the normal `<` or `>` operators. ``` import datetime import time timestamp = datetime.datetime.now().time() # Throw away the date information time.sleep(1) print (dat...
Usecase of |= in python
18,884,075
3
2013-09-18T23:35:31Z
18,884,099
11
2013-09-18T23:38:24Z
[ "python", "operators" ]
I came across `|=` operator today in codebase and did not recognise it, and searching google for `python "|="` returns nothing useful for me. Testing the outcome of operations below yields the following: ``` >>> from itertools import combinations >>> def wtf_is_it(left, right): >>> orig_left = left >>> left |...
For integers, it's the bitwise-OR compound assignment operator. Like all compound assignment operators, `a |= b` is the same thing as `a = a | b`. And the pipe is the symbol for bitwise OR. * [Compound Assignment (Augmented Assignment)](http://en.wikipedia.org/wiki/Augmented_assignment) * [Bitwise OR](http://en.wikipe...
Conflicting eigen vector outputs between Matlab and Numpy
18,884,212
7
2013-09-18T23:51:10Z
18,884,387
12
2013-09-19T00:12:47Z
[ "python", "matlab", "numpy", "octave", "eigenvector" ]
I am calculating eigenvectors in Matlab and Numpy, but getting different results. I was under the impression there was only one set of eigenvectors for a given matrix, however both of these outputs seem valid. Here is my matlab code: ``` m = [ 1.4675 + 0.0000i 0.1669 + 1.2654i; 0.1669 - 1.2654i 1.3085 + 0...
It's not immediately obvious, but the eigenvectors you are being returned are actually the same in both cases. Try the following: ``` >>> matlab_eigvec = np.array([[0.0896+0.6789j, 0.0953+0.7225j], ... [-0.7288+0.j, 0.6848+0.j]]) >>> >>> f1, f2 = matlab_eigvec.T # matlab eigenvectors >>> e1,...
TypeError: worker() takes 0 positional arguments but 1 was given
18,884,782
8
2013-09-19T01:10:06Z
18,884,811
23
2013-09-19T01:13:14Z
[ "python", "python-3.x" ]
I'm trying to implement a subclass and it throws the error: `TypeError: worker() takes 0 positional arguments but 1 was given` ``` class KeyStatisticCollection(DataDownloadUtilities.DataDownloadCollection): def GenerateAddressStrings(self): pass def worker(): pass def DownloadProc(self...
Your `worker` method needs 'self' as a parameter, since it is a class method and not a function. Adding that should make it work fine.
Read a zipped file as a pandas DataFrame
18,885,175
19
2013-09-19T02:05:15Z
18,885,319
20
2013-09-19T02:26:38Z
[ "python", "zip", "pandas" ]
I'm trying to unzip a csv file and pass it into pandas so I can work on the file. The code I have tried so far is: ``` import requests, zipfile, StringIO r = requests.get('http://data.octo.dc.gov/feeds/crime_incidents/archive/crime_incidents_2013_CSV.zip') z = zipfile.ZipFile(StringIO.StringIO(r.content)) crime2013 ...
I think you want to [`open`](http://docs.python.org/2/library/zipfile#zipfile.ZipFile.open) the ZipFile, which returns a file-like object, rather than [`read`](http://docs.python.org/2/library/zipfile#zipfile.ZipFile.read): ``` In [11]: crime2013 = pd.read_csv(z.open('crime_incidents_2013_CSV.csv')) In [12]: crime201...
Read a zipped file as a pandas DataFrame
18,885,175
19
2013-09-19T02:05:15Z
32,993,553
21
2015-10-07T13:30:12Z
[ "python", "zip", "pandas" ]
I'm trying to unzip a csv file and pass it into pandas so I can work on the file. The code I have tried so far is: ``` import requests, zipfile, StringIO r = requests.get('http://data.octo.dc.gov/feeds/crime_incidents/archive/crime_incidents_2013_CSV.zip') z = zipfile.ZipFile(StringIO.StringIO(r.content)) crime2013 ...
If you want to read a zipped or a tar.gz file into pandas dataframe, the read\_csv methods includes this particular implementation. ``` df = pd.read_csv(filename.tar.gz, compression='gzip', header=0, sep=',', quotechar='"') ``` compression : {‘gzip’, ‘bz2’, ‘infer’, None}, default ‘infer’ For on-the-f...
Pre Commit hook git error
18,885,644
2
2013-09-19T03:15:51Z
18,886,088
8
2013-09-19T04:15:13Z
[ "python", "git" ]
I am trying to execute a pre commit git hook in python to check if files have line lengths less than 80 chars. However i get a no such file/directory error. i am on fedora and have set the #!usr/bin/python.help would be appreciated ``` #!/usr/bin/env python #-*- mode: python -*- from subprocess import Popen, PIPE imp...
Your pre-commit file has extraneous carriage returns in it. This can happen if you edit the file in Windows and copy the file to a Linux computer. Try these commands: ``` cp .git/hooks/pre-commit /tmp/pre-commit tr -d '\r' < /tmp/pre-commit > .git/hooks/pre-commit ``` And then rerun your `git` command.
Questions about numpy matrix in python
18,885,671
4
2013-09-19T03:20:36Z
18,885,784
8
2013-09-19T03:36:18Z
[ "python", "numpy" ]
``` #these are defined as [a b] hyperplanes = np.mat([[0.7071, 0.7071, 1], [-0.7071, 0.7071, 1], [0.7071, -0.7071, 1], [-0.7071, -0.7071, 1]]); a = hyperplanes[:][:,0:2].T; b = hyperplanes[:,2]; ``` what does these denotes of [:][:,0:2] mean? ...
We can use the interactive interpreter to find this out. ``` In [3]: hyperplanes = np.mat([[0.7071, 0.7071, 1], ...: [-0.7071, 0.7071, 1], ...: [0.7071, -0.7071, 1], ...: [-0.7071, -0.7071, 1]]) ``` Notice that we don't need semicolon...
How to parse values from a JSON file in Python
18,886,319
2
2013-09-19T04:41:09Z
18,886,346
8
2013-09-19T04:44:18Z
[ "python", "json", "file" ]
I'm trying to get the values from the json file and the error that I'm getting is `TypeError: expected string or buffer`. I'm parsing the file correctly and moreover I guess my json file format is also correct. Where I'm going wrong? Both the files are in the same directory. **Main\_file.py** ``` import json json_d...
`loads` expects a string not a file handle. You need `json.load`: ``` import json with open('meters_parameters.json') as f: data = json.load(f) print data ```
Replace all quotes in a string with escaped quotes?
18,886,596
12
2013-09-19T05:09:56Z
18,886,707
10
2013-09-19T05:20:36Z
[ "python", "string", "replace" ]
Given a string in python, such as: ``` s = 'This sentence has some "quotes" in it\n' ``` I want to create a new copy of that string with any quotes escaped (for further use in Javascript). So, for example, what I want is to produce this: ``` 'This sentence has some \"quotes\" in it\n' ``` I tried using `replace()`,...
Your second attempt is correct, but you're getting confused by the difference between the `repr` and the `str` of a string. A more idiomatic way of doing your second way is to use "raw strings": ``` >>> s = 'This sentence has some "quotes" in it\n' >>> print s This sentence has some "quotes" in it >>> print s.replace...
Replace all quotes in a string with escaped quotes?
18,886,596
12
2013-09-19T05:09:56Z
18,886,842
14
2013-09-19T05:33:23Z
[ "python", "string", "replace" ]
Given a string in python, such as: ``` s = 'This sentence has some "quotes" in it\n' ``` I want to create a new copy of that string with any quotes escaped (for further use in Javascript). So, for example, what I want is to produce this: ``` 'This sentence has some \"quotes\" in it\n' ``` I tried using `replace()`,...
Hi usually when working with Javascript I use the json module provided by Python. It will escape the string as well as a bunch of other things as user2357112 has pointed out. ``` import json string = 'This sentence has some "quotes" in it\n' json.dumps(string) #gives you '"This sentence has some \\"quotes\\" in it\\n"...
Transforming list to dict with list items as keys and list indices as values in python
18,887,903
2
2013-09-19T06:47:51Z
18,887,931
9
2013-09-19T06:49:05Z
[ "python", "list", "python-2.7", "dictionary" ]
I want to transform ``` l = ['a','b','c','d'] ``` to ``` d = {'a': 0, 'b': 1, 'c': 2, 'd': 3} ``` The best solution I have so far is that one: ``` d = {l[i]:i for i in range(len(l))} ``` Is there more elegant way to do this?
``` d = {e:i for i, e in enumerate(l)} ``` *Edit:* As @LeonYoung suggested, if you want to be compatible with python < 2.7 (despite the tag), you must use ``` d = dict((e, i) for i, e in enumerate(l)) ```
Getting Attempted relative import in non-package error in spite of having __init__.py
18,888,198
5
2013-09-19T07:03:49Z
18,888,854
7
2013-09-19T07:40:51Z
[ "python", "python-2.7", "osx-lion" ]
I have a package `cclogger`. This directory has a `__init__.py` file with some code to load the configuration. When I try to run the file `api_main.py` in that directory using the following command... ``` python -m cclogger.api_main ``` I get the following erro:- ``` config loaded Instantiating DB with: cclogger/tes...
You cannot run a python module directly as a script (I don't really know the reason why). **EDIT** : The reason is explained in the [PEP338](http://www.python.org/dev/peps/pep-0338/) which is the spec for the `"-m"` option. > The release of 2.5b1 showed a surprising (although obvious in > retrospect) interaction betw...
how to change Qtablewidget's spesific cells backround color in pyqt
18,889,015
5
2013-09-19T07:50:18Z
18,905,408
14
2013-09-19T21:42:52Z
[ "python", "pyqt4", "stylesheet" ]
I am new in pyqt4 and I can't figure out how to do this. I have a QtableWidget with data in it. I want to change some background color of the tableWidget's cells. I tried `self.tableWidget.item(3, 5).setBackground(QtGui.QColor(100,100,150))` and it returns this error: > `AttributeError: 'NoneType' object has no attr...
You must first create an item in that place in the table, before you can set its background color. ``` self.tableWidget.setItem(3, 5, QtGui.QTableWidgetItem()) self.tableWidget.item(3, 5).setBackground(QtGui.QColor(100,100,150)) ```
Create dummies from column with multiple values in pandas
18,889,588
14
2013-09-19T08:20:56Z
25,208,947
25
2014-08-08T17:25:47Z
[ "python", "pandas", "dummy-data", "categorical-data" ]
I am looking for for a pythonic way to handle the following problem. The `pandas.get_dummies()` method is great to create dummies from a categorical column of a dataframe. For example, if the column has values in `['A', 'B']`, `get_dummies()` creates 2 dummy variables and assigns 0 or 1 accordingly. Now, I need to ha...
I know it's been a while since this question was asked, but there is (at least *now* there is) a one-liner that is supported by [the documentation](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.get_dummies.html): ``` In [4]: df Out[4]: label 0 (a, c, e) 1 (a, d) 2 (b,) 3 ...
Read .csv file from URL into Python 3.x - _csv.Error: iterator should return strings, not bytes (did you open the file in text mode?)
18,897,029
14
2013-09-19T14:09:48Z
18,897,408
18
2013-09-19T14:26:09Z
[ "python", "url", "csv", "python-3.x" ]
I've been struggling with this simple problem for too long, so I thought I'd ask for help. I am trying to read a list of journal articles from National Library of Medicine ftp site into Python 3.3.2 (on Windows 7). The journal articles are in a .csv file. I have tried the following code: ``` import csv import urllib....
The problem relies on `urllib` returning bytes. As a proof, you can try to download the csv file with your browser and opening it as a regular file and the problem is gone. A similar problem was addressed [here](http://stackoverflow.com/questions/6862770/python-3-let-json-object-accept-bytes-or-let-urlopen-output-stri...
pandas plot dataframe barplot with colors by category
18,897,261
3
2013-09-19T14:19:23Z
18,897,358
9
2013-09-19T14:23:57Z
[ "python", "plot", "pandas", "bar-chart" ]
I would like to use pandas to plot a barplot with diffrent colors for category in column. Here is a simple example: (index is variable) ``` df: value group variable a 10 1 b 9 1 c 8 1 d 7 2 f 6 2 g ...
Just pass a color parameter to the plot function with a list of colors: ``` df['group'].plot(kind='bar', color=['r', 'g', 'b', 'r', 'g', 'b', 'r']) ``` If you want to plot the `value` as bars and you also want the `group` to determine the color of the bar, use: ``` colors = {1: 'r', 2: 'b', 3: 'g'} df['value'].plot(...
Random choice works but only sometimes
18,897,398
2
2013-09-19T14:25:47Z
18,897,522
11
2013-09-19T14:30:54Z
[ "python", "random", "choice" ]
``` import random mylist = ["a", "b", "c"] mynums = ["1","2","3"] myint = ["6","7","8"] random.choice (mylist) if random.choice(mylist) == "a": print ("a") random.choice (mynums) print (random.choice (mynums)) if random.choice(mylist) == "b": print ("b") random.choice (myint) print (random.ch...
You are getting a new random letter in each if statement. There is a possibility that the new choice won't be the letter that you're comparing, or it could even be the letter you're comparing every time. There's no way to know. If you just want to get a single random letter from the list and do something based on which...
PyQt4: Difference between QWidget and QMainWindow
18,897,695
10
2013-09-19T14:38:59Z
18,898,636
10
2013-09-19T15:17:41Z
[ "python", "python-2.7", "pyqt", "pyqt4" ]
When reading through a PyQt4 tutorial, sometimes the examples uses `QtGui.QMainWindow`, sometimes it uses `QtGui.QWidget`. **Question:** How do you tell when to use which? ``` import sys from PyQt4 import QtGui class Example(QtGui.QMainWindow): def __init__(self): super(Example, self).__init__() ...
`QMainWindow` is a class that understands GUI elements like a * toolbar, * statusbar, * central widget, * docking areas. `QWidget` is just a raw widget. When you want to have a main window for you project, use `QMainWindow`. If you want to create a dialog box (modal dialog), use `QWidget`, or, more preferably, `QDi...
Why can't I access class Meta as a attribute of Django Model Class?
18,897,777
8
2013-09-19T14:41:53Z
18,897,852
10
2013-09-19T14:45:05Z
[ "python", "django", "django-models" ]
In Python I can define: ``` class Person(object): name = "Easwar" age = 35 sex = "male" class Occupation: name = "my_job" ``` I can then access it ``` >> p = Person() >> p.Occupation.name >> # prints "my_job" ``` However in Django, if I have a model defined with Class Meta inside I cannot do this...
The Meta attribute is changed by metaclass. Try: ``` SomeDjangoModel._meta ```
How to turn sqlalchemy logging off completely
18,900,888
5
2013-09-19T17:05:02Z
18,901,825
7
2013-09-19T18:00:08Z
[ "python", "logging", "sqlalchemy" ]
sqlalchemy is keep loggin to console even I have the following code ``` import logging logger = logging.getLogger() logger.disabled = True ``` How to turn off sqlalchemy's logging completely?
Did you pass `echo=True` to `create_engine()`? By default it creates StreamHandler which outputs to console. As [documentation](http://docs.sqlalchemy.org/en/latest/core/engines.html#configuring-logging) says, if you didn't provide any `echo=True` arguments and didn't configure root `sqlalchemy` logger, it will not log...
IPython Notebook save location
18,901,185
33
2013-09-19T17:22:18Z
18,901,898
43
2013-09-19T18:03:24Z
[ "python", "ipython", "ipython-notebook" ]
I just started IPython Notebook, and I tried to use "Save" to save my progress. However, instead of saving the \*.ipynb in my current working directory, it is saved in my python/Scripts folder. Would there be a way to set this? Thanks!
Yes, you can specify the notebooks location in your profile configuration. Since it's not saving them to the directory where you started the notebook, I assume that you have this option set in your profile. You can find out the the path to the profiles directory by using: ``` $ ipython locate ``` Either in your defau...
How can I patch / mock logging.getlogger()
18,901,360
5
2013-09-19T17:33:45Z
18,901,440
11
2013-09-19T17:38:29Z
[ "python", "unit-testing", "python-3.x", "mocking" ]
I have this code that I want to test: ``` log = logging.getLogger(__name__) class A(object): def __init__(self): log.debug('Init') ``` but I cannot figure out how to assert that log.debug was called with 'Init' I tried patching logger but inspecting it I only found a getLogger mock. I'm sure its simpl...
Assuming `log` is a global variable in a module `mymod`, you want to mock the actual instance that `getLogger` returned, which is what invokes `debug`. Then, you can check if `log.debug` was called with the correct argument. ``` with mock.patch('mymod.log') as log_mock: # test code log_mock.debug.assert_called...
What are the basic difference between pickle and yaml in Python?
18,901,729
5
2013-09-19T17:54:09Z
18,901,841
8
2013-09-19T18:00:48Z
[ "python", "python-2.7", "serialization", "yaml", "pickle" ]
I am naive to Python. But, what I came to know is that both are being used for serialization and deserialization. So, I just want to know what all basic differences in between them?
YAML is a language-neutral format that can represent primitive types (int, string, etc.) well, and is highly portable between languages. Kind of analogous to JSON, XML or a plain-text file; just with some useful formatting conventions mixed in -- in fact, YAML is a superset of JSON. Pickle format is specific to Python...
Read csv file with many named column labels with pandas
18,905,057
4
2013-09-19T21:16:53Z
18,905,310
8
2013-09-19T21:35:16Z
[ "python", "pandas", "multiple-columns", "labels", "hierarchical" ]
I'm brand new to pandas for python. I have a data file that has multiple row labels (per row) and column labels (per column) like the following data of observation counts for 3 different animals (dog,bat,ostrich) at multiple recording times (monday morning, day, night): ``` '' , '' , colLabel:name , d...
You can use the `header`, `index_col` and `tupleize_cols` arguments of [`read_csv`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.io.parsers.read_csv.html): ``` In [1]: df = pd.read_csv('foo.csv', header=[0, 1, 2], index_col=[0, 1], tupleize_cols=False, sep='\s*,\s+') ``` *Note: in 0.13 `tupelize=False...
Is there a decent alternative to "pip bundle"?
18,905,314
5
2013-09-19T21:36:01Z
18,905,381
7
2013-09-19T21:40:43Z
[ "python", "pip" ]
I use `pip bundle` for my production systems, and today I was greeted with the following disheartening message: ``` ############################################### ## ## ## Due to lack of interest and maintenance, ## ## 'pip bundle' and support for installing ## ## from *....
Use the new [wheel format](https://wheel.readthedocs.org/en/latest/); `wheel` builds on `pip` to bundle packages into a ZIP format. Alternatively, you could install an egg proxy; we use [Buildout](http://www.buildout.org/en/latest/) together with a local egg proxy to manage package dependencies and versioning in devel...
Logging in to LinkedIn with python requests sessions
18,907,503
6
2013-09-20T01:22:20Z
18,908,282
12
2013-09-20T03:18:42Z
[ "python", "web-scraping", "linkedin" ]
I'm trying to log into LinkedIn using Python requests: ``` import sys import requests from BeautifulSoup import BeautifulSoup payload={ 'session-key' : '[email protected]', 'session-password' : 'password' } URL='https://www.linkedin.com/uas/login-submit' s=requests.session() s.post(URL,data=payload) r=s.get('...
I modified a web-scraping template I use for most of my Python-based scraping needs to fit your needs. Verified it worked with my own login info. The way it works is by mimic-ing a browser and maintaining a cookieJar that stores your user session. Got it to work with BeautifulSoup for you as well. **Note:** This is a...
python - get list of all functions in current module. inspecting current module does not work?
18,907,712
2
2013-09-20T01:51:54Z
18,907,736
10
2013-09-20T01:55:05Z
[ "python" ]
I have following code ``` fset = [ obj for name,obj in inspect.getmembers(sys.modules[__name__]) if inspect.isfunction(obj) ] def func(num): pass if __name__ == "__main__": print(fset) ``` prints ``` [] ``` however this ``` def func(num): pass fset = [ obj for name,obj in inspect.getmembers(sys.modu...
It can't be. Function definitions are *executed* in Python. The functions don't exist until their definition is executed. Your `fset` variable can't be defined until after the functions are defined.
ImportError: No module named pywintypes
18,907,889
3
2013-09-20T02:18:43Z
18,907,911
8
2013-09-20T02:22:34Z
[ "python", "pywin32", "keylogger", "pyhook", "pythoncom" ]
I am working to make a small keylogger with Python, by using the pyHook, pythoncom and Pywin32 modules. Here is my code: ``` import pyHook, pythoncom, sys, logging file_log = 'C:\\important\\log.txt' def OnKeyboardEvent (event): logging.basicConfig(filename=file_log, level=logging.DEBUG, format='%(message)s') ...
`pywintypes` is part of the [Python for Windows extensions](http://starship.python.net/~skippy/win32/Downloads.html), otherwise known as pywin32. You'll need to install that to get access to `pywintypes`.
How do I create an array slice using the NumPy C API?
18,908,498
5
2013-09-20T03:48:28Z
18,910,271
7
2013-09-20T06:32:17Z
[ "python", "numpy", "multidimensional-array", "python-c-api" ]
I want to slice through a 1D NumPy from within a C extension. I see all sorts of helper functions in the C API for creating fresh arrays, reshaping, indexing particular values, etc.. But I don't see anything like PyArray\_Slice1D(array, start, stop, step). Does such a thing exist?
You can use Python API: create a slice object by `PySlice_New()` and then call `PyObject_GetItem()`: ``` PyObject* PySlice_New(PyObject *start, PyObject *stop, PyObject *step) PyObject* PyObject_GetItem(PyObject *o, PyObject *key) ```
What's ending comma in print function for?
18,908,897
20
2013-09-20T04:37:53Z
18,908,914
20
2013-09-20T04:39:49Z
[ "python" ]
This code is from <http://docs.python.org/2/tutorial/errors.html#predefined-clean-up-actions> ``` with open("myfile.txt") as f: for line in f: print line, ``` What I don't understand is what's that `,` for at the end of print command. I also checked doc, <http://docs.python.org/2/library/functions.html#p...
in python 2.7 the comma is to show that the string will be printed on the same line for example: ``` for i in xrange(10): print i, ``` this will print ``` 1 2 3 4 5 6 7 8 9 ``` to do this in python 3 you would do this: ``` for i in xrange(10): print(i,end=" ") ``` You will probably find this answer h...
Equivalent of Python's Pass in Scala
18,909,110
4
2013-09-20T05:00:35Z
18,913,212
7
2013-09-20T09:24:35Z
[ "python", "scala" ]
If there is a function that you don't want to do anything with you simple do something like this in Python: ``` def f(): pass ``` My question is, is there something similar to `pass` in Scala?
`pass` is a syntactic quirk of Python. There are some cases where the grammar *requires* you to write a statement, but sometimes you don't want a statement there. That's what `pass` is for: it's a statement that does nothing. Scala never requires you to write a statement, therefore the way to not write a statement is ...
Why is __init__ apparently optional?
18,909,695
4
2013-09-20T05:48:57Z
18,909,728
10
2013-09-20T05:50:59Z
[ "python", "python-3.x" ]
While experimenting, I wrote: ``` class Bag: pass g = Bag() print(g) ``` Which gave me: ``` <__main__.Bag object at 0x00000000036F0748> ``` Which surprised me. I expected an error when I tried to initialize it, since I didn't define `__init___`. Why isn't this the case?
You only need to override the methods you want to change. In other words: If you don't override `__init__`, the `__init__` method of the superclass will be called. E.g. ``` class Bag: pass ``` if equivalent to: ``` class Bag: def __init__(self): super(Bag, self).__init__() ``` Furthermore, `__ini...
How to change the text colour of font in legend?
18,909,696
3
2013-09-20T05:49:00Z
18,910,491
7
2013-09-20T06:47:34Z
[ "python", "colors", "fonts", "matplotlib", "legend" ]
Is there a way to change the font colour of the legend in a matplotlib plot? Specially in occasions where the background of the plot is dark, the default black text in the legend is hard or impossible to read.
call `Legend.get_texts()` will get a list of Text object in the legend object: ``` import pylab as pl pl.plot(randn(100), label="randn") l = legend() for text in l.get_texts(): text.set_color("red") ```
Does using virtualenvwrapper with Python3.3 mean I cannot (or should not) be using pyvenv?
18,911,070
18
2013-09-20T07:21:54Z
19,312,987
30
2013-10-11T07:51:21Z
[ "python", "virtualenv", "python-3.3", "virtualenvwrapper", "python-venv" ]
Virtualenvwrapper is a user-friendly shell around Python's virtualenv. Python 3.3 ships with pyvenv built into the standard library, which aims to supercede virtualenv. But if I install Virtualenvwrapper on Python3.3, it still installs virtualenv, leading me to believe it doesn't use 'pyvenv' under the covers. Presu...
Sorry this answer is a bit delayed. pyvenv does *not* aim to supersede virtualenv, in fact virtualenv in Python 3 depends on the standard library venv module. The **pyvenv** command creates an **absolutely minimal** virtual environment into which other packages can be installed. The Python 3 version of **virtualenv**...
Python PEP: blank line after function definition?
18,914,108
3
2013-09-20T10:06:55Z
18,914,365
8
2013-09-20T10:19:44Z
[ "python", "coding-style", "styles", "pep" ]
I can't find any PEP reference to this detail. There has to be a blank line after function definition? Should I do this: ``` def hello_function(): return 'hello' ``` or shoud I do this: ``` def hello_function(): return 'hello' ``` The same question applies when docstrings are used: this: ``` def hello_f...
Read [Docstring Conventions](http://www.python.org/dev/peps/pep-0257/). It says that even if the function is really obvious you have to write a one-line docstring. And it says that: > There's no blank line either before or after the docstring. So I would code something like ``` def hello_function(): """Returns ...
Sublime Text 2 & 3 setup for python / django with code completion
18,914,386
28
2013-09-20T10:21:00Z
18,915,780
30
2013-09-20T11:34:49Z
[ "python", "django", "autocomplete", "sublimetext2", "sublimetext" ]
I want to use an autocomplete plugin with sublime text for web development. I'm using django framework. I've looked into the following possible options. Not really a question, just for reference, I've added these here. --- The listing order represents popularity to a certain extent (based on activity level, commits, ...
In my opinion, there are ONLY 2 sulbime plugins that provide really good completion: * [SublimeJEDI](https://github.com/srusskih/SublimeJEDI) for ST2 and ST3 * [Anaconda](https://github.com/DamnWidget/anaconda) for ST3 CodeIntel and Rope works badly. Djaneiro is more snippets than completion but I also find it useful...
Create a pandas DataFrame from generator?
18,915,941
13
2013-09-20T11:42:51Z
18,916,457
10
2013-09-20T12:09:30Z
[ "python", "pandas" ]
I've create a tuple generator that extract information from a file filtering only the records of interest and converting it to a tuple that generator returns. I've try to create a DataFrame from: ``` import pandas as pd df = pd.DataFrame.from_records(tuple_generator, columns = tuple_fields_name_list) ``` but throws ...
You cannot create a DataFrame from a generator with the 0.12 version of pandas. You can either update yourself to the development version (get it from the github and compile it - which is a little bit painful on windows but I would prefer this option). Or you can, since you said you are filtering the lines, first filt...
selenium.common.exceptions.WebDriverException: Message: 'Can not connect to GhostDriver'
18,916,123
15
2013-09-20T11:52:44Z
20,035,539
8
2013-11-17T20:09:22Z
[ "python", "selenium-webdriver", "port", "phantomjs", "ghostdriver" ]
I'm trying to run `PhantomJS` from within `selenium.webdriver` on a Centos server. PhantomJS is in the path and is running properly from terminal. However in the script it appears to be launched, but afterwards cannot be reached on the specified port (I tried 2 different opened ports from my provider 29842 and 60099, t...
I had this issue on Ubuntu after upgrading to a new version. I re-installed all of the nodejs and python packages, but what I think solved the issue was making sure the `nodejs` executable was symbolically linked to `node`. These are the commands I used: ``` apt-get remove node nodejs apt-get install build-essential ...
Scrapy spider yields several items but pipeline is called only for first per request
18,917,652
2
2013-09-20T13:09:39Z
18,918,960
7
2013-09-20T14:16:08Z
[ "python", "scrapy" ]
Even though I have several items per request, only first one (per request) is making it's way to the pipeline and is actually saved as a Django model instance. Here is my code, what did I miss? ``` # my_spider.py class MySpider(CrawlSpider): name = 'my_spider' ... def parse(self, response): x = H...
You need to move the `MyDjangoItem` instantiation inside the for loop, otherwise it always yields the same object. ``` # my_spider.py class MySpider(CrawlSpider): name = 'my_spider' ... def parse(self, response): x = HtmlXPathSelector(response) headings = x.select('//h2/text()').extract()...
Django logging on Heroku
18,920,428
9
2013-09-20T15:25:14Z
20,983,546
19
2014-01-07T22:44:12Z
[ "python", "django", "logging", "heroku" ]
I know this question was already asked several times, but I just can't get it to work. I already spent half a day trying dozens of combinations, and again now and it is still not working. In my code, I am logging at several parts, like within a try-except or to log some infos from management commands. I'm doing just v...
Logging on Heroku from Django can be tricky at first, but it's actually not that horrible to get set up. This following logging definition (goes into your settings file) defined two formatters. The verbose one matches the logging format Heroku itself uses. It also defines two handlers, a null handler (shouldn't need t...
Scrapy Python Set up User Agent
18,920,930
11
2013-09-20T15:52:36Z
18,922,842
16
2013-09-20T17:45:41Z
[ "python", "scrapy", "web-crawler", "screen-scraping", "user-agent" ]
I tried to override the user-agent of my crawlspider by adding an extra line to the project [configuration file](http://doc.scrapy.org/en/latest/topics/settings.html#project-settings-module). Here is the code: ``` [settings] default = myproject.settings USER_AGENT = "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537...
Move your USER\_AGENT line to the `settings.py` file, and not in your `scrapy.cfg` file. `settings.py` should be at same level as `items.py` if you use `scrapy startproject` command, in your case it should be something like `myproject/settings.py`
How to incrementally sample without replacement?
18,921,302
13
2013-09-20T16:13:43Z
18,921,533
9
2013-09-20T16:27:05Z
[ "python", "algorithm", "statistics", "probability", "sample" ]
Python has `my_sample = random.sample(range(100), 10)` to randomly sample without replacement from `[0, 100)`. Suppose I have sampled `n` such numbers and now I want to sample one more without replacement (without including any of the previously sampled `n`), how to do so super efficiently? **update:** changed from "...
# The short way If the number sampled is much less than the population, just sample, check if it's been chosen and repeat while so. This might sound silly, but you've got an exponentially decaying possibility of choosing the same number, so it's much faster than `O(n)` if you've got even a small percentage unchosen. ...
How to incrementally sample without replacement?
18,921,302
13
2013-09-20T16:13:43Z
18,921,596
15
2013-09-20T16:30:27Z
[ "python", "algorithm", "statistics", "probability", "sample" ]
Python has `my_sample = random.sample(range(100), 10)` to randomly sample without replacement from `[0, 100)`. Suppose I have sampled `n` such numbers and now I want to sample one more without replacement (without including any of the previously sampled `n`), how to do so super efficiently? **update:** changed from "...
If you know in advance that you're going to want to multiple samples without overlaps, easiest is to do `random.shuffle()` on `list(range(100))` (Python 3 - can skip the `list()` in Python 2), then peel off slices as needed. ``` s = list(range(100)) random.shuffle(s) first_sample = s[-10:] del s[-10:] second_sample = ...
How to incrementally sample without replacement?
18,921,302
13
2013-09-20T16:13:43Z
18,922,585
7
2013-09-20T17:30:07Z
[ "python", "algorithm", "statistics", "probability", "sample" ]
Python has `my_sample = random.sample(range(100), 10)` to randomly sample without replacement from `[0, 100)`. Suppose I have sampled `n` such numbers and now I want to sample one more without replacement (without including any of the previously sampled `n`), how to do so super efficiently? **update:** changed from "...
Here's a way that doesn't build the difference set explicitly. But it does use a form of @Veedrac's "accept/reject" logic. If you're not willing to mutate the base sequence as you go along, I'm afraid that's unavoidable: ``` def sample(n, base, forbidden): # base is iterable, forbidden is a set. # Every elemen...
How to incrementally sample without replacement?
18,921,302
13
2013-09-20T16:13:43Z
18,925,011
7
2013-09-20T20:08:18Z
[ "python", "algorithm", "statistics", "probability", "sample" ]
Python has `my_sample = random.sample(range(100), 10)` to randomly sample without replacement from `[0, 100)`. Suppose I have sampled `n` such numbers and now I want to sample one more without replacement (without including any of the previously sampled `n`), how to do so super efficiently? **update:** changed from "...
OK, one last try ;-) At the cost of mutating the base sequence, this takes no additional space, and requires time proportional to `n` for each `sample(n)` call: ``` class Sampler(object): def __init__(self, base): self.base = base self.navail = len(base) def sample(self, n): from random...
How to incrementally sample without replacement?
18,921,302
13
2013-09-20T16:13:43Z
18,928,962
9
2013-09-21T04:40:54Z
[ "python", "algorithm", "statistics", "probability", "sample" ]
Python has `my_sample = random.sample(range(100), 10)` to randomly sample without replacement from `[0, 100)`. Suppose I have sampled `n` such numbers and now I want to sample one more without replacement (without including any of the previously sampled `n`), how to do so super efficiently? **update:** changed from "...
Ok, here we go. This should be the fastest possible non-probabilistic algorithm. It has runtime of `O(k⋅log²(s) + f⋅log(f)) ⊂ O(k⋅log²(f+k) + f⋅log(f)))` and space `O(k+f)`. `f` is the amount of forbidden numbers, `s` is the length of the longest streak of forbidden numbers. The expectation for that is more...
boolean and type checking in python vs numpy
18,922,407
3
2013-09-20T17:19:40Z
18,922,452
8
2013-09-20T17:22:34Z
[ "python", "numpy", "boolean", "pep8" ]
I ran into unexpected results in a python `if` clause today: ``` import numpy if numpy.allclose(6.0, 6.1, rtol=0, atol=0.5): print 'close enough' # works as expected (prints message) if numpy.allclose(6.0, 6.1, rtol=0, atol=0.5) is True: print 'close enough' # does NOT work as expected (prints nothing) ``` ...
You're doing something which is considered an anti-pattern. Quoting [PEP 8](http://www.python.org/dev/peps/pep-0008/#programming-recommendations): > Don't compare boolean values to True or False using ==. ``` Yes: if greeting: No: if greeting == True: Worse: if greeting is True: ``` The fact that numpy wasn't d...
why my coroutine blocks whole tornado instance?
18,923,560
2
2013-09-20T18:32:30Z
18,936,151
7
2013-09-21T18:34:25Z
[ "python", "asynchronous", "tornado", "coroutine" ]
``` from tornado import web, gen import tornado, time class CoroutineFactorialHandler(web.RequestHandler): @web.asynchronous @gen.coroutine def get(self, n, *args, **kwargs): n = int(n) def callbacker(iterator, callback): try: value = next(iterator) e...
You have to remember that Tornado runs in one thread. The code is split into task that are called sequentially in main loop. If one of these task takes long to finish (because of blocking functions like `time.sleep()` or some heavy computation like factorial) it will block entire loop as a result. So what you can do.....
Cant Solve "inc() takes 1 positional argument but 2 were given"
18,923,738
2
2013-09-20T18:43:31Z
18,923,763
11
2013-09-20T18:45:32Z
[ "python" ]
I am trying to develop a list(lets called "l") of list of tuple of two natural numbers(excluding 0) such as "a" can be a memeber of "l" if len(a) == len and for every member(lets call p) of "a", p[0] <= max and p[1] <= max For example poslist\_all(max=2,len=1) ``` [[(1,1)],[(1,2)],[(2,1)],[(2,2)]] ``` and poslist\_a...
The class instance is always passed as the first parameter to methods of the class. Try: ``` def inc(self, pnum): if ...: return ... else: return ... ```
Why is escaping of single quotes inconsistent on file read in Python?
18,924,102
4
2013-09-20T19:07:06Z
18,924,199
7
2013-09-20T19:12:09Z
[ "python", "string", "escaping" ]
Given two nearly identical text files (plain text, created in MacVim), I get different results when reading them into a variable in Python. I want to know why this is and how I can produce consistent behavior. For example, f1.txt looks like this: ``` This isn't a great example, but it works. ``` And f2.txt looks lik...
Both `f1` and `f2` contain perfectly normal, unescaped single quotes. The fact that their `repr` looks different is meaningless. There are a variety of different ways to represent the same string. For example, these are all equivalent literals: ``` "abc'def'ghi" 'abc\'def\'ghi' '''abc'def'ghi''' r"abc'def'ghi" ``` ...
Why is escaping of single quotes inconsistent on file read in Python?
18,924,102
4
2013-09-20T19:07:06Z
18,924,202
15
2013-09-20T19:12:19Z
[ "python", "string", "escaping" ]
Given two nearly identical text files (plain text, created in MacVim), I get different results when reading them into a variable in Python. I want to know why this is and how I can produce consistent behavior. For example, f1.txt looks like this: ``` This isn't a great example, but it works. ``` And f2.txt looks lik...
Python is giving you a string literal which, if you gave it back to Python, would result in the same string. This is known as the `repr()` (short for "representation") of the string. This may not (probably won't, in fact) match the string as it was originally specified, since there are so many ways to do that, and Pyth...
Selenium and iframe in html
18,924,146
7
2013-09-20T19:09:24Z
18,924,224
19
2013-09-20T19:13:50Z
[ "python", "iframe", "selenium", "selenium-webdriver" ]
Unable to use send\_key() for a iframe. How to select this iframe and which element inside this should be use for send\_key()? ![page image](http://i.stack.imgur.com/XzJ2E.png) and iframe html code ``` <iframe class="textarea" src="/framework/html/blank.html" style="width: 99%; border-width: 1px; height: 332px;"> #d...
`driver.switch_to.frame(driver.find_element_by_tag_name("iframe"))` assuming that driver is a healthy instance of webdriver. To continue with the default content do `driver.switch_to.default_content()` **EDIT**: When you have switched to needed frame, locate your webelement as you always do. I guess (but not sure) in ...
Mocking default=timezone.now for unit tests
18,924,869
7
2013-09-20T19:58:38Z
19,169,775
7
2013-10-03T21:44:14Z
[ "python", "django", "unit-testing", "mocking", "python-mock" ]
I'm trying to write unit tests for a django app that does a lot of datetime operations. I have installed [mock](http://www.voidspace.org.uk/python/mock/) to monkey patch django's `timezone.now` for my tests. While I am able to successfully mock `timezone.now` when it is called normally (actually calling `timezone.now(...
I just ran into this issue myself. The problem is that models are loaded before mock has patched the timezone module, so at the time the expression `default=timezone.now` is evaluated, it sets the `default` kwarg to the real `timezone.now` function. The solution is the following: ``` class MyModel(models.Model): ...
Procrustes Analysis with NumPy?
18,925,181
5
2013-09-20T20:19:40Z
18,927,641
13
2013-09-21T00:21:54Z
[ "python", "matlab", "numpy", "scipy" ]
Is there something like Matlab's [`procrustes`](http://www.mathworks.com/help/stats/procrustes.html) function in NumPy/SciPy or related libraries? --- For reference. Procrustes analysis aims to align 2 sets of points (in other words, 2 shapes) to minimize square distance between them by removing scale, translation an...
I'm not aware of any pre-existing implementation in Python, but it's easy to take a look at the MATLAB code using `edit procrustes.m` and port it to Numpy: ``` def procrustes(X, Y, scaling=True, reflection='best'): """ A port of MATLAB's `procrustes` function to Numpy. Procrustes analysis determines a lin...
Is there a way to NOT an arbitrary M x N matrix using numpy broadcasting?
18,925,979
2
2013-09-20T21:14:43Z
18,926,071
7
2013-09-20T21:21:16Z
[ "python", "numpy", "matrix", "numpy-broadcasting" ]
I have multiple matrices of 0's and 1's that I'd like to find the NOT'd versions of. For example: ``` M 0 1 0 1 0 1 0 1 0 ``` would become: ``` !M 1 0 1 0 1 0 1 0 1 ``` Right now I've got ``` for row in image: map(lambda x: 1 if x == 0 else 0, row) ``` which works perfectly well, but I've got a fe...
Given an integer array of 0s and 1s: ``` M = np.random.random_integers(0,1,(5,5)) print(M) # [[1 0 0 1 1] # [0 0 1 1 0] # [0 1 1 0 1] # [1 1 1 0 1] # [0 1 1 0 0]] ``` Here are three ways you could `NOT` the array: 1. Convert to a boolean array and use the `~` operator to [bitwise `NOT`](http://docs.scipy.org/doc...
how to extract a subset of a colormap as a new colormap in matplotlib?
18,926,031
14
2013-09-20T21:17:50Z
18,926,541
21
2013-09-20T21:59:41Z
[ "python", "matplotlib" ]
I would like to use a colormap from matplotlib e.g. CMRmap. But I don't want to use the "black" color at the beginning and the "white" color at the end. I'm interested to plot my data using the in-between colors. I think ppl use it quite often but I was searching over internet and could not manage to find any simple so...
The staticmethod [colors.LinearSegmentedColormap.from\_list](http://matplotlib.org/api/colors_api.html#matplotlib.colors.LinearSegmentedColormap.from_list) can be used to create new LinearSegmentedColormaps. Below, I sample the original colormap at 100 points between 0.2 and 0.8: ``` cmap(np.linspace(0.2, 0.8, 100)) `...
Numpy Array Get row index searching by a row
18,927,475
9
2013-09-20T23:56:43Z
18,927,811
25
2013-09-21T00:53:10Z
[ "python", "arrays", "numpy", "random-forest" ]
I am new to numpy and I am implementing clustering with random forest in python. My question is: How could I find the index of the exact row in an array? For example ``` [[ 0. 5. 2.] [ 0. 0. 3.] [ 0. 0. 0.]] ``` and I look for `[0. 0. 3.]` and get as result 1(the index of the second row). Any suggestion? Fo...
Why not simply do something like this? ``` >>> a array([[ 0., 5., 2.], [ 0., 0., 3.], [ 0., 0., 0.]]) >>> b array([ 0., 0., 3.]) >>> a==b array([[ True, False, False], [ True, True, True], [ True, True, False]], dtype=bool) >>> np.all(a==b,axis=1) array([False, True, False], d...
Why is my scrapy spider not following the Request callback in my item parse function?
18,928,253
3
2013-09-21T02:18:02Z
18,933,839
12
2013-09-21T14:34:19Z
[ "python", "scrapy" ]
I'm scraping a site to check in-stock status of various products. Unfortunately this requires actually clicking "Add to Cart" on the product page and checking the next page's message to determine if stock is available (i.e. it requires parsing two responses). I followed the [excellent documentation](http://doc.scrapy....
Posting my earlier comment as an answer. As all your POST requests (coming from `FormRequest.from_response()`) get redirected to `http://www.atlanticfirearms.com/browse-our-products.html`, you should set `dont_filter=True`: ``` if add_to_cart: # attempt to add to cart to verify availability reques...
TypeError: 'module' object is not callable for python object
18,928,826
6
2013-09-21T04:17:39Z
18,928,867
30
2013-09-21T04:25:11Z
[ "python" ]
I'm getting the following error in my code. I am attempting to make a maze solver and I am getting an error that says: ``` Traceback (most recent call last): File "./parseMaze.py", line 29, in <module> m = maze() TypeError: 'module' object is not callable ``` I am attempting to create a `maze` object called `m`...
It should be `maze.maze()` instead of `maze()`. Or you could change your `import` statement to `from maze import maze`.
how to install cloud9 IDE on ubuntu server
18,929,093
8
2013-09-21T05:03:46Z
18,941,769
7
2013-09-22T08:19:48Z
[ "python", "ubuntu", "web", "editor", "hosted" ]
I have a development server which runs mostly python-based apps. I like the interface of tools like cloud9, but since I have a server I'd rather have something similar on my own server. This is what I mean by "self-hosting". I only need to edit local files (ie, files on that server). The server is running Ubuntu serve...
Getting Cloud9 IDE installed on your own server is not as hard as you may think. It is basically these steps: 1. [Install node.js](http://askubuntu.com/a/49391/93577) 2. [Clone Cloud9's Git repository to your server and install](https://github.com/ajaxorg/cloud9/#installation-and-usage) 3. Run a command in the termin...
how to install cloud9 IDE on ubuntu server
18,929,093
8
2013-09-21T05:03:46Z
28,885,517
12
2015-03-05T18:54:56Z
[ "python", "ubuntu", "web", "editor", "hosted" ]
I have a development server which runs mostly python-based apps. I like the interface of tools like cloud9, but since I have a server I'd rather have something similar on my own server. This is what I mean by "self-hosting". I only need to edit local files (ie, files on that server). The server is running Ubuntu serve...
Cloud9's git repository and instructions have changed since the other answer was posted. See <https://github.com/c9/core/> for more information. The following instructions seem to work for me on a vanilla Ubuntu 14.04. 1. [Install Git](http://git-scm.com/book/en/v2/Getting-Started-Installing-Git) if you haven't alread...
django modifying the request object
18,930,234
11
2013-09-21T07:48:57Z
18,931,697
22
2013-09-21T10:47:11Z
[ "python", "django" ]
I already have a django project and it logical like those: url: URL?username=name&pwd=passwd view: ``` def func(request): dic = request.GET username = dic.get("username") pwd = dic.get("pwd") ``` but now we need encrypt the data. Then, the request become this: url: URL?crypt=XXXXXXXXXX (XXXXXXXX is encry...
[`django.http.QueryDict`](https://docs.djangoproject.com/en/dev/ref/request-response/#querydict-objects) objects that are assigned to `request.GET` and `request.POST` are immutable. You can convert it to a mutable `QueryDict` instance by copying it: ``` request.GET = request.GET.copy() ``` Afterwards you'll be able ...
Getting PyCharm to recognize Anaconda's SciPy
18,931,049
13
2013-09-21T09:28:32Z
19,025,207
28
2013-09-26T10:03:41Z
[ "python", "scipy", "pycharm", "anaconda" ]
I need to use the SciPy libraries inside the PyCharm IDE (on a Mac OSX Lion machine). The SciPy website writes that the simplest installation method for Mac users is to install Anaconda (or an equivalent distro). I used the Anaconda installer, and it created an anaconda directory in my home folder, where I find a `lib/...
I'm still coming to terms with the Python ecosystem and PyCharm, so take the following with a grain of salt, but after [reading up a bit](http://mirnazim.org/writings/python-ecosystem-introduction/), I thought I'd write a detailed explanation. During installation, Anaconda changes the default Python interpreter to ~/a...
TypeError: string indices must be integers, not str // working with dict
18,931,315
15
2013-09-21T10:03:10Z
18,931,339
20
2013-09-21T10:06:08Z
[ "python", "dictionary" ]
I am trying to define a procedure, `involved(courses, person)`, that takes as input a courses structure and a person and returns a Dictionary that describes all the courses the person is involved in. Here is my `involved(courses, person)` function: ``` def involved(courses, person): for time1 in courses: ...
`time1` is the key of the most outer dictionary, eg, `feb2012`. So then you're trying to index the string, but you can only do this with integers. I think what you wanted was: ``` for info in courses[time1][course]: ``` As you're going through each dictionary, you must add another nest.
python pandas: why map is faster?
18,932,254
3
2013-09-21T11:52:47Z
18,933,101
9
2013-09-21T13:21:06Z
[ "python", "pandas" ]
in pandas' manual, there is this example about indexing: ``` In [653]: criterion = df2['a'].map(lambda x: x.startswith('t')) In [654]: df2[criterion] ``` then Wes wrote: ``` **# equivalent but slower** In [655]: df2[[x.startswith('t') for x in df2['a']]] ``` can anyone here explain a bit why the map approach is fas...
Arguments about why a certain way of doing things in Python "should be" faster can't be taken too seriously, because you're often measuring implementation details which may behave differently in certain situations. As a result, when people guess what should be faster, they're often (usually?) wrong. For example, I find...
Delete array values in python
18,935,656
2
2013-09-21T17:46:32Z
18,935,704
7
2013-09-21T17:50:39Z
[ "python", "arrays" ]
I have a simple question, if I have an array of strings in python: ['a', 'b', 'c', 'd'] is there a way that I can compare another string and if it exists in the array delete that value and everything after it? I'm new to python and I'm not too familiar with the syntax but pseudocode: ``` s = 'b' array = ['a', 'b', 'c'...
``` s = 'b' array = ['a', 'b', 'c', 'd'] if s in array: del array[array.index(s):] ```
How to escape special characters of a string with single backslashes
18,935,754
5
2013-09-21T17:55:26Z
18,935,765
17
2013-09-21T17:56:56Z
[ "python", "nginx", "escaping" ]
I'm trying to escape the characters `-]\^$*.` each with a single backslash `\`. For example the string: `^stack.*/overflo\w$arr=1` will become: ``` \^stack\.\*/overflo\\w\$arr=1 ``` What's the most efficient way to do that in Python? `re.escape` double escapes which isn't what I want: ``` '\\^stack\\.\\*\\/overflo...
This is one way to do it (in Python 3.x): ``` escaped = a_string.translate(str.maketrans({"-": r"\-", "]": r"\]", "\\": r"\\", "^": r"\^", "$": r"\...
Count distinct words from a Pandas Data Frame
18,936,957
11
2013-09-21T19:56:21Z
18,937,023
10
2013-09-21T20:03:02Z
[ "python", "text", "pandas" ]
I've a Pandas data frame, where one column contains text. I'd like to get a list of unique words appearing across the entire column (space being the only split). ``` import pandas as pd r1=['My nickname is ft.jgt','Someone is going to my place'] df=pd.DataFrame(r1,columns=['text']) ``` The output should look like t...
Use `collections.Counter`: ``` >>> from collections import Counter >>> r1=['My nickname is ft.jgt','Someone is going to my place'] >>> Counter(" ".join(r1).split(" ")).items() [('Someone', 1), ('ft.jgt', 1), ('My', 1), ('is', 2), ('to', 1), ('going', 1), ('place', 1), ('my', 1), ('nickname', 1)] ```
Count distinct words from a Pandas Data Frame
18,936,957
11
2013-09-21T19:56:21Z
18,937,309
13
2013-09-21T20:31:45Z
[ "python", "text", "pandas" ]
I've a Pandas data frame, where one column contains text. I'd like to get a list of unique words appearing across the entire column (space being the only split). ``` import pandas as pd r1=['My nickname is ft.jgt','Someone is going to my place'] df=pd.DataFrame(r1,columns=['text']) ``` The output should look like t...
Use a `set` to create the sequence of unique elements. Do some clean-up on `df` to get the strings in lower case and split: ``` df['text'].str.lower().str.split() Out[43]: 0 [my, nickname, is, ft.jgt] 1 [someone, is, going, to, my, place] ``` Each list in this column can be passed to `set.update` fun...
Python: Clear screen in shell
18,937,058
24
2013-09-21T20:05:49Z
20,247,284
16
2013-11-27T16:03:19Z
[ "screen", "clear", "python" ]
Just a quick question: How do you clear the screen in shell? I've seen ways like: ``` import os os.system('cls') ``` This just opens the windows cmd, clears the screen and closes but I want the shell window to be cleared (PS: I don't know this helps, but I'm using version 3.3.2 of Python) Thank you :)
For OS X, you can use subprocess module and call 'cls' from shell: ``` import subprocess as sp sp.call('cls',shell=True) ``` To prevent '0' from showing on top of the window, replace the 2nd line with: ``` tmp = sp.call('cls',shell=True) ``` For linux, you must replace `cls` command with `clear` ``` tmp = sp.call(...
Python: Clear screen in shell
18,937,058
24
2013-09-21T20:05:49Z
23,516,888
19
2014-05-07T11:43:43Z
[ "screen", "clear", "python" ]
Just a quick question: How do you clear the screen in shell? I've seen ways like: ``` import os os.system('cls') ``` This just opens the windows cmd, clears the screen and closes but I want the shell window to be cleared (PS: I don't know this helps, but I'm using version 3.3.2 of Python) Thank you :)
``` import os os.system('cls') # for Windows os.system('clear') # for Linux/OS X ```
Python: Clear screen in shell
18,937,058
24
2013-09-21T20:05:49Z
31,871,439
13
2015-08-07T06:56:11Z
[ "screen", "clear", "python" ]
Just a quick question: How do you clear the screen in shell? I've seen ways like: ``` import os os.system('cls') ``` This just opens the windows cmd, clears the screen and closes but I want the shell window to be cleared (PS: I don't know this helps, but I'm using version 3.3.2 of Python) Thank you :)
What about the shortcut `CTRL`+`L`? It works for all shells e.g. Python, Bash, MySQL, MATLAB, etc.
How to convert nested list of lists into a list of tuples in python 3.3?
18,938,276
5
2013-09-21T22:21:52Z
18,938,286
9
2013-09-21T22:23:33Z
[ "python", "list", "tuples", "nested-lists", "data-type-conversion" ]
I am trying to convert a nested list of lists into a list of tuples in Python 3.3. However, it seems that I don't have the logic to do that. The input looks as below: ``` >>> nested_lst = [['tom', 'cat'], ['jerry', 'mouse'], ['spark', 'dog']] ``` And the desired ouptput should look as exactly as follows: ``` nested...
Just use a list comprehension: ``` nested_lst_of_tuples = [tuple(l) for l in nested_lst] ``` Demo: ``` >>> nested_lst = [['tom', 'cat'], ['jerry', 'mouse'], ['spark', 'dog']] >>> [tuple(l) for l in nested_lst] [('tom', 'cat'), ('jerry', 'mouse'), ('spark', 'dog')] ```
When is the object() built-in useful?
18,939,327
7
2013-09-22T01:08:14Z
18,939,439
11
2013-09-22T01:31:20Z
[ "python", "python-3.x", "built-in" ]
I'm trying to figure out what I would use the `object()` built-in function for. It takes no arguments, and returns a "featureless object" of the type that is common to all Python classes, and has all the methods that are common to all Python classes. To quote Jack Skellington, [WHAT. IS. THIS?](http://docs.python.org/...
Even if you do not need to program with it, `object` serves a purpose: it is the common class from which all other objects are derived. It is the last class listed by the `mro` ([method resolution order](http://www.python.org/2.3/mro.html)) method. We need a name and object for this concept, and `object` serves this pu...
Python: Difference between filter(function, sequence) and map(function, sequence)
18,939,596
11
2013-09-22T02:10:51Z
18,939,610
12
2013-09-22T02:13:42Z
[ "python", "functional-programming", "documentation", "map-function", "filterfunction" ]
I'm reading through the Python documentation to really get in depth with the Python language and came across the filter and map functions. I have used filter before, but never map, although I have seen both in various Python questions here on SO. After reading about them in the Python tutorial, I'm confused on the dif...
``` map(cube, range(1, 11)) ``` is equivalent to ``` [cube(1), cube(2), ..., cube(10)] ``` While the list returned by ``` filter(f, range(2, 25)) ``` is equivalent to `result` after running ``` result = [] for i in range(2, 25): if f(i): result.append(i) ``` Notice that when using `map`, the items in...
Python: Difference between filter(function, sequence) and map(function, sequence)
18,939,596
11
2013-09-22T02:10:51Z
18,939,630
8
2013-09-22T02:17:53Z
[ "python", "functional-programming", "documentation", "map-function", "filterfunction" ]
I'm reading through the Python documentation to really get in depth with the Python language and came across the filter and map functions. I have used filter before, but never map, although I have seen both in various Python questions here on SO. After reading about them in the Python tutorial, I'm confused on the dif...
`filter()`, as its name suggests, filters the original iterable and retents the items that returns `True` for the function provided to `filter()`. `map()` on the other hand, apply the supplied function to each element of the iterable and return a list of results for each element. Follows the example that you gave, le...
strange UnicodeDecodeError on django
18,940,441
9
2013-09-22T04:48:50Z
20,337,302
22
2013-12-02T20:35:21Z
[ "python", "django", "http", "unicode" ]
Was doing a fresh install of my vagrant box and my dev environment and when trying to run my django project I get the following error. Any ideas whats going on? ``` ---------------------------------------- [21/Sep/2013 23:44:03] code 400, message Bad HTTP/0.9 request type ('\x16\x03\x00\x00E\x01\x00\x00A\x03\x00R>u\xa...
Looks like you tried to hit `http` website with `https`
How to conjugate a verb in NLTK given POS tag?
18,942,096
5
2013-09-22T09:05:28Z
18,945,825
11
2013-09-22T16:03:37Z
[ "python", "nlp", "nltk" ]
Given a POS tag, such as VBD, how can I conjugate a verb to match with NLTK? e.g. ``` VERB: go POS: VBD RESULT: went ```
NLTK doesn't currently provide conjugations. [Pattern-en](http://www.clips.ua.ac.be/pages/pattern-en#conjugation) and [nodebox](http://nodebox.net/code/index.php/Linguistics#verb_conjugation) do conjugations. Sometimes the examples in the pattern-en website don't work as shown. This worked for me: ``` >>> from patter...
Add new column in Pandas DataFrame Python
18,942,506
34
2013-09-22T09:50:44Z
18,942,558
41
2013-09-22T09:55:58Z
[ "python", "pandas", "dataframe" ]
I have dataframe in Pandas for example: ``` Col1 Col2 A 1 B 2 C 3 ``` Now if I would like to add one more column named Col3 and the value is based on Col2. In formula, if Col2 > 1, then Col3 is 0, otherwise would be 1. So, in the example above. The output would be: ``` Col1 Col2 Col3 A 1 1 B 2 ...
You just do an opposite comparison. `if Col2 <= 1`. This will return a boolean Series with `False` values for those greater than 1 and `True` values for the other. If you convert it to an `int64` dtype, `True` becomes 1 and `False` become `0`, ``` df['Col3'] = (df['Col2'] <= 1).astype(int) ``` If you want a more gene...
python multiline regular expressions
18,943,223
8
2013-09-22T11:09:09Z
18,943,259
17
2013-09-22T11:13:19Z
[ "python", "regex" ]
How do I extract all the characters (including newline characters) until the first occurrence of the giver sequence of words? For example with the following input: input text: ``` "shantaram is an amazing novel. It is one of the best novels i have read. the novel is written by gregory david roberts. He is an australi...
You want to use the `DOTALL` option to match across newlines. From [doc.python.org](http://docs.python.org/2/library/re.html#re.DOTALL): > re.DOTALL > > Make the '.' special character match any character at all, including a newline; without this flag, '.' will match anything except a newline. Demo: ``` In [1]: impor...
Create a function with four parameters
18,943,673
15
2013-09-22T12:09:44Z
18,944,069
8
2013-09-22T12:57:55Z
[ "python", "string", "function", "parameters", "boolean" ]
Right, so I'm doing a homework assignment and I am asked to do the following: Create a function called student data, that takes four parameters, a name (a string), age (an integer), student number (a string) and whether they are enrolled in CSCA08 (a boolean), and returns a string containing that information in the fo...
In Python, there are *objects* and *names*. An object has a type, a name is just a pointer to an object. If an object doesn't have a name, you cannot access it (in fact, if there are no names pointing to an object, Python will get rid of it altogether). In other languages, a name is usually called *variable* and the a...
ImportError: No module named jinja2
18,944,345
14
2013-09-22T13:28:02Z
18,983,050
19
2013-09-24T13:30:52Z
[ "python", "google-app-engine", "python-2.7" ]
Using google-app-engine tutorial, I got the following error stack message: ``` Traceback (most recent call last): File "C:\Program Files (x86)\Google\google_appengine\google\appengine\runtime\wsgi.py", line 239, in Handle handler = _config_handle.add_wsgi_middleware(self._LoadHandler()) File "C:\Program Files (x86)\Go...
In order to use Jinja locally, you need to install it locally ``` easy_install Jinja2 ``` or ``` pip install Jinja2 ```
why I can't define a function like fun(**kwargs, *args)?
18,944,962
2
2013-09-22T14:38:50Z
18,945,238
10
2013-09-22T15:05:53Z
[ "python" ]
args always before kwargs when many python book introduce them. I just swap the position of them, but the interpreter told me this is a invalid syntax. Can anyone explain it?
It is against the syntax of Python to define positional arguments after keyword arguments. Thus how should it make sense for you to define a function that first accepts a dictionary of keyword parameters and then a tuple of positional parameters? For an explanation of the rationale behind the rule, imagine if you were...
Combine Pandas DataFrame DateTime Columns
18,944,993
4
2013-09-22T14:41:25Z
18,945,087
10
2013-09-22T14:51:25Z
[ "python", "pandas", "dataframe" ]
Supposely I have dataframes as below: ``` Year Month Day 2003 1 8 2003 2 7 ``` How to combine the Year, Month, and Day in the newly defined column in the dataframe as such the dataframe would be: ``` Year Month Day Date 2003 1 8 2003-1-8 2003 2 7 2003-2-7 ``` Any idea on this? I am using pandas...
``` >>> from datetime import datetime >>> df['Date'] = df.apply(lambda row: datetime( row['Year'], row['Month'], row['Day']), axis=1) >>> df Year Month Day Date 0 2003 1 8 2003-01-08 00:00:00 1 2003 2 7 2003-02-07 00:00:00 ```
How to delete all entities for NDB Model in Google App Engine for python?
18,945,109
15
2013-09-22T14:53:06Z
18,945,266
33
2013-09-22T15:08:14Z
[ "python", "google-app-engine", "app-engine-ndb" ]
I have a ndb model class: ``` class Game(ndb.Model): gameID = ndb.IntegerProperty() gameName = ndb.StringProperty() ``` Is there any way to quickly just delete all entities thats stored in the database for this class? Something like `Game.deletAll()`
No, but you could easily do this with something like: ``` from google.appengine.ext import ndb ndb.delete_multi( Game.query().fetch(keys_only=True) ) ```
Python3 installed successfully, but cannot be opened in terminal
18,946,286
8
2013-09-22T16:50:48Z
19,641,915
12
2013-10-28T18:03:56Z
[ "python", "osx", "python-3.x" ]
Yesterday I've reinstalled my Mac OS X 10.8, before this reinstallation there were python2.7.5 and python3.3.2 installed on my machine and worked fine, but after this system reinstallation I cannot open python3 again. So I downloaded the DMG package of Python3 and reinstalled it again, but it still throwing this except...
Well, I think this problem should be marked as answered. The solution is just like Mr mata said, I need to unset $PYTHONPATH, then everything goes on well..
Why shouldn't I use PyPy over CPython if PyPy is 6.3 times faster?
18,946,662
482
2013-09-22T17:24:13Z
18,946,700
53
2013-09-22T17:27:18Z
[ "python", "performance", "jit", "pypy", "cpython" ]
I've been hearing a lot about the [PyPy](http://en.wikipedia.org/wiki/PyPy) project. They claim it is 6.3 times faster than the [CPython](http://en.wikipedia.org/wiki/CPython) interpreter on [their site](http://speed.pypy.org). Whenever we talk about dynamic languages like Python, speed is one of the top issues. To so...
Because pypy is not 100% compatible, takes 8 gigs of ram to compile, is a moving target, and highly experimental, where cpython is stable, the default target for module builders for 2 decades (including c extensions that don't work on pypy), and already widely deployed. Pypy will likely never be the reference implemen...
Why shouldn't I use PyPy over CPython if PyPy is 6.3 times faster?
18,946,662
482
2013-09-22T17:24:13Z
18,946,741
27
2013-09-22T17:31:39Z
[ "python", "performance", "jit", "pypy", "cpython" ]
I've been hearing a lot about the [PyPy](http://en.wikipedia.org/wiki/PyPy) project. They claim it is 6.3 times faster than the [CPython](http://en.wikipedia.org/wiki/CPython) interpreter on [their site](http://speed.pypy.org). Whenever we talk about dynamic languages like Python, speed is one of the top issues. To so...
The second question is easier to answer: you basically *can* use PyPy as a drop-in replacement if all your code is pure Python. However, many widely used libraries (including some of the standard library) are written in C and compiled as Python extensions. Some of these can be made to work with PyPy, some can't. PyPy p...
Why shouldn't I use PyPy over CPython if PyPy is 6.3 times faster?
18,946,662
482
2013-09-22T17:24:13Z
18,946,824
518
2013-09-22T17:40:36Z
[ "python", "performance", "jit", "pypy", "cpython" ]
I've been hearing a lot about the [PyPy](http://en.wikipedia.org/wiki/PyPy) project. They claim it is 6.3 times faster than the [CPython](http://en.wikipedia.org/wiki/CPython) interpreter on [their site](http://speed.pypy.org). Whenever we talk about dynamic languages like Python, speed is one of the top issues. To so...
PyPy, as others have been quick to mention, has tenuous support for C extensions. It *has* support, but typically at slower-than-Python speeds and it's iffy at best. Hence a lot of modules simply *require* CPython. Cython and Numpy are *awesome* for numerics, and most people who actually need speed in Python are using ...