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 type() shows different results | 31,040,723 | 3 | 2015-06-25T03:29:00Z | 31,040,776 | 7 | 2015-06-25T03:34:36Z | [
"python",
"sublimetext2"
] | I'm using `Sublime Text 2` while learning Python, actually I'm just a beginner. Now, when I write `type(1/2)` in editor and build it(**cmd+B**), I get the output as **int**. Instead if I write the same instruction in Sublime's terminal(**ctrl + `** ), I get the result as **float**. Can somebody explain me why does that... | Somewhere the code is importing from `__future__.division`
```
>>> type(1/2)
<type 'int'>
>>> from __future__ import division
>>> type(1/2)
<type 'float'>
```
`python2.7`
```
>>> type(1/2)
<type 'int'>
```
Python 3 has type report this as a class so it's not the interpreter using python3.
`python3`
```
>>> type(1... |
Can't open video using opencv | 31,040,746 | 5 | 2015-06-25T03:31:33Z | 31,130,210 | 7 | 2015-06-30T05:27:26Z | [
"python",
"opencv",
"video",
"codec"
] | The opencv works fine when doing other things. It can open images and show images. But it can't open a video.
The code I'm using to open a video is as below
```
import cv2
cap = cv2.VideoCapture("MOV_0006.mp4")
while True:
ret, frame = cap.read()
cv2.imshow('video', frame)
if cv2.waitKey(1) & 0xff == o... | # It's a codec problem
I converted that `mp4` file to an `avi` file with `ffmpeg`. Then the above opencv code can play that `avi` file well.
Therefore I am sure that this is a codec problem.
(I then converted that `mp4` file to another `mp4` file using `ffmpeg`, thinking maybe `ffmpeg` would help turning that origin... |
How do I get authentication in a telegram bot? | 31,042,219 | 13 | 2015-06-25T05:52:34Z | 31,212,577 | 23 | 2015-07-03T18:33:26Z | [
"python",
"authentication",
"telegram",
"telegram-bot"
] | Telegram Bots are ready now.
If we use the analogy of web browser and websites, the telegram client applications are like the browser clients.
The Telegram Chatrooms are like websites.
Suppose we have some information we only want to restrict to certain users, on the websites, we will have authentication.
How do we... | *Forget about the webhook thingy.*
The deep linking explained:
1. Let the user log in on an actual website with actual username-password authentication.
2. Generate a unique hashcode (we will call it unique\_code)
3. Save unique\_code->username to a database or key-value storage.
4. Show the user the URL <https://tele... |
Define True, if not defined, causes syntax error | 31,042,827 | 19 | 2015-06-25T06:31:16Z | 31,042,847 | 9 | 2015-06-25T06:32:30Z | [
"python",
"python-3.x"
] | I have found the following construct today in someone elses code:
```
try: True, False
except NameError: True = 1==1; False = 1==0
```
As I understand this, it defines `True` and `False` if they are not defined already. So if they are defined it shouldn't throw the `NameError`-Exception, right?
I have tryed this for... | `SyntaxError` shows up during the byte-compilation stage, before the code is ever run -- so you can't get around it with `try`/`except`. |
Define True, if not defined, causes syntax error | 31,042,827 | 19 | 2015-06-25T06:31:16Z | 31,042,962 | 21 | 2015-06-25T06:39:06Z | [
"python",
"python-3.x"
] | I have found the following construct today in someone elses code:
```
try: True, False
except NameError: True = 1==1; False = 1==0
```
As I understand this, it defines `True` and `False` if they are not defined already. So if they are defined it shouldn't throw the `NameError`-Exception, right?
I have tryed this for... | This code is written for Python 2.x and won't work on Python 3.x (in which `True` and `False` are true keywords).
Since `True` and `False` are keywords in Python 3, you'll get a `SyntaxError` which you cannot catch.
This code exists because of very old versions of Python. In Python 2.2 (released in 2001!), `True` and... |
Method to get the max distance (step) between values in python? | 31,044,711 | 4 | 2015-06-25T08:11:44Z | 31,044,798 | 8 | 2015-06-25T08:16:12Z | [
"python",
"list"
] | Given an list of integers does exists a default method find the max distance between values?
So if I have this array
```
[1, 3, 5, 9, 15, 30]
```
The max step between the values is 15. Does the list object has a method for do that? | No, `list` objects have no standard "adjacent differences" method or the like. However, using the `pairwise` function mentioned in the [`itertools` recipes](https://docs.python.org/2/library/itertools.html#recipes):
```
def pairwise(iterable):
a, b = tee(iterable)
next(b, None)
return izip(a, b)
```
...yo... |
Finding prime numbers using list comprehention | 31,045,518 | 4 | 2015-06-25T08:50:02Z | 31,045,603 | 11 | 2015-06-25T08:53:41Z | [
"python",
"math",
"list-comprehension"
] | I was trying to generate all prime numbers in range x to y. I tried simple example first: `range(10,11)` which means to check if 10 is a prime number:
Here is my code:
```
prime_list = [x for x in range(10, 11) for y in range(2,x) if x % x == 0 and x % 1 == 0 and x % y != 0]
```
I know that the thing is missing the... | Use [`all`](https://docs.python.org/3/library/functions.html#all) to check all elements (from 2 upto x-1) met conditions:
```
>>> [x for x in range(2, 20)
if all(x % y != 0 for y in range(2, x))]
[2, 3, 5, 7, 11, 13, 17, 19]
``` |
What is the most pythonic way to iterate over OrderedDict | 31,046,231 | 17 | 2015-06-25T09:22:45Z | 31,046,250 | 40 | 2015-06-25T09:23:52Z | [
"python",
"python-2.7",
"loops",
"dictionary"
] | I have an OrderedDict and in a loop I want to get index, key and value.
It's sure can be done in multiple ways, i.e.
```
a = collections.OrderedDict({â¦})
for i,b,c in zip(range(len(a)), a.iterkeys(), a.itervalues()):
â¦
```
But I would like to avoid range(len(a)) and shorten a.iterkeys(), a.itervalues() to somet... | You can use tuple unpacking in [`for` statement](https://docs.python.org/2/reference/compound_stmts.html#the-for-statement):
```
for i, (key, value) in enumerate(a.iteritems()):
# Do something with i, key, value
```
---
```
>>> d = {'a': 'b'}
>>> for i, (key, value) in enumerate(d.iteritems()):
... print i, ... |
Scrapy gives URLError: <urlopen error timed out> | 31,048,130 | 5 | 2015-06-25T10:44:54Z | 31,055,000 | 15 | 2015-06-25T15:46:32Z | [
"python",
"web-scraping",
"scrapy"
] | So I have a scrapy program I am trying to get off the ground but I can't get my code to execute it always comes out with the error below.
I can still visit the site using the `scrapy shell` command so I know the Url's and stuff all work.
Here is my code
```
from scrapy.spiders import CrawlSpider, Rule
from scrapy.li... | There's an open scrapy issue for this problem: <https://github.com/scrapy/scrapy/issues/1054>
Although it seems to be just a warning on other platforms.
You can disable the S3DownloadHandler (that is causing this error) by adding to your scrapy settings:
```
DOWNLOAD_HANDLERS = {
's3': None,
}
``` |
how to merge two data structure in python | 31,049,042 | 4 | 2015-06-25T11:26:14Z | 31,049,085 | 7 | 2015-06-25T11:28:53Z | [
"python",
"dictionary",
"recursion",
"data-structures",
"iterator"
] | I am having two complex data structure(i.e. \_to and \_from), I want to override the entity of \_to with the same entity of \_from.
I have given this example.
```
# I am having two data structure _to and _from
# I want to override _to from _from
_to = {'host': 'test',
'domain': [
{
'ss... | It's quite simple:
```
_to.update(_from)
``` |
Migrating database from local development to Heroku-Django 1.8 | 31,057,998 | 4 | 2015-06-25T18:26:29Z | 31,059,287 | 10 | 2015-06-25T19:35:56Z | [
"python",
"django",
"postgresql",
"heroku",
"django-database"
] | After establishing a database using `heroku addons:create heroku-postgresql:hobby-dev`, I tried to migrate my local database to heroku database. So I first ran
`heroku python manage.py migrate`. After that I created a dump file of my local database using `pg_dump -Fc --no-acl --no-owner -h localhost -U myuser mydb > m... | If the database is small and you feel lucky this might do it
```
pg_dump --no-acl --no-owner -h localhost -U myuser myd | heroku pg:psql
``` |
Spark 1.4 increase maxResultSize memory | 31,058,504 | 9 | 2015-06-25T18:51:55Z | 31,058,669 | 16 | 2015-06-25T19:01:57Z | [
"python",
"memory",
"apache-spark",
"pyspark",
"jupyter"
] | I am using Spark 1.4 for my research and struggling with the memory settings. My machine has 16GB of memory so no problem there since the size of my file is only 300MB. Although, when I try to convert Spark RDD to panda dataframe using `toPandas()` function I receive the following error:
```
serialized results of 9 ta... | You can set `spark.driver.maxResultSize` parameter in the `SparkConf` object:
```
from pyspark import SparkConf, SparkContext
# In Jupyter you have to stop the current context first
sc.stop()
# Create new config
conf = (SparkConf()
.set("spark.driver.maxResultSize", "2g"))
# Create new context
sc = SparkContext... |
How to load default profile in chrome using Python Selenium Webdriver? | 31,062,789 | 3 | 2015-06-26T00:03:17Z | 31,063,104 | 11 | 2015-06-26T00:43:15Z | [
"python",
"selenium-chromedriver"
] | So I'd like to open chrome with its default profile using pythons webdriver. I've tried everything I could find but I still couldn't get it to work. Thanks for the help! | This is what finally got it working for me.
```
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
options = webdriver.ChromeOptions()
options.add_argument("user-data-dir=C:\\Path") #Path to your chrome profile
w = webdriver.Chrome(executable_path="C:\\Users\\chromedriver.exe", chro... |
Python3 error: initial_value must be str or None | 31,064,981 | 9 | 2015-06-26T04:33:15Z | 31,067,445 | 13 | 2015-06-26T07:28:52Z | [
"python",
"python-3.x",
"urllib2",
"urllib"
] | While porting code from `python2` to `3`, I get this error when reading from a URL
> TypeError: initial\_value must be str or None, not bytes.
```
import urllib
import json
import gzip
from urllib.parse import urlencode
from urllib.request import Request
service_url = 'https://babelfy.io/v1/disambiguate'
text = 'Ba... | `response.read()` returns an instance of `bytes` while [`StringIO`](https://docs.python.org/3/library/io.html#io.StringIO) is an in-memory stream for text only. Use [`BytesIO`](https://docs.python.org/3/library/io.html#io.BytesIO) instead.
From [What's new in Python 3.0 - Text Vs. Data Instead Of Unicode Vs. 8-bit](ht... |
Simple line plots using seaborn | 31,069,191 | 12 | 2015-06-26T09:08:51Z | 31,072,485 | 22 | 2015-06-26T11:50:49Z | [
"python",
"matplotlib",
"plot",
"seaborn",
"roc"
] | I'm trying to plot a ROC curve using seaborn (python).
With matplotlib I simply use the function `plot`:
```
plt.plot(one_minus_specificity, sensitivity, 'bs--')
```
where `one_minus_specificity` and `sensitivity` are two lists of paired values.
Is there a simple counterparts of the plot function in seaborn? I had a... | Since seaborn also uses matplotlib to do its plotting you can easily combine the two. If you only what to adopt the styling of seaborn the [`set_style`](http://stanford.edu/~mwaskom/software/seaborn/tutorial/aesthetics.html#styling-figures-with-axes-style-and-set-style) function should get you started:
```
import matp... |
Django Get Latest Entry from Database | 31,070,368 | 3 | 2015-06-26T10:03:41Z | 31,070,622 | 7 | 2015-06-26T10:15:43Z | [
"python",
"django",
"django-models"
] | I've got 2 questions, but they are related to the same topic.
I know how to retrieve data from a `for loop` using template tags
```
{% for status in status %}
<tr>
<td>{{ status.status}}</td>
</tr>
{% endfor %}
```
However when I want to retrieve a single object i get an error even when i use:
```... | You have two different questions here:
1. How do I retrieve the latest object from the database.
You can do this using the [`latest()`](https://docs.djangoproject.com/en/dev/ref/models/querysets/#latest) queryset operator. By reading the docs you will note that this operator works on date fields, not integers.
```
S... |
Find all local Maxima and Minima when x and y values are given as numpy arrays | 31,070,563 | 5 | 2015-06-26T10:12:49Z | 31,073,798 | 13 | 2015-06-26T12:57:37Z | [
"python",
"numpy",
"derivative"
] | I have two arrays `x` and `y` as :
```
x = np.array([6, 3, 5, 2, 1, 4, 9, 7, 8])
y = np.array([2, 1, 3, 5, 3, 9, 8, 10, 7])
```
I am finding index of local minima and maxima as follows:
```
sortId = np.argsort(x)
x = x[sortId]
y = y[sortId]
minm = np.array([])
maxm = np.array([])
while i < y.size-1:
while(y[i+1] ... | You do not need this `while` loop at all. The code below will give you the output you want; it finds all local minima and all local maxima and stores them in `minm` and `maxm`, respectively. Please note: When you apply this to large datasets, make sure to smooth the signals first; otherwise you will end up with tons of... |
Python: using comprehensions in for loops | 31,072,039 | 3 | 2015-06-26T11:26:54Z | 31,072,227 | 11 | 2015-06-26T11:37:38Z | [
"python",
"python-2.7"
] | I'm using Python 2.7. I have a list, and I want to use a for loop to iterate over a subset of that list subject to some condition. Here's an illustration of what I'd like to do:
```
l = [1, 2, 3, 4, 5, 6]
for e in l if e % 2 == 0:
print e
```
which seems to me very neat and Pythonic, and is lovely in every way ex... | What's wrong with a simple, readable solution:
```
l = [1, 2, 3, 4, 5, 6]
for e in l:
if e % 2 == 0:
print e
```
You can have any amount of statements instead of just a simple `print e` and nobody has to scratch their head trying to figure out what it does.
If you need to use the sub list for something e... |
Passing a list of strings from Python to Rust | 31,074,994 | 9 | 2015-06-26T13:51:14Z | 31,075,375 | 9 | 2015-06-26T14:08:54Z | [
"python",
"rust",
"ctypes",
"ffi"
] | I've been learning Rust for about two weeks now and today, I got into its FFI. I used Python to play with Rust, using ctypes and libc. I passed integers, strings and even learned to pass a list of integers ([thanks to this wonderful answer](http://stackoverflow.com/a/30313295/2313792)).
Then, I tried to pass a list of... | There is absolutely no difference with the case of array of numbers. C strings are zero-terminated arrays of bytes, so their representation in Rust will be `*const c_char`, which could then be converted to `&CStr` which then can be used to obtain `&[u8]` and then `&str`.
Python:
```
import ctypes
rustLib = "libtest.... |
How does Flask-SQLAlchemy create_all discover the models to create? | 31,082,692 | 5 | 2015-06-26T21:50:18Z | 31,091,883 | 7 | 2015-06-27T18:09:40Z | [
"python",
"flask",
"sqlalchemy",
"flask-sqlalchemy"
] | Flask-SQLAlchemy's `db.create_all()` method creates each table corresponding to my defined models. I never instantiate or register instances of the models. They're just class definitions that inherit from `db.Model`. How does it know which models I have defined? | Flask-SQLAlchemy does nothing special, it's all a standard part of SQLAlchemy.
Calling [`db.create_all`](https://github.com/mitsuhiko/flask-sqlalchemy/blob/1d8e9873bed9e8b75a9e7b0903870fe832b92628/flask_sqlalchemy/__init__.py#L967) eventually calls [`db.Model.metadata.create_all`](http://docs.sqlalchemy.org/en/rel_1_0... |
Installing pzmq with Cygwin | 31,082,901 | 4 | 2015-06-26T22:12:11Z | 32,684,916 | 7 | 2015-09-20T22:22:26Z | [
"python",
"windows",
"gcc",
"cygwin",
"ipython-notebook"
] | For two days I have been struggling to install pyzmq and I am really not sure what the issue is.
The error message I receive after:
```
pip install pyzmq
```
is:
```
error: command 'gcc' failed with exit status 1
```
I have gcc installed.
```
which gcc
/usr/bin/gcc
```
Python is installed at the same location. ... | Installing IPython in Cygwin with pip was painful but not impossible. This comment by @ahmadia on the zeromq GitHub project gives instructions for installing pyzmq: <https://github.com/zeromq/pyzmq/issues/113#issuecomment-25192831>
The comment says it's for 64-bit Cygwin but the instructions worked fine for me on 32-b... |
How to stop memory leaks when using `as_ptr()`? | 31,083,223 | 6 | 2015-06-26T22:47:30Z | 31,083,443 | 7 | 2015-06-26T23:10:23Z | [
"python",
"memory-leaks",
"rust",
"ctypes",
"ffi"
] | Since it's my first time learning systems programming, I'm having a hard time wrapping my head around the rules. Now, I got confused about memory leaks. Let's consider an example. Say, Rust is throwing a pointer (to a string) which Python is gonna catch.
In Rust, (I'm just sending the pointer of the `CString`)
```
us... | Your Rust function `do_something` constructs a temporary `CString`, takes a pointer into it, and then *drops the `CString`*. The `*const c_char` is invalid from the instant you return it. If you're on nightly, you probably want `CString#into_ptr` instead of `CString#as_ptr`, as the former consumes the `CString` without... |
ImportError: No module named concurrent.futures.process | 31,086,530 | 12 | 2015-06-27T08:05:06Z | 32,397,747 | 27 | 2015-09-04T12:11:01Z | [
"python",
"path"
] | I have followed the procedure given in [How to use valgrind with python?](http://stackoverflow.com/questions/20112989/how-to-use-valgrind-with-python) for checking memory leaks in my python code.
I have my python source under the path
```
/root/Test/ACD/atech
```
I have given above path in `PYTHONPATH`. Everything i... | If you're using Python 2.7 you must install this module :
```
pip install futures
```
Futures feature has never included in Python 2.x core. However, it's present in Python 3.x since Python 3.2. |
TypeError: 'list' object is not callable in python | 31,087,111 | 4 | 2015-06-27T09:16:56Z | 31,087,151 | 16 | 2015-06-27T09:22:10Z | [
"python",
"list"
] | I am novice to Python and following a tutorial. There is an example of `list` in the tutorial :
```
example = list('easyhoss')
```
Now, In tutorial, `example= ['e','a',...,'s']`. But in my case I am getting following error:
```
>>> example = list('easyhoss')
Traceback (most recent call last):
File "<stdin>", line ... | Seems like you've shadowed the built-in name `list` by an instance name somewhere in your code.
```
>>> example = list('easyhoss')
>>> list = list('abc')
>>> example = list('easyhoss')
Traceback (most recent call last):
File "<string>", line 1, in <module>
TypeError: 'list' object is not callable
```
I believe this i... |
Make a pythonic one line statement like "return True if flag"? | 31,091,184 | 2 | 2015-06-27T16:54:47Z | 31,091,215 | 8 | 2015-06-27T16:58:24Z | [
"python",
"syntax"
] | Is there a way to write a one line python statement for
```
if flag:
return True
```
Note that this can be semantically different from
```
return flag
```
In my case, None is expected to be returned otherwise.
I have tried with "return True if flag", which has syntactic error detected by my emacs. | `return True if flag` doesn't work because you need to supply an explicit `else`. You could use:
```
return True if flag else None
```
to replicate the behaviour of your original if statement. |
Do Python 2.7 views, for/in, and modification work well together? | 31,092,518 | 4 | 2015-06-27T19:07:59Z | 31,092,521 | 7 | 2015-06-27T19:08:28Z | [
"python",
"python-2.7",
"dictionary",
"concurrentmodification",
"for-in-loop"
] | The Python docs give warnings about trying to modify a dict while iterating over it. Does this apply to views?
I understand that views are "live" in the sense that if you change the underlying dict, the view automatically reflects the change. I'm also aware that a dict's natural ordering can change if elements are add... | Yes, this applies to dictionary views over either keys or items, as they provide a *live* view of the dictionary contents. You *cannot* add or remove keys to the dictionary while iterating over a dictionary view, because, as you say, this alters the dictionary order.
Demo to show that this is indeed the case:
```
>>>... |
Why do these print() calls appear to execute in the wrong order? | 31,093,617 | 3 | 2015-06-27T21:18:23Z | 31,093,631 | 7 | 2015-06-27T21:19:59Z | [
"python",
"python-3.x"
] | weird.py:
```
import sys
def f ():
print('f', end = '')
g()
def g ():
1 / 0
try:
f()
except:
print('toplevel', file = sys.stderr)
```
Python session:
```
Python 3.4.2 (v3.4.2:ab2c023a9432, Oct 6 2014, 22:16:31) [MSC v.1600 64 bit (AM
D64)] on win32
Type "help", "copyright", "credits" or "lice... | Because stdout and stderr are *line buffered*. They buffer characters and only flush when you have a complete line.
By setting `end=''` you ensure there is no complete line and the buffer isn't flushed until *later* when the Python interactive interpreter outputs `>>>` and flushes the buffer explicitly.
If you remove... |
Vectorize iterative addition in NumPy arrays | 31,093,989 | 8 | 2015-06-27T22:05:18Z | 31,094,448 | 8 | 2015-06-27T23:07:44Z | [
"python",
"loops",
"numpy",
"optimization",
"vectorization"
] | For each element in a randomized array of 2D indices (with potential duplicates), I want to "+=1" to the corresponding grid in a 2D zero array. However, I don't know how to optimize the computation. Using the standard for loop, as shown here,
```
def interadd():
U = 100
input = np.random.random(size=(5000,2))... | You could speed it up a little by using [`np.add.at`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.ufunc.at.html), which correctly handles the case of duplicate indices:
```
def interadd(U, idx):
grids = np.zeros((U,U))
for i in range(len(idx)):
grids[idx[i,0],idx[i,1]] += 1
retu... |
Numpy select non-zero rows | 31,097,043 | 2 | 2015-06-28T07:03:08Z | 31,097,051 | 7 | 2015-06-28T07:04:01Z | [
"python",
"numpy"
] | I wan to select only rows which has not any 0 element.
```
data = np.array([[1,2,3,4,5],
[6,7,0,9,10],
[11,12,13,14,15],
[16,17,18,19,0]])
```
The result would be:
```
array([[1,2,3,4,5],
[11,12,13,14,15]])
``` | Use [`numpy.all`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.all.html):
```
>>> data[np.all(data, axis=1)]
array([[ 1, 2, 3, 4, 5],
[11, 12, 13, 14, 15]])
``` |
Python lightweight case insensitive if "x" in variable | 31,099,178 | 2 | 2015-06-28T11:18:07Z | 31,099,222 | 7 | 2015-06-28T11:23:46Z | [
"python"
] | I am looking for a method analogous to `if "x" in variable:` that is case insensitive and light-weight to implement.
I have tried some of the implementations here but they don't really fit well for my usage: [Case insensitive 'in' - Python](http://stackoverflow.com/questions/3627784/case-insensitive-in-python)
What I... | Just do
```
if "Short".lower() in description.lower():
...
```
The `.lower()` method does not change the object, it returns a new one, which is changed. If you are worried about performance, don't be, unless your are doing it on huge strings, or thousands of times per second.
If you are going to do that more tha... |
Test if all elements of a python list are False | 31,099,561 | 9 | 2015-06-28T12:01:57Z | 31,099,577 | 19 | 2015-06-28T12:03:44Z | [
"python",
"list",
"numpy"
] | How to return 'false' because all elements are 'false'?
The given list is:
```
data = [False, False, False]
``` | Using [`any`](https://docs.python.org/2/library/functions.html#any):
```
>>> data = [False, False, False]
>>> not any(data)
True
```
`any` will return True if there's any truth value in the iterable. |
Efficiently build a graph of words with given Hamming distance | 31,100,623 | 18 | 2015-06-28T13:57:19Z | 31,101,320 | 19 | 2015-06-28T15:12:12Z | [
"python",
"algorithm",
"graph-algorithm",
"hamming-distance"
] | I want to build a graph from a list of words with [Hamming distance](https://en.wikipedia.org/wiki/Hamming_distance) of (say) 1, or to put it differently, two words are connected if they only differ from one letter (*lo**l*** -> *lo**t***).
so that given
`words = [ lol, lot, bot ]`
the graph would be
```
{
'lol' ... | Assuming you store your dictionary in a `set()`, so that [lookup is **O(1)** in the average (worst case **O(n)**)](https://wiki.python.org/moin/TimeComplexity).
You can generate all the valid words at hamming distance 1 from a word:
```
>>> def neighbours(word):
... for j in range(len(word)):
... for d in... |
Some doubts modelling some features for the libsvm/scikit-learn library in python | 31,104,106 | 8 | 2015-06-28T19:51:30Z | 31,202,538 | 8 | 2015-07-03T08:51:53Z | [
"python",
"dictionary",
"scikit-learn",
"libsvm"
] | I have scraped a lot of ebay titles like this one:
```
Apple iPhone 5 White 16GB Dual-Core
```
and I have manually tagged all of them in this way
```
B M C S NA
```
where B=Brand (Apple) M=Model (iPhone 5) C=Color (White) S=Size (Size) NA=Not Assigned (Dual Core)
Now I need to train a SVM classifier using the libs... | The reason that the solution proposed to you in the previous question had Insufficient results (I assume) - is that the feature were poor for this problem.
If I understand correctly, What you want is the following:
given the sentence -
> Apple iPhone 5 White 16GB Dual-Core
You to get-
> B M C S NA
The problem you... |
How to Python split by a character yet maintain that character? | 31,107,132 | 5 | 2015-06-29T03:01:31Z | 31,107,171 | 7 | 2015-06-29T03:08:08Z | [
"python",
"regex",
"python-2.7",
"split",
"newline"
] | Google Maps results are often displayed thus:

```
'\n113 W 5th St\nEureka, MO, United States\n(636) 938-9310\n'
```
Another variation:

```
'Clayton Village Shopping Center, 14856 ... | Don't use regex. Just split the string on the `'\n'`. The last index is a phone number, the other indexes are the address.
```
lines = inputString.split('\n')
phone = lines[-1] if lines[-1].match(REGEX_PHONE_US) else None
address = '\n'.join(lines[:-1]) if phone else inputString
```
Python has a lot of great buil... |
django-rest-framework accept JSON data? | 31,108,075 | 6 | 2015-06-29T04:59:48Z | 31,121,191 | 12 | 2015-06-29T16:47:45Z | [
"python",
"django",
"django-rest-framework"
] | I have created RESTFul APIs using django-rest-framework. The user endpoint is
```
/api/v1/users
```
I want to create new user. I send user data in JSOn format.
```
{
"username": "Test1",
"email": "test1@gmail.com",
"first_name": "Test1",
"last_name": "Test2",
"password":"12121212"
}
```
I am usi... | You have missed adding the `Content-Type` header in the headers section. Just set the `Content-Type` header to `application/json` and it should work.
See the below image:

Also, you might also need to include a CSRF token in the header in case you get an error `{"detail"... |
Swapping two sublists in a list | 31,111,258 | 16 | 2015-06-29T08:41:04Z | 31,111,801 | 25 | 2015-06-29T09:09:49Z | [
"python",
"list"
] | Given the following list:
```
my_list=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
```
I want to be able to swap the sub-list `my_list[2:4]` with the sub-list `my_list[7:10]` as quickly and as efficiently as possible, to get the new list:
```
new_list=[0, 1, 7, 8, 9, 4, 5, 6, 2, 3, 10, 11, 12]
```
Here's my attempt:
... | Slices can be assigned.
Two variables can be swapped with `a, b = b, a`.
Combine the two above::
```
>>> my_list[7:10], my_list[2:4] = my_list[2:4], my_list[7:10]
>>> my_list
[0, 1, 7, 8, 9, 4, 5, 6, 2, 3, 10, 11, 12]
```
---
Beware that - if slices have different sizes - the **order is important**: If you swap in... |
Find all possible ordered groups in a list | 31,115,816 | 4 | 2015-06-29T12:32:20Z | 31,115,974 | 8 | 2015-06-29T12:40:01Z | [
"python"
] | Given an ordered list of integers:
```
[1,3,7,8,9]
```
How can I find all the sublists that can be created from original list where order is maintained? Using the example above, I'm looking for a way to programmatically generate these sequences:
```
[[1],[3,7,8,9]]
[[1, 3],[7,8,9]]
[[1, 3, 7],[8,9]]
[[1, 3, 7, 8],[9... | How about:
```
import itertools
def subsets(seq):
for mask in itertools.product([False, True], repeat=len(seq)):
yield [item for x, item in zip(mask, seq) if x]
def ordered_groups(seq):
for indices in subsets(range(1, len(seq))):
indices = [0] + indices + [len(seq)]
yield [seq[a:b] fo... |
Load environment variables from a shell script | 31,117,531 | 2 | 2015-06-29T13:54:24Z | 32,206,226 | 7 | 2015-08-25T14:05:19Z | [
"python",
"bash",
"shell",
"environment-variables"
] | I have a file with some environment variables that I want to use in a python script
The following works form the command line
```
$ source myFile.sh
$ python ./myScript.py
```
and from inside the python script I can access the variables like
```
import os
os.getenv('myvariable')
```
How can I source the shell scri... | If you are saying backward environment propagation, sorry, you can't. It's a security issue. However, directly source environment from python is definitely valid. But it's more or less a manual process.
```
import subprocess as sp
SOURCE = 'your_file_path'
proc = sp.Popen(['bash', '-c', 'source {} && env'.format(SOUR... |
Why can't I remove quotes using `strip('\"')`? | 31,118,332 | 4 | 2015-06-29T14:29:33Z | 31,118,392 | 9 | 2015-06-29T14:32:04Z | [
"python",
"python-3.x"
] | I can only remove the left quotes using `str.strip('\"')`:
```
with open(filename, 'r') as fp :
for line in fp.readlines() :
print(line)
line = line.strip('\"')
print(line)
```
Part of results:
```
"Route d'Espagne"
Route d'Espagne"
```
Using `line.replace('\"', '')` gets the right resu... | Your lines do not *end* with quotes. The newline separator is part of the line to and is not removed when reading from a file, so unless you include `\n` in the set of characters to be stripped the `"` is going to stay.
When diagnosing issues with strings, produce debug output with `print(repr(line))` or even `print(a... |
Viewing the content of a Spark Dataframe Column | 31,124,131 | 7 | 2015-06-29T19:37:38Z | 31,124,244 | 7 | 2015-06-29T19:44:01Z | [
"python",
"apache-spark",
"dataframe",
"pyspark"
] | I'm using Spark 1.3.1.
I am trying to view the values of a Spark dataframe column in Python. With a Spark dataframe, I can do `df.collect()` to view the contents of the dataframe, but there is no such method for a Spark dataframe column as best as I can see.
For example, the dataframe `df` contains a column named `'z... | You can access underlying `RDD` and map over it
```
df.rdd.map(lambda r: r.zip_code).collect()
```
You can also use `select` if you don't mind results wrapped using `Row` objects:
```
df.select('zip_code').collect()
```
Finally, if you simply want to inspect content then `show` method should be enough:
```
df.sele... |
Does calling random.normal on an array of values add noise? | 31,128,510 | 6 | 2015-06-30T02:19:20Z | 31,128,610 | 8 | 2015-06-30T02:34:40Z | [
"python",
"numpy",
"random"
] | I saw this pattern in someone's code:
```
import numpy as np
# Create array
xx = np.linspace(0.0, 100.0, num=100)
# Add Noise
xx = np.random.normal(xx)
```
and it seems to add some noise to each value of the array, but I can't find any documentation for this. What's happening? What determines the properties (i.e. sca... | I don't see it documented either, but many numpy functions that take an ndarray will [operate on it element-wise](http://docs.scipy.org/doc/numpy/reference/ufuncs.html#). Anyway, you can easily verify that when passing it an array it call `numpy.random.normal` for each element on the array using that element's value as... |
Remove particular combinations from itertools.combinations | 31,131,526 | 2 | 2015-06-30T06:53:15Z | 31,131,552 | 7 | 2015-06-30T06:55:26Z | [
"python"
] | Suppose we have a pair of tuples where tuples can be of different length. Let's call them tuples `t1` and `t2`:
```
t1 = ('A', 'B', 'C')
t2 = ('d', 'e')
```
Now I compute all combinations of length 2 from both tuples using itertools:
```
import itertools
tuple(itertools.combinations(t1 + t2, 2))
```
Itertools gener... | You need `itertools.product` :
```
>>> t1 = ('A', 'B', 'C')
>>> t2 = ('d', 'e')
>>> from itertools import product
>>>
>>> list(product(t1,t2))
[('A', 'd'), ('A', 'e'), ('B', 'd'), ('B', 'e'), ('C', 'd'), ('C', 'e')]
```
If you are dealing with **short tuples** you can simply do this job with a list comprehension :
... |
Virtualenv Command Not Found | 31,133,050 | 11 | 2015-06-30T08:17:41Z | 37,242,519 | 13 | 2016-05-15T19:05:44Z | [
"python",
"osx",
"virtualenv"
] | I couldn't get `virtualenv` to work despite various attempts. I installed `virtualenv` on MAC OS X using:
```
pip install virtualenv
```
and have also added the `PATH` into my `.bash_profile`. Every time I try to run the `virtualenv` command, it returns:
```
-bash: virtualenv: command not found
```
Every time I run... | I faced the same issue and this is how I solved it:
1. The issue occurred to me because I installed virtualenv via pip as a regular user (not root). pip installed the packages into the directory `~/.local/lib/pythonX.X/site-packages`
2. When I ran pip as root or with admin privileges (sudo), it installed packages in `... |
Python str.translate VS str.replace | 31,143,290 | 4 | 2015-06-30T16:11:49Z | 31,145,842 | 7 | 2015-06-30T18:34:04Z | [
"python"
] | Why in ***Python*** `replace` is ~1.5x quicker than `translate`?
```
In [188]: s = '1 a 2'
In [189]: s.replace(' ','')
Out[189]: '1a2'
In [190]: s.translate(None,' ')
Out[190]: '1a2'
In [191]: %timeit s.replace(' ','')
1000000 loops, best of 3: 399 ns per loop
In [192]: %timeit s.translate(None,' ')
1000000 loops... | Assuming Python 2.7 (because I had to flip a coin without it being stated), we can find the source code for [string.translate](https://docs.python.org/2/library/string.html#string.translate) and [string.replace](https://docs.python.org/2/library/string.html#string.replace) in `string.py`:
```
>>> import inspect
>>> im... |
Theano Shared Variables on Python | 31,143,452 | 2 | 2015-06-30T16:21:02Z | 31,146,656 | 9 | 2015-06-30T19:20:11Z | [
"python",
"class",
"theano"
] | I am now learning the Theano library, and I am just feeling confused about Theano shared variables. By reading the tutorial, I think I didn't understand its detailed meaning. The following is the definition of the Theano shared variables from the tutorial:
"Variable with Storage that is shared between functions that i... | Theano shared variables behave more like ordinary Python variables. They have an explicit value that is persistent. In contrast, symbolic variables are not given an explicit value until one is assigned on the execution of a compiled Theano function.
Symbolic variables can be thought of as representing state for the du... |
Get Python Tornado Version? | 31,146,153 | 4 | 2015-06-30T18:50:56Z | 31,147,317 | 7 | 2015-06-30T19:55:44Z | [
"python",
"version",
"tornado"
] | How do I get the current version of my python Tornado Module Version?
With other packages I can do the following:
```
print <modulename>.__version__
```
Source:
[How to check version of python modules?](http://stackoverflow.com/questions/20180543/how-to-check-version-of-python-modules) | Tornado has both `tornado.version`, which is a string for human consumption (currently "4.2"), and `tornado.version_info`, which is a numeric tuple that is better for programmatic comparisons (currently `(4, 2, 0, 0)`). The fourth value of `version_info` will be negative for betas and other pre-releases. |
how do you create a linear regression forecast on time series data in python | 31,147,594 | 20 | 2015-06-30T20:10:13Z | 31,257,836 | 22 | 2015-07-07T00:23:04Z | [
"python"
] | I need to be able to create a python function for forecasting based on linear regression model with confidence bands on time series data:
The function needs to take in an argument to how far out it forecasts. For example 1day, 7days, 30days, 90days etc. Depending on the argument, it will need to create holtwinters for... | In the text of your question, you clearly state that you would like
upper and lower bounds on your regression output, as well as the output
prediction. You also mention using Holt-Winters algorithms for
forecasting in particular.
The packages suggested by other answerers are useful, but you might note
that `sklearn` L... |
Logarithmic plot of a cumulative distribution function in matplotlib | 31,147,893 | 13 | 2015-06-30T20:26:13Z | 31,575,603 | 13 | 2015-07-22T23:15:04Z | [
"python",
"numpy",
"matplotlib",
"logarithm",
"cdf"
] | I have a file containing logged events. Each entry has a time and latency. I'm interested in plotting the cumulative distribution function of the latencies. I'm most interested in tail latencies so I want the plot to have a logarithmic y-axis. I'm interested in the latencies at the following percentiles: 90th, 99th, 99... | Essentially you need to apply the following transformation to your `Y` values: `-log10(1-y)`. This imposes the only limitation that `y < 1`, so you should be able to have negative values on the transformed plot.
Here's a modified [example](http://matplotlib.org/examples/api/custom_scale_example.html) from `matplotlib`... |
Is "__module__" guaranteed to be defined during class creation? | 31,148,770 | 12 | 2015-06-30T21:24:12Z | 31,148,962 | 8 | 2015-06-30T21:37:09Z | [
"python",
"python-internals"
] | I was reading some code that looked basically like this:
```
class Foo(object):
class_name = __module__.replace('_', '-')
```
To me, that looked really weird (`__module__`, what is that?) so I went and looked at the python [data-model](https://docs.python.org/2/reference/datamodel.html). A quick search shows that... | What the documentation does define is that classes will have a `__module__` attribute. It seems the way CPython does this is that it defines a local variable `__module__` at the beginning of the class block. This variable then becomes a class attribut like any other variable defined there.
I can't find any documentati... |
Python - best way to check if tuple has any empty/None values? | 31,154,372 | 5 | 2015-07-01T06:49:50Z | 31,154,423 | 9 | 2015-07-01T06:52:46Z | [
"python",
"tuples",
"is-empty"
] | What is the best/most efficient way to check if all tuple values? Do I need to iterate over all tuple items and check or is there some even better way?
For example:
```
t1 = (1, 2, 'abc')
t2 = ('', 2, 3)
t3 = (0.0, 3, 5)
t4 = (4, 3, None)
```
Checking these tuples, every tuple except `t1`, should return True, meanin... | It's very easy:
```
not all(t1)
```
returns `False` only if all values in `t1` are non-empty/nonzero and not `None`. `all` short-circuits, so it only has to check the elements up to the first empty one, which makes it very fast. |
Python String argument without an encoding | 31,161,243 | 5 | 2015-07-01T12:24:56Z | 31,161,384 | 8 | 2015-07-01T12:30:04Z | [
"python",
"python-3.x",
"python-unicode"
] | Am trying to a run this piece of code, and it keeps giving an error saying "String argument without an encoding"
```
ota_packet = ota_packet.encode('utf-8') + bytearray(content[current_pos:(final_pos)]) + '\0'.encode('utf-8')
```
Any help? | You are passing in a string object to a `bytearray()`:
```
bytearray(content[current_pos:(final_pos)])
```
You'll need to supply an encoding argument (second argument) so that it can be encoded to bytes.
For example, you could encode it to UTF-8:
```
bytearray(content[current_pos:(final_pos)], 'utf8')
```
From the... |
Creating Probability/Frequency Axis Grid (Irregularly Spaced) with Matplotlib | 31,168,051 | 5 | 2015-07-01T17:35:12Z | 31,170,170 | 9 | 2015-07-01T19:36:56Z | [
"python",
"matplotlib",
"plot",
"probability"
] | I'm trying to create a frequency curve plot, and I'm having trouble manipulating the axis to get the plot I want.
Here is an example of the desired grid/plot I am trying to create:

Here is what I have managed to create with matplotlib:
![Current Matplot... | You can define a custom scale for the x-axis, which you can use instead of 'log'. Unfortunately, it's complicated and you'll need to figure out a function that lets you transform the numbers you give for the x-axis into something more linear. See <http://matplotlib.org/examples/api/custom_scale_example.html>.
Edit to ... |
How to send an array using requests.post (Python)? "Value Error: Too many values to unpack" | 31,168,819 | 11 | 2015-07-01T18:20:59Z | 35,535,240 | 14 | 2016-02-21T11:00:56Z | [
"python",
"api",
"python-requests"
] | I'm trying to send an array(list) of requests to the WheniWork API using requests.post, and I keep getting one of two errors. When I send the list as a list, I get an unpacking error, and when I send it as a string, I get an error asking me to submit an array. I think it has something to do with how requests handles li... | You want to pass in *JSON encoded* data. See the [API documentation](http://dev.wheniwork.com/):
> Remember â All post bodies must be JSON encoded data (no form data).
The `requests` library makes this trivially easy:
```
headers = {"W-Token": "Ilovemyboss"}
data = [
{
'url': '/rest/shifts',
'p... |
Django query annotation with boolean field | 31,169,108 | 10 | 2015-07-01T18:36:54Z | 31,186,546 | 12 | 2015-07-02T13:53:35Z | [
"python",
"django",
"orm",
"django-queryset"
] | Let's say I have a `Product` model with products in a storefront, and a `ProductImages` table with images of the product, which can have zero or more images. Here's a simplified example:
```
class Product(models.Model):
product_name = models.CharField(max_length=255)
# ...
class ProductImage(models.Model):
prod... | I eventually found a way to do this using django 1.8's new [conditional expressions](https://docs.djangoproject.com/en/1.8/ref/models/conditional-expressions/):
```
from django.db.models import Case, When, Value, IntegerField
q = (
Product.objects
.filter(...)
.annotate(image_count=Count('ima... |
pip install access denied on Windows | 31,172,719 | 9 | 2015-07-01T22:26:09Z | 32,885,745 | 12 | 2015-10-01T10:52:46Z | [
"python",
"windows",
"pip",
"access-denied"
] | I am trying to run `pip install mitmproxy` on Windows, but I keep getting access denied, even with `cmd` and `PowerShell` using the `Run as Administrator` option.
```
WindowsError: [Error 5] Access is denied: 'c:\\users\\bruno\\appdata\\local\\temp\\easy_install-0fme6u\\cryptography-0.9.1\\.eggs\\cffi-1.1.2-py2.7-win-... | In case of windows, in cmd try to run pip install using python executable
e.g.
```
python -m pip install mitmproxy
```
this should work, at least it worked for me for other package installation. |
getattr and setattr on nested objects? | 31,174,295 | 12 | 2015-07-02T01:29:42Z | 31,174,427 | 15 | 2015-07-02T01:49:55Z | [
"python",
"python-2.7",
"recursion",
"attributes",
"setattr"
] | this is probably a simple problem so hopefuly its easy for someone to point out my mistake or if this is even possible.
I have an object that has multiple objects as properties. I want to be able to dynamically set the properties of these objects like so:
```
class Person(object):
def __init__(self):
self... | You could use [`functools.reduce`](https://docs.python.org/3/library/functools.html#functools.reduce):
```
import functools
def rsetattr(obj, attr, val):
pre, _, post = attr.rpartition('.')
return setattr(rgetattr(obj, pre) if pre else obj, post, val)
sentinel = object()
def rgetattr(obj, attr, default=sent... |
How to avoid hard coding in if condition of python script | 31,174,387 | 3 | 2015-07-02T01:42:14Z | 31,174,457 | 7 | 2015-07-02T01:53:27Z | [
"python"
] | I am new to python. I have query regarding un-hardcoding object names(if condition) in python script.
I have fruit = [ Apple, Mango, Pineapple, Banana, Oranges]
and size = [ small, medium , big]
Currently I write code as below:
```
if (fruit == apple, size == small):
statement 1
statement 2
elif (fruit == apple... | You can create a map of values and functions. For example
```
MAP = {'apples':{'small':function1,
'large':function3},
'oranges':{'small':function2}}
#Then Run it like so:
fruit = 'apples'
size = 'large'
result = MAP[fruit][size]()
```
That will look up the function for you in the dictionary usin... |
RemovedInDjango19Warning: Model doesn't declare an explicit app_label | 31,179,459 | 6 | 2015-07-02T08:34:09Z | 31,180,171 | 9 | 2015-07-02T09:04:55Z | [
"python",
"django",
"django-signals",
"django-apps",
"deprecation-warning"
] | Have gone through
[Django 1.9 deprecation warnings app\_label](http://stackoverflow.com/questions/29635765/django-1-9-deprecation-warnings-app-label)
but answers couldn't fix my problem, so asking again.
I have an app that is added to INSTALLED\_APPS in settings.
when ever I run `manage.py runserver`, I get this wa... | You are importing **models.py** before app configuration run.
To fix it, you could import and configure signals in `CatalogConfig.ready` method.
like this:
**signals.py**
```
def someSignal(sender, **kwargs):
pass
```
**apps.py**
```
from django.apps import AppConfig
from django.db.models.signals import post_... |
How to import all the environment variables in tox | 31,192,106 | 14 | 2015-07-02T18:33:16Z | 32,252,679 | 12 | 2015-08-27T14:51:19Z | [
"python",
"virtualenv",
"setenv",
"tox"
] | I'm using following in setenv to import the environment variable from where I run, but is there a way to import all the variables so that I don't really need to import one by one.
e.g:
{env:TEMPEST\_CONFIG:} and {env:TEMPEST\_CONFIG\_DIR:} used to import these 2 variables.
```
[testenv:nosetests]
setenv =
TEMPEST... | You can use [passenv](https://testrun.org/tox/latest/config.html#confval-passenv=SPACE-SEPARATED-GLOBNAMES). If you pass the catch all wildcard `*` you have access to all environment variables from the parent environment:
> passenv=SPACE-SEPARATED-GLOBNAMES
>
> *New in version 2.0.*
>
> A list of wildcard environment ... |
ipdb debugger, step out of cycle | 31,196,818 | 3 | 2015-07-03T00:40:59Z | 32,097,568 | 7 | 2015-08-19T13:54:08Z | [
"python",
"debugging",
"ipdb"
] | Is there a command to step out of cycles (say, for or while) while debugging on ipdb without having to use breakpoints out of them?
I use the `until` command to step out of list comprehensions, but don't know how could I do a similar thing, if possible, of entire loop blocks. | You can use `j <line number> (jump)` to go to another line.
for example, `j 28` to go to line 28. |
Abstract base class is not enforcing function implementation | 31,201,706 | 4 | 2015-07-03T08:05:53Z | 31,201,830 | 7 | 2015-07-03T08:13:12Z | [
"python",
"python-3.x",
"abstract-class",
"python-3.4"
] | ```
from abc import abstractmethod, ABCMeta
class AbstractBase(object):
__metaclass__ = ABCMeta
@abstractmethod
def must_implement_this_method(self):
raise NotImplementedError()
class ConcreteClass(AbstractBase):
def extra_function(self):
print('hello')
# def must_implement_this_method(sel... | **The syntax** for the declaration of *metaclasses* **has changed in Python 3**. Instead of the `__metaclass__` field, **Python 3 uses a *keyword argument*** in the *base-class list*:
```
import abc
class AbstractBase(metaclass=abc.ABCMeta):
@abc.abstractmethod
def must_implement_this_method(self):
ra... |
Append differing number of characters to strings in list of strings | 31,213,520 | 3 | 2015-07-03T19:59:05Z | 31,213,598 | 7 | 2015-07-03T20:06:06Z | [
"python"
] | Let's say I have a list of strings:
```
strs = ["aa", "bbb", "c", "dddd"]
```
I want to append spaces to the end of each string so that each string is 4 characters long. That is, I want the end product to look like this:
```
strs_final = ["aa ", "bbb ", "c ", "dddd"]
```
I think list comprehension is the way to ... | Another solution is to use [str.ljust](https://docs.python.org/3/library/stdtypes.html#str.ljust)
```
[i.ljust(4) for i in strs]
``` |
What happen to a list when passed to a function? | 31,213,869 | 4 | 2015-07-03T20:32:19Z | 31,213,937 | 7 | 2015-07-03T20:38:06Z | [
"python",
"list",
"function"
] | I'm trying to understand how a list is treated when passed as an argument to a function. So what I did was the following:
I initialized a list:
```
ll = [1,2,3,4]
```
and define a function:
```
def Foo(ar):
ar += [11]
```
I passed the list to the function:
```
Foo(ll)
```
and when I print it I got:
```
prin... | `ar += [11]` is **not** just an assignment. It's a method call (the method called is: `__iadd__`). when Python executes that line it calls the method and then assigns `ar` to the result. The `__iadd__` method of `list` *modifies* the current `list`.
`ar = [11]` is an *assignment* and hence it simply changes the value ... |
How to match both multi line and single line | 31,215,512 | 3 | 2015-07-04T00:04:34Z | 31,215,541 | 9 | 2015-07-04T00:10:16Z | [
"python",
"regex",
"python-2.7"
] | Iâm trying to get my head around some Regex (using Python 2.7) and have hit a confusing snag. Itâs to do with the (.\*) . I know that dot matches everything except for new line unless you use the tag re.DOTALL. But when I do use the tag, it includes too much. Here is the code with a few variations and results that ... | > But when I do use the tag, it includes too much.
`*` is a [**greedy**](http://www.rexegg.com/regex-greed.html) operator meaning it will match as much as it can and still allow the remainder of the regular expression to match. You need to follow the `*` operator with `?` for a non-greedy match which means "zero or mo... |
Unexpected output from list(generator) | 31,218,826 | 20 | 2015-07-04T08:55:53Z | 31,218,896 | 15 | 2015-07-04T09:03:31Z | [
"python",
"python-2.7",
"list-comprehension",
"generator-expression"
] | I have a list and a `lambda` function defined as
```
In [1]: i = lambda x: a[x]
In [2]: alist = [(1, 2), (3, 4)]
```
Then I try two different methods to calculate a simple sum
First method.
```
In [3]: [i(0) + i(1) for a in alist]
Out[3]: [3, 7]
```
Second method.
```
In [4]: list(i(0) + i(1) for a in alist)
Out[... | This behaviour has been fixed in python 3. When you use a list comprehension `[i(0) + i(1) for a in alist]` you will define `a` in its surrounding scope which is accessible for `i`. In a new session `list(i(0) + i(1) for a in alist)` will throw error.
```
>>> i = lambda x: a[x]
>>> alist = [(1, 2), (3, 4)]
>>> list(i(... |
Scrapy - No module named mail.smtp | 31,219,359 | 9 | 2015-07-04T10:05:56Z | 31,664,739 | 18 | 2015-07-27T23:01:04Z | [
"python",
"scrapy"
] | System: Ubuntu 14.04
I installed scrapy using the command `sudo pip install scrapy`.
I am following the tutorial located [here](http://doc.scrapy.org/en/1.0/intro/tutorial.html).
When I run the command `scrapy crawl dmoz` at [this](http://doc.scrapy.org/en/1.0/intro/tutorial.html#crawling) step, I get the following ... | I had same problem.
installing twisted solved the problem.
```
sudo apt-get install python-twisted
``` |
Error 400 with python-amazon-simple-product-api via pythonanywhere | 31,223,301 | 4 | 2015-07-04T17:21:28Z | 31,274,244 | 8 | 2015-07-07T16:23:05Z | [
"python",
"django",
"amazon-web-services",
"pythonanywhere"
] | I've been at this for the better part of a day but have been coming up with the same Error 400 for quite some time. Basically, the application's goal is to parse a book's ISBN from the Amazon referral url and use it as the reference key to pull images from Amazon's Product Advertising API. The webpage is written in Pyt... | You still haven't authorised your account for API access. To do so, you can go to <https://affiliate-program.amazon.com/gp/advertising/api/registration/pipeline.html> |
Non time-specific once a day crontab? | 31,223,817 | 3 | 2015-07-04T18:18:16Z | 31,223,841 | 7 | 2015-07-04T18:20:48Z | [
"python",
"cron",
"scheduled-tasks",
"crontab",
"cron-task"
] | I have a python script, and I wish to run it once and only once everyday.
I did some research on the `crontab` command, and it seems to do so, but at a fixed time each day.
The issue is that my computer won't be on all day and a specific time for running it is just not possible. What can I do?
Could a log file help? I... | Install [`anacron`](https://en.wikipedia.org/wiki/Anacron), a `cron` scheduler that'll handle tasks that run at most once a day when your computer is powered on.
From the WikiPedia page:
> anacron is a computer program that performs periodic command scheduling which is traditionally done by cron, but without assuming... |
python regex not detecting square brackets | 31,225,304 | 3 | 2015-07-04T21:37:43Z | 31,225,325 | 10 | 2015-07-04T21:40:50Z | [
"python",
"regex"
] | I have a scenario where I want to remove all special characters except spaces from given content and I am working with Python and I was using this regex
```
re.sub(r"[^a-zA-z0-9 ]+","",content)
```
Itt was removing all special characters but was not removing square brackets `[ ]` and I just don't know why this happen... | You have a lowercase `z` where it should be upppercase. Change:
```
re.sub(r"[^a-zA-z0-9 ]+","",content)
```
to:
```
re.sub(r"[^a-zA-Z0-9 ]+","",content)
```
---
For the record, the range `'A-z'` expanded to the characters `A...Z`, `[`, `\`, `]`, `^`, `_`, ``` `` ```, `a...z`; that's why your regex was removing ev... |
Bokeh hover tooltip not displaying all data - Ipython notebook | 31,226,119 | 2 | 2015-07-05T00:05:27Z | 31,234,792 | 7 | 2015-07-05T20:39:11Z | [
"python",
"pandas",
"ipython-notebook",
"bokeh"
] | I am experimenting with Bokeh and mixing pieces of code. I created the graph below from a Pandas DataFrame, which displays the graph correctly with all the tool elements I want. However, the tooltip is partially displaying the data.
Here is the graph:

H... | Try using [`ColumnDataSource`](http://bokeh.pydata.org/en/latest/docs/reference/models.html#bokeh.models.sources.ColumnDataSource).
Hover tool needs to have access to the data source so that it can display info.
`@x`, `@y` are the x-y values in data unit. (`@` prefix is special, can only followed by a limited set of v... |
What is the difference between "range(0,2)" and "list(range(0,2))"? | 31,227,536 | 14 | 2015-07-05T05:53:36Z | 31,227,566 | 10 | 2015-07-05T06:00:02Z | [
"python",
"python-2.7",
"python-3.x"
] | Need to understand the difference between `range(0,2)` and `list(range(0,2))`, using python2.7
Both return a list so what exactly is the difference? | It depends on what version of Python you are using.
In Python 2.x, [`range()`](https://docs.python.org/2/library/functions.html#range) returns a list, so they are equivalent.
In Python 3.x, [`range()`](https://docs.python.org/3/library/functions.html#func-range) returns an immutable sequence type, you need `list(rang... |
What is the difference between "range(0,2)" and "list(range(0,2))"? | 31,227,536 | 14 | 2015-07-05T05:53:36Z | 31,227,578 | 27 | 2015-07-05T06:02:50Z | [
"python",
"python-2.7",
"python-3.x"
] | Need to understand the difference between `range(0,2)` and `list(range(0,2))`, using python2.7
Both return a list so what exactly is the difference? | In Python 3.x ,
`range(0,3)` returns a class of immutable iterable objects that lets you iterate over them, it does not produce lists, and they do not store all the elements in the range in memory, instead they produce the elements on the fly (as you are iterating over them) , whereas `list(range(0,3))` produces a lis... |
Queue vs JoinableQueue in Python | 31,230,241 | 4 | 2015-07-05T12:16:54Z | 31,230,329 | 8 | 2015-07-05T12:27:41Z | [
"python",
"queue",
"multiprocessing"
] | In Python while using multiprocessing module there are 2 kinds of queues:
* Queue
* JoinableQueue.
What is the difference between them?
# Queue
```
from multiprocessing import Queue
q = Queue()
q.put(item) # Put an item on the queue
item = q.get() # Get an item from the queue
```
# JoinableQueue
```
from multipro... | [`JoinableQueue`](https://docs.python.org/2/library/multiprocessing.html#multiprocessing.JoinableQueue) has methods `join()` and `task_done()`, which [`Queue`](https://docs.python.org/2/library/multiprocessing.html#multiprocessing.Queue) hasn't.
---
> **class multiprocessing.Queue( [maxsize] )**
>
> Returns a process... |
incorrect answers for quadratic equations | 31,232,563 | 5 | 2015-07-05T16:33:08Z | 31,232,584 | 9 | 2015-07-05T16:34:57Z | [
"python"
] | I was wondering if anyone could tell me why my python code for solving quadratic equations isn't working. I have looked through it and haven't found any errors.
```
print("This program will solve quadratic equations for you")
print("It uses the system 'ax**2 + bx + c'")
print("a, b and c are all numbers with or with... | Your trouble is in the part that tries to do the quadratic formula:
```
(-b+(((b**2)-(4*a* c))* * 0.5)/2*a)
```
The trouble is that `*` has the same precedence as `/` so you're dividing by 2 and then multiplying by `a`. Also your parentheses are off, so I reduced the unnecessary ones and moved the wrong ones. In shor... |
scrapy crawler caught exception reading instance data | 31,232,681 | 9 | 2015-07-05T16:44:30Z | 31,233,576 | 24 | 2015-07-05T18:24:32Z | [
"python",
"web-crawler",
"scrapy"
] | I am new to python and want to use scrapy to build a web crawler. I go through the tutorial in <http://blog.siliconstraits.vn/building-web-crawler-scrapy/>. Spider code likes following:
```
from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector
from nettuts.items impo... | in the settings.py file: add following code settings:
DOWNLOAD\_HANDLERS = {'s3': None,} |
Nested for-loops and dictionaries in finding value occurrence in string | 31,233,859 | 10 | 2015-07-05T18:54:27Z | 31,233,886 | 7 | 2015-07-05T18:57:13Z | [
"python",
"dictionary"
] | I've been tasked with creating a dictionary whose keys are elements found in a string and whose values count the number of occurrences per value.
Ex.
```
"abracadabra" â {'r': 2, 'd': 1, 'c': 1, 'b': 2, 'a': 5}
```
I have the for-loop logic behind it here:
```
xs = "hshhsf"
xsUnique = "".join(set(xs))
occurrence... | The *easiest* way is to use a Counter:
```
>>> from collections import Counter
>>> Counter("abracadabra")
Counter({'a': 5, 'r': 2, 'b': 2, 'c': 1, 'd': 1})
```
If you can't use a Python library, you can use [dict.get](https://docs.python.org/2/library/stdtypes.html#dict.get) with a default value of `0` to make your o... |
What's the difference between select_related and prefetch_related in Django ORM? | 31,237,042 | 41 | 2015-07-06T02:31:40Z | 31,237,071 | 79 | 2015-07-06T02:37:52Z | [
"python",
"django",
"django-models"
] | In Django doc,
> select\_related() âfollowâ foreign-key relationships, selecting additional related-object data when it executes its query.
>
> prefetch\_related() does a separate lookup for each relationship, and does the âjoiningâ in Python.
What does it mean by "doing the joining in python"? Can someone il... | Your understanding is mostly correct. You use `select_related` when the object that you're going to be selecting is a single object, so `OneToOneField` or a `ForeignKey`. You use `prefetch_related` when you're going to get a "set" of things, so `ManyToManyField`s as you stated or reverse `ForeignKey`s. Just to clarify ... |
How to protect my python code when a user inputs a string instead of an integer? | 31,240,305 | 2 | 2015-07-06T07:45:41Z | 31,240,381 | 7 | 2015-07-06T07:49:45Z | [
"python",
"python-3.x"
] | I would like to protect the python calculator I have created from crashing when a user inputs a string instead of an integer.
I have tried doing so with an else statement printing "Invalid Input" (or something else I cant remember) when ever a user inputs a string instead of numbers.
I would also like to know if ther... | you can use something like this for input
```
while True:
try:
num1 = int(input("Enter first number: "))
except ValueError:
continue
else:
break
``` |
How to throw exception if script is run with Python 2? | 31,240,907 | 3 | 2015-07-06T08:21:04Z | 31,241,081 | 7 | 2015-07-06T08:29:56Z | [
"python",
"python-3.x"
] | I have a script that should only be run with Python 3. I want to give a nice error message saying that this script should not be run with python2 if a user tries to run it with Python 2.x
How do I do this? When I try checking the Python version, it still throws an error, as Python parses the whole file before executin... | You can write a wrapper start-script in which you only import your actual script and catch for syntax errors:
```
try:
import real_module
except SyntaxError:
print('You need to run this with Python 3')
```
Then, when `real_module.py` uses Python 3 syntax that would throw an exception when used with Python 3, ... |
How do I check if an iterator is actually an iterator container? | 31,245,310 | 6 | 2015-07-06T12:00:31Z | 31,245,371 | 8 | 2015-07-06T12:03:54Z | [
"python",
"python-3.x",
"generator"
] | I have a dummy example of an iterator container below (the real one reads a file too large to fit in memory):
```
class DummyIterator:
def __init__(self, max_value):
self.max_value = max_value
def __iter__(self):
for i in range(self.max_value):
yield i
def regular_dummy_iterator(m... | First of all: There is no such thing as a *iterator container*. You have an *iterable*.
An iterable produces an iterator. Any iterator is also an iterable, but produces *itself* as the iterator:
```
>>> list_iter = iter([])
>>> iter(list_iter) is list_iter
True
```
You don't have an iterator if the `iter(ob) is ob` ... |
Python, Pandas : write content of DataFrame into text File | 31,247,198 | 7 | 2015-07-06T13:30:05Z | 31,247,247 | 9 | 2015-07-06T13:33:07Z | [
"python",
"file",
"pandas"
] | I have pandas DataFrame like this
```
X Y Z Value
0 18 55 1 70
1 18 55 2 67
2 18 57 2 75
3 18 58 1 35
4 19 54 2 70
```
I want to write this data to a text File in this way,
```
18 55 1 70
18 55 2 67
18 57 2 75
18 58 ... | You can just use [`np.savetxt`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.savetxt.html) and access the np attribute `.values`:
```
np.savetxt(r'c:\data\np.txt', df.values, fmt='%d')
```
yields:
```
18 55 1 70
18 55 2 67
18 57 2 75
18 58 1 35
19 54 2 70
```
or [`to_csv`](http://pandas.pydata.org/pand... |
Most efficient way to recode these multiple if statements | 31,249,422 | 2 | 2015-07-06T15:12:35Z | 31,249,603 | 7 | 2015-07-06T15:20:30Z | [
"python",
"python-2.7",
"if-statement"
] | I know this is a ridiculous example, but I'm looking for a more efficient way to write this code. Each project gets different values added to it depending on what state it takes place in. This is just a small snippet. I could potentially want to extend this out for all 50 states, which would be a lot of if statements. ... | Using a dictionary mapping:
```
for project in Projects:
project[2:4] = {
'CT': [project[0]+project[1], '222'],
'MA': ['123', None],
'ME': ['12323', '333'],
'RI': ['asdf', '3333']
}[project[1]]
```
removes all the `if`/`else`, and just deals with real data :)
As suggested by [... |
Node.js (npm) refuses to find python even after %PYTHON% has been set | 31,251,367 | 9 | 2015-07-06T16:48:16Z | 33,047,257 | 24 | 2015-10-09T21:15:31Z | [
"python",
"node.js",
"npm"
] | So I am trying to get the Node.js to work. Of course, it's not as easy as advertised :)
I happen to have two python versions on my computer, but Node.js seems to only work with the older one, 2.7. Upon error, it also encourages me to set the path into `PYTHON` environment variable with this error:
```
Error: Can't fi... | I figured out the most stable solution is to set `python` npm internal value to actual path:
```
npm config set python C:\Programs\Python2.7\python2.7.exe
```
This skips all environment variable and `%PATH%` crap and just starts the python wherever it's installed. |
Flask ImportError: No Module Named Flask | 31,252,791 | 6 | 2015-07-06T18:12:00Z | 31,253,927 | 15 | 2015-07-06T19:20:48Z | [
"python",
"flask"
] | I'm following the Flask tutorial here:
```
http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world
```
I get to the point where I try ./run.py and I get:
```
Traceback (most recent call last):
File "./run.py", line 3, in <module>
from app import app
File "/Users/benjaminclayman/Desktop... | try deleting the virtualenv you created.
create a new virtualenv
```
virtualenv flask
```
then
```
cd flask
```
let's activate the virtualenv
```
source bin/activate
```
now you should see (flask) on the left of the command line.
Let's install flask
```
pip install flask
```
Then create a file hello.py
```
fro... |
How do i reference values from various ranges within a list? | 31,253,312 | 3 | 2015-07-06T18:44:31Z | 31,253,327 | 7 | 2015-07-06T18:45:38Z | [
"python",
"list",
"slice"
] | What I want to do is reference several different ranges from within a list, i.e. I want the 4-6th elements, the 12 - 18th elements, etc. This was my initial attempt:
```
test = theList[4:7, 12:18]
```
Which I would expect to give do the same thing as:
```
test = theList[4,5,6,12,13,14,15,16,17]
```
But I got a synt... | You can add the two lists.
```
>>> theList = list(range(20))
>>> theList[4:7] + theList[12:18]
[4, 5, 6, 12, 13, 14, 15, 16, 17]
``` |
Why does numpy.linalg.solve() offer more precise matrix inversions than numpy.linalg.inv()? | 31,256,252 | 8 | 2015-07-06T21:49:02Z | 31,257,909 | 11 | 2015-07-07T00:31:31Z | [
"python",
"arrays",
"numpy",
"matrix",
"linear-algebra"
] | I do not quite understand why `numpy.linalg.solve()` gives the more precise answer, whereas `numpy.linalg.inv()` breaks down somewhat, giving (what I believe are) estimates.
For a concrete example, I am solving the equation `C^{-1} * d` where `C` denotes a matrix, and `d` is a vector-array. For the sake of discussion,... | `np.linalg.solve(A, b)` does *not* compute the inverse of *A*. Instead it calls one of the [`gesv` LAPACK routines](http://www.netlib.org/lapack/double/dgesv.f), which first factorizes *A* using LU decomposition, then solves for *x* using forward and backward substitution (see [here](https://en.wikipedia.org/wiki/LU_de... |
How do you perform basic joins of two RDD tables in Spark using Python? | 31,257,077 | 3 | 2015-07-06T22:55:35Z | 31,257,821 | 9 | 2015-07-07T00:20:57Z | [
"python",
"hadoop",
"join",
"apache-spark",
"pyspark"
] | How would you perform basic joins in Spark using python? In R you could use merg() to do this. What is the syntax using python on spark for:
1. Inner Join
2. Left Outer Join
3. Cross Join
With two tables (RDD) with a single column in each that has a common key.
```
RDD(1):(key,U)
RDD(2):(key,V)
```
I think an inner... | It can be done either using `PairRDDFunctions` or Spark Data Frames. Since data frame operations benefit from [Catalyst Optimizer](https://databricks.com/blog/2015/04/13/deep-dive-into-spark-sqls-catalyst-optimizer.html) the second option can worth considering.
Assuming your data looks as follows:
```
rdd1 = sc.para... |
Different behavior in python script and python idle? | 31,260,988 | 12 | 2015-07-07T06:07:27Z | 31,261,439 | 8 | 2015-07-07T06:38:09Z | [
"python",
"python-2.7",
"cpython"
] | In the python idle:
```
>>> a=1.1
>>> b=1.1
>>> a is b
False
```
But when I put the code in a script and run it, I will get a different result:
```
$cat t.py
a=1.1
b=1.1
print a is b
$python t.py
True
```
Why did this happen? I know that `is` compares the `id` of two objects, so why the ids of two objects are same/... | When Python executes a script file, the whole file is parsed first. You can notice that when you introduce a syntax error somewhere: Regardless of where it is, it will prevent any line from executing.
So since Python parses the file first, literals can be loaded effectively into the memory. Since Python knows that the... |
Different number of digits in PI | 31,263,763 | 3 | 2015-07-07T08:42:33Z | 31,263,897 | 11 | 2015-07-07T08:48:37Z | [
"python",
"variables",
"printing",
"pi"
] | I am a beginner in Python and I have a doubt regarding PI.
```
>>> import math
>>> p = math.pi
>>> print p
3.14159265359
>>> math.pi
3.141592653589793
```
* Why are the two having different number of digits ?
* How can I get the value of Pi up to more decimal places without using the Chudnovsky algorithm? | > Why are the two having different number of digits ?
One is 'calculated' with `__str__`, the other with `__repr__`:
```
>>> print repr(math.pi)
3.141592653589793
>>> print str(math.pi)
3.14159265359
```
`print` uses the return value of `__str__` of objects to determine what to print. Just doing `math.pi` uses `__re... |
Start a flask application in separate thread | 31,264,826 | 6 | 2015-07-07T09:30:33Z | 31,265,602 | 17 | 2015-07-07T10:06:04Z | [
"python",
"multithreading",
"flask"
] | I'm currently developping a Python application on which I want to see real-time statistics. I wanted to use `Flask` in order to make it easy to use and to understand.
My issue is that my Flask server should start at the very beginning of my python application and stop at the very end. It should look like that :
```
d... | You're running `Flask` in debug mode, which enables **the reloader** (reloads the Flask server when your code changes).
Flask can run just fine in a separate thread, but the reloader expects to run in the main thread.
---
To solve your issue, you should either disable debug (`app.debug = False`), or disable the relo... |
Remove list of indices from a list in Python | 31,267,493 | 4 | 2015-07-07T11:36:13Z | 31,267,522 | 8 | 2015-07-07T11:38:03Z | [
"python"
] | I have a list with points (centroids) and some of them have to be removed.
How can I do this without loops? I've tried [the answer given here](http://stackoverflow.com/a/627453/2071807) but this error is shown:
```
list indices must be integers, not list
```
My lists look like this:
```
centroids = [[320, 240], [40... | You can use [`enumerate`](https://docs.python.org/2/library/functions.html#enumerate) within a list comprehension :
```
>>> centroids = [[320, 240], [400, 200], [450, 600]]
>>> index = [0,2]
>>> [element for i,element in enumerate(centroids) if i not in index]
[[400, 200]]
```
Note that finally you have to loop over ... |
Applying uppercase to a column in pandas dataframe | 31,269,216 | 6 | 2015-07-07T12:59:54Z | 31,272,768 | 10 | 2015-07-07T15:20:47Z | [
"python",
"python-2.7",
"pandas"
] | I'm having trouble applying upper case to a column in my DataFrame.
dataframe is `df`.
`1/2 ID` is the column head that need to apply UPPERCASE.
The problem is that the values are made up of three letters and three numbers. For example `rrr123` is one of the values.
```
df['1/2 ID'] = map(str.upper, df['1/2 ID'])
`... | If your version of pandas is a recent version then you can just use the vectorised string method [`upper`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.upper.html#pandas.Series.str.upper):
```
df['1/2 ID'].str.upper()
``` |
How to add a favicon to a Pelican blog? | 31,270,373 | 5 | 2015-07-07T13:46:28Z | 31,270,471 | 7 | 2015-07-07T13:50:36Z | [
"python",
"favicon",
"pelican"
] | I am creating a static site with Pelican and I'm confused about how to add a favicon to it.
I've seen [in the documentation](http://docs.getpelican.com/en/3.6.0/tips.html?highlight=favicon#extra-tips) that:
> You can also use the `EXTRA_PATH_METADATA` mechanism to place a
> `favicon.ico` or `robots.txt` at the root o... | In [my `pelicanconf.py`](https://github.com/textbook/textbook.github.io-source/blob/master/pelicanconf.py#L45), I have:
```
STATIC_PATHS = [
'images',
'extra/robots.txt',
'extra/favicon.ico'
]
EXTRA_PATH_METADATA = {
'extra/robots.txt': {'path': 'robots.txt'},
'extra/favicon.ico': {'path': 'favic... |
pip install --upgrade sqlalchemy gives maximum recursion depth exceeded | 31,273,332 | 5 | 2015-07-07T15:43:37Z | 31,273,772 | 8 | 2015-07-07T16:02:42Z | [
"python",
"python-2.7",
"recursion",
"sqlalchemy",
"pip"
] | I've tried `pip install --upgrade sqlalchemy`, `python2.7 setup.py install`, and after deleting the sqlalchemy folder in site-packages, I've tried `pip install sqlalchemy`. They all give "RuntimeError: maximum recursion depth exceeded in cmp".
```
File "C:\Python27\lib\ntpath.py", line 200, in splitext
return generi... | Looks like my "distribute" (v0.6xxx) was out of date.
I ran
```
pip install --upgrade distribute
```
and it installed 0.7.3.
Then ran `pip install sqlalchemy` and it installed.
Same problem encountered installing other packages. |
Extracting Directory from Path with Ending Slash | 31,273,892 | 2 | 2015-07-07T16:07:18Z | 31,273,972 | 10 | 2015-07-07T16:11:15Z | [
"python"
] | What is an elegant way of extracting a directory from a path with an ending slash?
For example
`/foo/bar/test/`
and I want `test`.
I can do `os.path.basename` if there was no ending `/`.
Is my next best option to do something like:
```
if directory[:-1] == '/':
basename = os.path.basename(directory[:-1])
... | Calling `os.path.abspath` will take care of that for you:
```
>>> import os
>>> os.path.abspath('/foo/bar/test/')
'/foo/bar/test'
>>> os.path.abspath('/foo/bar/test')
'/foo/bar/test'
>>>
```
So:
```
>>> os.path.basename(os.path.abspath('/foo/bar/test/'))
'test'
``` |
Python - Reading Emoji Unicode Characters | 31,280,295 | 5 | 2015-07-07T22:16:25Z | 31,280,408 | 9 | 2015-07-07T22:25:00Z | [
"python",
"python-2.7",
"unicode",
"emoji"
] | I have a Python 2.7 program which reads iOS text messages from a SQLite database. The text messages are unicode strings. In the following text message:
```
u'that\u2019s \U0001f63b'
```
The apostrophe is represented by `\u2019`, but the emoji is represented by `\U0001f63b`. I looked up the code point for the emoji in... | I don't think you're using encode correctly, nor do you need to. What you have is a valid unicode string with one 4 digit and one 8 digit escape sequence. Try this in the REPL on, say, OS X
```
>>> s = u'that\u2019s \U0001f63b'
>>> print s
thatâs í ½í¸»
```
In python3, though -
```
Python 3.4.3 (default, Jul 7 20... |
How to limit one session from any browser for a username in flask? | 31,281,470 | 7 | 2015-07-08T00:08:01Z | 31,618,249 | 7 | 2015-07-24T19:21:45Z | [
"python",
"session",
"flask"
] | I am using a gunicorn server in which I am trying to figure out a way to limit only one session per username i.e. if user A is logged in to the app from Chrome he should not be able to login through Firefox unless he logs out of chrome, or shouldn`t be able to open another TAB in chrome itself.
How can I generate a un... | A possible method of limiting sessions to a single tab involves creating a random token on page load and embedding this token into the page. This most recently generated token gets stored in the user's session as well. This will be similar to how various frameworks add validation tokens to prevent [CSFR](https://en.wik... |
Strange... What does [::5,0] mean | 31,284,864 | 4 | 2015-07-08T06:15:50Z | 31,285,008 | 10 | 2015-07-08T06:25:57Z | [
"python",
"numpy",
"pandas",
"matplotlib"
] | I found a webpage which explaining how to use `set_xticks` and . `set_xticklabels`.
And they set `set_xticks` and 'set\_xticklabels' as following...
```
ax.set_xticks(xx[::5,0])
ax.set_xticklabels(times[::5])
ax.set_yticks(yy[0,::5])
ax.set_yticklabels(dates[::5])
```
What does `[::5,0]` exactly mean..
I don't have... | For a numpy array, the notation`[::5,6]` means to take the 6th column for that array and then in the 6th column, every 5th row starting at the first row till the last row.
Example -
```
In [12]: n = np.arange(100000)
In [17]: n.shape = (500,200)
In [18]: n[::1,2]
Out[18]:
array([ 2, 202, 402, 602, 802, 1... |
Logarithmic returns in pandas dataframe | 31,287,552 | 3 | 2015-07-08T08:38:51Z | 31,287,674 | 9 | 2015-07-08T08:44:29Z | [
"python",
"pandas"
] | Python pandas has a pct\_change function which I use to calculate the returns for stock prices in a dataframe:
```
ndf['Return']= ndf['TypicalPrice'].pct_change()
```
I am using the following code to get logarithmic returns, but it gives the exact same values as the pct.change() function:
```
ndf['retlog']=np.log(nd... | Here is one way to calculate log return using `.shift()`. And the result is similar to but not the same as the gross return calculated by `pct_change()`. Can you upload a copy of your sample data (dropbox share link) to reproduce the inconsistency you saw?
```
import pandas as pd
import numpy as np
np.random.seed(0)
... |
How to append a value to list attribute on AWS DynamoDB? | 31,288,085 | 4 | 2015-07-08T09:03:18Z | 35,051,660 | 8 | 2016-01-28T02:08:15Z | [
"python",
"amazon-web-services",
"amazon-dynamodb",
"boto"
] | I'm using DynamoDB as an K-V db (cause there's not much data, I think that's fine) , and part of 'V' is list type (about 10 elements). There's some session to append a new value to it, and I cannot find a way to do this in 1 request. What I did is like this:
```
item = self.list_table.get_item(**{'k': 'some_key'})
ite... | The following code should work with boto3:
```
table = get_dynamodb_resource().Table("table_name")
result = table.update_item(
Key={
'hash_key': hash_key,
'range_key': range_key
},
UpdateExpression="SET some_attr = list_append(some_attr, :i)",
ExpressionAttributeValues={
':i': [... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.