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 |
|---|---|---|---|---|---|---|---|---|---|
ParseError: not well-formed (invalid token) using cElementTree | 13,046,240 | 6 | 2012-10-24T09:18:51Z | 13,046,348 | 12 | 2012-10-24T09:25:11Z | [
"python",
"parsing",
"elementtree"
] | I receive xml strings from an external source that can contains unsanitized user contributed content.
The following xml string gave a ParseError in `cElementTree`:
```
>>> print repr(s)
'<Comment>dddddddd\x08\x08\x08\x08\x08\x08_____</Comment>'
>>> import xml.etree.cElementTree as ET
>>> ET.XML(s)
Traceback (most re... | It seems to complain about `\x08` you will need to escape that.
**Edit:**
Or you can have the parser ignore the errors using `recover`
```
from lxml import etree
parser = etree.XMLParser(recover=True)
etree.fromstring(xmlstring, parser=parser)
``` |
ParseError: not well-formed (invalid token) using cElementTree | 13,046,240 | 6 | 2012-10-24T09:18:51Z | 20,204,635 | 12 | 2013-11-25T22:24:57Z | [
"python",
"parsing",
"elementtree"
] | I receive xml strings from an external source that can contains unsanitized user contributed content.
The following xml string gave a ParseError in `cElementTree`:
```
>>> print repr(s)
'<Comment>dddddddd\x08\x08\x08\x08\x08\x08_____</Comment>'
>>> import xml.etree.cElementTree as ET
>>> ET.XML(s)
Traceback (most re... | I was having the same error (with ElementTree). In my case it was because of encodings, and I was able to solve it without having to use an external library. Hope this helps other people finding this question based on the title. ([reference](http://stackoverflow.com/a/9209547/2697658))
```
import xml.etree.ElementTree... |
Efficient ways to duplicate array/list in Python | 13,047,895 | 7 | 2012-10-24T11:02:01Z | 13,048,047 | 9 | 2012-10-24T11:10:39Z | [
"python",
"ruby",
"arrays"
] | Note: I'm a Ruby developer trying to find my way in Python.
When I wanted to figure out why some scripts use `mylist[:]` instead of `list(mylist)` to duplicate lists, I made a quick benchmark of the various methods to duplicate `range(10)` (see code below).
**EDIT:** I updated the tests to make use of Python's `timei... | Use the [`timeit`](http://docs.python.org/library/timeit.html) module in python for testing timings.
```
from copy import *
a=range(1000)
def cop():
b=copy(a)
def func1():
b=list(a)
def slice():
b=a[:]
def slice_len():
b=a[0:len(a)]
if __name__=="__main__":
import timeit
print "copy(a)"... |
pandas: apply function to DataFrame that can return multiple rows | 13,050,003 | 7 | 2012-10-24T13:14:11Z | 13,052,373 | 8 | 2012-10-24T15:25:40Z | [
"python",
"pandas",
"data-analysis"
] | I am trying to transform DataFrame, such that some of the rows will be replicated a given number of times. For example:
```
df = pd.DataFrame({'class': ['A', 'B', 'C'], 'count':[1,0,2]})
class count
0 A 1
1 B 0
2 C 2
```
should be transformed to:
```
class
0 A
1 C
2 ... | You could use groupby:
```
def f(group):
row = group.irow(0)
return DataFrame({'class': [row['class']] * row['count']})
df.groupby('class', group_keys=False).apply(f)
```
so you get
```
In [25]: df.groupby('class', group_keys=False).apply(f)
Out[25]:
class
0 A
0 C
1 C
```
You can fix the inde... |
Encrypt data with python, decrypt in php | 13,051,293 | 4 | 2012-10-24T14:27:03Z | 13,051,720 | 11 | 2012-10-24T14:50:22Z | [
"php",
"python",
"encryption"
] | I am looking for two fitting code snippets to encode some text with python, which is to be decoded in php. I am looking for something "easy" and compatible, and I have not much encryption experience myself.
If someone could give a working example that would be great! | python encrypt
```
from Crypto.Cipher import AES
import base64
import os
# the block size for the cipher object; must be 16, 24, or 32 for AES
BLOCK_SIZE = 32
BLOCK_SZ = 14
# the character used for padding--with a block cipher such as AES, the value
# you encrypt must be a multiple of BLOCK_SIZE in length. This char... |
Tastypie : Authentication for GET and Anonymous for POST | 13,051,544 | 10 | 2012-10-24T14:40:50Z | 13,202,569 | 17 | 2012-11-02T20:24:49Z | [
"python",
"django",
"api",
"rest",
"tastypie"
] | I use Django/Tastypie to manage my user collection.
Is it possible to allow anonymous users to POST in the API (when creating a new user at some endpoint) and restrict authenticated users to GET only their own user, but not all the users ?
Thanks for your help. | I found the easiest thing to do was subclass the Authentication class I'm using. Just override the `is_authenticated` method to return `True` when the method is POST.
```
class AnonymousPostAuthentication(BasicAuthentication):
""" No auth on post / for user creation """
def is_authenticated(self, request, **k... |
Tornado blocking asynchronous requests | 13,051,591 | 10 | 2012-10-24T14:43:13Z | 13,051,972 | 14 | 2012-10-24T15:04:19Z | [
"python",
"tornado",
"long-polling"
] | Using Tornado, I have a Get request that takes a long time as it makes many requests to another web service and processes the data, could take minutes to fully complete. I don't want this to block the entire web server from responding to other requests, which it currently does.
As I understand it, Tornado is single th... | Here's a complete sample Tornado app that uses the Async HTTP client and the `gen.Task` module to make things simple.
If you read more about `gen.Task` in the docs you'll see that you can actually dispatch multiple requests at the same time. This is using the core idea of Tornado where everything is no blocking and st... |
GAE - AppEngine - DeadlineExceededError: Deadline exceeded while waiting for HTTP response from URL: | 13,051,628 | 15 | 2012-10-24T14:44:52Z | 13,053,175 | 8 | 2012-10-24T16:09:03Z | [
"python",
"google-app-engine",
"urlfetch"
] | I have a Google AppEngine application which runs great on my local machine. The app posts a image (from a url) to my facebook wall. However, when I deploy it to Google's servers, I get
an error:
```
DeadlineExceededError: Deadline exceeded while waiting for HTTP response from URL:
```
The offending code is:
```
face... | Try setting the deadline for urlfetch to 30seconds or more(depending on whether you're calling urlfetch from within a task handler or request handler)
More info about urlfetch:[Url Fetch Docs](http://developers.google.com/appengine/docs/python/urlfetch/) |
GAE - AppEngine - DeadlineExceededError: Deadline exceeded while waiting for HTTP response from URL: | 13,051,628 | 15 | 2012-10-24T14:44:52Z | 22,091,200 | 23 | 2014-02-28T09:32:54Z | [
"python",
"google-app-engine",
"urlfetch"
] | I have a Google AppEngine application which runs great on my local machine. The app posts a image (from a url) to my facebook wall. However, when I deploy it to Google's servers, I get
an error:
```
DeadlineExceededError: Deadline exceeded while waiting for HTTP response from URL:
```
The offending code is:
```
face... | Simple answer: the default deadline for url fetching is set to 5 seconds.
How to fix:
```
from google.appengine.api import urlfetch
urlfetch.set_default_fetch_deadline(60)
``` |
nested list comprehension with os.walk | 13,051,785 | 2 | 2012-10-24T14:53:32Z | 13,051,822 | 11 | 2012-10-24T14:55:23Z | [
"python",
"list-comprehension"
] | Trying to enumerate all files in a certain directory (like 'find .' in Linux, or 'dir /s /b' in Windows).
I came up with the following nested list comprehension:
```
from os import walk
from os.path import join
root = r'c:\windows' #choose any folder here
allfiles = [join(root,f) for f in files for root,dirs,fil... | You need to reverse the nesting;
```
allfiles = [join(root,f) for root,dirs,files in walk(root) for f in files]
```
See the [list comprehension documentation](http://docs.python.org/reference/expressions.html#list-displays):
> When a list comprehension is supplied, it consists of a single expression followed by at l... |
python crypt in OSX | 13,052,047 | 7 | 2012-10-24T15:08:07Z | 13,052,999 | 7 | 2012-10-24T15:59:29Z | [
"python",
"c",
"encryption"
] | I have a Django application which resets unix user passwords running in an Ubuntu machine, but my development environment is OS X and I've come across this annoying situation:
OS X:
```
>>> import crypt
>>> crypt.crypt('test','$1$VFvON1xK$')
'$1SoNol0Ye6Xk'
```
Linux:
```
>>> import crypt
>>> crypt.crypt('test','$1... | This is because Linux's glibc handles passwords differently - the salt of the password on Linux corresponds to the type of hash that it generates. OSX crypt() is plain-old DES encryption, (which is horrible).
glibc supports a variety of hash algorithms (MD5, Blowfish, SHA-256, etc).
If we take a look at the [crypt.3]... |
matplotlib: how to decrease density of tick labels in subplots? | 13,052,844 | 11 | 2012-10-24T15:50:51Z | 13,053,381 | 12 | 2012-10-24T16:22:22Z | [
"python",
"plot",
"matplotlib",
"pandas"
] | I'm looking to decrease density of tick labels on differing subplot
```
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from StringIO import StringIO
data = """\
a b c d
z 54.65 6.27 19.53 4.54
w -1.27 4.41 11.74 3.06
d 5.51 3.39 22.98 2.... | You can set the ticks to where you want just like you set the xticks.
```
import numpy as np
ax0.yaxis.set_ticks(np.arange(70000,80000,2500))
```
This will create four ticks evenly spaced for your ax0 subplot. You can do something similar for your other subplots. |
matplotlib: how to decrease density of tick labels in subplots? | 13,052,844 | 11 | 2012-10-24T15:50:51Z | 13,053,967 | 27 | 2012-10-24T16:55:56Z | [
"python",
"plot",
"matplotlib",
"pandas"
] | I'm looking to decrease density of tick labels on differing subplot
```
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from StringIO import StringIO
data = """\
a b c d
z 54.65 6.27 19.53 4.54
w -1.27 4.41 11.74 3.06
d 5.51 3.39 22.98 2.... | An improvement over the approach suggestion by [Aman](http://stackoverflow.com/users/484596/aman) is the following:
```
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
# ... plot some things ...
# Find at most 101 ticks on the y-axis at 'nice' locations
max_yticks = 100
yloc = plt.M... |
Comparing two lists using the greater than or less than operator | 13,052,857 | 11 | 2012-10-24T15:51:55Z | 13,052,908 | 18 | 2012-10-24T15:54:27Z | [
"python",
"list"
] | I noticed a piece of code recently directly comparing two lists of integers like so:
```
a = [10,3,5, ...]
b = [5,4,3, ...,]
if a > b:
...
```
which seemed a bit peculiar, but I imagined it would return `True` if all of `list_a`'s elements are larger then `list_b`'s and False if each element is equal or `list_b`... | From [Comparing Sequences and Other Types](http://docs.python.org/tutorial/datastructures.html#comparing-sequences-and-other-types) in the Python tutorial:
> The comparison uses lexicographical ordering: first the first two items are compared, and if they differ this determines the outcome of the comparison; if they a... |
drawing a line on an image with PIL | 13,053,443 | 18 | 2012-10-24T16:26:14Z | 13,053,545 | 26 | 2012-10-24T16:31:37Z | [
"python",
"python-imaging-library"
] | I want to draw a line and show it.
assume I have a PIL image.
```
draw = ImageDraw.Draw(pilImage)
draw.line((100,200, 150,300), fill=128)
```
How can I show the image? Before drawing the line I could do:
```
imshow(pilImage)
```
but `imshow(draw)` does not show the image.
How do I convert this back to a PIL image? | This should work:
```
from PIL import Image, ImageDraw
im = Image.new('RGBA', (400, 400), (0, 255, 0, 0))
draw = ImageDraw.Draw(im)
draw.line((100,200, 150,300), fill=128)
im.show()
```
Basically using `ImageDraw` draw over the image, then display that image after changes, to draw a thick line pass width
```
draw.... |
Confused with python lists: are they or are they not iterators? | 13,054,057 | 32 | 2012-10-24T17:00:47Z | 13,054,102 | 12 | 2012-10-24T17:03:23Z | [
"python",
"list",
"iterator"
] | I am studying [Alex Marteli's Python in a Nutshell](http://rads.stackoverflow.com/amzn/click/0596100469) and the book suggests that any object that has a `next()` method is (or at least can be used as) an **iterator**. It also suggests that most iterators are built by implicit or explicit calls to a method called `iter... | You need to convert list to an iterator first using `iter()`:
```
In [7]: x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [8]: it=iter(x)
In [9]: for i in range(10):
it.next()
....:
....:
Out[10]: 0
Out[10]: 1
Out[10]: 2
Out[10]: 3
Out[10]: 4
Out[10]: 5
Out[10]: 6
Out[10]: 7
Out[10]: 8
Out[10]: 9
In [12]:... |
Confused with python lists: are they or are they not iterators? | 13,054,057 | 32 | 2012-10-24T17:00:47Z | 13,054,109 | 46 | 2012-10-24T17:03:44Z | [
"python",
"list",
"iterator"
] | I am studying [Alex Marteli's Python in a Nutshell](http://rads.stackoverflow.com/amzn/click/0596100469) and the book suggests that any object that has a `next()` method is (or at least can be used as) an **iterator**. It also suggests that most iterators are built by implicit or explicit calls to a method called `iter... | They are *iterable*, but they are not *iterators*. They can be passed to `iter()` to get an iterator for them either implicitly (e.g. via `for`) or explicitly, but they are not iterators in and of themselves. |
Confused with python lists: are they or are they not iterators? | 13,054,057 | 32 | 2012-10-24T17:00:47Z | 13,054,770 | 10 | 2012-10-24T17:44:34Z | [
"python",
"list",
"iterator"
] | I am studying [Alex Marteli's Python in a Nutshell](http://rads.stackoverflow.com/amzn/click/0596100469) and the book suggests that any object that has a `next()` method is (or at least can be used as) an **iterator**. It also suggests that most iterators are built by implicit or explicit calls to a method called `iter... | Just in case you are confused about what the difference between iterables and iterators is. An iterator is an object representing a stream of data. It implements the iterator protocol:
* `__iter__` method
* `next` method
Repeated calls to
the iteratorâs next() method return successive items in the stream. When
no m... |
Python: Finding multiple roots of nonlinear equation | 13,054,758 | 6 | 2012-10-24T17:43:41Z | 13,055,843 | 8 | 2012-10-24T18:54:30Z | [
"python",
"optimization",
"scipy"
] | Assume the following function:
`f(x) = x * cos(x-4)`
With `x = [-2.5, 2.5]` this function crosses `0` at `f(0) = 0` and `f(-0.71238898) = 0`.
This was determined with the following code:
```
import math
from scipy.optimize import fsolve
def func(x):
return x*math.cos(x-4)
x0 = fsolve(func, 0.0)
# returns [0.]
x... | I once wrote a module for this task. It's based on chapter 4.3 from the book [Numerical Methods in Engineering with Python by Jaan Kiusalaas](http://www.amazon.de/Numerical-Methods-Engineering-Python-Kiusalaas/dp/0521191327/ref=sr_1_1?ie=UTF8&qid=1351104745&sr=8-1):
```
import math
def rootsearch(f,a,b,dx):
x1 = ... |
How to print module documentation in Python | 13,054,970 | 7 | 2012-10-24T17:56:08Z | 13,054,992 | 7 | 2012-10-24T17:57:33Z | [
"python",
"python-2.7"
] | I know this question is very simple, I know it must have been asked a lot of times and I did my search on both SO and Google but I could not find the answer, probably due to my lack of ability of putting what I seek into a proper sentence.
I want to be able to read the docs of what I import.
For example if I import x... | `pydoc foo.bar` from the command line or `help(foo.bar)` or `help('foo.bar')` from Python. |
How to print module documentation in Python | 13,054,970 | 7 | 2012-10-24T17:56:08Z | 13,055,021 | 7 | 2012-10-24T18:00:01Z | [
"python",
"python-2.7"
] | I know this question is very simple, I know it must have been asked a lot of times and I did my search on both SO and Google but I could not find the answer, probably due to my lack of ability of putting what I seek into a proper sentence.
I want to be able to read the docs of what I import.
For example if I import x... | try `.__doc__`
```
In [14]: import itertools
In [15]: print itertools.__doc__
Functional tools for creating and using iterators..........
In [18]: print itertools.permutations.__doc__
permutations(iterable[, r]) --> permutations object
Return successive r-length permutations of elements in the iterable.
permutatio... |
HTTPError: HTTP Error 403: Forbidden | 13,055,208 | 7 | 2012-10-24T18:12:37Z | 13,055,444 | 17 | 2012-10-24T18:29:32Z | [
"python",
"python-2.7",
"beautifulsoup"
] | I making a python script for personal use but it's not working for wikipedia...
This work:
```
import urllib2, sys
from bs4 import BeautifulSoup
site = "http://youtube.com"
page = urllib2.urlopen(site)
soup = BeautifulSoup(page)
print soup
```
This not work:
```
import urllib2, sys
from bs4 import BeautifulSoup
s... | Within the current code
```
import urllib2, sys
from BeautifulSoup import BeautifulSoup
site= "http://en.wikipedia.org/wiki/StackOverflow"
hdr = {'User-Agent': 'Mozilla/5.0'}
req = urllib2.Request(site,headers=hdr)
page = urllib2.urlopen(req)
soup = BeautifulSoup(page)
print soup
```
The reason modified version work... |
Python parsing log file for IP address and Protocol | 13,056,858 | 6 | 2012-10-24T20:05:53Z | 13,056,942 | 7 | 2012-10-24T20:12:46Z | [
"python",
"parsing",
"loops",
"hash"
] | this is my first question asked here at stackoverflow and am really looking forward to being part of this community. I am new to program and python was the most recommended first program by many people.
**Anyways**. I have a log file which looks like this:
```
"No.","Time","Source","Destination","Protocol","Info"
"1"... | You can parse the file using the [`csv` module](http://docs.python.org/library/csv.html):
```
import csv
with open('logfile.txt') as logfile:
for row in csv.reader(logfile):
no, time, source, dest, protocol, info = row
# do stuff with these
```
I can't quite tell what you're asking, but I thin... |
Google App Engine NDB custom key id | 13,058,327 | 22 | 2012-10-24T21:50:01Z | 13,058,461 | 28 | 2012-10-24T21:58:25Z | [
"python",
"google-app-engine",
"app-engine-ndb",
"djangoappengine"
] | When I create an object with ndb's method put it creates the key automatically of the type Key(kind, id) where id is a number. All over the documentation it shows that you can use a string for the key's id but I couldn't find out how to do this automatically when an object is created.
I have a User model and I was thi... | ```
class UserModel(ndb.Model):
...
user_model_entity = UserModel(id='some_string', ...)
```
If these IDs are subject to change, this may be a bad idea. If it's your own system and you can react to potential changes, it is a fine idea, but you need make sure the IDs will be unique and relatively stable before decid... |
Google App Engine NDB custom key id | 13,058,327 | 22 | 2012-10-24T21:50:01Z | 13,058,736 | 13 | 2012-10-24T22:23:09Z | [
"python",
"google-app-engine",
"app-engine-ndb",
"djangoappengine"
] | When I create an object with ndb's method put it creates the key automatically of the type Key(kind, id) where id is a number. All over the documentation it shows that you can use a string for the key's id but I couldn't find out how to do this automatically when an object is created.
I have a User model and I was thi... | You specify the id of the entity at the time of creation. When you define the model, you don't set an id attribute there. Thus, for example you have:
```
class User(ndb.Model):
# fields here
```
When you create the model, you have:
```
user = User(id='username', ...)
```
Since the username is unique and you val... |
Is there a way to detect when a python program is going to end? | 13,058,739 | 4 | 2012-10-24T22:23:37Z | 13,058,766 | 7 | 2012-10-24T22:25:48Z | [
"python",
"callback",
"python-2.7",
"python-2.x"
] | Is there a way to detect when a python program is going to end? Something like a callback I can connect to?
I have a class thats keeping a [cache](http://stackoverflow.com/questions/13054250/python-object-cache) and I'd like to write the cache out to disk before the program ends. If I can do that then I can load it up... | [Yes, there is](http://docs.python.org/library/atexit.html):
```
import atexit
@atexit.register
def writecache():
# etc
``` |
Is there a way to detect when a python program is going to end? | 13,058,739 | 4 | 2012-10-24T22:23:37Z | 13,058,767 | 7 | 2012-10-24T22:25:57Z | [
"python",
"callback",
"python-2.7",
"python-2.x"
] | Is there a way to detect when a python program is going to end? Something like a callback I can connect to?
I have a class thats keeping a [cache](http://stackoverflow.com/questions/13054250/python-object-cache) and I'd like to write the cache out to disk before the program ends. If I can do that then I can load it up... | You can use [`atexit.register(some_function)`](http://docs.python.org/library/atexit.html#atexit.register) or simply decorate your function with `@atexit.register`. It will be called when the interpreter terminates.
Example:
```
import atexit
@atexit.register
def save_cache():
print 'save cache'
```
or
```
impo... |
Using Flask-SQLAlchemy in Blueprint models without reference to the app | 13,058,800 | 41 | 2012-10-24T22:28:25Z | 13,364,932 | 7 | 2012-11-13T16:46:10Z | [
"python",
"design",
"flask",
"flask-sqlalchemy"
] | I'm trying to create a "modular application" in Flask using Blueprints.
When creating models, however, I'm running into the problem of having to reference the app in order to get the `db`-object provided by Flask-SQLAlchemy. I'd like to be able to use some blueprints with more than one app (similar to how Django apps ... | Blueprints are more of a logical separation of concerns than actual applications.
The database instance should be setup by the application and not a Blueprint to allow things like background processing and other modules to be configured in one spot. If a Blueprint setup the database, it is then a dependency to the res... |
Using Flask-SQLAlchemy in Blueprint models without reference to the app | 13,058,800 | 41 | 2012-10-24T22:28:25Z | 13,432,373 | 18 | 2012-11-17T16:22:06Z | [
"python",
"design",
"flask",
"flask-sqlalchemy"
] | I'm trying to create a "modular application" in Flask using Blueprints.
When creating models, however, I'm running into the problem of having to reference the app in order to get the `db`-object provided by Flask-SQLAlchemy. I'd like to be able to use some blueprints with more than one app (similar to how Django apps ... | I believe the truest answer is that modular blueprints shouldn't concern themselves directly with data access, but instead rely on the application providing a compatible implementation.
So given your example blueprint.
```
from flask import current_app, Blueprint, render_template
flat_pages = Blueprint('flat_pages',... |
Is there any python function/library for calculate binomial confidence intervals? | 13,059,011 | 12 | 2012-10-24T22:48:20Z | 13,061,491 | 10 | 2012-10-25T04:15:26Z | [
"python",
"statistics"
] | I need to calculate binomial confidence intervals for large set of data within a script of python. Do you know any function or library of python that can do this?
Ideally I would like to have a function like this <http://statpages.org/confint.html> implemented on python.
Thanks for your time. | I would say that R (or another stats package) would probably serve you better if you have the option. That said, if you only need the binomial confidence interval you probably don't need an entire library. Here's the function in my most naive translation from javascript.
```
def binP(N, p, x1, x2):
p = float(p)
... |
Is there any python function/library for calculate binomial confidence intervals? | 13,059,011 | 12 | 2012-10-24T22:48:20Z | 25,196,394 | 8 | 2014-08-08T05:06:22Z | [
"python",
"statistics"
] | I need to calculate binomial confidence intervals for large set of data within a script of python. Do you know any function or library of python that can do this?
Ideally I would like to have a function like this <http://statpages.org/confint.html> implemented on python.
Thanks for your time. | Just noting because it hasn't been posted elsewhere here that [`statsmodels.stats.proportion.proportion_confint`](http://statsmodels.sourceforge.net/devel/generated/statsmodels.stats.proportion.proportion_confint.html) lets you get a binomial confidence interval with a variety of methods. It only does symmetric interva... |
Using Python, reverse an integer, and tell if palindrome | 13,059,540 | 3 | 2012-10-24T23:42:44Z | 13,059,602 | 22 | 2012-10-24T23:51:07Z | [
"python",
"string",
"list",
"main",
"function"
] | Using Python, reverse an integer and determine if it is a palindrome. Here is my definition of reverse and palindrome. Do I have a correct logic?
```
def reverse(num):
s=len(num)
newnum=[None]*length
for i in num:
s=s-1
newnum[s]=i
return newnum
def palindrome(num):
a=str(num)
... | ```
def palindrome(num):
return str(num) == str(num)[::-1]
``` |
Fast algorithm to detect main colors in an image? | 13,060,069 | 7 | 2012-10-25T00:50:51Z | 13,061,716 | 9 | 2012-10-25T04:46:52Z | [
"python",
"algorithm",
"colors",
"python-imaging-library"
] | Does anyone know a fast algorithm to detect main colors in an image?
I'm currently using k-means to find the colors together with Python's PIL but it's very slow. One 200x200 image takes 10 seconds to process. I've several hundred thousand images. | One fast method would be to simply divide up the color space into bins and then construct a histogram. It's fast because you only need a small number of decisions per pixel, and you only need one pass over the image (and one pass over the histogram to find the maxima).
**Update:** here's a rough diagram to help explai... |
Why Tor cant access localhost pages | 13,060,096 | 5 | 2012-10-25T00:54:26Z | 13,061,245 | 9 | 2012-10-25T03:45:47Z | [
"python",
"proxy",
"socks",
"tor"
] | I have Tor running and a python script to get web pages:
```
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9050)
socket.socket = socks.socksocket
print urllib2.urlopen(URL).read()
```
However, if the URL is
```
http://localhost/some_page.html
```
I get the following error:
```
raise Socks5Error(ord(... | It is the way protocol is designed. When you send a request, it is transported to another machine on Internet with Socks5 envelope. So actual request is made from external server, thus accessing 127.0.0.1 is not possible. |
Efficiently find the range of an array in python? | 13,060,458 | 5 | 2012-10-25T01:45:19Z | 13,060,519 | 10 | 2012-10-25T01:55:08Z | [
"python",
"performance",
"range",
"max",
"min"
] | Is there an accepted efficient way to find the range (ie. max value - min value) of a list of numbers in python? I have tried using a loop and I know I can use the `min` and `max` functions with subtraction. I am just wondering if there is some kind of built-in that is faster. | If you really need high performance, try Numpy. The function [`numpy.ptp`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.ptp.html) computes the range of values (i.e. `max - min`) across an array. |
Getting values with the right type in Redis | 13,060,632 | 13 | 2012-10-25T02:13:02Z | 13,060,733 | 7 | 2012-10-25T02:30:19Z | [
"python",
"types",
"redis",
"type-conversion"
] | I'm using redis in my python application to store simple values like counters and time stamp lists, but trying to get a counter and comparing it with a number i came across a problem.
If i do:
```
import redis
...
myserver = redis.Redis("localhost")
myserver.set('counter', 5)
```
and then try to get that value like ... | Technically speaking you need to take care of that on your own.
However, have a look at [this link](https://github.com/andymccurdy/redis-py), especially at the part of their README that refers to parsers and response callbacks, maybe that's something you can use. Question would be whether this is an overkill for you o... |
Getting values with the right type in Redis | 13,060,632 | 13 | 2012-10-25T02:13:02Z | 17,635,214 | 9 | 2013-07-13T23:48:53Z | [
"python",
"types",
"redis",
"type-conversion"
] | I'm using redis in my python application to store simple values like counters and time stamp lists, but trying to get a counter and comparing it with a number i came across a problem.
If i do:
```
import redis
...
myserver = redis.Redis("localhost")
myserver.set('counter', 5)
```
and then try to get that value like ... | As @favoretti said, response callbacks will do the trick. It's not complicate at all, just one line and all will be taken care of.
```
In [2]: import redis
In [3]: r = redis.Redis()
In [10]: r.set_response_callback('HGET', float)
In [11]: r.hget('myhash', 'field0')
Out[11]: 4.6
```
for `hmget`, it returns a list of s... |
psycopg - INSERT gzipped data into bytea column | 13,061,358 | 5 | 2012-10-25T03:59:18Z | 13,061,402 | 14 | 2012-10-25T04:05:15Z | [
"python",
"postgresql",
"psycopg2"
] | I'm trying to gzip a string and then write it into a `bytea` column using [psycopg2](http://www.initd.org/psycopg/).
**table:**
```
CREATE TABLE test
(
data bytea
)
```
**insert:**
```
import psycopg2
data = "some string".encode("zlib") # 'x\x9c+\xce\xcfMU(.)\xca\xccK\x07\x00\x1ak\x04l'
conn = psycopg2.connect(... | If you want to insert binary data into the database, you will need to use the psycopg2.Binary() wrapper. Using a string like you've done will cause the data to be treated as text, which will either be rejected due to encoding issues, or accepted but mangled when you try to read it again.
Try replacing the last execute... |
error of install numpy on linux red hat | 13,061,379 | 12 | 2012-10-25T04:01:11Z | 14,002,944 | 13 | 2012-12-22T12:45:00Z | [
"python",
"linux",
"numpy",
"scipy"
] | I am trying to install numpy from <http://www.scipy.org/Download> .
by `git clone git://github.com/numpy/numpy.git numpy`
But, when I ran `python setup.py install`
I got:
`SystemError: Cannot compile 'Python.h'. Perhaps you need to install python-dev|python-devel`
Where to get python-dev ?
I tried:
```
$ easy_in... | If you are in Ubuntu(e.g. Ubuntu 12.04), it is very easy,
```
sudo apt-get install python-numpy
```
or you can compile from source through pip(I think on RedHat almost the same):
```
sudo apt-get install python-dev
sudo apt-get install python-pip
pip install numpy
``` |
Change a pandas DataFrame column value based on another column value | 13,061,478 | 3 | 2012-10-25T04:13:43Z | 13,062,410 | 9 | 2012-10-25T05:54:10Z | [
"python",
"dataframe",
"pandas"
] | I have a dataframe with two columns each of which represents an organism. They are called ORG1 and ORG2
I want to move the values of ORG2 into ORG1 for the corresponding index value.
So, if ORG1 is 'A' and ORG2 is 'B' I want ORG1 to take the value 'B' from ORG2.
I have already started work to identify indexes of the ... | ```
In [13]: df
Out[13]:
ORG1 ORG2
0 A ESBL
1 B P
2 C Q
3 D R
4 E ESBL
In [14]: cond = df.ORG2 == 'ESBL'
In [15]: df.ORG1[cond] = df.ORG2[cond]
In [16]: df
Out[16]:
ORG1 ORG2
0 ESBL ESBL
1 B P
2 C Q
3 D R
4 ESBL ESBL
``` |
convert a dict to sorted dict in python | 13,062,300 | 4 | 2012-10-25T05:45:02Z | 13,062,357 | 10 | 2012-10-25T05:49:36Z | [
"python",
"pandas",
"sorteddictionary"
] | I want to convert a dict into sorted dict in python
```
data = pandas.read_csv('D:\myfile.csv')
for colname, dtype in data.dtypes.to_dict().iteritems():
if dtype == 'object':
print colname
count = data[colname].value_counts()
d = dict((str(k), int(v)) for k, v in count.iteritems())
... | You cannot sort a `dict` because dictionary has no ordering.
Instead, use [`collections.OrderedDict`](http://docs.python.org/library/collections.html#collections.OrderedDict):
```
>>> from collections import OrderedDict
>>> d = {'Gears of war 3': 6, 'Batman': 5, 'gears of war 3': 4, 'Rocksmith': 5, 'Madden': 3}
>>> ... |
Is making in-place operations return the object a bad idea? | 13,062,423 | 19 | 2012-10-25T05:55:12Z | 13,574,153 | 8 | 2012-11-26T22:20:40Z | [
"python",
"coding-style",
"mutable",
"mutability"
] | I'm talking mostly about Python here, but I suppose this probably holds for most languages. If I have a mutable object, is it a bad idea to make an in-place operation also return the object? It seems like most examples just modify the object and return `None`. For example, `list.sort`. | Returning the modified object from the method that modified it can have some benefits, but is not recommended in Python. Returning `self` after a modification operation will allow you to perform [method chaining](https://en.wikipedia.org/wiki/Method_chaining) on the object, which is a convenient way of executing severa... |
Is making in-place operations return the object a bad idea? | 13,062,423 | 19 | 2012-10-25T05:55:12Z | 13,574,259 | 23 | 2012-11-26T22:29:09Z | [
"python",
"coding-style",
"mutable",
"mutability"
] | I'm talking mostly about Python here, but I suppose this probably holds for most languages. If I have a mutable object, is it a bad idea to make an in-place operation also return the object? It seems like most examples just modify the object and return `None`. For example, `list.sort`. | Yes, it is a bad idea. The reason is that if in-place and non-in-place operations have apparently identical output, then programmers will frequently mix up in-place operations and non-in-place operations (`List.sort()` vs. `sorted()`) and that results in hard-to-detect errors.
In-place operations returning themselves ... |
How to show the whole image when using OpenCV warpPerspective | 13,063,201 | 13 | 2012-10-25T06:57:17Z | 20,355,545 | 20 | 2013-12-03T15:46:56Z | [
"python",
"image-processing",
"opencv",
"numpy",
"computer-vision"
] | I have 2 test images here. My is question is, how to map the square in first image to the quadrilateral in the second image without cropping the image.
Image 1:

Image 2:

Here is my current code using openCV warpPerspective ... | My solution is to calculate the result image size, and then do a translation.
```
def warpTwoImages(img1, img2, H):
'''warp img2 to img1 with homograph H'''
h1,w1 = img1.shape[:2]
h2,w2 = img2.shape[:2]
pts1 = float32([[0,0],[0,h1],[w1,h1],[w1,0]]).reshape(-1,1,2)
pts2 = float32([[0,0],[0,h2],[w2,h... |
DeprecationWarning: BaseException.message has been deprecated as of Python 2.6 exception.__class__, exception.message, | 13,063,212 | 9 | 2012-10-25T06:58:19Z | 13,063,924 | 21 | 2012-10-25T07:46:42Z | [
"python",
"exception",
"python-2.6",
"deprecation-warning"
] | Can anyone tell me the actual reason behind the warning I am getting in this Django middleware, and how can I solve this?
I am getting this message "*DeprecationWarning: BaseException.message has been deprecated as of Python 2.6 exception.**class**, exception.message,*"
```
class GeneralMiddleware(object):
def pr... | If I remember correctly, when Python switched to the new raise syntax in 2.5(?), they got rid of the `message` member in favor of an `args` tuple. For backward compatibility, `BaseException.message` is effectively the same thing as `BaseException.args[0] if BaseException.args else None`, but you shouldn't use it in new... |
Downloading the files from s3 recursively using boto python. | 13,063,474 | 14 | 2012-10-25T07:16:00Z | 13,063,610 | 20 | 2012-10-25T07:25:57Z | [
"python",
"amazon-s3",
"amazon-web-services",
"boto"
] | I have a bucket in s3, which has deep directory structure. I wish I could download them all at once. My files look like this :
```
foo/bar/1. .
foo/bar/100 . .
```
Are there any ways to download these files recursively from the s3 bucket using boto lib in python?
Thanks in advance. | You can download all files in a bucket like this (untested):
```
from boto.s3.connection import S3Connection
conn = S3Connection('your-access-key','your-secret-key')
bucket = conn.get_bucket('bucket')
for key in bucket.list():
try:
res = key.get_contents_to_filename(key.name)
except:
logging.i... |
Applying a function to values in dict | 13,063,691 | 18 | 2012-10-25T07:31:49Z | 13,063,716 | 25 | 2012-10-25T07:33:48Z | [
"python",
"dictionary"
] | I want to apply a function to all values in dict and store that in a separate dict. I am just trying to see how I can play with python and want to see how I can rewrite something like this
```
for i in d:
d2[i] = f(d[i])
```
to something like
```
d2[i] = f(d[i]) for i in d
```
The first way of writing it is of ... | If you're using Python 2.7 or 3.x:
```
d2 = {k: f(v) for k, v in d1.items()}
```
Which is equivalent to:
```
d2 = {}
for k, v in d1.items():
d2[k] = f(v)
```
Otherwise:
```
d2 = dict((k, f(v)) for k, v in d1.items())
``` |
Python bottle runs initialization method twice | 13,064,490 | 4 | 2012-10-25T08:23:08Z | 13,064,594 | 7 | 2012-10-25T08:30:09Z | [
"python",
"web-applications",
"bottle"
] | I've got a problem with bottle, the `_initialize` function is run twice. Example app:
```
@route("/index")
def index():
return "bang"
def _initialize():
print("bam")
if __name__ == "__main__":
_initialize()
run(reloader=True, host="localhost", port = 8990)
```
The output is:
```
bam
bam
B... | The problem is the `reloader=True` argument for the `run` function. See <http://bottlepy.org/docs/dev/tutorial.html#auto-reloading> for the sentence:
> All module-level code is executed at least twice! Be careful. |
Double-indexed dictionary | 13,065,426 | 9 | 2012-10-25T09:21:34Z | 13,065,439 | 16 | 2012-10-25T09:22:42Z | [
"python",
"dictionary"
] | I want to be able to store and look up values in a dictionary based on two integer values.
So when I look up a value I want to use the keys `read_length` and `min_size` to access the element, like so:
```
number_of_read_lengths[read_length][min_size]
```
I know I can create nested dictionaries, but that is a slight ... | You can use any immutable and hashable object as key, including tuples
```
number_of_read_lengths = {}
number_of_read_lengths[14,3] = "Your value"
``` |
Is there a way to secure strings for Python's eval? | 13,066,594 | 7 | 2012-10-25T10:28:10Z | 13,066,657 | 8 | 2012-10-25T10:31:45Z | [
"python",
"security",
"eval"
] | There are many questions on SO about using Python's eval on **insecure strings** (eg.: [Security of Python's eval() on untrusted strings?](http://stackoverflow.com/questions/661084/security-of-pythons-eval-on-untrusted-strings), [Python: make eval safe](http://stackoverflow.com/questions/3513292/python-make-eval-safe) ... | No, there isn't, or at least, not a sensible, truly secure way. Python is a highly dynamic language, and the flipside of that is that it's very easy to subvert any attempt to lock the language down.
You either need to write your own parser for the subset you want, or use something existing, like `ast.literal_eval()`, ... |
Is there a way to secure strings for Python's eval? | 13,066,594 | 7 | 2012-10-25T10:28:10Z | 13,284,815 | 9 | 2012-11-08T07:58:50Z | [
"python",
"security",
"eval"
] | There are many questions on SO about using Python's eval on **insecure strings** (eg.: [Security of Python's eval() on untrusted strings?](http://stackoverflow.com/questions/661084/security-of-pythons-eval-on-untrusted-strings), [Python: make eval safe](http://stackoverflow.com/questions/3513292/python-make-eval-safe) ... | Here you have a working "exploit" with your restrictions in place - only contains lower case ascii chars or any of the signs +-\*/() .
It relies on a 2nd eval layer.
```
def mask_code( python_code ):
s="+".join(["chr("+str(ord(i))+")" for i in python_code])
return "eval("+s+")"
bad_code='''__import__("os").ge... |
Read a local file in django | 13,067,107 | 4 | 2012-10-25T10:58:25Z | 13,067,290 | 13 | 2012-10-25T11:09:17Z | [
"python",
"django",
"path"
] | I'm quite stuck on this one!
I am writing a Django view that reads data from an external database. To do this, I am using the standard MySQLdb library.
Now, to load the data, I must do a very long and complex query. I can hard code that query in my view and that works just fine.
But I think that is not practical; I wan... | Keep the file in django project root and add the following in the settings.py file.
```
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
```
Then in the view do this.
```
import os
from django.conf.settings import PROJECT_ROOT
file_ = open(os.path.join(PROJECT_ROOT, 'filename'))
``` |
Python: Getting the max value of y from a list of objects | 13,067,615 | 11 | 2012-10-25T11:29:54Z | 13,067,638 | 7 | 2012-10-25T11:31:20Z | [
"python",
"list",
"max"
] | I have this list of objects wich have a x and a y parameter (and some other stuff).
```
path.nodes = (
<GSNode x=535.0 y=0.0 GSLINE GSSHARP>,
<GSNode x=634.0 y=0.0 GSLINE GSSHARP>,
<GSNode x=377.0 y=706.0 GSLINE GSSHARP>,
<GSNode x=279.0 y=706.0 GSLINE GSSHARP>,
<GSNode x=10.0 y=0.0 GSLINE GSSHARP>... | There's a built-in to help with this case.
```
import operator
print max(path.nodes, key=operator.attrgetter('y'))
```
Alternatively:
```
print max(path.nodes, key=lambda item: item.y)
```
Edit: But Mark Byers' answer is most Pythonic.
```
print max(node.y for node in path.nodes)
``` |
Python: Getting the max value of y from a list of objects | 13,067,615 | 11 | 2012-10-25T11:29:54Z | 13,067,652 | 20 | 2012-10-25T11:32:29Z | [
"python",
"list",
"max"
] | I have this list of objects wich have a x and a y parameter (and some other stuff).
```
path.nodes = (
<GSNode x=535.0 y=0.0 GSLINE GSSHARP>,
<GSNode x=634.0 y=0.0 GSLINE GSSHARP>,
<GSNode x=377.0 y=706.0 GSLINE GSSHARP>,
<GSNode x=279.0 y=706.0 GSLINE GSSHARP>,
<GSNode x=10.0 y=0.0 GSLINE GSSHARP>... | To get just the maximum value and not the entire object you can use a generator expression:
```
print max(node.y for node in path.nodes)
``` |
Python SyntaxError :'return' outside function | 13,068,043 | 4 | 2012-10-25T11:56:18Z | 13,068,072 | 9 | 2012-10-25T11:58:24Z | [
"python"
] | Compiler showed:
```
File "temp.py", line 56
return result
SyntaxError: 'return' outside function
```
Where was I wrong?
```
class Complex (object):
def __init__(self, realPart, imagPart):
self.realPart = realPart
self.imagPart = imagPart
def __str__(self):
if type(se... | I would check my indentation, it looks off. Are you possibly mixing tabs and spaces? The [PEP8 (Python Style Guide)](http://www.python.org/dev/peps/pep-0008/) recommends using [4 spaces only](http://www.python.org/dev/peps/pep-0008/#tabs-or-spaces). Unlike other languages, whitepace makes a big difference in Python, so... |
Multiprocessing scikit-learn | 13,068,257 | 9 | 2012-10-25T12:10:03Z | 13,082,746 | 12 | 2012-10-26T07:36:25Z | [
"python",
"multithreading",
"numpy",
"machine-learning",
"scikit-learn"
] | I got linearsvc working against training set and test set using `load_file` method i am trying to get It working on Multiprocessor enviorment.
How can i get multiprocessing work on `LinearSVC().fit()` `LinearSVC().predict()`? I am not really familiar with datatypes of scikit-learn yet.
I am also thinking about splitt... | I think using SGDClassifier instead of LinearSVC for this kind of data would be a good idea, as it is much faster. For the vectorization, I suggest you look into the [hash transformer PR](https://github.com/scikit-learn/scikit-learn/pull/909).
For the multiprocessing: You can distribute the data sets across cores, do ... |
Multiprocessing scikit-learn | 13,068,257 | 9 | 2012-10-25T12:10:03Z | 13,084,224 | 10 | 2012-10-26T09:24:50Z | [
"python",
"multithreading",
"numpy",
"machine-learning",
"scikit-learn"
] | I got linearsvc working against training set and test set using `load_file` method i am trying to get It working on Multiprocessor enviorment.
How can i get multiprocessing work on `LinearSVC().fit()` `LinearSVC().predict()`? I am not really familiar with datatypes of scikit-learn yet.
I am also thinking about splitt... | For linear models (`LinearSVC`, `SGDClassifier`, `Perceptron`...) you can chunk your data, train independent models on each chunk and build an aggregate linear model (e.g. `SGDClasifier`) by sticking in it the average values of `coef_` and `intercept_` as attributes. The `predict` method of `LinearSVC`, `SGDClassifier`... |
Parallelise python loop with numpy arrays and shared-memory | 13,068,760 | 14 | 2012-10-25T12:37:24Z | 13,093,515 | 16 | 2012-10-26T19:52:48Z | [
"python",
"numpy",
"parallel-processing",
"multiprocessing",
"shared-memory"
] | I am aware of several questions and answers on this topic, but haven't found a satisfactory answer to this particular problem:
What is the easiest way to do a simple shared-memory parallelisation of a python loop where numpy arrays are manipulated through numpy/scipy functions?
I am not looking for the most efficient... | With Cython parallel support:
```
# asd.pyx
from cython.parallel cimport prange
import numpy as np
def foo():
cdef int i, j, n
x = np.zeros((200, 2000), float)
n = x.shape[0]
for i in prange(n, nogil=True):
with gil:
for j in range(100):
x[i,:] = np.cos(x[i,:])
... |
Efficient implementation for: "Python For Else Loop" in Java | 13,069,402 | 15 | 2012-10-25T13:13:03Z | 13,069,441 | 10 | 2012-10-25T13:15:49Z | [
"java",
"python",
"if-statement",
"for-loop"
] | In Python there is an efficient for else loop implementation described
[here](http://docs.python.org/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops)
Example code:
```
for x in range(2, n):
if n % x == 0:
print n, 'equals', x, '*', n/x
break
else:
# loop fell ... | When I need to do something like this, I typically try to break it out into a separate method - which can then return `true`/`false` if no extra information is needed, or possibly "the value found, or null if it's not found". It doesn't *always* work - it's very context-specific - but it's something worth trying.
Then... |
Efficient implementation for: "Python For Else Loop" in Java | 13,069,402 | 15 | 2012-10-25T13:13:03Z | 17,281,801 | 34 | 2013-06-24T17:51:53Z | [
"java",
"python",
"if-statement",
"for-loop"
] | In Python there is an efficient for else loop implementation described
[here](http://docs.python.org/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops)
Example code:
```
for x in range(2, n):
if n % x == 0:
print n, 'equals', x, '*', n/x
break
else:
# loop fell ... | It's done like this:
```
class A {
public static void main(String[] args) {
int n = 13;
found: {
for (int x : new int[]{2,3,4,5,6,7,8,9,10,11,12})
if (n % x == 0) {
System.out.println("" + n + " equals " + x + "*" + (n/x));
break f... |
Python daemon and systemd service | 13,069,634 | 27 | 2012-10-25T13:25:10Z | 13,082,597 | 13 | 2012-10-26T07:25:18Z | [
"python",
"python-daemon",
"systemd"
] | I have simple Python script with works as a daemon. I am trying to create systemd script to be able to start this script during startup.
Current systemd script:
```
[Unit]
Description=Text
After=syslog.target
[Service]
Type=forking
User=node
Group=node
WorkingDirectory=/home/node/Node/
PIDFile=/var/run/zebra.pid
Exe... | You're not creating the PID file.
systemd expects your program to write its PID in `/var/run/zebra.pid`. As you don't do it, systemd probably thinks that your program is failing, hence deactivating it.
To add the PID file, install [lockfile](http://pypi.python.org/pypi/lockfile/) and change your code to this:
```
im... |
Python daemon and systemd service | 13,069,634 | 27 | 2012-10-25T13:25:10Z | 21,388,697 | 12 | 2014-01-27T18:28:31Z | [
"python",
"python-daemon",
"systemd"
] | I have simple Python script with works as a daemon. I am trying to create systemd script to be able to start this script during startup.
Current systemd script:
```
[Unit]
Description=Text
After=syslog.target
[Service]
Type=forking
User=node
Group=node
WorkingDirectory=/home/node/Node/
PIDFile=/var/run/zebra.pid
Exe... | It is possible to daemonize like Schnouki and Amit describe. But with systemd this is not necessary. There are two nicer ways to initialize the daemon: socket-activation and explicit notification with sd\_notify().
Socket activation works for daemons which want to listen on a network port or UNIX socket or similar. Sy... |
Python daemon and systemd service | 13,069,634 | 27 | 2012-10-25T13:25:10Z | 30,189,540 | 30 | 2015-05-12T11:29:02Z | [
"python",
"python-daemon",
"systemd"
] | I have simple Python script with works as a daemon. I am trying to create systemd script to be able to start this script during startup.
Current systemd script:
```
[Unit]
Description=Text
After=syslog.target
[Service]
Type=forking
User=node
Group=node
WorkingDirectory=/home/node/Node/
PIDFile=/var/run/zebra.pid
Exe... | The reason, it does not complete the startup sequence is, that for Type `forking` your startup process is expected to fork and exit (see $ man systemd.service - search for forking).
# Simply use only the main process, do not daemonize
One option is to do less. With systemd, there is often no need to create daemons an... |
Get index of the top n values of a list in python | 13,070,461 | 19 | 2012-10-25T14:08:25Z | 13,070,505 | 37 | 2012-10-25T14:10:51Z | [
"python"
] | I have a list say `a = [5,3,1,4,10]`. I need to get a index of top two values of the list viz 5 and 10. Is there a one-liner that python offers for such a case? | ```
sorted(range(len(a)), key=lambda i: a[i])[-2:]
```
or
```
sorted(range(len(a)), key=lambda i: a[i], reverse=True)[:2]
```
or
```
zip(*sorted(enumerate(a), key=operator.itemgetter(1)))[0][-2:]
```
or (for long lists)
```
zip(*heapq.nlargest(2, enumerate(a), key=operator.itemgetter(1)))[0]
``` |
flask jinja macros variable in url_for | 13,071,275 | 3 | 2012-10-25T14:50:31Z | 13,071,388 | 7 | 2012-10-25T14:56:38Z | [
"python",
"flask",
"jinja2",
"jinja"
] | I have a flask app with a jinja macro that looks like that
```
{% macro icon(site, title="") %}
<img src="{{ url_for('static', filename="icons/XXX.png") }}" alt="{{ title }}" class="img-icon">
{% endmacro %}
```
What I need to do is have the filename equals to the `site` variable passed to the macro. so instead o... | This should work:
```
{% macro icon(site, title="") %}
<img src="{{ url_for('static', filename='icons/%s.png' % site) }}" alt="{{ title }}" class="img-icon">
{% endmacro %}
``` |
Python - Ceil a datetime to next quarter of an hour | 13,071,384 | 11 | 2012-10-25T14:56:25Z | 13,071,569 | 7 | 2012-10-25T15:05:24Z | [
"python",
"math",
"datetime",
"ceil"
] | Let's imagine this datetime
```
>>> import datetime
>>> dt = datetime.datetime(2012, 10, 25, 17, 32, 16)
```
I'd like to ceil it to the next quarter of hour, in order to get
```
datetime.datetime(2012, 10, 25, 17, 45)
```
I imagine something like
```
>>> quarter = datetime.timedelta(minutes=15)
>>> import math
>>>... | ```
def ceil(dt):
if dt.minute % 15 or dt.second:
return dt + datetime.timedelta(minutes = 15 - dt.minute % 15,
seconds = -(dt.second % 60))
else:
return dt
```
This gives you:
```
>>> ceil(datetime.datetime(2012,10,25, 17,45))
datetime.datetime(2012, 10,... |
Python - Ceil a datetime to next quarter of an hour | 13,071,384 | 11 | 2012-10-25T14:56:25Z | 13,071,613 | 12 | 2012-10-25T15:07:46Z | [
"python",
"math",
"datetime",
"ceil"
] | Let's imagine this datetime
```
>>> import datetime
>>> dt = datetime.datetime(2012, 10, 25, 17, 32, 16)
```
I'd like to ceil it to the next quarter of hour, in order to get
```
datetime.datetime(2012, 10, 25, 17, 45)
```
I imagine something like
```
>>> quarter = datetime.timedelta(minutes=15)
>>> import math
>>>... | This one takes microseconds into account!
```
import math
def ceil_dt(dt):
# how many secs have passed this hour
nsecs = dt.minute*60 + dt.second + dt.microsecond*1e-6
# number of seconds to next quarter hour mark
# Non-analytic (brute force is fun) way:
# delta = next(x for x in xrange(0,36... |
Transforming Pandas dataframe | 13,072,259 | 6 | 2012-10-25T15:41:32Z | 13,072,686 | 11 | 2012-10-25T16:06:06Z | [
"python",
"pandas"
] | I'm having a little trouble with this maybe someone could direct me in the right direction here.
Suppose I have a data frame that looks as follows (actual dataset has many more entries and idents):
```
open ident
2011-01-01 00:00:00 -1.252090 df1
2011-01-01 01:00:00 -1.427444 df1
2011-01-... | You can use the `pivot` function:
```
df.pivot(index='date', columns='variable', values='value')
```
For more info see: <http://pandas.pydata.org/pandas-docs/stable/reshaping.html> |
How to mock python's datetime.now() in a class method for unit testing? | 13,073,281 | 21 | 2012-10-25T16:41:23Z | 13,073,350 | 16 | 2012-10-25T16:46:01Z | [
"python",
"django",
"unit-testing",
"testing",
"mocking"
] | I'm trying to write tests for a class that has methods like:
```
import datetime
import pytz
class MyClass:
def get_now(self, timezone):
return datetime.datetime.now(timezone)
def do_many_things(self, tz_string='Europe/London'):
tz = pytz.timezone(tz_string)
localtime_now = self.get_n... | You'd create a function that returns a specific datetime, localized to the timezone passed in:
```
import mock
def mocked_get_now(timezone):
dt = datetime.datetime(2012, 1, 1, 10, 10, 10)
return timezone.localize(dt)
@mock.patch('path.to.your.models.MyClass.get_now', side_effect=mocked_get_now)
def your_test... |
How to mock python's datetime.now() in a class method for unit testing? | 13,073,281 | 21 | 2012-10-25T16:41:23Z | 30,169,148 | 14 | 2015-05-11T13:36:22Z | [
"python",
"django",
"unit-testing",
"testing",
"mocking"
] | I'm trying to write tests for a class that has methods like:
```
import datetime
import pytz
class MyClass:
def get_now(self, timezone):
return datetime.datetime.now(timezone)
def do_many_things(self, tz_string='Europe/London'):
tz = pytz.timezone(tz_string)
localtime_now = self.get_n... | You could use [freezegun](https://github.com/spulec/freezegun) :
```
from freezegun import freeze_time
def test():
assert datetime.datetime.now() != datetime.datetime(2012, 01, 14)
with freeze_time("2012-01-14"):
assert datetime.datetime.now() == datetime.datetime(2012, 01, 14)
assert datetime.dat... |
Java and python ^ operator | 13,073,957 | 3 | 2012-10-25T17:25:13Z | 13,073,997 | 15 | 2012-10-25T17:27:45Z | [
"java",
"python",
"operators"
] | For a CompSci class, we were reviewing the Java Math class. Being the foolish programmer that I am, I tried using the ^ operator instead of the Math.pow function. Surprise, Surprise, it did not work. But, what Java spit out, is my question. I am trying to figure out the operation that is being done with the numbers. Yo... | This is a *bitwise* operation, and thus it operates on the binary bits of your numbers. 6 is `110` in binary form. 5 is `101` in binary form.
```
110
101
=== (^ xor)
011
```
`011` is 3 in binary.
Read up on <https://en.wikipedia.org/wiki/Exclusive_or> |
TypeError 'x' object has no attribute '__getitem__' | 13,074,331 | 12 | 2012-10-25T17:51:11Z | 13,074,385 | 29 | 2012-10-25T17:54:17Z | [
"python",
"django",
"typeerror"
] | Im getting the error
> ```
> 'CampSite' object has no attribute '__getitem__'
> ```
when I save a new CampCon entry in the admin interface. I have one application called campsites that handles the database of campsites, and I have another application called content that handles reviews. I am very new to Django and th... | Your issue is that your `__unicode__` functions are returning model objects when they need to be returning unicode strings.
You can achieve this by adding the `unicode()` function to your `__unicode__` methods:
```
class CampCon(models.Model):
campsite = models.ForeignKey(CampSite)
trip = models.ForeignKey('T... |
Extracting selected columns from a table using BeautifulSoup | 13,074,586 | 7 | 2012-10-25T18:08:24Z | 13,074,920 | 16 | 2012-10-25T18:30:49Z | [
"python",
"html-parsing",
"beautifulsoup"
] | I am trying to extract the first and third columns of [this data table](http://www.samhsa.gov/data/NSDUH/2k10State/NSDUHsae2010/NSDUHsaeAppC2010.htm#tabC.7) using BeautifulSoup. From looking at the HTML the first column has a `<th>` tag. The other column of interest has as `<td>` tag. In any case, all I've been able to... | You can try this code:
```
import urllib2
from BeautifulSoup import BeautifulSoup
url = "http://www.samhsa.gov/data/NSDUH/2k10State/NSDUHsae2010/NSDUHsaeAppC2010.htm"
soup = BeautifulSoup(urllib2.urlopen(url).read())
for row in soup.findAll('table')[0].tbody.findAll('tr'):
first_column = row.findAll('th')[0].con... |
Catching exception in context manager __enter__() | 13,074,847 | 13 | 2012-10-25T18:25:56Z | 13,075,071 | 11 | 2012-10-25T18:38:44Z | [
"python",
"exception",
"python-2.7",
"with-statement",
"contextmanager"
] | Is it possible to ensure the `__exit__()` method is called even if there is an exception in `__enter__()`?
```
>>> class TstContx(object):
... def __enter__(self):
... raise Exception('Oops in __enter__')
...
... def __exit__(self, e_typ, e_val, trcbak):
... print "This isn't running"
...
>>> with... | Like this:
```
import sys
class Context(object):
def __enter__(self):
try:
raise Exception("Oops in __enter__")
except:
# Swallow exception if __exit__ returns a True value
if self.__exit__(*sys.exc_info()):
pass
else:
... |
default value of parameter as result of instance method | 13,075,044 | 8 | 2012-10-25T18:37:47Z | 13,075,096 | 15 | 2012-10-25T18:40:28Z | [
"python"
] | I would like to initialize method parameter by some default value, if explicit value was not passing in the method. Something like this:
```
class Example
def __init__(self, data = self.default_data()):
self.data = data
def default_data():
# ....
return something
```
But I get the error:
```... | The common idiom here is to set the default to some sentinel value (`None` is typical, although [some have suggested `Ellipsis`](http://stackoverflow.com/questions/6185475/custom-placeholder-like-none-in-python/6186450#6186450) for this purpose) which you can then check.
```
class Example(object): #inherit from object... |
Move "help" to a different Argument Group in python argparse | 13,075,241 | 18 | 2012-10-25T18:50:05Z | 13,075,485 | 19 | 2012-10-25T19:06:17Z | [
"python",
"argparse"
] | Currently I'm creating a directory reader program using Python.
I'm using 'argparse' to parse the arguments from command line. I have the following code:
```
parser = argparse.ArgumentParser(prog = "LS.py",
usage = "%(prog)s [options] [path1 [path2 [...pathN]]]\nThe paths are optional;... | You can use `add_help=False` to disable the built-in help command and add your own instead, using `action="help"` (thanks @mgilson!)
To get rid of the spaces, don't set `metavar` to an empty string. Your options should be specified using `action="store_true"` to make them true (argument-less) options:
```
import argp... |
typeerror 'builtin_function_or_method' object has no attribute '__getitem__' | 13,075,632 | 15 | 2012-10-25T19:16:59Z | 13,075,688 | 46 | 2012-10-25T19:20:02Z | [
"python",
"typeerror"
] | Here's the code:
```
The_Start = [1,1]
The_End = [1, 1]
for z in range(20):
for x in range(len(The_Start) - 1):
y = The_Start[x] + The_Start[x + 1]
The_End.insert[x + 1, y]
print The_End
The_Start = The_End
The_End = [1, 1]
```
This code is supposed to make a Pascal's triangle. The er... | You need to change the brackets in `The_End.insert[x + 1, y]` to parenthesis.
```
The_End.insert(x + 1, y)
```
It's good practice in Python to use lowercase variable names. Uppercase is generaly used for classes. |
typeerror 'builtin_function_or_method' object has no attribute '__getitem__' | 13,075,632 | 15 | 2012-10-25T19:16:59Z | 13,075,703 | 10 | 2012-10-25T19:21:09Z | [
"python",
"typeerror"
] | Here's the code:
```
The_Start = [1,1]
The_End = [1, 1]
for z in range(20):
for x in range(len(The_Start) - 1):
y = The_Start[x] + The_Start[x + 1]
The_End.insert[x + 1, y]
print The_End
The_Start = The_End
The_End = [1, 1]
```
This code is supposed to make a Pascal's triangle. The er... | You need parenthesis instead of `[]`:
```
The_End.insert(x + 1, y)
``` |
ASCII art in Python [UPDATED] | 13,076,194 | 16 | 2012-10-25T19:54:35Z | 13,076,368 | 13 | 2012-10-25T20:05:03Z | [
"python",
"ascii"
] | I'm pretty new to python, picked it up as an hobby interest, and through some searching found myself a bunch of exercises from "*The Practice of computing*", one of them asks about writing an ASCII figure, like the one denoted below.

It all seems like an easy enough ... | Think about the difference between 1 and 2. Try to draw by hand what 3 and 4 should look like to make the sequence work. Think about it like one of those problems where you are given the start of a sequence and you have to work our the rest.
Like:
0 1 1 2 3 5 8 13
If you don't recognize that right off, it is the Fib... |
Get the indexes of truthy elements of a boolean list as a list/tuple | 13,076,560 | 5 | 2012-10-25T20:16:21Z | 13,076,574 | 11 | 2012-10-25T20:17:44Z | [
"python",
"json",
"list"
] | Given a boolean list such as `[True, False, False, True, False, True]`, what is the *quickest* way to get a list/tuple containing the indexes (starting from 1, not zero-indexed) of the Truthy elements in the original list? So for the list above, it should returns `[1, 4, 6]` or `(1, 4, 6)`.
I was using a generator lik... | ```
[i for i, elem in enumerate(bool_list, 1) if elem]
``` |
How do I create a Tiling layout / Flow layout in TkInter? | 13,076,668 | 5 | 2012-10-25T20:24:01Z | 13,076,829 | 7 | 2012-10-25T20:35:05Z | [
"python",
"tkinter",
"tk",
"flowlayout"
] | I want to to fill my window with, say, labels and I want them to wrap once the column would be bigger than the current window (or rather parent frame) size.
I've tried using the `grid` layout, but then I have to calculate the size of the content of each row myself, to know when to put the next element in the next row.... | What I do when I want something like this is use the text widget for a container. The text widget can have embedded widgets, and they wrap just like text. As long as your widgets are all the same height the effect is pretty nice.
For example (cut and pasted from the question at the author's request):
```
textwidget =... |
PyMongo import Connection - causes ImportError | 13,077,446 | 4 | 2012-10-25T21:18:49Z | 13,085,050 | 12 | 2012-10-26T10:19:46Z | [
"python",
"mongodb",
"import",
"pymongo"
] | I'm calling the following simple script to connect to a mongo database via Python.
This is an example from the [10gen education course M101 - MongoDB for Developers](https://education.10gen.com/courses/10gen/M101/2012_Fall/about),
and according to the forums I'm not the only person who has this issue.
```
import pymo... | Make sure there are no files called `pymongo.py` or `pymongo.pyc` in the path you are executing the script from. I named my test script `pymongo.py`, which caused Python to try and import Connection from that same file. Renaming it to `pymongo-test.py` and removing the automatically created `pymongo.pyc` solved the iss... |
Is there a numpy.delete() equivalent for sparse matrices? | 13,077,527 | 13 | 2012-10-25T21:24:32Z | 13,078,768 | 11 | 2012-10-25T23:21:58Z | [
"python",
"numpy",
"scipy"
] | Let's say I have a 2-dimensional matrix as a numpy array. If I want to delete rows with specific indices in this matrix, I use [`numpy.delete()`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.delete.html?highlight=delete#numpy.delete). Here is an example of what I mean:
```
In [1]: my_matrix = numpy.array(... | For CSR, this is probably the most efficient way to do it in-place:
```
def delete_row_csr(mat, i):
if not isinstance(mat, scipy.sparse.csr_matrix):
raise ValueError("works only for CSR format -- use .tocsr() first")
n = mat.indptr[i+1] - mat.indptr[i]
if n > 0:
mat.data[mat.indptr[i]:-n] =... |
How do I remove the last character of an R-T-L string in python? | 13,078,327 | 6 | 2012-10-25T22:31:12Z | 13,078,474 | 8 | 2012-10-25T22:45:52Z | [
"python",
"string",
"unicode",
"right-to-left"
] | I am trying to remove the last character of a string in a "right-to-left" language. When I do, however, the last character wraps to the beginning of the string.
e.g.
`×תֵ××Ö¶×]×`
becomes
`×תֵ××Ö¶×]`
I know that this is a fundamental issue with how I'm handling the R-T-L paradigm, but if someone could help... | Some characters in Unicode are always LTR, some are always RTL, and some can be either depending on their surrounding context. In addition, the display context for bidirectional text will have a "predominant" directionality (e.g. a text editor configured for mainly-English text would be predominantly LTR and have a rag... |
Merge Columns within a DataFrame that have the Same Name | 13,078,751 | 5 | 2012-10-25T23:19:21Z | 13,083,900 | 10 | 2012-10-26T09:02:36Z | [
"python",
"pandas"
] | If I have a dataframe that has columns that include the same name, is there a way to combine the columns that have the same name with some sort of function (i.e. sum)?
For instance with:
```
In [186]:
df["NY-WEB01"].head()
Out[186]:
NY-WEB01 NY-WEB01
DateTime
2012-10-18 16:00:00 5.6 2.8
2012-10-18 17... | I believe this does what you are after:
```
df.groupby(lambda x:x, axis=1).sum()
```
Alternatively, between 3% and 15% faster depending on the length of the df:
```
df.groupby(df.columns, axis=1).sum()
```
EDIT: To extend this beyond sums, use `.agg()` (short for `.aggregate()`):
```
df.groupby(df.columns, axis=1)... |
Switching user in Fabric | 13,080,643 | 17 | 2012-10-26T04:16:49Z | 13,092,755 | 10 | 2012-10-26T18:56:00Z | [
"python",
"fabric"
] | I have a problem when using Fabric to mimic my SSH workflow to deploy my web application.
Here's my usual flow of commands when I SSH to a server:
1. SSH using root user. ssh root@1.2.3.4
2. Switch to web user: su - web
3. Change directory: cd /srv/web/prod/abc\_project
4. Start virtualenv: workon abc\_env
5. Perform... | First of all, you should use `sudo` when executing commands under another user. Second, `workon` sets environment variables for current shell. Since fabric invokes new shell for every command, you should run `workon rhino_env` in every command, where you need virtualenv (i.e. as prefix). With this edits yor code should... |
The difference between three single quote'd and three double quote'd docstrings in python | 13,081,178 | 4 | 2012-10-26T05:22:53Z | 13,081,214 | 7 | 2012-10-26T05:26:19Z | [
"python"
] | I was just wondering what is the difference between two ways of writing python docstrings (`__doc__`):
1. three single quotes:
```
'''
Comment goes here
'''
```
2. three double quotes:
```
"""
Comment goes here
"""
```
Is there any subtle difference in the way doc string could be forma... | No. They are the same. The only difference is that the first one can contain a sequence of three unescaped double quotes, while the second can contain a sequence of three unescaped single quotes. (In other words, because the delimiters are different, there is a slight difference in what characters you can use inside th... |
How to return json using Flask web framework | 13,081,532 | 107 | 2012-10-26T05:56:47Z | 13,081,686 | 56 | 2012-10-26T06:11:55Z | [
"python",
"json",
"flask",
"web-frameworks"
] | My aim is to do data summary in python using Pandas and return the summary in the form of JSON. I am using the Flask web framework to return JSON.
My code to get JSON is as follows:(excluding libraries)
```
data = pandas.read_csv('D:\myfile.csv')
for colname, dtype in data.dtypes.to_dict().iteritems():
if dtype =... | See the documentation of: [flask.jsonify](http://flask.pocoo.org/docs/0.10/api/#flask.json.jsonify)
```
@app.route('/_get_current_user')
def get_current_user():
return jsonify(username=g.user.username,
email=g.user.email,
id=g.user.id)
```
Returns:
```
{
"username": "adm... |
How to return json using Flask web framework | 13,081,532 | 107 | 2012-10-26T05:56:47Z | 13,089,975 | 166 | 2012-10-26T15:33:57Z | [
"python",
"json",
"flask",
"web-frameworks"
] | My aim is to do data summary in python using Pandas and return the summary in the form of JSON. I am using the Flask web framework to return JSON.
My code to get JSON is as follows:(excluding libraries)
```
data = pandas.read_csv('D:\myfile.csv')
for colname, dtype in data.dtypes.to_dict().iteritems():
if dtype =... | If `f` is your dictionary, you can just do
```
return flask.jsonify(**f)
``` |
How to return json using Flask web framework | 13,081,532 | 107 | 2012-10-26T05:56:47Z | 20,405,740 | 8 | 2013-12-05T16:44:35Z | [
"python",
"json",
"flask",
"web-frameworks"
] | My aim is to do data summary in python using Pandas and return the summary in the form of JSON. I am using the Flask web framework to return JSON.
My code to get JSON is as follows:(excluding libraries)
```
data = pandas.read_csv('D:\myfile.csv')
for colname, dtype in data.dtypes.to_dict().iteritems():
if dtype =... | It looks like no one answered how to identify the filename in your /summary route. It looks like you want the user to input a csv file and return a summary via json. The Flask [Quickstart](http://flask.pocoo.org/docs/quickstart/) guide shows how to get files from users and access them. Briefly, you need to use the requ... |
How to return json using Flask web framework | 13,081,532 | 107 | 2012-10-26T05:56:47Z | 26,961,568 | 53 | 2014-11-16T20:16:47Z | [
"python",
"json",
"flask",
"web-frameworks"
] | My aim is to do data summary in python using Pandas and return the summary in the form of JSON. I am using the Flask web framework to return JSON.
My code to get JSON is as follows:(excluding libraries)
```
data = pandas.read_csv('D:\myfile.csv')
for colname, dtype in data.dtypes.to_dict().iteritems():
if dtype =... | `jsonify` is the right way of doing this but if you want to have full control of how your data will be serialized to JSON you can build yourself response (with `status=200` and `mimetype="application/json"`)
```
from flask import Flask, Response,
dat = ... # your JSON serialized data
resp = Response(response=dat,
... |
Is there any benefit to pyc files in a WSGI app where deployments happen several times per week? | 13,081,659 | 2 | 2012-10-26T06:09:31Z | 13,081,746 | 7 | 2012-10-26T06:16:29Z | [
"python",
"django",
"wsgi",
"pyc"
] | Seems like with ever increasing frequency, I am bit by pyc files running outdated code.
This has led to deployment scripts scrubbing \*.pyc each time, otherwise deployments don't seem to take effect.
I am wondering, what benefit (if any) is there to pyc files in a long-running WSGI application? So far as I know, the ... | The best strategy for doing deployments is to write the deployed files into a new directory, and then use a symlink or similar to swap the codebase over in a single change. This has the side-benefit of also automatically clearing any old `.pyc` files.
That way, you get the best of both worlds - clean and atomic deploy... |
How can I print a float with thousands separators? | 13,082,620 | 8 | 2012-10-26T07:26:58Z | 13,082,684 | 13 | 2012-10-26T07:31:47Z | [
"python",
"format",
"decimal"
] | How can I format a decimal number so that `32757121.33` will display as `32.757.121,33`? | Use [`locale.format()`](http://docs.python.org/library/locale.html#locale.format):
```
>>> import locale
>>> locale.setlocale(locale.LC_ALL, 'German')
'German_Germany.1252'
>>> print(locale.format('%.2f', 32757121.33, True))
32.757.121,33
```
You can restrict the locale changes to the display of numeric values (when ... |
Rounding down integers to nearest multiple | 13,082,698 | 8 | 2012-10-26T07:32:36Z | 13,082,705 | 25 | 2012-10-26T07:33:21Z | [
"python"
] | Is there a function in Python that allows me to round down to the nearest multiple of an integer?
```
round_down(19,10)=10
round_down(19,5)=15
round_down(10,10)=10
```
I conscientiously looked at SO and found nothing related to rounding ***down*** to a nearest base. Please keep this in mind before you post links to r... | ```
def round_down(num, divisor):
return num - (num%divisor)
In [2]: round_down(19,10)
Out[2]: 10
In [3]: round_down(19,5)
Out[3]: 15
In [4]: round_down(10,10)
Out[4]: 10
``` |
Slicing a string repeatedly | 13,083,681 | 8 | 2012-10-26T08:47:33Z | 13,083,741 | 12 | 2012-10-26T08:51:26Z | [
"python"
] | Repeated slicing works on tuples and lists just fine:
```
>>> tuple = ("nav", "yad")
>>> tuple[0]
'nav'
>>> tuple[0][0]
'n'
```
But with strings:
```
>>> name="university"
>>> name[0]
'u'
```
The weird thing here is, when I try repeated slicing over string name variable,
there is nothing at `name[0][0]` or `name[0]... | String is a sequence. String of one character is still a sequence with one element. So with a string you can do `name[0][0][0][0]...` and it will work fine. Same with index `-1`, that returns last element of a sequence:
```
>>> name[0][0]
'u'
>>> name[0][0][-1]
'u'
>>> name[0][0][-1][-1]
'u'
```
`name[0][1]` obviousl... |
First items in inner list efficiently as possible | 13,084,619 | 4 | 2012-10-26T09:50:22Z | 13,084,647 | 7 | 2012-10-26T09:52:04Z | [
"python",
"list",
"optimization",
"performance"
] | I have a coordinated storage list in python `A[row,col,value]` for storing non-zeros values.
How can I get the list of all the row indexes? I expected this `A[0:][0]` to work as `print A[0:]` prints the whole list but `print A[0:][0]` only prints `A[0]`.
The reason I ask is for efficient calculation of the number of ... | This should do it:
```
c = [x[0] for x in A]
```
It's a list comprehension that takes the first (sub-)element of every element of `A`. |
df.head() sometimes doesn't work in Pandas, Python | 13,085,709 | 13 | 2012-10-26T11:02:58Z | 13,086,305 | 14 | 2012-10-26T11:43:09Z | [
"python",
"pandas"
] | I'm a beginner in Python and the Pandas library, and I'm rather confused by some basic functionality of data frame. I've got a pandas dataframe as below:
```
>>>df.head()
X Y unixtime
0 652f5e69fcb3 1 1346689910622
1 400292 1 1346614723542
2 1c9d02e4f14e 1 1346862070161
3 6... | `df.head(n)` returns a `DataFrame` holding the first n rows of df.
Now to display a `DataFrame` pandas checks by default the width of the terminal, if this is too small to display the `DataFrame` a summary view will be shown. Which is what you get in the second case.
Could you increase the size of your terminal, or di... |
Is it a good practice to create a new `virtualenv` each time I start building a new Flask app? | 13,086,960 | 2 | 2012-10-26T12:30:50Z | 13,089,693 | 9 | 2012-10-26T15:17:41Z | [
"python",
"flask",
"virtualenv"
] | This is how I started my first `virtualenv` for my Flask app:
```
$ virtualenv flask_env
$ source flask_env/bin/activate
(flask_env) $ pip install Flask
```
This is my first time working with this. Is it a good practice to create a new `virtualenv` each time I start building a new Flask app? | Short answer: Yes.
Longer answer: It's a bit of personal question as to how you want to work. I think you'll find that as you build more apps, each one will have different dependencies. Maybe for one app you'll want to use wtforms. Maybe for another app you'll use requests. Maybe for a third, you'll need flask-sqlalch... |
python function default parameter is evaluated only once? | 13,087,344 | 12 | 2012-10-26T12:56:11Z | 13,087,455 | 10 | 2012-10-26T13:03:25Z | [
"python",
"function",
"parameters"
] | I am a python beginner, reading 'python tutorial', it says if we have a function:
```
def f(a, L=[]):
L.append(a)
return L
print f(1)
print f(2)
print f(3)
```
This will print
```
[1]
[1, 2]
[1, 2, 3]
```
Because the default value is evaluated only once and list is a mutable object. I can understand it.
... | "The default value is only evaluated once" does not mean that a parameter with a default retains its value between invocations of the function. It means that the expression which you specify (the `None` part of `def f(a, L=None)`) is evaluated once, and the object it results in is stored in a hidden location and re-use... |
Homebrew , python installing | 13,088,998 | 27 | 2012-10-26T14:37:16Z | 13,089,188 | 75 | 2012-10-26T14:47:51Z | [
"python",
"osx",
"osx-snow-leopard",
"homebrew"
] | i got an error while trying to install python throught homebrew. brew says what it failed to link python , here is output:
```
Linking /usr/local/Cellar/python/2.7.3... Warning: Could not link python. Unlinking...
Error: Could not symlink file: /usr/local/Cellar/python/2.7.3/bin/smtpd2.py
/usr/local/bin/smtpd2.py may ... | Sounds like a permissions issue with /usr/local.
```
### Makes you owner of /usr/local
$ sudo chown -R `whoami` /usr/local
### Force uninstalls failed python
$ brew uninstall -f python
### Clear the brew cache
$ rm -rf `brew --cache`
### Recreate the brew cache
$ mkdir `brew --cache`
### Cleanup - cleans up old h... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.