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 |
|---|---|---|---|---|---|---|---|---|---|
BeautifulSoup findAll() given multiple classes? | 18,725,760 | 14 | 2013-09-10T17:53:22Z | 18,726,009 | 21 | 2013-09-10T18:08:06Z | [
"python",
"html",
"beautifulsoup",
"html-parsing"
] | I would like to scrape a list of items from a website, and preserve the order that they are presented in. These items are organized in a table, but they can be one of two different classes (in random order).
Is there any way to provide multiple classes and have BeautifulSoup4 find all items which are in any of the giv... | you can do this
```
soup.findAll(True, {'class':['class1', 'class2']})
```
example:
```
>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup('<html><body><div class="class1"></div><div class="class2"></div><div class="class3"></div></body></html>')
>>> soup.findAll(True, {"class":["class1", "class2"]})
[<div c... |
Fetch table values using alembic and update to another table. | 18,726,527 | 11 | 2013-09-10T18:40:47Z | 18,739,259 | 15 | 2013-09-11T10:56:03Z | [
"python",
"sqlalchemy",
"alembic"
] | I have `oauth secret` and `oauth key` in `client` table. Now I moving them to `oauth credentials` table which will be created during migration. Alembic produced following schema for upgrade.
```
from myapp.models import Client, ClientCredential
from alembic import op
import sqlalchemy as sa
def upgrade():
### comman... | Finally I solved the problem. Created raw sql to fetch the values and used `bulk_insert`.
```
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.create_table('client_credential',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('created_at', sa.DateTime(), nullable=Fa... |
random is not defined in python | 18,727,556 | 10 | 2013-09-10T19:46:23Z | 18,727,568 | 25 | 2013-09-10T19:47:13Z | [
"python"
] | I'm trying to produce a random integer `n`, and create a list of n random integers with values between 0 and 9.
Here is my code:
```
def randomNumbers(n):
myList = []
needMoreNumbers = True
while (needMoreNumbers):
randomNumber = int(random.random() * 10)
myList.append(randomNumber)
... | You haven't imported `random` module. Add this to the top of your script:
```
import random
``` |
Numpy: averaging many datapoints at each time step | 18,727,686 | 3 | 2013-09-10T19:54:18Z | 18,728,217 | 9 | 2013-09-10T20:30:22Z | [
"python",
"numpy",
"matplotlib",
"scipy"
] | This question is probably answered somewhere, but I cannot find where, so I will ask here:
I have a set of data consisting of several samples per timestep. So, I basically have two arrays, "times", which looks something like: (0,0,0,1,1,1,1,1,2,2,3,4,4,4,4,...) and my data which is the value for each time. Each timest... | A generic code to do this would do something as follows:
```
def average_values_bis(x, y):
unq_x, idx = np.unique(x, return_inverse=True)
count_x = np.bincount(idx)
sum_y = np.bincount(idx, weights=y)
return unq_x, sum_y / count_x
```
Adding the function above and following line for the plotting to y... |
Upload Images to Amazon S3 using Django | 18,729,026 | 4 | 2013-09-10T21:27:52Z | 18,731,115 | 12 | 2013-09-11T01:03:34Z | [
"python",
"django",
"amazon-s3",
"boto"
] | I'm currently resizing images on the fly when a user uploads a picture. The original picture is stored on Amazon S3 in a bucket called djangobucket. Inside this bucket, contains thousands of folders.
Each folder is named after the user. I don't have to worry about bucket creation or folder creation since all of that i... | `boto` is the best way to do this.
You can get an existing bucket using:
```
get_bucket(bucket_name, validate=True, headers=None)
```
After installing boto, this code should do what you need to do
```
from boto.s3.connection import S3Connection
from boto.s3.key import Key
conn = S3Connection('<aws access key>', '<... |
Converting two lists into a matrix | 18,730,044 | 9 | 2013-09-10T22:55:30Z | 18,730,323 | 15 | 2013-09-10T23:25:03Z | [
"python",
"arrays",
"numpy",
"matrix"
] | I'll try to be as clear as possible, and I'll start by explaining why I want to transform two arrays into a matrix.
To plot the performance of a portfolio vs an market index I need a data structure like in this format:
```
[[portfolio_value1, index_value1]
[portfolio_value2, index_value2]]
```
But I have the the da... | The standard numpy function for what you want is `np.column_stack`:
```
>>> np.column_stack(([1, 2, 3], [4, 5, 6]))
array([[1, 4],
[2, 5],
[3, 6]])
```
So with your `portfolio` and `index` arrays, doing
```
np.column_stack((portfolio, index))
```
would yield something like:
```
[[portfolio_value1, in... |
Python sum() function with list parameter | 18,730,299 | 10 | 2013-09-10T23:22:55Z | 18,730,347 | 35 | 2013-09-10T23:28:14Z | [
"python",
"list",
"int",
"sum",
"typeerror"
] | I am required to use the sum() function in order to sum the values in a list. Please note that this is DISTINCT from using a 'for' loop to add the numbers manually. I thought it would be something simple like the following, but I receive 'TypeError: 'int' object is not callable'.
```
numbers = [1, 2, 3]
numsum = (sum(... | Have you used the variable `sum` anywhere else? That would explain it.
```
>>> sum = 1
>>> numbers = [1, 2, 3]
>>> numsum = (sum(numbers))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
```
The name `sum` doesn't point to the function anymore now, it p... |
Installing numpy on Amazon EC2 | 18,732,250 | 8 | 2013-09-11T03:36:40Z | 25,456,990 | 10 | 2014-08-22T23:37:29Z | [
"python",
"numpy",
"amazon-ec2",
"pip",
"easy-install"
] | I am having trouble installing numpy on an Amazon EC2 server. I have tried using easy\_install, pip, pip inside a virtual env, pip inside another virtual env using python 2.7...
Every time I try, it fails with the error: `gcc: internal compiler error: Killed (program cc1)`, and then further down the line I get a bunch... | Requirements for installing Numpy
* c compiler (gcc)
* fortran compiler (gfortran)
* python header files (2.4.x - 3.2.x)
* Strongly recommended BLAS or LAPACK
I wrote a script to [install virtualenv and scikit-learn](https://gist.github.com/dacamo76/4780765) along with all the dependencies. You can follow up to the n... |
What is the quickest way to get a number with unique digits in python? | 18,732,297 | 8 | 2013-09-11T03:42:01Z | 18,732,321 | 7 | 2013-09-11T03:44:48Z | [
"python",
"performance"
] | Lemme clarify:
What would be the fastest way to get every number with all unique digits between two numbers. For example, 10,000 and 100,000.
Some obvious ones would be 12,345 or 23,456. I'm trying to find a way to gather all of them.
```
for i in xrange(LOW, HIGH):
str_i = str(i)
...?
``` | Cheap way to do this:
```
for i in xrange(LOW, HIGH):
s = str(i)
if len(set(s)) == len(s):
# number has unique digits
```
This uses a `set` to collect the unique digits, then checks to see that there are as many unique digits as digits in total. |
What is the quickest way to get a number with unique digits in python? | 18,732,297 | 8 | 2013-09-11T03:42:01Z | 18,732,389 | 15 | 2013-09-11T03:53:33Z | [
"python",
"performance"
] | Lemme clarify:
What would be the fastest way to get every number with all unique digits between two numbers. For example, 10,000 and 100,000.
Some obvious ones would be 12,345 or 23,456. I'm trying to find a way to gather all of them.
```
for i in xrange(LOW, HIGH):
str_i = str(i)
...?
``` | Use [`itertools.permutations`](http://docs.python.org/2/library/itertools.html#itertools.permutations):
```
from itertools import permutations
result = [
a * 10000 + b * 1000 + c * 100 + d * 10 + e
for a, b, c, d, e in permutations(range(10), 5)
if a != 0
]
```
I used the fact, that:
* numbers between `... |
Getting attribute's value using BeautifulSoup | 18,733,023 | 5 | 2013-09-11T05:03:21Z | 18,737,759 | 14 | 2013-09-11T09:42:26Z | [
"python",
"python-2.7",
"beautifulsoup"
] | I'm writing a python script which will extract the script locations after parsing from a webpage.
Lets say there are two scenarios :
```
<script type="text/javascript" src="http://example.com/something.js"></script>
```
and
```
<script>some JS</script>
```
I'm able to get the JS from the second scenario, that is wh... | It will get all the `src` values only if they are present. Or else it would skip that `<script>` tag
```
from bs4 import BeautifulSoup
import urllib2
url="http://rediff.com/"
page=urllib2.urlopen(url)
soup = BeautifulSoup(page.read())
sources=soup.findAll('script',{"src":True})
for source in sources:
print source['sr... |
Annoying message when opening windows from Python on OS X 10.8 | 18,733,965 | 9 | 2013-09-11T06:18:46Z | 21,567,601 | 9 | 2014-02-05T02:37:12Z | [
"python",
"osx",
"osx-mountain-lion"
] | Whenever I run a Python script that opens any kind of window on OS X 10.8, whether it's a GLUT window or a QT one or anything else, I get a message that looks like this:
```
2013-09-11 14:36:53.321 Python[3027:f07] ApplePersistenceIgnoreState: Existing state will not be touched. New state will be written to /var/folde... | Answering my own question, with thanks to @Steve Barnes for giving me a hint. It seems this problem can be solved with the terminal command
```
$ defaults write org.python.python ApplePersistenceIgnoreState NO
```
I am not sure exactly what this command does, but having done it some time ago I have observed no ill ef... |
Annoying message when opening windows from Python on OS X 10.8 | 18,733,965 | 9 | 2013-09-11T06:18:46Z | 22,467,012 | 10 | 2014-03-17T22:47:01Z | [
"python",
"osx",
"osx-mountain-lion"
] | Whenever I run a Python script that opens any kind of window on OS X 10.8, whether it's a GLUT window or a QT one or anything else, I get a message that looks like this:
```
2013-09-11 14:36:53.321 Python[3027:f07] ApplePersistenceIgnoreState: Existing state will not be touched. New state will be written to /var/folde... | The correct command to run is:
```
defaults write org.python.python ApplePersistenceIgnoreState NO
```
This message appears due to the "application resume" feature in newer versions of OS X. Clearly, this isn't a useful feature for most Python programs (in my case, plotting data with matplotlib), so we can just turn ... |
does scikit-lean decision tree support unordered ('enum') multiclass features? | 18,734,183 | 4 | 2013-09-11T06:33:10Z | 18,736,132 | 9 | 2013-09-11T08:23:31Z | [
"python",
"scikit-learn",
"decision-tree"
] | From the [documentation](http://scikit-learn.org/stable/modules/tree.html#classification), it appears that `DecisionTreeClassifier` supports multiclass features
> DecisionTreeClassifier is capable of both binary (where the labels are [-1, 1]) classification and multiclass (where the labels are [0, ..., K-1]) classific... | The term multiclass only affects the target variable: for the random forest in scikit-learn it is either categorical with an integer coding for multiclass classification or continuous for regression.
"Greater-than" rules apply to the input variables independently of the kind of target variable. If you have categorical... |
Passing a function to re.sub in Python | 18,737,863 | 8 | 2013-09-11T09:47:28Z | 18,737,927 | 14 | 2013-09-11T09:50:06Z | [
"python",
"regex"
] | I have strings which contain a number somewhere in them and I'm trying to replace this number with their word notation (ie. 3 -> three). I have a function which does this. The problem now is finding the number inside the string, while keeping the rest of the string intact. For this, I opted to use the `re.sub` function... | You should call `group()` to get the matching string:
```
import re
number_mapping = {'1': 'one',
'2': 'two',
'3': 'three'}
s = "1 testing 2 3"
print re.sub(r'\d', lambda x: number_mapping[x.group()], s)
```
prints:
```
one testing two three
``` |
Control the size TextArea widget look in django admin | 18,738,486 | 20 | 2013-09-11T10:17:19Z | 18,738,715 | 21 | 2013-09-11T10:27:53Z | [
"python",
"css",
"django",
"django-admin"
] | I managed to override the look of a `TextArea` Widget in the django admin interface with two different ways:
### using formfield\_overrides
in `admin.py`:
```
class RulesAdmin(admin.ModelAdmin):
formfield_overrides = {
models.TextField: {'widget': Textarea(
attrs={'rows': 1,
... | This is a browser-specific problem.
According to the thread [Height of textarea does not match the rows in Firefox](http://stackoverflow.com/questions/7695945/height-of-textarea-does-not-match-the-rows-in-firefox):
> Firefox always adds an extra line after the textfield. If you want it
> to have a constant height, us... |
Python: How to get stdout after running os.system? | 18,739,239 | 39 | 2013-09-11T10:54:32Z | 18,739,828 | 50 | 2013-09-11T11:24:23Z | [
"python",
"python-2.7",
"stdout",
"stderr",
"os.system"
] | I want to get the `stdout` in a variable after running the `os.system` call.
Lets take this line as an example:
```
batcmd="dir"
result = os.system(batcmd)
```
`result` will contain the error code (`stderr` `0` under Windows or `1` under some linux for the above example).
How can I get the `stdout` for the above co... | If all you need is the `stdout` output, then take a look at [`subprocess.check_output()`](http://docs.python.org/2/library/subprocess.html#subprocess.check_output) (added in Python 2.7):
```
import subprocess
batcmd="dir"
result = subprocess.check_output(batcmd, shell=True)
```
Because you were using `os.system()`, ... |
Python: How to get stdout after running os.system? | 18,739,239 | 39 | 2013-09-11T10:54:32Z | 26,343,770 | 9 | 2014-10-13T15:38:42Z | [
"python",
"python-2.7",
"stdout",
"stderr",
"os.system"
] | I want to get the `stdout` in a variable after running the `os.system` call.
Lets take this line as an example:
```
batcmd="dir"
result = os.system(batcmd)
```
`result` will contain the error code (`stderr` `0` under Windows or `1` under some linux for the above example).
How can I get the `stdout` for the above co... | These answers didn't work for me. I had to use the following:
```
import subprocess
p = subprocess.Popen(["pwd"], stdout=subprocess.PIPE)
out = p.stdout.read()
print out
```
Or as a function (using shell=True was required for me on Python 2.6.7 and check\_output was not added until 2.7, making it unusable here):
```... |
Preventing PyQt to silence exceptions occurring in slots | 18,740,884 | 17 | 2013-09-11T12:13:12Z | 19,015,654 | 13 | 2013-09-25T21:41:36Z | [
"python",
"pyqt"
] | As far as I can see, if an exception occurs in a slot under PyQt, the exception is printed to screen, but not bubbled. This creates a problem in my testing strategy, because if an exception occurs in a slot, I will not see the test fail.
Here is an example:
```
import sys
from PyQt4 import QtGui, QtCore
class Test(Q... | Can create a decorator that wraps PyQt' new signal/slot decorators and provides exception handling for all slots. Can also override QApplication::notify to catch uncaught C++ exceptions.
```
import sys
import traceback
import types
from functools import wraps
from PyQt4 import QtGui, QtCore
def MyPyQtSlot(*args):
... |
Calculating minimum length among the lists inside a list | 18,741,633 | 2 | 2013-09-11T12:47:08Z | 18,741,679 | 7 | 2013-09-11T12:48:54Z | [
"python",
"list"
] | ```
a=[[1,0,1,2,1,1,1,3111111],[31,1,4,51,1,1,1],[1,1,6,7,8]]
print min(a[0],a[1],a[2])
```
The following code returns the `[1, 0, 1, 2, 1, 1, 1, 3111111]`. Not sure what is the default key and according to what logic is it returned?
Plus I was actually trying to find the minimum length out of these lists within a li... | Yes, you can use `map` to iterate over the inner lists to create a list of lengths, then get the minimum with `min`:
```
>>> a=[[1,0,1,2,1,1,1,3111111],[31,1,4,51,1,1,1],[1,1,6,7,8]]
>>> min(map(len, a))
5
``` |
Calculating minimum length among the lists inside a list | 18,741,633 | 2 | 2013-09-11T12:47:08Z | 18,741,701 | 7 | 2013-09-11T12:50:07Z | [
"python",
"list"
] | ```
a=[[1,0,1,2,1,1,1,3111111],[31,1,4,51,1,1,1],[1,1,6,7,8]]
print min(a[0],a[1],a[2])
```
The following code returns the `[1, 0, 1, 2, 1, 1, 1, 3111111]`. Not sure what is the default key and according to what logic is it returned?
Plus I was actually trying to find the minimum length out of these lists within a li... | A few options:
```
a = [[1,0,1,2,1,1,1,3111111], [31,1,4,51,1,1,1], [1,1,6,7,8]]
print min(a, key=len)
# [1, 1, 6, 7, 8]
print len(min(a, key=len))
# 5
print min(map(len, a))
# 5
``` |
How to alphabetically order a drop-down list in Django admin? | 18,742,632 | 4 | 2013-09-11T13:30:49Z | 18,742,744 | 9 | 2013-09-11T13:35:23Z | [
"python",
"django",
"order"
] | Here's a (very) simplified version of my models:
**laboratory/models.py**
```
class Lab(Model):
professor = ForeignKey('authors.Author')
```
**authors/models.py**
```
class Author(Model):
name = CharField(max_length=100)
```
In the Django admin, when I add or update a Lab, a drop-down list containing each ... | You can define default ordering for Author model:
```
class Author(Model):
name = CharField(max_length=100)
class Meta:
ordering = ('name',)
``` |
Execute Shell Script from python with variable | 18,742,657 | 7 | 2013-09-11T13:31:48Z | 18,742,753 | 12 | 2013-09-11T13:35:52Z | [
"python",
"variables",
"execute"
] | I have this code:
```
opts.info("Started domain %s (id=%d)" % (dom, domid))
```
I want to execute a shell script with the parameter `domid` from above.
Something like this:
```
subprocess.call(['test.sh %d', domid])
```
How does it work?
I've tried it with:
```
subprocess.call(['test.sh', domid])
```
But I get t... | Like this ?
```
subprocess.call(['test.sh', str(domid)])
```
Documentation is available on the [python website](http://docs.python.org/2/library/subprocess.html#subprocess.call) |
Django access to subclasses items from abstract class | 18,742,870 | 3 | 2013-09-11T13:40:24Z | 18,743,205 | 9 | 2013-09-11T13:55:28Z | [
"python",
"django"
] | ```
class Animal(models.Model):
....
class Meta:
abstract = True
class Cat(models.Model, Animal):
...
class Dog(models.Model, Animal):
....
```
I want to be able to return all instances of querysets of all the subclasses of Animal. Lets say I have a function called `allData` which returns an ... | This is not possible in one query. You have two options, one use to use [`django-model-utils`](https://django-model-utils.readthedocs.org/en/latest/managers.html#inheritancemanager) or you can use [`django_polymorphic`](https://github.com/chrisglass/django_polymorphic).
Polymorphic is better suited to your task, howev... |
Python send UDP packet | 18,743,962 | 11 | 2013-09-11T14:28:37Z | 18,746,406 | 25 | 2013-09-11T16:21:57Z | [
"python",
"sockets"
] | I am trying to write a program to send UDP packets, as in <https://wiki.python.org/moin/UdpCommunication> The code appears to be in Python 2:
```
import socket
UDP_IP = "127.0.0.1"
UDP_PORT = 5005
MESSAGE = "Hello, World!"
print "UDP target IP:", UDP_IP
print "UDP target port:", UDP_PORT
print "message:", MESSAGE
s... | With Python3x, you need to convert your string to raw bytes. You would have to encode the string as bytes. Over the network you need to send bytes and not characters. You are right that this would work for Python 2x since in Python 2x, socket.sendto on a socket takes a "plain" string and not bytes. Try this:
```
print... |
Comparing True False confusion | 18,745,958 | 3 | 2013-09-11T15:56:00Z | 18,746,055 | 14 | 2013-09-11T16:02:20Z | [
"python"
] | i have some confusion over testing values that are assigned False, True
To check for True value, we can simply just
```
a = True
if (a):
```
how about False?
```
a=False
if (a) <--- or should it be if (a==False), or if not a ?
```
thanks | From the [Python Style Guide](http://www.python.org/dev/peps/pep-0008/):
> For sequences, (strings, lists, tuples), use the fact that empty
> sequences are false.
```
Yes: if not seq:
if seq:
No: if len(seq)
if not len(seq)
```
> [..]
>
> Don't compare boolean values to True or False using ==.
```
Yes: if... |
Plotting arrows with different color in matplotlib | 18,748,328 | 5 | 2013-09-11T18:11:05Z | 18,748,959 | 8 | 2013-09-11T18:46:18Z | [
"python",
"matplotlib"
] | I have a two dimensional array with 5 columns and some number of rows. The different columns have the following entries`x1 y1 x2 y2 z`
I want to plot an arrow from (x1,y1) to (x2,y2) and the color of the arrow should be taken from z column corresponding to some inbuilt colormap.
How can I do this matplotlib/python? | You can do this:
```
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import matplotlib.cm as cmx
DATA = np.random.rand(5,5)
cmap = plt.cm.jet
cNorm = colors.Normalize(vmin=np.min(DATA[:,4]), vmax=np.max(DATA[:,4]))
scalarMap = cmx.ScalarMappable(norm=cNorm,cmap=cmap)
for idx... |
Concatenate strings if they have an overlapping region | 18,749,059 | 4 | 2013-09-11T18:53:07Z | 18,750,057 | 7 | 2013-09-11T19:53:05Z | [
"python",
"python-2.7",
"while-loop"
] | I am trying to write a script that will find strings that share an overlapping region of 5 letters at the beginning or end of each string (shown in example below).
```
facgakfjeakfjekfzpgghi
pgghiaewkfjaekfjkjakjfkj
kjfkjaejfaefkajewf
```
I am trying to create a ne... | Create a dictionary mapping the first 5 characters of each string to its tail
```
strings = {s[:5]: s[5:] for s in x}
```
and a set of all the suffixes:
```
suffixes = set(s[-5:] for s in x)
```
Now find the string whose prefix does not match any suffix:
```
prefix = next(p for p in strings if p not in suffixes)
`... |
The *args and **kwds in python super call | 18,751,910 | 8 | 2013-09-11T21:52:20Z | 18,752,039 | 8 | 2013-09-11T22:01:54Z | [
"python"
] | I am trying to understand the use of `*args` and `**kwds` when creating subclasses in Python.
I want to understand why this code behaves the way it does. If I leave out the `*args` and `**kwds` in a call to `super().__init__`, I get some strange argument unpacking.
Here is my test case:
```
class Animal(object):
... | In `Snake.__init__`, `args` is a tuple of all positional arguments after `poisonous` and `kwds` is a dict of all the keyword arguments apart from `poisonous`. By calling
```
super(Snake,self).__init__(args,kwds)
```
you assign `args` to `moves` and `kwds` to `num_legs` in `Animal.__init__`. Thatâs exactly what you ... |
Cannot install pycurl on Mac OS X - get errors 1 and 2 | 18,752,405 | 3 | 2013-09-11T22:34:09Z | 20,587,496 | 12 | 2013-12-14T19:46:35Z | [
"python",
"osx",
"curl",
"libcurl",
"pycurl"
] | I am attempting to install pycurl-7.19.0 on my Mac OSX 10.8.4.
The error I get when compiling:
```
py setup.py install
```
The results:
```
Using curl-config (libcurl 7.24.0)
running install
running build
running build_py
running build_ext
building 'pycurl' extension
clang -fno-strict-aliasing -fno-common -dynamic ... | This works for me on OSX 10.9
```
sudo env ARCHFLAGS="-arch x86_64" easy_install setuptools pycurl==7.19.0
``` |
Updating openssl in python 2.7 | 18,752,409 | 11 | 2013-09-11T22:34:53Z | 20,740,964 | 8 | 2013-12-23T09:53:29Z | [
"python",
"ssl",
"openssl"
] | wondering if someone may please explain how openssl works in python2.7.
I'm not sure if python got its own openssl or picks it up from local machine/env?
let me explain:
(if I do this in Python)
```
>>> import ssl
>>> ssl.OPENSSL_VERSION
'OpenSSL 0.9.8x 10 May 2012'
```
(In terminal)
```
$ openssl version
OpenSSL 0... | Outdated SSL is a common issue on multiple platforms:
Here's the general approach...
### 0. Install OpenSSL
* **Option I:** Install system packages of side-by-side OpenSSL 1.x libs (-dev or -devel) packages.
```
# FreeBSD
pkg install openssl
OPENSSL_ROOT=/usr/local
# Mac (brew)
brew install openssl ... |
Updating openssl in python 2.7 | 18,752,409 | 11 | 2013-09-11T22:34:53Z | 27,230,127 | 16 | 2014-12-01T14:06:48Z | [
"python",
"ssl",
"openssl"
] | wondering if someone may please explain how openssl works in python2.7.
I'm not sure if python got its own openssl or picks it up from local machine/env?
let me explain:
(if I do this in Python)
```
>>> import ssl
>>> ssl.OPENSSL_VERSION
'OpenSSL 0.9.8x 10 May 2012'
```
(In terminal)
```
$ openssl version
OpenSSL 0... | Please refer to <http://rkulla.blogspot.kr/2014/03/the-path-to-homebrew.html>
After upgrading openssl to 1.0.1j by homebrew on MAC, but system python still referred to old version 0.9.8. It turned out the python referred to openssl. So I have installed new python with brewed openssl and finished this issue on Mac, not... |
How to handle errors with imaplib in Python | 18,754,195 | 2 | 2013-09-12T02:07:32Z | 18,754,844 | 8 | 2013-09-12T03:28:28Z | [
"python",
"email",
"error-handling",
"imap"
] | I want to write error handling for wen a user would input a wrong password to my script. I keep changing the code after the except statement, but I can't find out what the right code for the error is. Am I missing something?
```
import imaplib
import email
mail = imaplib.IMAP4_SSL('imap.gmail.com')
username = raw_in... | If you want to catch a certain exception, the exception name in [`try...except`](http://docs.python.org/2/tutorial/errors.html#handling-exceptions) clause in Python should be written after `except` keyword:
```
try:
mail.login(username, password)
print "Logged in as %r !" % username
except imaplib.IMAP4.error:... |
Is `a<b<c` valid python? | 18,755,059 | 7 | 2013-09-12T03:53:41Z | 18,755,094 | 7 | 2013-09-12T03:56:30Z | [
"python"
] | I was curious to see if I could use this `a<b<c` as a conditional without using the standard `a<b and b<c`. So I tried it out and my test results passed.
```
a = 1
b = 2
c = 3
assert(a<b<c) # In bounds test
assert(not(b<a<c)) # Out of bounds test
assert(not(a<c<b)) # Out of bounds test
```
Just for good measure I tr... | This is documented [here](http://docs.python.org/2/reference/expressions.html#not-in).
> Formally, if a, b, c, ..., y, z are expressions and op1, op2, ..., opN
> are comparison operators, then a op1 b op2 c ... y opN z is equivalent
> to a op1 b and b op2 c and ... y opN z, except that each expression is
> evaluated a... |
parse a pdf using python | 18,755,412 | 3 | 2013-09-12T04:31:53Z | 18,755,644 | 8 | 2013-09-12T04:56:15Z | [
"python",
"pdf"
] | i have a pdf file. It contains of four columns and all the pages dont have gridlines. They are the marks of students.
I would like to run some analysis on this distribution.(histograms, line graphs etc).
I want to parse this pdf file into a Spreadsheet or an HTML file (which i can then parse very easily).
The link t... | Use [`PyPDF2`](https://github.com/colemana/PyPDF2):
```
from pyPdf import PdfFileReader
f = open('CT1-All.pdf', 'rb')
reader = PdfFileReader(f)
contents = reader.getPage(0).extractText().split('\n')
f.close()
```
When you print `contents`, it will look like this (I have trimmed it here):
```
[u'Serial NoRoll NoName... |
Printing with indentation in python | 18,756,510 | 9 | 2013-09-12T06:04:57Z | 18,756,806 | 13 | 2013-09-12T06:22:35Z | [
"python",
"textwrapping"
] | is there a way to print the following,
```
print user + ":\t\t" + message
```
so that lengthy messages that are wider than the length of the terminal always wraps (starts from the same position) ?
so for example this
```
Username: LEFTLEFTLEFTLEFTLEFTLEFTLEFT
RIGHTRIGHTRIGHT
```
should become
```
User... | I think what you're looking for here is the [`textwrap`](http://docs.python.org/2/library/textwrap.html) module:
```
user = "Username"
prefix = user + ": "
preferredWidth = 70
wrapper = textwrap.TextWrapper(initial_indent=prefix, width=preferredWidth,
subsequent_indent=' '*len(prefix))
m... |
How to flatten only some dimensions of a numpy array | 18,757,742 | 19 | 2013-09-12T07:12:21Z | 18,758,049 | 17 | 2013-09-12T07:27:33Z | [
"python",
"numpy",
"flatten"
] | Is there a quick way to "sub-flatten" or flatten only some of the first dimensions in a numpy array?
For example, given a numpy array of dimensions `(50,100,25)`, the resultant dimensions would be `(5000,25)`
Thanks | Take a look at [numpy.reshape](http://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html) .
```
>>> arr = numpy.zeros((50,100,25))
>>> arr.shape
# (50, 100, 25)
>>> new_arr = arr.reshape(5000,25)
>>> new_arr.shape
# (5000, 25)
# One shape dimension can be -1.
# In this case, the value is inferred fr... |
How to flatten only some dimensions of a numpy array | 18,757,742 | 19 | 2013-09-12T07:12:21Z | 26,553,855 | 35 | 2014-10-24T18:14:30Z | [
"python",
"numpy",
"flatten"
] | Is there a quick way to "sub-flatten" or flatten only some of the first dimensions in a numpy array?
For example, given a numpy array of dimensions `(50,100,25)`, the resultant dimensions would be `(5000,25)`
Thanks | A slight generalization to Alexander's answer - np.reshape can take -1 as an argument, meaning "total array size divided by product of all other listed dimensions":
e.g. to flatten all but the last dimension:
```
>>> arr = numpy.zeros((50,100,25))
>>> new_arr = arr.reshape(-1, arr.shape[-1])
>>> new_arr.shape
# (5000... |
Trying to use open( filename, 'w' ) gives IOError: [Errno 2] No such file or directory: | 18,758,673 | 8 | 2013-09-12T08:00:03Z | 18,758,737 | 17 | 2013-09-12T08:03:40Z | [
"python",
"python-2.7",
"windows-7",
"maya"
] | I am trying to create and write to a text file from Maya using Python. The version of Python in this version of Maya is 2.7.3. I have searched and cannot find a solution/reason for this error.
Here's the code that doesn't work.
```
afile = 'D:\\temp\\test.txt'
outFile = open( afile, 'w' )
outFile.write('Test.')
outFi... | You are correct in surmising that the parent directory for the file must exist in order for `open` to succeed. The simple way to deal with this is to make a call to [`os.makedirs`](http://docs.python.org/2/library/os.html#os.makedirs).
From the [documentation](http://docs.python.org/2/library/os.html#os.makedirs):
> ... |
How to assign items inside a Model object with Django? | 18,759,476 | 4 | 2013-09-12T08:42:18Z | 18,759,639 | 11 | 2013-09-12T08:50:46Z | [
"python",
"django",
"models"
] | Is it possible to override values inside a Model?
I am getting **'MyModel' object does not support item assignment.**
```
my_model = MyModel.objects.get(id=1)
print my_model.title
if my_model.is_changed:
my_model['title'] = 'something' # 'MyModel' object does not support item assignment
params = {
'my_mo... | Models are objects, not dictionaries. Set attributes on them directly:
```
if my_model.is_changed:
my_model.title = 'something'
```
Or, if the attribute name is dynamic, use `setattr`:
```
attr_name = 'title' # in practice this would be more complex
if my_model.is_changed:
setattr(my_model, attr_name, 'somet... |
Firefox + Selenium WebDriver and download a csv file automatically | 18,759,762 | 8 | 2013-09-12T08:56:08Z | 18,765,470 | 10 | 2013-09-12T13:18:50Z | [
"python",
"firefox",
"csv",
"selenium",
"webdriver"
] | I have problem with Selenium WebDriver and Firefox. I want to download csv file without confirmation in dialog window and I have code like this:
```
fp = webdriver.FirefoxProfile()
fp.set_preference("browser.download.folderList",2)
fp.set_preference("browser.download.dir", download_dir)
fp.set_preference("browser.down... | Sometime the content type is not as you'd expect
Use **HttpFox** Firefox plugin (or similar) to find the real content type of the file and use it in your code
BTW, For me the content type was
```
fp.set_preference("browser.helperApps.neverAsk.openFile", "application/octet-stream");
fp.set_preference("browser.helperAp... |
CORS - Using AJAX to post on a Python (webapp2) web service | 18,760,224 | 5 | 2013-09-12T09:17:53Z | 18,765,590 | 12 | 2013-09-12T13:24:13Z | [
"python",
"google-app-engine",
"jquery",
"cors",
"webapp2"
] | This is going to be long:
Ok so I'm developing a google calendar gadget which sends requests to a Python webapp2 REST api hosted on Google App Engine.
The problem comes when I try to POST something it doesn't allows me because of CORS.
In Chromes' DevTools it says:
```
Method: OPTIONS.
Status: (failed) Request head... | Ok I fixed it.
First of all I realized [here](http://www.html5rocks.com/en/tutorials/cors/) that the headers were sent by the server so I was doing wrong when sending those headers in the AJAX request.
Finally, after searching around the worldwide web I found what I was missing. It was something stupid. I found the p... |
Fit a curve using matplotlib on loglog scale | 18,760,903 | 4 | 2013-09-12T09:48:26Z | 18,761,200 | 8 | 2013-09-12T10:01:19Z | [
"python",
"numpy",
"matplotlib"
] | I am plotting simple 2D graph using loglog function in python as follows,
```
plt.loglog(x,y,label='X vs Y);
```
X and Y are both lists of floating numbers of `n` size
I want to fit a line on same graph, I tried numpy.polyfit , but I am going nowhere,
How to fit a line using polyfit if your graph is already in logl... | Numpy doesn't care what the axes of your matplotlib graph are.
I presume that you think `log(y)` is some polynomial function of `log(x)`, and you want to find that polynomial? If that is the case, then run [`numpy.polyfit`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.polyfit.html#numpy-polyfit) on the lo... |
Sort list of dictionaries by multiple keys with different ordering | 18,761,776 | 14 | 2013-09-12T10:28:52Z | 18,761,839 | 12 | 2013-09-12T10:32:01Z | [
"python",
"list",
"sorting",
"python-2.7",
"dictionary"
] | I need sort this list of dictionaries:
```
[ {K: 1, B: 2, A: 3, Z: 4, ... } , ... ]
```
Ordering should be:
* K - descending
* B - descending
* A - ascending
* Z - ascending
I only found out how to sort all keys in ascending or descending (`reverse=True`):
```
stats.sort(key=lambda x: (x['K'], x['B'], x['A'], x['Z... | if you have numbers as values, you can use this:
```
stats.sort(key=lambda x: (-x['K'], -x['B'], x['A'], x['Z']))
```
For general values:
```
stats.sort(key=lambda x: (x['A'], x['Z']))
stats.sort(key=lambda x: (x['K'], x['B']), reverse=True)
``` |
Playing with the Python zip function | 18,764,647 | 2 | 2013-09-12T12:44:27Z | 18,764,867 | 8 | 2013-09-12T12:52:29Z | [
"python"
] | Say I wanted to find "greater than" in 2 lists.
```
a = [1,2,3]
b = [0, 0.1, 4]
map( <something>, zip(a,b))
```
I tried operator module. It has a operator.gt() method. But i couldn't find a way to make use of it with zip. any ideas? Edit: The output is just a True value if any one of the them is True.
thanks | To just compare the items in lists `a` with items in `b`, you don't event have to use `zip()`:
```
>>> a = [1, 2, 3]
>>> b = [0, 0.1, 4]
>>> map(operator.gt, a, b)
[True, True, False]
>>>
```
But on the other hand you've not specified what kind of output you're expecting.
**EDIT:**
To effectively `OR` the result, ... |
Make contour of scatter | 18,764,814 | 8 | 2013-09-12T12:50:35Z | 18,764,960 | 15 | 2013-09-12T12:56:34Z | [
"python",
"matplotlib",
"contour",
"scatter-plot"
] | In python, If I have a set of data
```
x, y, z
```
I can make a scatter with
```
import matplotlib.pyplot as plt
plt.scatter(x,y,c=z)
```
How I can get a `plt.contourf(x,y,z)` of the scatter ? | Use the following function to convert to the format required by contourf:
```
from numpy import linspace, meshgrid
from matplotlib.mlab import griddata
def grid(x, y, z, resX=100, resY=100):
"Convert 3 column data to matplotlib grid"
xi = linspace(min(x), max(x), resX)
yi = linspace(min(y), max(y), resY)
... |
Having Ansible pip update python package during development | 18,766,646 | 5 | 2013-09-12T14:12:28Z | 18,769,349 | 11 | 2013-09-12T16:11:51Z | [
"python",
"pip",
"ansible"
] | I have been writing some Ansible plays to setup a python virtualenv and also during development to update the python package and restart the server. I am having problems though getting pip to update a package. I don't really care how this is done, but I would prefer during development just adding the path to the python... | I am going to post this as the correct answer for everyone else to have a reference back to this.
Currently I have an Ansible play that sets up an environment by installing local python packages and then creating a virtualenv and installing everything into that for development. First in setting up the virtualenv and i... |
Resolve GCC error when installing python-ldap on Redhat Enterprise Server | 18,766,930 | 7 | 2013-09-12T14:24:27Z | 18,766,931 | 16 | 2013-09-12T14:24:27Z | [
"python",
"redhat",
"python-ldap"
] | ## Python-LDAP + Redhat = Gnashing of Teeth
Recently, I spent a few hours tearing my hair (or what's left of it) out attempting to install python-ldap (via pip) onto a Redhat Enterprise server.
Here's the error message that I would get (look familiar?):
`Modules/constants.c:365: error: âLDAP_CONTROL_RELAXâ undec... | But wait! I can help you, because I figured it out after a copious amount of cursing!
## Step 1: Verify Prerequisites are Installed
According to the [docs](http://www.python-ldap.org/doc/html/installing.html#prerequisites) you must have OpenLDAP libraries installed on your system. At the time that I'm writing the ver... |
How to write UTF-8 in a CSV file | 18,766,955 | 27 | 2013-09-12T14:25:27Z | 22,607,671 | 13 | 2014-03-24T11:07:52Z | [
"python",
"csv",
"encoding",
"utf-8",
"pyqt4"
] | I am trying to create a text file in csv format out of a PyQt4 `QTableWidget`. I want to write the text with a UTF-8 encoding because it contains special characters. I use following code:
```
import codecs
...
myfile = codecs.open(filename, 'w','utf-8')
...
f = result.table.item(i,c).text()
myfile.write(f+";")
```
It... | Use this package, it just works: <https://github.com/jdunck/python-unicodecsv>. |
How to write UTF-8 in a CSV file | 18,766,955 | 27 | 2013-09-12T14:25:27Z | 31,642,070 | 34 | 2015-07-26T21:19:04Z | [
"python",
"csv",
"encoding",
"utf-8",
"pyqt4"
] | I am trying to create a text file in csv format out of a PyQt4 `QTableWidget`. I want to write the text with a UTF-8 encoding because it contains special characters. I use following code:
```
import codecs
...
myfile = codecs.open(filename, 'w','utf-8')
...
f = result.table.item(i,c).text()
myfile.write(f+";")
```
It... | From your shell run:
```
pip2 install unicodecsv
```
And (unlike the original question) presuming you're using Python's built in `csv` module, turn
`import csv` into
`import unicodecsv as csv` in your code.
(Gijs' answer is the basis for this. I prefer answers that I can use directly without going to another w... |
fitting data with numpy | 18,767,523 | 12 | 2013-09-12T14:49:06Z | 18,767,992 | 20 | 2013-09-12T15:08:12Z | [
"python",
"numpy",
"regression",
"data-fitting"
] | Let me start by telling that what I get may not be what I expect and perhaps you can help me here. I have the following data:
```
>>> x
array([ 3.08, 3.1 , 3.12, 3.14, 3.16, 3.18, 3.2 , 3.22, 3.24,
3.26, 3.28, 3.3 , 3.32, 3.34, 3.36, 3.38, 3.4 , 3.42,
3.44, 3.46, 3.48, 3.5 , 3.52, 3.54, 3... | Unfortunately, `np.polynomial.polynomial.polyfit` returns the coefficients in the opposite order of that for `np.polyfit` and `np.polyval` (or, as you used `np.poly1d`). To illustrate:
```
In [40]: np.polynomial.polynomial.polyfit(x, y, 4)
Out[40]:
array([ 84.29340848, -100.53595376, 44.83281408, -8.85931101,
... |
How do I use a minimization function in scipy with constraints | 18,767,657 | 9 | 2013-09-12T14:54:40Z | 18,769,783 | 11 | 2013-09-12T16:37:21Z | [
"python",
"optimization",
"numpy",
"scipy"
] | I need some help regarding optimisation functions in python(scipy)
the problem is optimizing `f(x)` where `x=[a,b,c...n]`. the constraints are that values of a,b etc should be between 0 and 1, and `sum(x)==1`. The scipy.optimise.minimize function seems best as it requires no differential. How do I pass the arguments?
... | You can do a constrained optimization with `COBYLA` or `SLSQP` as it says in the [docs](http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html).
```
from scipy.optimize import minimize
start_pos = np.ones(6)*(1/6.) #or whatever
#Says one minus the sum of all variables must be zero
cons = ({... |
Python Segmentation fault: 11 on OSX | 18,768,967 | 11 | 2013-09-12T15:53:17Z | 19,551,329 | 17 | 2013-10-23T20:08:01Z | [
"python",
"osx",
"segmentation-fault"
] | Im starting development with python, and tried some simple commands like calculations.
But, some times python aborts with "Segmentation fault:11"
In google i didnt find a similar issue or solution for that.
Python is installed with homebrew.
home-brew doctor command don't show any issues for the python installation a... | Hmmm... spread the word. The following seems that it fixed it:
```
cd /Library/Frameworks/Python.framework/Versions/3.3
cd ./lib/python3.3/lib-dynload
sudo mv readline.so readline.so.disabled
``` |
pandas efficient dataframe set row | 18,771,963 | 5 | 2013-09-12T18:40:02Z | 18,772,565 | 11 | 2013-09-12T19:14:28Z | [
"python",
"pandas",
"dataframe"
] | First I have the following empty DataFrame preallocated:
```
df=DataFrame(columns=range(10000),index=range(1000))
```
Then I want to update the `df` row by row (efficiently) with a length-10000 numpy array as data. My problem is: I don't even have an idea what method of DataFrame I should use to accomplish this task.... | Here's 3 methods, only 100 columns, 1000 rows
```
In [5]: row = np.random.randn(100)
```
Row wise assignment
```
In [6]: def method1():
...: df = DataFrame(columns=range(100),index=range(1000))
...: for i in xrange(len(df)):
...: df.iloc[i] = row
...: return df
...:
```
Build up t... |
Read a file in buffer from FTP python | 18,772,703 | 5 | 2013-09-12T19:21:19Z | 18,773,444 | 13 | 2013-09-12T20:07:31Z | [
"python",
"ftp",
"stream",
"ftplib"
] | I am trying to read a file from an FTP server. The file is a `.gz` file. I would like to know if I can perform actions on this file while the socket is open. I tried to follow what was mentioned in two StackOverflow questions on [reading files without writing to disk](http://stackoverflow.com/questions/11208957/is-it-p... | Make sure to login to the ftp server first. After this, use `retrbinary` which pulls the file in binary mode. It uses a callback on each chunk of the file. You can use this to load it into a string.
```
from ftplib import FTP
ftp = FTP('ftp.ncbi.nlm.nih.gov')
ftp.login() # Username: anonymous password: anonymous@
# S... |
Python doctest with newline characters: inconsistent leading whitespace error | 18,772,991 | 10 | 2013-09-12T19:38:35Z | 18,773,049 | 9 | 2013-09-12T19:42:02Z | [
"python",
"doctest"
] | When writing python doctests, how does one properly introduce newline characters within a string in the test? Here's a simple example:
```
def remove_newlines(text):
"""
>>> remove_newlines("line1 \n"
... "still line 1\r"
... "now line2 \n"
... "more ... | You need to escape the backslash.
The docstring is itself a string where `\n` means newline. In
```
def foo():
"""
print "Hello world\n";
"""
pass
```
the docstring doesn't contain a valid Python statement but contains instead a newline inside the quoted string |
Python doctest with newline characters: inconsistent leading whitespace error | 18,772,991 | 10 | 2013-09-12T19:38:35Z | 18,773,341 | 10 | 2013-09-12T20:02:32Z | [
"python",
"doctest"
] | When writing python doctests, how does one properly introduce newline characters within a string in the test? Here's a simple example:
```
def remove_newlines(text):
"""
>>> remove_newlines("line1 \n"
... "still line 1\r"
... "now line2 \n"
... "more ... | The [docstring docs](http://docs.python.org/2/library/doctest.html#how-are-docstring-examples-recognized) actually allude to the problem, but not entirely clearly.
A couple of other stackoverflow threads [here](http://stackoverflow.com/questions/8834916/how-can-i-include-special-characters-tab-newline-in-a-python-doct... |
python: scatter plot logarithmic scale | 18,773,662 | 11 | 2013-09-12T20:21:10Z | 18,774,741 | 24 | 2013-09-12T21:37:13Z | [
"python",
"matplotlib",
"logarithm"
] | In my code, I take the logarithm of two data series and plot them. I would like to change each tick value of the x-axis by raising it to the power of e (anti-log of natural logarithm).
In other words. I want to graph the logarithms of both series but have x-axis in levels.

ax = plt.gca()
ax.scatter(data['o_value'] ,data['time_diff_day'] , c='blue', alpha=0.05, edgecolors='none')
ax.set_yscale('log')
ax.set_xscale('log')
```
If you are using all the same size and color markers, it is faster to use `plot`
```
fig = plt.figure... |
re-import aliased/shadowed python built-in methods | 18,774,388 | 11 | 2013-09-12T21:10:21Z | 18,774,474 | 9 | 2013-09-12T21:16:57Z | [
"python",
"numpy"
] | If one has run
```
from numpy import *
```
then the built-in `all`, and several other functions, are shadowed by `numpy` functions with the same names.
The most common case where this happens (without people fully realizing it) is when starting `ipython` with `ipython --pylab` (but you shouldn't be doing this, use `... | you can just do
```
all = __builtins__.all
```
The statement `from numpy import *` basically do two separate things
1. imports the module `numpy`
2. copies all the exported names from the module to the current module
by re-assigning the original value from `__builtins__` you can restore the situation for the functi... |
subprocess.call logger info and error for stdout and stderr respectively | 18,774,476 | 4 | 2013-09-12T21:16:58Z | 18,774,517 | 14 | 2013-09-12T21:20:40Z | [
"python",
"logging"
] | I have a logger. something like this:
```
import logging
logger = logging.getLogger('myApp')
hdlr = logging.FileHandler('myApp.log')
logger.addHandler(hdlr)
logger.setLevel(logging.INFO)
```
I am calling an external process like this:
```
subprocess.call("someCommand")
```
I want to capture stdout and stderr seper... | Use `subprocess.Popen()` and call `.communicate()` on the returned process object:
```
p = subprocess.Popen(["someCommand"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = p.communicate()
if stdout:
logger.info(stdout)
if stderr:
logger.error(stderr)
``` |
Converting a csv file into a list of tuples with python | 18,776,370 | 6 | 2013-09-13T00:31:06Z | 18,777,019 | 8 | 2013-09-13T01:51:11Z | [
"python",
"csv",
"dictionary",
"tuples"
] | I am to take a csv with 4 columns: brand, price, weight, and type.
The types are orange, apple, pear, plum.
Parameters: I need to select the most possible weight, but by selecting 1 orange, 2 pears, 3 apples, and 1 plum by not exceeding as $20 budget. I cannot repeat brands of the same fruit (like selecting the same ... | You can ponder this:
```
import csv
def fitem(item):
item=item.strip()
try:
item=float(item)
except ValueError:
pass
return item
with open('/tmp/test.csv', 'r') as csvin:
reader=csv.DictReader(csvin)
data={k.strip():[fitem(v)] for k,v in reader.next().items()}
for ... |
python what happens when a function is called? | 18,776,482 | 3 | 2013-09-13T00:45:11Z | 18,777,818 | 7 | 2013-09-13T03:28:13Z | [
"python",
"python-2.7",
"pdb"
] | I am using pdb to debug a program. I successively hit 'c' to run through the code and at each step pdb shows me which line is executed.
Let's say we have this code:
```
def foo(bar):
print(bar)
foo('hey')
```
First, line 4 calls function foo. Then pdb shows me the line
```
def foo(bar)
```
is executed.
Why? I... | `def` is not a declaration in Python, it's an executable statement. At runtime it retrieves the code object compiled for the function, wraps that in a dynamically created function object, and binds the result to the name following the `def`. For example, consider this useless code:
```
import dis
def f():
def g():... |
Gunicorn with Flask using wrong Python | 18,776,745 | 9 | 2013-09-13T01:18:33Z | 18,776,917 | 10 | 2013-09-13T01:40:05Z | [
"python",
"flask",
"gunicorn"
] | I'm trying to bootstrap a Flask app on a Gunicorn server. By putting the two tools' docs together, plus searching around on SO, this is what I have so far... but it's not quite working.
**app.py**:
```
from flask import Flask, render_template
from flask.ext.sqlalchemy import SQLAlchemy
from werkzeug.contrib.fixers im... | The gunicorn utility may be running out of the system path rather than your virtualenv.
Make sure to `pip install gunicorn` into the virtualenv.
Here's the pip freeze of a virtualenv I setup to run your app:
```
(so_2)20:38:25 ~/code/tmp/flask_so$ pip freeze
Flask==0.10.1
Flask-SQLAlchemy==1.0
Jinja2==2.7.1
MarkupSa... |
Gunicorn with Flask using wrong Python | 18,776,745 | 9 | 2013-09-13T01:18:33Z | 19,472,358 | 7 | 2013-10-19T23:46:07Z | [
"python",
"flask",
"gunicorn"
] | I'm trying to bootstrap a Flask app on a Gunicorn server. By putting the two tools' docs together, plus searching around on SO, this is what I have so far... but it's not quite working.
**app.py**:
```
from flask import Flask, render_template
from flask.ext.sqlalchemy import SQLAlchemy
from werkzeug.contrib.fixers im... | I have the same problem as You.
The problem is that gunicorn for some reason load the enviroment outside your virtual env. I solved by uninstalling the package gunicorn outside virtual enviroment;
```
(env) $ deactivate
$ sudo pip uninstall gunicorn
```
So you come back to your env and try to run. In my case env fold... |
Convert RGB to black OR white | 18,777,873 | 18 | 2013-09-13T03:34:51Z | 18,778,280 | 39 | 2013-09-13T04:23:21Z | [
"python",
"opencv",
"numpy",
"python-imaging-library"
] | How would I take an RGB image in Python and convert it to black OR white? Not grayscale, I want each pixel to be either fully black (0, 0, 0) or fully white (255, 255, 255).
Is there any built-in functionality for this in the popular Python image processing libraries? If not, would the best way be just to loop through... | # Scaling to Black and White
Convert to grayscale and then scale to white or black (whichever is closest).
Original:

Result:

## Pure Pillow implementation
Install `pillow` if you haven't ... |
multiprocessing.Pool with a global variable | 18,778,187 | 5 | 2013-09-13T04:12:58Z | 18,779,028 | 9 | 2013-09-13T05:38:21Z | [
"python",
"multiprocessing"
] | I am using the Pool class from python's multiprocessing library write a program that will run on an HPC cluster.
Here is an abstraction of what I am trying to do:
```
def myFunction(x):
# myObject is a global variable in this case
return myFunction2(x, myObject)
def myFunction2(x,myObject):
myObject.modi... | > I am using the Pool class from python's multiprocessing library to do
> some *shared memory processing* on an HPC cluster.
**Processes are not threads!** You *cannot* simply replace `Thread` with `Process` and expect all to work the same. `Process`es do **not** share memory, which means that the global variables are... |
Emacs 24.3 python: Can't guess python-indent-offset, using defaults 4 | 18,778,894 | 9 | 2013-09-13T05:26:08Z | 18,780,754 | 12 | 2013-09-13T07:34:06Z | [
"python",
"python-2.7",
"emacs",
"elisp",
"indentation"
] | Can anyone who understands Lisp please help resolve this warning?
I upgraded to Emacs 24.3 and whenever I create a Python file using Emacs I get this warning message. Searched in `python.el` and found the following section of code that produces the warning:
```
(let ((indentation (when block-end
... | When you open a python file, emacs guesses the indentation offset (number of spaces to indent) based on that file style. When you **create** a file (the case you describe), emacs cannot guess (file is empty) so it uses your default (4) and notifies the user.
In other words: tt is a harmless warning; if you find this i... |
Most "pythonic" way to check ordering of sub lists of a list? | 18,779,154 | 4 | 2013-09-13T05:49:29Z | 18,779,177 | 8 | 2013-09-13T05:51:40Z | [
"python"
] | what's the most "pythonic" way to calculate if a list of list has each element greater than its neigbbour? eg
```
a = [[3.1, 3.13], [3.14, 3.12], [3.12, 3.1]]
```
I want to see if the first element in each of the list (inside the bigger list) is greater than the 2nd element. So for first item, its false because 3.1 <... | Pattern matching and list comprehension:
```
[x > y for x, y in a]
``` |
python pip specify a library directory and an include directory | 18,783,390 | 21 | 2013-09-13T09:56:42Z | 22,942,120 | 37 | 2014-04-08T15:54:41Z | [
"python",
"shared-libraries",
"pip",
"include-path",
"pyodbc"
] | I am using pip and trying to install a python module called pyodbc which has some dependencies on non-python libraries like unixodbc-dev, unixodbc-bin, unixodbc. I cannot install these dependencies system wide at the moment, as I am only playing, so I have installed them in a non-standard location. How do I tell pip wh... | pip has a `--global-option` flag
You can use it to pass additional flags to `build_ext`.
For instance, to add a --library-dirs (-L) flag:
`pip install --global-option=build_ext --global-option="-L/path/to/local" pyodbc`
gcc supports also environment variables:
<http://gcc.gnu.org/onlinedocs/gcc/Environment-Variab... |
imshow when you are plotting data, not images. Realtion between aspect and extent? | 18,784,354 | 5 | 2013-09-13T10:42:27Z | 18,786,106 | 7 | 2013-09-13T12:17:04Z | [
"python",
"matplotlib",
"plot"
] | I am plotting a 2D data array with imshow in matplotlib. I have a problem trying to scale the resulting plot. The size of the array is 30x1295 points, but the extent in units are:
`extent = [-130,130,0,77]`
If I plot the array without the extent, I get the right plot, but if I use extent, I get this plot with the wrong... | I'm guessing that you're wanting "square" pixels in the final plot?
For example, if we plot random data similar to yours:
```
import numpy as np
import matplotlib.pyplot as plt
data = np.random.random((30, 1295))
fig, ax = plt.subplots()
ax.imshow(data, extent=[-130,130,0,77])
plt.show()
```
We'll get an image wit... |
Install numpy in Python virtualenv | 18,785,063 | 17 | 2013-09-13T11:20:01Z | 19,874,999 | 24 | 2013-11-09T10:40:49Z | [
"python",
"ubuntu",
"numpy",
"virtualenv"
] | I've created virtualenv for Python 2.7.4 on Ubuntu 13.04. I've installed python-dev.
I have [the error](http://pastebin.com/YQfdYDVK) when installing numpy in the virtualenv.
Maybe, you have any ideas to fix? | The problem is `SystemError: Cannot compile 'Python.h'. Perhaps you need to install python-dev|python-devel.`
so do the following in order to obtain 'Python.h'
make sure apt-get and gcc are up to date
```
sudo apt-get update
sudo apt-get upgrade gcc
```
then install the python2.7-dev
```
sudo apt-get install p... |
Install numpy in Python virtualenv | 18,785,063 | 17 | 2013-09-13T11:20:01Z | 23,831,818 | 17 | 2014-05-23T14:27:24Z | [
"python",
"ubuntu",
"numpy",
"virtualenv"
] | I've created virtualenv for Python 2.7.4 on Ubuntu 13.04. I've installed python-dev.
I have [the error](http://pastebin.com/YQfdYDVK) when installing numpy in the virtualenv.
Maybe, you have any ideas to fix? | If you're on Python3 you'll need to do `sudo apt-get install python3-dev`. Took me a little while to figure it out. |
Install numpy in Python virtualenv | 18,785,063 | 17 | 2013-09-13T11:20:01Z | 24,241,717 | 12 | 2014-06-16T10:34:10Z | [
"python",
"ubuntu",
"numpy",
"virtualenv"
] | I've created virtualenv for Python 2.7.4 on Ubuntu 13.04. I've installed python-dev.
I have [the error](http://pastebin.com/YQfdYDVK) when installing numpy in the virtualenv.
Maybe, you have any ideas to fix? | If you're hitting this issue even though you've installed all OS dependencies (python-devel, fortran compiler, etc), the issue might be instead related to the following bug:
["numpy installation thru install\_requires directive issue..."](http://github.com/numpy/numpy/issues/2434)
Work around is to manually install nu... |
Get Output From the logging Module in IPython Notebook | 18,786,912 | 55 | 2013-09-13T12:57:47Z | 18,809,051 | 42 | 2013-09-15T04:55:39Z | [
"python",
"logging",
"ipython-notebook"
] | When I running the following inside IPython Notebook I don't see any output:
```
import logging
logging.basicConfig(level=logging.DEBUG)
logging.debug("test")
```
Anyone know how to make it so I can see the "test" message inside the notebook? | Try following:
```
import logging
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
logging.debug("test")
```
According to [logging.basicConfig](http://docs.python.org/2/library/logging.html#logging.basicConfig):
> Does basic configuration for the logging system by creating a
> StreamHandler with a default... |
Get Output From the logging Module in IPython Notebook | 18,786,912 | 55 | 2013-09-13T12:57:47Z | 21,475,297 | 31 | 2014-01-31T08:17:30Z | [
"python",
"logging",
"ipython-notebook"
] | When I running the following inside IPython Notebook I don't see any output:
```
import logging
logging.basicConfig(level=logging.DEBUG)
logging.debug("test")
```
Anyone know how to make it so I can see the "test" message inside the notebook? | If you still want to use `basicConfig`, reload the logging module like this
```
import logging
reload(logging)
logging.basicConfig(format='%(asctime)s %(levelname)s:%(message)s', level=logging.DEBUG, datefmt='%I:%M:%S')
``` |
Get Output From the logging Module in IPython Notebook | 18,786,912 | 55 | 2013-09-13T12:57:47Z | 28,195,348 | 10 | 2015-01-28T14:56:38Z | [
"python",
"logging",
"ipython-notebook"
] | When I running the following inside IPython Notebook I don't see any output:
```
import logging
logging.basicConfig(level=logging.DEBUG)
logging.debug("test")
```
Anyone know how to make it so I can see the "test" message inside the notebook? | My understanding is that the IPython session starts up logging so basicConfig doesn't work. Here is the setup that works for me (I wish this was not so gross looking since I want to use it for almost all my notebooks):
```
import logging
logger = logging.getLogger()
fhandler = logging.FileHandler(filename='mylog.log',... |
Difference between entry_points/console_scripts and scripts in setup.py? | 18,787,036 | 27 | 2013-09-13T13:04:06Z | 18,985,818 | 13 | 2013-09-24T15:28:21Z | [
"python",
"package",
"setup.py"
] | There are basically two ways to install Python console scripts to my path by `setup.py`:
```
setup(
...
entry_points = {
'console_scripts': [
'foo = package.module:func',
],
}
)
```
and
```
setup(
...
scripts = [
'scripts/myscript.sh'
]
)
```
What are the ... | One key difference between these two ways of creating command line executables is that with the `setuptools` approach (your first example), you have to call a function inside of the script -- in your case this is the `func` inside of your `module`. However, in the `distutils` approach (your second example) you call the... |
Difference between entry_points/console_scripts and scripts in setup.py? | 18,787,036 | 27 | 2013-09-13T13:04:06Z | 28,119,736 | 17 | 2015-01-23T22:25:20Z | [
"python",
"package",
"setup.py"
] | There are basically two ways to install Python console scripts to my path by `setup.py`:
```
setup(
...
entry_points = {
'console_scripts': [
'foo = package.module:func',
],
}
)
```
and
```
setup(
...
scripts = [
'scripts/myscript.sh'
]
)
```
What are the ... | The docs for the (awesome) Click package [suggest a few reasons](http://click.pocoo.org/dev/setuptools/) to use entry points instead of scripts, including
1. cross-platform compatibility and
2. avoiding having the interpreter assign `\__name__` to `\__main__`, which could cause code to be imported twice (if another mo... |
Trimming dictionaries | 18,789,467 | 3 | 2013-09-13T15:01:06Z | 18,789,531 | 7 | 2013-09-13T15:03:53Z | [
"python"
] | I'd like to know if there is a more simple/pythonic way to trim the "size/length" of a dictionary in python. If I have a dict with 10 key-value-pairs(elements) and I'd like to restrict the size to be 5. Is deleting elements in a loop the best solution *(order/identity does not matter)*
```
def _trim_search_results(sel... | You could try
```
d = dict(d.items()[:MAX_RESULTS])
``` |
Equivalent to numpy.roll() in R? | 18,791,212 | 11 | 2013-09-13T16:39:15Z | 18,791,252 | 16 | 2013-09-13T16:41:34Z | [
"python",
"numpy"
] | I have an array:
```
a <- c(1,2,3,4,5)
```
And I'd like to do somthing like:
```
b <- roll(a,2) # 4,5,1,2,3
```
Is there a function like that in R? I've been googling around, but "R Roll" mostly gives me pages about Spanish pronunciation. | How about using `head` and `tail`...
```
roll <- function( x , n ){
if( n == 0 )
return( x )
c( tail(x,n) , head(x,-n) )
}
roll(1:5,2)
#[1] 4 5 1 2 3
# For the situation where you supply 0 [ this would be kinda silly! :) ]
roll(1:5,0)
#[1] 1 2 3 4 5
```
One cool thing about using `head` and `tail`... you g... |
Equivalent to numpy.roll() in R? | 18,791,212 | 11 | 2013-09-13T16:39:15Z | 18,791,601 | 11 | 2013-09-13T17:03:00Z | [
"python",
"numpy"
] | I have an array:
```
a <- c(1,2,3,4,5)
```
And I'd like to do somthing like:
```
b <- roll(a,2) # 4,5,1,2,3
```
Is there a function like that in R? I've been googling around, but "R Roll" mostly gives me pages about Spanish pronunciation. | Here's an alternative which has the advantage of working even when `x` is "rolled" by more than one full cycle (i.e. when `abs(n) > length(x)`):
```
roll <- function(x, n) {
x[(seq_along(x) - (n+1)) %% length(x) + 1]
}
roll(1:5, 2)
# [1] 4 5 1 2 3
roll(1:5, 0)
# [1] 1 2 3 4 5
roll(1:5, 11)
# [1] 5 1 2 3 4
```
FW... |
How to group / count list elements by range | 18,791,571 | 3 | 2013-09-13T17:01:12Z | 18,791,631 | 7 | 2013-09-13T17:05:04Z | [
"python",
"list",
"dictionary"
] | If my x list and y list are:
```
x = [10,20,30]
y = [1,2,3,15,22,27]
```
I'd like a return value to be a dictionary that has a count of the elements that were less than the x value:
```
{
10:3,
20:1,
30:2,
}
```
I have a very large list, so I was hoping there was a better way to do it that didn't involv... | You can use the `bisect` module and `collections.Counter`:
```
>>> import bisect
>>> from collections import Counter
>>> Counter(x[bisect.bisect_left(x, item)] for item in y)
Counter({10: 3, 30: 2, 20: 1})
``` |
Python - How to make program go back to the top of the code instead of closing | 18,791,882 | 4 | 2013-09-13T17:20:36Z | 18,791,912 | 12 | 2013-09-13T17:22:39Z | [
"python",
"python-3.3"
] | I'm trying to figure out how to make Python go back to the top of the code. In SmallBasic, you do
```
start:
textwindow.writeline("Poo")
goto start
```
But I can't figure out how you do that in Python :/ Any ideas anyone?
The code I'm trying to loop is this
```
#Alan's Toolkit for conversions
def start() :... | Use an infinite loop:
```
while True:
print('Hello world!')
```
This certainly can apply to your `start()` function as well; you can exit the loop with either `break`, or use `return` to exit the function altogether, which also terminates the loop:
```
def start():
print ("Welcome to the converter toolkit ma... |
Same module is being imported in different files | 18,792,145 | 2 | 2013-09-13T17:37:51Z | 18,792,512 | 9 | 2013-09-13T18:02:42Z | [
"python",
"import",
"module"
] | Is it a bad practice to do this:
In first.py:
```
import second
import mymodule
```
In second.py:
```
import mymodule
```
`mymodule` is being imported in both files and first.py imports second.py. Is it possible to somehow import the `mymodule` just once? It's not a big deal, it's just not elegant nor Pythonic IMO... | `mymodule` is only run once; every module that imports it shares the same copy. It's fine. Just be careful if you have any cyclic imports (A imports B imports A, or A imports B imports C ... imports A), because those can cause subtle initialization order problems and mess you up. |
What do boolean operations on lists mean? | 18,792,460 | 4 | 2013-09-13T17:58:52Z | 18,792,493 | 7 | 2013-09-13T18:01:03Z | [
"python",
"boolean"
] | I was going through the source of `pyftpdlib` and I found this:
`if self.rejected_users and self.allowed_users:
raise AuthorizerError("rejected_users and allowed_users options are mutually exclusive")`
`rejected_users` and `allowed_users` are lists.
What's confusing me is how the `and` operator operates on two lists.... | **All** objects in Python have a boolean 'value'; they are either true or false in a boolean context.
Empty lists are false. This applies to all sequences and containers, including tuples, sets, dictionaries and strings.
Numeric 0 is false too, so 0, 0.0, 0j are all false as well, as are `None` and of course `False` ... |
Pandas Combining 2 Data Frames (join on a common column) | 18,792,918 | 19 | 2013-09-13T18:29:46Z | 18,793,067 | 14 | 2013-09-13T18:39:35Z | [
"python",
"pandas",
"left-join",
"dataframe"
] | I have 2 dataframes:
restaurant\_ids\_dataframe
```
Data columns (total 13 columns):
business_id 4503 non-null values
categories 4503 non-null values
city 4503 non-null values
full_address 4503 non-null values
latitude 4503 non-null values
longitude 4503 non-null values... | Joining fails if the DataFrames have some column names in common. The simplest way around it is to include an `lsuffix` or `rsuffix` keyword like so:
```
restaurant_review_frame.join(restaurant_ids_dataframe, on='business_id', how='left', lsuffix="_review")
```
This way, the columns have distinct names. The documenta... |
Pandas Combining 2 Data Frames (join on a common column) | 18,792,918 | 19 | 2013-09-13T18:29:46Z | 18,799,713 | 33 | 2013-09-14T08:11:16Z | [
"python",
"pandas",
"left-join",
"dataframe"
] | I have 2 dataframes:
restaurant\_ids\_dataframe
```
Data columns (total 13 columns):
business_id 4503 non-null values
categories 4503 non-null values
city 4503 non-null values
full_address 4503 non-null values
latitude 4503 non-null values
longitude 4503 non-null values... | You can use **merge** to combine two dataframes into one:
```
import pandas as pd
pd.merge(restaurant_ids_dataframe, restaurant_review_frame, on='business_id', how='outer')
```
where **on** specifies field name that exists in both dataframes to join on, and **how**
defines whether its inner/outer/left/right join, wit... |
Pandas Combining 2 Data Frames (join on a common column) | 18,792,918 | 19 | 2013-09-13T18:29:46Z | 19,937,902 | 7 | 2013-11-12T19:14:07Z | [
"python",
"pandas",
"left-join",
"dataframe"
] | I have 2 dataframes:
restaurant\_ids\_dataframe
```
Data columns (total 13 columns):
business_id 4503 non-null values
categories 4503 non-null values
city 4503 non-null values
full_address 4503 non-null values
latitude 4503 non-null values
longitude 4503 non-null values... | In case anyone needs to try and merge two dataframes together on the index (instead of another column), this also works!
T1 and T2 are dataframes that have the same indices
```
import pandas as pd
T1 = pd.merge(T1, T2, on=T1.index, how='outer')
```
P.S. I had to use merge because append would fill NaNs in unnecessar... |
Is it possible to have contextlib.closing() to call an arbitrary cleanup method instead of .close() | 18,794,278 | 2 | 2013-09-13T19:58:48Z | 18,794,386 | 8 | 2013-09-13T20:05:33Z | [
"python",
"with-statement"
] | I was running into some problems using `with statement`([PEP 343](http://www.python.org/dev/peps/pep-0343/)) in python to automatically manage resource clean up after the context. In particular, `with statement` always assumes the resource clean up method is `.close()`. I.E. in the following block of code, `browser.clo... | Well, it's python, you can make your own `closing` class, based on `contextlib.closing` and override `__exit__()` method:
```
import contextlib
from selenium import webdriver
class closing(contextlib.closing):
def __exit__(self, *exc_info):
self.thing.quit()
with closing(webdriver.Firefox()) as browser:... |
python string unicode issue | 18,796,174 | 2 | 2013-09-13T22:25:37Z | 18,796,197 | 9 | 2013-09-13T22:28:25Z | [
"python",
"string",
"unicode"
] | Here is my code (I am using python 2.7 )
```
result = " '{0}' is unicode or something: ".format(mongdb['field'])
UnicodeEncodeError: 'ascii' codec can't encode character u'\xb0' in position 27: ordinal not in range(128)
```
It looks like a string I read from mongodb contains unicode. And it throws this error. How... | Use a `unicode` format string (recommended):
```
result = u" '{0}' is unicode or something: ".format(mongdb['field'])
```
Or encode the field:
```
result = " '{0}' is unicode or something: ".format(mongdb['field'].encode('utf-8'))
``` |
Passing Javascript Array to Flask | 18,796,921 | 4 | 2013-09-13T23:59:10Z | 18,799,325 | 9 | 2013-09-14T07:13:32Z | [
"javascript",
"python",
"flask"
] | I have a function in flask called array that takes in a list and prints out the items in the list:
```
def array(list):
string = ""
for x in list:
string+= x
return string
```
On the client side, I want to pass in a javascript array named str into this array. How would I do that? Here's what I hav... | [Flask has a built in object called request. In request there is a multidict called args.](http://stackoverflow.com/questions/11774265/flask-how-do-you-get-a-query-string-from-flask)
You can use `request.args.get('key')` to retrieve the value of a query string.
```
from flask import request
@app.route('/example')
de... |
How to differentiate between hasattr and normal attribute access in __getattr__? | 18,797,897 | 3 | 2013-09-14T03:09:03Z | 18,797,913 | 9 | 2013-09-14T03:12:01Z | [
"python"
] | ```
class a_class:
def __getattr__(self, name):
# if called by hasattr(a, 'b') not by a.b
# print("I am called by hasattr")
print(name)
a = a_class()
a.b_attr
hasattr(a, 'c_attr')
```
Please take a look the comment inside `__getattr__`. How do I do that? I am using Python 3. The reason is... | You can't, without cheating. As [the documentation](http://docs.python.org/2/library/functions.html#hasattr) says:
> This [that is, `hasattr`] is implemented by calling `getattr(object, name)` and seeing whether it raises an exception or not.
In other words, you can't block `hasattr` without also blocking `getattr`, ... |
Count number of occurrences of a character in a string | 18,797,928 | 7 | 2013-09-14T03:16:12Z | 18,797,950 | 11 | 2013-09-14T03:20:02Z | [
"python"
] | I'm just getting into Python and I'm building a program that analyzes a group of words and returns how many times each letter appears in the text. i.e 'A:10, B:3, C:5...etc'. So far it's working perfectly except that i am looking for a way to condense the code so i'm not writing out each part of the program 26 times. H... | You can use Counter but @TimPeters is probably right and it is better to stick with the basics.
```
from collections import Counter
c = Counter([letter for letter in message if letter.isalpha()])
for k, v in sorted(c.items()):
print('{0}: {1}'.format(k, v))
``` |
Count number of occurrences of a character in a string | 18,797,928 | 7 | 2013-09-14T03:16:12Z | 18,797,962 | 13 | 2013-09-14T03:22:19Z | [
"python"
] | I'm just getting into Python and I'm building a program that analyzes a group of words and returns how many times each letter appears in the text. i.e 'A:10, B:3, C:5...etc'. So far it's working perfectly except that i am looking for a way to condense the code so i'm not writing out each part of the program 26 times. H... | There are many ways to do this. Most use a dictionary (`dict`). For example,
```
count = {}
for letter in message:
if letter in count: # saw this letter before
count[letter] += 1
else: # first time we've seen this - make its first dict entry
count[letter] = 1
```
There are shorter ways to w... |
Matrix solution with Numpy: no solution? | 18,798,321 | 5 | 2013-09-14T04:32:31Z | 18,798,494 | 7 | 2013-09-14T05:03:28Z | [
"python",
"numpy"
] | Ran a simple script in Numpy to solve a system of 3 equations:
```
from numpy import *
a = matrix('1 4 1; 4 13 7; 7 22 13')
b = matrix('0;0;1')
print linalg.solve(a,b)
```
But when I ran it through the command prompt, I somehow got:
```
[[ 3.46430741e+15]
[ -6.92861481e+14]
[ -6.92861481e+14]]
```
although Wolfr... | If you take pen and paper (or use `numpy.linalg.matrix_rank`) and calculate the ranks of the coefficient and the augmented matrix you'll see that, according to [RouchéâCapelli theorem](https://en.wikipedia.org/wiki/Rouch%C3%A9%E2%80%93Capelli_theorem), there can't be any solution. So Wolfram is right.
Numpy searche... |
Is there a python equivalent to Laravel 4? | 18,798,848 | 10 | 2013-09-14T06:03:16Z | 18,799,001 | 14 | 2013-09-14T06:24:53Z | [
"python",
"python-3.x",
"laravel"
] | Laravel 4 enables me to develop both small scale and enterprise scale app's easily and efficiently, and its modular concepts allow me to extend it core, build custom reusable packages, and easily follow TDD practices.
I have been diving into the wonderful world of python (v3) and wondered what the equivalent web frame... | Yes. [Pyramid](http://www.pylonsproject.org/projects/pyramid/about) is what you are looking for. It's written from the ground up to be based in common Python libraries and components, and you can swap out pieces for other pieces as you wish. Python as a language is geared for TDD, and Pyramid takes advantage of that. Y... |
Python: Best Way to remove duplicate character from string | 18,799,036 | 8 | 2013-09-14T06:30:21Z | 18,799,050 | 9 | 2013-09-14T06:32:40Z | [
"python",
"string",
"text-processing"
] | How can I remove duplicate characters from a string using Python? For example, let's say I have a string:
```
foo = "SSYYNNOOPPSSIISS"
```
How can I make the string:
```
foo = SYNOPSIS
```
I'm new to python and What I have tired and it's working. I knew there is smart and best way to do this.. and only experience c... | Using [`itertools.groupby`](http://docs.python.org/2/library/itertools.html#itertools.groupby):
```
>>> foo = "SSYYNNOOPPSSIISS"
>>> import itertools
>>> ''.join(ch for ch, _ in itertools.groupby(foo))
'SYNOPSIS'
``` |
how do I print in python if a list contains only 0s? | 18,799,441 | 3 | 2013-09-14T07:31:18Z | 18,799,449 | 12 | 2013-09-14T07:32:05Z | [
"python",
"list"
] | how do i print in python if a list contains only 0s??
```
list1=[0,0,0,0,0,0]
if list1 has all 0s
print("something")
```
I want the output to be "something" | Use [`all()`](http://docs.python.org/2/library/functions.html#all):
```
if all(item == 0 for item in list1):
print("something")
```
**Demo:**
```
>>> list1 = [0,0,0,0,0,0]
>>> all(item == 0 for item in list1)
True
```
Another alternative will be to use `sets`, if all the items in list are hashable:
```
>>> set(... |
fminunc alternate in numpy | 18,801,002 | 8 | 2013-09-14T10:54:26Z | 21,446,032 | 9 | 2014-01-30T01:11:15Z | [
"python",
"matlab",
"python-2.7",
"numpy",
"octave"
] | Is there an alternative to the `fminunc` function (from octave/matlab) in python? I have a cost function for a binary classifier. Now I want to run gradient descent to get minimum value of theta. The octave/matlab implementation will look like this.
```
% Set options for fminunc
options = optimset('GradObj', 'on', 'M... | There is more information about the functions of interest here: <http://docs.scipy.org/doc/scipy-0.10.0/reference/tutorial/optimize.html>
Also, it looks like you are doing the Coursera Machine Learning course, but in Python. You might check out <http://aimotion.blogspot.com/2011/11/machine-learning-with-python-logisti... |
Why do I lose precision while multiplying and dividing whole ints? | 18,802,091 | 7 | 2013-09-14T13:09:42Z | 18,802,107 | 11 | 2013-09-14T13:11:08Z | [
"python",
"python-3.x"
] | I had thought Python3 is supposed to be able to handle numbers of arbitrary length, but I'm running into a problem where they don't seem to act consistently.
After multiplying then dividing, my int seems to have changed it's internal representation, and no longer evaluates as a match for it's former self.
I'm using w... | You are dividing using the true division operator `/`, which will *always* result in floating point values. Use floor division instead, `//`, to get integer results:
```
>>> a = 313585730727764141482831584863
>>> b = a*2
>>> c = b // 2
>>> a == c
True
```
Your computer hardware cannot handle float values with the req... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.