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 |
|---|---|---|---|---|---|---|---|---|---|
'is' operator behaves differently when comparing strings with spaces | 16,756,699 | 26 | 2013-05-26T06:09:39Z | 16,757,434 | 17 | 2013-05-26T08:22:09Z | [
"python",
"python-3.x",
"operators"
] | I've started learning Python (python 3.3) and I was trying out the `is` operator. I tried this:
```
>>> b = 'is it the space?'
>>> a = 'is it the space?'
>>> a is b
False
>>> c = 'isitthespace'
>>> d = 'isitthespace'
>>> c is d
True
>>> e = 'isitthespace?'
>>> f = 'isitthespace?'
>>> e is f
False
```
It seems like th... | *Warning: this answer is about the implementation details of a specific python interpreter. comparing strings with `is`==bad idea.*
Well, at least for cpython3.4/2.7.3, the answer is "no, it is not the whitespace". Not *only* the whitespace:
* Two string literals will share memory if they are either alphanumeric or r... |
OS X AppEngine - ImportError: No module named _sqlite3 | 16,757,013 | 3 | 2013-05-26T07:15:48Z | 16,898,123 | 8 | 2013-06-03T13:38:34Z | [
"python",
"google-app-engine"
] | UPDATE: This is a problem I am having with the 1.8.0 App Engine SDK on a fresh install of OS X 10.8.3.
First up - there's a bunch of questions on SO with a similar title. I've checked them out, and I don't believe they answer my question. Mostly they recommend getting libsqlite3-dev and rebuilding python to get \_sqli... | It looks like adding `'_sqlite3'` to the `_WHITE_LIST_C_MODULES` list at line 742 in sandbox.py (which lives at `/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/devappserver2/python` on my machine) has worked for me f... |
what is the default python logging formatter | 16,757,578 | 8 | 2013-05-26T08:41:49Z | 16,759,818 | 13 | 2013-05-26T13:42:45Z | [
"python",
"logging"
] | I'm trying to decipher the information contained in my logs (the logging setup is using the default formatter). The [documentation](http://docs.python.org/2/library/logging.html#logging.Formatter) states:
> Do formatting for a record - if a formatter is set, use it. Otherwise, use the default formatter for the module.... | The default format is located [here](http://hg.python.org/cpython/file/5c4ca109af1c/Lib/logging/__init__.py#l1640) which is:
```
BASIC_FORMAT = "%(levelname)s:%(name)s:%(message)s"
```
The [Format](http://hg.python.org/cpython/file/5c4ca109af1c/Lib/logging/__init__.py#l399) code will tell you how you can customize it... |
How to AES encrypt/decrypt files using Python/PyCrypto in an OpenSSL-compatible way? | 16,761,458 | 29 | 2013-05-26T16:47:41Z | 16,761,459 | 62 | 2013-05-26T16:47:41Z | [
"python",
"encryption",
"openssl",
"aes",
"pycrypto"
] | There are many ways to use AES, resulting in frequent incompatibilities between different implementations. OpenSSL provides a popular command line interface for AES encryption/decryption:
```
openssl aes-256-cbc -salt -in filename -out filename.enc
openssl aes-256-cbc -d -in filename.enc -out filename
```
This could ... | Given the popularity of Python, at first I was disappointed that there was no complete answer to this question to be found. It took me a fair amount of reading different answers on this board, as well as other resources, to get it right. I thought I might share the result for future reference and perhaps review; I'm by... |
How to AES encrypt/decrypt files using Python/PyCrypto in an OpenSSL-compatible way? | 16,761,458 | 29 | 2013-05-26T16:47:41Z | 20,457,519 | 15 | 2013-12-08T18:54:31Z | [
"python",
"encryption",
"openssl",
"aes",
"pycrypto"
] | There are many ways to use AES, resulting in frequent incompatibilities between different implementations. OpenSSL provides a popular command line interface for AES encryption/decryption:
```
openssl aes-256-cbc -salt -in filename -out filename.enc
openssl aes-256-cbc -d -in filename.enc -out filename
```
This could ... | I am re-posting your code with a couple of corrections (I didn't want to obscure your version). While your code works, it does not detect some errors around padding. In particular, if the decryption key provided is incorrect, your padding logic may do something odd. If you agree with my change, you may update your solu... |
How to AES encrypt/decrypt files using Python/PyCrypto in an OpenSSL-compatible way? | 16,761,458 | 29 | 2013-05-26T16:47:41Z | 21,708,946 | 8 | 2014-02-11T17:33:13Z | [
"python",
"encryption",
"openssl",
"aes",
"pycrypto"
] | There are many ways to use AES, resulting in frequent incompatibilities between different implementations. OpenSSL provides a popular command line interface for AES encryption/decryption:
```
openssl aes-256-cbc -salt -in filename -out filename.enc
openssl aes-256-cbc -d -in filename.enc -out filename
```
This could ... | The code below should be Python 3 compatible with the small changes documented in the code. Also wanted to use os.urandom instead of Crypto.Random. 'Salted\_\_' is replaced with salt\_header that can be tailored or left empty if needed.
```
from os import urandom
from hashlib import md5
from Crypto.Cipher import AES
... |
How to properly iterate with re.sub() in Python | 16,761,652 | 7 | 2013-05-26T17:09:05Z | 16,761,684 | 10 | 2013-05-26T17:12:11Z | [
"python",
"regex"
] | I want to make a Python script that creates footnotes. The idea is to find all strings of the sort `"Some body text.{^}{Some footnote text.}"` and replace them with `"Some body text.^#"`, where `"^#"` is the proper footnote number. (A different part of my script deals with actually printing out the footnotes at the bot... | Any callable can be used, so you could use a class to track the numbering:
```
class FootnoteNumbers(object):
def __init__(self, start=1):
self.count = start - 1
def __call__(self, match):
self.count += 1
return "<sup>{}</sup>".format(self.count)
new_body_text = re.sub(pattern, Footn... |
lambda functions and list of functions in Python | 16,763,495 | 2 | 2013-05-26T20:39:27Z | 16,763,536 | 10 | 2013-05-26T20:44:24Z | [
"python",
"lambda"
] | I have an array of functions, for example:
```
>>> def f():
... print "f"
...
>>> def g():
... print "g"
...
>>> c=[f,g]
```
Then i try to create two lambda functions:
```
>>> i=0
>>> x=lambda: c[i]()
>>> i+=1
>>> y=lambda: c[i]()
```
And then, call them:
```
>>> x()
g
>>> y()
g
```
Why c[i] in lambda a... | That's because the lambda function is fetching the value of the global variable `i` at runtime:
```
>>> i = 0
>>> x=lambda z = i : c[z]() #assign the current value of `i` to a local variable inside lambda
>>> i+=1
>>> y =lambda z = i : c[z]()
>>> x()
f
>>> y()
g
```
A must read:
[What do (lambda) function closures ca... |
How to save a image file on a Postgres database? | 16,763,904 | 5 | 2013-05-26T21:38:08Z | 16,764,874 | 16 | 2013-05-27T00:11:49Z | [
"python",
"database",
"image",
"postgresql",
"bytea"
] | For learning purposes, I'm creating a site using Python+Flask. I want to recover an image from database and show it on screen. But one step at a time.
I have no idea how to save an image in my database in the first place. My searches only revealed that I have to use a `bytea` type in my database. Then I get my image a... | I don't normally write complete example programs for people, but you didn't demand it and it's a pretty simple one, so here you go:
```
#!/usr/bin/env python3
import os
import sys
import psycopg2
import argparse
db_conn_str = "dbname=regress user=craig"
create_table_stm = """
CREATE TABLE files (
id serial prim... |
"None" keeps showing up when I run my program | 16,764,247 | 2 | 2013-05-26T22:24:20Z | 16,764,262 | 9 | 2013-05-26T22:26:14Z | [
"python"
] | Whenever I run the calculator program I created, it works fine but the text "None" keeps showing up and I don't know why. Here's the code:
```
def add():
print 'choose 2 numbers to add'
a=input('add this')
b=input('to this')
print a+b
return menu()
def sub():
print 'choose 2 numbers to subract'... | That's because the function `menu()` is not returning anything, by default a function in python returns `None`
```
>>> def func():pass
>>> print func() #use `print` only if you want to print the returned value
None
```
Just use:
```
menu() #no need of print as you're already printing inside the function body.
```
... |
Convert Date String to Day of Week | 16,766,643 | 14 | 2013-05-27T05:11:35Z | 16,766,724 | 12 | 2013-05-27T05:21:12Z | [
"python",
"datetime"
] | I have date strings like this:
```
'January 11, 2010'
```
and I need a function that returns the day of the week, like
```
'mon', or 'monday'
```
etc.
I can't find this anywhere in the Python help.
Anyone? Thanks. | use `date.weekday()`
Return the day of the week as an integer, where Monday is 0 and Sunday is 6.
<http://docs.python.org/2/library/datetime.html#datetime.date.weekday> |
Convert Date String to Day of Week | 16,766,643 | 14 | 2013-05-27T05:11:35Z | 16,766,750 | 29 | 2013-05-27T05:23:29Z | [
"python",
"datetime"
] | I have date strings like this:
```
'January 11, 2010'
```
and I need a function that returns the day of the week, like
```
'mon', or 'monday'
```
etc.
I can't find this anywhere in the Python help.
Anyone? Thanks. | You might want to use [`strptime and strftime`](http://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior) methods from [`datetime`](http://docs.python.org/2/library/datetime.html):
```
>>> import datetime
>>> datetime.datetime.strptime('January 11, 2010', '%B %d, %Y').strftime('%A')
'Monday'
```
... |
Understanding Popen.communicate | 16,768,290 | 26 | 2013-05-27T07:26:54Z | 16,769,956 | 11 | 2013-05-27T09:17:38Z | [
"python",
"subprocess",
"communicate"
] | I have a script named `1st.py` which creates a REPL (read-eval-print-loop):
```
print "Something to print"
while True:
r = raw_input()
if r == 'n':
print "exiting"
break
else:
print "continuing"
```
I then launched `1st.py` with the following code:
```
p = subprocess.Popen(["pytho... | Do not use communicate(input=""). It writes input to the process, closes its stdin and then reads all output.
Do it like this:
```
p=subprocess.Popen(["python","1st.py"],stdin=PIPE,stdout=PIPE)
# get output from process "Something to print"
one_line_output = p.stdout.readline()
# write 'a line\n' to the process
p.s... |
Understanding Popen.communicate | 16,768,290 | 26 | 2013-05-27T07:26:54Z | 16,770,371 | 25 | 2013-05-27T09:40:37Z | [
"python",
"subprocess",
"communicate"
] | I have a script named `1st.py` which creates a REPL (read-eval-print-loop):
```
print "Something to print"
while True:
r = raw_input()
if r == 'n':
print "exiting"
break
else:
print "continuing"
```
I then launched `1st.py` with the following code:
```
p = subprocess.Popen(["pytho... | `.communicate()` writes input (there is no input in this case so it just closes subprocess' stdin to indicate to the subprocess that there is no more input), reads all output, and waits for the subprocess to exit.
The exception EOFError is raised in the child process by `raw_input()` (it expected data but got EOF (no ... |
Does Python have a toString() equivalent, and can I convert a db.Model element to String? | 16,768,302 | 12 | 2013-05-27T07:27:39Z | 16,768,514 | 27 | 2013-05-27T07:41:07Z | [
"python",
"google-app-engine",
"django-templates"
] | I'm writing a ToDo list app to help myself get started with Python. The app is running on GAE and I'm storing todo items in the Data Store. I want to display everyone's items to them, and them alone. The problem is that the app currently displays all items to all users, so I can see what you write, and you see what I w... | In python, the [`str()` method](http://docs.python.org/2/library/functions.html#str) is similar to the `toString()` method in other languages. It is called passing the object to convert to a string as a parameter. Internally it calls the `__str__()` method of the parameter object to get its string representation.
In t... |
Remove space from print output - Python 3 | 16,768,979 | 2 | 2013-05-27T08:16:57Z | 16,769,010 | 8 | 2013-05-27T08:18:42Z | [
"python",
"python-3.x"
] | I have this..
```
the_tuple = (1,2,3,4,5)
print ('\"',the_tuple[1],'\"')
```
showing
```
" 2 "
```
How can I get the output to show `"2"`? | Use:
```
print ('\"',the_tuple[1],'\"', sep='')
^^^^^^
```
Note that those escapes are completely unnecessary:
```
print ('"', the_tuple[1], '"', sep='')
```
Or even better, use string formatting:
```
print ('"{}"'.format(the_tuple[1]))
``` |
Cython, Python and KeyboardInterrupt ignored | 16,769,870 | 8 | 2013-05-27T09:12:53Z | 16,778,026 | 10 | 2013-05-27T17:36:13Z | [
"python",
"cython",
"keyboardinterrupt"
] | Is there a way to interrupt (`Ctrl+C`) a Python script based on a loop that is embedded in a Cython extension?
I have the following python script:
```
def main():
# Intantiate simulator
sim = PySimulator()
sim.Run()
if __name__ == "__main__":
# Try to deal with Ctrl+C to abort the running simulation... | You have to periodically check for pending signals, for example, on every Nth iteration of the simulation loop:
```
from cpython.exc cimport PyErr_CheckSignals
cdef Run(self):
while True:
# do some work
PyErr_CheckSignals()
```
`PyErr_CheckSignals` will run signal handlers installed with [signal]... |
Why are there multiple release versions of python | 16,771,409 | 10 | 2013-05-27T10:43:13Z | 16,771,551 | 10 | 2013-05-27T10:52:18Z | [
"python"
] | At present(May 2013), there are three release versions, all released on may 15
* python 3.3.2
* python 3.2.5
* python 2.7.5
I can understand the need for 2.x and 3.x branches but why are there seperate 3.3.x and 3.2.x versions? | In [this](http://www.python.org/download/) link is says `The current production versions are 2.7.5 and 3.3.2.`.
And if you look [here](http://www.python.org/download/releases/3.2.5/) it says:
> Python 3.2.5 was released on May 15th, 2013. This release fixes a few regressions found in Python 3.2.4, and is planned to b... |
python NameError: global name '__file__' is not defined | 16,771,894 | 26 | 2013-05-27T11:11:59Z | 20,510,502 | 25 | 2013-12-11T04:27:35Z | [
"python",
"nameerror"
] | When I run this code by python 2.7,I got this error.please help me,thank you very much!
```
Traceback (most recent call last):
File "C:\Python26\Lib\site-packages\pyutilib.subprocess-3.5.4\setup.py", line 30, in <module>
long_description = read('README.txt'),
File "C:\Python26\Lib\site-packages\pyutilib.subproce... | This error comes when you append this line `os.path.join(os.path.dirname(__file__))` in python interactive shell.
`Python Shell` doesn't detect current file path in `__file__` and it's related to your `filepath` in which you added this line
So you should write this line `os.path.join(os.path.dirname(__file__))` in `f... |
python NameError: global name '__file__' is not defined | 16,771,894 | 26 | 2013-05-27T11:11:59Z | 23,104,021 | 37 | 2014-04-16T08:32:28Z | [
"python",
"nameerror"
] | When I run this code by python 2.7,I got this error.please help me,thank you very much!
```
Traceback (most recent call last):
File "C:\Python26\Lib\site-packages\pyutilib.subprocess-3.5.4\setup.py", line 30, in <module>
long_description = read('README.txt'),
File "C:\Python26\Lib\site-packages\pyutilib.subproce... | I solved it by treating file as a string, i.e. put `"__file__"` (together with the quotes!) instead of `__file__`
This works fine for me:
```
wk_dir = os.path.dirname(os.path.realpath('__file__'))
``` |
sort dict by value python | 16,772,071 | 33 | 2013-05-27T11:22:14Z | 16,772,088 | 73 | 2013-05-27T11:23:16Z | [
"python",
"dictionary",
"python-2.6"
] | Assume that I have a dict.
```
data = {1:'b', 2:'a'}
```
And I want to sort data by 'b' and 'a' so I get the result
```
'a','b'
```
How do I do that?
Any ideas? | To get the values use
```
sorted(data.values())
```
To get the matching keys, use a `key` function
```
sorted(data, key=data.get)
```
To get a list of tuples ordered by value
```
sorted(data.items(), key=lambda x:x[1])
``` |
sort dict by value python | 16,772,071 | 33 | 2013-05-27T11:22:14Z | 16,772,651 | 19 | 2013-05-27T11:53:33Z | [
"python",
"dictionary",
"python-2.6"
] | Assume that I have a dict.
```
data = {1:'b', 2:'a'}
```
And I want to sort data by 'b' and 'a' so I get the result
```
'a','b'
```
How do I do that?
Any ideas? | If you actually want to sort the dictionary instead of just obtaining a sorted list use [`collections.OrderedDict`](http://docs.python.org/2/library/collections.html#collections.OrderedDict)
```
>>> from collections import OrderedDict
>>> from operator import itemgetter
>>> data = {1: 'b', 2: 'a'}
>>> d = OrderedDict(... |
sort dict by value python | 16,772,071 | 33 | 2013-05-27T11:22:14Z | 16,773,365 | 11 | 2013-05-27T12:35:48Z | [
"python",
"dictionary",
"python-2.6"
] | Assume that I have a dict.
```
data = {1:'b', 2:'a'}
```
And I want to sort data by 'b' and 'a' so I get the result
```
'a','b'
```
How do I do that?
Any ideas? | From your comment to gnibbler answer, i'd say you want a list of pairs of key-value sorted by value:
```
sorted(data.items(), key=lambda x:x[1])
``` |
How to use socket in Python as a context manager? | 16,772,465 | 26 | 2013-05-27T11:43:35Z | 16,772,515 | 18 | 2013-05-27T11:45:59Z | [
"python",
"sockets",
"contextmanager"
] | It seems like it would be only natural to do something like:
```
with socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
```
but Python doesn't implement a context manager for socket. Can I easily use it as a context manager, and if so, how? | The socket module is just a wrapper around the BSD socket interface. It's low-level, and does not really attempt to provide you with a handy or easy to use Pythonic API. You may want to use something higher-level.
That said, it does in fact implement a context manager:
```
>>> with socket.socket() as s:
... print(s... |
How to use socket in Python as a context manager? | 16,772,465 | 26 | 2013-05-27T11:43:35Z | 16,772,520 | 44 | 2013-05-27T11:46:19Z | [
"python",
"sockets",
"contextmanager"
] | It seems like it would be only natural to do something like:
```
with socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
```
but Python doesn't implement a context manager for socket. Can I easily use it as a context manager, and if so, how? | The `sockets` module is fairly low-level, giving you almost direct access to the C library functionality.
You can always use the [`contextlib.contextmanager` decorator](http://docs.python.org/2/library/contextlib.html#contextlib.contextmanager) to build your own:
```
from contextlib import contextmanager
@contextman... |
Why is the 'running' of .pyc files not faster compared to .py files? | 16,773,362 | 8 | 2013-05-27T12:35:31Z | 16,773,381 | 13 | 2013-05-27T12:37:14Z | [
"python",
"pyc"
] | I know the difference between a .py and a .pyc file. My question is **not** about **how**, **but** about **why** According to the [docs](http://docs.python.org/2/tutorial/modules.html#compiled-python-files):
> A program doesnât run any faster when it is read from a .pyc or .pyo
> file than when it is read from a .py... | When you run a `.py` file, it is first compiled to bytecode, then executed. The loading of such a file is slower because for a `.pyc`, the compilation step has already been performed, but after loading, the same bytecode interpretation is done.
In pseudocode, the Python interpreter executes the following algorithm:
`... |
Why is the 'running' of .pyc files not faster compared to .py files? | 16,773,362 | 8 | 2013-05-27T12:35:31Z | 16,773,412 | 9 | 2013-05-27T12:38:44Z | [
"python",
"pyc"
] | I know the difference between a .py and a .pyc file. My question is **not** about **how**, **but** about **why** According to the [docs](http://docs.python.org/2/tutorial/modules.html#compiled-python-files):
> A program doesnât run any faster when it is read from a .pyc or .pyo
> file than when it is read from a .py... | The way the programs are *run* is always the same. The compiled code is interpreted.
The way the programs are *loaded* differs. If there is a current `pyc` file, this is taken as the compiled version, so no compile step has to be taken before running the command. Otherwise the `py` file is read, the compiler has to co... |
Regular Expression for whole numbers and integers? | 16,774,064 | 6 | 2013-05-27T13:14:21Z | 16,774,198 | 23 | 2013-05-27T13:20:36Z | [
"python",
"regex"
] | I am trying to detect all integers and whole numbers (among a lot of other things) from a string. Here are the regular expressions I am currently using:
Whole numbers: `r"[0-9]+"`
Integers: `r"[+,-]?[0-9]+"`
Here are the issues:
1. The whole numbers regex is detecting negative numbers as well, which I cannot have. ... | For positive integers, use
```
r"(?<![-.])\b[0-9]+\b(?!\.[0-9])"
```
**Explanation:**
```
(?<![-.]) # Assert that the previous character isn't a minus sign or a dot.
\b # Anchor the match to the start of a number.
[0-9]+ # Match a number.
\b # Anchor the match to the end of the number.
(?!\.... |
Fast Way to slice image into overlapping patches and merge patches to image | 16,774,148 | 9 | 2013-05-27T13:18:26Z | 16,788,733 | 9 | 2013-05-28T09:39:56Z | [
"python",
"numpy",
"slice"
] | Trying to slice a grayscale image of size 100x100 into patches of size 39x39 which are overlapping, with a stride-size of 1. That means that the next patch which starts one pixel to the right/or below is only different to the previous patch in one additional column/or row.
**Rough Outline of the code**: First compute ... | An efficient way to "patchify" an array, that is, to get an array of windows to the original array is to create a view with custom [strides](http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.strides.html), the number of bytes to jump to the following element. It can be helpful to think of a numpy array ... |
Set variable point size in matplotlib | 16,774,197 | 16 | 2013-05-27T13:20:35Z | 16,774,289 | 16 | 2013-05-27T13:25:18Z | [
"python",
"python-2.7",
"python-3.x",
"matplotlib"
] | I want to set a **variable** marker size in a scatter plot. This is my code:
```
import numpy as np
import matplotlib.pyplot as plt
from os import getcwd
from os.path import join, realpath, dirname
mypath = realpath(join(getcwd(), dirname(__file__)))
myfile = 'b34.dat'
data = np.loadtxt(join(mypath,myfile),
us... | `help(plt.plot)` shows
```
markersize or ms: float
```
so it appears `plt.plot` does not allow the markersize to be an array.
You could use `plt.scatter` however:
```
ax1.scatter(data[0], data[1], marker='o', c='b', s=data[2], label='the data')
```
---
PS. You can also verify that `plt.plot`'s `markersize` must... |
Python scatter-plot: Conditions for marker styles? | 16,774,586 | 2 | 2013-05-27T13:44:35Z | 16,774,762 | 7 | 2013-05-27T13:54:43Z | [
"python",
"matplotlib",
"scatter-plot"
] | I have a data set I wish to plot as scatter plot with matplotlib, and a vector the same size that categorizes and labels the data points (discretely, e.g. from 0 to 3). I want to use different markers for different labels (e.g. 'x' for 0, 'o' for 1 and so on). How can I solve this elegantly? I am quite sure I am just m... | What about iterating over all markers like this:
```
import numpy as np
import matplotlib.pyplot as plt
x = np.random.rand(100)
y = np.random.rand(100)
category = np.random.random_integers(0, 3, 100)
markers = ['s', 'o', 'h', '+']
for k, m in enumerate(markers):
i = (category == k)
plt.scatter(x[i], y[i], ma... |
Mean Squared Error in Numpy? | 16,774,849 | 17 | 2013-05-27T13:59:14Z | 18,047,482 | 23 | 2013-08-04T20:54:36Z | [
"python",
"arrays",
"numpy",
"mean",
"mean-square-error"
] | Is there a method in numpy for calculating the Mean Squared Error between two matrices?
I've tried searching but found none. Is it under a different name?
If there isn't, how do you overcome this? Do you write it yourself or use a different lib? | As suggested by @larsmans you can use:
```
mse = ((A - B) ** 2).mean(axis=ax)
```
* with `ax=0` the average is performed along the row, for each column, returning an array
* with `ax=1` the average is performed along the column, for each row, returning an array
* with `ax=None` the average is performed element-wise a... |
WSGI: what's the purpose of start_response function | 16,774,952 | 6 | 2013-05-27T14:05:24Z | 16,775,731 | 7 | 2013-05-27T14:53:26Z | [
"python",
"web-services",
"web-applications",
"wsgi",
"middleware"
] | Could you supply a real-life example of [WSGI](http://wsgi.readthedocs.org/en/latest/) [`start_response`](http://webpython.codepoint.net/wsgi_application_interface) function? (Web-server provides that function to wsgi application)
I can't understand the **purpose** of introducing the `start_response`.
(I've read like... | > Could you supply a real-life example of WSGI `start_response()` function?
Well, the `start_response()` function for [`mod_wsgi`](http://en.wikipedia.org/wiki/Mod_wsgi) is defined on [line 2678 of `mod_wgsi.c`](http://code.google.com/p/modwsgi/source/browse/mod_wsgi/mod_wsgi.c#2678)
> None of them says "WSGI is desi... |
List of non-zero elements in a list in Python | 16,775,379 | 5 | 2013-05-27T14:32:04Z | 16,775,394 | 10 | 2013-05-27T14:33:11Z | [
"python",
"list"
] | Given the list
```
a = [6, 3, 0, 0, 1, 0]
```
What is the best way in Python to return the list
```
b = [1, 1, 0, 0, 1, 0]
```
where the 1's in b correspond to the non-zero elements in a. I can think of running a for loop and simply appending onto b, but I'm sure there must be a better way. | List comprehension method:
```
a = [6, 3, 0, 0, 1, 0]
b = [1 if i else 0 for i in a]
print b
>>>
[1, 1, 0, 0, 1, 0]
```
---
Timing mine, [Dave's method](http://stackoverflow.com/a/16775401/1561176) and [Lattyware's slight alteration](http://stackoverflow.com/questions/16775379/list-of-non-zero-elements-in-a-list-in... |
Do things in random order? | 16,776,500 | 2 | 2013-05-27T15:41:09Z | 16,776,514 | 15 | 2013-05-27T15:42:18Z | [
"python",
"random"
] | Is there any way in Python to do things in random order? Say I'd like to run `function1()`, `function2()`, and `function3()`, but not necessarilly in that order, could that be done? The obvious answer is to make a list and choose them randomly, but how would you get the function name from the list and actually run it? | This is actually pretty simple. Python functions are just objects, that happen to be callable. So you can store them in a list, and then call them using the call operator (`()`).
Make your list of functions, shuffle them with [`random.shuffle()`](http://docs.python.org/3.3/library/random.html?highlight=random#random.s... |
Calculate time difference between Pandas Dataframe indices | 16,777,570 | 15 | 2013-05-27T17:01:30Z | 16,780,413 | 30 | 2013-05-27T20:53:26Z | [
"python",
"dataframe",
"pandas"
] | I am trying to add a column of deltaT to a dataframe where deltaT is the time difference between the successive rows (as indexed in the timeseries).
```
value
time
2012-03-16 23:50:00 1
2012-03-16 23:56:00 2
2012-03-17 00:08:00 3
2012-03-17 00:10:00 4
2012... | Note this is using numpy >= 1.7, for numpy < 1.7, see the conversion here: <http://pandas.pydata.org/pandas-docs/dev/timeseries.html#time-deltas>
Your original frame, with a datetime index
```
In [196]: df
Out[196]:
value
2012-03-16 23:50:00 1
2012-03-16 23:56:00 2
2012-03-17 00:08:00 ... |
Why does S3 (using with boto and django-storages) give signed url even for public files? | 16,777,900 | 8 | 2013-05-27T17:25:16Z | 16,818,992 | 17 | 2013-05-29T16:13:02Z | [
"python",
"django",
"amazon-s3",
"boto",
"django-storage"
] | This is strange. I have mix of public as well as private files. I want normal urls in public files, and signed urls in private files.
I tried to change `AWS_QUERYSTRING_AUTH to False` as I see by default, it's True in django-storages.
But, when I change it, my private files url is not signed (thus not accessible).
M... | `AWS_QUERYSTRING_AUTH` sets the default behavior, but you can override it when you create an instance of `S3BotoStorage`, by passing in an additional argument to the initializer:
```
S3BotoStorage(bucket="foo", querystring_auth=False)
```
So if you have one bucket private and another bucket public, you can set the `q... |
Python check if website exists | 16,778,435 | 20 | 2013-05-27T18:08:20Z | 16,778,473 | 41 | 2013-05-27T18:11:34Z | [
"python",
"html",
"urlopen"
] | I wanted to check if a certain website exists, this is what I'm doing:
```
user_agent = 'Mozilla/20.0.1 (compatible; MSIE 5.5; Windows NT)'
headers = { 'User-Agent':user_agent }
link = "http://www.abc.com"
req = urllib2.Request(link, headers = headers)
page = urllib2.urlopen(req).read() - ERROR 402 generated here!
```... | You can use HEAD request instead of GET. It will only download the header, but not the content. Then you can check the response status from the headers.
```
import httplib
c = httplib.HTTPConnection('www.example.com')
c.request("HEAD", '')
if c.getresponse().status == 200:
print('web site exists')
```
or you can u... |
Python check if website exists | 16,778,435 | 20 | 2013-05-27T18:08:20Z | 16,778,749 | 23 | 2013-05-27T18:35:39Z | [
"python",
"html",
"urlopen"
] | I wanted to check if a certain website exists, this is what I'm doing:
```
user_agent = 'Mozilla/20.0.1 (compatible; MSIE 5.5; Windows NT)'
headers = { 'User-Agent':user_agent }
link = "http://www.abc.com"
req = urllib2.Request(link, headers = headers)
page = urllib2.urlopen(req).read() - ERROR 402 generated here!
```... | It's better to check that status code is < 400, like it was done [here](http://stackoverflow.com/questions/6471275/python-script-to-see-if-a-web-page-exists-without-downloading-the-whole-page). Here is what do status codes mean (taken from [wikipedia](http://en.wikipedia.org/wiki/List_of_HTTP_status_codes)):
* `1xx` -... |
Python check if website exists | 16,778,435 | 20 | 2013-05-27T18:08:20Z | 16,778,783 | 7 | 2013-05-27T18:38:16Z | [
"python",
"html",
"urlopen"
] | I wanted to check if a certain website exists, this is what I'm doing:
```
user_agent = 'Mozilla/20.0.1 (compatible; MSIE 5.5; Windows NT)'
headers = { 'User-Agent':user_agent }
link = "http://www.abc.com"
req = urllib2.Request(link, headers = headers)
page = urllib2.urlopen(req).read() - ERROR 402 generated here!
```... | ```
from urllib2 import Request, urlopen, HTTPError, URLError
user_agent = 'Mozilla/20.0.1 (compatible; MSIE 5.5; Windows NT)'
headers = { 'User-Agent':user_agent }
link = "http://www.abc.com/"
req = Request(link, headers = headers)
try:
page_open = urlopen(req)
except HTTPError, e:
print e.code
except... |
django - how to sort objects alphabetically by first letter of name field | 16,778,819 | 7 | 2013-05-27T18:41:42Z | 16,779,964 | 9 | 2013-05-27T20:12:54Z | [
"python",
"django"
] | I have a model which has the fields `word` and `definition`. model of dictionary.
in db, i have for example these objects:
```
word definition
-------------------------
Banana Fruit
Apple also Fruit
Coffee drink
```
I want to make a query which gives me, sorting by the first letter of ... | Given the model...
```
class Wiki(models.Model):
word = models.TextField()
definition = models.TextField()
```
...the code...
```
my_words = Wiki.objects.order_by('word')
```
...should return the records in the correct order.
However, you won't be able to create an index on the `word` field if the type is `... |
Get frequency count of elements in an array | 16,779,470 | 3 | 2013-05-27T19:33:18Z | 16,779,524 | 8 | 2013-05-27T19:37:54Z | [
"python"
] | Hi I have a list of values. I want to get another list with the amount of times every values in that list occurs. This is fairly easy, but I also need to have the values which are not present in the original list, to be present in the frequency list, but then with value 0. For example:
```
I = [0,1,1,2,2,2,4,4,5,5,6,6... | ```
>>> lis = [0,1,1,2,2,2,4,4,5,5,6,6,6,8,8,8]
>>> maxx,minn = max(lis),min(lis)
>>> from collections import Counter
>>> c = Counter(lis)
>>> [c[i] for i in xrange(minn,maxx+1)]
[1, 2, 3, 0, 2, 2, 3, 0, 3]
```
or as suggested by @DSM we can get `min` and `max` from the `dict` itself:
```
>>> [c[i] for i in xrange( m... |
Return in generator together with yield in Python 3.3 | 16,780,002 | 19 | 2013-05-27T20:16:37Z | 16,780,023 | 14 | 2013-05-27T20:18:10Z | [
"python",
"generator"
] | In Python 2 there was an error when return was together with yield in function definition. But for this code in Python 3.3
```
def f():
return 3
yield 2
x = f()
print(x.__next__())
```
there is no error that return is used in function with yield. However when the function `__next__` is called then there is throw... | The return value is not ignored, but generators only *yield* values, a `return` just ends the generator, in this case early. Advancing the generator never reaches the `yield` statement in that case.
Whenever a iterator reaches the 'end' of the values to yield, a `StopIteration` *must* be raised. Generators are no exce... |
Return in generator together with yield in Python 3.3 | 16,780,002 | 19 | 2013-05-27T20:16:37Z | 16,780,113 | 23 | 2013-05-27T20:25:26Z | [
"python",
"generator"
] | In Python 2 there was an error when return was together with yield in function definition. But for this code in Python 3.3
```
def f():
return 3
yield 2
x = f()
print(x.__next__())
```
there is no error that return is used in function with yield. However when the function `__next__` is called then there is throw... | This is a new feature in Python 3.3 (as a comment notes, it doesn't even work in 3.2). Much like `return` in a generator has long been equivalent to `raise StopIteration()`, `return <something>` in a generator is now equivalent to `raise StopIteration(<something>)`. For that reason, the exception you're seeing should b... |
Import file from parent directory? | 16,780,014 | 13 | 2013-05-27T20:17:36Z | 16,780,068 | 7 | 2013-05-27T20:21:08Z | [
"python"
] | I have the following directory structure:
```
application
tests
main.py
main.py
```
application/main.py contains some functions.
tests/main.py will contain my tests for these functions but I can't import the top level main.py. I get the following error:
```
ImportError: Import by filename is not sup... | You must add the application dir to your path:
```
import sys
sys.path.append("/path/to/dir")
from app import object
```
Or from shell:
```
setenv PATH $PATH:"path/to/dir"
```
In case you use windows:
Adding variable to path in [windows](http://www.computerhope.com/issues/ch000549.htm).
Or from command line:
```
... |
Import file from parent directory? | 16,780,014 | 13 | 2013-05-27T20:17:36Z | 30,536,516 | 10 | 2015-05-29T18:20:28Z | [
"python"
] | I have the following directory structure:
```
application
tests
main.py
main.py
```
application/main.py contains some functions.
tests/main.py will contain my tests for these functions but I can't import the top level main.py. I get the following error:
```
ImportError: Import by filename is not sup... | If you'd like your script to be more portable, consider finding the parent directory automatically:
```
import os, sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
# import ../db.py
import db
``` |
Yield vs generator expression - different type returned | 16,780,434 | 4 | 2013-05-27T20:56:00Z | 16,780,452 | 9 | 2013-05-27T20:57:37Z | [
"python",
"generator",
"yield"
] | There is this code:
```
def f():
return 3
return (i for i in range(10))
x = f()
print(type(x)) # int
def g():
return 3
for i in range(10):
yield i
y = g()
print(type(y)) # generator
```
Why `f` returns `int` when there is return generator statement? I guess that `yield` and generator expression both re... | As *soon* as you use a `yield` statement in a function body, it becomes a generator. Calling a generator function just returns that generator object. It is no longer a normal function; the generator object has taken over control instead.
From the [`yield` expression documentation](http://docs.python.org/3/reference/ex... |
python, module object is not callable, calling method in another file | 16,780,510 | 12 | 2013-05-27T21:02:47Z | 16,780,543 | 26 | 2013-05-27T21:06:19Z | [
"python",
"import",
"module"
] | I have a fair background in java, trying to learn python. I'm running into a problem understanding how to access methods from other classes when they're in different files. I keep getting module object is not callable.
I made a simple function to find the largest and smallest integer in a list in one file, and want to... | The problem is in the `import` line. you are importing a *module*, not a class. assuming your file is named `other_file.py` (unlike java, again, there is no rule of "one class, one file"):
```
from other_file import findTheRange
```
if your file is named findTheRange too, following java's convenions, then you should ... |
Werkzeug response too slow | 16,780,731 | 3 | 2013-05-27T21:24:45Z | 16,781,888 | 8 | 2013-05-27T23:41:53Z | [
"python",
"apache",
"mod-wsgi",
"httpresponse",
"werkzeug"
] | I have the following Werkzeug application for returning a file to the client:
```
from werkzeug.wrappers import Request, Response
@Request.application
def application(request):
fileObj = file(r'C:\test.pdf','rb')
response = Response( response=fileObj.read() )
response.headers['content-type'] = 'applic... | The answer to that is pretty simple:
* `x.read()` <- reads the whole file into memory, inefficient
* setting response to a file: very inefficient as the protocol for that object is an iterator. So you will send the file line by line. If it's binary you will send it with random chunk sizes even.
* setting `response` to... |
Can PyYAML dump dict items in non-alphabetical order? | 16,782,112 | 12 | 2013-05-28T00:15:26Z | 16,782,282 | 20 | 2013-05-28T00:42:23Z | [
"python",
"yaml",
"pyyaml"
] | I'm using `yaml.dump` to output a dict. It prints out each item in alphabetical order based on the key.
```
>>> d = {"z":0,"y":0,"x":0}
>>> yaml.dump( d, default_flow_style=False )
'x: 0\ny: 0\nz: 0\n'
```
Is there a way to control the order of the key/value pairs?
In my particular use case, printing in reverse woul... | There's probably a better workaround, but I couldn't find anything in the documentation or the source. I subclassed `OrderedDict` and made it return a list of unsortable items:
```
from collections import OrderedDict
class UnsortableList(list):
def sort(self, *args, **kwargs):
pass
class UnsortableOrdere... |
Python pandas: Keep selected column as DataFrame instead of Series | 16,782,323 | 22 | 2013-05-28T00:48:52Z | 16,789,254 | 26 | 2013-05-28T10:03:16Z | [
"python",
"pandas"
] | When selecting a single column from a pandas DataFrame(say `df.iloc[:, 0]`, `df['A']`, or `df.A`, etc), the resulting vector is automatically converted to a Series instead of a single-column DataFrame. However, I am writing some functions that takes a DataFrame as an input argument. Therefore, I prefer to deal with sin... | As @Jeff mentions there are a few ways to do this, but I recommend using loc/iloc to be more explicit (and raise errors early if your trying something ambiguous):
```
In [10]: df = pd.DataFrame([[1, 2], [3, 4]], columns=['A', 'B'])
In [11]: df
Out[11]:
A B
0 1 2
1 3 4
In [12]: df[['A']]
In [13]: df[[0]]
In... |
Timedelta is not defined | 16,782,682 | 6 | 2013-05-28T01:46:17Z | 16,782,697 | 11 | 2013-05-28T01:48:09Z | [
"python",
"python-2.7",
"nameerror"
] | Below is the code I am working on. From what I can tell there is no issue, but when I attempt to run the piece of code I receive an error.
```
import os
import datetime
def parseOptions():
import optparse
parser = optparse.OptionParser(usage= '-h')
parser.add_option('-t', '--type', \
... | You've imported datetime, but not defined timedelta. You want either:
```
from datetime import timedelta
```
or:
```
subtract = datetime.timedelta(hours=options.goback)
```
Also, your goback parameter is defined as a string, but then you pass it to timedelta as the number of hours. You'll need to convert it to an i... |
web scraping tutorial using python 3? | 16,782,726 | 3 | 2013-05-28T01:52:40Z | 18,049,474 | 9 | 2013-08-05T01:37:24Z | [
"python",
"web-scraping",
"python-3.2"
] | I am trying to learn python 3.x so that I can scrape websites. People have recommended that I use Beautiful Soup 4 or lxml.html. Could someone point me in the right direction for tutorial or examples for BeautifulSoup with python 3.x?
Thank you for your help. | I've actually just written [a full guide on web scraping](http://blog.hartleybrody.com/guide-to-web-scraping/) that includes some sample code in Python. I wrote and tested in on Python 2.7 but both the of the packages that I used (requests and BeautifulSoup) are fully compatible with Python 3 according to the [Wall of ... |
What is a solid example of something that can be done with list comprehensions that is tricky with high order functions? | 16,784,162 | 16 | 2013-05-28T04:59:48Z | 16,784,312 | 10 | 2013-05-28T05:12:53Z | [
"python",
"haskell",
"clojure",
"functional-programming",
"list-comprehension"
] | I've heard from many Pythonists that they prefer list comprehensions because they can do everything you can do using high order functions such as filter and reduce, **and** more. So this question address them: what is a solid example of something you can do with them, that is tricky to do with HOFs? | In Haskell, list comprehensions are 'syntactic sugar' for conditionals and functions (or can trivially be translated into do notation and then desugared monadically). Here's the 'official' guide to translating them: <http://www.haskell.org/onlinereport/haskell2010/haskellch3.html#x8-420003.11>
Hence, since list compre... |
What is a solid example of something that can be done with list comprehensions that is tricky with high order functions? | 16,784,162 | 16 | 2013-05-28T04:59:48Z | 16,784,318 | 34 | 2013-05-28T05:13:28Z | [
"python",
"haskell",
"clojure",
"functional-programming",
"list-comprehension"
] | I've heard from many Pythonists that they prefer list comprehensions because they can do everything you can do using high order functions such as filter and reduce, **and** more. So this question address them: what is a solid example of something you can do with them, that is tricky to do with HOFs? | The answer is that there is no such example. Everything you can do with list comprehensions has a mechanical translation to higher-order functions. In fact, this is how Haskell implements list comprehensions: it desugars them to higher-order functions.
Given a list comprehension like this:
```
[(x, y) | x <- [1..3], ... |
What is a solid example of something that can be done with list comprehensions that is tricky with high order functions? | 16,784,162 | 16 | 2013-05-28T04:59:48Z | 16,786,490 | 20 | 2013-05-28T07:43:01Z | [
"python",
"haskell",
"clojure",
"functional-programming",
"list-comprehension"
] | I've heard from many Pythonists that they prefer list comprehensions because they can do everything you can do using high order functions such as filter and reduce, **and** more. So this question address them: what is a solid example of something you can do with them, that is tricky to do with HOFs? | As has been said, everything you can do with list comprehensions can be desugared into higher-order functions, but a large part of the problem with doing this in Python is that Python lacks support for the kind of point-free programming you can use with `filter`, `map`, and friends in Haskell. Here's a somewhat contriv... |
Append data to existing pytables table | 16,784,564 | 5 | 2013-05-28T05:34:56Z | 16,831,479 | 9 | 2013-05-30T08:37:00Z | [
"python",
"pytables"
] | I am new to PyTables and implemented a few basic techniques of inserting and retrieving data from a table in pytables. However, I am not sure about how to insert data in an existing table of PyTables because all I read/get in the [tutorial](http://pytables.github.io/usersguide/tutorials.html#creating-a-pytables-file-fr... | You need open your file in append mode `"a"`. Also do not create the group and table again. This appends another 10 rows:
```
import tables
class Particle(tables.IsDescription):
name = tables.StringCol(16) # 16-character String
idnumber = tables.Int64Col() # Signed 64-bit integer
ADCcount =... |
Splitting list of python dictionaries by repeating dictionary key values | 16,784,819 | 5 | 2013-05-28T05:56:51Z | 16,784,854 | 11 | 2013-05-28T05:59:05Z | [
"python",
"list",
"python-2.7",
"dictionary",
"split"
] | say I have a list of dictionaries:
```
foo = [
{'host': 'localhost', 'db_name': 'test', 'table': 'partners'},
{'host': 'localhost', 'db_name': 'test', 'table': 'users'},
{'host': 'localhost', 'db_name': 'test', 'table': 'sales'},
{'host': 'localhost', 'db_name': 'new', 'table': 'partners'},
... | ```
>>> from collections import defaultdict
>>> dd = defaultdict(list)
>>> foo = [
{'host': 'localhost', 'db_name': 'test', 'table': 'partners'},
{'host': 'localhost', 'db_name': 'test', 'table': 'users'},
{'host': 'localhost', 'db_name': 'test', 'table': 'sales'},
{'host': 'localhost', 'db_name... |
Python data scraping with Scrapy | 16,785,540 | 7 | 2013-05-28T06:49:25Z | 16,786,934 | 15 | 2013-05-28T08:06:26Z | [
"python",
"python-2.7",
"web-scraping",
"scrapy"
] | I want to scrape data from a website which has TextFields, Buttons etc.. and my requirement is to fill the text fields and submit the form to get the results and then scrape the data points from results page.
I want to know that does Scrapy has this feature or If anyone can recommend a library in Python to accomplish ... | Basically, you have plenty of tools to choose from:
* [scrapy](http://scrapy.org/)
* [beautifulsoup](https://pypi.python.org/pypi/BeautifulSoup/)
* [lxml](http://lxml.de/)
* [mechanize](http://wwwsearch.sourceforge.net/mechanize/)
* [requests](http://docs.python-requests.org/en/latest/) (and [grequests](https://github... |
Code is looped again and again | 16,789,243 | 3 | 2013-05-28T10:02:43Z | 16,789,319 | 10 | 2013-05-28T10:06:38Z | [
"python",
"if-statement"
] | I have next code:
```
def begin_game():
print "You landed on planet and see three rooms."
door=int(raw_input("Pick number of door>>>"))
print "You approach and see that you need to enter password..."
password=raw_input("Enter your surname>>>")
if door==1:
medical_room()
if door==2:
... | You need to use `elif` for the second and third if statements. `else` only considers the statement immediately before it. |
Differences between use of os.path.join and os.sep concatenation | 16,789,714 | 4 | 2013-05-28T10:27:37Z | 16,789,790 | 7 | 2013-05-28T10:31:03Z | [
"python",
"string",
"path",
"operating-system"
] | I am trying to figure out if it is better to use:
```
os.path.join(str1, str2)
```
or:
```
str1 + os.sep + str2
```
Profiling with `timeit` I found that, as expected, concatenation is faster:
```
%timeit 'playground' + os.sep + 'Text'
10000000 loops, best of 3: 139 ns per loop
%timeit os.path.join('playground', '... | It's right there in the documentation:
> `os.path.join(path1[, path2[, ...]])`
>
> Join one or more path components **intelligently**. If any component is an absolute path, all previous components (on Windows, including the previous drive letter, if there was one) are thrown away, and joining continues. The return val... |
open multiple filenames in tkinter and add the filesnames to a list | 16,790,328 | 5 | 2013-05-28T10:58:14Z | 16,791,727 | 8 | 2013-05-28T12:10:37Z | [
"python",
"file",
"tkinter"
] | what I want to do is to select multiple files
using the tkinter filedialog
and then add those items to a list.
After that I want to use the list to process
each file one by one.
```
#replace.py
import string
def main():
#import tkFileDialog
#import re
#ff = tkFileDialog.askopenfilenames()
... | `askopenfilenames` returns a string instead of a list, that problem is still open in the [issue tracker](http://bugs.python.org/issue5712), and the best solution so far is to use `splitlist`:
```
import Tkinter,tkFileDialog
root = Tkinter.Tk()
filez = tkFileDialog.askopenfilenames(parent=root,title='Choose a file')
p... |
<Django object > is not JSON serializable | 16,790,375 | 35 | 2013-05-28T11:00:51Z | 16,790,455 | 46 | 2013-05-28T11:04:30Z | [
"python",
"django",
"json",
"serialization",
"django-class-based-views"
] | I have the following code for serializing the queryset;
```
def render_to_response(self, context, **response_kwargs):
return HttpResponse(json.simplejson.dumps(list(self.get_queryset())),
mimetype="application/json")
```
And following is my `get_querset()`
```
[{'product': <Product: hede... | `simplejson` and `json` don't work with django objects well.
Django's built-in [serializers](https://docs.djangoproject.com/en/dev/topics/serialization/) can only serialize querysets filled with django objects:
```
data = serializers.serialize('json', self.get_queryset())
return HttpResponse(data, mimetype="applicati... |
Why would "\n" become "^@" when writing Python in a .vim file? | 16,791,232 | 6 | 2013-05-28T11:45:16Z | 16,791,502 | 9 | 2013-05-28T11:59:04Z | [
"python",
"vim",
"vim-plugin"
] | For example, here is my function:
```
function! Test()
python << EOF
import vim
str = "\n\n"
vim.command("let rs = append(line('$'), '%s')"%str)
EOF
endfunction
```
and when I `:call Test()` , what I see is "^@^@".
Why would this happen and how can I use the origin '\n' ? | Two things: Vim internally stores *null* bytes (i.e. `CTRL-@`) as `<NL>` == `CTRL-J` for implementation reasons (the text is stored as C strings, which are null-terminated).
Additionally, the `append()` function only inserts multiple lines when passed a *List* of text lines as its second argument. A single String will... |
Counting outcomes from a loop? | 16,792,603 | 2 | 2013-05-28T12:52:30Z | 16,792,732 | 7 | 2013-05-28T12:58:10Z | [
"python",
"count"
] | Created a program which flips a coin 100 times and gives a random outcome for each time. Just wondering if it is possible to count the number of times each outcome appears. No idea where to start. What I have so far....
```
# A program which flips a coin 100 times and tells you the outcome each time
import random
co... | If 1 represents heads, then the number of heads:
```
import random
print sum(random.choice([0,1]) for x in range(100))
# or more verbose:
print sum('heads' == random.choice(['heads','tails']) for x in range(100))
``` |
"os.environ" in django settings.py cannot get system environment variables with apache and wsgi | 16,792,698 | 2 | 2013-05-28T12:56:41Z | 16,793,387 | 7 | 2013-05-28T13:29:52Z | [
"python",
"django",
"apache",
"environment-variables",
"wsgi"
] | I set up the django setting.py like this:
```
import os
from django.core.exceptions import ImproperlyConfigured
def get_env_variable(var_name):
try:
return os.environ[var_name]
except KeyError:
error_msg = "Set the %s environment variable" % var_name
raise ImproperlyConfigured(error_msg... | You say "The environment variables were set in .bashrc." Presumably you mean *your* .bashrc. Which is pointless, because Apache is not running as you, it is running as the Apache user.
As explained in the blog post referenced in the very question you link to, you need to set the environment variables in the Apache con... |
Regex in Python does not mach string (but it does when checking on rubular) | 16,795,818 | 3 | 2013-05-28T15:25:44Z | 16,795,897 | 8 | 2013-05-28T15:30:27Z | [
"python",
"regex"
] | I'm writing a program in Python that uses regular expressions. I am having trouble because an expression that I think should match a string doesn't do it. This is the python code that reproduces my problem:
```
regex = re.compile(r"ord(er)? *0?([1-4])", re.I)
m = regex.match("CMord01")
```
m evaluates to FALSE.
I wou... | In Python `re.match()` matches from the beginning of the string. The first letter in `CMord01` is `C`, not `O`, thus it does not match.
Most language's regular expression modules don't have this limitation so they match the string no problem. To have this kind of behaviour in Python you need to use `re.search()` inste... |
Align columns in a text file | 16,796,709 | 6 | 2013-05-28T16:09:06Z | 16,797,930 | 7 | 2013-05-28T17:21:34Z | [
"python",
"python-3.x"
] | I am a Python noobie and I'm stuck on something I know is going to be simple...
I have a plain text file that contains user login data:
```
dtrapani HCPD-EPD-3687 Mon 05/13/2013 9:47:01.72
dlibby HCPD-COS-4611 Mon 05/13/2013 9:49:34.55
lmurdoch HCPD-SDDEB-3736 Mon 05/13/2013 9:50:38.48
lpatrick HCP... | I would go for the new(er) print formatter with this one (assuming your fields are consistent). The print/format statement is pretty easy to use and can be found [here](http://docs.python.org/2/library/string.html#formatstrings). Since your data can be seen as a list, you can do a single call to format and supplying th... |
Proper Usage of list.append in Python | 16,798,378 | 4 | 2013-05-28T17:48:59Z | 16,798,403 | 16 | 2013-05-28T17:50:03Z | [
"python"
] | Like to know why method 1 is correct and method 2 is wrong.
Method1:
```
def remove_duplicates(x):
y = []
for n in x:
if n not in y:
y.append(n)
return y
```
Method 2:
```
def remove_duplicates(x):
y = []
for n in x:
if n not in y:
y = y.append(n)
retu... | The `list.append` method returns `None`. So `y = y.append(n)`
sets `y` to `None`.
If this happens on the very last iteration of the `for-loop`, then `None` is returned.
If it happens before the last iteration, then on the next time through the loop,
```
if n not in y
```
will raise a
```
TypeError: argument of typ... |
Print LIST of unicode chars without escape characters | 16,798,811 | 5 | 2013-05-28T18:20:01Z | 16,799,274 | 8 | 2013-05-28T18:50:20Z | [
"python",
"list",
"encoding",
"python-2.7"
] | If you have a string as below, with unicode chars, you can print it, and get the unescaped version:
```
>>> s = "äåö"
>>> s
'\xc3\xa4\xc3\xa5\xc3\xb6'
>>> print s
äåö
```
but if we have a list containing the string above and print it:
```
>>> s = ['äåö']
>>> s
['\xc3\xa4\xc3\xa5\xc3\xb6']
>>> print s
['\xc3... | When you print a string, you get the output of the `__str__` method of the object - in this case the string without quotes. The `__str__` method of a list is different, it creates a string containing the opening and closing `[]` and the string produced by the `__repr__` method of each object contained within. What you'... |
How can set two field primary key for my models in django | 16,800,375 | 13 | 2013-05-28T19:56:12Z | 16,800,384 | 28 | 2013-05-28T19:56:41Z | [
"python",
"django",
"primary-key",
"models"
] | I have a model like this:
```
class Hop(models.Model):
migration = models.ForeignKey('Migration')
host = models.ForeignKey(User, related_name='host_set')
```
I want to migration and host both together be primary key. | I would implement this slightly differently.
I would use a default primary key (auto field), and use the meta class property, `unique_together`
```
class Hop(models.Model):
migration = models.ForeignKey('Migration')
host = models.ForeignKey(User, related_name='host_set')
class Meta:
unique_togeth... |
Running Selenium WebDriver using Python with extensions (.crx files) | 16,800,689 | 10 | 2013-05-28T20:14:49Z | 24,182,729 | 10 | 2014-06-12T11:00:37Z | [
"python",
"google-chrome",
"google-chrome-extension",
"selenium-webdriver"
] | I went to [Chrome Extension Downloader](http://chrome-extension-downloader.com/) to snag the .crx file for 'Adblock-Plus\_v1.4.1'.
I threw it in the directory im working in, and then ran:
```
from selenium import webdriver
chop = webdriver.ChromeOptions()
chop.add_extension('Adblock-Plus_v1.4.1.crx')
driver = webdri... | Just add this extra line in your program `
"from selenium.webdriver.chrome.options import Options"` it will work...
like this
```
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
chop = webdriver.ChromeOptions()
chop.add_extension('Adblock-Plus_v1.4.1.crx')
driver = webdriver.Chr... |
Elegant way to skip elements in an iterable | 16,800,832 | 2 | 2013-05-28T20:23:09Z | 16,800,855 | 7 | 2013-05-28T20:25:52Z | [
"python",
"iterator",
"iterable"
] | I've got a large iterable, in fact, a large iterable given by:
```
itertools.permutations(range(10))
```
I would like to access to the millionth element. I alredy have problem solved in some different ways.
1. Casting iterable to list and getting 1000000th element:
```
return list(permutations(range(10)))[999... | Use the [`itertools` recipe `consume`](http://docs.python.org/2/library/itertools.html) to skip `n` elements:
```
def consume(iterator, n):
"Advance the iterator n-steps ahead. If n is none, consume entirely."
# Use functions that consume iterators at C speed.
if n is None:
# feed the entire iterat... |
Django South - How do I reset migration history and start clean on Django app | 16,800,951 | 8 | 2013-05-28T20:31:15Z | 16,801,022 | 13 | 2013-05-28T20:35:42Z | [
"python",
"django",
"django-south"
] | [This](http://stackoverflow.com/questions/4625712/whats-the-recommended-approach-to-resetting-migration-history-using-django-sout) seems to be outdated as the `reset` command does not seem to be found using the version of South I am using, which is the most recent I believe.
Anyways, say you are in production and thin... | Steps:
1. Erase every `/migrations` folder inside your apps
2. Go to the database and drop the south\_migrationhistory table (or delete its rows)
3. (Optional) Remove south from your installed apps (if you want to get rid of south, if not, leave it alone)
Done
Notice that you may drop the table or delete all its row... |
How can I check that a list has one and only one truthy value? | 16,801,322 | 48 | 2013-05-28T20:53:35Z | 16,801,336 | 33 | 2013-05-28T20:54:50Z | [
"python"
] | In python, I have a list that should have **one and only one** truthy value (that is, `bool(value) is True`). Is there a clever way to check for this? Right now, I am just iterating across the list and manually checking:
```
def only1(l)
true_found = False
for v in l:
if v and not true_found:
... | It depends if you are just looking for the value `True` or are also looking for other values that would evaluate to `True` logically (like `11` or `"hello"`). If the former:
```
def only1(l):
return l.count(True) == 1
```
If the latter:
```
def only1(l):
return sum(bool(e) for e in l) == 1
```
since this wo... |
How can I check that a list has one and only one truthy value? | 16,801,322 | 48 | 2013-05-28T20:53:35Z | 16,801,422 | 17 | 2013-05-28T21:00:15Z | [
"python"
] | In python, I have a list that should have **one and only one** truthy value (that is, `bool(value) is True`). Is there a clever way to check for this? Right now, I am just iterating across the list and manually checking:
```
def only1(l)
true_found = False
for v in l:
if v and not true_found:
... | A one-line answer that retains the short-circuiting behavior:
```
from itertools import ifilter, islice
def only1(l):
return len(list(islice(ifilter(None, l), 2))) == 1
```
This will be significantly faster than the other alternatives here for very large iterables that have two or more true values relatively ear... |
How can I check that a list has one and only one truthy value? | 16,801,322 | 48 | 2013-05-28T20:53:35Z | 16,801,605 | 155 | 2013-05-28T21:14:08Z | [
"python"
] | In python, I have a list that should have **one and only one** truthy value (that is, `bool(value) is True`). Is there a clever way to check for this? Right now, I am just iterating across the list and manually checking:
```
def only1(l)
true_found = False
for v in l:
if v and not true_found:
... | One that doesn't require imports:
```
def single_true(iterable):
i = iter(iterable)
return any(i) and not any(i)
```
Alternatively, perhaps a more readable version:
```
def single_true(iterable):
iterator = iter(iterable)
has_true = any(iterator) # consume from "i" until first true or it's exhuasted
... |
How can I check that a list has one and only one truthy value? | 16,801,322 | 48 | 2013-05-28T20:53:35Z | 16,801,638 | 29 | 2013-05-28T21:16:30Z | [
"python"
] | In python, I have a list that should have **one and only one** truthy value (that is, `bool(value) is True`). Is there a clever way to check for this? Right now, I am just iterating across the list and manually checking:
```
def only1(l)
true_found = False
for v in l:
if v and not true_found:
... | The most verbose solution is not always the most unelegant solution. Therefore I add just a minor modification (in order to save some redundant boolean evaluations):
```
def only1(l):
true_found = False
for v in l:
if v:
# a True was found!
if true_found:
# found... |
How can I check that a list has one and only one truthy value? | 16,801,322 | 48 | 2013-05-28T20:53:35Z | 24,999,205 | 9 | 2014-07-28T15:57:44Z | [
"python"
] | In python, I have a list that should have **one and only one** truthy value (that is, `bool(value) is True`). Is there a clever way to check for this? Right now, I am just iterating across the list and manually checking:
```
def only1(l)
true_found = False
for v in l:
if v and not true_found:
... | I wanted to earn the necromancer badge, so I generalized the Jon Clements' excellent answer, preserving the benefits of short-circuiting logic and fast predicate checking with any and all.
Thus here is:
N(trues) = n
```
def n_trues(iterable, n=1):
i = iter(iterable)
return all(any(i) for j in range(n)) and n... |
Error flask-sqlalchemy NameError: global name 'joinedload' is not defined | 16,802,202 | 5 | 2013-05-28T22:00:28Z | 16,802,472 | 10 | 2013-05-28T22:22:59Z | [
"python",
"sqlalchemy",
"flask",
"flask-sqlalchemy"
] | I'm trying to use a sqlalchemy loading strategy to speed up my queries. After reading [this](http://www.tracelytics.com/blog/advanced-sqlalchemy-performance-concerns/) I realized that I was making the mistake of looping through the records in my template. The only problem is that i get this error:
> NameError: global ... | Well, the error message says `joinedload` is not defined, so the obvious solution would be to check if you imported it and if not -
```
from sqlalchemy.orm import joinedload
``` |
Flow control after breaking out of while loop in Python | 16,802,815 | 3 | 2013-05-28T22:54:10Z | 16,802,832 | 7 | 2013-05-28T22:55:25Z | [
"python",
"while-loop",
"flow"
] | I am pretty new to both programming and Python. A few times now, I have created what feels like an awkward program flow, and I am wondering if I am following best practices. This is conceptually what I have wanted to do:
```
def pseudocode():
while some condition is true:
do some stuff
if a conditi... | You're looking for [`while-else`](http://docs.python.org/2/reference/compound_stmts.html#while) loop:
```
def pseudocode():
while some condition is true:
do some stuff
if a condition is met:
break out of the while loop
else:
now do a thing once, but only if you never broke o... |
python: how to identify if a variable is an array or a scalar | 16,807,011 | 75 | 2013-05-29T06:33:42Z | 16,807,050 | 103 | 2013-05-29T06:35:51Z | [
"python",
"arrays",
"variables",
"scalar"
] | I have a function that takes the argument `NBins`. I want to make a call to this function with a scalar `50` or an array `[0, 10, 20, 30]`. How can I identify within the function, what the length of `NBins` is? or said differently, if it is a scalar or a vector?
I tried this:
```
>>> N=[2,3,5]
>>> P = 5
>>> len(N)
3
... | ```
>>> isinstance([0, 10, 20, 30], list)
True
>>> isinstance(50, list)
False
```
To support any type of sequence, check `collections.Sequence` instead of `list`.
**note**: `isinstance` also supports a tuple of classes, check `type(x) in (..., ...)` should be avoided and is unnecessary.
You may also wanna check `not... |
python: how to identify if a variable is an array or a scalar | 16,807,011 | 75 | 2013-05-29T06:33:42Z | 16,807,073 | 9 | 2013-05-29T06:37:21Z | [
"python",
"arrays",
"variables",
"scalar"
] | I have a function that takes the argument `NBins`. I want to make a call to this function with a scalar `50` or an array `[0, 10, 20, 30]`. How can I identify within the function, what the length of `NBins` is? or said differently, if it is a scalar or a vector?
I tried this:
```
>>> N=[2,3,5]
>>> P = 5
>>> len(N)
3
... | While, @jamylak's approach is the better one, here is an alternative approach
```
>>> N=[2,3,5]
>>> P = 5
>>> type(P) in (tuple, list)
False
>>> type(N) in (tuple, list)
True
``` |
python: how to identify if a variable is an array or a scalar | 16,807,011 | 75 | 2013-05-29T06:33:42Z | 19,773,559 | 54 | 2013-11-04T17:32:06Z | [
"python",
"arrays",
"variables",
"scalar"
] | I have a function that takes the argument `NBins`. I want to make a call to this function with a scalar `50` or an array `[0, 10, 20, 30]`. How can I identify within the function, what the length of `NBins` is? or said differently, if it is a scalar or a vector?
I tried this:
```
>>> N=[2,3,5]
>>> P = 5
>>> len(N)
3
... | Previous answers assume that the array is a python standard list. As someone who uses numpy often, I'd recommend a very pythonic test of:
```
if hasattr(N, "__len__")
``` |
python: how to identify if a variable is an array or a scalar | 16,807,011 | 75 | 2013-05-29T06:33:42Z | 28,858,378 | 9 | 2015-03-04T15:32:13Z | [
"python",
"arrays",
"variables",
"scalar"
] | I have a function that takes the argument `NBins`. I want to make a call to this function with a scalar `50` or an array `[0, 10, 20, 30]`. How can I identify within the function, what the length of `NBins` is? or said differently, if it is a scalar or a vector?
I tried this:
```
>>> N=[2,3,5]
>>> P = 5
>>> len(N)
3
... | Combining @jamylak and @jpaddison3's answers together, if you need to be robust against numpy arrays as the input and handle them in the same way as lists, you should use
```
import numpy as np
isinstance(P, (list, tuple, np.ndarray))
```
This is robust against subclasses of list, tuple and numpy arrays.
And if you ... |
db.ReferenceProperty() vs ndb.KeyProperty in App Engine | 16,807,108 | 13 | 2013-05-29T06:39:24Z | 16,807,593 | 7 | 2013-05-29T07:08:58Z | [
"python",
"google-app-engine",
"gae-datastore",
"app-engine-ndb"
] | ReferenceProperty was very helpful in handling references between two modules. Fox example:
```
class UserProf(db.Model):
name = db.StringProperty(required=True)
class Team(db.Model):
manager_name = db.ReferenceProperty(UserProf, collection_name='teams')
name = db.StringProperty(required=True)
```
* To g... | I don't know the answer as to why Guido didn't implement reference property.
However I found a spent a lot of time using pre\_fetch\_refprops <http://blog.notdot.net/2010/01/ReferenceProperty-prefetching-in-App-Engine> (pre fetches all of the reference properties by grabbing all the keys with get\_value\_for\_datastor... |
db.ReferenceProperty() vs ndb.KeyProperty in App Engine | 16,807,108 | 13 | 2013-05-29T06:39:24Z | 16,822,045 | 22 | 2013-05-29T19:12:40Z | [
"python",
"google-app-engine",
"gae-datastore",
"app-engine-ndb"
] | ReferenceProperty was very helpful in handling references between two modules. Fox example:
```
class UserProf(db.Model):
name = db.StringProperty(required=True)
class Team(db.Model):
manager_name = db.ReferenceProperty(UserProf, collection_name='teams')
name = db.StringProperty(required=True)
```
* To g... | Tim explained it well. We found that a common anti-pattern was using reference properties and loading them one at a time, because the notation "entity.property1.property2" doesn't make it clear that the first dot causes a database "get" operation. So we made it more obvious by forcing you to write "entity.property1.get... |
Selenium - Click at certain position | 16,807,258 | 6 | 2013-05-29T06:49:24Z | 26,385,456 | 8 | 2014-10-15T14:45:37Z | [
"python",
"selenium"
] | Using the Python version of Selenium, is it possible to click some element in the DOM and to specify the coordinates where you want to click it?
The Java version has the method [`clickAt`](http://release.seleniumhq.org/selenium-remote-control/0.9.2/doc/java/com/thoughtworks/selenium/Selenium.html#clickAt%28java.lang.St... | This should do it! Namely you need to use action chains from webdriver. Once you have an instance of that, you simply register a bunch of actions and then call `perform()` to perform them.
```
from selenium import webdriver
driver = webdriver.Firefox()
driver.get("http://www.google.com")
el=driver.find_elements_by_xpa... |
Python: Non-Blocking + Non defunct process | 16,807,603 | 3 | 2013-05-29T07:09:34Z | 16,809,886 | 7 | 2013-05-29T09:12:43Z | [
"python",
"subprocess"
] | I would like to create a parent process, which will create many child process. Since the parent process is responsible to create the child process, the parent process would not care the status of the childs.
Since subprocess.call is blocking, it doesn't work. Therefore I use subprocess.Popen to replace call. However P... | There are a lot of ways to deal with this. The key point is that zombie / "defunct" processes exist so that the parent process can collect their statuses.
1. As the creator of the process, you can announce your intent to ignore the status. The POSIX method is to set the flag `SA_NOCLDWAIT` (using `sigaction`). This is... |
Ruby inline documentation | 16,808,469 | 2 | 2013-05-29T08:02:24Z | 16,808,536 | 7 | 2013-05-29T08:06:09Z | [
"python",
"ruby",
"irb",
"rdoc",
"docstring"
] | In IRB, or other interactive interpreter such as pry, how can I get some inline documentation on objects and methods? For example, I can get this far:
```
[1] pry(main)> x = 'hello world'
=> "hello world"
[2] pry(main)> x.st
x.start_with? x.strip x.strip!
[2] pry(main)> x.st
```
But now I want to read usag... | First you need to install
```
gem install pry-doc
```
Then you can get documentation with the `show-doc [method]` command (aliased to `? [method]`)
```
pry> x = 'potato'
=> "potato"
pry> show-doc x.strip
From: string.c (C Method):
Owner: String
Visibility: public
Signature: strip()
Number of lines: 4
Returns a cop... |
shorthand for [:alpha:] in python regex | 16,810,092 | 2 | 2013-05-29T09:22:06Z | 16,810,321 | 8 | 2013-05-29T09:33:36Z | [
"python",
"regex",
"unicode"
] | What is equivalent of `[:alpha:]` if I am making a unicode regex that need it.
For example for `[:word:]` it is `[\w]`
will be great if I get some help. | For Unicode compliance, you need to use
```
regex = re.compile(r"[^\W\d_]", re.UNICODE)
```
Unicode character properties (like `\p{L}`) are not supported by the current Python regex engine.
**Explanation:**
`\w` matches (if the Unicode flag is set) any letter, digit or underscore.
`[^\W]` matches the same thing, b... |
Python regex subsitution: separate backreference from digit | 16,810,523 | 11 | 2013-05-29T09:42:11Z | 16,810,524 | 8 | 2013-05-29T09:42:11Z | [
"python",
"regex",
"backreference"
] | In a regex replacement pattern, a backreference looks like `\1`. If you want to include a digit after that backreference, this will fail because the digit is considered to be part of the backreference number:
```
# replace all twin digits by zeroes, but retain white space in between
re.sub(r"\d(\s*)\d", r"0\10", "0 1"... | Instead of using a backreference with a sequence number (`\1`), you can use named groups and the problem is solved:
```
# replace all twin digits by zeroes, but retain whitespace in between
re.sub(r"\d(?P<whitespace>\s*)\d", r"0\g<whitespace>0", "0 1")
>>> '0 0'
```
Turns out this trick is in fact described in the [d... |
Python regex subsitution: separate backreference from digit | 16,810,523 | 11 | 2013-05-29T09:42:11Z | 16,810,902 | 13 | 2013-05-29T10:01:01Z | [
"python",
"regex",
"backreference"
] | In a regex replacement pattern, a backreference looks like `\1`. If you want to include a digit after that backreference, this will fail because the digit is considered to be part of the backreference number:
```
# replace all twin digits by zeroes, but retain white space in between
re.sub(r"\d(\s*)\d", r"0\10", "0 1"... | You can use `\g<1>`, as mentioned in [the docs](http://docs.python.org/2/library/re.html#re.sub). |
Find if the array contain a 2 next to a 2 | 16,812,980 | 3 | 2013-05-29T11:44:16Z | 16,813,305 | 7 | 2013-05-29T11:59:54Z | [
"python",
"debugging"
] | I am stuck on this problem
> Given an array of ints, return True if the array contains a 2 next to a 2 somewhere.
```
has22([1, 2, 2]) â True
has22([1, 2, 1, 2]) â False
has22([2, 1, 2]) â False
```
I know the basic idea (there are syntax errors) but I can't implement it. I would also like to know what type of... | ```
def has22(nums):
return any(x == y == 2 for x, y in zip(nums, nums[1:]))
>>> has22([1, 2, 2])
True
>>> has22([1, 2, 1, 2])
False
>>> has22([2, 1, 2])
False
```
In Python 2 use: `from itertools import izip` if you want a lazy `zip` |
Python gzip refuses to read uncompressed file | 16,813,267 | 2 | 2013-05-29T11:58:12Z | 16,816,627 | 7 | 2013-05-29T14:28:08Z | [
"python",
"gzip"
] | I seem to remember that the Python gzip module previously allowed you to read non-gzipped files transparently. This was really useful, as it allowed to read an input file whether or not it was gzipped. You simply didn't have to worry about it.
Now,I get an IOError exception (in Python 2.7.5):
```
Traceback (most r... | The best solution for this would be to use something like <https://github.com/ahupp/python-magic> with libmagic. You simply cannot avoid at least reading a header to identify a file (unless you implicitly trust file extensions)
If you're feeling spartan the magic number for identifying gzip(1) files is the first two b... |
Python list iterator behavior and next(iterator) | 16,814,984 | 71 | 2013-05-29T13:17:46Z | 16,815,056 | 101 | 2013-05-29T13:21:17Z | [
"python",
"list",
"iterator"
] | Consider:
```
>>> lst = iter([1,2,3])
>>> next(lst)
1
>>> next(lst)
2
```
So, advancing the iterator is, as expected, handled by mutating that same object.
This being the case, I would expect:
```
a = iter(list(range(10)))
for i in a:
print(i)
next(a)
```
to skip every second element: the call to `next` shou... | What you see is the *interpreter* echoing back the return value of `next()` in addition to `i` being printed each iteration:
```
>>> a = iter(list(range(10)))
>>> for i in a:
... print(i)
... next(a)
...
0
1
2
3
4
5
6
7
8
9
```
So `0` is the output of `print(i)`, `1` the return value from `next()`, echoed by t... |
Python list iterator behavior and next(iterator) | 16,814,984 | 71 | 2013-05-29T13:17:46Z | 16,815,101 | 7 | 2013-05-29T13:23:23Z | [
"python",
"list",
"iterator"
] | Consider:
```
>>> lst = iter([1,2,3])
>>> next(lst)
1
>>> next(lst)
2
```
So, advancing the iterator is, as expected, handled by mutating that same object.
This being the case, I would expect:
```
a = iter(list(range(10)))
for i in a:
print(i)
next(a)
```
to skip every second element: the call to `next` shou... | What is happening is that `next(a)` returns the next value of a, which is printed to the console because it is not affected.
What you can do is affect a variable with this value:
```
>>> a = iter(list(range(10)))
>>> for i in a:
... print(i)
... b=next(a)
...
0
2
4
6
8
``` |
What does [:, :] mean on NumPy arrays | 16,815,928 | 9 | 2013-05-29T13:58:26Z | 16,815,975 | 9 | 2013-05-29T14:00:43Z | [
"python",
"arrays",
"numpy",
"matrix-indexing"
] | Sorry for the stupid question.
I'm programming on PHP but found some nice code on Python and want to "recreate" it on PHP.
But I'm quite frustrated about the line
```
self.h = -0.1
self.activity = numpy.zeros((512, 512)) + self.h
self.activity[:, :] = self.h
```
But I don't understand what does
```
[:, :]
```
m... | This is slice assignment. Technically, it calls1
```
self.activity.__setitem__((slice(None,None,None),slice(None,None,None)),self.h)
```
which sets all of the elements in `self.activity` to whatever value `self.h` is storing. The code you have there really seems redundant. As far as I can tell, you could remove the a... |
What does [:, :] mean on NumPy arrays | 16,815,928 | 9 | 2013-05-29T13:58:26Z | 16,816,142 | 7 | 2013-05-29T14:07:39Z | [
"python",
"arrays",
"numpy",
"matrix-indexing"
] | Sorry for the stupid question.
I'm programming on PHP but found some nice code on Python and want to "recreate" it on PHP.
But I'm quite frustrated about the line
```
self.h = -0.1
self.activity = numpy.zeros((512, 512)) + self.h
self.activity[:, :] = self.h
```
But I don't understand what does
```
[:, :]
```
m... | The `[:, :]` stands for everything from the beginning to the end just like for lists. The difference is that the first `:` stands for first and the second `:` for the second dimension.
```
a = numpy.zeros((3, 3))
In [132]: a
Out[132]:
array([[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.]])
```
Assi... |
Is it possible to print using different color in ipython's Notebook? | 16,816,013 | 8 | 2013-05-29T14:02:23Z | 16,816,874 | 14 | 2013-05-29T14:38:31Z | [
"python",
"ipython-notebook"
] | Is it somehow possible to have certain output appear in a different color in the IPython Notebook?
For example, something along the lines of:
```
print("Hello Red World", color='red')
``` | The notebook has, of course, its own syntax highlighting. So I would be careful when using colour elsewhere, just to avoid making things harder to read for yourself or someone else (e.g., output should simply be in black, but you get parts in red if there is an exception).
But (to my surprise), it appears that you can... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.