title stringlengths 12 150 | question_id int64 469 40.1M | question_score int64 2 5.52k | question_date stringdate 2008-08-02 15:11:16 2016-10-18 06:16:31 | answer_id int64 536 40.1M | answer_score int64 7 8.38k | answer_date stringdate 2008-08-02 18:49:07 2016-10-18 06:19:33 | tags listlengths 1 5 | question_body_md stringlengths 15 30.2k | answer_body_md stringlengths 11 27.8k |
|---|---|---|---|---|---|---|---|---|---|
python matplotlib: unable to call FuncAnimation from inside a function | 21,099,121 | 7 | 2014-01-13T18:56:31Z | 21,116,525 | 11 | 2014-01-14T14:52:00Z | [
"python",
"animation",
"matplotlib"
] | I'm trying to implement a function which outputs an animated plot.
If I take simple\_anim.py (from matplotlib examples) as a base:
```
"""
A simple example of an animated plot
"""
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
fig, ax = plt.subplots()
x = np.arange(0, 2... | The reason that this happens is that the timers and call backs which update the window are attributes of the object `ani`. If you do not keep a reference to it around, then `ani` in garbage collected and your timers/callbacks go away.
The solution is to have your function return `ani` and keep a reference to it in you... |
How to write to Kafka from Python logging module? | 21,102,293 | 2 | 2014-01-13T22:04:23Z | 21,122,445 | 9 | 2014-01-14T19:38:44Z | [
"python",
"apache-kafka"
] | I've got a large complex application that is heavily using the Python logging module.
I need to start getting these logs into a Kafka cluster, and need to ensure that I don't change the data along the way.
To me the ideal solution is to just create a new handler for Kafka - and allow the logs to go to both the old lo... | Handler implementation is really simple. Actually, setting up the environment took more time than implementing the handler.
The handler constructor accepts optional argument `key`. If it's provided, the messages written will be sent to a single partition specified by this key. If not provided, the messages will be dis... |
python split() vs rsplit() performance? | 21,103,433 | 4 | 2014-01-13T23:29:45Z | 21,103,459 | 14 | 2014-01-13T23:32:20Z | [
"python",
"string",
"split"
] | I have a string in python. I want to split it with `maxsplit = 1` on separator which is pretty close to end of the string.
For e.g.
```
a = "abcdefghijklmnopqrstuvwxyz,1".
```
Will `a.split(",", 1)` be better in terms of performance than `a.rsplit(",",1)`? | Below is a time test using [`timeit.timeit`](http://docs.python.org/3/library/timeit.html#timeit.timeit) to compare the speeds of the two methods:
```
>>> from timeit import timeit
>>> timeit('"abcdefghijklmnopqrstuvwxyz,1".split(",", 1)')
1.6438178595324267
>>> timeit('"abcdefghijklmnopqrstuvwxyz,1".rsplit(",", 1)')
... |
Missing scheme in request url | 21,103,533 | 5 | 2014-01-13T23:39:40Z | 21,103,645 | 8 | 2014-01-13T23:48:41Z | [
"python",
"url",
"scrapy",
"relative"
] | I've been stuck on this bug for a while, the following error message is as follows:
```
File "C:\Python27\lib\site-packages\scrapy-0.20.2-py2.7.egg\scrapy\http\request\__init__.py", line 61, in _set_url
raise ValueError('Missing scheme in request url: %s' % self._url)
exceptions.ValueError: Mis... | change `start_urls` to:
```
self.start_urls = ["http://www.bankofwow.com/"]
``` |
How to tell Jenkins to use a particular virtualenv python | 21,103,727 | 6 | 2014-01-13T23:57:22Z | 21,103,793 | 10 | 2014-01-14T00:02:37Z | [
"python",
"python-2.7",
"jenkins",
"virtualenv",
"jenkins-plugins"
] | I have already created a virtualenv for running my python script.
Now when I integrate this python scrip with Jenkins, I have found at the time execution Jenkins is using wrong python environment.
How I can ensure Jenkins is using the correct virtualenv?
As an example, for my case I want to use virtualenv test. How ... | You should install one of python plugins. I've used [ShiningPanda](https://wiki.jenkins-ci.org/display/JENKINS/ShiningPanda+Plugin). Then you'll be able to create separate virtual environment configurations in Manage Jenkins > Configure System > Python > Python installation.
In job configuration there will be Python Bu... |
OrderedDict comprehensions | 21,103,732 | 35 | 2014-01-13T23:57:52Z | 21,103,800 | 44 | 2014-01-14T00:03:03Z | [
"python",
"dictionary",
"cpython",
"ordereddictionary",
"dictionary-comprehension"
] | Can I extend syntax in python for dict comprehensions for other dicts, like the OrderedDict in `collections` module or my own types which inherit from `dict`?
Just rebinding the `dict` name obviously doesn't work, the `{key: value}` comprehension syntax still gives you a plain old dict for comprehensions and literals.... | Sorry, not possible. Dict literals and dict comprehensions map to the built-in dict type, in a way that's hardcoded at the C level. That can't be overridden.
You can use this as an alternative, though:
```
OrderedDict((i, i * i) for i in range(3))
``` |
OrderedDict comprehensions | 21,103,732 | 35 | 2014-01-13T23:57:52Z | 21,103,852 | 17 | 2014-01-14T00:09:24Z | [
"python",
"dictionary",
"cpython",
"ordereddictionary",
"dictionary-comprehension"
] | Can I extend syntax in python for dict comprehensions for other dicts, like the OrderedDict in `collections` module or my own types which inherit from `dict`?
Just rebinding the `dict` name obviously doesn't work, the `{key: value}` comprehension syntax still gives you a plain old dict for comprehensions and literals.... | There is no direct way to change Python's syntax from within the language. A dictionary comprehension (or plain display) is always going to create a `dict`, and there's nothing you can do about that. If you're using CPython, it's using special bytecodes that generate a dict directly, which ultimately call the [`PyDict`... |
What does the "r" in pythons re.compile(r' pattern flags') mean? | 21,104,476 | 6 | 2014-01-14T01:18:28Z | 21,104,539 | 11 | 2014-01-14T01:25:06Z | [
"python",
"regex"
] | I am reading through <http://docs.python.org/2/library/re.html>. According to this the "r" in pythons re.compile(**r**' pattern flags') refers the raw string notation :
> The solution is to use Pythonâs raw string notation for regular
> expression patterns; backslashes are not handled in any special way in
> a strin... | As `@PauloBu` stated, the `r` string prefix is not specifically related to regex's, but to strings generally in Python.
Normal strings use the backslash character as an escape character for special characters (like newlines):
```
>>> print 'this is \n a test'
this is
a test
```
The `r` prefix tells the interpreter... |
JSON to pandas DataFrame | 21,104,592 | 28 | 2014-01-14T01:32:07Z | 21,266,043 | 40 | 2014-01-21T18:17:22Z | [
"python",
"json",
"google-maps",
"pandas"
] | What I am trying to do is extract elevation data from a google maps API along a path specified by latitude and longitude coordinates as follows:
```
from urllib2 import Request, urlopen
import json
path1 = '42.974049,-81.205203|42.974298,-81.195755'
request=Request('http://maps.googleapis.com/maps/api/elevation/json?... | I found a quick and easy solution to what I wanted using json\_normalize function included in the latest release of pandas 0.13.
```
from urllib2 import Request, urlopen
import json
from pandas.io.json import json_normalize
path1 = '42.974049,-81.205203|42.974298,-81.195755'
request=Request('http://maps.googleapis.co... |
Keyboard Interrupt with python's multiprocessing | 21,104,997 | 6 | 2014-01-14T02:21:56Z | 21,106,459 | 12 | 2014-01-14T05:09:09Z | [
"python",
"multithreading",
"multiprocessing"
] | I am having an issues gracefully handling a Keyboard Interrupt with python's multi-processing
(Yes I know that Ctr-C should not guarantee a graceful shutdown -- but lets leave that discussion for a different thread)
Consider the following code, where I am user a `multiprocessing.Manager#list()` which is a ListProxy w... | multiprocessing.Manager() fires up a child process which is responsible for handling your shared list proxy.
netstat output while running:
> unix 2 [ ACC ] STREAM LISTENING 3921657 8457/python
> /tmp/pymp-B9dcij/listener-X423Ml
this child process created by multiprocessing.Manager() is catching your SIGINT and exiti... |
Python Logger not working | 21,105,753 | 5 | 2014-01-14T03:47:41Z | 21,105,825 | 9 | 2014-01-14T03:55:03Z | [
"python",
"logging"
] | I try to use logging in Python to write some log, but strangely, only the `error` will be logged, the `info` will be ignored no matter whichn level I set.
code:
```
import logging
import logging.handlers
if __name__ == "__main__":
logger = logging.getLogger()
fh = logging.handlers.RotatingFileHandler('./logt... | The problem is that the *logger's* level is still set to the default. So the logger discards the message before it even gets to the handlers. The fact that the handler would have accepted the message if it received it doesn't matter, because it never receives it.
So, just add this:
```
logger.setLevel(logging.INFO)
`... |
Loop performance degradation | 21,105,803 | 3 | 2014-01-14T03:52:23Z | 21,105,939 | 8 | 2014-01-14T04:10:10Z | [
"python",
"dictionary",
"pickle"
] | I have the following code:
```
keywordindex = cPickle.load(open('keywordindex.p','rb'))#contains~340 thousand items
masterIndex = {}
indexes = [keywordindex]
for partialIndex in indexes:
start = time.time()
for key in partialIndex.iterkeys():
if key not in masterIndex.keys():
masterIndex[k... | This block contains two instances of horridly inefficient coding:
```
if key not in masterIndex.keys():
masterIndex[key]= partialIndex[key]
elif key in masterIndex.keys():
masterIndex[key].extend(partialIndex[key])
```
First, the key is or is not in `masterIndex`, so there's no *useful* point ... |
Numpy Pure Functions for performance, caching | 21,106,134 | 8 | 2014-01-14T04:32:01Z | 21,106,536 | 23 | 2014-01-14T05:16:44Z | [
"python",
"optimization",
"numpy",
"blas",
"memorization"
] | I'm writing some moderately performance critical code in numpy.
This code will be in the inner most loop, of a computation that's run time is measured in hours.
A quick calculation suggest that this code will be executed up something like 10^12 times, in some variations of the calculation.
So the function is to calcul... | These functions already exist in scipy. The sigmoid function is available as [`scipy.special.expit`](http://docs.scipy.org/doc/scipy/reference/generated/scipy.special.expit.html).
```
In [36]: from scipy.special import expit
```
Compare `expit` to the vectorized sigmoid function:
```
In [38]: x = np.linspace(-6, 6, ... |
Pyramid CORS for Ajax requests | 21,107,057 | 8 | 2014-01-14T06:06:29Z | 21,109,961 | 7 | 2014-01-14T09:29:21Z | [
"python",
"cors",
"pyramid"
] | Is it possible automatically add `Access-Control-Allow-Origin` header to all responses which was initiated by ajax request (with header `X-Requested-With`) in Pyramid? | I've solved the problem using `set_request_factory`:
```
from pyramid.request import Request
from pyramid.request import Response
def request_factory(environ):
request = Request(environ)
if request.is_xhr:
request.response = Response()
request.response.headerlist = []
request.response.... |
Pyramid CORS for Ajax requests | 21,107,057 | 8 | 2014-01-14T06:06:29Z | 22,862,087 | 8 | 2014-04-04T11:53:01Z | [
"python",
"cors",
"pyramid"
] | Is it possible automatically add `Access-Control-Allow-Origin` header to all responses which was initiated by ajax request (with header `X-Requested-With`) in Pyramid? | There are several ways to do this: 1) a custom request factory like drnextgis showed, a NewRequest event handler, or a tween. A tween is almost certainly not the right way to do this, so I won't show that. Here is the event handler version:
```
def add_cors_headers_response_callback(event):
def cors_headers(reques... |
Classification using movie review corpus in NLTK/Python | 21,107,075 | 8 | 2014-01-14T06:08:11Z | 21,126,594 | 10 | 2014-01-14T23:59:56Z | [
"python",
"nlp",
"nltk",
"sentiment-analysis",
"corpus"
] | I'm looking to do some classification in the vein of [NLTK Chapter 6](http://nltk.org/book/ch06.html). The book seems to skip a step in creating the categories, and I'm not sure what I'm doing wrong. I have my script here with the response following. My issues primarily stem from the first part -- category creation bas... | Yes, the tutorial on chapter 6 is aim for a basic knowledge for students and from there, the students should build on it by exploring what's available in NLTK and what's not. So let's go through the problems one at a time.
Firstly, the way to get 'pos' / 'neg' documents through the directory is most probably the right... |
python word count from a txt file program | 21,107,505 | 6 | 2014-01-14T06:48:35Z | 21,107,578 | 21 | 2014-01-14T06:55:30Z | [
"python",
"putty"
] | I am counting word of a txt file with the following code:
```
#!/usr/bin/python
file=open("D:\\zzzz\\names2.txt","r+")
wordcount={}
for word in file.read().split():
if word not in wordcount:
wordcount[word] = 1
else:
wordcount[word] += 1
print (word,wordcount)
file.close();
```
this is giving ... | The funny symbols you're encountering are a UTF-8 [BOM (Byte Order Mark)](http://en.wikipedia.org/wiki/Byte_order_mark). To get rid of them, open the file using the correct encoding (I'm assuming you're on Python 3):
```
file = open(r"D:\zzzz\names2.txt", "r", encoding="utf-8-sig")
```
Furthermore, for counting, you ... |
python word count from a txt file program | 21,107,505 | 6 | 2014-01-14T06:48:35Z | 21,108,583 | 22 | 2014-01-14T08:08:24Z | [
"python",
"putty"
] | I am counting word of a txt file with the following code:
```
#!/usr/bin/python
file=open("D:\\zzzz\\names2.txt","r+")
wordcount={}
for word in file.read().split():
if word not in wordcount:
wordcount[word] = 1
else:
wordcount[word] += 1
print (word,wordcount)
file.close();
```
this is giving ... | ```
#!/usr/bin/python
file=open("D:\\zzzz\\names2.txt","r+")
wordcount={}
for word in file.read().split():
if word not in wordcount:
wordcount[word] = 1
else:
wordcount[word] += 1
for k,v in wordcount.items():
print k, v
``` |
Updating json field in Postgres | 21,108,853 | 9 | 2014-01-14T08:26:55Z | 21,128,336 | 11 | 2014-01-15T03:00:10Z | [
"python",
"json",
"postgresql"
] | Querying Postgres 9.3 by json field is really great.
However i couldn't find a formal way to update the json object, for which i use an internal function written in **plpythonu** based on previous post ([How do I modify fields inside the new PostgreSQL JSON datatype?](http://stackoverflow.com/questions/18209625/how-do-... | No `eval` is required. Your issue is that you're not decoding the value as a json object.
```
CREATE OR REPLACE FUNCTION json_update(data json, key text, value json)
RETURNS json AS
$BODY$
from json import loads, dumps
if key is None: return data
js = loads(data)
# you must decode 'value' with loads too:
... |
A Python "Everything" keyword that always returns True for membership tests | 21,109,479 | 6 | 2014-01-14T09:02:49Z | 21,109,512 | 17 | 2014-01-14T09:05:07Z | [
"python"
] | I feel like I want an "Everything" keyword in Python that would have the following properties:
* Any boolean test of the form `x in Everything` would always return True, regardless of x.
* Any attempt to iterate it, such as `for x in Everything` would raise an exception
My motivation is that I would like to have an o... | ```
class Everything(object):
def __contains__(self, other):
return True
everything = Everything()
print 212134 in everything
print everything in everything
print None in everything
for i in everything:
print i # TypeError.
```
This class implements the`__contains__` behaviour for the `in` keyword. T... |
Output difference between ipython and python | 21,110,915 | 2 | 2014-01-14T10:16:06Z | 21,111,008 | 8 | 2014-01-14T10:20:42Z | [
"python",
"ipython",
"read-eval-print-loop",
"repr"
] | It was my understanding that python will print the `repr` of the output, but this is apparently not always the case. For example:
In ipython:
```
In [1]: type([])
Out[1]: list
In [2]: set([3,1,2])
Out[2]: {1, 2, 3}
```
In python:
```
>>> type([])
<type 'list'>
>>> set([3,1,2])
set([1, 2, 3])
```
What transformati... | Instead of `repr` or standard `pprint` module IPython uses `IPython.lib.pretty.RepresentationPrinter.pretty` method to [print the output](http://ipython.org/ipython-doc/dev/api/generated/IPython.lib.pretty.html#IPython.lib.pretty.RepresentationPrinter).
Module `IPython.lib.pretty` provides two functions that use `Repr... |
Can't pickle static method - Multiprocessing - Python | 21,111,106 | 7 | 2014-01-14T10:25:06Z | 21,114,450 | 8 | 2014-01-14T13:13:17Z | [
"python",
"class",
"multiprocessing",
"pickle",
"pool"
] | I'm applying some parallelization to my code, in which I use classes. I knew that is not possible to pick a class method without any other approach different of what Python provides. I found a solution [here](https://gist.github.com/fiatmoney/1086393). In my code, I have to parts that should be parallelized, both using... | You could define a plain function at the module level *and* a staticmethod as well. This preserves the calling syntax, introspection and inheritability features of a staticmethod, while avoiding the pickling problem:
```
def aux():
return "VoG - Sucess"
class VariabilityOfGradients(object):
aux = staticmetho... |
Wheel is a reference to the other Python | 21,113,163 | 8 | 2014-01-14T12:06:20Z | 21,113,214 | 8 | 2014-01-14T12:08:34Z | [
"python",
"python-wheel"
] | [PEP 427](http://www.python.org/dev/peps/pep-0427/) describes the move to [.whl files](http://wheel.readthedocs.org/) from .egg for python packaging purposes.
In the [comparisons section](http://www.python.org/dev/peps/pep-0427/#comparison-to-egg) of the PEP, there is point 6:
> Wheel is a reference to the other Pyth... | `.egg` is a reference to the snake variety of python, `.whl` is a reference to Monty Python's "wheel of cheese" |
Get the order of parameters for python function? | 21,113,443 | 2 | 2014-01-14T12:19:59Z | 21,113,468 | 9 | 2014-01-14T12:21:40Z | [
"python",
"reflection"
] | I have the following function:
```
def foo(a, b, c):
print "Hello"
```
Let's say I know it exists, and I know it takes three parameters named a, b and c, but I don't know in which order.
I want to be able to call foo given a dictionary like:
```
args = { "a": 1, "b" : 17, "c": 23 }
```
Is there a way to find o... | You don't need to; let Python figure that out for you:
```
foo(**args)
```
This applies your dictionary as keyword arguments, which is perfectly legal. You can use the arguments to `foo()` in any order when you use keyword arguments:
```
>>> def foo(a, b, c):
... print a, b, c
...
>>> foo(c=3, a=5, b=42)
5 42 3... |
Query to check if size of collection is 0 or empty in SQLAlchemy? | 21,114,830 | 4 | 2014-01-14T13:31:56Z | 21,115,972 | 9 | 2014-01-14T14:25:13Z | [
"python",
"sqlalchemy",
"flask"
] | `Person` has one `Building`.
`Person` has many `Group`
I want to return all of the `people` from a certain `building` who do not have any `Group` in their `groups` collection.
Maybe I can search by people who have a group list that has a length of 0?
Something like:
```
unassigned=Person.query.filter(Person.build... | Use negation (`~`) with [`any`](http://docs.sqlalchemy.org/en/rel_0_9/orm/internals.html#sqlalchemy.orm.properties.RelationshipProperty.Comparator.any):
```
q = session.query(Person)
q = q.filter(Person.building == g.current_building)
q = q.filter(~Person.groups.any())
```
`any` is more powerful than needed in your c... |
Possible to alter worksheet order in xlsxwriter? | 21,118,823 | 5 | 2014-01-14T16:37:24Z | 21,119,451 | 8 | 2014-01-14T17:05:02Z | [
"python",
"excel",
"xlsxwriter"
] | I have a script which creates a number of the following pairs of worksheets in order:
```
WorkSheet (holds data) -> ChartSheet using WorkSheet
```
After the script is finished, I am left with worksheets ordered as such:
```
Data1, Chart1, Data2, Chart2, Data3, Chart3, ...
```
Is it possible to re-order the workshee... | Just sort `workbook.worksheets_objs` list:
```
import xlsxwriter
workbook = xlsxwriter.Workbook('test.xlsx')
sheet_names = ['Data1', 'Chart1', 'Data2', 'Chart2', 'Data3', 'Chart3']
for sheet_name in sheet_names:
workbook.add_worksheet(sheet_name)
# sort sheets based on name
workbook.worksheets_objs.sort(key=la... |
Catching KeyboardInterrupt in Python during program shutdown | 21,120,947 | 17 | 2014-01-14T18:17:03Z | 21,144,662 | 26 | 2014-01-15T17:48:43Z | [
"python",
"keyboardinterrupt"
] | I'm writing a command line utility in Python which, since it is production code, ought to be able to shut down cleanly without dumping a bunch of stuff (error codes, stack traces, etc.) to the screen. This means I need to catch keyboard interrupts.
I've tried using both a try catch block like:
```
if __name__ == '__m... | Checkout [this thread](http://stackoverflow.com/questions/1187970/how-to-exit-from-python-without-traceback), it has some useful information about exiting and tracebacks.
If you are more interested in just killing the program, try something like this (this will take the legs out from under the cleanup code as well):
... |
Apache2 mod_wsgi 403 forbidden error | 21,122,121 | 2 | 2014-01-14T19:21:31Z | 21,267,129 | 8 | 2014-01-21T19:17:00Z | [
"python",
"apache",
"mod-wsgi"
] | I had it configured right, but then I decided to reinstall my Debian (switching from wheezy to jessie version by the way). Here's the problem:
I have a python mod\_wsgi application at: `/mnt/doc/Python/www/index.py`.
```
$ ls -l / | grep mnt
drwxr-xr-x 3 root root 4096 sty 12 09:36 mnt
$ ls -l /mnt
drwxrwxrwx 1 s... | I solved it finally. pxl was half-right, because not only `Allow from all` should be replaced by `Reuqire from all`, but also `Order allow,deny` is no longer necessary. It turns out to be the reason for my error. Complete script alias config should be like this:
```
WSGIScriptAlias /huh /mnt/doc/Python/www/index.py ... |
input() error - NameError: name '...' is not defined | 21,122,540 | 52 | 2014-01-14T19:44:14Z | 21,122,697 | 12 | 2014-01-14T19:53:13Z | [
"python",
"python-2.7",
"python-3.x",
"input",
"nameerror"
] | I am getting an error when I try to run this simple python script:
```
input_variable = input ("Enter your name: ")
print ("your name is" + input_variable)
```
Lets say I type in "dude", the error I am getting is:
```
line 1, in <module>
input_variable = input ("Enter your name: ")
File "<string>", line 1, in <modul... | You are running Python 2, not Python 3. For this to work in Python 2, use `raw_input`.
```
input_variable = raw_input ("Enter your name: ")
print ("your name is" + input_variable)
``` |
input() error - NameError: name '...' is not defined | 21,122,540 | 52 | 2014-01-14T19:44:14Z | 21,122,817 | 111 | 2014-01-14T20:00:05Z | [
"python",
"python-2.7",
"python-3.x",
"input",
"nameerror"
] | I am getting an error when I try to run this simple python script:
```
input_variable = input ("Enter your name: ")
print ("your name is" + input_variable)
```
Lets say I type in "dude", the error I am getting is:
```
line 1, in <module>
input_variable = input ("Enter your name: ")
File "<string>", line 1, in <modul... | **TL;DR**
`input` function in Python 2.7, evaluates whatever your enter, as a Python expression. If you simply want to read strings, then use `raw_input` function in Python 2.7, which will not evaluate the read strings.
If you are using Python 3.x, `raw_input` has been renamed to `input`. Quoting the [Python 3.0 rele... |
How do I manipulate a variable whose name conflicts with PDB commands? | 21,123,473 | 16 | 2014-01-14T20:35:53Z | 21,127,663 | 7 | 2014-01-15T01:46:12Z | [
"python",
"pdb"
] | My code is, for better or worse, rife with single letter variables (it's physics stuff, so those letters are meaningful), as well as NumPy's, which I'm often interacting with.
When using the Python debugger, occasionally I'll want to look at the value of, say, `n`. However, when I hit `n<enter>`, that's the PDB comman... | You can use semicolons, so just put something else in front of it:
```
ipdb> print n
2
ipdb> n
> 145 <some code here>
146
147
ipdb> 1; n=4
1
ipdb> print n
4
``` |
How do I manipulate a variable whose name conflicts with PDB commands? | 21,123,473 | 16 | 2014-01-14T20:35:53Z | 26,828,151 | 22 | 2014-11-09T12:28:06Z | [
"python",
"pdb"
] | My code is, for better or worse, rife with single letter variables (it's physics stuff, so those letters are meaningful), as well as NumPy's, which I'm often interacting with.
When using the Python debugger, occasionally I'll want to look at the value of, say, `n`. However, when I hit `n<enter>`, that's the PDB comman... | Use an exclamation mark `!` before a statement to have it run :
```
python -m pdb test.py
> /home/user/test.py(1)<module>()
-> print('foo')
(Pdb) !n = 77
(Pdb) !n
77
(Pdb) n
foo
> /home/user/test.py(2)<module>()
-> print('bar')
(Pdb)
``` |
where is "from __future__ import braces" code | 21,125,228 | 35 | 2014-01-14T22:21:01Z | 21,125,305 | 42 | 2014-01-14T22:24:50Z | [
"python",
"python-2.7",
"python-internals"
] | I was wondering what is exactly the code that executed on the command:
```
>>> from __future__ import braces
SyntaxError: not a chance
```
so, since python is open-sourced I opened `C:\Python27\Lib\__future__.py` and looked.
surprisingly, I found nothing there that handle importing `braces` module.
so, my question i... | The code is in [future.c](http://hg.python.org/cpython/file/956b8afdaa3e/Python/future.c#l14):
```
future_check_features(PyFutureFeatures *ff, stmt_ty s, const char *filename)
...
else if (strcmp(feature, "braces") == 0) {
PyErr_SetString(PyExc_SyntaxError,
"not a chance");
PyErr_SyntaxLocation(filen... |
Python 2.7: log displayed twice when `logging` module is used in two python scripts | 21,127,360 | 5 | 2014-01-15T01:15:32Z | 21,127,526 | 9 | 2014-01-15T01:32:30Z | [
"python",
"python-2.7",
"logging"
] | # Context:
Python 2.7.
Two files in the same folder:
* First: main script.
* Second: custom module.
# Goal:
Possibility to use the `logging` module without any clash (see output below).
# Files:
## a.py:
```
import logging
from b import test_b
def test_a(logger):
logger.debug("debug")
logger.info("info... | I'm not sure I understand your case, because the description doesn't match the outputâ¦Â but I think I know what your problem is.
As [the docs](http://docs.python.org/2/library/logging.html#logging.Logger.propagate) explain:
> **Note:** If you attach a handler to a logger and one or more of its ancestors, it may emi... |
Factorial function works in Python, returns 0 for Julia | 21,127,770 | 12 | 2014-01-15T01:56:15Z | 21,127,971 | 20 | 2014-01-15T02:18:10Z | [
"python",
"julia-lang"
] | I define a factorial function as follows in Python:
```
def fact(n):
if n == 1:
return n
else:
return n * fact(n-1)
print(fact(100))
```
and as follows in Julia:
```
function fact(n)
if n == 1
n
else
n * fact(n-1)
end
end
println(fact(100))
```
The python progra... | Julia has separate fixed-size integer types, plus a BigInt type. The default type is `Int64`, which is of course 64 bits.
Since 100! takes about 526 bits, it obviously overflows an `Int64`.
You can solve this problem by just doing `fact(BigInt(100))` (assuming you've `require`d it), or of course you can do the conver... |
Factorial function works in Python, returns 0 for Julia | 21,127,770 | 12 | 2014-01-15T01:56:15Z | 21,128,011 | 10 | 2014-01-15T02:21:29Z | [
"python",
"julia-lang"
] | I define a factorial function as follows in Python:
```
def fact(n):
if n == 1:
return n
else:
return n * fact(n-1)
print(fact(100))
```
and as follows in Julia:
```
function fact(n)
if n == 1
n
else
n * fact(n-1)
end
end
println(fact(100))
```
The python progra... | I guess the answer to this is to use `BigInt`:
```
function fact(n::BigInt)
if n == BigInt(1) ... |
Factorial function works in Python, returns 0 for Julia | 21,127,770 | 12 | 2014-01-15T01:56:15Z | 21,148,186 | 15 | 2014-01-15T21:05:50Z | [
"python",
"julia-lang"
] | I define a factorial function as follows in Python:
```
def fact(n):
if n == 1:
return n
else:
return n * fact(n-1)
print(fact(100))
```
and as follows in Julia:
```
function fact(n)
if n == 1
n
else
n * fact(n-1)
end
end
println(fact(100))
```
The python progra... | Nobody answers why the result in Julia is 0.
Julia does not check integer multiplication for overflow and thus the multiplication for 64 bit integers is performed mod 2^63. See [this FAQ entry](http://docs.julialang.org/en/latest/manual/faq/#why-does-julia-use-native-machine-integer-arithmetic)
when you write out the... |
How to make an auto increment integer field Django | 21,128,899 | 12 | 2014-01-15T04:01:50Z | 21,130,206 | 23 | 2014-01-15T06:06:29Z | [
"python",
"django",
"django-models",
"sqlite3"
] | the question is simple, I am making an order for shopping cart and I need to make a field that auto increments when the order is made. But I don't know how to make the integer field auto increment :S any help.
order.py
```
class Order(models.Model):
cart = models.ForeignKey(Cart)
add_date = models.DateTimeFie... | In Django
1 : There will be a default field with name "id" which is auto increment .
2 : You can define any field as auto increment field using `AutoField`
field.
```
class Order(models.Model):
auto_increment_id = models.AutoField(primary_key=True)
#you use primary_key = True if you do not want to use defaul... |
How to make an auto increment integer field Django | 21,128,899 | 12 | 2014-01-15T04:01:50Z | 34,872,412 | 9 | 2016-01-19T08:58:18Z | [
"python",
"django",
"django-models",
"sqlite3"
] | the question is simple, I am making an order for shopping cart and I need to make a field that auto increments when the order is made. But I don't know how to make the integer field auto increment :S any help.
order.py
```
class Order(models.Model):
cart = models.ForeignKey(Cart)
add_date = models.DateTimeFie... | In django with every model you will get the by default id field that is auto increament. But still if you manually want to use auto increment. You just need to specify in your Model `AutoField`.
```
class Author(models.Model):
author_id = models.AutoField(primary_key=True)
```
you can read more about the auto fie... |
Plotting a horizontal line on multiple subplots in python using pyplot | 21,129,007 | 10 | 2014-01-15T04:14:46Z | 21,129,112 | 16 | 2014-01-15T04:26:07Z | [
"python",
"matplotlib",
"scatter-plot",
"subplot",
"line-plot"
] | I am plotting three subplots on the same page. I want to draw a horiZontal line through all the subplots. Following is my code and the resultant graph: (You can notice I can get the horizontal line on one of the plots, but not all)
```
gs1 = gridspec.GridSpec(8, 2)
gs1.update(left=0.12, right=.94, wspace=0.12)
ax1 = p... | I found a way to do it for anyone who stumbles on this anyways.
We need to replace the following line from the OP:
```
plt.axhline(y=0.002, xmin=0, xmax=1, hold=None)
```
We replace it with:
```
ax1.axhline(y=0.002,xmin=0,xmax=3,c="blue",linewidth=0.5,zorder=0)
ax2.axhline(y=0.002,xmin=0,xmax=3,c="blue",linewidth=0... |
How to fix: "UnicodeDecodeError: 'ascii' codec can't decode byte" | 21,129,020 | 107 | 2014-01-15T04:15:37Z | 21,129,492 | 71 | 2014-01-15T05:04:19Z | [
"python",
"python-2.7"
] | ```
as3:~/ngokevin-site# nano content/blog/20140114_test-chinese.mkd
as3:~/ngokevin-site# wok
Traceback (most recent call last):
File "/usr/local/bin/wok", line 4, in
Engine()
File "/usr/local/lib/python2.7/site-packages/wok/engine.py", line 104, in init
self.load_pages()
File "/usr/local/lib/python2.7/site-packages/wo... | This is the classic "unicode issue". I believe that explaining this is beyond the scope of a StackOverflow answer to completely explain what is happening.
It is well explained [here](http://nedbatchelder.com/text/unipain.html).
In very brief summary, you have passed something that is being interpreted as a string of ... |
How to fix: "UnicodeDecodeError: 'ascii' codec can't decode byte" | 21,129,020 | 107 | 2014-01-15T04:15:37Z | 21,190,382 | 209 | 2014-01-17T16:03:41Z | [
"python",
"python-2.7"
] | ```
as3:~/ngokevin-site# nano content/blog/20140114_test-chinese.mkd
as3:~/ngokevin-site# wok
Traceback (most recent call last):
File "/usr/local/bin/wok", line 4, in
Engine()
File "/usr/local/lib/python2.7/site-packages/wok/engine.py", line 104, in init
self.load_pages()
File "/usr/local/lib/python2.7/site-packages/wo... | **Finally I got it:**
```
as3:/usr/local/lib/python2.7/site-packages# cat sitecustomize.py
# encoding=utf8
import sys
reload(sys)
sys.setdefaultencoding('utf8')
```
**Let me check:**
```
as3:~/ngokevin-site# python
Python 2.7.6 (default, Dec 6 2013, 14:49:02)
[GCC 4.4.5] on linux2
Type "help", "copyright", "... |
How to fix: "UnicodeDecodeError: 'ascii' codec can't decode byte" | 21,129,020 | 107 | 2014-01-15T04:15:37Z | 26,767,972 | 20 | 2014-11-05T22:01:27Z | [
"python",
"python-2.7"
] | ```
as3:~/ngokevin-site# nano content/blog/20140114_test-chinese.mkd
as3:~/ngokevin-site# wok
Traceback (most recent call last):
File "/usr/local/bin/wok", line 4, in
Engine()
File "/usr/local/lib/python2.7/site-packages/wok/engine.py", line 104, in init
self.load_pages()
File "/usr/local/lib/python2.7/site-packages/wo... | In some cases, when you check your default encoding (`print sys.getdefaultencoding()`), it returns that you are using ASCII. If you change to UTF-8, it doesn't work, depending on the content of your variable.
I found another way:
```
import sys
reload(sys)
sys.setdefaultencoding('Cp1252')
``` |
How to fix: "UnicodeDecodeError: 'ascii' codec can't decode byte" | 21,129,020 | 107 | 2014-01-15T04:15:37Z | 35,444,608 | 58 | 2016-02-16T22:54:20Z | [
"python",
"python-2.7"
] | ```
as3:~/ngokevin-site# nano content/blog/20140114_test-chinese.mkd
as3:~/ngokevin-site# wok
Traceback (most recent call last):
File "/usr/local/bin/wok", line 4, in
Engine()
File "/usr/local/lib/python2.7/site-packages/wok/engine.py", line 104, in init
self.load_pages()
File "/usr/local/lib/python2.7/site-packages/wo... | # tl;dr
* Don't decode/encode willy nilly
* Don't assume your strings are UTF-8 encoded
* Try to convert strings to Unicode strings as soon as possible in your code
# The Long Version
Without seeing the source it's difficult to know the root cause, so I'll have to speak generally.
`UnicodeDecodeError: 'ascii' codec... |
Decoding a Cryptic Python statement | 21,131,742 | 2 | 2014-01-15T07:47:25Z | 21,132,097 | 7 | 2014-01-15T08:07:54Z | [
"python"
] | I saw this on a job ad (on SO):
```
lambda f: (lambda a: a(a))(lambda b: f(lambda *args: b(b)(*args)))
```
So what I understand is it is an anonymous (unnamed) function, which is composed of two further nested anonymous functions. The innermost function takes a variable list of arguements (\*args).
I can't work out ... | I've undone the lambdas just to make it a little easier to read. Here's the code using nested functions:
```
def f1(f):
def f2(a):
return a(a)
def f3(b):
def f4(*args):
return b(b)(*args)
return f(f4)
return f2(f3)
```
This would be equivalent basically to:
```
f1 =... |
Using cython to early type class attributes | 21,131,884 | 4 | 2014-01-15T07:56:28Z | 21,132,931 | 8 | 2014-01-15T08:59:02Z | [
"python",
"class",
"cython"
] | I'm writing a python class and I would like to accelerate the execution using cython early typing.
I get the error `"Syntax error in C variable declaration"` when I try to cython compile the following:
```
import numpy as np
cimport numpy as np
class MyClass:
def __init__( self, np.ndarray[double, ndim=1] Redge... | What you want is to define an [*extension* type](http://docs.cython.org/src/userguide/extension_types.html). In particular your code should look like:
```
import numpy as np
cimport numpy as np
cdef class MyClass:
cdef double var1
cdef np.ndarray[double, ndim=1] Redges
def __init__( self, np.ndarray[doub... |
Error by sudo pip install pil on Mac 10.9.1 | 21,135,568 | 4 | 2014-01-15T10:58:13Z | 21,135,690 | 8 | 2014-01-15T11:03:50Z | [
"python",
"django",
"xcode",
"osx"
] | I am trying to install PIL on Mac 10.9.1 I get an error message which I can not get to find here. I have already installed Python27, pip, DJango, now I try to install:
```
sudo pip install pil
```
The message I receive:
```
Downloading/unpacking PIL
Could not find any downloads that satisfy the requirement PIL
S... | There's a fork of PIL called [Pillow](http://pillow.readthedocs.org/en/latest/) that most probably will solve your issue. |
Format / Suppress Scientific Notation from Python Pandas Aggregation Results | 21,137,150 | 18 | 2014-01-15T12:14:36Z | 21,140,339 | 33 | 2014-01-15T14:40:32Z | [
"python",
"pandas"
] | How can one modify the format for the output from a groupby operation in pandas that produces scientific notation for very large numbers. I know how to do string formatting in pythong but I'm at a loss when it comes to applying it here.
```
df1.groupby('dept')['data1'].sum()
dept
value1 1.192433e+08
value2 ... | Granted, the answer I linked in the comments is not very helpful. You can specify your own string converter like so.
```
In [25]: pd.set_option('display.float_format', lambda x: '%.3f' % x)
In [28]: Series(np.random.randn(3))*1000000000
Out[28]:
0 -757322420.605
1 -1436160588.997
2 -1235116117.064
dtype: floa... |
AttributeError: '_AppCtxGlobals' object has no attribute 'user' in Flask | 21,138,025 | 9 | 2014-01-15T12:55:59Z | 21,138,130 | 14 | 2014-01-15T13:01:23Z | [
"python",
"flask",
"attributeerror"
] | I'm trying to learn flask by following the [Flask Mega Tutorial](http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world). In [part 5](http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-v-user-logins), the login() view is edit like so:
```
@app.route('/login', methods = ['GET', 'PO... | The same tutorial, a little further on, explains how `g.user` is set:
> ## The g.user global
>
> If you were paying attention, you will remember that in the login view function we check `g.user` to determine if a user is already logged in. To implement this we will use the `before_request` event from Flask. Any functi... |
False Unused Import Statement in PyCharm? | 21,139,329 | 18 | 2014-01-15T13:55:36Z | 21,143,553 | 8 | 2014-01-15T16:56:59Z | [
"python",
"ide",
"pycharm"
] | Given this scenario:
b.py:
```
import A
# A is unused here
```
c.py:
```
from b import A
# A is used here
```
PyCharm complains in b.py that "import A" is an unused import and Optimize imports deletes it, breaking import in c.py
I know these chained imports are not a good practice (although you may use it to impl... | As far as I can tell this behaviour is *not* handled as an inspection or some other configurable option, which means there is no `#noinspection UnusedImport` (or equivalent) that can be placed before the imports.
If you don't want to define an unused block where you use those variables there's an other simple and prob... |
False Unused Import Statement in PyCharm? | 21,139,329 | 18 | 2014-01-15T13:55:36Z | 21,469,018 | 31 | 2014-01-30T22:44:11Z | [
"python",
"ide",
"pycharm"
] | Given this scenario:
b.py:
```
import A
# A is unused here
```
c.py:
```
from b import A
# A is used here
```
PyCharm complains in b.py that "import A" is an unused import and Optimize imports deletes it, breaking import in c.py
I know these chained imports are not a good practice (although you may use it to impl... | You can actually use the `PyUnresolvedReferences` marker to deactivate the inspection for your import statement:
```
# noinspection PyUnresolvedReferences
import A
```
Reference: [PyCharm bug PY-2240](http://youtrack.jetbrains.com/issue/PY-2240) |
How to import python class file from same directory? | 21,139,364 | 9 | 2014-01-15T13:56:57Z | 21,139,466 | 13 | 2014-01-15T14:01:32Z | [
"python",
"python-3.x",
"python-import"
] | I have a directory in my Python 3.3 project called /models.
from my main.py I simply do a
```
from models import *
```
in my `__init__.py`
```
__all__ = ["Engine","EngineModule","Finding","Mapping","Rule","RuleSet"]
from models.engine import Engine,EngineModule
from models.finding import Finding
from models.mapping... | Since you are using Python 3, which disallows these relative imports (it can lead to confusion between modules of the same name in different packages).
Use either:
```
from models import finding
```
or
```
import models.finding
```
or, probably best:
```
from . import finding # The . means "from the same directo... |
AJAX and Python Error - No 'Access-Control-Allow-Origin' header is present on the requested resource | 21,140,038 | 2 | 2014-01-15T14:28:20Z | 21,140,254 | 8 | 2014-01-15T14:36:29Z | [
"javascript",
"python",
"ajax",
"jquery"
] | I'm building a Javascript library that can talk to a simple Python web server using AJAX.
Here is the web server class:
```
class WebHandler(http.server.BaseHTTPRequestHandler):
def parse_POST(self):
ctype, pdict = cgi.parse_header(self.headers['content-type'])
if ctype == 'multipart/form-data':
... | There is a lot of topics about: Access-Control-Allow-Origin. Read more: <http://en.wikipedia.org/wiki/Same_origin_policy>
Add this lines after: `self.send_header("Content-type", "application/json")`
```
self.send_header("Access-Control-Allow-Origin","*");
self.send_header("Access-Control-Expose-Headers: Access-Contro... |
Group consecutive integers and tolerate gaps of 1 | 21,142,231 | 6 | 2014-01-15T16:02:11Z | 21,142,465 | 9 | 2014-01-15T16:11:36Z | [
"python",
"list",
"grouping",
"itertools"
] | In Python, given a list of sorted integers, I would to group them by consecutive values ***and* tolerate gaps of 1.**
For instance, given a list `my_list`:
```
In [66]: my_list
Out[66]: [0, 1, 2, 3, 5, 6, 10, 11, 15, 16, 18, 19, 20]
```
I would like the following output:
```
[[0, 1, 2, 3, 5, 6], [10, 11], [15, 16, ... | When in doubt you can always write your own generator:
```
def group_runs(li,tolerance=2):
out = []
last = li[0]
for x in li:
if x-last > tolerance:
yield out
out = []
out.append(x)
last = x
yield out
```
demo:
```
list(group_runs(my_list))
Out[48]: [[0... |
ImportError: cannot import name <model_class> | 21,142,366 | 2 | 2014-01-15T16:07:53Z | 21,157,024 | 8 | 2014-01-16T08:45:27Z | [
"python",
"django",
"django-models",
"django-forms"
] | I am using `forms.ModelChoiceField` to have the choice loaded from a specific model entries:
```
from order.models import Region
class CheckoutForm(forms.Form):
area = forms.ModelChoiceField(queryset=Region.objects.all(),label=("Area"))
```
The problem I am facing is that when importing the class name from the a... | As I mentioned in the comments, you have a circular dependency between your forms and models files. You'll either need to refactor to remove the circularity, or if you really can't do that you'll have to move one of the imports into the function where it's used. |
Python: Wait on all of `concurrent.futures.ThreadPoolExecutor`'s futures | 21,143,162 | 11 | 2014-01-15T16:40:29Z | 21,143,809 | 9 | 2014-01-15T17:08:19Z | [
"python",
"concurrency",
"future"
] | I've given `concurrent.futures.ThreadPoolExecutor` a bunch of tasks, and I want to wait until they're all completed before proceeding with the flow. How can I do that, without having to save all the futures and call `wait` on them? (I want an action on the executor.) | Just call [`Executor.shutdown`](http://docs.python.org/3.3/library/concurrent.futures.html#concurrent.futures.Executor.shutdown):
> **`shutdown(wait=True)`**
>
> Signal the executor that it should free any resources that it is
> using *when the currently pending futures are done executing*. Calls
> to `Executor.submit... |
How do I find the nth day of the next month in Python? | 21,145,618 | 3 | 2014-01-15T18:38:54Z | 21,145,729 | 7 | 2014-01-15T18:45:31Z | [
"python",
"datetime"
] | I am trying to get the date `delta` by subtracting today's date from the `nth` day of the next month.
```
delta = nth_of_next_month - todays_date
print delta.days
```
**How do you get the date object for the 1st (or 2nd, 3rd.. nth) day of the next month.** I tried taking the month number from the date object and incr... | The `dateutil` library is useful for this:
```
from dateutil.relativedelta import relativedelta
from datetime import datetime
# Where day is the day you want in the following month
dt = datetime.now() + relativedelta(months=1, day=20)
``` |
pandas to_csv output quoting issue | 21,147,058 | 3 | 2014-01-15T20:01:08Z | 21,147,228 | 9 | 2014-01-15T20:11:09Z | [
"python",
"file-io",
"pandas"
] | I am fairly new to python pandas, but having trouble getting the to\_csv output quoting right.
```
import pandas as pd
text = 'this is "out text"'
df = pd.DataFrame(index=['1'],columns=['1','2'])
df.loc['1','1']=123
df.loc['1','2']=text
df.to_csv('foo.txt',index=False,header=False)
```
The output is:
> 123,"this is... | You could pass `quoting=csv.QUOTE_NONE`, for example:
```
>>> df.to_csv('foo.txt',index=False,header=False)
>>> !cat foo.txt
123,"this is ""out text"""
>>> import csv
>>> df.to_csv('foo.txt',index=False,header=False, quoting=csv.QUOTE_NONE)
>>> !cat foo.txt
123,this is "out text"
```
but in my experience it's better ... |
What is the correct way to get the previous page of results given an NDB cursor? | 21,148,476 | 13 | 2014-01-15T21:20:47Z | 21,203,487 | 7 | 2014-01-18T11:31:31Z | [
"python",
"google-app-engine",
"gae-datastore",
"app-engine-ndb"
] | I'm working on providing an API via GAE that will allow users to page forwards and backwards through a set of entities. I've reviewed the [section about cursors on the NDB Queries documentation page](https://developers.google.com/appengine/docs/python/ndb/queries#cursors), which includes some sample code that describes... | To make the example from the docs a little clearer let's forget about the datastore for a moment and work with a list instead:
```
# some_list = [4, 6, 1, 12, 15, 0, 3, 7, 10, 11, 8, 2, 9, 14, 5, 13]
# Set up.
q = Bar.query()
q_forward = q.order(Bar.key)
# This puts the elements of our list into the following order:... |
Finding a better way to count matrices | 21,149,014 | 8 | 2014-01-15T21:52:56Z | 21,210,460 | 8 | 2014-01-18T22:02:50Z | [
"python",
"performance",
"algorithm",
"math",
"numpy"
] | I would like to count the number of 2d arrays with only 1 and 0 entries that have a disjoint pair of disjoint pairs of rows that have equal vector sums. For a 4 by 4 matrix the following code achieves this by just iterating over all of them and testing each one in turn.
```
import numpy as np
from itertools import com... | Computed in about a minute on my machine, with CPython 3.3:
```
4 3136
5 3053312
6 7247819776
7 53875134036992
8 1372451668676509696
```
Code, based on memoized inclusion-exclusion:
```
#!/usr/bin/env python3
import collections
import itertools
def pairs_of_pairs(n):
for (i, j, k, m) in itertools.combinations(r... |
Pandas: import multiple csv files into dataframe using a loop and hierarchical indexing | 21,149,920 | 10 | 2014-01-15T22:48:37Z | 21,150,533 | 10 | 2014-01-15T23:33:40Z | [
"python",
"csv",
"pandas",
"hierarchical-data"
] | I would like to read multiple CSV files (with a different number of columns) from a target directory into a single Python Pandas DataFrame to efficiently search and extract data.
Example file:
```
Events
1,0.32,0.20,0.67
2,0.94,0.19,0.14,0.21,0.94
3,0.32,0.20,0.64,0.32
4,0.87,0.13,0.61,0.54,0.25,0.43
5,0.62,0.21,0.... | You need to decide in what axis you want to append your files. Pandas will always try to do the right thing by:
1. Assuming that each column from each file is different, and appending digits to columns with similar names across files if necessary, so that they don't get mixed;
2. Items that belong to the same row inde... |
UnicodeDecodeError error writing .xlsx file using xlsxwriter | 21,150,783 | 5 | 2014-01-15T23:52:48Z | 21,151,185 | 7 | 2014-01-16T00:29:25Z | [
"python",
"xlsxwriter"
] | I am trying to write about 1000 rows to a .xlsx file from my python application. The data is basically a combination of integers and strings. I am getting intermittent error while running wbook.close() command. The error is the following:
```
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 15:
... | 0xc3 is "Ã". So what you need to do is change the encoding. Use the decode() method.
```
string.decode('utf-8')
```
Also depending on your needs and uses you could add
```
# -*- coding: utf-8 -*-
```
at the beginning of your script, but only if you are sure that the encoding will not interfere and break something ... |
How to apply hierarchy or multi-index to panda columns | 21,151,510 | 9 | 2014-01-16T01:00:50Z | 21,151,663 | 8 | 2014-01-16T01:15:56Z | [
"python",
"pandas",
"dataframe"
] | I have seen lots of examples on how to arrange dataframe row indexes hierarchically, but I am trying to do the same for columns and am not understanding the syntax:
Given:
```
df = pd.DataFrame(np.random.randn(10,10),
columns=['consumption', 'voltage', 'consumption',
'vol... | You can [define `MultiIndices`](http://pandas.pydata.org/pandas-docs/stable/indexing.html#creating-a-multiindex-hierarchical-index-object) using the `from_arrays` or `from_tuples` or `from_product` classmethods. Here is an example using `from_arrays`:
```
arrays = [[1, 2]*3, ['A', 'B', 'C']*2]
columns = pd.MultiIndex.... |
Convert unicode to datetime proper strptime format | 21,151,664 | 11 | 2014-01-16T01:15:57Z | 21,151,903 | 16 | 2014-01-16T01:41:15Z | [
"python",
"django",
"datetime",
"unicode",
"strptime"
] | I am trying to convert a unicode object to a datetime object.
I read through the documentation: <http://docs.python.org/2/library/time.html#time.strptime>
and tried
```
datetime.strptime(date_posted, '%Y-%m-%dT%H:%M:%SZ')
```
but I get the error message `ValueError: time data '2014-01-15T01:35:30.314Z' does not mat... | You can parse the microseconds:
```
from datetime import datetime
date_posted = '2014-01-15T01:35:30.314Z'
datetime.strptime(date_posted, '%Y-%m-%dT%H:%M:%S.%fZ')
``` |
broken easy_install and pip after upgrading to OS X Mavericks | 21,151,695 | 18 | 2014-01-16T01:18:34Z | 21,751,997 | 29 | 2014-02-13T10:48:42Z | [
"python",
"pip",
"osx-mavericks",
"setuptools",
"easy-install"
] | Upgraded to OS X 10.9 Mavericks and installed XCode, Command Line Tools, XQuartz, etc. Trying to run a pip install now, but it says that the distribution is not found:
```
Traceback (most recent call last):
File "/usr/local/bin/pip", line 5, in <module>
from pkg_resources import load_entry_point
File "/Sy... | 1. Install `easy_install`:
Download `ez_setup.py` module from <https://pypi.python.org/pypi/setuptools>
```
$ cd path/to/ez_setup.py
$ python ez_setup.py
```
2. Install `pip`:
```
$ sudo easy_install pip
``` |
Error in SQLAlchemy with Integer: "object() takes no parameters" | 21,152,894 | 5 | 2014-01-16T03:36:51Z | 21,152,980 | 7 | 2014-01-16T03:47:55Z | [
"python",
"sqlalchemy"
] | I suddenly started seeing an error in my Python SQLAlchemy application and I can't figure out what's causing it. My code looks like this:
```
from sqlalchemy import create_engine
from sqlalchemy import Column
from sqlalchemy import ForeignKey
from sqlalchemy import Integer
from sqlalchemy import MetaData
from sqlalche... | `Integer` takes no parameters. This is a change in version 0.9.
There exist `BigInteger` and `SmallInteger` instead. |
How to read the describe_stack Output attribute | 21,154,126 | 4 | 2014-01-16T05:38:55Z | 21,160,452 | 8 | 2014-01-16T11:25:21Z | [
"python",
"amazon-web-services",
"boto"
] | i have created a stack in cloudformatin and wants to get the output.
My code is:
```
c = a.describe_stacks('Stack_id')
print c
```
Returns an object
```
<boto.cloudformation.stack.StackSummary object at 0x1901d10>
``` | The call to `describe_stacks` should return a list of `Stack` objects, not a single `StackSummary` object. Let's just walk through a complete example to avoid confusion.
First, do something like this:
```
import boto.cloudformation
conn = boto.cloudformation.connect_to_region('us-west-2') # or your favorite region
s... |
setting expiration time to django password reset token | 21,155,264 | 8 | 2014-01-16T07:01:13Z | 22,522,549 | 12 | 2014-03-20T02:55:07Z | [
"python",
"django",
"django-users"
] | I am using the inbuilt password reset functionality of Django which emails the user the password reset link. Is there an option in Django to set an expiration time to the link suppose 6 hours after which the link become invalid and user will have to request again for password recovery. | If you're using Django's built-in password reset functionality, you can use the setting `PASSWORD_RESET_TIMEOUT_DAYS`.
Example: if a user clicks a password reset link that was generated 2 days ago and you have `PASSWORD_RESET_TIMEOUT_DAYS=1` in your project's settings, the link will be invalid and the user cannot cont... |
Call method on multiple instances in Python | 21,155,355 | 3 | 2014-01-16T07:06:38Z | 21,155,442 | 7 | 2014-01-16T07:10:39Z | [
"python"
] | Is there something like this:
```
a,b,c = a,b,c.method()
```
?
It's just an example, I want to know the shortest way to do this | Not exactly that short, but if I understand you correct, this will work:
```
a, b, c = (x.method() for x in (a, b, c))
```
(Note, that if `a`, `b` or `c` are referring to the same object, the method will be called few times). |
Set environment variable using saltstack | 21,156,186 | 12 | 2014-01-16T07:54:31Z | 21,176,019 | 7 | 2014-01-17T01:02:52Z | [
"python",
"tomcat",
"salt-stack"
] | I am writing some salt stack formulas which will install tomcat package. but after installation I have to set JAVA\_HOME in /etc/default/tomcat7 file. Is there any option to set JAVA\_HOME? Or is there any option to modify or add JAVA\_HOME in environment variable (i.e. in .bashrc or .profile files)?
My pillar.example... | As an alternative to setting .bashrc or .profile, you could simply set the JAVA\_HOME value directly in /etc/default/tomcat7:
```
tomcat_configuration:
file.append:
- name: /etc/default/tomcat7
- text: export JAVA_HOME={{ pillar['java_home'] }}
```
If for some reason `file.append` is not suitable, salt offe... |
iterating through queue with for loop instead of while loop | 21,157,739 | 7 | 2014-01-16T09:20:29Z | 21,157,892 | 11 | 2014-01-16T09:27:49Z | [
"python"
] | Normally we code it like this:
```
while not queue.empty():
try:
job = queue.get()
```
But is it also possible to do something in the lines of:
```
for job in queue.get():
#do stuff to job
```
The real reason why I want to do that is because I wanted to use python-progressbar's auto detect maxval. They do... | You can use [`iter`](http://docs.python.org/2/library/functions.html#iter) with callable. (You should pass two arguments, one for the callable, the other for the sentinel value)
```
for job in iter(queue.get, None): # Replace `None` as you need.
# do stuff with job
```
**NOTE** This will block when there's no ele... |
query from postgresql using python as dictionary | 21,158,033 | 5 | 2014-01-16T09:33:56Z | 21,158,697 | 7 | 2014-01-16T10:05:40Z | [
"python",
"postgresql",
"python-2.7",
"dictionary",
"psycopg2"
] | I'm using Python 2.7 and postgresql 9.1.
Trying to get dictionary from query, I've tried the code as described here:
<http://wiki.postgresql.org/wiki/Using_psycopg2_with_PostgreSQL>
```
import psycopg2
import psycopg2.extras
conn = psycopg2.connect("dbname=mydb host=localhost user=user password=password")
cur = conn.c... | Tnx a lot Andrey Shokhin ,
full answer is:
```
#!/var/bin/python
import psycopg2
import psycopg2.extras
conn = psycopg2.connect("dbname=uniart4_pr host=localhost user=user password=password")
cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
cur.execute ("select * from port")
ans =cur.fetchall()
ans1 = []... |
Comparing two paths in python | 21,158,667 | 7 | 2014-01-16T10:04:20Z | 21,158,837 | 9 | 2014-01-16T10:12:20Z | [
"python",
"python-2.7",
"path"
] | consider,
```
path1 = "c:/fold1/fold2"
list_of_paths = ["c:\\fold1\\fold2","c:\\temp\\temp123"]
if path1 in list_of_paths:
print "found"
```
I expect if statement to return true but it evaluates to False
since it is string comparision
how to compare two paths irrespective of forward or backward slash it has !
i... | Use [`os.path.normpath`](http://docs.python.org/2/library/os.path.html#os.path.normpath) to convert `c:/fold1/fold2` to `c:\fold1\fold2`:
```
>>> path1 = "c:/fold1/fold2"
>>> list_of_paths = ["c:\\fold1\\fold2","c:\\temp\\temp123"]
>>> os.path.normpath(path1)
'c:\\fold1\\fold2'
>>> os.path.normpath(path1) in list_of_p... |
What kind of problems (if any) would there be combining asyncio with multiprocessing? | 21,159,103 | 23 | 2014-01-16T10:25:33Z | 29,147,750 | 19 | 2015-03-19T14:50:04Z | [
"python",
"multithreading",
"asynchronous",
"multiprocessing",
"python-asyncio"
] | As almost everyone is aware when they first look at threading in Python, there is the GIL that makes life miserable for people who actually want to do processing in parallel - or at least give it a chance.
I am currently looking at implementing something like the Reactor pattern. Effectively I want to listen for incom... | You should be able to safely combine `asyncio` and `multiprocessing` without too much trouble, though you shouldn't be using `multiprocessing` directly. The cardinal sin of `asyncio` (and any other event-loop based asynchronous framework) is blocking the event loop. If you try to use `multiprocessing` directly, any tim... |
training data format for nltk punkt | 21,160,310 | 7 | 2014-01-16T11:19:01Z | 21,178,024 | 8 | 2014-01-17T04:38:47Z | [
"python",
"nlp",
"nltk"
] | I would like to run nltk punkt to split sentences. There is no training model so I train model separately, but I am not sure if the training data format I am using is correct.
My training data is one sentence per line. I wasn't able to find any documentation about this, only this thread (<https://groups.google.com/for... | Ah yes, Punkt tokenizer is the magical unsupervised sentence boundary detection. And the author's last name is pretty cool too, [Kiss and Strunk (2006)](http://www.mitpressjournals.org/doi/abs/10.1162/coli.2006.32.4.485). The idea is to use **NO annotation** to train a sentence boundary detector, hence the input will b... |
strange numpy fft performance | 21,161,033 | 8 | 2014-01-16T11:52:42Z | 21,161,146 | 10 | 2014-01-16T11:57:52Z | [
"python",
"numpy",
"fft"
] | During testing I have noticed something strange.
Iâm FFTâing a lot of vectors, and from time to time the numpy FFT function seemed to crash.
I briefly debugged this, and found that some vector lengths triggered the behavior.
By incident, I kept a script running, and to my surprise, it was not crashed, it simply ... | Divide-and-conquer FFT algorithms, such as [Cooley-Tukey](http://en.wikipedia.org/wiki/Cooley%E2%80%93Tukey_FFT_algorithm), work much better the more factors the input length has. Powers of 2 work especially well, whereas primes (like 165037) require alternate, slower implementations. If you can pad your input to a pow... |
Delete Column in Pandas based on Condition | 21,164,910 | 7 | 2014-01-16T14:43:41Z | 21,165,116 | 28 | 2014-01-16T14:52:51Z | [
"python",
"pandas"
] | I currently have a dataframe consisting of columns with 1's and 0's as values, I would like to iterate through the columns and delete the ones that are made up of only 0's. Here's what I have tried so far:
```
ones = []
zeros = []
for year in years:
for i in range(0,599):
if year[str(i)].values.any() == 1:... | ```
df.loc[:, (df != 0).any(axis=0)]
```
---
Here is a break-down of how it works:
```
In [74]: import pandas as pd
In [75]: df = pd.DataFrame([[1,0,0,0], [0,0,1,0]])
In [76]: df
Out[76]:
0 1 2 3
0 1 0 0 0
1 0 0 1 0
[2 rows x 4 columns]
```
`df != 0` creates a boolean DataFrame which is True where... |
NLTK collocations for specific words | 21,165,702 | 7 | 2014-01-16T15:18:35Z | 21,185,357 | 7 | 2014-01-17T11:54:31Z | [
"python",
"nltk",
"collocation"
] | I know how to get bigram and trigram collocations using NLTK and I apply them to my own corpora. The code is below.
I'm not sure however about (1) how to get the collocations for a particular word? (2) does NLTK have a collocation metric based on Log-Likelihood Ratio?
```
import nltk
from nltk.collocations import *
f... | Try this code:
```
import nltk
from nltk.collocations import *
bigram_measures = nltk.collocations.BigramAssocMeasures()
trigram_measures = nltk.collocations.TrigramAssocMeasures()
# Ngrams with 'creature' as a member
creature_filter = lambda *w: 'creature' not in w
## Bigrams
finder = BigramCollocationFinder.from_... |
What does a colon and comma stand in a python list? | 21,165,751 | 9 | 2014-01-16T15:20:42Z | 21,166,366 | 9 | 2014-01-16T15:45:40Z | [
"python",
"numpy"
] | I met this in a python script `list[:, 1]` and I am trying to figure out the role of the comma. | Generally speaking:
```
foo[somestuff]
```
calls either `__getitem__`, or `__setitem__`. (there's also `__getslice__` and `__setslice__`, but those are now deprecated, so let's not talk about that). Now, if `somestuff` has a comma in it, python will pass a `tuple` to the underlying function:
```
foo[1,2] # passes a... |
When to use imshow over pcolormesh? | 21,166,679 | 21 | 2014-01-16T15:58:38Z | 21,169,703 | 23 | 2014-01-16T18:16:37Z | [
"python",
"matplotlib"
] | I often find myself needing to create heatmap-style visualizations in Python with matplotlib. Matplotlib provides several functions which apparently do the same thing. `pcolormesh` is recommended instead of `pcolor` but what is the difference (from a practical point of view as a data plotter) between `imshow` and `pcol... | Fundamentally, `imshow` assumes that all data elements in your array are to be rendered at the same size, whereas `pcolormesh`/`pcolor` associates elements of the data array with rectangular elements whose size may vary over the rectangular grid.
If your mesh elements are uniform, then `imshow` with interpolation set ... |
Does unittest allow single case/suite testing through "setup.py test"? | 21,167,516 | 6 | 2014-01-16T16:35:19Z | 21,167,760 | 8 | 2014-01-16T16:45:58Z | [
"python",
"unit-testing",
"setuptools"
] | I'm a newbie when it comes to python unit testing, but I'm eager to learn!
I just read "python setup.py tests" can run all suites derived from unittest classes. I wonder if I also can use setup.py to run a single suite and/or a single test case, maybe adding some modifier to the previous command like "python setup.py t... | The `setup.py test` runner is rather limited; it only supports letting you specify a specific module. The documentation for the command-line switches is given when you use the `--help` switch:
```
python setup.py test --help
Common commands: (see '--help-commands' for more)
[ ... cut ... ]
Options for 'test' comman... |
Difference in type() and hasattr() between Python 3 and Python 2 | 21,174,596 | 3 | 2014-01-16T22:53:15Z | 21,174,624 | 9 | 2014-01-16T22:55:25Z | [
"python",
"python-2.7",
"python-3.x"
] | When I am trying to check type of `class` declaration in `Python 3` and `Python 2`, I get strange results, as followings show,
```
>>> #python 2.7.6
>>> class MyClass:
... pass
...
>>> type(MyClass)
<type 'classobj'>
>>> hasattr(MyClass, '__call__')
False
```
The `type` of `MyClass` in `Python 2` is `classobj` a... | What changed is that all classes in 3.x are **new-style classes** by default. Your Python 2 classes did not inherit from `object`, so Python thought it was an old-style class.
In 2.7.5:
```
>>> class MyClass(object):
... pass
...
>>> type(MyClass)
<type 'type'>
>>> hasattr(MyClass, '__call__')
True
``` |
How to create a numpy array of all True or all False? | 21,174,961 | 58 | 2014-01-16T23:22:01Z | 21,174,962 | 69 | 2014-01-16T23:22:01Z | [
"python",
"arrays",
"numpy"
] | In Python, how do I create a numpy array of arbitrary shape filled with all True or all False? | numpy already allows the creation of arrays of all ones or all zeros very easily:
e.g. `np.ones((2, 2))` or `np.zeros((2, 2))`
Since `True` and `False` are represented in Python as `1` and `0`, respectively, we have only to cast this array as boolean using the optional `dtype` parameter and we are done.
`np.ones((2,... |
How to create a numpy array of all True or all False? | 21,174,961 | 58 | 2014-01-16T23:22:01Z | 21,174,985 | 12 | 2014-01-16T23:24:00Z | [
"python",
"arrays",
"numpy"
] | In Python, how do I create a numpy array of arbitrary shape filled with all True or all False? | `ones` and `zeros`, which create arrays full of ones and zeros respectively, take an optional `dtype` parameter:
```
>>> numpy.ones((2, 2), dtype=bool)
array([[ True, True],
[ True, True]], dtype=bool)
>>> numpy.zeros((2, 2), dtype=bool)
array([[False, False],
[False, False]], dtype=bool)
``` |
How to create a numpy array of all True or all False? | 21,174,961 | 58 | 2014-01-16T23:22:01Z | 35,224,478 | 15 | 2016-02-05T12:38:09Z | [
"python",
"arrays",
"numpy"
] | In Python, how do I create a numpy array of arbitrary shape filled with all True or all False? | ```
numpy.full((2,2), True, dtype=bool)
``` |
Automatically run %matplotlib inline in IPython Notebook | 21,176,731 | 35 | 2014-01-17T02:22:41Z | 21,188,508 | 36 | 2014-01-17T14:40:47Z | [
"python",
"matplotlib",
"ipython-notebook"
] | Every time I launch IPython Notebook, the first command I run is
```
%matplotlib inline
```
Is there some way to change my config file so that when I launch IPython, it is automatically in this mode? | # The configuration way
IPython has profiles for configuration, located at `~/.ipython/profile_*`. The default profile is called `profile_default`. Within this folder there are two primary configuration files:
* `ipython_config.py`
* `ipython_kernel_config`
Add the inline option for matplotlib to `ipython_kernel_con... |
Assigning method to object at runtime in Python | 21,177,253 | 4 | 2014-01-17T03:23:36Z | 21,177,260 | 9 | 2014-01-17T03:24:10Z | [
"python",
"python-2.7"
] | I'm trying to do the Javascript equivalent in Python:
```
a.new_func = function(arg1, arg2) {
var diff = arg1 - arg2;
return diff * diff;
}
```
Right now, the way I'm doing this is by defining the method first, and then assigning it, but my question is whether or not Python allows a shorthand to do the assign... | Python supports no such syntax.
I suppose if you wanted, you could write a decorator. It might look a bit nicer:
```
def method_of(instance):
def method_adder(function):
setattr(instance, function.__name__, function)
return function
return method_adder
@method_of(a)
def new_func(arg1, arg2):
... |
Does python list store the object or the reference to the object? | 21,178,563 | 9 | 2014-01-17T05:31:39Z | 21,178,693 | 8 | 2014-01-17T05:41:48Z | [
"python",
"list"
] | Size of an **integer is 24 bytes** and **size of a char is 38 bytes,** but when i insert into a list the size of the list doesn't reflect the exact size of the object that i insert. So, now I am wandering list is holding the reference of the object and the object is storing somewhere in memory.
```
>>> sys.getsizeof(1... | All values in Python are boxed, they don't map to machine types or sizes. Namely everything in the implementation of CPython is a `PyObject` struct.
<http://docs.python.org/2/c-api/structures.html#PyObject>
> So, now I am wandering list is holding the reference of the object and the object is storing somewhere in mem... |
python scrapy get href using css selector | 21,181,628 | 6 | 2014-01-17T08:58:36Z | 21,182,445 | 18 | 2014-01-17T09:37:13Z | [
"python",
"css",
"python-2.7",
"scrapy"
] | I want to get the href value.
I tried this:
```
Link = Link1.css('span[class=title] a::text').extract()[0]
```
but i just get the text inside the `<a>`.
### how can i get the link inside the href please | What you're looking for is:
```
Link = Link1.css('span[class=title] a::attr(href)').extract()[0]
```
Since you're matching a `span` "class" attribute also, you can even write
```
Link = Link1.css('span.title a::attr(href)').extract()[0]
```
Please note that `::text` pseudo element and `::attr(attributename)` functi... |
Django REST framework - filtering against query param | 21,182,725 | 18 | 2014-01-17T09:50:35Z | 21,186,065 | 24 | 2014-01-17T12:29:00Z | [
"python",
"django",
"api",
"rest",
"django-rest-framework"
] | So I created my "API" using REST framework, now trying to do filtering for it.
That's how my `models.py` look like more or less:
```
class Airline(models.Model):
name = models.TextField()
class Workspace(models.Model):
airline = models.ForeignKey(Airline)
name = models.CharField(max_length=100)
class Pas... | So with the @limelights I managed to do what I wanted, here is the code:
```
class PassengerList(generics.ListCreateAPIView):
model = Passenger
serializer_class = PassengerSerializer
# Show all of the PASSENGERS in particular WORKSPACE
# or all of the PASSENGERS in particular AIRLINE
def get_query... |
Python basics printing 1 to 100 | 21,184,494 | 10 | 2014-01-17T11:10:43Z | 21,184,538 | 11 | 2014-01-17T11:12:44Z | [
"python"
] | ```
def gukan(count):
while count!=100:
print(count)
count=count+1;
gukan(0)
```
My question is: When I try to increment by 3 or 9 instead of 1 in `count=count+1` I get an infinite loop - why is that? | When you change `count = count + 1` to `count = count + 3` or `count = count + 9`, `count` will never be equal to 100. At the very best it'll be 99. That's not enough.
What you've got here is the classic case of infinite loop: `count` is never *equal* to 100 (sure, at some point it'll be greater than 100, but your `wh... |
Fill username and password using selenium in python | 21,186,327 | 16 | 2014-01-17T12:43:14Z | 21,186,465 | 25 | 2014-01-17T12:50:02Z | [
"python",
"selenium"
] | How can I auto fill the username and password over the link below:
```
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
chromedriver = 'C:\\chromedriver.exe'
browser = webdriver.Chrome(chromedriver)
browser.get('http://www.example.com')
```
After that I really do not know:
```
username... | ```
username = selenium.find_element_by_id("username")
password = selenium.find_element_by_id("password")
username.send_keys("YourUsername")
password.send_keys("Pa55worD")
selenium.find_element_by_name("submit").click()
```
Notes to your code:
* `find_element_by_name('Username')`: `Username` capitalized doesn't mat... |
Fill username and password using selenium in python | 21,186,327 | 16 | 2014-01-17T12:43:14Z | 21,186,468 | 12 | 2014-01-17T12:50:16Z | [
"python",
"selenium"
] | How can I auto fill the username and password over the link below:
```
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
chromedriver = 'C:\\chromedriver.exe'
browser = webdriver.Chrome(chromedriver)
browser.get('http://www.example.com')
```
After that I really do not know:
```
username... | Use [`WebElement.send_keys`](http://selenium-python.readthedocs.org/en/latest/api.html#selenium.webdriver.remote.webelement.WebElement.send_keys) method to simulate key typing.
`name` in the code (`Username`, `Password`) does not match actual `name` of the elements (`username`, `password`).
---
```
username = browse... |
How to use random.shuffle() on a generator? python | 21,187,131 | 5 | 2014-01-17T13:22:56Z | 21,187,207 | 13 | 2014-01-17T13:26:06Z | [
"python",
"list",
"random",
"generator",
"shuffle"
] | How do I use random.shuffle() on a generator without initializing a list from the generator?
Is that even possible? if not, how else should I use `random.shuffle()` on my list?
```
>>> import random
>>> random.seed(2)
>>> x = [1,2,3,4,5,6,7,8,9]
>>> def yielding(ls):
... for i in ls:
... yield i
...
>... | In order to shuffle the sequence uniformly, `random.shuffle()` needs to know how long the input is. A generator cannot provide this; you *have* to materialize it into a list:
```
lst = list(yielding(x))
random.shuffle(lst)
for i in lst:
print i
```
You could, instead, use `sorted()` with `random.random()` as the ... |
python pandas: apply a function with arguments to a series. Update | 21,188,504 | 4 | 2014-01-17T14:40:38Z | 21,189,254 | 8 | 2014-01-17T15:13:06Z | [
"python",
"pandas",
"apply"
] | I would like to apply a function with argument to a pandas series: I have found two different solution of SO:
[python pandas: apply a function with arguments to a series](http://stackoverflow.com/questions/12182744/python-pandas-apply-a-function-with-arguments-to-a-series)
and
[Passing multiple arguments to apply (P... | The `TypeError` is saying that you passed the wrong type to the `lambda` function `x + y`. It's expecting the `args` to be a sequence, but it got an `int`. You may have thought that `(100)` was a tuple (a sequence), but in python it's the comma that makes a tuple:
```
In [10]: type((100))
Out[10]: int
In [11]: type((... |
Python Mechanize - Login | 21,190,395 | 3 | 2014-01-17T16:04:06Z | 21,190,761 | 11 | 2014-01-17T16:22:51Z | [
"python",
"mechanize"
] | I am trying to login to a website and get data from it. I can't seem to get mechanize to work on the following site. I have provided the HTML below. Could someone please give me brief help of how I can log in and print the next page?
I have tried using mechanize and looping through br.forms(). I can see the form in th... | All those `div`s should be wrapped in a `form` element. Look for that and find the `name` tag. This is the form you'll want to log in with. Then you can use the snippet below to get the cookies you'll to use for further browsing.
```
import cookielib
import urllib2
import mechanize
# Browser
br = mechanize.Browse... |
Returning boolean if set is empty | 21,191,259 | 9 | 2014-01-17T16:45:13Z | 21,191,286 | 7 | 2014-01-17T16:46:32Z | [
"python",
"python-2.7"
] | I am struggling to find a more clean way of returning a boolean value if my set is empty at the end of my function
I take the intersection of two sets, and want to return `True` or `False` based on if the resulting set is empty.
```
def myfunc(a,b):
c = a.intersection(b)
#...return boolean here
```
My initia... | ```
def myfunc(a,b):
c = a.intersection(b)
return bool(c)
```
[`bool()`](http://docs.python.org/3/library/functions.html#bool) will do something similar to `not not`, but more ideomatic and clear. |
Returning boolean if set is empty | 21,191,259 | 9 | 2014-01-17T16:45:13Z | 21,191,329 | 12 | 2014-01-17T16:48:02Z | [
"python",
"python-2.7"
] | I am struggling to find a more clean way of returning a boolean value if my set is empty at the end of my function
I take the intersection of two sets, and want to return `True` or `False` based on if the resulting set is empty.
```
def myfunc(a,b):
c = a.intersection(b)
#...return boolean here
```
My initia... | not as pythonic as the other answers, but mathematics:
```
return len(c) == 0
``` |
Matplotlib: Vertical lines in scatter plot | 21,192,576 | 4 | 2014-01-17T17:51:54Z | 21,193,028 | 8 | 2014-01-17T18:18:35Z | [
"python",
"matplotlib"
] | I have posted a fair amount of code here and it's at the bottom of this post. The code opens a tkinter GUI with various buttons and fields etc. It also displays a graph at the very bottom using matplotlib. I understand that this isn't the best library to use but I have no idea how the others work with tkinter. So I wou... | To me, it looks like you want the [`vlines`](http://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes.vlines) method rather than the `plot` method. |
Managing pip in an RPM environment | 21,193,037 | 10 | 2014-01-17T18:18:51Z | 22,568,504 | 8 | 2014-03-21T20:04:22Z | [
"python",
"pip",
"rpm",
"yum",
"package-managers"
] | For our prod apps, we manage all packages in RPM. In a perfect yum-only world, this is fine.
However, each language or framework recently are deploying their own package managers. For python for example, I am almost always using pip and then having to build the packages for rpm again when going to production. Same goe... | I have used [pyp2rpm](https://pypi.python.org/pypi/pyp2rpm) to build rpm package for *rstr* module and I dislike random installations of some files via *pip* as well:
```
pyp2rpm -n rstr > ~/rpmbuild/SPECS/rstr.spec
rpmbuild -ba ~/rpmbuild/SPECS/rstr.spec
```
but I do not know if this is good enough for your producti... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.