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 can I sum a column of a python list?
15,352,457
7
2013-03-12T02:51:43Z
15,352,504
9
2013-03-12T02:56:24Z
[ "python", "for-loop" ]
I have a Python array, like so: ``` [[1,2,3], [1,2,3]] ``` I can add the row by doing `sum(array[i])`, how can I sum a column, using a double for loop? I.E. for the first column, I could get 2, then 4, then 6.
Using a `for` loop (in a [generator expression](http://docs.python.org/2/howto/functional.html?highlight=list%20comprehension#generator-expressions-and-list-comprehensions)): ``` data = [[1,2,3], [1,2,3]] column = 1 print sum(row[column] for row in data) ```
how to check if a number is a power of base b?
15,352,593
4
2013-03-12T03:08:22Z
15,352,628
9
2013-03-12T03:12:27Z
[ "python", "logarithm" ]
In python, how can you check if a number n is an exact power of base b? Note: it needs to be generalized to any base which is given as a parameter. Here is what I got: Assume n and base are integers > 0. ``` import math def is_power(n,base): return math.log(n,base) == base**n ```
First, assuming you have a specific logarithm operator (many languages provide logarithms to base `10` or base `e` only), `logab` can be calculated as `logxb / logxa` (where `x` is obviously a base that your language provides). Python goes one better since it can work out the logarithm for an *arbitrary* base without ...
Download and decompress gzipped file in memory?
15,352,668
19
2013-03-12T03:16:58Z
15,353,312
26
2013-03-12T04:25:24Z
[ "python", "file", "gzip", "urllib2", "stringio" ]
I would like to download a file using urllib and decompress the file in memory before saving. This is what I have right now: ``` response = urllib2.urlopen(baseURL + filename) compressedFile = StringIO.StringIO() compressedFile.write(response.read()) decompressedFile = gzip.GzipFile(fileobj=compressedFile, mode='rb')...
You need to seek to the beginning of `compressedFile` after writing to it but before passing it to `gzip.GzipFile()`. Otherwise it will be read from the end by `gzip` module and will appear as an empty file to it. See below: ``` #! /usr/bin/env python import urllib2 import StringIO import gzip baseURL = "https://www....
How to use a python context manager inside a generator
15,353,220
14
2013-03-12T04:16:58Z
15,353,416
8
2013-03-12T04:37:40Z
[ "python", "generator", "with-statement" ]
In python, should with-statements be used inside a generator? To be clear, I am not asking about using a decorator to create a context manager from a generator function. I am asking whether there is an inherent issue using a with-statement as a context manager inside a generator as it will catch `StopIteration` and `Ge...
from the [Data model entry for `object.__exit__`](http://docs.python.org/2/reference/datamodel.html#object.__exit__) > If an exception is supplied, and the method wishes to suppress the exception (i.e., prevent it from being propagated), it should return a true value. Otherwise, the exception will be processed normall...
in python what's the relation between the loop variable and the elements in list when we do for loop?
15,354,328
3
2013-03-12T05:59:10Z
15,354,396
7
2013-03-12T06:03:47Z
[ "python", "for-loop" ]
Here are several list: a, b, etc I want to make some change of them respectively, but I'm confused with the behavier of for loop. for example: if we do ``` a, b = range(5), range(5,10) for x in [a, b]: x += [0] print(a,b) ``` we get ``` ([0, 1, 2, 3, 4, 0], [5, 6, 7, 8, 9, 0]) ``` a,b are modified. but if we do ...
The relation is the same as with all variable binding in Python. The name is bound to the value. The differences you are seeing are because you are doing different things, sometimes, operating on the value and sometimes on the name. For lists, `+=` extends the list in-place --- that is, it modifies the original list. ...
in python ,if a function doesn't have a return statement,what does it return?
15,355,083
6
2013-03-12T06:52:50Z
15,355,150
13
2013-03-12T06:57:54Z
[ "python", "python-3.x" ]
Like this: ``` def writeFile(listLine,fileName): '''put a list of str-line into a file named fileName''' with open(fileName,'a',encoding = 'utf-8') as f: for line in listLine: f.writelines(line+'\r\n') return True ``` I wonder if this `return True` statement does anything useful? What'...
If a function doesn't specify a return value, it returns `None`. In an if/then conditional statement, `None` evaluates to False. So in theory you could check the return value of this function for success/failure. I say "in theory" because for the code in this question, the function does not catch or handle exceptions ...
"import decimal" raises errors
15,355,142
3
2013-03-12T06:57:35Z
15,355,284
10
2013-03-12T07:08:49Z
[ "python", "module", "decimal", "pypdf" ]
here's the code I am using ``` import os import decimal from pyPdf import PdfFileReader path = r"E:\python\Real Python\Real Python\Course materials\Chapter 8\Practice files" inputFileName = os.path.join(path,"Pride and Prejudice.pdf") inputFile = PdfFileReader(file(inputFileName,"rb")) print "Number of pages:", input...
That's a printout of all numbers up to 50 that aren't divisible by 3. It's probably in a `numbers` module on `sys.path` that's shadowing the standard library `numbers`. See where it is: ``` import numbers print numbers.__file__ ```
How to convert Dates into Specified Format using python?
15,355,413
3
2013-03-12T07:18:47Z
15,355,486
8
2013-03-12T07:23:01Z
[ "python", "list", "datetime", "timezone" ]
I have a list of dates as below: ``` list_dates = ['2013-05-01', '15th Oct 2013', '01-05-13', '2013/FEB/05',. . .] ``` What I want is: ``` list_dates = ['2013-05-01', '2013-10-15', '2013-05-01', '2013-02-05', . . .] ``` Is there ANY way, or package/module to accomplish this task?
You can try using the third-party library [dateutil](http://labix.org/python-dateutil)'s `parser`, which is usually very good at determining the proper way to parse a date (at least way better than I'll ever be :) ). The result of `parser.parse` is a `datetime` object, on which you can call `strftime` with your desired...
How to write XML declaration using xml.etree.ElementTree
15,356,641
18
2013-03-12T08:42:21Z
15,356,805
13
2013-03-12T08:50:45Z
[ "python", "xml", "elementtree" ]
I am generating a XML document in python, but the string functions do not print the XML declaration. My code: ``` from xml.etree.ElementTree import Element, tostring document = Element('outer') node = SubElement(document, 'inner') node.NewValue = 1 print tostring(document) ``` Outputs: `<outer><inner /></outer>` I...
I would use lxml (see <http://lxml.de/api.html>). Then you can: ``` from lxml import etree document = etree.Element('outer') node = etree.SubElement(document, 'inner') print(etree.tostring(document, xml_declaration=True)) ```
How to write XML declaration using xml.etree.ElementTree
15,356,641
18
2013-03-12T08:42:21Z
15,357,667
31
2013-03-12T09:36:37Z
[ "python", "xml", "elementtree" ]
I am generating a XML document in python, but the string functions do not print the XML declaration. My code: ``` from xml.etree.ElementTree import Element, tostring document = Element('outer') node = SubElement(document, 'inner') node.NewValue = 1 print tostring(document) ``` Outputs: `<outer><inner /></outer>` I...
I am surprised to find that there doesn't seem to be a way with `ElementTree.tostring()`. You can however use `ElementTree.ElementTree.write()` to write your XML document to a fake file: ``` from io import BytesIO from xml.etree import ElementTree as ET document = ET.Element('outer') node = ET.SubElement(document, 'i...
Python, Determine if a string should be converted into Int or Float
15,357,422
8
2013-03-12T09:24:45Z
15,357,477
14
2013-03-12T09:27:48Z
[ "python", "type-conversion", "decimal-point" ]
I want to convert a string to the tightest possible datatype: int or float. I have two strings: ``` value1="0.80" #this needs to be a float value2="1.00" #this needs to be an integer. ``` How I can determine that value1 should be Float and value2 should be Integer in Python?
``` def isfloat(x): try: a = float(x) except ValueError: return False else: return True def isint(x): try: a = float(x) b = int(a) except ValueError: return False else: return a == b ```
Python, Determine if a string should be converted into Int or Float
15,357,422
8
2013-03-12T09:24:45Z
15,358,486
9
2013-03-12T10:17:02Z
[ "python", "type-conversion", "decimal-point" ]
I want to convert a string to the tightest possible datatype: int or float. I have two strings: ``` value1="0.80" #this needs to be a float value2="1.00" #this needs to be an integer. ``` How I can determine that value1 should be Float and value2 should be Integer in Python?
Python `float` objects have an [`is_integer` method](http://docs.python.org/2/library/stdtypes.html#float.is_integer): ``` from ast import literal_eval def parses_to_integer(s): val = literal_eval(s) return isinstance(val, int) or (isinstance(val, float) and val.is_integer()) ```
mathematical limits in python?
15,357,458
3
2013-03-12T09:26:50Z
15,359,180
7
2013-03-12T10:50:39Z
[ "python", "turtle-graphics" ]
I am trying to do mathematical limits in python. I have defined a function for smoke ``` import turtle t = turtle.Pen() def drawsmoke(y): i = 0 while i < ((2 * y) - 1): t.seth(i * 5) t.circle((10 + i), 160) i = i + 2 ``` this draws one side of the smoke, the other side yet to be done...
use [sympy](http://sympy.org/en/index.html). SymPy is a Python library for symbolic mathematics. It aims to become a full-featured computer algebra system (CAS) while keeping the code as simple as possible in order to be comprehensible and easily extensible. SymPy is written entirely in Python and does not require any ...
what is the difference between functools.wraps and update_wrapper
15,357,776
10
2013-03-12T09:42:35Z
15,358,110
8
2013-03-12T10:00:00Z
[ "python" ]
I am not able to find what is the difference between these two python functions. `functools.wraps` and `update_wrapper` Can some give me some code example so that i can understand what is the difference
`functools.wraps` is equivalent to: ``` def wraps(wrapped, assigned=WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES): def decorator(wrapper): return update_wrapper(wrapper, wrapped=wrapped, ...) return decorator ``` It's actually implemented using `partial` instead of an inner function, but the effect is...
Python spliting a list based on a delimiter word
15,357,830
10
2013-03-12T09:45:52Z
15,358,005
10
2013-03-12T09:54:01Z
[ "python", "list", "split" ]
I have a list containing various string values. I want to split the list whenever I see `WORD`. The result will be a list of lists (which will be the sublists of original list) containing exactly one instance of the `WORD` I can do this using a loop but is there a *more pythonic* way to do achieve this ? Example = `['...
I would use a generator: ``` def group(seq, sep): g = [] for el in seq: if el == sep: yield g g = [] g.append(el) yield g ex = ['A', 'WORD', 'B' , 'C' , 'WORD' , 'D'] result = list(group(ex, 'WORD')) print(result) ``` This prints ``` [['A'], ['WORD', 'B', 'C'], ['...
How to get the first column of a pandas DataFrame as a Series?
15,360,925
35
2013-03-12T12:14:22Z
15,361,537
28
2013-03-12T12:42:57Z
[ "python", "dataframe", "pandas", "series" ]
I tried: ``` x=pandas.DataFrame(...) s = x.take([0], axis=1) ``` And `s` gets a DataFrame, not a Series.
You can get the first column as a Series by following code: ``` x[x.columns[0]] ```
How to get the first column of a pandas DataFrame as a Series?
15,360,925
35
2013-03-12T12:14:22Z
15,362,700
44
2013-03-12T13:33:39Z
[ "python", "dataframe", "pandas", "series" ]
I tried: ``` x=pandas.DataFrame(...) s = x.take([0], axis=1) ``` And `s` gets a DataFrame, not a Series.
``` >>> import pandas as pd >>> df = pd.DataFrame({'x' : [1, 2, 3, 4], 'y' : [4, 5, 6, 7]}) >>> df x y 0 1 4 1 2 5 2 3 6 3 4 7 >>> s = df.ix[:,0] >>> type(s) <class 'pandas.core.series.Series'> >>> ```
How to get the first column of a pandas DataFrame as a Series?
15,360,925
35
2013-03-12T12:14:22Z
15,364,468
15
2013-03-12T14:49:17Z
[ "python", "dataframe", "pandas", "series" ]
I tried: ``` x=pandas.DataFrame(...) s = x.take([0], axis=1) ``` And `s` gets a DataFrame, not a Series.
``` in 0.11 In [7]: df.iloc[:,0] Out[7]: 0 1 1 2 2 3 3 4 Name: x, dtype: int64 ```
What better way to concatenate string in python?
15,360,961
19
2013-03-12T12:16:23Z
15,361,006
12
2013-03-12T12:19:09Z
[ "python", "string", "string-concatenation" ]
Understand "better" as a quicker, elegant and readable. I have two strings (`a` and `b`) that could be null or not. And I want concatenate them separated by a hyphen only if both are not null: `a - b` `a` (if b is null) `b` (where a is null)
Here is one option: ``` ("%s - %s" if (a and b) else "%s%s") % (a,b) ``` EDIT: As pointed by mgilson, this code would fail on with `None`'s a better way (but less readable one) would be: ``` "%s - %s" % (a,b) if (a and b) else (a or b) ```
What better way to concatenate string in python?
15,360,961
19
2013-03-12T12:16:23Z
15,361,064
45
2013-03-12T12:21:32Z
[ "python", "string", "string-concatenation" ]
Understand "better" as a quicker, elegant and readable. I have two strings (`a` and `b`) that could be null or not. And I want concatenate them separated by a hyphen only if both are not null: `a - b` `a` (if b is null) `b` (where a is null)
``` # Concatenates a and b with ' - ' or Coalesces them if one is None '-'.join([x for x in (a,b) if x]) ``` **Edit** Here are the results of this algorithm (Note that None will work the same as ''): ``` >>> '-'.join([x for x in ('foo','bar') if x]) 'foo-bar' >>> '-'.join([x for x in ('foo','') if x]) 'foo' >>> '-'...
What better way to concatenate string in python?
15,360,961
19
2013-03-12T12:16:23Z
15,361,067
35
2013-03-12T12:21:47Z
[ "python", "string", "string-concatenation" ]
Understand "better" as a quicker, elegant and readable. I have two strings (`a` and `b`) that could be null or not. And I want concatenate them separated by a hyphen only if both are not null: `a - b` `a` (if b is null) `b` (where a is null)
How about something simple like: ``` # if I always need a string even when `a` and `b` are both null, # I would set `output` to a default beforehand. # Or actually, as Supr points out, simply do `a or b or 'default'` if a and b: output = '%s - %s' % (a, b) else: output = a or b ``` Edit: Lots of interesting s...
What better way to concatenate string in python?
15,360,961
19
2013-03-12T12:16:23Z
15,361,590
32
2013-03-12T12:45:17Z
[ "python", "string", "string-concatenation" ]
Understand "better" as a quicker, elegant and readable. I have two strings (`a` and `b`) that could be null or not. And I want concatenate them separated by a hyphen only if both are not null: `a - b` `a` (if b is null) `b` (where a is null)
Wow, seems like a hot question :p My proposal: ``` ' - '.join(filter(bool, (a, b))) ``` Which gives: ``` >>> ' - '.join(filter(bool, ('', ''))) '' >>> ' - '.join(filter(bool, ('1', ''))) '1' >>> ' - '.join(filter(bool, ('1', '2'))) '1 - 2' >>> ' - '.join(filter(bool, ('', '2'))) '2' ``` Obviously, `None` behaves li...
How to fit result of matplotlib.pyplot.contourf into circle?
15,361,143
7
2013-03-12T12:25:43Z
15,432,819
7
2013-03-15T12:42:54Z
[ "python", "matplotlib", "contour" ]
Here is my code to plot some data: ``` from scipy.interpolate import griddata from numpy import linspace import matplotlib.pyplot as plt meanR = [9.95184937, 9.87947708, 9.87628496, 9.78414422, 9.79365258, 9.96168969, 9.87537519, 9.74536093, 10.16686878, 10.04425475, 10.10444126, 10.291...
Because you don't seem to need any axes you can also use a normal projection, remove the axes and draw a circle. I had some fun and added some bonus ears, a nose and a color bar. I annotated the code, I hope it is clear. ![EEG](http://i.stack.imgur.com/YhhQs.png) ``` from __future__ import print_function from __futur...
Joining specific tuples within a list
15,361,690
3
2013-03-12T12:49:34Z
15,361,806
8
2013-03-12T12:54:18Z
[ "python", "python-2.7", "list-comprehension" ]
I've been asking quite a bit recently, and don't feel too much comfortably needing this much help but this algorithm looks real tough. I have a list of tuples like this: ``` [('12 Mar 2011',), ('152', 'Farko', 'Kier'), ('153', 'Park', 'Pub'), ('09 Mar 2011',), ('158', 'Diving', 'Jogging')] ``` The tuple with date wi...
You could write this using `itertools.groupby`, but an imperative generator function is likely to be more readable: ``` def join_dates(l): date = None for t in l: if len(t) == 1: date = t else: yield t + date ``` For completeness, here's the `itertools` solution: ``` f...
Scope of python variable in for loop
15,363,138
16
2013-03-12T13:53:29Z
15,363,210
18
2013-03-12T13:56:44Z
[ "python", "for-loop", "scope" ]
Heres the python code im having problems with: ``` for i in range (0,10): if i==5: i+=3 print i ``` I expected the output to be: ``` 0 1 2 3 4 8 9 ``` however the interpreter spits out: ``` 0 1 2 3 4 8 6 7 8 9 ``` I know that a `for` loop creates a new scope for a variable in C, but have no idea a...
The for loop iterates over all the numbers in `range(10)`, that is, `[0,1,2,3,4,5,6,7,8,9]`. That you change the *current* value of `i` has no effect on the next value in the range. You can get the desired behavior with a while loop. ``` i = 0 while i < 10: # do stuff and manipulate `i` as much as you like ...
Scope of python variable in for loop
15,363,138
16
2013-03-12T13:53:29Z
15,363,227
9
2013-03-12T13:57:19Z
[ "python", "for-loop", "scope" ]
Heres the python code im having problems with: ``` for i in range (0,10): if i==5: i+=3 print i ``` I expected the output to be: ``` 0 1 2 3 4 8 9 ``` however the interpreter spits out: ``` 0 1 2 3 4 8 6 7 8 9 ``` I know that a `for` loop creates a new scope for a variable in C, but have no idea a...
A for loop in Python is actually a for-each loop. At the start of each loop, `i` is set to the next element in the iterator (`range(0, 10)` in your case). The value of `i` gets re-set at the beginning of each loop, so changing it in the loop body does not change its value for the next iteration. That is, the `for` loo...
Scope of python variable in for loop
15,363,138
16
2013-03-12T13:53:29Z
15,363,559
8
2013-03-12T14:11:13Z
[ "python", "for-loop", "scope" ]
Heres the python code im having problems with: ``` for i in range (0,10): if i==5: i+=3 print i ``` I expected the output to be: ``` 0 1 2 3 4 8 9 ``` however the interpreter spits out: ``` 0 1 2 3 4 8 6 7 8 9 ``` I know that a `for` loop creates a new scope for a variable in C, but have no idea a...
# Analogy with C code You are imagining that your `for-loop` in python is like this C code: ``` for (int i = 0; i < 10; i++) if (i == 5) i += 3; ``` It's more like this C code: ``` int r[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; for (int j = 0; j < sizeof(r)/sizeof(r[0]); j++) { int i = r[j]; if (i ==...
Disable the underlying window when a popup is created in Python TKinter
15,363,923
5
2013-03-12T14:25:27Z
15,363,998
13
2013-03-12T14:28:27Z
[ "python", "tkinter" ]
I have a master Frame (call it `a`), and a popup Toplevel (call it `b`). How do I make sure the user cannot click on anything in `a` while `b` is "alive"?
If you don't want to hide the root but just make sure the user can only interact with the popup, you can use [`grab_set()`](http://www.pythonware.com/library/tkinter/introduction/toplevel-window-methods.htm) and [`grab_release()`](http://effbot.org/tkinterbook/widget.htm#Tkinter.Widget.grab_release-method). ``` b.grab...
'ascii' codec can't encode character at position * ord not in range(128)
15,364,266
10
2013-03-12T14:39:51Z
15,364,316
9
2013-03-12T14:42:30Z
[ "python", "unicode", "decode", "encode" ]
There are a few threads on stackoverflow, but i couldn't find a valid solution to the problem as a whole. I have collected huge sums of textual data from the urllib read function and stored the same in pickle files. Now I want to write this data to a file. While writing i'm getting errors similar to - ``` 'ascii' co...
Your data is *unicode* data. To write that to a file, use `.encode()`: ``` text = text.encode('ascii', 'ignore') ``` but that would remove anything that isn't ASCII. Perhaps you wanted to encode to a more suitable encoding, like UTF-8, instead? You may want to read up on Python and Unicode: * [The Absolute Minimum ...
'ascii' codec can't encode character at position * ord not in range(128)
15,364,266
10
2013-03-12T14:39:51Z
15,364,584
10
2013-03-12T14:54:12Z
[ "python", "unicode", "decode", "encode" ]
There are a few threads on stackoverflow, but i couldn't find a valid solution to the problem as a whole. I have collected huge sums of textual data from the urllib read function and stored the same in pickle files. Now I want to write this data to a file. While writing i'm getting errors similar to - ``` 'ascii' co...
You can do it through `smart_str` of `Django` module. Just try this: ``` from django.utils.encoding import smart_str, smart_unicode text = u'\u2019' print smart_str(text) ``` You can install Django by starting a command shell with administrator privileges and run this command: ``` pip install Django ```
Is there an easy way generate a probable list of words from an unspaced sentence in python?
15,364,975
10
2013-03-12T15:12:16Z
15,367,466
9
2013-03-12T17:00:50Z
[ "python", "nlp" ]
I have some text: ``` s="Imageclassificationmethodscan beroughlydividedinto two broad families of approaches:" ``` I'd like to parse this into its individual words. I quickly looked into the enchant and nltk, but didn't see anything that looked immediately useful. If I had time to invest in this, I'd look into writi...
# Greedy approach using trie Try this using [Biopython](https://github.com/biopython/biopython) (`pip install biopython`): ``` from Bio import trie import string def get_trie(dictfile='/usr/share/dict/american-english'): tr = trie.trie() with open(dictfile) as f: for line in f: word = li...
Run Class methods in threads (python)
15,365,406
17
2013-03-12T15:32:19Z
15,365,553
31
2013-03-12T15:39:04Z
[ "python", "multithreading", "class", "methods" ]
I'm currently learning Python and Classes and I have a basic question, but I didn't find any answer to it. Let's say I have this dummy class ``` class DomainOperations: def __init__(self, domain): self.domain = domain self.domain_ip = '' self.website_thumbnail = '' def resolve_domain(s...
If you call them from the class, it is as simple as: ``` import threading class DomainOperations: def __init__(self): self.domain_ip = '' self.website_thumbnail = '' def resolve_domain(self): self.domain_ip = 'foo' def generate_website_thumbnail(self): self.website_thumb...
Aligning Floats to decimal points in Python 2.7 using the format() mini-language
15,365,685
4
2013-03-12T15:44:45Z
15,365,738
7
2013-03-12T15:47:08Z
[ "python", "python-2.7", "format" ]
I want to print lines so that the decimal points of the numbers align. Currently, it prints like shown below: ``` ydisp 0.176 xdisp -0.509 ``` and what I want is something like this ``` ydisp 0.176 xdisp -0.509 ``` The code that I am using is ``` print "{:{width}} {}".format(items,float_di...
Use `' '` as the sign modifier to include a space for the sign: ``` >>> '{:20} {: }'.format('ydisp', 0.176) 'ydisp 0.176' >>> '{:20} {: }'.format('xdisp', -0.509) 'xdisp -0.509' ``` Note the space after the `:` colon. This causes positive numbers to be padded with a space on the left, n...
Flatten a nested list of variable sized sublists into a SciPy array
15,366,053
8
2013-03-12T15:58:51Z
15,366,348
10
2013-03-12T16:11:28Z
[ "python", "numpy", "scipy" ]
How can I use numpy/scipy to flatten a nested list with sublists of different sizes? Speed is very important and the lists are large. ``` lst = [[1, 2, 3, 4],[2, 3],[1, 2, 3, 4, 5],[4, 1, 2]] ``` Is anything faster than this? ``` vec = sp.array(list(*chain(lst))) ```
How about [np.fromiter](http://docs.scipy.org/doc/numpy/reference/generated/numpy.fromiter.html): ``` In [49]: %timeit np.hstack(lst*1000) 10 loops, best of 3: 25.2 ms per loop In [50]: %timeit np.array(list(chain.from_iterable(lst*1000))) 1000 loops, best of 3: 1.81 ms per loop In [52]: %timeit np.fromiter(chain.fr...
Find minimum values in a python 3.3 list
15,366,579
3
2013-03-12T16:20:25Z
15,366,679
8
2013-03-12T16:24:07Z
[ "python", "python-3.x" ]
For example: ``` a=[-5,-3,-1,1,3,5] ``` I want to find a negative and a positive minimum. example: negative ``` print(min(a)) = -5 ``` positive ``` print(min(a)) = 1 ```
``` >>> a = [-5,-3,-1,1,3,5] >>> min(el for el in a if el < 0) -5 >>> min(el for el in a if el > 0) 1 ``` Special handling may be required if `a` doesn't contain any negative or any positive values.
Find minimum values in a python 3.3 list
15,366,579
3
2013-03-12T16:20:25Z
15,367,305
8
2013-03-12T16:52:07Z
[ "python", "python-3.x" ]
For example: ``` a=[-5,-3,-1,1,3,5] ``` I want to find a negative and a positive minimum. example: negative ``` print(min(a)) = -5 ``` positive ``` print(min(a)) = 1 ```
For getting minimum negative: ``` min(a) ``` For getting minimum positive: `min(filter(lambda x:x>0,a))`
Default working directory for Python IDLE?
15,367,688
7
2013-03-12T17:11:35Z
20,509,072
7
2013-12-11T01:51:59Z
[ "python", "python-idle" ]
Is there a configuration file where I can set its default working directory? It currently defaults to my home directory, but I want to set it to another directory when it starts. I know I can do "import os" followed by "os.chdir("")" but that's kind of troublesome. It'd be great if there is a conf file that I can edit ...
I actually just discovered the easiest answer, if you use the shortcut link labeled "IDLE (Python GUI)". This is in Windows Vista, so I don't know if it'll work in other OS's. 1) Right-click "Properties". 2) Select "Shortcut" tab. 3) In "Start In", write file path (e.g. "C:\Users..."). This is also my answer here: ...
UnboundLocalError: local variable referenced before assignment when reading from file
15,367,760
17
2013-03-12T17:14:40Z
15,367,806
19
2013-03-12T17:17:00Z
[ "python" ]
I have also tried searching for the answer but I don't understand the answers to other people's similar problems... ``` tfile= open("/home/path/to/file",'r') def temp_sky(lreq, breq): for line in tfile: data = line.split() if ( abs(float(data[0]) - lreq) <= 0.1 and abs(float(data[...
Your `if` statement is always false and T gets initialized only if a condition is met, so the code doesn't reach the point where `T` gets a value (and by that, gets defined/bound). You should introduce the variable in a place that always gets executed. Try: ``` def temp_sky(lreq, breq): T = <some_default_value> #...
Import error on installed package using setup.py
15,368,054
7
2013-03-12T17:29:29Z
15,368,107
12
2013-03-12T17:32:02Z
[ "python", "import", "python-2.7", "setuptools" ]
I have a problem with using `setup.py` to setup a python package. First, I have the following directory setup: ``` maindir |- setup.py |-mymodule |- __init__.py |- mainmodule.py |-subdir |- __init__.py |- submodule.py ``` i.e. the project directory contains t...
You have to list all packages in `setup`, including subpackages: ``` setup( name = "mytestmodule", version = "0.0.1", description = ("A simple module."), packages=['mymodule', 'mymodule.subdir'], ) ``` Or you can use `setuptools`'s magic function `find_packages`: ``` from setuptools import setup, fin...
Finding the dimension with highest variance using scikit-learn PCA
15,369,006
13
2013-03-12T18:17:59Z
15,376,380
14
2013-03-13T03:10:41Z
[ "python", "scikit-learn", "pca", "variance" ]
I need to use pca to identify the dimensions with the highest variance of a certain set of data. I'm using scikit-learn's pca to do it, but I can't identify from the output of the pca method what are the components of my data with the highest variance. Keep in mind that I don't want to eliminate those dimensions, only ...
The pca.explained\_variance\_ratio\_ returned are the variances from principal components. You can use them to find how many dimensions (components) your data could be better transformed by pca. You can use a threshold for that (e.g, you count how many variances are greater than 0.5, among others). After that, you can ...
input a symbolic function in a python code
15,369,106
3
2013-03-12T18:22:27Z
15,369,443
8
2013-03-12T18:39:56Z
[ "python", "sympy" ]
I was just wondering if there is a method to input a symbolic function in a python code? like in my code I have: ``` from sympy import * import numpy as np import math myfunction = input("enter your function \n") l = Symbol('l') print myfunction(l**2).diff(l) ``` If I put cos, sin or exp, as an input then I have an...
As a syntax, `sin + cos` simply isn't going to work very well. The simplest way to get the general case to work is to give sympy an *expression* to evaluate. We can let `sympify` do the hard work of turning a string into a `sympy` object: ``` >>> s = raw_input("enter a formula: ") enter a formula: sin(x) + x**3 >>> s ...
Python: adding xml schema attributes with lxml
15,369,329
5
2013-03-12T18:33:44Z
15,370,357
7
2013-03-12T19:26:22Z
[ "python", "xsd", "lxml" ]
I've written a script that prints out all the .xml files in the current directory in xml format, but I can't figure out how to add the xmlns attributes to the top-level tag. The output I want to get is: ``` <?xml version='1.0' encoding='utf-8'?> <databaseChangeLog xmlns="http://www.host.org/xml/ns/dbchangelog" ...
``` import lxml.etree as ET import lxml.builder import glob dbchangelog = 'http://www.host.org/xml/ns/dbchangelog' xsi = 'http://www.host.org/2001/XMLSchema-instance' E = lxml.builder.ElementMaker( nsmap={ None: dbchangelog, 'xsi': xsi}) ROOT = E.databaseChangeLog DOC = E.include # grab all the x...
Writing multi-line strings into cells using openpyxl
15,370,432
7
2013-03-12T19:29:22Z
15,384,171
14
2013-03-13T11:35:41Z
[ "python", "openpyxl" ]
I'm trying to write data into a cell, which has multiple line breaks (I believe \n), the resulting .xlsx has line breaks removed. Is there a way to keep these line breaks?
In `openpyxl` you can set the `wrap_text` alignment property to wrap multi-line strings: ``` from openpyxl import Workbook workbook = Workbook() worksheet = workbook.worksheets[0] worksheet.title = "Sheet1" worksheet.cell('A1').style.alignment.wrap_text = True worksheet.cell('A1').value = "Line 1\nLine 2\nLine 3" w...
PhantomJS 1.8 with Selenium on python. How to block images?
15,371,495
10
2013-03-12T20:30:10Z
20,016,790
14
2013-11-16T09:22:00Z
[ "python", "selenium", "phantomjs" ]
Is there a way to configure PhantomJS webdriver on Selenium to do not load images? I know if I use phantomjs directly, I can start it with `--load-images=no` and it won't load the images, but how can I configure that via Selenium and Python? UPDATE Tried the following: ``` args = { 'desired_capabilities': { ...
Why are you not trying `webdriver.PhantomJS(service_args=['--load-images=no'])` ?
backward slash followed by a number in python strings
15,371,660
4
2013-03-12T20:39:25Z
15,371,720
10
2013-03-12T20:42:08Z
[ "python", "windows", "string", "directory", "slash" ]
I've encountered a problem in Python when dealing with backward slashes followed by numbers inside a string. I use windows OS environment. This becomes especially annoying when you have numbers in the beginning of a name in a directory. Ex: `"P:\70_parseFile\80_FileDir\60_FA_050"` This was a discovery for me that yo...
You have two choices: * Backslash those backslashes: ``` "P:\\70_parseFile\\80_FileDir\\60_FA_050" ``` * Use a [raw string](http://docs.python.org/2/reference/lexical_analysis.html#string-literals), in which the backslash loses its "special meaning" ``` r"P:\70_parseFile\80_FileDir\60_FA_050" ```
Python Sorted: Sorting a dictionary by value (DESC) then by key (ASC)
15,371,691
7
2013-03-12T20:40:44Z
15,371,752
14
2013-03-12T20:44:00Z
[ "python", "sorting", "key", "sorted" ]
Just after discovering the amazing sorted(), I became stuck again. The problem is I have a dictionary of the form string(key) : integer(value) and I need to sort it in descending order of its integer values, BUT if two elements where to have same value, then by ascending order of key. An example to make it clearer: ...
Something like ``` In [1]: d = {'banana': 3, 'orange': 5, 'apple': 5} In [2]: sorted(d.items(), key=lambda x: (-x[1], x[0])) Out[2]: [('apple', 5), ('orange', 5), ('banana', 3)] ```
Python resolve a host name with IPv6 address
15,373,288
3
2013-03-12T22:14:39Z
15,373,338
7
2013-03-12T22:17:33Z
[ "python", "dns", "ipv6" ]
I wonder if there is a way to use python to resolve a hostname that resolves only in ipv6 and/or for a hostname that resolves both in ipv4 and ipv6? `socket.gethostbyname()` and `socket.gethostbyname_ex()`does not work for ipv6 resolution. A dummy way to do that is to run actual linux host command and parse the resul...
[socket.getaddrinfo](http://docs.python.org/2/library/socket.html#socket.getaddrinfo) supports IPv6. You just need to set `family` to `AF_INET6`. ``` socket.getaddrinfo("example.com", None, socket.AF_INET6) ```
Python Tkinter menu bars don't display
15,373,493
3
2013-03-12T22:27:35Z
15,387,078
8
2013-03-13T13:43:36Z
[ "python", "tkinter", "menubar" ]
I'm trying to make a GUI using Tkinter and have come to implementing a menu bar. I've looked at a few tutorials and written some code for it, but a menu bar never seems to appear - just a blank frame with a white background. This doesn't just happen for my code though; on copying and pasting the code of one of the afor...
Based on some comments you made to one of the answers, you are apparently running this on a Macintosh. The code works fine, but the menu appears in the mac menubar rather than on the window like it does on Windows and Linux. So, there's nothing wrong with your code as far as the menubar is concerned.
Why does Popen.communicate() return b'hi\n' instead of 'hi'?
15,374,211
18
2013-03-12T23:24:04Z
15,374,326
24
2013-03-12T23:33:50Z
[ "python", "subprocess", "popen" ]
Can someone explain why the result I want, "hi", is preceded with a letter 'b' and followed with a newline? I am using **Python 3.3** ``` >>> import subprocess >>> print(subprocess.Popen("echo hi", shell=True, stdout=subprocess.PIPE).communicate()[0]) b'hi\n' ``` This extra 'b' does not ap...
The `b` indicates that what you have is [`bytes`](http://docs.python.org/3/library/stdtypes.html#bytes), which is a binary sequence of bytes rather than a string of Unicode characters. Subprocesses output bytes, not characters, so that's what `communicate()` is returning. The `bytes` type is not directly `print()`able...
Writing a faster Python physics simulator
15,374,291
10
2013-03-12T23:30:58Z
15,375,757
7
2013-03-13T02:02:01Z
[ "python", "numpy", "physics", "scientific-computing", "verlet-integration" ]
I have been playing around with writing my own physics engine in Python as an exercise in physics and programming. I started out by following the tutorial [located here](http://www.petercollingridge.co.uk/pygame-physics-simulation). That went well, but then I found the article "Advanced character physics" by thomas jak...
There is a [Guido van Rossum's article](http://www.python.org/doc/essays/list2str.html) linked in the section [Performance Tips](http://wiki.python.org/moin/PythonSpeed/PerformanceTips) of the Python Wiki. In its conclusion, you can read the following sentence: > If you feel the need for speed, go for built-in functio...
Apply function to pandas groupby
15,374,597
7
2013-03-13T00:01:13Z
15,375,176
11
2013-03-13T01:00:05Z
[ "python", "pandas" ]
I have a pandas dataframe with a column called `my_labels` which contains strings: `'A', 'B', 'C', 'D', 'E'`. I would like to count the number of occurances of each of these strings then divide the number of counts by the sum of all the counts. I'm trying to do this in Pandas like this: ``` func = lambda x: x.size() /...
`apply` takes a function to apply to *each* value, not the series, and accepts kwargs. So, the values do not have the `.size()` method. Perhaps this would work: ``` from pandas import * d = {"my_label": Series(['A','B','A','C','D','D','E'])} df = DataFrame(d) def as_perc(value, total): return value/float(total...
Should all Python classes extend object?
15,374,857
61
2013-03-13T00:27:13Z
15,374,884
30
2013-03-13T00:29:55Z
[ "python", "inheritance" ]
I have found that both of the following work: ``` class Foo(): def a(self): print "hello" class Foo(object): def a(self): print "hello" ``` Should all Python classes extend object? Are there any potential problems with not extending object?
In Python 3, classes extend `object` implicitly, whether you say so yourself or not. In Python 2, there's [old-style and new-style](http://docs.python.org/release/2.5.2/ref/node33.html) classes. To signal a class is new-style, you have to inherit explicitly from `object`. If not, the old-style implementation is used. ...
Should all Python classes extend object?
15,374,857
61
2013-03-13T00:27:13Z
15,374,901
63
2013-03-13T00:31:29Z
[ "python", "inheritance" ]
I have found that both of the following work: ``` class Foo(): def a(self): print "hello" class Foo(object): def a(self): print "hello" ``` Should all Python classes extend object? Are there any potential problems with not extending object?
In Python 2, not inheriting from `object` will create an old-style class, which, amongst other effects, causes `type` to give different results: ``` >>> class Foo: pass ... >>> type(Foo()) <type 'instance'> ``` vs. ``` >>> class Bar(object): pass ... >>> type(Bar()) <class '__main__.Bar'> ``` Also the rules for m...
python: get number of items from list(sequence) with certain condition
15,375,093
24
2013-03-13T00:51:18Z
15,375,122
33
2013-03-13T00:54:15Z
[ "python", "list", "count", "functional-programming", "sequence" ]
Assuming that I have a list with huge number of items. ``` l = [ 1, 4, 6, 30, 2, ... ] ``` I want to get the number of items from that list, where an item should satisfy certain condition. My first thought was: ``` count = len([i for i in l if my_condition(l)]) ``` But if the my\_condition() filtered list has also ...
You can use a [generator expression](http://docs.python.org/2/tutorial/classes.html#generator-expressions): ``` >>> l = [1, 3, 7, 2, 6, 8, 10] >>> sum(1 for i in l if i % 4 == 3) 2 ``` or even ``` >>> sum(i % 4 == 3 for i in l) 2 ``` which uses the fact that `int(True) == 1`. Alternatively, you could use `itertool...
Pycrypto install fatal error: gmp.h file not found
15,375,171
11
2013-03-13T00:59:50Z
35,753,259
12
2016-03-02T16:46:08Z
[ "python", "osx-mountain-lion", "gmp", "pycrypto" ]
It seems like there are a number of people who have had a similar problem, however, after much searching I haven't been able to find a solution that works with my particular architecture. I'm trying to install Pycrypto (as a subsidiary of Fabric) to no avail. I'm running Mac 10.8.2, python 2.7.3 via Homebrew, and XCod...
If you use Homebrew, this should do the trick: ``` brew install gmp env "CFLAGS=-I/usr/local/include -L/usr/local/lib" pip install pycrypto ```
How to best perform Multiprocessing within requests with the python Tornado server?
15,375,336
30
2013-03-13T01:18:44Z
23,412,001
12
2014-05-01T16:30:01Z
[ "python", "multiprocessing", "tornado", "python-multithreading" ]
I am using the I/O non-blocking python server Tornado. I have a class of `GET` requests which may take a significant amount of time to complete (think in the range of 5-10 seconds). The problem is that Tornado blocks on these requests so that subsequent fast requests are held up until the slow request completes. I loo...
`multiprocessing.Pool` can be integrated into the `tornado` I/O loop, but it's a bit messy. A much cleaner integration can be done using `concurrent.futures` (see [my other answer](http://stackoverflow.com/a/25208213/2073595) for details), but if you're stuck on Python 2.x and can't install the `concurrent.futures` bac...
How to best perform Multiprocessing within requests with the python Tornado server?
15,375,336
30
2013-03-13T01:18:44Z
25,208,213
20
2014-08-08T16:40:38Z
[ "python", "multiprocessing", "tornado", "python-multithreading" ]
I am using the I/O non-blocking python server Tornado. I have a class of `GET` requests which may take a significant amount of time to complete (think in the range of 5-10 seconds). The problem is that Tornado blocks on these requests so that subsequent fast requests are held up until the slow request completes. I loo...
If you're willing to use [`concurrent.futures.ProcessPoolExecutor`](https://docs.python.org/3/library/concurrent.futures.html#processpoolexecutor) instead of `multiprocessing`, this is actually very simple. Tornado's ioloop already supports `concurrent.futures.Future`, so they'll play nicely together out of the box. `c...
Unique zero-based id for values in pandas
15,376,475
2
2013-03-13T03:21:43Z
15,376,505
7
2013-03-13T03:24:22Z
[ "python", "pandas" ]
I have some data in a DataFrame with an identifier column. ``` data = DataFrame({'id' : [50,50,30,10,50,50,30]}) ``` For each unique id, I want to come up with a new unique identifier. I'd like the ids to be sequential integers starting at 0. Here's what I have so far: ``` unique = data[['id']].drop_duplicates() ...
That is what `pandas.factorize` does: ``` data = pd.DataFrame({'id' : [50,50,30,10,50,50,30]}) print pd.factorize(data.id)[0] ``` The output: ``` [0 0 1 2 0 0 1] ``` `numpy.unique` can also do this: ``` import numpy as np print np.unique([50,50,30,10,50,50,30], return_inverse=True)[1] ``` the output: ``` array([...
When is "i += x" different from "i = i + x" in Python?
15,376,509
160
2013-03-13T03:24:44Z
15,376,520
251
2013-03-13T03:25:31Z
[ "python", "operators" ]
I was told that `+=` can have different effects than the standard notation of `i = i +`. Is there a case in which `i += 1` would be different from `i = i + 1`?
This depends entirely on the object `i`. `+=` calls the [`__iadd__` method](http://docs.python.org/2/reference/datamodel.html#object.__iadd__) (if it exists -- falling back on `__add__` if it doesn't exist) whereas `+` calls the [`__add__` method](http://docs.python.org/2/reference/datamodel.html#object.__add__)1. Fr...
When is "i += x" different from "i = i + x" in Python?
15,376,509
160
2013-03-13T03:24:44Z
15,376,553
60
2013-03-13T03:29:52Z
[ "python", "operators" ]
I was told that `+=` can have different effects than the standard notation of `i = i +`. Is there a case in which `i += 1` would be different from `i = i + 1`?
Under the covers, `i += 1` does something like this: ``` try: i = i.__iadd__(1) except AttributeError: i = i.__add__(1) ``` While `i = i + 1` does something like this: ``` i = i.__add__(1) ``` This is a slight oversimplification, but you get the idea: Python gives types a way to handle `+=` specially, by cr...
Scapy send function without output
15,377,150
7
2013-03-13T04:33:52Z
15,377,260
11
2013-03-13T04:44:44Z
[ "python", "scapy" ]
Does anyone know how to send a packet using scapy and not receive any output? This is the command: ``` send(packet,iface="eth0") ``` This is the output ``` Sent 1 packets. ``` I'm trying to get it not to print the packet count line at all.
Try the `verbose` parameter. [Scapy documentation](http://www.secdev.org/projects/scapy/files/scapydoc.pdf) says that `verbose` should "make the function totally silent when 0". Both `False` and `0` appear to work. For example: ``` >>> send(IP(dst="1.2.3.4")/ICMP()) . Sent 1 packets. >>> send(IP(dst="1.2.3.4")/ICMP(),...
List of Lists to List of Dictionaries
15,380,073
4
2013-03-13T08:19:50Z
15,380,116
22
2013-03-13T08:22:17Z
[ "python", "list", "dictionary" ]
How can I convert a list of lists into a list of dictionaries? More specifiicaly: How do I go from this: ``` [['a1', 'b1', 'c1', 'd1', 'e1', 'f1', 'g1', 'h1', 'i1'], ['a2', 'b2', 'c2', 'd2', 'e2', 'f2', 'g2', 'h2', 'i2'], ['a3', 'b3', 'c3', 'd3', 'e3', 'f3', 'g3', 'h3', 'i3'], ['a4', 'b4', 'c4', 'd4', 'e4', 'f4', 'g4...
``` In [20]: l = [['a1', 'b1', 'c1', 'd1', 'e1', 'f1', 'g1', 'h1', 'i1'], ['a2', 'b2', 'c2', 'd2', 'e2', 'f2', 'g2', 'h2', 'i2'], ['a3', 'b3', 'c3', 'd3', 'e3', 'f3', 'g3', 'h3', 'i3'], ['a4', 'b4', 'c4', 'd4', 'e4', 'f4', 'g4', 'h4', 'i4'], ['a5', 'b5', 'c5', 'd5', 'e5', 'f5', 'g5', 'h5', 'i5'], ['a6', 'b6', 'c6', 'd6...
Plotting power spectrum in python
15,382,076
16
2013-03-13T10:01:54Z
15,385,586
11
2013-03-13T12:37:53Z
[ "python", "numpy", "scipy", "signal-processing" ]
I have an array with 301 values, which were gathered from a movie clip with 301 frames. This means 1 value from 1 frame. The movie clip is running at 30 fps, so is in fact 10 sec long Now I would like to get the power spectrum of this "signal" ( with the right Axis). I tried: ``` X = fft(S_[:,2]); pl.plot(abs(X)) ...
if rate is the sampling rate(Hz), then `np.linspace(0, rate/2, n)` is the frequency array of every point in fft. You can use `rfft` to calculate the fft in your data is real values: ``` import numpy as np import pylab as pl rate = 30.0 t = np.arange(0, 10, 1/rate) x = np.sin(2*np.pi*4*t) + np.sin(2*np.pi*7*t) + np.ran...
Plotting power spectrum in python
15,382,076
16
2013-03-13T10:01:54Z
15,388,340
29
2013-03-13T14:39:01Z
[ "python", "numpy", "scipy", "signal-processing" ]
I have an array with 301 values, which were gathered from a movie clip with 301 frames. This means 1 value from 1 frame. The movie clip is running at 30 fps, so is in fact 10 sec long Now I would like to get the power spectrum of this "signal" ( with the right Axis). I tried: ``` X = fft(S_[:,2]); pl.plot(abs(X)) ...
Numpy has a convenience function, `np.fft.fftfreq` to compute the frequencies associated with FFT components: ``` from __future__ import division import numpy as np import matplotlib.pyplot as plt data = np.random.rand(301) - 0.5 ps = np.abs(np.fft.fft(data))**2 time_step = 1 / 30 freqs = np.fft.fftfreq(data.size, t...
How to make ordered dictionary from list of lists?
15,382,807
2
2013-03-13T10:32:49Z
15,382,911
7
2013-03-13T10:37:18Z
[ "python", "list", "dictionary", "python-2.7", "ordereddictionary" ]
The problem is: Having a list of names, and a list of lists, how to create a list, in which each item is an ordered dictionary with names as keys, and items from list of lists as values? It might be more clear from code below: ``` from collections import OrderedDict list_of_lists = [ ['20010103', '0.9...
Use [`zip()`](http://docs.python.org/2/library/functions.html#zip) to combine the names and the values. With a list comprehension: ``` from collections import OrderedDict ordered_dictionary = [OrderedDict(zip(names, subl)) for subl in list_of_lists] ``` which gives: ``` >>> from pprint import pprint >>> pprint([Ord...
Plotting single points on a graph
15,382,887
6
2013-03-13T10:35:48Z
15,383,233
11
2013-03-13T10:52:17Z
[ "python", "matplotlib" ]
I have a violin plot which looks like this: ![enter image description here](http://i.stack.imgur.com/yAIzo.gif) I want to plot a few individual dots (or lines, crosses, points whichever is easiest) on each x-value, on top of the violins, like this: ![enter image description here](http://i.stack.imgur.com/nYqKt.png) ...
Just plot the extra data right after the other plot: ``` from matplotlib.pyplot import figure, show from scipy.stats import gaussian_kde from numpy.random import normal from numpy import arange def violin_plot(ax, data, pos, bp=False): ''' create violin plots on an axis ''' dist = max(pos)-min(pos) ...
Python: list comprehensions vs. lambda
15,384,058
2
2013-03-13T11:30:13Z
15,384,248
9
2013-03-13T11:38:48Z
[ "python", "list", "lambda", "list-comprehension" ]
I want to retrieve the integer value from the sublist containing "b" as the first element (b will only appear once in the list) Those two ways came to my mind: ``` foo = [["a", 5], ["b", 10], ["c", 100]] y = filter(lambda x: x[0] == "b", foo) print y[0][1] z = [foo[i][1] for i in range(len(foo)) if foo[i][0] == "b"...
When the list is so small there is no significant difference between the two. If the input list can grow large then there is a worse problem: you're iterating over the whole list, while you could stop at the first element. You could accomplish this with a for loop, but if you want to use a comprehension-like statement,...
How to compare list values with dictionary keys and make a new dictionary of it using python
15,385,308
2
2013-03-13T12:26:28Z
15,385,351
7
2013-03-13T12:28:06Z
[ "python", "list", "dictionary", "generator" ]
I have a list like this: ``` lis = ['Date', 'Product', 'Price'] ``` I want to compare it with: ``` dict = {'Date' : '2013-05-01', 'Salary' : '$5000', 'Product' : 'Toys', 'Price' : '$10', 'Salesman' : 'Smith'} ``` I want to compare each item of list with keys of dictionary and make a new dictionary. What I have tr...
Treat `lis` as a set instead, so you can use [dictionary views](http://docs.python.org/2/library/stdtypes.html#dictionary-view-objects) and an intersection: ``` # python 2.7: n = {k: d[k] for k in d.viewkeys() & set(lis)} # python 3: n = {k: d[k] for k in d.keys() & set(lis)} ``` Or you could use a simple dict compr...
Does zeromq support IPC as a transport channel on windows?
15,386,121
11
2013-03-13T13:01:56Z
15,386,238
13
2013-03-13T13:07:36Z
[ "python", "windows", "zeromq" ]
I get the following error message, when I try the router example wiht python on Windows (Windows 8): ``` Traceback (most recent call last): File "router.py", line 43, in <module> client.bind("ipc://routing.ipc") File "socket.pyx", line 432, in zmq.core.socket.Socket.bind (zmq\core\socket.c:3870) File "checkr...
The question [How to use Zeromq's inproc and ipc transports?](http://stackoverflow.com/questions/8492377/how-to-use-zeromqs-inproc-and-ipc-transports) mentions that IPC relies on POSIX named pipes, which Windows doesn't support. You should be able to use TCP on a Loopback Interface instead without trouble.
Does zeromq support IPC as a transport channel on windows?
15,386,121
11
2013-03-13T13:01:56Z
15,406,728
10
2013-03-14T10:30:42Z
[ "python", "windows", "zeromq" ]
I get the following error message, when I try the router example wiht python on Windows (Windows 8): ``` Traceback (most recent call last): File "router.py", line 43, in <module> client.bind("ipc://routing.ipc") File "socket.pyx", line 432, in zmq.core.socket.Socket.bind (zmq\core\socket.c:3870) File "checkr...
It is not supported on Windows, but TCP over localhost gives much the same performance as IPC, on Linux and OS/X and I'd just use that on Windows too.
Does SessionAuthentication work in Tastypie for HTTP POST?
15,388,694
6
2013-03-13T14:53:48Z
15,392,853
10
2013-03-13T17:53:39Z
[ "python", "django", "rest", "tastypie" ]
I am able to do GET to work with SessionAuthentication and Tastypie without setting any headers except for `content-type` to `application/json`. HTTP POST however just fails even though the Cookie in the Header has the session id. It fails with a 401 AuthorizationHeader but it has nothing to do with Authorization. Chan...
Yes I have gotten it to work. All you need to do is to pass the csfr token: > ## SessionAuthentication > > This authentication scheme uses the built-in > Django sessions to check if a user is logged. This is typically useful > when used by Javascript on the same site as the API is hosted on. > > It requires that the u...
What are all possible pos tags of NLTK?
15,388,831
55
2013-03-13T14:59:09Z
15,389,153
69
2013-03-13T15:12:23Z
[ "python", "nltk" ]
How do I find a list with all possible pos tags used by the Natural Language Toolkit (nltk)?
[The book](http://nltk.org/book/ch05.html) has a note how to find help on tag sets, e.g.: ``` nltk.help.upenn_tagset() ``` Others are probably similar. (Note: Maybe you first have to download `tagsets` from the download helper's *Models* section for this)
What are all possible pos tags of NLTK?
15,388,831
55
2013-03-13T14:59:09Z
15,389,667
39
2013-03-13T15:33:50Z
[ "python", "nltk" ]
How do I find a list with all possible pos tags used by the Natural Language Toolkit (nltk)?
The tag set depends on the corpus that was used to train the tagger. The default tagger of `nltk.pos_tag()` uses the [Penn Treebank Tag Set](http://www.ling.upenn.edu/courses/Fall_2003/ling001/penn_treebank_pos.html). In NLTK 2, you could check which tagger is the default tagger as follows: ``` import nltk nltk.tag._...
What are all possible pos tags of NLTK?
15,388,831
55
2013-03-13T14:59:09Z
32,336,935
8
2015-09-01T16:46:21Z
[ "python", "nltk" ]
How do I find a list with all possible pos tags used by the Natural Language Toolkit (nltk)?
The below can be useful to access a dict keyed by abbreviations: ``` >>> from nltk.data import load >>> tagdict = load('help/tagsets/upenn_tagset.pickle') >>> tagdict['NN'][0] 'noun, common, singular or mass' >>> tagdict.keys() ['PRP$', 'VBG', 'VBD', '``', 'VBN', ',', "''", 'VBP', 'WDT', ... ```
What are all possible pos tags of NLTK?
15,388,831
55
2013-03-13T14:59:09Z
38,264,311
8
2016-07-08T10:22:13Z
[ "python", "nltk" ]
How do I find a list with all possible pos tags used by the Natural Language Toolkit (nltk)?
To save some folks some time, here is a list I extracted from a small corpus. I do not know if it is complete, but it should have most (if not all) of the help definitions from upenn\_tagset... **CC**: conjunction, coordinating ``` & 'n and both but either et for less minus neither nor or plus so therefore times v. v...
Standard deviation of a list
15,389,768
28
2013-03-13T15:38:20Z
15,389,874
49
2013-03-13T15:42:16Z
[ "python", "list", "standard-deviation" ]
I want to find mean and standard deviation of 1st, 2nd,... digit of number of list. For example, I have ``` A_rank=[0.8,0.4,1.2,3.7,2.6,5.8] B_rank=[0.1,2.8,3.7,2.6,5,3.4] C_Rank=[1.2,3.4,0.5,0.1,2.5,6.1] # etc (up to Z_rank )... ``` Now I want to take mean, std of all `*_Rank[0]`, mean and std of `*_Rank[1]`, etc. (...
I would put `A_Rank` et al into a 2D [NumPy](http://www.numpy.org/) array, and then use [`numpy.mean()`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.mean.html) and [`numpy.std()`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.std.html) to compute the means and the standard deviations: ``` In ...
Standard deviation of a list
15,389,768
28
2013-03-13T15:38:20Z
21,505,523
33
2014-02-02T00:27:10Z
[ "python", "list", "standard-deviation" ]
I want to find mean and standard deviation of 1st, 2nd,... digit of number of list. For example, I have ``` A_rank=[0.8,0.4,1.2,3.7,2.6,5.8] B_rank=[0.1,2.8,3.7,2.6,5,3.4] C_Rank=[1.2,3.4,0.5,0.1,2.5,6.1] # etc (up to Z_rank )... ``` Now I want to take mean, std of all `*_Rank[0]`, mean and std of `*_Rank[1]`, etc. (...
Since Python 3.4 / [PEP450](http://www.python.org/dev/peps/pep-0450/) there is a [`statistics module`](http://docs.python.org/3.4/library/statistics.html) in the standard library, which has a [method `stddev`](http://docs.python.org/3.4/library/statistics.html#statistics.stdev) for calculating the standard deviation of...
Standard deviation of a list
15,389,768
28
2013-03-13T15:38:20Z
27,758,326
21
2015-01-03T18:48:25Z
[ "python", "list", "standard-deviation" ]
I want to find mean and standard deviation of 1st, 2nd,... digit of number of list. For example, I have ``` A_rank=[0.8,0.4,1.2,3.7,2.6,5.8] B_rank=[0.1,2.8,3.7,2.6,5,3.4] C_Rank=[1.2,3.4,0.5,0.1,2.5,6.1] # etc (up to Z_rank )... ``` Now I want to take mean, std of all `*_Rank[0]`, mean and std of `*_Rank[1]`, etc. (...
Here's some pure-Python code you can use to calculate the mean and standard deviation. All code below is based on the [`statistics`](https://hg.python.org/cpython/file/3.4/Lib/statistics.py) module in Python 3.4. ``` def mean(data): """Return the sample arithmetic mean of data.""" n = len(data) if n < 1: ...
Standard deviation of a list
15,389,768
28
2013-03-13T15:38:20Z
31,366,254
11
2015-07-12T09:22:24Z
[ "python", "list", "standard-deviation" ]
I want to find mean and standard deviation of 1st, 2nd,... digit of number of list. For example, I have ``` A_rank=[0.8,0.4,1.2,3.7,2.6,5.8] B_rank=[0.1,2.8,3.7,2.6,5,3.4] C_Rank=[1.2,3.4,0.5,0.1,2.5,6.1] # etc (up to Z_rank )... ``` Now I want to take mean, std of all `*_Rank[0]`, mean and std of `*_Rank[1]`, etc. (...
In Python 2.7.1, you may calculate standard deviation using `numpy.std()` for: * **Population std**: Just use `numpy.std()` with no additional arguments besides to your data list. * **Sample std**: You need to pass **ddof** (i.e. Delta Degrees of Freedom) set to 1, as in the following example: > numpy.std(< your-list...
Integer square root in python
15,390,807
21
2013-03-13T16:19:55Z
15,391,420
45
2013-03-13T16:45:53Z
[ "python", "math", "integer", "sqrt" ]
Is there an integer square root somewhere in python, or in standard libraries? I want it to be exact (i.e. return an integer), and bark if there's no solution. At the moment I rolled my own naive one: ``` def isqrt(n): i = int(math.sqrt(n) + 0.5) if i**2 == n: return i raise ValueError('input was ...
Newton's method works perfectly well on integers: ``` def isqrt(n): x = n y = (x + 1) // 2 while y < x: x = y y = (x + n // x) // 2 return x ``` This returns the largest integer *x* for which *x* \* *x* does not exceed *n*. If you want to check if the result is exactly the square root,...
Integer square root in python
15,390,807
21
2013-03-13T16:19:55Z
17,495,624
11
2013-07-05T19:23:47Z
[ "python", "math", "integer", "sqrt" ]
Is there an integer square root somewhere in python, or in standard libraries? I want it to be exact (i.e. return an integer), and bark if there's no solution. At the moment I rolled my own naive one: ``` def isqrt(n): i = int(math.sqrt(n) + 0.5) if i**2 == n: return i raise ValueError('input was ...
Sorry for the very late response; I just stumbled onto this page. In case anyone visits this page in the future, the python module gmpy2 is designed to work with very large inputs, and includes among other things an integer square root function. Example: ``` >>> import gmpy2 >>> gmpy2.isqrt((10**100+1)**2) mpz(100000...
Weird behaviour of np.sqrt for large integers
15,390,858
7
2013-03-13T16:22:09Z
15,390,958
8
2013-03-13T16:26:11Z
[ "python", "numpy", "sqrt" ]
``` >>> np.__version__ '1.7.0' >>> np.sqrt(10000000000000000000) 3162277660.1683793 >>> np.sqrt(100000000000000000000.) 10000000000.0 >>> np.sqrt(100000000000000000000) Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: sqrt ``` Huh... `AttributeError: sqrt` what's going on here t...
The final number is a `long` (Python's name for an arbitrary precision integer), which NumPy apparently can't deal with: ``` >>> type(100000000000000000000) <type 'long'> >>> type(np.int(100000000000000000000)) <type 'long'> >>> np.int64(100000000000000000000) Traceback (most recent call last): File "<stdin>", line ...
How to parse options without any argument using optparse module
15,391,089
7
2013-03-13T16:32:01Z
15,391,197
9
2013-03-13T16:36:15Z
[ "python" ]
How can I pass options without any argument and without passing any default argument? For example: ``` ./log.py --ipv4 ```
``` parser.add_option("--ipv4", action="store_true", dest="ipv4") ``` See <http://docs.python.org/2/library/optparse.html#handling-boolean-flag-options>
In Python, is it possible to escape newline characters when printing a string?
15,392,730
28
2013-03-13T17:48:59Z
15,392,758
48
2013-03-13T17:49:52Z
[ "python", "escaping", "newline" ]
I want the newline `\n` to show up explicitly when printing a string retrieved from elsewhere. So if the string is 'abc\ndef' I don't want this to happen: ``` >>> print(line) abc def ``` but instead this: ``` >>> print(line) abc\ndef ``` Is there a way to modify print, or modify the argument, or maybe another funct...
Just encode it with the `'string_escape'` codec. ``` >>> print "foo\nbar".encode('string_escape') foo\nbar ```
In Python, is it possible to escape newline characters when printing a string?
15,392,730
28
2013-03-13T17:48:59Z
15,392,971
26
2013-03-13T17:59:34Z
[ "python", "escaping", "newline" ]
I want the newline `\n` to show up explicitly when printing a string retrieved from elsewhere. So if the string is 'abc\ndef' I don't want this to happen: ``` >>> print(line) abc def ``` but instead this: ``` >>> print(line) abc\ndef ``` Is there a way to modify print, or modify the argument, or maybe another funct...
Another way that you can stop python using escape characters is to use a raw string like this: ``` >>> print(r"abc\ndef") abc\ndef ``` or ``` >>> string = "abc\ndef" >>> print (repr(string)) >>> 'abc\ndef' ``` the only proplem with using `repr()` is that it puts your string in single quotes, it can be handy if you ...
In Python, is it possible to escape newline characters when printing a string?
15,392,730
28
2013-03-13T17:48:59Z
15,393,515
12
2013-03-13T18:26:50Z
[ "python", "escaping", "newline" ]
I want the newline `\n` to show up explicitly when printing a string retrieved from elsewhere. So if the string is 'abc\ndef' I don't want this to happen: ``` >>> print(line) abc def ``` but instead this: ``` >>> print(line) abc\ndef ``` Is there a way to modify print, or modify the argument, or maybe another funct...
Simplest method: `str_object.replace("\n", "\\n")` The other methods are better if you want to show *all* escape characters, but if all you care about is newlines, just use a direct replace.
Django: How can i create a multiple select form?
15,393,134
6
2013-03-13T18:07:45Z
15,393,771
17
2013-03-13T18:41:55Z
[ "python", "django", "forms", "field", "multiple-select" ]
I'm beginner in Django/Python and i need to create a multiple select form. I know it's easy but i can't find any example. I know how to create a CharField with a widget but i get confused of all the options inside [fields.py](https://github.com/django/django/blob/1.3/django/forms/fields.py). For example i don't know w...
I think CheckboxSelectMultiple should work. According to your problem, In your forms.py wirite the below code ``` from django import forms class CountryForm(forms.Form): OPTIONS = ( ("AUT", "Austria"), ("DEU", "Germany"), ("NLD", "Neitherlands"), ...
Create Multidimensional Zeros Python
15,393,216
5
2013-03-13T18:11:03Z
15,393,266
10
2013-03-13T18:13:20Z
[ "python", "arrays", "multidimensional-array", "numpy" ]
I need to make a multidimensional array of zeros. For two (D=2) or three (D=3) dimensions, this is easy and I'd use: ``` a = numpy.zeros(shape=(n,n)) ``` or ``` a = numpy.zeros(shape=(n,n,n)) ``` How for I for higher D, make the array of length n?
You can multiply a tuple `(n,)` by the number of dimensions you want. e.g.: ``` >>> import numpy as np >>> N=2 >>> np.zeros((N,)*1) array([ 0., 0.]) >>> np.zeros((N,)*2) array([[ 0., 0.], [ 0., 0.]]) >>> np.zeros((N,)*3) array([[[ 0., 0.], [ 0., 0.]], [[ 0., 0.], [ 0., 0.]]]) ```
Python MySQLdb iterate through table
15,397,239
7
2013-03-13T21:53:39Z
15,397,409
7
2013-03-13T22:05:50Z
[ "python", "mysql", "mysql-python" ]
I have a MSQL db and I need to iterate through a table and perform an action once a WHERE clause is met. Then once it reached the end of the table return to the top and start over. Currently I have ``` cursor = database.cursor() cursor.execute("SELECT user_id FROM round WHERE state == -1 AND state = 2") round_i...
This will set the cursor at the beginning of the result set and tell you how many rows it got back (I went back and forth on this one, but [this is the most authoritative documentation](http://www.python.org/dev/peps/pep-0249/#id14) I have found, older Python MySQLdb lib returned rowcount on execute, but Python Databas...
How do I set browser width and height in Selenium WebDriver?
15,397,483
35
2013-03-13T22:10:30Z
15,397,571
13
2013-03-13T22:16:44Z
[ "python", "selenium", "selenium-webdriver", "screen-resolution" ]
I'm using Selenium WebDriver for Python. I want instantiate the browser with a specific width and height. So far the closest I can get is: ``` driver = webdriver.Firefox() driver.set_window_size(1080,800) ``` Which works, but sets the browser size after it is created, and I want it set at instantiation. I'm guessing ...
Try something like this: ``` IWebDriver _driver = new FirefoxDriver(); _driver.Manage().Window.Position = new Point(0, 0); _driver.Manage().Window.Size = new Size(1024, 768); ``` Not sure if it'll resize after being launched though, so maybe it's not what you want
How do I set browser width and height in Selenium WebDriver?
15,397,483
35
2013-03-13T22:10:30Z
21,964,952
24
2014-02-23T06:20:30Z
[ "python", "selenium", "selenium-webdriver", "screen-resolution" ]
I'm using Selenium WebDriver for Python. I want instantiate the browser with a specific width and height. So far the closest I can get is: ``` driver = webdriver.Firefox() driver.set_window_size(1080,800) ``` Which works, but sets the browser size after it is created, and I want it set at instantiation. I'm guessing ...
For me, the only thing that worked in Java 7 on OS X 10.9 was this: ``` // driver = new RemoteWebDriver(new URL(grid), capability); driver.manage().window().setPosition(new Point(0,0)); driver.manage().window().setSize(new Dimension(1024,768)); ``` Where `1024` is the width, and `768` is the height.
in python webapp2 how put a __init__ in a handler (for get and post)
15,398,179
7
2013-03-13T23:01:45Z
15,624,669
12
2013-03-25T21:00:36Z
[ "python", "webapp2" ]
How can I create initialization code? When I put the `__init__` contructor always tell me that parameters are wrong. Also please gave a example also using `__new__` and one using `super()` and why should we use or not use them. ``` import webapp2 class MainHandler( webapp2.RequestHandler ): def __init__( self ): ...
Finally got it... The problem is that overriding "webapp2.RequestHandler" requires special special handling from the webapp2 manual: If you want to override the webapp2.RequestHandler.**init**() method, you must call webapp2.RequestHandler.initialize() at the beginning of the method. It’ll set the current request, ...
Does the `is` operator use a __magic__ method in Python?
15,399,024
5
2013-03-14T00:21:54Z
15,399,044
13
2013-03-14T00:24:20Z
[ "python", "operators" ]
The [is](http://docs.python.org/2/reference/expressions.html#is) operator is used test for identity. I was wondering if the `is` operator and `id()` function call any `__magic__` method, the way `==` calls `__eq__`. I had some fun checking out `__hash__`: ``` class Foo(object): def __hash__(self): return...
No, `is` is a straight pointer comparison, and `id` just returns the address of the object cast to a `long`. From [`ceval.c`](http://hg.python.org/cpython/file/bd8afb90ebf2/Python/ceval.c#l4423): ``` case PyCmp_IS: res = (v == w); break; case PyCmp_IS_NOT: res = (v != w); break; ``` `v` and `w` here ...
Does the `is` operator use a __magic__ method in Python?
15,399,024
5
2013-03-14T00:21:54Z
15,399,080
9
2013-03-14T00:27:08Z
[ "python", "operators" ]
The [is](http://docs.python.org/2/reference/expressions.html#is) operator is used test for identity. I was wondering if the `is` operator and `id()` function call any `__magic__` method, the way `==` calls `__eq__`. I had some fun checking out `__hash__`: ``` class Foo(object): def __hash__(self): return...
The short answer is: No, they do not. As the docs that you link to say: > The operators `is` and `is not` test for object identity: `x is y` is true if and only if `x` and `y` are the same object. Being "the same object" is not something you're allowed to override. If your object is not the same object as another, it...
Can't start foreman in Heroku Tutorial using Python
15,399,637
41
2013-03-14T01:32:27Z
15,726,134
70
2013-03-31T03:49:53Z
[ "python", "ruby", "heroku", "foreman", "git-bash" ]
I have been attempting to complete [this tutorial](https://devcenter.heroku.com/articles/python), but have run into a problem with the `foreman start` line. I am using a windows 7, 64 bit machine and am attempting to do this in the git bash terminal provided by the Heroku Toolbelt. When I enter `foreman start` I recei...
I had this problem. I fixed it by uninstalling version 0.62 of the foreman gem and installing 0.61. ``` gem uninstall foreman gem install foreman -v 0.61 ```
Can't start foreman in Heroku Tutorial using Python
15,399,637
41
2013-03-14T01:32:27Z
18,523,283
11
2013-08-30T00:58:10Z
[ "python", "ruby", "heroku", "foreman", "git-bash" ]
I have been attempting to complete [this tutorial](https://devcenter.heroku.com/articles/python), but have run into a problem with the `foreman start` line. I am using a windows 7, 64 bit machine and am attempting to do this in the git bash terminal provided by the Heroku Toolbelt. When I enter `foreman start` I recei...
Yes, heroku-toolbelt-installer is not working correctly at present (30-Aug-2013). For windows the following steps worked for me: 1. uninstall heroku (via windows 'program uninstall') 2. install heroku <https://toolbelt.heroku.com/windows> into C:\bin\heroku , i.e. 'no spaces' 3. install ruby from <http://rubyinstaller...
How to generate the 1000th prime in python?
15,400,108
9
2013-03-14T02:27:26Z
15,421,617
7
2013-03-14T22:44:15Z
[ "python", "primes" ]
``` count = 0 i = 11 while count <= 1000 and i <= 10000: if i%2 != 0: if (i%3 == 0 or i%4 == 0 or i%5 == 0 or i%6 == 0 or i%7 == 0 or i%9 == 0): continue else: print i,'is prime.' count += 1 i+=1 ``` I'm trying to generate the 1000th prime number only through the...
Let's see. ``` count = 1 i = 3 while count != 1000: if i%2 != 0: for k in range(2,i): if i%k == 0: # 'i' is _not_ a prime! print(i) # ?? count += 1 # ?? break i += 1 # should be one space to the left, # for pro...
What's going on with this python syntax? (c == c in s)
15,401,111
10
2013-03-14T04:16:53Z
15,401,182
13
2013-03-14T04:24:30Z
[ "python", "python-2.7" ]
Someone just showed me this weird example of python syntax. Why is [4] working? I would have expected it to evaluate to either [5] or [6], neither of which works. Is there some premature optimisation going on here which shouldn't be? ``` In [1]: s = 'abcd' In [2]: c = 'b' In [3]: c in s Out[3]: True In [4]: c == ...
This is the same syntactic sugar that allows python to chain multiple operators (like `<`) together. For example: ``` >>> 0 < 1 < 2 True ``` This is equivalent to `(0<1) and (1<2)`, with the exception that the middle expression is only evaluated once. The statement `c == c in s` is similarly equivalent to `(c == c)...
Python SimpleHTTPServer
15,401,815
5
2013-03-14T05:24:16Z
15,401,921
8
2013-03-14T05:33:08Z
[ "python", "ember.js", "simplehttpserver" ]
Is there a way to make Python SimpleHTTPServer supports mod\_rewrite? I'm trying things with Ember.js with leveraging History API as the location API, and to make it work, I have to : ``` 1) add some vhosts config in WAMP (not simple), or 2) run python -m simpleHTTPServer (very simple) ``` So when I opened it in the...
[SimpleHTTPServer](http://docs.python.org/2/library/simplehttpserver.html) does not support apache modules and does not respect .htaccess, because it isn't apache. it won't work with php either.
Python SimpleHTTPServer
15,401,815
5
2013-03-14T05:24:16Z
15,423,169
7
2013-03-15T01:25:04Z
[ "python", "ember.js", "simplehttpserver" ]
Is there a way to make Python SimpleHTTPServer supports mod\_rewrite? I'm trying things with Ember.js with leveraging History API as the location API, and to make it work, I have to : ``` 1) add some vhosts config in WAMP (not simple), or 2) run python -m simpleHTTPServer (very simple) ``` So when I opened it in the...
If you know the cases you need to redirect you can subclass [SimpleHTTPRequestHandler](http://docs.python.org/2/library/simplehttpserver.html#SimpleHTTPServer.SimpleHTTPRequestHandler) and do a redirect. This redirects any missing file requests to **/index.html** ``` import SimpleHTTPServer, SocketServer import urlpar...