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 |
|---|---|---|---|---|---|---|---|---|---|
how to handle 302 redirect in scrapy | 22,795,416 | 4 | 2014-04-01T19:42:22Z | 23,070,418 | 8 | 2014-04-14T21:06:25Z | [
"python",
"scrapy",
"http-status-code-302"
] | I am receiving a 302 response from a server while scrapping a website:
```
2014-04-01 21:31:51+0200 [ahrefs-h] DEBUG: Redirecting (302) to <GET http://www.domain.com/Site_Abuse/DeadEnd.htm> from <GET http://domain.com/wps/showmodel.asp?Type=15&make=damc&a=664&b=51&c=0>
```
I want to send request to GET urls instead o... | Forgot about middlewares in this scenario, this will do the trick:
```
meta = {'dont_redirect': True,'handle_httpstatus_list': [302]}
```
That said, you will need to include meta parameter when you yield your request:
```
yield Request(item['link'],meta = {
'dont_redirect': True,
... |
Why is copying a list using a slice[:] faster than using the obvious way? | 22,796,138 | 14 | 2014-04-01T20:23:24Z | 22,796,367 | 9 | 2014-04-01T20:37:27Z | [
"python",
"performance",
"list",
"cpython",
"shallow-copy"
] | Why is shallow-copying a list using a slice so much faster than using `list` builtin?
```
In [1]: x = range(10)
In [2]: timeit x_ = x[:]
10000000 loops, best of 3: 83.2 ns per loop
In [3]: timeit x_ = list(x)
10000000 loops, best of 3: 147 ns per loop
```
Usually when I see weird things like this, they're fixed in ... | The difference is in additional function call (just `SLICE+0` vs `CALL_FUNCTION 1` with **extra stack operations**):
```
>>> import dis
>>> def f(lst):
... return lst[:]
...
>>> def f1(lst):
... return list(lst)
...
>>> dis.dis(f)
2 0 LOAD_FAST 0 (lst)
3 SLICE+0 ... |
What does "global variables are bad" mean? | 22,796,917 | 4 | 2014-04-01T21:08:11Z | 22,797,101 | 8 | 2014-04-01T21:19:52Z | [
"python",
"global-variables"
] | So I can read from a global variable
```
def f() :
print x
```
And I can also assign it
```
def g()
global x
x = 3
```
When people say "global variables are bad", do they mean that both reading and assigning are bad, or just assigning is bad? (my impression is that reading is not dangerous) | The problem is not so much "global == bad" so much as "Global mutable state makes it hard to reason about program flow"
To illustrate, imagine this function:
```
def frob():
if my_global:
wibble()
else:
wobble()
```
That is, `frob()`s behavior depends on state whos nature is not obvious from ... |
PyQt: How to set Combobox to Item knowing Item's text (a title) | 22,797,794 | 8 | 2014-04-01T22:03:30Z | 22,798,753 | 12 | 2014-04-01T23:21:13Z | [
"python",
"pyqt",
"pyqt4",
"qcombobox"
] | Is it possible to set Combobox to an item knowing an Item's text value. I am trying to avoid looping through `for i in range(myCombobox.count())` just to find an Item's index so it could be used to set a combobox to that item's index. | Yes, there is [QComboBox.findText](http://qt-project.org/doc/qt-4.8/qcombobox.html#findText), which will return the index of the matched item (or -1, if there isn't one). By default, the search does exact, case-sensitive matching, but you can tweak the behaviour by passing some [match-flags](http://qt-project.org/doc/q... |
Pandas long to wide reshape | 22,798,934 | 5 | 2014-04-01T23:37:44Z | 22,799,916 | 8 | 2014-04-02T01:30:23Z | [
"python",
"pandas"
] | I have data in long format and am trying to reshape to wide, but there doesn't seem to be a straightforward way to do this using melt/stack/unstack:
```
Salesman Height product price
Knut 6 bat 5
Knut 6 ball 1
Knut 6 wand 3
Steve 5 ... | A simple pivot might be sufficient for your needs but this is what I did to reproduce your desired output:
```
df['idx'] = df.groupby('Salesman').cumcount()
```
Just adding a within group counter/index will get you most of the way there but the column labels will not be as you desired:
```
print df.pivot(index='Sale... |
BeatifulSoup4 get_text still has javascript | 22,799,990 | 12 | 2014-04-02T01:39:33Z | 22,800,287 | 29 | 2014-04-02T02:15:39Z | [
"python",
"beautifulsoup",
"nltk"
] | I'm trying to remove all the html/javascript using bs4, however, it doesn't get rid of javascript. I still see it there with the text. How can I get around this?
I tried using `nltk` which works fine however, `clean_html` and `clean_url` will be removed moving forward. Is there a way to use soups `get_text` and get th... | Based partly on [Can I remove script tags with BeautifulSoup?](http://stackoverflow.com/questions/5598524/can-i-remove-script-tags-with-beautifulsoup)
```
import urllib
from bs4 import BeautifulSoup
url = "http://www.cnn.com"
html = urllib.urlopen(url).read()
soup = BeautifulSoup(html)
# kill all script and style el... |
Remove a column from a nested list in Python | 22,800,028 | 13 | 2014-04-02T01:43:13Z | 22,800,048 | 9 | 2014-04-02T01:45:56Z | [
"python",
"list"
] | I need help figuring how to work around removing a 'column' from a nested list to modify it.
Say I have
```
L = [[1,2,3,4],
[5,6,7,8],
[9,1,2,3]]
```
and I want to remove the second column (so values 2,6,1) to get:
```
L = [[1,3,4],
[5,7,8],
[9,2,3]]
```
I'm stuck with how to modify the list wi... | You can simply delete the appropriate element from each row using [`del`](https://docs.python.org/3/tutorial/datastructures.html#the-del-statement):
```
L = [[1,2,3,4],
[5,6,7,8],
[9,1,2,3]]
for row in L:
del row[1] # 0 for column 1, 1 for column 2, etc.
print L
# outputs [[1, 3, 4], [5, 7, 8], [9, 2,... |
Converting time zone pandas dataframe | 22,800,079 | 3 | 2014-04-02T01:50:11Z | 22,800,199 | 7 | 2014-04-02T02:04:38Z | [
"python",
"pandas"
] | I have data:
```
Symbol bid ask
Timestamp
2014-01-01 21:55:34.378000 EUR/USD 1.37622 1.37693
2014-01-01 21:55:40.410000 EUR/USD 1.37624 1.37698
2014-01-01 21:55:47.210000 EUR/USD 1.37619 1.37696
2014-01-01 21:55:57.963000 EUR/... | Localize the index (using `tz_localize`) to UTC (to make the Timestamps timezone-aware) and then convert to Eastern (using `tz_convert`):
```
import pytz
eastern = pytz.timezone('US/Eastern')
df.index = index.tz_localize(pytz.utc).tz_convert(eastern)
```
---
For example:
```
import pandas as pd
import pytz
index =... |
How to get a dot notation of a python module? | 22,800,125 | 2 | 2014-04-02T01:55:40Z | 22,800,150 | 7 | 2014-04-02T01:58:25Z | [
"python"
] | I am writing a custom django model field which has serialize and unserialize operations, on unserialize, I am using the [import\_by\_path](https://docs.djangoproject.com/en/dev/ref/utils/#django.utils.module_loading.import_by_path) to get the class and initialise an instance.
On the opposite, I need to serialize an in... | Not entirely clear on what you're asking, but dot notation is equivalent to your above example in Python, for instance:
```
import datetime
datetime.datetime
```
is the same as
```
from datetime import datetime
datetime
```
I hope that makes sense, let me know if you have any more questions.
Here's a better exampl... |
Django ORM - objects.filter() vs. objects.all().filter() - which one is preferred? | 22,804,252 | 11 | 2014-04-02T07:23:36Z | 22,806,277 | 16 | 2014-04-02T08:56:47Z | [
"python",
"django",
"django-queryset",
"django-orm",
"django-managers"
] | Very often I see constructs like
```
MyModel.objects.all().filter(...)
```
which will return a QuerySet of the default Mananger. At first `all()` seems to be quite redundant, because
```
MyMode.objects.filter(...)
```
delivers the same result.
However, this seems to be save for the default Manager only, because of... | The method `all()` on a manager just delegates to `get_queryset()`, as you can see in the [Django source code](https://github.com/django/django/blob/687b3d96c40d745371c64bca7fe6d46a4e7e379c/django/db/models/manager.py#L132-L133):
```
def all(self):
return self.get_queryset()
```
So it's just a way to get the quer... |
Python best practice in terms of logging | 22,807,972 | 10 | 2014-04-02T10:04:08Z | 22,808,654 | 10 | 2014-04-02T10:32:02Z | [
"python",
"logging"
] | When using the `logging` module from python for logging purposes. Is it best-practice to define a logger for each class?
Considering some things would be redundant such as file log location, I was thinking of abstracting logging to its own class and import an instance into each of my classes requiring logging. However... | Best practice is to follow Python's rules for software (de)composition - the module is the unit of Python software, not the class. Hence, the recommended approach is to use
```
logger = logging.getLogger(__name__)
```
in each module, and to configure logging (using `basicConfig()` or `dictConfig()`) from the main scr... |
Python best practice in terms of logging | 22,807,972 | 10 | 2014-04-02T10:04:08Z | 22,809,337 | 11 | 2014-04-02T10:59:57Z | [
"python",
"logging"
] | When using the `logging` module from python for logging purposes. Is it best-practice to define a logger for each class?
Considering some things would be redundant such as file log location, I was thinking of abstracting logging to its own class and import an instance into each of my classes requiring logging. However... | **Use JSON or YAML logging configuration** - After Python 2.7, you can load logging configuration from a dict. It means you can load the logging configuration from a JSON or YAML file.
**Yaml Example** -
```
version: 1
disable_existing_loggers: False
formatters:
simple:
format: "%(asctime)s - %(name)s - %... |
Circular array indices in Python | 22,808,141 | 3 | 2014-04-02T10:10:50Z | 22,808,166 | 7 | 2014-04-02T10:11:41Z | [
"python"
] | This is a bit fiddly.
I'm looking to get an array (or matrix) that is circular, such that
Let:
```
a = [1,2,3]
```
Then I would like
```
a[0] = 1
a[1] = 2
a[2] = 3
a[3] = 1
a[4] = 2
```
Etc for all index values of a.
The reason is because I have an image as a matrix and what I'm trying to process it with the be... | You can use modulo operator, like this
```
print a[3 % len(a)]
```
If you don't want to use modulo operator like this, you need to subclass `list` and implement [`__getitem__`](https://docs.python.org/2/reference/datamodel.html#object.__getitem__), yourself.
```
class CustomList(list):
def __getitem__(self, inde... |
Do Python and Haskell have the float uncertanity issue of C/C++? | 22,811,050 | 2 | 2014-04-02T12:11:04Z | 22,811,510 | 10 | 2014-04-02T12:29:00Z | [
"python",
"c++",
"haskell",
"floating-point"
] | First of all, I was not studying math in English language, so I may use wrong words in my text.
**Float numbers can be finite(42.36) and infinite (42.363636...)**
**In C/C++ numbers are stored at base 2**. **Our minds operate floats at base 10**.
The problem is -
`many (a lot, actually) of float numbers with base 1... | The format C and C++ use for representing float and double is standardized (IEEE 754), and the problems you describe are inherent in that representation. Since Python is implemented in C, its floating point types are prone to the same rounding problems.
Haskell's Float and Double are a somewhat higher level abstractio... |
How to clear an entire Treeview with Tkinter | 22,812,134 | 8 | 2014-04-02T12:52:37Z | 27,068,344 | 13 | 2014-11-21T18:55:38Z | [
"python",
"tkinter",
"treeview"
] | My program uses a `ttk.Treeview` as a table and fills it with many numbers.
I want to clear the `ttk.Treeview` when I press a button in the window.
Is there a simple way to clear the `ttk.Treeview`?
Thanks. | Even simpler:
```
tree.delete(*tree.get_children())
``` |
Use endswith with multiple extensions | 22,812,785 | 13 | 2014-04-02T13:18:56Z | 22,812,835 | 36 | 2014-04-02T13:20:40Z | [
"python",
"list",
"file"
] | I'm trying to detect files with a list of extensions.
```
ext = [".3g2", ".3gp", ".asf", ".asx", ".avi", ".flv", \
".m2ts", ".mkv", ".mov", ".mp4", ".mpg", ".mpeg", \
".rm", ".swf", ".vob", ".wmv"]
if file.endswith(ext): # how to use the list ?
command 1
elif file.end... | Use a tuple for it.
```
>>> ext = [".3g2", ".3gp", ".asf", ".asx", ".avi", ".flv", \
".m2ts", ".mkv", ".mov", ".mp4", ".mpg", ".mpeg", \
".rm", ".swf", ".vob", ".wmv"]
>>> ".wmv".endswith(tuple(ext))
True
>>> ".rand".endswith(tuple(ext))
False
```
Instead of converting... |
Clearly documented reading of emails functionality with python win32com outlook | 22,813,814 | 3 | 2014-04-02T13:57:29Z | 22,814,286 | 7 | 2014-04-02T14:15:09Z | [
"python",
"email",
"python-3.x",
"outlook"
] | I'm trying to understand outlook interaction through win32com better. I've been unable to find clear documentation that allows me to utilise win32com to read emails effectively, from my current investigation it seems like a fairly regular sentiment by users. Thus comes the following information and request:
Could some... | The visual basic for applications reference is your friend here. Try starting with this link...
[Interop Outlook Mailitem Properties](http://msdn.microsoft.com/en-us/library/microsoft.office.interop.outlook.mailitem_properties.aspx)
For instance I can see that message will probably have additional properties than wha... |
Benefits of accessing the Abstract Syntaxt Tree (AST) . How does Julia exploit it? | 22,815,869 | 5 | 2014-04-02T15:15:37Z | 22,821,247 | 14 | 2014-04-02T19:32:16Z | [
"python",
"abstract-syntax-tree",
"julia-lang"
] | I have read that Julia has access to the [AST](http://en.wikipedia.org/wiki/Abstract_syntax_tree) of the code it runs. What exactly does this mean? Is it that the runtime can access it, that code itself can access it, or both?
Building on this:
1. Is this a key difference of Julia with respect to other dynamic langua... | What distinguishes Julia from languages like Python is that Julia allows you to intercept code before it is evaluated. Macros are just functions, written in Julia, which let you access that code and manipulate it before it runs. Furthermore, rather than treating code as a string (like `"f(x)"`), it's provided as a Juli... |
Disregarding a line while calculating frequency in python | 22,816,539 | 2 | 2014-04-02T15:42:47Z | 22,816,601 | 7 | 2014-04-02T15:45:45Z | [
"python"
] | I have the following format in a text file.
```
-FRFR
YOUAREMYFRIEND
-JKJK
YOUARENOTMYFRIEND
-SSFF
LETUSBEFRIENDS
```
I want to calculate the frequency of each letter in the line that doesn't start with a "-" and it's a huge file so I cannot just copy.
Is there anyway I can do
```
for line in str
if line starts wi... | You can use [collections.Counter()](https://docs.python.org/2/library/collections.html#collections.Counter):
```
from collections import Counter
results = Counter()
with open('input.txt', 'r') as f:
for line in f:
if line.startswith('-'):
continue
results.update(line)
print results
`... |
Testing regexes in Python using py.test | 22,818,948 | 3 | 2014-04-02T17:39:08Z | 22,823,668 | 7 | 2014-04-02T21:41:14Z | [
"python",
"unit-testing",
"python-3.x",
"py.test"
] | Regexes are still something of a dark art to me, but I think that's one of those things that just takes practice. As such, I'm more concerned with being able to produce py.test functions that show me where my regexes are failing. My current code is something like this:
```
my_regex = re.compile("<this is where the mag... | Another approach is to use [parametrize](https://pytest.org/latest/example/parametrize.html).
```
my_regex = re.compile("<this is where the magic (doesn't)? happen(s)?>")
@pytest.mark.parametrize('test_str', [
"an easy test that I'm sure will pass",
"a few things that may trip me up",
"a really pathologic... |
How to use Pandas rolling_* functions on a forward-looking basis | 22,820,292 | 7 | 2014-04-02T18:43:36Z | 22,820,689 | 10 | 2014-04-02T19:03:17Z | [
"python",
"pandas"
] | Suppose I have a time series:
```
In[138] rng = pd.date_range('1/10/2011', periods=10, freq='D')
In[139] ts = pd.Series(randn(len(rng)), index=rng)
In[140]
Out[140]:
2011-01-10 0
2011-01-11 1
2011-01-12 2
2011-01-13 3
2011-01-14 4
2011-01-15 5
2011-01-16 6
2011-01-17 7
2011-01-18 8
2011-01-1... | Why not just do it on the reversed Series (and reverse the answer):
```
In [11]: pd.rolling_sum(ts[::-1], window=3, min_periods=0)[::-1]
Out[11]:
2011-01-10 3
2011-01-11 6
2011-01-12 9
2011-01-13 12
2011-01-14 15
2011-01-15 18
2011-01-16 21
2011-01-17 24
2011-01-18 17
2011-01-19 9
Fre... |
What is a Python bytestring? | 22,824,539 | 12 | 2014-04-02T22:45:05Z | 22,824,719 | 15 | 2014-04-02T22:59:27Z | [
"python",
"string",
"bytestring"
] | What's a Python bytestring?
All I can find are topics on how to encode to bytestring or decode to `ascii` or `utf-8`. I'm trying to understand how it works under the hood. In a normal ASCII string, it's an array or list of characters, and each character represents an ASCII value from 0-255, so that's how you know what... | It is a common misconception that text is ascii or utf8 or cp1252, and therefore bytes are text.
Text is only text, in the way that images are only images. The matter of storing text or images to disk is a matter of encoding that data into a sequence of bytes. There are many ways to encode images into bytes: Jpeg, png... |
What is a Python bytestring? | 22,824,539 | 12 | 2014-04-02T22:45:05Z | 22,831,093 | 9 | 2014-04-03T07:49:48Z | [
"python",
"string",
"bytestring"
] | What's a Python bytestring?
All I can find are topics on how to encode to bytestring or decode to `ascii` or `utf-8`. I'm trying to understand how it works under the hood. In a normal ASCII string, it's an array or list of characters, and each character represents an ASCII value from 0-255, so that's how you know what... | Python *does not* know how to represent a bytestring. That's the point.
When you output a character with value 97 into pretty much any output window, you'll get the character 'a' but that's not part of the implementation; it's just a thing that happens to be locally true. If you want an encoding, you don't use bytestr... |
Converting between datetime and Pandas Timestamp objects | 22,825,349 | 4 | 2014-04-02T23:58:09Z | 22,825,954 | 7 | 2014-04-03T01:03:52Z | [
"python",
"datetime",
"pandas"
] | I have the following:
```
> date1
Timestamp('2014-01-23 00:00:00', tz=None)
> date2
datetime.date(2014, 3, 26)
```
and I read on [this answer](http://stackoverflow.com/a/13753918/283296) that I could use `pandas.to_datetime()` to convert from `Timestamps` to `datetime` objects, but it doesn't seem to work:
```
> pd... | You can use the to\_pydatetime method to be more explicit:
```
In [11]: ts = pd.Timestamp('2014-01-23 00:00:00', tz=None)
In [12]: ts.to_pydatetime()
Out[12]: datetime.datetime(2014, 1, 23, 0, 0)
```
It's also available on a DatetimeIndex:
```
In [13]: rng = pd.date_range('1/10/2011', periods=3, freq='D')
In [14]:... |
What do >> and << mean in Python? | 22,832,615 | 6 | 2014-04-03T08:59:04Z | 22,832,675 | 15 | 2014-04-03T09:01:53Z | [
"python",
"syntax",
"operator-keyword"
] | Double less than and double greater than signs.
I notice that I can do things like `2 << 5` to get 64 and `1000 >> 2` to get 250.
Also I can use >> in print
```
print >>obj, "Hello world"
```
What is happening here? | These are bitwise shift operators.
Quoting from the [docs](https://wiki.python.org/moin/BitwiseOperators):
```
x << y
```
Returns `x` with the bits shifted to the left by y places (and new bits on the right-hand-side are zeros). This is the same as multiplying `x` by `2**y`.
```
x >> y
```
Returns `x` with the bit... |
How do I plot hatched bars using pandas? | 22,833,404 | 8 | 2014-04-03T09:30:53Z | 22,836,353 | 8 | 2014-04-03T11:33:46Z | [
"python",
"matplotlib",
"plot",
"pandas"
] | I am trying to achieve differentiation by hatch pattern instead of by (just) colour. How do I do it using pandas?
It's possible in matplotlib, by passing the `hatch` optional argument as discussed [here](http://stackoverflow.com/questions/14279344/how-can-i-add-textures-to-my-bars-and-wedges). I know I can also pass t... | This is kind of hacky but it works:
```
df = pd.DataFrame(np.random.rand(10, 4), columns=['a', 'b', 'c', 'd'])
ax = plt.figure(figsize=(10, 6)).add_subplot(111)
df.plot(ax=ax, kind='bar', legend=False)
bars = ax.patches
hatches = ''.join(h*len(df) for h in 'x/O.')
for bar, hatch in zip(bars, hatches):
bar.set_ha... |
python - if not in list | 22,833,893 | 5 | 2014-04-03T09:50:33Z | 27,367,640 | 14 | 2014-12-08T21:50:39Z | [
"python",
"list",
"for-loop",
"notin"
] | I have two lists:
```
mylist = ['total','age','gender','region','sex']
checklist = ['total','civic']
```
I have to work with some code I have inherited which looks like this:
```
for item in mylist:
if item in checklist:
do something:
```
How can I work with the code above to tell me that **'civic' is n... | Your code should work, but you can also try:
```
if not item in mylist :
``` |
Understanding "Too many ancestors" from pylint | 22,834,392 | 4 | 2014-04-03T10:10:20Z | 22,906,402 | 8 | 2014-04-07T07:45:30Z | [
"python",
"pylint"
] | example.py:
```
'''
demo too many ancestors
'''
from flask_security.forms import RegisterForm
from wtforms.fields import TextField
class ExtendedRegisterForm(RegisterForm):
'''An extended register form'''
name = TextField('Name', [])
```
When I run pylint:
```
$ pylint -r n example.py
************* Module ... | The problem is that you inherit from a class which has itself (too) many ancestors: RegisterForm. In your case, you can't do a lot about this, beside stopping using it which is probably not an option. So you may want to disable this message for this class, eg:
```
class ExtendedRegisterForm(RegisterForm): # pylint: di... |
How to get tkinter canvas to dynamically resize to window width? | 22,835,289 | 12 | 2014-04-03T10:50:26Z | 22,837,522 | 12 | 2014-04-03T12:17:11Z | [
"python",
"canvas",
"python-3.x",
"tkinter",
"autoresize"
] | I need to get a canvas in Python to set its width to the width of the window, and then dynamically re-size the canvas when the user makes the window smaller/bigger. Is there any way of doing this (easily)? Thank-you in advance. | I thought I would add in some extra code to expand on @fredtantini's answer, as it doesn't deal with how to update the shape of widgets drawn on the `Canvas`.
To do this you need to use the `scale` method and tag all of the widgets. A complete example is below.
```
from Tkinter import *
# a subclass of Canvas for de... |
Python Serial write function not working | 22,835,551 | 5 | 2014-04-03T11:02:34Z | 22,835,887 | 11 | 2014-04-03T11:15:43Z | [
"python",
"python-3.x",
"typeerror"
] | I am very new to python and trying to write data using serial and python 3. Please help with the error below.
```
>>> import serial
>>> check=serial.Serial(1)
>>> print(check.name)
COM2
>>> check.write("test")
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
check.write("test")
File "... | ```
import serial
check=serial.Serial(1)
check.write(b"test")
```
Previous versions of Python did a lot of the `string` to `bytes` conversion for you (personally I liked the old methods quite a lot). Nowadays, in Python3+ you need to handle the data-type conversion yourself depending on your output/input, which makes ... |
How does open() work with and without `with`? | 22,836,081 | 4 | 2014-04-03T11:23:11Z | 22,836,333 | 7 | 2014-04-03T11:33:02Z | [
"python"
] | I'd like to write a function similar to `open`. I'd like to be able to call it with `with`, but also without `with`.
When I use `contextlib.contextmanager`, it makes my function work fine with `with`:
```
@contextmanager
def versioned(file_path, mode):
version = calculate_version(file_path, mode)
versioned_fi... | The problem is that [`contextmanager`](https://docs.python.org/3.4/library/contextlib.html#contextlib.contextmanager) only provides exactly that; a context manager to be used in the `with` statement. Calling the function does *not* return the file object, but a special context generator which provides the `__enter__` a... |
How to stub time.sleep() in Python unit testing | 22,836,874 | 4 | 2014-04-03T11:53:59Z | 22,839,439 | 9 | 2014-04-03T13:35:34Z | [
"python",
"class",
"time",
"constructor",
"python-unittest"
] | I want to make a stub to prevent time.sleep(..) to sleep to improve the unit test execution time.
What I have is:
```
import time as orgtime
class time(orgtime):
'''Stub for time.'''
_sleep_speed_factor = 1.0
@staticmethod
def _set_sleep_speed_factor(sleep_speed_factor):
'''Sets sleep speed.... | You can use [mock](https://pypi.python.org/pypi/mock/) library in your tests.
```
import time
from mock import patch
class MyTestCase(...):
@patch('time.sleep', return_value=None)
def my_test(self, patched_time_sleep):
time.sleep(666) # Should be instant
``` |
Hadoop: Python client driver for HiveServer2 fails to install | 22,838,752 | 7 | 2014-04-03T13:08:52Z | 23,913,894 | 11 | 2014-05-28T14:04:58Z | [
"python",
"hadoop",
"hive",
"sasl"
] | I am trying to install a Python client driver for HiveServer2:
<https://cwiki.apache.org/confluence/display/Hive/Setting+Up+HiveServer2#SettingUpHiveServer2-PythonClientDriver>
Installations says that:
"A Python client driver for HiveServer2 is available at <https://github.com/BradRuderman/pyhs2> **It includes all the... | pyhs2 is great, it packages several needed **python** packages together for a dbapi, among them sasl. Note if you `pip install sasl` you'll get the same error.
sasl (the python package) depends on libsasl2-dev (on a Debian/Ubuntu machine). The error you're seeing is that the compiler can't find the libraries that sasl... |
Hadoop: Python client driver for HiveServer2 fails to install | 22,838,752 | 7 | 2014-04-03T13:08:52Z | 30,478,405 | 7 | 2015-05-27T09:30:48Z | [
"python",
"hadoop",
"hive",
"sasl"
] | I am trying to install a Python client driver for HiveServer2:
<https://cwiki.apache.org/confluence/display/Hive/Setting+Up+HiveServer2#SettingUpHiveServer2-PythonClientDriver>
Installations says that:
"A Python client driver for HiveServer2 is available at <https://github.com/BradRuderman/pyhs2> **It includes all the... | Pyhs2 has the following dependencies:
1. gcc-c++
2. python-devel.x86\_64
3. cyrus-sasl-devel.x86\_64
So, just run this
```
sudo yum install gcc-c++ python-devel.x86_64 cyrus-sasl-devel.x86_64
sudo pip install pyhs2
``` |
How to update Pandas from Anaconda and is it possible to use eclipse with this last? | 22,840,449 | 10 | 2014-04-03T14:15:38Z | 22,840,737 | 17 | 2014-04-03T14:27:50Z | [
"python",
"eclipse",
"pandas"
] | I have installed Python via Anaconda using the doc at <http://www.kevinsheppard.com/images/0/09/Python_introduction.pdf> and my Pandas version is 0.13.1.
However, since I presently have some issue with this version (no possibility to really calculate the mean using resample with DataFrame) I would like to know how I c... | Simply type `conda update pandas` in your preferred shell (on Windows, use cmd). You can of course use Eclipse together with Anaconda, but you need to specify the Python-Path (the one in the Anaconda-Directory).
See this [document](http://docs.continuum.io/anaconda/ide_integration.html) for a detailed instruction. |
Generate Smooth White Border Around Circular Image | 22,845,539 | 6 | 2014-04-03T18:04:44Z | 22,940,729 | 7 | 2014-04-08T14:56:04Z | [
"python",
"imagemagick",
"graphicsmagick",
"pgmagick"
] | I'm using pgmagick to generate a circular thumbnail. I'm using a process similar to the one discussed [here](http://stackoverflow.com/questions/890051/how-do-i-generate-circular-thumbnails-with-pil), which does indeed produce a nice circular thumbnail for me. However, I need a white border around the radius of the circ... | I leave it as a simple exercise for the reader to convert this solution from
commandline to pgmagick (see more below). The code underlying pgmagick is the same as that used by the commandline.
You could draw the circle larger and then "resize" it down. This ameliorates the jaggy look of the circle by averaging the edg... |
Django form.as_p DateField not showing input type as date | 22,846,048 | 2 | 2014-04-03T18:34:10Z | 22,846,522 | 8 | 2014-04-03T18:56:56Z | [
"python",
"django",
"django-forms"
] | Working on my first django app, and I have a model defined with some `DateFields`, and then a `ModelForm` off of that model i.e.
**models.py**
```
class MyModel(models.Model):
...
my_date = models.DateField('my date')
...
class MyModelForm(ModelForm):
class Meta:
model = MyModel
field... | You can create a custom widget:
```
from django import forms
class DateInput(forms.DateInput):
input_type = 'date'
class MyModelForm(ModelForm):
class Meta:
model = MyModel
fields = '__all__'
widgets = {
'my_date': DateInput()
}
``` |
Recursion: how to avoid Python set changed set during iteration RuntimeError | 22,846,719 | 4 | 2014-04-03T19:07:09Z | 22,847,851 | 12 | 2014-04-03T20:04:14Z | [
"python",
"algorithm",
"recursion",
"constraint-programming"
] | # Background and Problem Description:
I have some code that solves the graph coloring problem (broadly defined as the problem of assigning "colors" to an undirected graph, making sure that no two vertices connected by an edge have the same color). I'm trying to implement a solution using constraint propagation to impr... | I think the problem is here:
```
for color in self.domains[var]:
if not self._valid(var, color):
continue
self.map[var].color = color
for key in node.neighbors:
if color in self.domains[key]:
self.domains[key].remove(color) # This is potentially bad.
```
if `key == var` whe... |
Swap two values in a numpy array. | 22,847,410 | 4 | 2014-04-03T19:41:18Z | 22,847,433 | 7 | 2014-04-03T19:42:49Z | [
"python",
"numpy",
"scipy",
"swap"
] | Is there something more efficient than the following code to swap two values of a numpy 1D array?
```
input_seq = arange(64)
ix1 = randint(len(input_seq))
ixs2 = randint(len(input_seq))
temp = input_seq[ix2]
input_seq[ix2] = input_seq[ix1]
input_seq[ix1] = temp
``` | You can use tuple unpacking. Tuple unpacking allows you to avoid the use of a temporary variable in your code (in actual fact I believe the Python code itself uses a temp variable behind the scenes but it's at a much lower level and so is much faster).
```
input_seq[ix1], input_seq[ix2] = input_seq[ix2], input_seq[ix1... |
turn off axis border for polar matplotlib plot | 22,847,765 | 6 | 2014-04-03T19:59:28Z | 22,848,030 | 12 | 2014-04-03T20:12:53Z | [
"python",
"matplotlib"
] | I have a polar axes in matplotlib that has text which extends outside of the range of the axes. I would like to remove the border for the axis -- or set it to the color of the background so that the text is more legible. How can I do this?
Simply increasing the size of the axes is not an acceptable solution (because t... | Just add this line: `axes.spines['polar'].set_visible(False)` and it should go away!
eewh, all the anatomy terms. |
How do I solve NameError: name 'threading' is not defined in python 3.3 | 22,848,621 | 3 | 2014-04-03T20:44:07Z | 22,848,666 | 10 | 2014-04-03T20:47:00Z | [
"python",
"python-3.x"
] | I have the following program, and nothing else, python 3.3. When I run it. I get
```
NameError: name 'threading' is not defined
```
I googled but none of the answers given explain my situation. any clues? Thanks!
```
#!/usr/bin/python
import Utilities
import os
import sys
import getopt
import time
from queue import... | You must import threading. Add the following to the beginning of your file:
```
import threading
```
The error originates from the line:
```
_db_lock=threading.Lock()
```
That's because you've used `from threading import Thread`, but you've never actually introduced `threading` in to the local namespace. So far the... |
Getting the remaining arguments in argparse | 22,850,332 | 4 | 2014-04-03T22:41:20Z | 22,850,437 | 15 | 2014-04-03T22:51:18Z | [
"python",
"argparse"
] | I want to get all the remaining unused arguments at once. How do I do it?
```
parser.add_argument('-i', action='store', dest='i', default='i.log')
parser.add_argument('-o', action='store', dest='o', default='o.log')
``` | Use `parse_known_args()`:
```
args, unknownargs = parser.parse_known_args()
``` |
What is the inverse of regularization strength in Logistic Regression? How should it affect my code? | 22,851,316 | 12 | 2014-04-04T00:18:46Z | 22,851,480 | 18 | 2014-04-04T00:36:59Z | [
"python",
"machine-learning",
"scikit-learn",
"logistic-regression"
] | I am using [`sklearn.linear_model.LogisticRegression`](http://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html) in `scikit learn` to run a Logistic Regression.
```
C : float, optional (default=1.0) Inverse of regularization strength;
must be a positive float. Like in support v... | [Regularization](http://en.wikipedia.org/wiki/Regularization_%28mathematics%29#Regularization_in_statistics_and_machine_learning) is applying a penalty to increasing the magnitude of parameter values in order to reduce [overfitting](http://en.wikipedia.org/wiki/Overfitting). When you train a model such as a logistic re... |
Flask and Ajax Post requests 400 | 22,854,749 | 10 | 2014-04-04T06:03:28Z | 22,929,593 | 13 | 2014-04-08T06:48:09Z | [
"javascript",
"jquery",
"python",
"ajax",
"flask"
] | I am writing a small flask based site and I would like to send data from the client to the server using Ajax. Until now I have only used Ajax requests to retrieve data from the server. This time I would like to submit data via POST request.
This is the receiver on the flask side, I reduced it to barely log a message t... | If you are using the [Flask-WTF CSRF protection](https://flask-wtf.readthedocs.org/en/latest/csrf.html) you'll need to either exempt your view or include the CSRF token in your AJAX POST request too.
Exempting is done with a decorator:
```
@csrf.exempt
@app.route("/json_submit", methods=["POST"])
def submit_handler()... |
Fastest way to find which two elements of a list another item is closest to in python | 22,854,910 | 5 | 2014-04-04T06:13:20Z | 22,854,934 | 9 | 2014-04-04T06:14:49Z | [
"python",
"list"
] | The input is a sorted list of elements and an external item. For example:
```
list_ = [0, 3.5, 5.8, 6.2, 88]
item = 4.4
```
What is the fastest way of finding out which two elements in `list_` `item` falls between? In this case for example, the two numbers would be 3.5 and 5.8. Any ideas? | Since the input is sorted, you're best bet algorithmically is to use the `bisect` module -- e.g. [`bisect_left`](https://docs.python.org/2/library/bisect.html#bisect.bisect_left)
```
>>> list_ = [0, 3.5, 5.8, 6.2, 88]
>>> item = 4.4
>>> bisect.bisect_left(list_, item)
2
```
The items you want reside at indices `bisec... |
nose vs pytest - what are the (subjective) differences that should make me pick either? | 22,856,638 | 47 | 2014-04-04T07:45:47Z | 22,856,817 | 41 | 2014-04-04T07:56:17Z | [
"python",
"py.test",
"nosetests"
] | I've started working on a rather big (multithreaded) Python project, with loads of (unit)tests. The most important problem there is that running the application requires a preset environment, which is implemented by a context manager. So far we made use of a patched version of the unittest runner that would run the tes... | I used to use Nose because it was the default with Pylons. I didn't like it at all. It had configuration tendrils in multiple places, virtually everything seemed to be done with an underdocumented plugin which made it all even more indirect and confusing, and because it did unittest tests by default, it regularly broke... |
Include html file in Jinja2 template | 22,860,085 | 26 | 2014-04-04T10:22:34Z | 22,860,144 | 56 | 2014-04-04T10:25:33Z | [
"python",
"html",
"flask",
"jinja2"
] | I am using Flask microframework for my server which uses Jinja templates. I have parent template.html and some childs child1.html, child2.html. Some of these childs are pretty large html files and I would like to somehow split them for better lucidity over my work.
the main.py:
```
from flask import Flask, request, r... | Use the jinja2 [`{% include %}`](http://jinja.pocoo.org/docs/templates/#include) directive.
```
{% extends 'template.html' %}
{% block content %}
{% if task == 'content1' %}
{% include 'content1.html' %}
{% endif %}
{% if task == 'content2' %}
{% include 'content2.html' %}
{% endif %}
{... |
Include html file in Jinja2 template | 22,860,085 | 26 | 2014-04-04T10:22:34Z | 22,860,147 | 7 | 2014-04-04T10:25:44Z | [
"python",
"html",
"flask",
"jinja2"
] | I am using Flask microframework for my server which uses Jinja templates. I have parent template.html and some childs child1.html, child2.html. Some of these childs are pretty large html files and I would like to somehow split them for better lucidity over my work.
the main.py:
```
from flask import Flask, request, r... | You can use the [include](http://jinja.pocoo.org/docs/templates/#include) statement. |
Is the list of Python reserved words and builtins available in a library? | 22,864,221 | 81 | 2014-04-04T13:29:13Z | 22,864,250 | 115 | 2014-04-04T13:30:21Z | [
"python"
] | Is the list of Python reserved words and builtins available in a library? I want to do something like:
```
from x.y import reserved_words_and_builtins
if x in reserved_words_and_builtins:
x += '_'
``` | To verify that a string is a keyword you can use [`keyword.iskeyword`](https://docs.python.org/2/library/keyword.html#keyword.iskeyword); to get the list of reserved keywords you can use [`keyword.kwlist`](https://docs.python.org/2/library/keyword.html#keyword.kwlist):
```
>>> import keyword
>>> keyword.iskeyword('bre... |
Doctest and Decorators in Python | 22,866,510 | 4 | 2014-04-04T15:10:23Z | 22,866,550 | 7 | 2014-04-04T15:11:46Z | [
"python",
"decorator",
"doctest"
] | I was trying to use Python decorator to catch exceptions and log the exceptions.
```
import os.path
import shutil
class log(object):
def __init__(self, f):
print "Inside __init__()"
self.f = f
def __call__(self, *args):
print "Inside __call__()"
try:
self.f(*args)
... | The decorated function (which is actually a class instance) doesn't get the `__doc__` attribute of the original function (which is what `doctest` parses). You *could* just copy `__doc__` over to the class instance, but ... Honestly, I don't really see the need for a class at all here -- you'd probably be better just us... |
download images with google custom search api | 22,866,579 | 3 | 2014-04-04T15:12:53Z | 22,871,658 | 16 | 2014-04-04T19:37:46Z | [
"python",
"json",
"google-app-engine",
"google-custom-search"
] | I have used google image api in python to download 20 first image result with the following code:
```
import os
import sys
import time
from urllib import FancyURLopener
import urllib2
import simplejson
searchTerm = "Cat"
# Replace spaces ' ' in search term for '%20' in order to comply with request
searchTerm = sea... | You can use this [Google APIs Client](http://code.google.com/p/google-api-python-client/) Library for Python.
**Demo:**
[Here](http://code.google.com/p/google-api-python-client/source/browse/samples/customsearch/main.py) is a sample (i change it to):
```
from apiclient.discovery import build
service = build("custom... |
Putting arrowheads on vectors in matplotlib's 3d plot | 22,867,620 | 9 | 2014-04-04T16:00:13Z | 22,867,877 | 16 | 2014-04-04T16:13:36Z | [
"python",
"matplotlib",
"plot"
] | I plotted the eigenvectors of some 3D-data and was wondering if there is currently (already) a way to put arrowheads on the lines? Would be awesome if someone has a tip for me. 
```
import numpy as np
from matplotlib import pyplot as plt
from mpl_toolk... | Please check this post:
[Python/matplotlib : plotting a 3d cube, a sphere and a vector?](http://stackoverflow.com/questions/11140163/python-matplotlib-plotting-a-3d-cube-a-sphere-and-a-vector)
***Edit, 02/16/2016***
I didn't expect this answer to be voted favorably for 12 times, as it is a very simple solution (and a... |
How do I safely get the user's real IP address in Flask (using mod_wsgi)? | 22,868,900 | 6 | 2014-04-04T17:08:03Z | 22,936,947 | 15 | 2014-04-08T12:25:25Z | [
"python",
"flask",
"werkzeug"
] | I have a flask app setup on mod\_wsgi/Apache and need to log the IP Address of the user. request.remote\_addr returns "127.0.0.1" and [this fix](http://esd.io/blog/flask-apps-heroku-real-ip-spoofing.html) attempts to correct that but I've found that Django removed similar code for security reasons.
Is there a better w... | You can use the [`request.access_route` attribute](http://werkzeug.pocoo.org/docs/wrappers/#werkzeug.wrappers.BaseRequest.access_route) only if you define a list of *trusted* proxies.
The `access_route` attribute uses the [`X-Forwarded-For` header](http://en.wikipedia.org/wiki/X-Forwarded-For), falling back to the `RE... |
Git Bash won't run my python files? | 22,869,192 | 12 | 2014-04-04T17:24:30Z | 22,869,540 | 30 | 2014-04-04T17:44:34Z | [
"python",
"windows",
"git",
"bash"
] | I have been trying to run my python files in Git Bash but I keep getting an error and can't figure out how to fix it. My command as follows in the git bash executable `python filename.py` then it says
```
"Bash.exe": python.exe: command not found
```
I'm a windows user and I have added the path to my environment vari... | Adapting the `PATH` should work. Just tried on my Git bash:
```
$ python --version
sh.exe": python: command not found
$ PATH=$PATH:/c/Python27/
$ python --version
Python 2.7.6
```
In particular, only provide the directory; don't specify the `.exe` on the `PATH` ; and use slashes. |
Git Bash won't run my python files? | 22,869,192 | 12 | 2014-04-04T17:24:30Z | 32,408,138 | 12 | 2015-09-04T23:59:06Z | [
"python",
"windows",
"git",
"bash"
] | I have been trying to run my python files in Git Bash but I keep getting an error and can't figure out how to fix it. My command as follows in the git bash executable `python filename.py` then it says
```
"Bash.exe": python.exe: command not found
```
I'm a windows user and I have added the path to my environment vari... | That command did not work for me, I used:
```
$ export PATH="$PATH:/c/Python27"
```
Then to make sure that git remembers the python path every time you open git type the following.
```
echo 'export PATH="$PATH:/c/Python27"' > .profile
``` |
How do I satisfy the Unused Variable rule from PEP8 if I don't need a variable returned by a function? | 22,871,708 | 6 | 2014-04-04T19:40:50Z | 22,871,723 | 10 | 2014-04-04T19:41:58Z | [
"python",
"pep8"
] | When having a function in Python that returns a couple of variables,
for example:
```
row, column = search_in_table(table_name, search_for)
```
Sometimes you only need to use one of the variables returned by the function. But when this happens, the line is marked with a PEP8 `Unused Variable` warning.
How can I hand... | Well, depending on your taste, you can do either one of two things:
1. Follow the Python convention for unused variables and replace every one with an underscore:
```
# We only need row
row, _ = search_in_table(table_name, search_for)
```
or:
```
# We only need column
_, column = search_in_t... |
AttributeError: 'EditForm' object has no attribute 'validate_on_submit' | 22,873,794 | 7 | 2014-04-04T22:02:13Z | 22,873,885 | 12 | 2014-04-04T22:10:40Z | [
"python",
"forms",
"flask"
] | I have a small edit app with the files bellow. When I submit tbe form it shows me **AttributeError: 'EditForm' object has no attribute 'validate\_on\_submit'** Can anyone please tell me what is the issue?
**forms.py**
```
from flask.ext.wtf import Form
from wtforms import Form, TextField, BooleanField, PasswordField,... | You imported the wrong `Form` object:
```
from flask.ext.wtf import Form
from wtforms import Form, TextField, BooleanField, PasswordField, TextAreaField, validators
```
The second import line imports `Form` from `wtforms`, replacing the import from `flask_wtf`. Remove `Form` from the second import line (and update yo... |
Error installing bcrypt with pip on OS X: cant find ffi.h (libffi is installed) | 22,875,270 | 31 | 2014-04-05T00:51:36Z | 23,142,216 | 20 | 2014-04-17T19:51:32Z | [
"python",
"osx",
"pip",
"bcrypt",
"libffi"
] | I'm getting this error when trying to install bcrypt with pip. I have libffi installed in a couple places (the Xcode OS X SDK, and from homebrew), but I don't know how to tell pip to look for it. Any suggestions?
```
Downloading/unpacking bcrypt==1.0.2 (from -r requirements.txt (line 41))
Running setup.py egg_info f... | I finally got it working with the following with a little help from [these](https://groups.google.com/forum/#!msg/python-cffi/gRiL5pSHKnc/8Y-6ZzrXcwAJ) [posts](http://stackoverflow.com/questions/22703393/clang-error-unknown-argument-mno-fused-madd-wunused-command-line-argumen#comment34658415_22704271):
```
brew instal... |
Error installing bcrypt with pip on OS X: cant find ffi.h (libffi is installed) | 22,875,270 | 31 | 2014-04-05T00:51:36Z | 25,854,749 | 69 | 2014-09-15T18:44:23Z | [
"python",
"osx",
"pip",
"bcrypt",
"libffi"
] | I'm getting this error when trying to install bcrypt with pip. I have libffi installed in a couple places (the Xcode OS X SDK, and from homebrew), but I don't know how to tell pip to look for it. Any suggestions?
```
Downloading/unpacking bcrypt==1.0.2 (from -r requirements.txt (line 41))
Running setup.py egg_info f... | Without using sudo and CFLAGS and CPPFLAGS (unnecessary for pip):
```
$ brew install pkg-config libffi
$ export PKG_CONFIG_PATH=/usr/local/Cellar/libffi/3.0.13/lib/pkgconfig/
$ pip install bcrypt
``` |
Error installing bcrypt with pip on OS X: cant find ffi.h (libffi is installed) | 22,875,270 | 31 | 2014-04-05T00:51:36Z | 30,453,414 | 13 | 2015-05-26T08:30:50Z | [
"python",
"osx",
"pip",
"bcrypt",
"libffi"
] | I'm getting this error when trying to install bcrypt with pip. I have libffi installed in a couple places (the Xcode OS X SDK, and from homebrew), but I don't know how to tell pip to look for it. Any suggestions?
```
Downloading/unpacking bcrypt==1.0.2 (from -r requirements.txt (line 41))
Running setup.py egg_info f... | Xcode was already installed for me (as mentioned in the question itself that it does provide the ffi.h header), but for some reason that didn't populate /usr/include (as Zachary Young mentioned). I dug around to see why the /usr/include wasn't populated and found that the following command fixed it:
```
$ xcode-select... |
Error installing scipy library through pip on python 3: "compile failed with error code 1" | 22,878,109 | 7 | 2014-04-05T07:47:58Z | 23,772,908 | 14 | 2014-05-21T02:11:03Z | [
"python",
"python-3.x",
"scipy",
"pip"
] | I'm trying to install scipy library through pip on python 3.3.5. By the end of the script, i'm getting this error:
> Command /usr/local/opt/python3/bin/python3.3 -c "import setuptools, tokenize;**file**='/private/tmp/pip\_build\_root/scipy/setup.py';exec(compile(getattr(tokenize, 'open', open)(**file**).read().replace... | I was getting the same thing when using pip, I went to the install and it pointed to the following dependencies.
`sudo apt-get install python python-dev libatlas-base-dev gcc gfortran g++` |
How to split dictionary into multiple dictionaries fast | 22,878,743 | 6 | 2014-04-05T08:57:06Z | 22,878,842 | 16 | 2014-04-05T09:07:54Z | [
"python",
"python-2.7",
"dictionary"
] | I have found a solution but it is really slow:
```
def chunks(self,data, SIZE=10000):
for i in xrange(0, len(data), SIZE):
yield dict(data.items()[i:i+SIZE])
```
Do you have any ideas without using external modules (numpy and etc.) | Since the dictionary is so big, it would be better to keep all the items involved to be just iterators and generators, like this
```
from itertools import islice
def chunks(data, SIZE=10000):
it = iter(data)
for i in xrange(0, len(data), SIZE):
yield {k:data[k] for k in islice(it, SIZE)}
```
**Sample... |
Socks proxy in tornado AsyncHttpClient | 22,882,667 | 2 | 2014-04-05T15:12:25Z | 22,882,765 | 11 | 2014-04-05T15:20:07Z | [
"python",
"tornado"
] | How can I use socks proxy in tornado AsyncHttpClient?
I found it possible to use only HTTP Proxy without changing the lib... | According to the documentation, proxy support is only available for the `libcurl` implementation of `AsyncHTTPClient`.
If you will take a deeper look at the `HTTPRequest` object you're passing to the `fetch()` method, you'll notice there's an extra `prepare_curl_callback` argument, which can call `setopt` on the `PyCu... |
Splitting a string with repeated characters into a list using regex | 22,882,922 | 13 | 2014-04-05T15:34:06Z | 22,883,012 | 8 | 2014-04-05T15:43:51Z | [
"python",
"regex",
"string"
] | I am not well experienced with Regex but I have been reading a lot about it. Assume there's a string `s = '111234'` I want a list with the string split into `L = ['111', '2', '3', '4']`. My approach was to make a group checking if it's a digit or not and then check for a repetition of the group. Something like this
``... | If you want to group all the repeated characters, then you can also use [`itertools.groupby`](http://docs.python.org/2/library/itertools.html#itertools.groupby), like this
```
from itertools import groupby
print ["".join(grp) for num, grp in groupby('111234')]
# ['111', '2', '3', '4']
```
If you want to make sure tha... |
Splitting a string with repeated characters into a list using regex | 22,882,922 | 13 | 2014-04-05T15:34:06Z | 22,883,249 | 9 | 2014-04-05T16:03:08Z | [
"python",
"regex",
"string"
] | I am not well experienced with Regex but I have been reading a lot about it. Assume there's a string `s = '111234'` I want a list with the string split into `L = ['111', '2', '3', '4']`. My approach was to make a group checking if it's a digit or not and then check for a repetition of the group. Something like this
``... | Use [`re.finditer()`](https://docs.python.org/2/library/re.html#re.finditer):
```
>>> s='111234'
>>> [m.group(0) for m in re.finditer(r"(\d)\1*", s)]
['111', '2', '3', '4']
``` |
ImportError: No module named 'pymongo' | 22,885,593 | 8 | 2014-04-05T19:20:36Z | 22,888,055 | 14 | 2014-04-05T23:09:45Z | [
"python",
"mongodb",
"pymongo"
] | I have a problem running pymongo on Win 7 (64) with Python 3.4, mongodb 4.2.10.
The error output is as follows:
```
import pymongo
ImportError: No module named 'pymongo'
```
The code is pretty simple:
```
import pymongo
from pymongo import MongoClient
client=MongoClient()
db=client.test_db
dict={'A':[1,2,3,4,5,6]}
... | All you need is to actually install `pymongo` (currently you just have mongo and python, but they do not know how to speak with each other). This [page is telling yo](http://api.mongodb.org/python/2.2/installation.html)u exactly what to do:
* go to [pymongo page](https://pypi.python.org/pypi/pymongo/)
* download and r... |
What is the difference between Lock and RLock | 22,885,775 | 16 | 2014-04-05T19:34:28Z | 22,885,810 | 33 | 2014-04-05T19:37:22Z | [
"python",
"multithreading",
"locking",
"reentrancy"
] | From the [docs](https://docs.python.org/2/library/threading.html):
> threading.RLock() --
> A factory function that returns a new reentrant lock object. A reentrant lock must be released by the thread that acquired it. Once a thread has acquired a reentrant lock, the same thread may acquire it again without blocking; ... | The main difference is that a `Lock` can only be acquired once. It cannot be acquired again, until it is released. (After it's been released, it can be re-acaquired by any thread).
An `RLock` on the other hand, can be acquired multiple times, by the same thread. It needs to be released the same number of times in orde... |
When, if ever, to use the 'is' keyword in Python? | 22,885,931 | 3 | 2014-04-05T19:47:11Z | 22,886,008 | 9 | 2014-04-05T19:53:40Z | [
"python",
"keyword"
] | Today I learnt about the `is` keyword in Python and tried the following:
```
>>> x=2+2
>>> y=4
>>> x is y
True
```
I started off trying `is` with integers because I knew the answer would be `False` -- so I found the result very surprising! To give some context, my background is C++ and C# where there is a distinction... | "`is` tests for identity, not equality. That means Python simply compares the memory address a object resides in"
There is a simple rule of thumb to tell you when to use == or is.
* `==` is for value equality. Use it when you would like to know if two objects have the same value.
* `is` is for reference equality. Use... |
Exiting out of for loop and returning when at the end of a file | 22,887,591 | 2 | 2014-04-05T22:19:28Z | 22,887,598 | 9 | 2014-04-05T22:20:38Z | [
"python",
"for-loop"
] | I want to loop through a file and return every line:
```
for i in master_file:
columns = re.split('\s{2,}', i)
last_name = columns[1]
print(last_name)
```
If I replace `print` with `return` it will only return `columns[1]` for the first line, but I want to return it for all the lines. So I can... | In this case you need to `yield` the value and not `return` it:
```
for i in master_file:
columns = re.split('\s{2,}', i)
last_name = columns[1]
yield last_name
```
Complete sample:
```
def readLastNames ():
for i in master_file:
columns = re.split('\s{2,}', i)
las... |
pandas count values in each column of a dataframe | 22,888,434 | 3 | 2014-04-06T00:05:37Z | 22,888,503 | 7 | 2014-04-06T00:16:16Z | [
"python",
"pandas",
"dataframe"
] | i'm lookng to find a way to count the number of values in a column and its proving trickier than i originally thought.
```
Percentile Percentile1 Percentile2 Percentile3
0 mediocre contender contender mediocre
69 mediocre bad mediocre mediocre
117 mediocre mediocre me... | It helps to make your data "tidy" [(PDF)](http://vita.had.co.nz/papers/tidy-data.pdf) first. That means the columns should represent variables and the rows should represent observations.
```
In [98]: df
Out[98]:
Percentile Percentile1 Percentile2 Percentile3
0 mediocre contender contender mediocre
69 ... |
Best way to split every nth string element and merge into array? | 22,888,894 | 5 | 2014-04-06T01:20:37Z | 22,888,928 | 10 | 2014-04-06T01:27:00Z | [
"python",
"list"
] | Sorry for the vague title, but it's hard to explain concisely.
Basically, imagine I have a list (in Python) that looks like this:
```
['a', 'b', 'c\nd', 'e', 'f\ng', 'h', 'i']
```
From that, I want to get this:
```
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
```
One way I was thinking of doing this was using `re... | You can just do `('\n'.join(lst)).split()` to get the 2nd list.
```
In [17]:
%timeit reduce(lambda x, y: x + y.split('\n'), lst, [])
100000 loops, best of 3: 9.64 µs per loop
In [18]:
%timeit ('\n'.join(lst)).split()
1000000 loops, best of 3: 1.09 µs per loop
```
Thanks to @Joran Beasley for suggesting `split()`... |
How to add a location filter to tweepy module | 22,889,122 | 10 | 2014-04-06T01:57:40Z | 22,889,470 | 14 | 2014-04-06T02:57:48Z | [
"python",
"twitter",
"tweepy"
] | I have found the following piece of code that works pretty well for letting me view in Python Shell the standard 1% of the twitter firehose:
```
import sys
import tweepy
consumer_key=""
consumer_secret=""
access_key = ""
access_secret = ""
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_t... | The streaming API doesn't allow to filter by location AND keyword simultaneously.
> Bounding boxes do not act as filters for other filter parameters. For example
> track=twitter&locations=-122.75,36.8,-121.75,37.8 would match any tweets containing
> the term Twitter (even non-geo tweets) OR coming from the San Francis... |
How to add a location filter to tweepy module | 22,889,122 | 10 | 2014-04-06T01:57:40Z | 26,674,808 | 7 | 2014-10-31T12:33:11Z | [
"python",
"twitter",
"tweepy"
] | I have found the following piece of code that works pretty well for letting me view in Python Shell the standard 1% of the twitter firehose:
```
import sys
import tweepy
consumer_key=""
consumer_secret=""
access_key = ""
access_secret = ""
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_t... | Juan gave the correct answer. I'm filtering for Germany only using this:
```
# Bounding boxes for geolocations
# Online-Tool to create boxes (c+p as raw CSV): http://boundingbox.klokantech.com/
GEOBOX_WORLD = [-180,-90,180,90]
GEOBOX_GERMANY = [5.0770049095, 47.2982950435, 15.0403900146, 54.9039819757]
stream.filter(... |
Flask self.errors.append() - AttributeError: 'tuple' object has no attribute 'append' | 22,889,295 | 3 | 2014-04-06T02:26:15Z | 22,889,381 | 8 | 2014-04-06T02:42:34Z | [
"python",
"django",
"flask",
"flask-wtforms"
] | My small registration app gives and error when I try to validate the submited data by user and check if the entered e-mail exists.
here is my files:
**forms:**
```
from flask.ext.wtf import Form
from wtforms import TextField, BooleanField, PasswordField, TextAreaField, validators
from wtforms.validators import Req... | The `tuple` objects [cannot append](http://stackoverflow.com/questions/1380860/add-variables-to-tuple/1380875#1380875). Instead, convert to a list using `list()`, and append, and then convert back, as such:
```
>>> obj1 = (6, 1, 2, 6, 3)
>>> obj2 = list(obj1) #Convert to list
>>> obj2.append(8)
>>> print obj2
[6, 1, 2... |
How to make a post with a from data of empty json through HTTPie? | 22,890,579 | 6 | 2014-04-06T06:08:44Z | 22,938,625 | 14 | 2014-04-08T13:31:35Z | [
"python",
"json",
"curl",
"httpie"
] | I'm wondering how to make a POST request with a from data of empty json through HTTPie? The corresponding Curl solution is here:
```
curl -X POST -H "Content-Type: application/json" -d '{}' http://ooxx.asdf/
``` | Verbatim request data can be specified [via redirected `STDIN`](https://httpie.org/docs#redirected-input):
```
$ echo '{}' | http httpbin.org/post
```
---
Note that for requests that include a body:
* `POST` is the [default HTTP method](https://httpie.org/docs#http-method)
* `application/json` is the [default `Cont... |
Installing shapefile / shapelib not found via conda or pip | 22,891,332 | 2 | 2014-04-06T07:50:20Z | 22,891,798 | 9 | 2014-04-06T08:44:31Z | [
"python",
"matplotlib",
"gis",
"ipython",
"anaconda"
] | I am trying to read shapefiles to view suburbs in a city following this [tutorial](http://www.geophysique.be/2013/02/12/matplotlib-basemap-tutorial-10-shapefiles-unleached-continued/) using windows 8, Anaconda and iPython.
I tried "conda install shapefile" and "pip install shapefile" in command prompt, both returning ... | try
```
pip install pyshp
```
in your cmd.
that is the name of you library as far as I can see, see <https://pypi.python.org/pypi/pyshp>
conda only works for these <http://docs.continuum.io/anaconda/pkgs.html> packages.
For the ones not in the list you need to use pip install. It can be confusing as the name of th... |
Testing whether a tuple has all distinct elements | 22,891,726 | 2 | 2014-04-06T08:36:06Z | 22,891,749 | 7 | 2014-04-06T08:38:20Z | [
"python",
"set",
"tuples",
"distinct",
"ipython"
] | I was seeking for a way to test whether a tuple has all distinct elements - so to say, it is a set and ended up with this quick and dirty solution.
```
def distinct ( tup):
n=0
for t in tup:
for k in tup:
#print t,k,n
if (t == k ):
n = n+1
if ( n != len(tup))... | You can very easily do it as:
```
len(set(tup))==len(tup)
```
This creates a `set` of `tup` and checks if it is the same length as the original `tup`. The only case in which they would have the same length is if all elements in `tup` were unique
### Examples
```
>>> a = (1,2,3)
>>> print len(set(a))==len(a)
True
>... |
Error installing gnureadline via pip | 22,892,482 | 15 | 2014-04-06T09:59:09Z | 25,390,189 | 34 | 2014-08-19T18:10:35Z | [
"python",
"linux",
"pip"
] | I broke my IPython setup whilst trying to upgrade to IPython 2.0. The installation fails when `gnureadline` is being installed. I originally had [this problem](http://stackoverflow.com/questions/22313407/clang-error-unknown-argument-mno-fused-madd-python-package-installation-fa) but I fixed it. Now I'm getting this err... | `sudo apt-get install libncurses5-dev`
Reference:
[Ipython no readline available and pip install readline error](http://stackoverflow.com/questions/6622490/ipython-no-readline-available-and-pip-install-readline-error) |
Why is a function/method call in python expensive? | 22,893,139 | 4 | 2014-04-06T11:04:25Z | 22,893,174 | 11 | 2014-04-06T11:08:28Z | [
"python",
"profiling",
"function-calls",
"python-internals"
] | In [this post](https://plus.google.com/115212051037621986145/posts/HajXHPGN752), Guido van Rossum says that a function call may be expensive, but I do not understand why nor how much expensive can be.
How much delay adds to your code a simple function call and why? | A function call requires that the current execution frame is suspended, and a new frame is created and pushed on the stack. This is relatively expensive, compared to many other operations.
You can measure the exact time required with the `timeit` module:
```
>>> import timeit
>>> def f(): pass
...
>>> timeit.timeit(... |
How to resume file download in Python? | 22,894,211 | 6 | 2014-04-06T12:44:09Z | 22,894,873 | 9 | 2014-04-06T13:46:13Z | [
"python",
"python-2.7",
"python-requests"
] | I am using python 2.7 requests module to download a binary file using the following code, how to make this code "auto-resume" the download from partially downloaded file.
```
r = requests.get(self.fileurl, stream=True, verify=False, allow_redirects=True)
if r.status_code == 200:
CHUNK_SIZE = 8192
bytes_read =... | If the web server supports the range request then you can add the Range header to your request:
```
Range: bytes=StartPos-StopPos
```
You will receive the part between StartPos and StopPos. If dont know the StopPos just use:
```
Range: bytes=StartPos-
```
So your code would be:
```
def resume_download(fileurl, res... |
Scipy's Optimize Curve Fit Limits | 22,895,794 | 3 | 2014-04-06T15:08:31Z | 34,104,609 | 7 | 2015-12-05T11:55:10Z | [
"python",
"scipy",
"curve-fitting"
] | Is there any way I can provide limits for the Scipy's Optimize Curve Fit?
My example:
```
def optimized_formula(x, m_1, m_2, y_1, y_2, ratio_2):
return (log(x[0]) * m_1 + m_2)*((1 - x[1]/max_age)*(1-ratio_2)) + ((log(x[1]) * y_1 + y_2)*(x[1]/max_age)*ratio_2)
popt, pcov = optimize.curve_fit(optimized... | As suggested in another answer, you could use [lmfit](http://cars9.uchicago.edu/software/python/lmfit/installation.html) for these kind of problems. Therefore, I add an example on how to use it in case someone is interested in this topic, too.
Let's say you have a dataset as follows:
```
xdata = np.array([177.,180.,1... |
Alembic migration stuck with postgresql? | 22,896,496 | 4 | 2014-04-06T16:08:02Z | 22,902,857 | 12 | 2014-04-07T02:54:11Z | [
"python",
"postgresql",
"alembic"
] | I wrote a migration script which works fine on sqlite, but if i try to apply the same to postgres it is stuck forever.
With a simple ps i can see the postres stuck on "create table waiting".
There are any best practice? | If it's really stuck on a lock, you need to see what it's waiting for. It'd be pretty odd for `CREATE TABLE` to be stuck on a lock, but it's not impossible.
## Get the stuck process id
Get the process ID of the waiting backend. You can find it in `ps`, or by `SELECT`ing from `pg_stat_activity`, looking for processes ... |
python re.search error TypeError: expected string or buffer | 22,896,914 | 4 | 2014-04-06T16:41:29Z | 22,896,928 | 9 | 2014-04-06T16:43:32Z | [
"python",
"expression"
] | Why would
```
re.search("\.docx", os.listdir(os.getcwd()))
```
yield the following error?
> TypeError: expected string or buffer | Because `os.listdir` returns a `list` but `re.search` wants a string.
The easiest way to do what you are doing is:
```
[f for f in os.listdir(os.getcwd()) if f.endswith('.docx')]
```
Or even:
```
import glob
glob.glob('*.docx')
``` |
Dijkstra's algorithm in python | 22,897,209 | 3 | 2014-04-06T17:09:54Z | 22,899,400 | 10 | 2014-04-06T20:11:56Z | [
"python",
"algorithm",
"dijkstra"
] | I am trying to implement Dijkstra's algorithm in python using arrays. This is my implementation.
```
def extract(Q, w):
m=0
minimum=w[0]
for i in range(len(w)):
if w[i]<minimum:
minimum=w[i]
m=i
return m, Q[m]
def dijkstra(... | As others have pointed out, due to not using understandable variable names, it is almost impossible to debug your code.
Following the wiki article about Dijkstra's algorithm, one can implement it along these lines (and in a million other manners):
```
nodes = ('A', 'B', 'C', 'D', 'E', 'F', 'G')
distances = {
'B':... |
PyEnchant: spellchecking block of text with a personal word list | 22,898,355 | 6 | 2014-04-06T18:48:15Z | 22,987,129 | 9 | 2014-04-10T11:47:56Z | [
"python",
"spell-checking",
"pyenchant"
] | So PyEnchant allows you to define a personal word list of correctly spelled words in addition to a language dictionary:
```
d2 = enchant.DictWithPWL("en_US","mywords.txt")
```
However, the resulting `d2` checker is of class `Dict`, which can only be used to check a single word, e.g.:
```
>>> d.check("Hello")
True
``... | The first argument of the SpellChecker initializer can be both the name of a language or an enchant dictionary:
```
from enchant import DictWithPWL
from enchant.checker import SpellChecker
my_dict = DictWithPWL("en_US", "mywords.txt")
my_checker = SpellChecker(my_dict)
my_checker.set_text("This is sme sample txt wit... |
filtering pandas dataframes on dates | 22,898,824 | 13 | 2014-04-06T19:24:42Z | 22,898,920 | 27 | 2014-04-06T19:32:50Z | [
"python",
"datetime",
"pandas",
"filtering",
"dataframe"
] | I have a pandas data frame with a 'date' column. Now i need to filter out all rows in the dataframe that have dates outside of the next two months.
Essentially, I only need to retain the row that are within the next two months.
What is the best way to achieve this. | If it's the index, you should use the `.ix` or `.loc` selector.
For example:
```
df.ix['2014-01-01':'2014-02-01']
```
See details here <http://pandas.pydata.org/pandas-docs/stable/dsintro.html#indexing-selection>
I guess it's smart to read up on pandas quite extensively before you start, as it's a very powerful lib... |
filtering pandas dataframes on dates | 22,898,824 | 13 | 2014-04-06T19:24:42Z | 35,203,658 | 12 | 2016-02-04T14:29:12Z | [
"python",
"datetime",
"pandas",
"filtering",
"dataframe"
] | I have a pandas data frame with a 'date' column. Now i need to filter out all rows in the dataframe that have dates outside of the next two months.
Essentially, I only need to retain the row that are within the next two months.
What is the best way to achieve this. | Previous answer is not correct in my experience, you can't pass it a simple string, needs to be a datetime object. So:
```
import datetime
df.ix[datetime.date(year=2014,month=1,day=1):datetime.date(year=2014,month=2,day=1)]
``` |
How do you set up Pycharm to debug a Fabric fabfile on Windows? | 22,899,787 | 4 | 2014-04-06T20:44:27Z | 23,942,623 | 9 | 2014-05-29T20:43:05Z | [
"python",
"debugging",
"pycharm",
"fabric"
] | Is is possible to set up Pycharm to step through a a Fabric fabfile.py?
It seems like this would be doable with the run/debug configuration editor but I can't seem to get the settings just right. The editor is asking for a script to run and I've tried the fab-script.py file it is just giving me the fab help options.
... | Here is how I ended up setting this up in case this is useful for someone else. As with most things like this, once you know the magic settings, it was very easy. All these instructions are through PyCharm but several of them can be done in alternate ways. However, since this is about debugging in PyCharm, thatâs wha... |
"daily limit exceeded" when using Google custom search API | 22,902,415 | 6 | 2014-04-07T01:56:59Z | 22,902,550 | 14 | 2014-04-07T02:15:24Z | [
"python",
"google-custom-search",
"google-api-python-client"
] | I wanna crawl 200 results for about 2000 queries but it gives me a "daily limit exceeded" error.
I want to confirm how many results can we crawl per day. Is there any solution that can solve this problem? Or the only way is to crawl a small part of queries each day...?
My code to crawl google is as follow:
```
def c... | According to this [post](http://dazdaztech.wordpress.com/2013/08/03/using-google-custom-search-api-from-the-command-line/):
> The first 100 queries per day are free. Any more, then you have to pay
> $5 per 1000 queries, for up to 10,000 queries per day, just enable
> billing to do so. Each query returns a maximum of 1... |
Django ListView customising queryset | 22,902,457 | 2 | 2014-04-07T02:01:38Z | 22,919,273 | 7 | 2014-04-07T17:34:23Z | [
"python",
"django",
"listview",
"views"
] | Hopefully this should be a simple one to help me with.
I have a page with a dropdown menu containing three items:
```
<form method="GET">
<select name="browse">
<option>Cats</option>
<option>Dogs</option>
<option>Worms</option>
</select>
<input type="submit" value="Submit" />
<... | To solve this problem I just modified the pagination HTML, to accommodate both the get request from the form and the page number in the url string, like so:
```
<div class="pagination">
<span class="page-links">
{% if page_obj.has_previous %}
<a href="/browse/?browse={{ input }}&page={{ page_ob... |
Overcome ValueError for empty array | 22,903,114 | 3 | 2014-04-07T03:28:25Z | 22,903,196 | 8 | 2014-04-07T03:38:28Z | [
"python",
"numpy",
"matplotlib"
] | In [this discussion](http://stackoverflow.com/questions/22853118/twiny-in-matplotlib-changes-the-y-axis-scale/22856984?noredirect=1#comment34952087_22856984) I tried to fix a issue in plotting limits for y-axis, after the `twiny()` messes up my plot.
I thought this:
```
ax.set_ylim([y.min()-0.05, y.max()+0.05])
```
w... | Just catch the exception and ignore it:
```
try:
ax.set_ylim([y.min()-0.05, y.max()+0.05])
except ValueError: #raised if `y` is empty.
pass
``` |
Django cannot import LOCAL settings | 22,904,209 | 3 | 2014-04-07T05:25:11Z | 22,906,379 | 11 | 2014-04-07T07:44:23Z | [
"python",
"django",
"settings"
] | EDIT:
Playing around with Django 1.7... and Python 3
I can't seem to import local\_settings.py into my settings.py file when using manage.py.
If I execute the settings.py file directly, my local\_settings.py file is imported fine, without any errors.
However, when I run manage.py, it complains that it could not find... | Python 3.4 does not support implicit relative imports: `from local_settings import *` in Python 3 is an *absolute import* and would only search for a `local_settings` module in your `sys.path`, but NOT in the same directory where your `settings.py` module is. You need to use explicit relative import: `from .local_setti... |
TemplateDoesNotExist at / | 22,909,010 | 4 | 2014-04-07T09:53:35Z | 22,940,181 | 10 | 2014-04-08T14:32:11Z | [
"python",
"django"
] | Hej! Many threads here had the same caption, but none of them solved my problem. I have a Django site an can access /admin (but it looks ugly). But on / there appears the following error page (`DEBUG = True` in `settings.py`):
```
TemplateDoesNotExist at /
index.html
Request Method: GET
Request URL: http://... | From what you've shown, I think you may have a problem with your project layout.
Usually, it is set as follows :
```
âââ manage.py
âââ yourproject
â  âââ __init__.py
â  âââ settings.py
â  âââ templates
â  âââ urls.py
â  âââ wsgi.py
â  âââ w... |
Pandas converting String object to lower case and checking for string | 22,909,082 | 4 | 2014-04-07T09:56:08Z | 22,909,357 | 7 | 2014-04-07T10:07:54Z | [
"python",
"pandas"
] | I have the below code
```
import pandas as pd
private = pd.read_excel("file.xlsx","Pri")
public = pd.read_excel("file.xlsx","Pub")
private["ISH"] = private.HolidayName.str.lower().contains("holiday|recess")
public["ISH"] = public.HolidayName.str.lower().contains("holiday|recess")
```
I get the following error:
```
A... | ```
private["ISH"] = private.HolidayName.str.contains("(?i)holiday|recess")
```
The `(?i)` in the regex pattern tells the `re` module to ignore case.
---
The reason why you were getting an error is because the Series object does not have the `contains` method; instead the `Series.str` attribute has the `contains` me... |
Keyboard interrupt in debug mode PyCharm | 22,913,490 | 15 | 2014-04-07T13:12:28Z | 23,782,505 | 9 | 2014-05-21T11:57:00Z | [
"python",
"python-2.7",
"pycharm"
] | Is there any way to send a keyboard interrupt event in PyCharm IDE (3.1) while in the debugging mode? | Unfortunately, there is no simple way to do this. You will need to use `psutil` and the `signal` module. For this to work you need to install `psutil` and the best way to do that is through `pip`:
```
pip install psutil
```
So, lets say we have here, exhibit A:
```
while True:
try:
time.sleep(3)
... |
How to comment each condition in a multi-line if statement? | 22,914,821 | 4 | 2014-04-07T14:07:56Z | 22,914,853 | 12 | 2014-04-07T14:08:59Z | [
"python",
"python-3.x",
"comments",
"conditional",
"multiline"
] | I want to have a multi-line `if` statement such as:
```
if CONDITION1 or\
CONDITION2 or\
CONDITION3:
```
I want to comment the end of each line of source code
```
if CONDITION1 or\ #condition1 is really cool
CONDITION2 or\ #be careful of condition2!
CONDITION3: #see document A sec. B for info
```
I a... | Don't use `\`, use parenthesis:
```
if (CONDITION1 or
CONDITION2 or
CONDITION3):
```
and you can add comments at will:
```
if (CONDITION1 or # condition1 is really cool
CONDITION2 or # be careful of conditon2!
CONDITION3): # see document A sec. B for info
```
Python allows for newlines in a pare... |
Google+ login - Server side flow - Storing credentials - Python examples | 22,915,461 | 3 | 2014-04-07T14:34:29Z | 22,930,708 | 9 | 2014-04-08T07:45:56Z | [
"python",
"google-app-engine",
"session",
"flask",
"google-plus"
] | I am building an app on Google App Engine using Flask. I am implementing Google+ login from the server-side flow described in the Python examples: <https://developers.google.com/+/web/signin/server-side-flow> and <https://github.com/googleplus/gplus-quickstart-python/blob/master/signin.py>.
Both of the examples have:
... | Flask *used* to use `pickle` instead of JSON to store values in the session, and the Google example code was written with that in mind. Flask switched to a JSON-based format to reduce the impact of the server-side secret being disclosed (a hacker can hijack your process with `pickle`, not with JSON).
Store *just* the ... |
Why does `for x in list[None:None]:` work? | 22,916,670 | 11 | 2014-04-07T15:24:25Z | 22,916,739 | 15 | 2014-04-07T15:27:44Z | [
"python",
"slice"
] | I have a script that attempts to read the begin and end point for a subset via a binary search, these values are then used to create a slice for further processing.
I noticed that when these variables did not get set (the search returned None) the code would still run and in the end I noticed that a slice spanning fro... | Because `None` is the *default* for slice positions. You can use either `None` or omit the value altogether, at which point `None` is passed in for you.
`None` is the default because you can use a negative stride, at which point what the default start and end positions are *changed*. Compare `list[0:len(list):-1]` to ... |
Django string to date format | 22,918,095 | 5 | 2014-04-07T16:33:26Z | 22,918,124 | 9 | 2014-04-07T16:34:58Z | [
"python",
"django",
"datetime"
] | I want to convert my string date to django date format. I tried a method. but did not work.
```
date = datetime.datetime.strptime(request.POST.get('date'),"Y-mm-dd").date()
```
I got this error.
```
time data '2014-04-07' does not match format 'Y-mm-dd'
```
what 's wrong in my code. | It should be `%Y-%m-%d`:
```
>>> s = "2014-04-07"
>>> datetime.datetime.strptime(s, "%Y-%m-%d").date()
datetime.date(2014, 4, 7)
```
According to the [documentation](https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior):
* `%Y` stands for a year with century as a decimal number
* `%m` - month a... |
Flask HTTP Basicauth - How does it work? | 22,919,182 | 4 | 2014-04-07T17:28:57Z | 22,919,299 | 10 | 2014-04-07T17:35:43Z | [
"python",
"login",
"flask",
"http-basic-authentication"
] | I'm trying to create a login system using Flask and HTTP Basic Auth. My question is, is it my responsibility to provide user information from databases, or does basicauth create and access those databases for me? If it doesn't, what can I use to do that? | Werkzeug can decode the Basic Authorization header for you, into the username and password. The rest is up to you to see what you want to do with that information.
The [`request.authorization` attribute](http://werkzeug.pocoo.org/docs/wrappers/#werkzeug.wrappers.AuthorizationMixin.authorization) returns a [`Authorizat... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.