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 |
|---|---|---|---|---|---|---|---|---|---|
Install opencv for Python 3.3 | 20,953,273 | 33 | 2014-01-06T15:29:14Z | 20,953,731 | 13 | 2014-01-06T15:50:53Z | [
"python",
"opencv",
"python-3.x"
] | Is OpenCV still not available for Python 3.3 and do I really have to downgrade to Python 2.7 to use it? I didn't find much about it on the internet, only some posts from 2012 that OpenCV wasn't yet ported to be used in Python 3.x. But now it's 2014 and after trying to install the latest OpenCV 2.4.x and copying the `cv... | Yes support for Python 3 it is still not available in current version, but it will be available from version [3.0, (see this ticket)](http://code.opencv.org/issues/2811). If you really want to have python 3 try using development version, you can download it [from GitHub](https://github.com/Itseez/opencv/tree/master).
... |
Install opencv for Python 3.3 | 20,953,273 | 33 | 2014-01-06T15:29:14Z | 21,212,023 | 24 | 2014-01-19T01:12:55Z | [
"python",
"opencv",
"python-3.x"
] | Is OpenCV still not available for Python 3.3 and do I really have to downgrade to Python 2.7 to use it? I didn't find much about it on the internet, only some posts from 2012 that OpenCV wasn't yet ported to be used in Python 3.x. But now it's 2014 and after trying to install the latest OpenCV 2.4.x and copying the `cv... | Following Pawelmhm's pointer, I installed latest OpenCV from Git master on Ubuntu 12.10 with Python 3.2 and 3.3 bindings. I was able to get feature detectors, matchers, homography, and perspective stuff working!
Steps:
1. Ensure you have the \*-dev package installed for your version of Python
* Eg: `sudo apt-get i... |
Install opencv for Python 3.3 | 20,953,273 | 33 | 2014-01-06T15:29:14Z | 32,084,967 | 7 | 2015-08-19T01:09:57Z | [
"python",
"opencv",
"python-3.x"
] | Is OpenCV still not available for Python 3.3 and do I really have to downgrade to Python 2.7 to use it? I didn't find much about it on the internet, only some posts from 2012 that OpenCV wasn't yet ported to be used in Python 3.x. But now it's 2014 and after trying to install the latest OpenCV 2.4.x and copying the `cv... | Here a solution for (I believe as seen by 'cp34' on the link below) Python 3.4.
Go to to <http://www.lfd.uci.edu/~gohlke/pythonlibs/#opencv>.
Download the appropriate .whl.
Go to the directory where the .whl is saved.
Use pip to install the .whl. e.g. `pip install opencv_python-3.0.0-cp34-none-win_amd64.whl`
Then ... |
Python writing binary | 20,955,543 | 7 | 2014-01-06T17:21:30Z | 20,955,643 | 10 | 2014-01-06T17:27:43Z | [
"python",
"file",
"python-3.x",
"binary"
] | I use python 3
I tried to write binary to file I use r+b.
```
for bit in binary:
fileout.write(bit)
```
where binary is a list that contain numbers.
How do I write this to file in binary?
The end file have to look like
b' x07\x08\x07\
Thanks | > where binary is a list that contain numbers
A number can have one thousand and one different binary representations (endianess, width, 1-complement, 2-complement, floats of different precision, etc). So first you have to decide in which representation you want to store your numbers. Then you can use the [struct](htt... |
Python writing binary | 20,955,543 | 7 | 2014-01-06T17:21:30Z | 20,955,678 | 22 | 2014-01-06T17:30:03Z | [
"python",
"file",
"python-3.x",
"binary"
] | I use python 3
I tried to write binary to file I use r+b.
```
for bit in binary:
fileout.write(bit)
```
where binary is a list that contain numbers.
How do I write this to file in binary?
The end file have to look like
b' x07\x08\x07\
Thanks | When you open a file in binary mode, then you are essentially working with the [`bytes`](http://docs.python.org/3/library/stdtypes.html#bytes) type. So when you write to the file, you need to pass a `bytes` object, and when you read from it, you get a `bytes` object. In contrast, when opening the file in text mode, you... |
Python multiprocessing- sharing a complex object | 20,955,683 | 6 | 2014-01-06T17:30:32Z | 20,958,036 | 8 | 2014-01-06T19:50:21Z | [
"python",
"concurrency",
"multiprocessing"
] | I've got a large dict-like object that needs to be shared between a number of worker processes. Each worker reads a random subset of the information in the object and does some computation with it. I'd like to avoid copying the large object as my machine quickly runs out of memory.
I was playing with the code for [thi... | I'm afraid virtually nothing here works the way you *hope* it works :-(
First note that identical `id()` values produced *by different processes* tell you *nothing* about whether the objects are really the same object. Each process has its own virtual address space, assigned by the operating system. The same virtual a... |
How do I generate and open an Outlook email with Python (but do not send) | 20,956,424 | 7 | 2014-01-06T18:11:01Z | 20,956,653 | 7 | 2014-01-06T18:24:59Z | [
"python",
"email",
"outlook"
] | I have a script that automatically creates and sends emails sends emails using the simple function below:
```
def Emailer(text, subject, recipient):
import win32com.client as win32
outlook = win32.Dispatch('outlook.application')
mail = outlook.CreateItem(0)
mail.To = recipient
mail.Subject = su... | Call `mail.Display(True)` instead of `mail.send` |
Distinguish between f() and f(**kwargs) in Python 2.7 | 20,956,659 | 4 | 2014-01-06T18:25:28Z | 20,956,706 | 9 | 2014-01-06T18:28:41Z | [
"python",
"python-2.7"
] | I'd like to be able to tell if a function was declared as `f()` or `f(**kwargs)` in Python 2.7, so I know whether or not it can accept arbitrary keyword arguments... but invoke.getargspec.args() returns [] in both cases. Is there a way of doing this? | You need to look at `inspect.getargspec().keywords` instead. If it is `None` no `**kwargs` was given.
From the [`inspect.getargspec()` documentation](http://docs.python.org/2/library/inspect.html#inspect.getargspec):
> *varargs* and *keywords* are the names of the `*` and `**` arguments or `None`.
Demo:
```
>>> imp... |
Merge Duplicates based on column? | 20,956,671 | 4 | 2014-01-06T18:26:11Z | 20,956,783 | 7 | 2014-01-06T18:32:31Z | [
"python",
"pandas",
"grouping"
] | Here's my situation -
```
In[9]: df
Out[9]:
fruit val1 val2
0 Orange 1 1
1 orANGE 2 2
2 apple 3 3
3 APPLE 4 4
4 mango 5 5
5 appLE 6 6
In[10]: type(df)
Out[10]: pandas.core.frame.DataFrame
```
How do remove case-insensitive duplicates such that resultin... | In two steps:
```
df['fruit'] = df['fruit'].map(lambda x: x.lower())
res = df.groupby('fruit').sum()
res
# val1 val2
# fruit
# apple 13 13
# mango 5 5
# orange 3 3
```
And to recover your structure:
```
res.reset_index()
```
---
as per the comment, the lower casi... |
Python: Selenium Firefox Webdriver failing with error: 'Can't load the profile...WARN addons.xpi..." | 20,957,968 | 25 | 2014-01-06T19:45:53Z | 20,958,024 | 28 | 2014-01-06T19:49:49Z | [
"python",
"firefox",
"selenium",
"xpi"
] | I am trying to run the following Python code to create a Firefox Webdriver window via Selenium:
```
from selenium import webdriver
driver = webdriver.Firefox()
driver.get("http://www.google.com")
```
While this code worked fine a few weeks ago, it now produces the following foreboding message:
```
Traceback (most r... | Selenium 2.35 is not compatible with Firefox 26. As the [release notes](http://selenium.googlecode.com/git/py/CHANGES) say, FF 26 support was added in Selenium 2.39. You need to update to 2.39. Try `pip install -U selenium` instead. |
Python: Removing negatives from a list of numbers | 20,959,964 | 3 | 2014-01-06T21:53:31Z | 20,960,018 | 7 | 2014-01-06T21:56:21Z | [
"python",
"list",
"negative-number"
] | The question is to remove negatives from numbers.
When `remove_negs([1, 2, 3, -3, 6, -1, -3, 1])` is executed, the result is: `[1, 2, 3, 6, -3, 1]`. The result is suppose to be `[1, 2, 3, 6, 3, 1]`. what is happening is that if there are two negative numbers in a row (e.g., `-1, -3`) then the second number will not ge... | It's generally a bad idea to remove elements from a list while iterating over it (see [the link](http://arshajii.com/coding-faqs/conc-list-mod.html) in my comment for an explanation as to why this is so). A better approach would be to use a [list comprehension](http://docs.python.org/3/tutorial/datastructures.html#list... |
How do I get warnings.warn to issue a warning and not ignore the line? | 20,960,110 | 11 | 2014-01-06T22:01:32Z | 20,960,427 | 12 | 2014-01-06T22:22:49Z | [
"python",
"python-2.7",
"warnings",
"suppress-warnings"
] | I'm trying to raise a `DeprecationWarning`, with a code snippet based on the example shown in the docs. <http://docs.python.org/2/library/warnings.html#warnings.warn>
Official
```
def deprecation(message):
warnings.warn(message, DeprecationWarning, stacklevel=2)
```
Mine
```
import warnings
warnings.warn("This ... | From the docs:
> By default, Python installs several warning filters, which can be
> overridden by the command-line options passed to -W and calls to
> filterwarnings().
>
> * DeprecationWarning and PendingDeprecationWarning, and ImportWarning are ignored.
> * BytesWarning is ignored unless the -b option is given once... |
What is %pylab? | 20,961,287 | 16 | 2014-01-06T23:33:18Z | 20,962,070 | 13 | 2014-01-07T00:49:14Z | [
"python",
"matplotlib"
] | I keep seeing people use `%pylab`in various code snippits, particularly with iPython. However, I cannot see where `%pylab`is mentioned anywhere in Learning Python (and the few other Python books I have) and am not really sure what it means.
I'm sure the answer is simple, but can anyone enlighten me? | *`%pylab`* is a *magic function* in ***ipython***.
Magic functions in pylab always begin with the percent sign (%) followed without
any spaces by a small text string; in essence, ipython magic functions define
shortcuts particularly useful for interactive work, e.g.,
to give you an idea of how magic functions work in ... |
What is %pylab? | 20,961,287 | 16 | 2014-01-06T23:33:18Z | 24,338,062 | 9 | 2014-06-21T03:45:32Z | [
"python",
"matplotlib"
] | I keep seeing people use `%pylab`in various code snippits, particularly with iPython. However, I cannot see where `%pylab`is mentioned anywhere in Learning Python (and the few other Python books I have) and am not really sure what it means.
I'm sure the answer is simple, but can anyone enlighten me? | `%pylab` is shortcut for typing all of below commands which in essence adds numpy and matplotlib in to your session. This was added in IPython as a transition tool and current recommendation is that **you should not use it**. The core reason is that below sets of commands imports too much in the global namespace and al... |
Making a list with every possible combination of 0's and 1's in Python | 20,962,853 | 3 | 2014-01-07T02:22:40Z | 20,962,871 | 13 | 2014-01-07T02:24:05Z | [
"python"
] | I am trying to iterate over every possible combination of 0's and 1's in a list. For example, if I was working with 3 parameters, I would get:
```
[0, 0, 0], [0, 0, 1], [0, 1, 0], [1, 0, 0], [1, 1, 0], [1, 0, 1], [0, 1, 1], [1, 1, 1]
```
I thought the solution on [Array combinations of 0s and 1s](http://stackoverflow... | Use [`itertools.product`](http://docs.python.org/3/library/itertools.html#itertools.product):
```
import itertools
for numbers in itertools.product([0, 1], repeat=3):
print(numbers)
```
output:
```
(0, 0, 0)
(0, 0, 1)
(0, 1, 0)
(0, 1, 1)
(1, 0, 0)
(1, 0, 1)
(1, 1, 0)
(1, 1, 1)
``` |
Cumulative sum and percentage on column? | 20,965,046 | 16 | 2014-01-07T06:11:04Z | 20,965,090 | 31 | 2014-01-07T06:15:34Z | [
"python",
"pandas",
"dataframe",
"cumulative-sum"
] | I have a `DataFrame` like this:
`df`:
```
fruit val1 val2
0 orange 15 3
1 apple 10 13
2 mango 5 5
```
How do I get Pandas to give me a cumulative sum and percentage column on only `val1`?
Desired output:
`df_with_cumsum`:
```
fruit val1 val2 cum_sum cum_perc
0 orange 15 3 ... | ```
df['cum_sum'] = df.val1.cumsum()
df['cum_perc'] = 100*df.cum_sum/df.val1.sum()
```
This will add the columns to `df`. If you want a copy, copy `df` first and then do these operations on the copy. |
Pyramid - I have to run python setup.py install before changes register | 20,967,112 | 2 | 2014-01-07T08:34:15Z | 20,967,674 | 7 | 2014-01-07T09:10:19Z | [
"python",
"configuration",
"pyramid",
"pycharm"
] | I am just starting learning Pyramid using Pycharm. I have been reading tutorials but unfortunately there don't seem to be many out there.
My problem is that whenever I make a change to the source I have to run `python setup.py install` before I can test my changes. This step seems unnecessary and I am confused why this... | You should remove all the installed bits in Python site-packages and run `python setup.py develop` to create a symlink (or .egg-link) to your project in site-packages, instead of the actual installed package. This should make your changes work as usual, without running `install` all the time. |
How to pass extra argument when creating object that uses ** (double star) syntax in python? | 20,967,945 | 4 | 2014-01-07T09:24:50Z | 20,968,092 | 7 | 2014-01-07T09:32:17Z | [
"python",
"function",
"object",
"arguments"
] | How do I pass an extra argument "`page_name`" when creating `NotebookPage` object below? I get the error below:
```
class NotebookPage(wx.Panel):
def __init__(self, *args, **kwargs):
wx.Panel.__init__(self, *args, **kwargs)
NotebookPage(self, name='NotebookPage0', page_name=page)
TypeError: 'page_name... | You should remove additional argument from `kwargs` before calling `__init__`. For example with dict [`pop`](http://docs.python.org/2/library/stdtypes.html?highlight=dict.pop#dict.pop) method:
```
class NotebookPage(wx.Panel):
def __init__(self, *args, **kwargs):
page_name = kwargs.pop('page_name', None)
... |
How to download datasets for sklearn? - python | 20,968,237 | 4 | 2014-01-07T09:38:45Z | 20,974,351 | 8 | 2014-01-07T14:36:22Z | [
"python",
"machine-learning",
"dataset",
"nlp",
"scikit-learn"
] | In NLTK there is a `nltk.download()` function to download the datasets that are comes with the NLP suite.
In sklearn, it talks about loading data sets (<http://scikit-learn.org/stable/datasets/>) and fetching datas from <http://mldata.org/> but for the rest of the datasets, the instructions were to download from the s... | A network connection problem has probably corrupted the source archive on your drive. Delete the twenty groups related files or folders from you `scikit_learn_data` folder in your user's home directory and try again.
```
$ cd ~/scikit_learn_data'
$ rm -rf 20news_home
$ rm 20news-bydate.pkz
``` |
Exponentials in python x.**y vs math.pow(x, y) | 20,969,773 | 17 | 2014-01-07T10:52:57Z | 20,970,087 | 35 | 2014-01-07T11:09:34Z | [
"python",
"math",
"built-in",
"pow"
] | Which one is more efficient using math.pow or the \*\* operator? When should I use one over the other?
So far I know that `x**y` can return an `int` or a `float` if you use a decimal
the function `pow` will return a float
```
import math
print math.pow(10, 2)
print 10. ** 2
``` | Using the power operator `**` will be faster as it wonât have the overhead of a function call. You can see this if you disassemble the Python code:
```
>>> dis.dis('7. ** i')
1 0 LOAD_CONST 0 (7.0)
3 LOAD_NAME 0 (i)
6 BINARY_POWER
... |
how to do a left,right and mid of a string in a pandas dataframe | 20,970,279 | 11 | 2014-01-07T11:20:20Z | 20,970,328 | 18 | 2014-01-07T11:22:28Z | [
"python",
"pandas"
] | in a pandas dataframe how can I apply a sort of excel left('state',2) to only take the first two letters. Ideally I want to learn how to use left,right and mid in a dataframe too. So need an equivalent and not a "trick" for this specific example.
```
data = {'state': ['Auckland', 'Otago', 'Wellington', 'Dunedin', 'Ham... | First two letters for each value in a column:
```
>>> df['StateInitial'] = df['state'].str[:2]
>>> df
pop state year StateInitial
0 1.5 Auckland 2000 Au
1 1.7 Otago 2001 Ot
2 3.6 Wellington 2002 We
3 2.4 Dunedin 2001 Du
4 2.9 Hamilton 2002 ... |
Ensuring py.test includes the application directory in sys.path | 20,971,619 | 19 | 2014-01-07T12:27:04Z | 20,972,950 | 15 | 2014-01-07T13:32:03Z | [
"python",
"unit-testing",
"py.test"
] | I have a project directory structure as follows (which I think is pretty standard):
```
my_project
setup.py
mypkg
__init__.py
foo.py
tests
functional
test_f1.py
unit
test_u1.py
```
I'm using py.test for my testing framework, and I'd expect to be able... | As you say yourself py.test basically assumes you have the PYTHONPATH setup up correctly. There are several ways of achieving this:
* Give your project a setup.py and use `pip install -e .` in a virtualenv for this project. This is probably the standard method.
* As a variation on this if you have a virtualenv but no ... |
How to invoke external scripts/programs from node.js | 20,972,788 | 17 | 2014-01-07T13:23:56Z | 20,973,067 | 29 | 2014-01-07T13:37:31Z | [
"python",
"c++",
"node.js"
] | I have a `C++` program and a `Python` script that I want to incorporate into my `node.js` web app.
I want to use them to parse the files that are uploaded to my site; it may take a few seconds to process, so I would avoid to block the app as well.
How can I just accept the file then just run the `C++` program and scr... | see [child\_process](http://nodejs.org/api/child_process.html). here is an example using `spawn`, which allows you to write to stdin and read from stderr/stdout as data is output. If you have no need to write to stdin and you can handle all output when the process completes, `child_process.exec` offers a slightly short... |
Cannot complete Flask-Migration | 20,973,145 | 15 | 2014-01-07T13:40:34Z | 21,482,968 | 7 | 2014-01-31T14:52:45Z | [
"python",
"postgresql",
"sqlalchemy-migrate",
"flask-migrate"
] | I've setup a local Postgres DB with SQLAlchemy and cannot commit my first entry. I keep on getting this error...
```
ProgrammingError: (ProgrammingError) relation "user" does not exist
LINE 1: INSERT INTO "user" (name, email, facebook_id, facebook_token...
```
It seems like the fields aren't matching to those in the ... | Alembic keeps the migration history in your database, this is why it still recognises there is another revision there. I keep my project on Heroku so I was able to just do *heroku pg:pull ...* to be able to get a new copy of my database. Prior to this you will have to drop your local db. In case you don't want to drop ... |
Cannot complete Flask-Migration | 20,973,145 | 15 | 2014-01-07T13:40:34Z | 24,473,808 | 11 | 2014-06-29T06:50:44Z | [
"python",
"postgresql",
"sqlalchemy-migrate",
"flask-migrate"
] | I've setup a local Postgres DB with SQLAlchemy and cannot commit my first entry. I keep on getting this error...
```
ProgrammingError: (ProgrammingError) relation "user" does not exist
LINE 1: INSERT INTO "user" (name, email, facebook_id, facebook_token...
```
It seems like the fields aren't matching to those in the ... | flask-migrate will create a table named "alembic\_version" in your database.
so you should drop this table and delete migrations folder in your project.
and then use `$ python app.py db init` again...
I think `$ python app.py db migrate` will work fine. |
What's the best way to retry publishing messages with kombu? | 20,975,914 | 4 | 2014-01-07T15:47:31Z | 21,016,469 | 8 | 2014-01-09T09:40:55Z | [
"python",
"kombu"
] | I'm testing how kombu works. I'm planning to replace pika in several projects. I see that kombu has a lot of documentation but using what I found in the documentation some messages are lost. Here it's the code:
```
from kombu import Connection, Producer
conn = Connection('amqp://localhost:5672')
def errback(exc, inter... | The problem was that by default Kombu doesn't use 'confirm', you have to use:
```
conn = Connection('amqp://localhost:5672', transport_options={'confirm_publish': True})
```
Thanks |
Cython: Convert memory view to NumPy array | 20,978,377 | 9 | 2014-01-07T17:47:27Z | 20,978,575 | 13 | 2014-01-07T17:59:57Z | [
"python",
"arrays",
"numpy",
"cython",
"memoryview"
] | How to convert a typed memoryview to an NumPy array in cython? The docs have
```
cimport numpy as np
import numpy as np
numpy_array = np.asarray(<np.int32_t[:10, :10]> my_pointer)
```
I took this for my case
```
np.asarray(<np.float_t[:, :]> my_memview)
```
Using this the compiler tells me:
```
Can only create cy... | You should just be able to use `np.asarray` directly on the memoryview itself, so something like:
```
np.asarray(my_memview)
```
should work. For example if your cython source file contains this:
```
import numpy as np
cimport numpy as np
def test(double[:,:] x):
print type(x)
print type(np.asarray(x))
```
... |
How to append a vector to a matrix in python | 20,978,757 | 2 | 2014-01-07T18:10:23Z | 20,978,864 | 11 | 2014-01-07T18:17:12Z | [
"python",
"arrays",
"numpy"
] | I want to append a vector to a matrix in python. I tried `append` or `concatenate` methods but I didn't get the answer. I was previously working with Matlab and there I used this:
```
m = zeros(10,4) % define my matrix, 10x4
v = ones(10,1) % my vecto, 10x1
c = [m,v] % so simple! the result is: 10x5 (the vector a... | You're looking for [`np.r_`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.r_.html) and [`np.c_`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.c_.html#numpy.c_). (Think "column stack" and "row stack" (which are also functions) but with matlab-style range generations.)
Also see [`np.concatenate... |
Cython: Should I use np.float_t rather than double for typed memory views | 20,978,938 | 6 | 2014-01-07T18:20:47Z | 20,983,590 | 9 | 2014-01-07T22:47:32Z | [
"python",
"numpy",
"cython",
"typing",
"memoryview"
] | Concerning memoryviews in cython, is there any advantage of typing a view with NumPy types such as `np.float_t` instead of simply do `double` if I'm working with numpy float arrays?
And should I type the `cdef` then the same way, doing e. g.
```
ctypedef np.float64_t np_float_t
...
@cython.profile(False)
@cython.wra... | If you look in the numpy header file included with cython (e.g. in the master branch, it is [`__init__.pxd`](https://github.com/cython/cython/blob/master/Cython/Includes/numpy/__init__.pxd)), you'll find
```
ctypedef double npy_double
```
and
```
ctypedef npy_double float_t
```
In other words, `float_... |
save a tuple to a django model | 20,979,485 | 2 | 2014-01-07T18:52:32Z | 20,979,899 | 7 | 2014-01-07T19:16:02Z | [
"python",
"django",
"django-models",
"tuples"
] | Is there a way to save a tuple to a django model?
**example:**
```
Class User(models.Model):
location = models.tupleField()
```
where `User.location = (longitude, latitude)` | Maybe you are looking for [GeoDjango's PointField](https://docs.djangoproject.com/en/dev/ref/contrib/gis/model-api/#pointfield):
```
from django.contrib.gis.db import models
Class User(models.Model):
location = models.PointField(help_text="Represented as (longitude, latitude)â)
``` |
How to pretty print in ipython notebook via sympy? pprint only prints Unicode version | 20,979,993 | 13 | 2014-01-07T19:20:19Z | 20,993,540 | 18 | 2014-01-08T10:55:12Z | [
"python",
"ipython-notebook",
"sympy"
] | ```
from sympy import symbols, Function
import sympy.functions as sym
from sympy import init_printing
init_printing(use_latex=True)
from sympy import pprint
from sympy import Symbol
x = Symbol('x')
# If a cell contains only the following, it will render perfectly.
(pi + x)**2
# However I would like to control what t... | you need to use display:
```
from IPython.display import display
display(yourobject)
```
It will choose the appropriate representation (text/LaTex/png...) |
How to pretty print in ipython notebook via sympy? pprint only prints Unicode version | 20,979,993 | 13 | 2014-01-07T19:20:19Z | 24,973,261 | 9 | 2014-07-26T16:44:34Z | [
"python",
"ipython-notebook",
"sympy"
] | ```
from sympy import symbols, Function
import sympy.functions as sym
from sympy import init_printing
init_printing(use_latex=True)
from sympy import pprint
from sympy import Symbol
x = Symbol('x')
# If a cell contains only the following, it will render perfectly.
(pi + x)**2
# However I would like to control what t... | The issue is with your init\_printing statement. In a notebook, you do not want to run latex, instead you should use mathjax, so try this instead:
```
init_printing(use_latex='mathjax')
```
When I use this, I get normal pretty printing everywhere, even when I have a sympy expression as the last line of the cell. |
What happens when returning a reversed list like this | 20,980,255 | 3 | 2014-01-07T19:38:30Z | 20,980,284 | 7 | 2014-01-07T19:40:13Z | [
"python",
"return",
"return-value"
] | I used this code to return a list say [1,2,3,4]
```
return (list.reverse())
```
But it simply wont return the correct result. I had to use
```
list.reverse()
return list
```
why is this happening? and when I break up my issue and do
```
list1 = list.reverse()
```
in console and print list1, it simply prints "list... | `list.reverse` method doesn't return anything. It works over the elements on the list to which is applied (modifying the list). Hence, returning its result will return `None`. Here's the prof:
```
>>>[].reverse() == None
True
```
If you're trying to return a new list with element in reverse order, this is how you do ... |
NameError: name 'self' is not defined, even though it is? | 20,982,780 | 2 | 2014-01-07T21:56:31Z | 20,982,860 | 9 | 2014-01-07T22:01:27Z | [
"python",
"class",
"oop"
] | Can anyone helps me understand why this is this giving me an error? The error being "NameError: name 'self' is not defined". I have a similar class higher up in my code and that works fine?
I'm using 'xlrd' and team is a reference to a workbook.sheet\_by\_name.
```
class Rollout:
... | The `for` loop is indented incorrectly resulting in it being outside that method's scope but inside the class' scope. This in turn means that `self` is not defined.
Python does interpret that loop code in the scope of the class, but without an instance of the object. Sample malformed code:
```
class Simple(object):
... |
Efficient dot products of large memory-mapped arrays | 20,983,882 | 30 | 2014-01-07T23:06:42Z | 21,096,605 | 19 | 2014-01-13T16:41:45Z | [
"python",
"arrays",
"performance",
"numpy",
"linear-algebra"
] | I'm working with some rather large, dense numpy float arrays that currently reside on disk in PyTables `CArray`s. I need to be able to perform efficient dot products using these arrays, for example `C = A.dot(B)`, where `A` is a huge (~1E4 x 3E5 float32) memory-mapped array, and `B` and `C` are smaller numpy arrays tha... | I've implemented a function for applying `np.dot` to blocks that are explicitly read into core memory from the memory-mapped array:
```
import numpy as np
def _block_slices(dim_size, block_size):
"""Generator that yields slice objects for indexing into
sequential blocks of an array along a particular axis
... |
Topic distribution: How do we see which document belong to which topic after doing LDA in python | 20,984,841 | 11 | 2014-01-08T00:30:08Z | 20,991,190 | 13 | 2014-01-08T09:10:18Z | [
"python",
"nltk",
"lda",
"gensim"
] | I am able to run the LDA code from gensim and got the top 10 topics with their respective keywords.
Now I would like to go a step further to see how accurate the LDA algo is by seeing which document they cluster into each topic. Is this possible in gensim LDA?
Basically i would like to do something like this, but in ... | Using the probabilities of the topics, you can try to set some threshold and use it as a clustering baseline, but i am sure there are better ways to do clustering than this 'hacky' method.
```
from gensim import corpora, models, similarities
from itertools import chain
""" DEMO """
documents = ["Human machine interfa... |
Py.test No module named * | 20,985,157 | 9 | 2014-01-08T01:03:05Z | 35,896,910 | 9 | 2016-03-09T16:16:49Z | [
"python",
"py.test"
] | I have a folder structure like this
```
App
--App
--app.py
--Docs
--Tests
--test_app.py
```
In my `test_app.py file`, I have a line to import my app module. When I run py.test on the root folder, I get this error about no module named app. How should I configure this? | I already had an `__init__.py` file in the `/App/App` directory and wanted to run tests from the project root without any path-mangling magic:
```
python -m pytest tests
```
The output immediately looks like this:
```
â python -m pytest tests
====================================== test session starts ===========... |
Print all fields of ctypes "Structure" with introspection | 20,986,330 | 6 | 2014-01-08T03:11:59Z | 20,986,376 | 8 | 2014-01-08T03:17:13Z | [
"python",
"reflection",
"ctypes"
] | test.c:
```
#include <stdio.h>
#include <stdlib.h>
struct s {
char a;
int b;
float c;
double d;
};
struct s *create_struct()
{
struct s *res = malloc(sizeof(struct s));
res->a = 1; res->b = 2; res->c = 3.0f; res->d = 4.0;
return res;
}
```
test.py:
```
from ctypes import *
class S(Stru... | How about using [`getattr`](http://docs.python.org/2/library/functions.html#getattr)?
```
>>> from ctypes import *
>>>
>>> class S(Structure):
... _fields_ = [
... ('a', c_byte),
... ('b', c_int),
... ('c', c_float),
... ('d', c_double)
... ]
...
>>> s = S(1, 2, 3, 4.0)
>>>
>>> ... |
How can I scroll a web page using selenium webdriver in python? | 20,986,631 | 14 | 2014-01-08T03:44:49Z | 20,986,812 | 8 | 2014-01-08T04:04:44Z | [
"python",
"selenium",
"selenium-webdriver",
"automated-tests"
] | I am currently using selenium webdriver to parse through facebook user friends page and extract all ids from the AJAX script. But I need to scroll down to get all the friends. How can I scroll down in Selenium. I am using python. | same method as shown here: <http://stackoverflow.com/a/12195714/725944>
in python you can just use
```
driver.execute_script("window.scrollTo(0, Y)")
```
(Y is the vertical position you want to scroll to) |
How can I scroll a web page using selenium webdriver in python? | 20,986,631 | 14 | 2014-01-08T03:44:49Z | 27,760,083 | 29 | 2015-01-03T22:13:15Z | [
"python",
"selenium",
"selenium-webdriver",
"automated-tests"
] | I am currently using selenium webdriver to parse through facebook user friends page and extract all ids from the AJAX script. But I need to scroll down to get all the friends. How can I scroll down in Selenium. I am using python. | or
```
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
```
to scroll to the bottom of the page. |
PyCharm - Is community edition able to highlight css/javascript? | 20,986,720 | 9 | 2014-01-08T03:54:49Z | 20,986,966 | 9 | 2014-01-08T04:20:22Z | [
"python",
"ide",
"pycharm"
] | I'm exploring the features of PyCharm to decide if I should use it(now PyDev). All looks great, but I haven't find a way to make PyCharm highlight css or js files:

Is this a functionality which only provided in the commercial edition? | Web development with JavaScript, CoffeeScript, TypeScript, HTML/CSS supported by Professional Edition only. They are edited as text files with no mark-up in Community Edition.
[PyCharm Editions Comparison](http://www.jetbrains.com/pycharm/features/editions_comparison_matrix.html) |
PyCharm - Is community edition able to highlight css/javascript? | 20,986,720 | 9 | 2014-01-08T03:54:49Z | 25,447,766 | 9 | 2014-08-22T13:05:13Z | [
"python",
"ide",
"pycharm"
] | I'm exploring the features of PyCharm to decide if I should use it(now PyDev). All looks great, but I haven't find a way to make PyCharm highlight css or js files:

Is this a functionality which only provided in the commercial edition? | You can create a new syntax definition via **Settings / Editor / File and Code Templates**.
Alternatively create a javascript.xml file in **C:\Users\%USERNAME%.PyCharm30\config\filetypes** with this content:
```
<?xml version="1.0" encoding="UTF-8"?>
<filetype binary="false" default_extension="" description="Javascri... |
PyCharm - Is community edition able to highlight css/javascript? | 20,986,720 | 9 | 2014-01-08T03:54:49Z | 27,042,542 | 12 | 2014-11-20T14:51:42Z | [
"python",
"ide",
"pycharm"
] | I'm exploring the features of PyCharm to decide if I should use it(now PyDev). All looks great, but I haven't find a way to make PyCharm highlight css or js files:

Is this a functionality which only provided in the commercial edition? | If you create `css.xml` with this content then you'll get css highlighting and code-completion:
```
<?xml version="1.0" encoding="UTF-8"?>
<filetype binary="false" default_extension="" description="css" name="css">
<highlighting>
<options>
<option name="LINE_COMMENT" value="" />
<option name="COMMENT... |
Cython: (Why / When) Is it preferable to use Py_ssize_t for indexing? | 20,987,390 | 19 | 2014-01-08T05:02:07Z | 20,987,501 | 15 | 2014-01-08T05:12:33Z | [
"python",
"numpy",
"indexing",
"cython",
"unsigned-integer"
] | This is a follow-up to [this question](http://stackoverflow.com/questions/20978938/cython-should-i-use-np-float-t-rather-than-double-for-typed-memory-views).
(Why / When) Is it preferable to use `Py_ssize_t` for indexing? In the [docs](http://docs.cython.org/src/userguide/numpy_tutorial.html) I just found
> ```
> # P... | `Py_ssize_t` is signed. See [PEP 353](http://www.python.org/dev/peps/pep-0353/), where it says *"A new type Py\_ssize\_t is introduced, which has the same size as the compiler's size\_t type, but is signed. It will be a typedef for ssize\_t where available."*
You should use `Py_ssize_t` for indexing. I didn't find a d... |
Cython: (Why / When) Is it preferable to use Py_ssize_t for indexing? | 20,987,390 | 19 | 2014-01-08T05:02:07Z | 20,987,522 | 10 | 2014-01-08T05:13:57Z | [
"python",
"numpy",
"indexing",
"cython",
"unsigned-integer"
] | This is a follow-up to [this question](http://stackoverflow.com/questions/20978938/cython-should-i-use-np-float-t-rather-than-double-for-typed-memory-views).
(Why / When) Is it preferable to use `Py_ssize_t` for indexing? In the [docs](http://docs.cython.org/src/userguide/numpy_tutorial.html) I just found
> ```
> # P... | `Py_ssize_t` is a typedef used internally in the implementation of CPython (the C implementation of Python - I'm *not* talking about Cython there, I'm talking about CPython). It's used everywhere Python C API functions accept or return a C-level integer that can be used for indexing Python sequences. That's why it's "t... |
Python Dictionaries vs Javascript Objects | 20,987,485 | 15 | 2014-01-08T05:11:10Z | 20,988,172 | 22 | 2014-01-08T06:10:27Z | [
"javascript",
"python",
"object",
"dictionary"
] | I'm new to python and I was reading about Dictionaries. And from my previous experience with langages like javascript they seemed like objects to me. Dictionaries can store lists and share many similaraties to objects in javascript.
ex python code:
```
menu = {}
menu['Chicken Alfredo'] = 14.50
menu['Italian Pasta'] =... | [From :](http://www.cs.miami.edu/~burt/learning/five-easy-pieces/newwb/arrays_objects_dictionaries.html)
> In Python, dictionaries are a form of mapping type. They can be
> initialized using a sequence of comma separated name:value pairs,
> enclosed in curly braces. The are accessed using array notation
> involving sq... |
Why Python need rich comparison? | 20,989,750 | 15 | 2014-01-08T07:46:39Z | 20,990,080 | 8 | 2014-01-08T08:07:45Z | [
"python"
] | There is a confusion for me for some time: is there a scene that we do need to use rich comparison in Python?
I read the official doc [here](http://docs.python.org/2/reference/datamodel.html#object.__lt__), but it only gives how it works not why we need it.
A snippet of the doc:
> *The truth of `x==y` does not imply... | [NumPy](http://www.numpy.org/) uses rich comparisons to vectorize `==`, `!=`, `<`, etc, just like it does with most other operators. For example,
```
>>> x = numpy.array([1, 2, 3, 4, 5])
>>> y = numpy.array([2, 2, 1, 4, 4])
>>> x == y
array([False, True, False, True, False], dtype=bool)
```
When arrays `x` and `y` ... |
Reverse for 'index' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] | 20,993,598 | 11 | 2014-01-08T10:57:40Z | 20,993,800 | 13 | 2014-01-08T11:06:07Z | [
"python",
"django",
"python-3.3",
"django-registration",
"django-1.6"
] | I'm trying to get django-register to work on my website but I keep getting this error which I do not understand
I'm using django 1.6 on Python 3.3
```
NoReverseMatch at /accounts/register/
Reverse for 'index' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []
Request Method: GET
... | Its complaining about line no.14 because Django is unable to determine the url named as "index" in your urls.py files. I don't see a URL named as "index" above. Where/What is the URL pattern for your home page? |
What is the difference between pip and conda? | 20,994,716 | 145 | 2014-01-08T11:44:44Z | 20,994,790 | 113 | 2014-01-08T11:47:46Z | [
"python",
"pip",
"ipython",
"package-managers",
"conda"
] | I know `pip` is a package manager for python packages. However, I saw the installation on iPython's website use `conda` to install iPython.
Can I use `pip` to install iPython? Why should I use `conda` as another python package manager when I already have `pip`?
What is the difference between `pip` and `conda`? | Quoting from the [Conda blog](https://www.continuum.io/blog/developer-blog/python-packages-and-environments-conda):
> Having been involved in the python world for so long, we are all aware of pip, easy\_install, and virtualenv, but these tools did not meet all of our specific requirements. The main problem is that the... |
What is the difference between pip and conda? | 20,994,716 | 145 | 2014-01-08T11:44:44Z | 21,008,900 | 88 | 2014-01-08T23:37:25Z | [
"python",
"pip",
"ipython",
"package-managers",
"conda"
] | I know `pip` is a package manager for python packages. However, I saw the installation on iPython's website use `conda` to install iPython.
Can I use `pip` to install iPython? Why should I use `conda` as another python package manager when I already have `pip`?
What is the difference between `pip` and `conda`? | Here is a short rundown:
## pip
* Python packages only.
* Compiles everything from source. **EDIT: pip now installs binary wheels, if they are available.**
* Blessed by the core Python community (i.e., Python 3.4+ includes code that automatically boostraps pip).
## conda
* Python agnostic. The main focus of existin... |
What is the difference between pip and conda? | 20,994,716 | 145 | 2014-01-08T11:44:44Z | 21,009,909 | 36 | 2014-01-09T01:13:06Z | [
"python",
"pip",
"ipython",
"package-managers",
"conda"
] | I know `pip` is a package manager for python packages. However, I saw the installation on iPython's website use `conda` to install iPython.
Can I use `pip` to install iPython? Why should I use `conda` as another python package manager when I already have `pip`?
What is the difference between `pip` and `conda`? | The other answers give a fair description of the details, but I want to highlight some high-level points.
pip is a package manager that facilitates installation, upgrade, and uninstallation of **python packages**. It also works with virtual **python** environments.
conda is a package manager for **any software** (ins... |
What is the difference between pip and conda? | 20,994,716 | 145 | 2014-01-08T11:44:44Z | 30,233,285 | 8 | 2015-05-14T09:03:02Z | [
"python",
"pip",
"ipython",
"package-managers",
"conda"
] | I know `pip` is a package manager for python packages. However, I saw the installation on iPython's website use `conda` to install iPython.
Can I use `pip` to install iPython? Why should I use `conda` as another python package manager when I already have `pip`?
What is the difference between `pip` and `conda`? | **For WINDOWS users**
"standard" packaging tools situation is improving recently:
* on pypi itself, there are now 48% of wheel packages as of sept. 11th 2015 (up from 38% in may 2015 , 24% in sept. 2014),
* the wheel format is now supported out-of-the-box per latest python 2.7.9,
"standard"+"tweaks" packaging tools ... |
Python Pandas counting and summing specific conditions | 20,995,196 | 13 | 2014-01-08T12:06:24Z | 20,995,313 | 9 | 2014-01-08T12:12:11Z | [
"python",
"pandas",
"sum"
] | Are there single functions in pandas to perform the equivalents of [SUMIF](http://office.microsoft.com/en-us/excel-help/sumifs-function-HA010047504.aspx), which sums over a specific condition and [COUNTIF](http://office.microsoft.com/en-us/excel-help/countifs-function-HA010047494.aspx), which counts values of specific ... | You didn't mention the fancy indexing capabilities of dataframes, e.g.:
```
>>> df = pd.DataFrame({"class":[1,1,1,2,2], "value":[1,2,3,4,5]})
>>> df[df["class"]==1].sum()
class 3
value 6
dtype: int64
>>> df[df["class"]==1].sum()["value"]
6
>>> df[df["class"]==1].count()["value"]
3
```
You could replace `df["cla... |
Python Pandas counting and summing specific conditions | 20,995,196 | 13 | 2014-01-08T12:06:24Z | 20,995,428 | 16 | 2014-01-08T12:16:40Z | [
"python",
"pandas",
"sum"
] | Are there single functions in pandas to perform the equivalents of [SUMIF](http://office.microsoft.com/en-us/excel-help/sumifs-function-HA010047504.aspx), which sums over a specific condition and [COUNTIF](http://office.microsoft.com/en-us/excel-help/countifs-function-HA010047494.aspx), which counts values of specific ... | You can first make a conditional selection, and sum up the results of the selection using the `sum` function.
```
>> df = pd.DataFrame({'a': [1, 2, 3]})
>> df[df.a > 1].sum()
a 5
dtype: int64
```
Having more than one condition:
```
>> df[(df.a > 1) & (df.a < 3)].sum()
a 2
dtype: int64
``` |
How to get text with selenium web driver in python | 20,996,392 | 6 | 2014-01-08T13:00:35Z | 20,996,441 | 17 | 2014-01-08T13:02:46Z | [
"python",
"selenium"
] | I'm trying to get text using selenium web driver and here is my code. Please note that I don't wanna use Xpath, because in my case id gets change on every re-launch of the web page, help please.
my code:
```
text=driver.find_element_by_class_name("current-stage").getText("my text")
```
simple HTML:
```
span class="... | You want just `.text`.
You can then verify it *after* you've got it, don't attempt to pass in what you *expect* it should have. |
Why does `setup.py develop` not work? | 20,996,639 | 4 | 2014-01-08T13:11:13Z | 20,997,675 | 9 | 2014-01-08T13:54:00Z | [
"python",
"python-3.x",
"cython",
"distutils",
"setup.py"
] | I would like to install my Python module in development mode. As I have seen in many examples `python setup.py develop` is supposed to do that. But the `develop` command does not exist for my `setup.py` file:
```
from distutils.core import setup
from distutils.extension import Extension
from Cython.Build import cython... | The `develop` command is a part of [setuptools](http://pythonhosted.org/setuptools/setuptools.html#develop-deploy-the-project-source-in-development-mode). Install setuptools and replace the first line in `setup.py` with this:
```
from setuptools import setup
``` |
How to yield element multiple times | 20,997,849 | 2 | 2014-01-08T14:03:34Z | 20,997,885 | 10 | 2014-01-08T14:05:07Z | [
"python",
"generator"
] | I am trying to implement a method, in which each element of list gets yielded as much as the paramter says:
```
def rgen (n):
for elem in list:
yield elem
```
When I call rgen(2), I would like to yield every element of that list twice etc.
But how could I actually implement that? | Loop again:
```
def rgen (n):
for elem in list:
for times in xrange(n):
yield elem
```
I'd probably write a helper function similar to:
```
from itertools import chain, repeat
def repeated(iterable, n=1):
items = chain.from_iterable(repeat(item, n) for item in iterable)
for item in i... |
What does the Brown clustering algorithm output mean? | 20,998,832 | 15 | 2014-01-08T14:48:05Z | 21,006,240 | 14 | 2014-01-08T20:51:57Z | [
"python",
"algorithm",
"machine-learning",
"nlp",
"cluster-analysis"
] | I've ran the brown-clustering algorithm from <https://github.com/percyliang/brown-cluster> and also a python implementation <https://github.com/mheilman/tan-clustering>. And they both give some sort of binary and another integer for each unique token. For example:
```
0 the 6
10 chased 3
11... | If I understand correctly, the algorithm gives you a tree and you need to truncate it at some level to get clusters. In case of those bit strings, you should just take first `L` characters.
For example, cutting at the second character gives you two clusters
```
10 chased
11 dog
11 ... |
ElementTree find()/findall() can't find tag with namespace? | 20,999,239 | 4 | 2014-01-08T15:05:14Z | 20,999,334 | 8 | 2014-01-08T15:09:10Z | [
"python",
"xml",
"python-2.7",
"xml-namespaces",
"elementtree"
] | Using the following code I would expect to be able to search for the target tag, if I specify the namespace.
```
import xml.etree.ElementTree as ET
xml = """<?xml version="1.0" encoding="UTF-8"?>
<xyz2:outer xmlns:xyz1="http://www.company.com/url/common/v1"
xmlns:xyz2="http://www.company... | `target` is not a root element; You should prepend `.//`.
```
>>> import xml.etree.ElementTree as ET
>>> tree = ET.fromstring(xml)
>>> tree.findall('.//{http://www.company.com/app/v2}target')
[<Element '{http://www.company.com/app/v2}target' at 0x2d143c8>]
``` |
Python method accessor creates new objects on each access? | 21,002,292 | 9 | 2014-01-08T17:18:22Z | 21,002,370 | 13 | 2014-01-08T17:22:20Z | [
"python",
"methods",
"python-internals"
] | When investigating for [another question](http://stackoverflow.com/questions/20981789/difference-between-methods-and-functions/20981876#20981876), I found the following:
```
>>> class A:
... def m(self): return 42
...
>>> a = A()
```
This was expected:
```
>>> A.m == A.m
True
>>> a.m == a.m
True
```
But this I d... | Yes, Python creates new method objects for each access, because it builds a wrapper object to pass in `self`. This is called a *bound method*.
Python uses descriptors to do this; function objects have a `__get__` method that is called when accessed on a class:
```
>>> A.__dict__['m'].__get__(A(), A)
<bound method A.m... |
Python method accessor creates new objects on each access? | 21,002,292 | 9 | 2014-01-08T17:18:22Z | 21,002,463 | 7 | 2014-01-08T17:27:24Z | [
"python",
"methods",
"python-internals"
] | When investigating for [another question](http://stackoverflow.com/questions/20981789/difference-between-methods-and-functions/20981876#20981876), I found the following:
```
>>> class A:
... def m(self): return 42
...
>>> a = A()
```
This was expected:
```
>>> A.m == A.m
True
>>> a.m == a.m
True
```
But this I d... | Because that's the most convenient, least magical and most space efficient way of implementing bound methods.
In case you're not aware, bound methods refers to being able to do something like this:
```
f = obj.m
# ... in another place, at another time
f(args, but, not, self)
```
Functions are descriptors. Descriptor... |
Using Flask-Mail to send Email through Gmail- socket.gaierr | 21,004,784 | 6 | 2014-01-08T19:28:21Z | 21,004,912 | 11 | 2014-01-08T19:34:32Z | [
"python",
"flask",
"flask-mail"
] | I am building a simple contact page using Flask and Flask-Mail. I built the app following this tutorial - [Add a contact page](http://net.tutsplus.com/tutorials/python-tutorials/intro-to-flask-adding-a-contact-page/?search_index=1) - and now when I try to send the message I receive the eror `gaierror: [Errno -2] Name o... | I have the following settings that work for me
```
app.config['MAIL_SERVER']='smtp.gmail.com'
app.config['MAIL_PORT'] = 465
app.config['MAIL_USERNAME'] = '[email protected]'
app.config['MAIL_PASSWORD'] = 'xx;'
app.config['MAIL_USE_TLS'] = False
app.config['MAIL_USE_SSL'] = True
```
Note that MAIL\_USE\_TLS parameter that ... |
No module named lxml.html while running python script on Fedora | 21,004,960 | 2 | 2014-01-08T19:37:24Z | 22,648,918 | 7 | 2014-03-26T00:07:34Z | [
"python",
"linux",
"lxml",
"fedora"
] | I'm trying to run a python script on Fedora Server. I'm getting the following error.
```
/usr/bin/python report_generation.py
Traceback (most recent call last):
File "report_generation.py", line 9, in ?
import lxml.html
ImportError: No module named lxml.html
```
Doing some research, I found it needs python-lxml packa... | ```
sudo yum install python-lxml
```
or
```
sudo apt-get install python-lxml
``` |
What does os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir)) mean? python | 21,005,822 | 6 | 2014-01-08T20:28:43Z | 21,006,000 | 13 | 2014-01-08T20:37:50Z | [
"python",
"import",
"path",
"operating-system",
"directory"
] | In several SO's question there is these lines to access the parent directory of the code, e.g. [os.path.join(os.path.dirname(\_\_file\_\_)) returns nothing](http://stackoverflow.com/questions/10953540/os-path-joinos-path-dirname-file-returns-nothing) and [os.path.join(os.path.dirname(\_\_file\_\_)) returns nothing](htt... | That is a clever way to refer to paths regardless of the script location. The *cryptic* line you're referring is:
```
os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir))
```
There are 3 methods and a 2 constants present:
1. `abspath` returns absolute path of a path
2. `join` join to path strings... |
How to load all entries in an infinite scroll at once to parse the HTML in python | 21,006,940 | 9 | 2014-01-08T21:29:57Z | 21,008,335 | 11 | 2014-01-08T22:56:10Z | [
"python",
"html",
"json",
"beautifulsoup",
"python-requests"
] | I am trying to extract information from [this page](https://medium.com/top-100/december-2013). The page loads 10 items at a time, and I need to scroll to load all entries (for a total of 100). I am able to parse the HTML and get the information that I need for the first 10 entries, but I want to fully load all entries ... | This you won't be able to do with requests and BeautifulSoup as the page that you want to extract the information from loads the rest of the entries through JS when you scroll down. You can do this using [selenium](http://selenium-python.readthedocs.org/en/latest/api.html) which opens a real browser and you can pass pa... |
Django, Celery, Redis, RabbitMQ: Chained Tasks for Fanout-On-Writes | 21,007,096 | 9 | 2014-01-08T21:38:26Z | 21,079,734 | 8 | 2014-01-12T20:12:35Z | [
"python",
"django",
"redis",
"rabbitmq",
"celery"
] | I've been watching Rick Branson's PyCon video: [Messaging at Scale at Instagram](http://www.youtube.com/watch?v=E708csv4XgY). You might want to watch the video in order to answer this question. Rick Branson uses Celery, Redis and RabbitMQ. To get you up to speed, each user has a redis list for their homefeed. Each list... | The approach described in the video is task "chaining".
To get your task method up and running as a chain, you want to add an extra parameter that represents the index into the list of followers. Instead of working on the full list of followers, the task only works on a fixed batch size, starting from the index argume... |
Formatting floats in a numpy array | 21,008,858 | 11 | 2014-01-08T23:33:32Z | 21,008,883 | 7 | 2014-01-08T23:35:50Z | [
"python",
"arrays",
"numpy"
] | If I have a numpy array like this:
```
[2.15295647e+01, 8.12531501e+00, 3.97113829e+00, 1.00777250e+01]
```
how can I move the decimal point and format the numbers so I end up with a numpy array like this:
```
[21.53, 8.13, 3.97, 10.08]
```
`np.around(a, decimals=2)` only gives me `[2.15300000e+01, 8.13000000e+00, ... | You can use round function. Here some example
```
numpy.round([2.15295647e+01, 8.12531501e+00, 3.97113829e+00, 1.00777250e+01],2)
array([ 21.53, 8.13, 3.97, 10.08])
```
IF you want change just display representation, I would **not** recommended to alter printing format globally, as it suggested above. I would fo... |
Formatting floats in a numpy array | 21,008,858 | 11 | 2014-01-08T23:33:32Z | 21,008,904 | 10 | 2014-01-08T23:37:44Z | [
"python",
"arrays",
"numpy"
] | If I have a numpy array like this:
```
[2.15295647e+01, 8.12531501e+00, 3.97113829e+00, 1.00777250e+01]
```
how can I move the decimal point and format the numbers so I end up with a numpy array like this:
```
[21.53, 8.13, 3.97, 10.08]
```
`np.around(a, decimals=2)` only gives me `[2.15300000e+01, 8.13000000e+00, ... | You're confusing actual precision and display precision. Decimal rounding cannot be represented exactly in binary. You should try:
```
> np.set_printoptions(precision=2)
> np.array([5.333333])
array([ 5.33])
``` |
Formatting floats in a numpy array | 21,008,858 | 11 | 2014-01-08T23:33:32Z | 21,009,774 | 18 | 2014-01-09T00:57:02Z | [
"python",
"arrays",
"numpy"
] | If I have a numpy array like this:
```
[2.15295647e+01, 8.12531501e+00, 3.97113829e+00, 1.00777250e+01]
```
how can I move the decimal point and format the numbers so I end up with a numpy array like this:
```
[21.53, 8.13, 3.97, 10.08]
```
`np.around(a, decimals=2)` only gives me `[2.15300000e+01, 8.13000000e+00, ... | In order to make numpy **display** float arrays in an arbitrary format, you can define a custom function that takes a float value as its input and returns a formatted string:
```
In [1]: float_formatter = lambda x: "%.2f" % x
```
The `f` here means fixed-point format (not 'scientific'), and the `.2` means two decimal... |
Python-Requests (>= 1.*): How to disable keep-alive? | 21,008,953 | 6 | 2014-01-08T23:42:51Z | 21,009,511 | 11 | 2014-01-09T00:31:46Z | [
"python",
"web",
"web-crawler",
"python-requests"
] | I'm trying to program a simple web-crawler using the Requests module, and I would like to know how to disable its -default- keep-alive feauture.
I tried using:
```
s = requests.session()
s.config['keep_alive'] = False
```
However, I get an error stating that session object has no attribute 'config', I think it was c... | This works
```
s = requests.session()
s.keep_alive = False
```
[Answered in the comments of a similar question.](http://stackoverflow.com/questions/10115126/python-requests-close-http-connection#comment22579942_10115553) |
How can I remove Nan from list Python/NumPy | 21,011,777 | 11 | 2014-01-09T04:46:59Z | 21,011,822 | 18 | 2014-01-09T04:51:57Z | [
"python",
"numpy"
] | I have a list that countain values, one of the values I got is 'nan'
```
countries= [nan, 'USA', 'UK', 'France']
```
I tried to remove it, but I everytime get an error
```
cleanedList = [x for x in countries if (math.isnan(x) == True)]
TypeError: a float is required
```
When I tried this one :
```
cleanedList = ci... | The question has changed, so to has the answer:
Strings can't be tested using `math.isnan` as this expects a float argument. In your `countries` list, you have floats and strings.
In your case the following should suffice:
```
cleanedList = [x for x in countries if str(x) != 'nan']
```
---
# Old answer
In your `c... |
Cython: how to make an python object as a property of cython class | 21,012,348 | 11 | 2014-01-09T05:37:36Z | 21,065,200 | 10 | 2014-01-11T17:03:29Z | [
"python",
"c",
"class",
"binding",
"cython"
] | I have a existing python class `X` and I want to do the followings:
```
from my_python_module import X
cdef class Y:
cdef X test
```
But this does not work out of the box, the cdef only accepts C type, not a Python class. Any work-around ? | I don't think you can (<http://docs.cython.org/src/userguide/sharing_declarations.html#sharing-extension-types>) but you can work-around it using `__cinit__` to assert that the attribute has the correct type:
In your Cython file (named "p.pyx" for example):
```
import my_python_module as q
cdef class Y:
cdef int... |
How to uninstall pip on OSX Mavericks? | 21,012,597 | 7 | 2014-01-09T05:55:45Z | 24,249,599 | 8 | 2014-06-16T18:06:05Z | [
"python",
"osx"
] | I ran the following commands:
```
easy_install pip
sudo pip install setuptools --no-use-wheel --upgrade
```
How do I reverse the two commands to get my python back to its original state in OSX? (removing pip as part of it) | In order to completely remove pip, I believe you have to delete its files from all Python versions on your computer. For me, they are here:
```
cd /Library/Frameworks/Python.framework/Versions/Current/bin/
cd /Library/Frameworks/Python.framework/Versions/3.3/bin/
```
You may need to remove the files or the directorie... |
How to uninstall pip on OSX Mavericks? | 21,012,597 | 7 | 2014-01-09T05:55:45Z | 29,846,144 | 23 | 2015-04-24T11:19:32Z | [
"python",
"osx"
] | I ran the following commands:
```
easy_install pip
sudo pip install setuptools --no-use-wheel --upgrade
```
How do I reverse the two commands to get my python back to its original state in OSX? (removing pip as part of it) | In my case I ran the following command and it worked (not that I was expecting it to):
```
sudo pip uninstall pip
```
Which resulted in:
```
Uninstalling pip-6.1.1:
/Library/Python/2.7/site-packages/pip-6.1.1.dist-info/DESCRIPTION.rst
/Library/Python/2.7/site-packages/pip-6.1.1.dist-info/METADATA
/Library/Pyth... |
How do I make `python setup.py test -q` quieter? | 21,012,855 | 4 | 2014-01-09T06:13:25Z | 21,013,023 | 7 | 2014-01-09T06:24:06Z | [
"python",
"unit-testing",
"pyramid"
] | I've just started a Pyramid project, following the recommendations from the [Pyramid docs](http://docs.pylonsproject.org/projects/pyramid/en/latest/index.html).
The command for testing looks like this:
```
../bin/python setup.py test -q
```
..which gives me this result:
```
$ ../bin/python setup.py test -q
running ... | The position of arguments is important here. Move the `-q` switch back a bit:
```
python setup.py -q test
```
This makes the switch a global one, and suppresses the build output. Any switches for the tests must come after the `test` command. |
Python randomly generated IP address of the string | 21,014,618 | 8 | 2014-01-09T07:59:26Z | 21,014,653 | 17 | 2014-01-09T08:01:21Z | [
"python"
] | In Python, what should I do if I want to generate a random string in the form of an IP address?
For example: `"10.0.1.1"`, `"10.0.3.14"`, `"172.23.35.1"` and so on.
Could someone give me some help? | ```
>>> import random
>>> import socket
>>> import struct
>>> socket.inet_ntoa(struct.pack('>I', random.randint(1, 0xffffffff)))
'197.38.59.143'
>>> socket.inet_ntoa(struct.pack('>I', random.randint(1, 0xffffffff)))
'228.237.175.64'
```
**NOTE** This could generarte IPs like `0.0.0.0`, `255.255.255.255`. |
Python randomly generated IP address of the string | 21,014,618 | 8 | 2014-01-09T07:59:26Z | 21,014,713 | 16 | 2014-01-09T08:05:45Z | [
"python"
] | In Python, what should I do if I want to generate a random string in the form of an IP address?
For example: `"10.0.1.1"`, `"10.0.3.14"`, `"172.23.35.1"` and so on.
Could someone give me some help? | If you just want a string:
```
import random
ip = ".".join(map(str, (random.randint(0, 255)
for _ in range(4))))
``` |
'list' object has no attribute 'shape' | 21,015,674 | 9 | 2014-01-09T09:01:47Z | 21,015,708 | 12 | 2014-01-09T09:04:02Z | [
"python",
"list",
"numpy"
] | how to create an array to numpy array?
```
def test(X, N):
[n,T] = X.shape
print "n : ", n
print "T : ", T
if __name__=="__main__":
X = [[[-9.035250067710876], [7.453250169754028], [33.34074878692627]], [[-6.63700008392334], [5.132999956607819], [31.66075038909912]], [[-5.1272499561309814], [8.2514... | Use [`numpy.array`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.array.html) to use `shape` attribute.
```
>>> import numpy as np
>>> X = np.array([
... [[-9.035250067710876], [7.453250169754028], [33.34074878692627]],
... [[-6.63700008392334], [5.132999956607819], [31.66075038909912]],
... [[... |
pip tries to use git when git is not installed | 21,017,169 | 3 | 2014-01-09T10:10:52Z | 21,019,095 | 7 | 2014-01-09T11:35:56Z | [
"python",
"git",
"pip"
] | I have a project folder that is a git repository (has a .git folder). When I use the command `pip freeze`, pip tries to use git. However, I don't have git installed on my system so this causes an error:
```
(env) PS C:\Users\eclaird\work\myproject> pip freeze
Cannot find command 'git'
Storing complete log in C:\Users\... | Unfortunately, no. There is no config option to enable/disable backends.
Details, found by digging in the code:
**Git module is always registered:** In [pip/**install**.py](https://github.com/pypa/pip/blob/1.4.1/pip/__init__.py), the [git module](https://github.com/pypa/pip/blob/1.4.1/pip/vcs/git.py) is imported. At ... |
Converting int to bytes in Python 3 | 21,017,698 | 28 | 2014-01-09T10:31:48Z | 21,017,834 | 32 | 2014-01-09T10:37:38Z | [
"python",
"python-3.x"
] | I was trying to build this bytes object in Python 3:
`b'3\r\n'`
so I tried the obvious (for me), and found a weird behaviour:
```
>>> bytes(3) + b'\r\n'
b'\x00\x00\x00\r\n'
```
Apparently:
```
>>> bytes(10)
b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
```
I've been unable to see any pointers on why the bytes conve... | That's the way it was designed - and it makes sense because usually, you would call `bytes` on an iterable instead of a single integer:
```
>>> bytes([3])
b'\x03'
```
The [docs state this](http://docs.python.org/3.3/library/stdtypes.html#binaryseq), as well as the docstring for `bytes`:
```
>>> help(bytes)
...
by... |
Converting int to bytes in Python 3 | 21,017,698 | 28 | 2014-01-09T10:31:48Z | 26,920,966 | 7 | 2014-11-14T00:25:01Z | [
"python",
"python-3.x"
] | I was trying to build this bytes object in Python 3:
`b'3\r\n'`
so I tried the obvious (for me), and found a weird behaviour:
```
>>> bytes(3) + b'\r\n'
b'\x00\x00\x00\r\n'
```
Apparently:
```
>>> bytes(10)
b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
```
I've been unable to see any pointers on why the bytes conve... | You can use the [struct's pack](https://docs.python.org/2/library/struct.html#struct.pack):
```
In [11]: struct.pack(">I", 1)
Out[11]: '\x00\x00\x00\x01'
```
The ">" is the [byte-order (big-endian)](https://docs.python.org/2/library/struct.html#byte-order-size-and-alignment) and the "I" is the [format character](http... |
Converting int to bytes in Python 3 | 21,017,698 | 28 | 2014-01-09T10:31:48Z | 30,375,198 | 21 | 2015-05-21T13:28:45Z | [
"python",
"python-3.x"
] | I was trying to build this bytes object in Python 3:
`b'3\r\n'`
so I tried the obvious (for me), and found a weird behaviour:
```
>>> bytes(3) + b'\r\n'
b'\x00\x00\x00\r\n'
```
Apparently:
```
>>> bytes(10)
b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
```
I've been unable to see any pointers on why the bytes conve... | From python 3.2 you can do
```
>>> (1024).to_bytes(2, byteorder='big')
b'\x04\x00'
```
<https://docs.python.org/3/library/stdtypes.html#int.to_bytes> |
Strings in a DataFrame, but dtype is object | 21,018,654 | 34 | 2014-01-09T11:16:23Z | 21,020,411 | 55 | 2014-01-09T12:33:58Z | [
"python",
"types",
"pandas"
] | Why does Pandas tell me that I have objects, although every item in the selected column is a string â even after explicit conversion.
This is my DataFrame:
```
<class 'pandas.core.frame.DataFrame'>
Int64Index: 56992 entries, 0 to 56991
Data columns (total 7 columns):
id 56992 non-null values
attr1 ... | The dtype object comes from NumPy, it describes the type of element in a ndarray. Every element in a ndarray must has the same size in byte. For int64 and float64, they are 8 bytes. But for strings, the length of the string is not fixed. So instead of save the bytes of strings in the ndarray directly, Pandas use object... |
write multiple lines in a file in python | 21,019,942 | 5 | 2014-01-09T12:13:21Z | 21,020,007 | 10 | 2014-01-09T12:16:29Z | [
"python"
] | I have the following code:
```
line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")
print "I'm going to write these to the file."
target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")
```
Here target is the file object... | You're confusing the braces. Do it like this:
```
target.write("%s \n %s \n %s \n" % (line1, line2, line3))
```
Or even better, use `writelines`:
```
target.writelines([line1, line2, line3])
``` |
Security considerations of `pip --allow-external` | 21,021,326 | 15 | 2014-01-09T13:14:01Z | 21,069,581 | 23 | 2014-01-12T00:07:35Z | [
"python",
"security",
"pip"
] | What are the security considerations of using `--allow-external` or `--allow-all-externals` options of `pip`?
The documentation sections where these options are described ([pip install](http://www.pip-installer.org/en/latest/reference/pip_install.html?install#externally-hosted-files), [pip wheel](http://www.pip-instal... | I have asked this question on the FreeNode `#pip` channel. The following is my interpretation of the replies I've got there. Thanks go to `agronholm` and `dstufft` from `#pip` for answering my question.
Packages can be maintained on PyPI in three different ways:
1. Directly on PyPI. If a package is hosted on PyPI, no... |
Difference between "yield" of Tornado and "yield from" of asyncio in mechanism? | 21,021,498 | 20 | 2014-01-09T13:23:28Z | 21,021,569 | 19 | 2014-01-09T13:27:12Z | [
"python",
"generator",
"tornado",
"yield"
] | In Tornado, we usually write the following code to call a function asynchronously:
```
class MainHandler(tornado.web.RequestHandler):
@tornado.gen.coroutine
def post(self):
...
yield self.handleRequest(foo)
...
@tornado.gen.coroutine
def handleRequest(self, foo):
...
`... | There is a huge difference between the two. `yield from` takes another generator and continues yielding from that generator instead (delegating responsibility, as it were). `yield` just yields **one** value.
In other words, `yield from`, in the simplest case, could be replaced by:
```
for value in self.handleRequest(... |
Pandas: Elementwise multiplication of two dataframes | 21,022,865 | 11 | 2014-01-09T14:25:13Z | 21,023,125 | 16 | 2014-01-09T14:36:34Z | [
"python",
"pandas",
"multiplication",
"dataframe"
] | I know how to do element by element multiplication between two Pandas dataframes. However, things get more complicated when the dimensions of the two dataframes are not compatible. For instance below `df * df2` is straightforward, but `df * df3` is a problem:
```
df = pd.DataFrame({'col1' : [1.0] * 5,
... | ```
In [161]: pd.DataFrame(df.values*df2.values, columns=df.columns, index=df.index)
Out[161]:
col1 col2 col3
1 10 200 3000
2 10 200 3000
3 10 200 3000
4 10 200 3000
5 10 200 3000
``` |
Python list comprehensions to create multiple lists | 21,023,482 | 6 | 2014-01-09T14:51:10Z | 21,023,578 | 10 | 2014-01-09T14:55:06Z | [
"python",
"list",
"list-comprehension"
] | I want to create two lists `listOfA` and `listOfB` to store indices of `A` and `B` from another list s.
```
s=['A','B','A','A','A','B','B']
```
Output should be two lists
```
listOfA=[0,2,3,4]
listOfB=[1,5,6]
```
I am able to do this with two statements.
```
listOfA=[idx for idx,x in enumerate(s) if x=='A']
listOf... | Sort of; the key is to generate a 2-element list that you can then unpack:
```
listOfA, listOfB = [[idx for idx, x in enumerate(s) if x == c] for c in 'AB']
```
That said, I think it's pretty daft to do it that way, an explicit loop is much more readable. |
Python list comprehensions to create multiple lists | 21,023,482 | 6 | 2014-01-09T14:51:10Z | 21,023,591 | 21 | 2014-01-09T14:55:31Z | [
"python",
"list",
"list-comprehension"
] | I want to create two lists `listOfA` and `listOfB` to store indices of `A` and `B` from another list s.
```
s=['A','B','A','A','A','B','B']
```
Output should be two lists
```
listOfA=[0,2,3,4]
listOfB=[1,5,6]
```
I am able to do this with two statements.
```
listOfA=[idx for idx,x in enumerate(s) if x=='A']
listOf... | The very definition of a list comprehension is to produce **one** list object. Your 2 list objects are of different lengths even; you'd have to use side-effects to achieve what you want.
Don't use list comprehensions here. Just use an ordinary loop:
```
listOfA, listOfB = [], []
for idx, x in enumerate(s):
targe... |
Annotate heatmap with value from Pandas dataframe | 21,024,066 | 4 | 2014-01-09T15:16:52Z | 21,167,108 | 7 | 2014-01-16T16:17:01Z | [
"python",
"text",
"matplotlib",
"pandas",
"heatmap"
] | I would like to annotate a heatmap with the values that I pass from a dataframe into the function below. I have looked at matplotlib.text but have not been able to get the values from my dataframe in a desired way in my heatmap. I have pasted in my function for generating a heatmap below, after that my dataframe and th... | The values you were using for your coordinates in your `for` loop were screwed up. Also you were using `plt.colorbar` instead of something cleaner like `fig.colorbar`. Try this (it gets the job done, with no effort made to otherwise cleanup the code):
```
def heatmap_binary(df,
edgecolors='w',
... |
Python custom function using rolling_apply for pandas | 21,025,821 | 2 | 2014-01-09T16:29:22Z | 21,026,837 | 7 | 2014-01-09T17:14:22Z | [
"python",
"pandas"
] | I would like to use the `pandas.rolling_apply` function to apply my own custom function on a rolling window basis.
but my function requires two arguments, and also has two outputs. Is this possible?
Below is a minimum reproducible example...
```
import pandas as pd
import numpy as np
import random
tmp = pd.DataFram... | `rolling_apply` passes numpy arrays to the applied function (at-the-moment), by 0.14 it should pass a frame. The issue is [here](https://github.com/pydata/pandas/issues/5071)
So redefine your function to work on a numpy array. (You can of course construct a DataFrame inside here, but your index/column names won't be t... |
Factory Design Pattern | 21,025,959 | 9 | 2014-01-09T16:35:19Z | 21,026,371 | 10 | 2014-01-09T16:52:46Z | [
"python"
] | I am trying to implement Factory Design Pattern and have done this far till now.
```
import abc
class Button(object):
__metaclass__ = abc.ABCMeta
html = ""
def get_html(self, html):
return self.html
class ButtonFactory():
def create_button(self, type):
baseclass = Button()
ta... | You are trying to call `baseclass` attribute of `str`, which does not exist, because `b` gets string values (one of `['image', 'input', 'flash']`).
If you want to create an object according to a string representing its name, you can use the `globals()` dictionary, which holds a mapping between variable names and their ... |
Joblib Parallel multiple cpu's slower than single | 21,027,477 | 13 | 2014-01-09T17:47:38Z | 21,029,356 | 18 | 2014-01-09T19:28:17Z | [
"python",
"parallel-processing"
] | I've just started using the Joblib module and I'm trying to understand how the Parallel function works. Below is an example of where parallelizing leads to longer runtimes but I don't understand why. My runtime on 1 cpu was 51 sec vs. 217 secs on 2 cpu.
My assumption was that running the loop in parallel would copy li... | In short: I cannot reproduce your problem. If you are on Windows you should use a protector for your main loop: [documentation of `joblib.Parallel`](http://pythonhosted.org/joblib/parallel.html#common-usage). The only problem I see is much data copying overhead, but your numbers seem unrealistic to be caused by that.
... |
Joblib Parallel multiple cpu's slower than single | 21,027,477 | 13 | 2014-01-09T17:47:38Z | 32,649,856 | 7 | 2015-09-18T10:33:20Z | [
"python",
"parallel-processing"
] | I've just started using the Joblib module and I'm trying to understand how the Parallel function works. Below is an example of where parallelizing leads to longer runtimes but I don't understand why. My runtime on 1 cpu was 51 sec vs. 217 secs on 2 cpu.
My assumption was that running the loop in parallel would copy li... | In addition to the above answer, and for future reference, there are two aspects to this question, and joblib's recent evolutions helps with both.
**Parallel pool creation overhead**: The problem here is that creating a parallel pool is costly. It's was especially costly here, as the code not protected by the "**main*... |
Python - Datetime not accounting for leap second properly? | 21,027,639 | 10 | 2014-01-09T17:55:25Z | 21,029,510 | 7 | 2014-01-09T19:35:58Z | [
"python",
"datetime",
"leap-second"
] | I am parsing some data that has the leapsecond timestampe datetime `2012-06-30T23:59:60.209215`. I used following code to parse that string and convert to a datetime object:
```
nofrag, frag = t.split('.')
nofrag_dt = datetime.datetime.strptime(nofrag, "%Y-%m-%dT%H:%M:%S")
dt = nofrag_dt.replace(microsecon... | [The documentation for `%S` says](http://docs.python.org/2.7/library/datetime.html#strftime-strptime-behavior):
> Unlike the time module, the datetime module does not support leap seconds.
The time string `"2012-06-30T23:59:60.209215"` implies that the time is in UTC (it is the last leap second at the moment):
```
i... |
How to remove ellipsis from a row in a Python Pandas series or data frame, shown when long lines/wide columns are truncated? | 21,028,819 | 4 | 2014-01-09T18:57:58Z | 21,028,960 | 7 | 2014-01-09T19:05:25Z | [
"python",
"pandas",
"printing",
"options",
"column-width"
] | When I create the following Pandas Series:
```
pandas.Series(['a', 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'aaaaaaaaaaaaaaaa', 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa']
```
I get this... | pandas is truncating the output, you can change this:
```
In [4]:
data = pd.Series(['a', 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'aaaaaaaaaaaaaaaa', 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa... |
Why \g<0> behaves differently than \0 in re.sub? | 21,028,917 | 10 | 2014-01-09T19:03:24Z | 21,028,980 | 9 | 2014-01-09T19:06:30Z | [
"python",
"regex"
] | I'm using Python 3.3
```
re.sub("(.)(.)",r"\2\1\g<0>","ab") returns baab
```
BUT
```
re.sub("(.)(.)",r"\2\1\0","ab") returns ba
```
Is this a bug in the sub method or does the sub method not recognize \0 on purpose for some reason? | As [written on this page](http://bugs.python.org/issue17426), the `\0` is interpreted as the null character (`\x00`) and group number start at 1 in Python (according to the `re` module documentation):
> \number
>
> Matches the contents of the group of the same number. Groups are **numbered starting from 1**. For examp... |
recursive iteration through nested json for specific key in python | 21,028,979 | 6 | 2014-01-09T19:06:27Z | 21,029,414 | 7 | 2014-01-09T19:30:53Z | [
"python",
"json",
"recursion",
"iteration",
"list-comprehension"
] | I'm trying to pull nested values from a json file. I want to print out each of the values for every "id" key. I think I'm close but can't figure out why the obj type changes from a dict to a list, and then why I'm unable to parse that list.
Here is a link to the json I'm working with: <http://hastebin.com/ratevimixa.te... | ```
def id_generator(dict):
for k, v in dict.items():
if k == "id":
yield v
elif isinstance(v, dict):
for id_val in id_generator(v):
yield id_val
```
This will create iterator which will yield every value on any level under key "id"... |
Understanding python subprocess.check_output's first argument and shell=True | 21,029,154 | 8 | 2014-01-09T19:17:20Z | 21,029,310 | 10 | 2014-01-09T19:25:26Z | [
"python",
"linux",
"shell",
"subprocess"
] | I'm confused on how to correctly use Python's subprocess module, specifically, the check\_output method's first argument and the `shell` option. Check out the output from the interactive prompt below. I pass the first argument as a list and depending on whether `shell=True` is set, I get different output. Can someone e... | From the documentation of [`Popen`](http://docs.python.org/2/library/subprocess.html#subprocess.Popen):
> The shell argument (which defaults to `False`) specifies whether to use
> the shell as the program to execute. If shell is `True`, it is
> recommended to pass `args` as a string rather than as a sequence.
>
> On U... |
Python test Average Calculator returen error 'list' object has no attribute 'len' | 21,030,116 | 3 | 2014-01-09T20:09:00Z | 21,030,132 | 7 | 2014-01-09T20:09:43Z | [
"python"
] | Hey this is a demo to show some of my classmates an intro to python and coding. The code below should be able to take a list like `[0,1]` and if run using the `average` function would return 0.5. When run using a list the function below returns the error `'list' object has no attribute 'len'`. How would I get this func... | Change the line. Refer the python docs for the built-in [len](http://docs.python.org/2/library/functions.html#len). The built-in len calculates the number of items in a sequence. As list is a sequence, the built-in can work on it.
```
averageGrade= total / lst.len()
```
to
```
averageGrade= total / len(lst)
```
The... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.