title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags list |
|---|---|---|---|---|---|---|---|---|---|
How to define class variables using the functions and variables of an instance in Python | 39,856,861 | <p>Is there a way to define a class variable using the variables and functions of the instance? Thanks</p>
<p>The simplified code looks like this:</p>
<pre><code>def ClassA():
X = self.func(self.a)
def __init__(self, avalue):
self.a = avalue
def func(self):
return self.a + 5
</code></pre... | -3 | 2016-10-04T15:57:17Z | 39,857,029 | <p>I guess what you tried to do was:</p>
<pre><code>class ClassA():
def __init__(self,avalue):
self.a = avalue
self.X = self.func
def func(self):
return self.a + 5
b = ClassA(43)
b.X()
</code></pre>
<p>outputs </p>
<pre><code>48
</code></pre>
| 0 | 2016-10-04T16:06:10Z | [
"python",
"class",
"scope"
] |
How to define class variables using the functions and variables of an instance in Python | 39,856,861 | <p>Is there a way to define a class variable using the variables and functions of the instance? Thanks</p>
<p>The simplified code looks like this:</p>
<pre><code>def ClassA():
X = self.func(self.a)
def __init__(self, avalue):
self.a = avalue
def func(self):
return self.a + 5
</code></pre... | -3 | 2016-10-04T15:57:17Z | 39,857,055 | <pre><code>class A():
def __init__(self):
self.y = 0
def m(self):
A.x = 1
b = A()
#print(b.x) doesn't work here since we haven't made it yet.
b.m()
print(b.x) #1
c = A()
print(c.x) #1
A.x = 2
print(c.x) #2
print(b.x) #2
print(vars(A)) #{'__dict__': <attribute '__dict__' of 'A' objects>... | 0 | 2016-10-04T16:07:58Z | [
"python",
"class",
"scope"
] |
How to use matplotlib quiver using an external file | 39,856,867 | <p>I am trying to write a very simple code (should be):</p>
<p>I want to plot arrows from an external data file which gives me the vector dimensions in x and y, given in two columns sx and sy.</p>
<p>For example, I have two columns of 36 numbers each but they are the dimension of a vector having 6x6 grid. however whe... | 0 | 2016-10-04T15:57:56Z | 39,857,142 | <p>You would benefit from a quick sanity check.</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
data=np.loadtxt(r'text.dat')
x,y = np.meshgrid(np.arange(0, 6, 1), np.arange(0, 6, 1))
print x # 6x6 array, 2D!
print y # 6x6 array, 2D!
u = data[:,1] # 36 array, 1D!
v = data... | 1 | 2016-10-04T16:11:31Z | [
"python",
"matplotlib",
"plot",
"vector-graphics"
] |
How to extract a specific part from a JSON response? | 39,856,978 | <p>I have code like</p>
<pre><code>import requests
dict_api = "http://api.pearson.com/v2/dictionaries/entries?headword="
r = requests.get(dict_api + word)
results = r.json()["results"]
</code></pre>
<p>and this gives me this:</p>
<pre><code>[
{
"senses": [
{
"translation": "\\... | 0 | 2016-10-04T16:03:37Z | 39,857,083 | <pre><code>print(results[0]['part_of_speech'])
#prints 'noun'
</code></pre>
| 3 | 2016-10-04T16:09:02Z | [
"python",
"json",
"python-requests"
] |
How to extract a specific part from a JSON response? | 39,856,978 | <p>I have code like</p>
<pre><code>import requests
dict_api = "http://api.pearson.com/v2/dictionaries/entries?headword="
r = requests.get(dict_api + word)
results = r.json()["results"]
</code></pre>
<p>and this gives me this:</p>
<pre><code>[
{
"senses": [
{
"translation": "\\... | 0 | 2016-10-04T16:03:37Z | 39,857,151 | <pre><code>for i in range(len(results)):
print(results[i]['part_of_speech'])
noun
noun
noun
noun
noun
noun
noun
noun
noun
noun
</code></pre>
| 1 | 2016-10-04T16:12:02Z | [
"python",
"json",
"python-requests"
] |
Dropping multilevel columns from lists of dictionaries in pandas | 39,857,148 | <p>I have a dataframe with multilevel columns, like the one in the following MWE:</p>
<pre><code>df = pd.DataFrame([[1,2],[3,4]], columns=[['a','c'],['b','d']], index=['one','two'])
df.columns.names = ['aa', 'bb']
</code></pre>
<p>Which looks like this:</p>
<pre><code>In [267]: df
Out[267]:
aa a c
bb b d
one ... | 2 | 2016-10-04T16:11:55Z | 39,859,358 | <p>Create a <code>DF</code> mapping the column names to it's levels of the multi-index <code>DF</code>:</p>
<pre><code>level_df = pd.DataFrame(df.columns.values.tolist(), columns=np.array(df.columns.names))
level_df
</code></pre>
<p><a href="http://i.stack.imgur.com/55E5e.png" rel="nofollow"><img src="http://i.stack.... | 1 | 2016-10-04T18:30:38Z | [
"python",
"pandas",
"multi-index"
] |
plot differently colored background rectangles on plot over several axes | 39,857,170 | <p>The following code is a snippet from a much larger function that plots several financial indicators over 3 axis:</p>
<pre><code>left, width = 0.1, 0.8
rect1 = [left, 0.7, width, 0.2]
rect2 = [left, 0.3, width, 0.4]
rect3 = [left, 0.1, width, 0.2]
fig = plt.figure(facecolor='white')
axescolor = '#f6f6f6' # the axes... | 0 | 2016-10-04T16:13:16Z | 39,857,214 | <p>This works :</p>
<pre><code>ax1.axvspan(start, end, facecolor='g', alpha=0.25, label=my_label)
</code></pre>
| 1 | 2016-10-04T16:15:56Z | [
"python",
"matplotlib"
] |
plot differently colored background rectangles on plot over several axes | 39,857,170 | <p>The following code is a snippet from a much larger function that plots several financial indicators over 3 axis:</p>
<pre><code>left, width = 0.1, 0.8
rect1 = [left, 0.7, width, 0.2]
rect2 = [left, 0.3, width, 0.4]
rect3 = [left, 0.1, width, 0.2]
fig = plt.figure(facecolor='white')
axescolor = '#f6f6f6' # the axes... | 0 | 2016-10-04T16:13:16Z | 39,857,261 | <p>You can use the <code>patches</code> from <code>matplotlib</code></p>
<pre><code>import matplotlib.patches as patches
left, width = 0.1, 0.8
rect1 = [left, 0.7, width, 0.2]
rect2 = [left, 0.3, width, 0.4]
rect3 = [left, 0.1, width, 0.2]
fig = plt.figure(facecolor='white')
axescolor = '#f6f6f6' # the axes backgrou... | 2 | 2016-10-04T16:18:17Z | [
"python",
"matplotlib"
] |
Use OrderedDict for SQLAlchemy relationship()? | 39,857,194 | <p>Is it possible to tell SQLAlchemy to use <code>OrderedDict</code> for the <code>relationship</code> storage? I'm only familiar with <code>attribute_mapped_collection</code>, but that's unordered.</p>
| 1 | 2016-10-04T16:14:53Z | 39,859,765 | <p>There's an <a href="http://docs.sqlalchemy.org/en/latest/orm/collections.html#custom-dictionary-based-collections" rel="nofollow">example</a> of this in the docs:</p>
<pre><code>from sqlalchemy.util import OrderedDict
from sqlalchemy.orm.collections import MappedCollection
class NodeMap(OrderedDict, MappedCollecti... | 3 | 2016-10-04T18:56:07Z | [
"python",
"python-3.x",
"sqlalchemy"
] |
Email as Username in an existing django app | 39,857,213 | <p>I created an app where I used to require an <code>email</code> and a <code>username</code> for signup. </p>
<p>Now I would like to change this so that any existing users have their username changed to their email. Any new users will not see the username field upon signup, but in the backend they'd be the same. </p>... | 0 | 2016-10-04T16:15:55Z | 39,861,387 | <p>You probably need to change the authentication backend and then change your models. More information can be found on the django documentation website: </p>
<p><a href="https://docs.djangoproject.com/en/1.10/topics/auth/customizing/" rel="nofollow">https://docs.djangoproject.com/en/1.10/topics/auth/customizing/</a><... | 4 | 2016-10-04T20:41:31Z | [
"python",
"django"
] |
sqlite3 update database with "?" - python | 39,857,219 | <p>I have: </p>
<p>database testing.db3
table: mytable
columns: 'name', 'status'</p>
<p>I do:</p>
<pre><code>con = sqlite3.connect('testing.db3')
cur = con.cursor()
cur.execute('select * from mytable where status is null')
data = cur.fetchone()
print(data[0])
</code></pre>
<p>as wanted I receive following result:<... | 0 | 2016-10-04T16:16:05Z | 39,857,448 | <pre><code>cur.execute('UPDATE mytable SET status = "Online" WHERE name is ?', (data[0], ))
</code></pre>
<p><code>execute</code> expects a tuple as an input parameter. Therefore, even if you insert only a single value, you should format it as a tuple. </p>
<p>Although in your question you say that <code>data[0] = ('... | 2 | 2016-10-04T16:28:44Z | [
"python",
"sql",
"sqlite3",
"insert"
] |
Deleting a row if it contains a string in a CSV file | 39,857,223 | <p>I'm having trouble deleting rows in text file that contains a string in one column. My code so far is not able to delete the row, but it's able to read the text file and save it as a CSV file into separate columns. But the rows are not getting deleted.</p>
<p>This is what the values in that column looks like:</p>
... | 1 | 2016-10-04T16:16:17Z | 39,857,616 | <p>Each line output by the csv reader is a list of strings, not a string, so your list comprehension is checking if 'INAC' or 'EIM' is one of the members of the list, i.e:</p>
<pre><code>'INAC' in ['3000004000_SHIP_TO-INAC-EIM', ...]
</code></pre>
<p>Which is always false, since 'in' looks for exact matches when call... | 1 | 2016-10-04T16:39:58Z | [
"python",
"python-3.x"
] |
Deleting a row if it contains a string in a CSV file | 39,857,223 | <p>I'm having trouble deleting rows in text file that contains a string in one column. My code so far is not able to delete the row, but it's able to read the text file and save it as a CSV file into separate columns. But the rows are not getting deleted.</p>
<p>This is what the values in that column looks like:</p>
... | 1 | 2016-10-04T16:16:17Z | 39,857,619 | <p>The problem here is that the <code>csv.reader</code> object returns the rows of the file as lists of individual column values, so the "in" test is checking to see whether any of the individual values in that list is equal to a <code>remove_word</code>.</p>
<p>A quick fix would be to try</p>
<pre><code> if n... | 1 | 2016-10-04T16:40:16Z | [
"python",
"python-3.x"
] |
Deleting a row if it contains a string in a CSV file | 39,857,223 | <p>I'm having trouble deleting rows in text file that contains a string in one column. My code so far is not able to delete the row, but it's able to read the text file and save it as a CSV file into separate columns. But the rows are not getting deleted.</p>
<p>This is what the values in that column looks like:</p>
... | 1 | 2016-10-04T16:16:17Z | 39,859,748 | <p>As other answers have pointed out, the reason your code doesn't work is because each <code>line in csv.reader</code> is actually a list of column values, so the <code>remove_word in line</code> checks to see if any of them is exactly equal to one of the <code>remove_words</code> â which is apparently never <code>T... | 1 | 2016-10-04T18:55:08Z | [
"python",
"python-3.x"
] |
how to create a new variable in a loop | 39,857,224 | <p>I'm trying to make a function that prints n number of rows of the following sequence </p>
<pre><code>1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
...
</code></pre>
<p>this is what I have so far:</p>
<pre><code>def numTriangle(n):
#n = number of rows
integers = range(0,n-1)
val = 1
places... | 0 | 2016-10-04T16:16:17Z | 39,857,457 | <p>Not trying to do your homework for you, but you at least have a basic description of your plan. Here is a pretty minimal version.</p>
<pre><code>def pyramid(n):
k = 1
for i in range(n):
print ' '.join(map(str, range(k, k+i+1)))
k += i + 1
</code></pre>
<p>Here is a version that is more verb... | 1 | 2016-10-04T16:29:27Z | [
"python",
"jes"
] |
how to create a new variable in a loop | 39,857,224 | <p>I'm trying to make a function that prints n number of rows of the following sequence </p>
<pre><code>1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
...
</code></pre>
<p>this is what I have so far:</p>
<pre><code>def numTriangle(n):
#n = number of rows
integers = range(0,n-1)
val = 1
places... | 0 | 2016-10-04T16:16:17Z | 39,857,712 | <p>This produces your output:</p>
<pre><code>n = 6; y= 1;
for i in range(0,n):
for j in range (0,i):
print y,
y = y+1;
print "\n"
</code></pre>
<p>Note the indentation, indentation defines the scopes.</p>
| 0 | 2016-10-04T16:45:48Z | [
"python",
"jes"
] |
How to remove a random element from a list and add it to another list in python | 39,857,231 | <p><code>list = ['john','james','michael','david','william']</code></p>
<p><code>winner = []</code></p>
<p>How can I remove a random item from <code>list</code> and add it to <code>winner</code>?</p>
| 0 | 2016-10-04T16:16:48Z | 39,857,313 | <p>This selects a random item from a list of names <code>names</code> and adds it to another list <code>winner</code>. The chosen winner is then removed from the <code>names</code>.</p>
<pre><code>import random
winner = []
names = ['john','james','michael','david','william']
winnerindex = random.randint(0,len(names)-1... | 0 | 2016-10-04T16:21:05Z | [
"python",
"list",
"random-access"
] |
How to remove a random element from a list and add it to another list in python | 39,857,231 | <p><code>list = ['john','james','michael','david','william']</code></p>
<p><code>winner = []</code></p>
<p>How can I remove a random item from <code>list</code> and add it to <code>winner</code>?</p>
| 0 | 2016-10-04T16:16:48Z | 39,857,337 | <p>Simply use random.randint from index 0 to len(list) to get the index of the element of list and append it to winner.</p>
<pre><code>import random
index = random.randomint(0, len(list)-1)
winner.append(list[index])
del list[index]
</code></pre>
| -1 | 2016-10-04T16:22:42Z | [
"python",
"list",
"random-access"
] |
How to remove a random element from a list and add it to another list in python | 39,857,231 | <p><code>list = ['john','james','michael','david','william']</code></p>
<p><code>winner = []</code></p>
<p>How can I remove a random item from <code>list</code> and add it to <code>winner</code>?</p>
| 0 | 2016-10-04T16:16:48Z | 39,857,461 | <pre><code>winner.append(list.pop(random.randrange(0,len(list))))
</code></pre>
<p>To break this down:</p>
<pre><code>random.randrange(0,len(list))
</code></pre>
<p>will generate a random number between zero and the length of your list inclusive. This will generate a random index in your list that you can reference... | 3 | 2016-10-04T16:29:38Z | [
"python",
"list",
"random-access"
] |
Should I use Conda or Conda Forge when creating Anaconda Python environments? | 39,857,289 | <p>I understand that conda-forge was initiated to build and maintain packages. </p>
<p>But when building Anaconda Python environments, how do we know when to use 'conda-forge' verses 'conda install' if a package exists in both repositories? Django for example can be installed with both 'conda install' and 'conda-forg... | 0 | 2016-10-04T16:19:58Z | 39,862,730 | <p>The short answer is that, in my experience generally, it doesn't matter which you use.</p>
<p>The long answer:</p>
<p>So <code>conda-forge</code> is an additional channel from which packages may be installed. In this sense, it is not any more special than the default channel, or any of the other hundreds (thousand... | 1 | 2016-10-04T22:28:14Z | [
"python",
"conda"
] |
How save an string output after a for loop in python with pandas and csv modules? | 39,857,297 | <p>I have the following for loop:</p>
<pre><code> for titles in titles:
title = titles.xpath("a/text()").extract()
link = titles.xpath("a/@href").extract()
print(title, link)
</code></pre>
<p>How can I dump the title and link into a formmated .csv file?</p>
| 0 | 2016-10-04T16:20:14Z | 39,857,380 | <p>Use a <a href="https://docs.python.org/2/library/csv.html" rel="nofollow">csv writer</a>.</p>
<p>Basic usage:</p>
<pre><code>import csv
with open('file.csv') as f:
writer = csv.writer(f)
writer.writerow(["title", "link"])
</code></pre>
| 1 | 2016-10-04T16:25:00Z | [
"python",
"python-3.x",
"csv",
"pandas"
] |
How save an string output after a for loop in python with pandas and csv modules? | 39,857,297 | <p>I have the following for loop:</p>
<pre><code> for titles in titles:
title = titles.xpath("a/text()").extract()
link = titles.xpath("a/@href").extract()
print(title, link)
</code></pre>
<p>How can I dump the title and link into a formmated .csv file?</p>
| 0 | 2016-10-04T16:20:14Z | 39,857,488 | <p>You should use the python CSV module. Look here for more infromation, <a href="http://stackoverflow.com/questions/6916542/writing-list-of-strings-to-excel-csv-file-in-python">Writing List of Strings to Excel CSV File in Python</a>. Here is some example for your problem. </p>
<pre><code>import csv
results = []
# yo... | 3 | 2016-10-04T16:31:07Z | [
"python",
"python-3.x",
"csv",
"pandas"
] |
How save an string output after a for loop in python with pandas and csv modules? | 39,857,297 | <p>I have the following for loop:</p>
<pre><code> for titles in titles:
title = titles.xpath("a/text()").extract()
link = titles.xpath("a/@href").extract()
print(title, link)
</code></pre>
<p>How can I dump the title and link into a formmated .csv file?</p>
| 0 | 2016-10-04T16:20:14Z | 39,857,501 | <p>Something like this (<a href="https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files" rel="nofollow">documentation</a>): </p>
<pre><code>...
doc_path = "path/to/doc.csv" # must exist, first folder on the place
# where you are running the script!
with open(doc_path... | 2 | 2016-10-04T16:31:47Z | [
"python",
"python-3.x",
"csv",
"pandas"
] |
How save an string output after a for loop in python with pandas and csv modules? | 39,857,297 | <p>I have the following for loop:</p>
<pre><code> for titles in titles:
title = titles.xpath("a/text()").extract()
link = titles.xpath("a/@href").extract()
print(title, link)
</code></pre>
<p>How can I dump the title and link into a formmated .csv file?</p>
| 0 | 2016-10-04T16:20:14Z | 39,857,561 | <pre><code>result = []
for titles in titles:
title = titles.xpath("a/text()").extract()
link = titles.xpath("a/@href").extract()
print(title, link)
result += [title + ',' + link + '\n']
with open("result.csv" "w+") as f:
f.writelines(result)
</code></pre>
| 1 | 2016-10-04T16:36:35Z | [
"python",
"python-3.x",
"csv",
"pandas"
] |
Creating pattern using simple loops? | 39,857,341 | <p>I am trying to create this pattern in python:</p>
<pre><code> *
* *
* * *
* *
*
</code></pre>
<p>This is my program so far that I've come up with:</p>
<pre><code>ster = "*"
space = " "
lines = 0
n = 3
x = 1
while lines <= 5:
print space*n, ster*x
n-= 1
x+= 1
lines += 1
</code></... | -2 | 2016-10-04T16:22:52Z | 39,857,587 | <p>Okay, first of all you can create a list of numbers which represents the number of stars in each line.</p>
<pre><code>number_of_stars = 5
i_list = list(range(number_of_stars))
# extend the list by its inverse i_list[::-1]
# but exclude the first item
i_list.extend(i_list[::-1][1:])
print(i_list) # prints: [0, 1, ... | 2 | 2016-10-04T16:38:20Z | [
"python",
"python-2.7",
"loops"
] |
Creating pattern using simple loops? | 39,857,341 | <p>I am trying to create this pattern in python:</p>
<pre><code> *
* *
* * *
* *
*
</code></pre>
<p>This is my program so far that I've come up with:</p>
<pre><code>ster = "*"
space = " "
lines = 0
n = 3
x = 1
while lines <= 5:
print space*n, ster*x
n-= 1
x+= 1
lines += 1
</code></... | -2 | 2016-10-04T16:22:52Z | 39,857,626 | <p>Notice you have</p>
<ul>
<li>3 spaces for 1 star</li>
<li>2 spaces for 2 stars</li>
<li>1 space for 3 stars.</li>
</ul>
<p>For the upright triangle part of your diamond (including the large part). Then you have</p>
<ul>
<li>2 spaces for 2 stars</li>
<li>3 spaces for 1 star</li>
</ul>
<p>Without throwing out the ... | 1 | 2016-10-04T16:40:43Z | [
"python",
"python-2.7",
"loops"
] |
Creating pattern using simple loops? | 39,857,341 | <p>I am trying to create this pattern in python:</p>
<pre><code> *
* *
* * *
* *
*
</code></pre>
<p>This is my program so far that I've come up with:</p>
<pre><code>ster = "*"
space = " "
lines = 0
n = 3
x = 1
while lines <= 5:
print space*n, ster*x
n-= 1
x+= 1
lines += 1
</code></... | -2 | 2016-10-04T16:22:52Z | 39,857,692 | <p>Thank you for the help, I wrote a functional code for the problem. It was supposed to made using while loop(s).
This is what I did:</p>
<pre><code>width = int(input("Width: "))
i = 1
while i < width*2:
if i < width:
print " " * (width-i) + "* " * i
else:
print " " * (i-width) + "* " * (2*... | 2 | 2016-10-04T16:44:48Z | [
"python",
"python-2.7",
"loops"
] |
Pandas - Selecting multiple dataframe criteria | 39,857,428 | <p>I have a DataFrame with multiple columns and I need to set the criteria to access specific values from two different columns. I'm able to do it successfully on one column as shown here:</p>
<pre><code>status_filter = df[df['STATUS'] == 'Complete']
</code></pre>
<p>But I'm struggling to specify values from two colu... | 1 | 2016-10-04T16:28:05Z | 39,857,462 | <pre><code>status_filter = df.ix[(df['STATUS'] == 'Complete') & (df['READY TO INVOICE'] == 'No'),]
</code></pre>
<p>ur welcome</p>
| 1 | 2016-10-04T16:29:41Z | [
"python",
"pandas",
"dataframe"
] |
Pandas - Selecting multiple dataframe criteria | 39,857,428 | <p>I have a DataFrame with multiple columns and I need to set the criteria to access specific values from two different columns. I'm able to do it successfully on one column as shown here:</p>
<pre><code>status_filter = df[df['STATUS'] == 'Complete']
</code></pre>
<p>But I'm struggling to specify values from two colu... | 1 | 2016-10-04T16:28:05Z | 39,857,531 | <p>you can use:</p>
<pre><code>status_filter = df[(df['STATUS'] == 'Complete') & (df['READY TO INVOICE'] == 'No')]
</code></pre>
| 0 | 2016-10-04T16:34:07Z | [
"python",
"pandas",
"dataframe"
] |
Pandas - Selecting multiple dataframe criteria | 39,857,428 | <p>I have a DataFrame with multiple columns and I need to set the criteria to access specific values from two different columns. I'm able to do it successfully on one column as shown here:</p>
<pre><code>status_filter = df[df['STATUS'] == 'Complete']
</code></pre>
<p>But I'm struggling to specify values from two colu... | 1 | 2016-10-04T16:28:05Z | 39,857,722 | <p>Your code has two very small errors: 1) need parentheses for two or more criteria and 2) you need to use the ampersand between your criteria:</p>
<pre><code>status_filter = df[(df['STATUS'] == 'Complete') & (df['READY TO INVOICE'] == 'No')]
</code></pre>
| 4 | 2016-10-04T16:46:28Z | [
"python",
"pandas",
"dataframe"
] |
Repeated regex groups of arbitrary number | 39,857,497 | <p>I have this example text snippet</p>
<pre><code>headline:
Status[apphmi]: blubb, 'Statustext1'
Main[apphmi]: bla, 'Maintext1'Main[apphmi]: blaa, 'Maintext2'
Popup[apphmi]: blaaa, 'Popuptext1'
</code></pre>
<p>and I want to extract the words within '', but sorted with the context (status, ma... | 0 | 2016-10-04T16:31:42Z | 39,857,790 | <p>You can try with this:</p>
<pre><code>r"(.*?]):(?:[^']*)'([^']*)'"g
</code></pre>
<p><a href="http://pythex.org/?regex=(.*%3F%5D)%3A(%3F%3A%5B%5E%27%5D*)%27(%5B%5E%27%5D*)%27&test_string=headline%3A%0A%20%20%20%20Status%5Bapphmi%5D%3A%20blubb%2C%20%27Statustext%27%0A%20%20%20%20Main%5Bapphmi%5D%3A%20bla%2C%20%... | 0 | 2016-10-04T16:51:13Z | [
"python",
"regex"
] |
Google App Engine urlfetch DeadlineExceededError in push task handler running apiclient batch request | 39,857,515 | <p>I have a task handler that is making a batch request to the Google Calendar API. After 5 seconds, the request fails with <em>DeadlineExceededError: The API call urlfetch.Fetch() took too long to respond and was cancelled.</em> I have changed <code>urlfetch.set_default_fetch_deadline(60)</code> near where I make the... | 2 | 2016-10-04T16:32:42Z | 39,860,394 | <p>Try adding the <code>deadline</code> parameter:</p>
<p><code>my_result = urlfetch.fetch(my_url, deadline=15)</code></p>
| 0 | 2016-10-04T19:35:36Z | [
"python",
"google-app-engine",
"google-api",
"google-calendar",
"task-queue"
] |
Google App Engine urlfetch DeadlineExceededError in push task handler running apiclient batch request | 39,857,515 | <p>I have a task handler that is making a batch request to the Google Calendar API. After 5 seconds, the request fails with <em>DeadlineExceededError: The API call urlfetch.Fetch() took too long to respond and was cancelled.</em> I have changed <code>urlfetch.set_default_fetch_deadline(60)</code> near where I make the... | 2 | 2016-10-04T16:32:42Z | 39,865,233 | <p>So, <code>urlfetch.set_default_fetch_deadline()</code> did eventually work for me. The problem was my underlying http client (oauth2client / httplib2) was essentially stored in a global. Once I created it in the task handler thread the <code>set_default_fetch_deadline</code> worked.</p>
| 1 | 2016-10-05T04:01:53Z | [
"python",
"google-app-engine",
"google-api",
"google-calendar",
"task-queue"
] |
How to accept 0 as a value in a list? and When I enter the numbers after a space I get an error | 39,857,608 | <p>Everytime I enter a value such as 002
the length comes out as 1 however it should come out as 3
My code is:</p>
<pre><code>list1 = int(input("Enter a number"))
list1 = [int(x) for x in str(list1)]
print (len(list1))
</code></pre>
<p>If I type in a number after a space I get an error saying:</p>
<pre><code>File "... | 1 | 2016-10-04T16:39:17Z | 39,857,647 | <p>Don't convert your input to a int. If you convert your the string <code>002</code> to a int, the leading zeros are gone, because <code>002</code> is the same number as <code>2</code>. Converting to string again leads to <code>2</code>, which only has a length of 1.</p>
<pre><code>text = input("Enter a number")
lis... | 3 | 2016-10-04T16:41:38Z | [
"python"
] |
How to accept 0 as a value in a list? and When I enter the numbers after a space I get an error | 39,857,608 | <p>Everytime I enter a value such as 002
the length comes out as 1 however it should come out as 3
My code is:</p>
<pre><code>list1 = int(input("Enter a number"))
list1 = [int(x) for x in str(list1)]
print (len(list1))
</code></pre>
<p>If I type in a number after a space I get an error saying:</p>
<pre><code>File "... | 1 | 2016-10-04T16:39:17Z | 39,857,673 | <p>You're casting the input to an integer with <code>int</code>, so you're removing trailing zeroes. Integers don't preserve their trailing zeroes, so when converted it becomes a single digit:</p>
<pre><code>int("002")
# 2
</code></pre>
<p>You should remove the first int call, save it as a string until you split it u... | 0 | 2016-10-04T16:43:51Z | [
"python"
] |
How to accept 0 as a value in a list? and When I enter the numbers after a space I get an error | 39,857,608 | <p>Everytime I enter a value such as 002
the length comes out as 1 however it should come out as 3
My code is:</p>
<pre><code>list1 = int(input("Enter a number"))
list1 = [int(x) for x in str(list1)]
print (len(list1))
</code></pre>
<p>If I type in a number after a space I get an error saying:</p>
<pre><code>File "... | 1 | 2016-10-04T16:39:17Z | 39,857,675 | <p>Because you cast the user input <code>"002"</code> to an int with value <code>2</code>. Then, in your list comprehension you cast it back to a string <code>"2"</code>, over which you iterate (once). </p>
<p>The result of your list comprehension is thus <code>["2"]</code>, a list of length 1.</p>
<p>So instead of c... | 0 | 2016-10-04T16:43:54Z | [
"python"
] |
How to accept 0 as a value in a list? and When I enter the numbers after a space I get an error | 39,857,608 | <p>Everytime I enter a value such as 002
the length comes out as 1 however it should come out as 3
My code is:</p>
<pre><code>list1 = int(input("Enter a number"))
list1 = [int(x) for x in str(list1)]
print (len(list1))
</code></pre>
<p>If I type in a number after a space I get an error saying:</p>
<pre><code>File "... | 1 | 2016-10-04T16:39:17Z | 39,857,685 | <p>If you do:</p>
<pre><code>s = "002"
i = int(s)
print(i)
</code></pre>
<p>outputs</p>
<pre><code>2
</code></pre>
<p>because leading 0 are dropped during the casting to int. As a matter of fact,</p>
<pre><code>i = 002
</code></pre>
<p>is illegal and yields</p>
<pre><code>SyntaxError: invalid token
</code></pre>... | 0 | 2016-10-04T16:44:13Z | [
"python"
] |
Fastest Method To Read Thousands of JSON Files in Python | 39,857,632 | <p>I have a number of JSON files I need to analyze. I am using iPython (<code>Python 3.5.2 | IPython 5.0.0</code>), reading in the files to a dictionary and appending each dictionary to a list.</p>
<p>My main bottleneck is reading in the files. Some files are smaller, and are read quickly, but the larger files are slo... | 1 | 2016-10-04T16:41:00Z | 39,857,750 | <p>Use list comprehension to avoid resizing list multiple times.</p>
<pre><code>def giant_list(json_files):
return [read_json_file(path) for path in json_files]
</code></pre>
<p>You are closing file object twice, simply do it once (on exiting <code>with</code> file would be closed automatically)</p>
<pre><code>d... | 1 | 2016-10-04T16:48:40Z | [
"python",
"json",
"python-3.x",
"ipython"
] |
Python array_flip analogue or best way to do this? | 39,857,691 | <p>Is there array_flip (php) analogue for Python 3.x? </p>
<p>from</p>
<pre><code>obj = ['a', 'c', 'b' ]
</code></pre>
<p>to </p>
<pre><code>{'a': 1, 'c':2, 'b': 3}
</code></pre>
| 2 | 2016-10-04T16:44:48Z | 39,857,729 | <p>You can use a list comprehension along with the <code>dict</code> constructor, as follows:</p>
<pre><code>>>> obj = [ 'a', 'c', 'b' ]
>>> dict((x, i + 1) for i, x in enumerate(obj))
{'a': 1, 'c': 2, 'b': 3}
</code></pre>
<p>As noted in the comments, you can also use a simple dict comprehension:</... | 1 | 2016-10-04T16:47:07Z | [
"python",
"sorting"
] |
error: list indices must be indtegers, not str | 39,857,717 | <pre><code>fields = ["date", "time", "a_x", "a_y", "a_z", "roll", "pitch", "yaw", "ug_x", "ug_y", "ug_z", "o2", "hyd", "bpm"]
import csv
f = open("data.TXT")
dialect = csv.Sniffer().sniff(f.read(), delimiters=' ')
f.seek(0)
reader = csv.reader(f, dialect)
rows = []
obj = {}
for row in reader:
for i, field i... | -1 | 2016-10-04T16:46:19Z | 39,857,813 | <pre><code>for obj in rows:
row["player_id"] = ['03fd6907-64fc-46e7-b1f2-38af96c48037']
</code></pre>
<p>The loop variable is called <code>obj</code> but you are trying to access <code>row</code>. <code>row</code> is a list left over from a previous loop (<code>for row in reader:</code>). Change <code>row</code>... | 2 | 2016-10-04T16:52:27Z | [
"python",
"database",
"mongodb",
"csv"
] |
Fetch HTML From URL in Python | 39,857,757 | <p>I am trying to read the <code>HTML</code> contents of a <code>URL</code> with <code>Python</code>. To fetch the <code>HTML</code> contents of a <code>URL</code>, would I use the module <code>wget</code>, <code>urllib</code> or a different module entirely? </p>
<p>After Answers:
I will use the <code>urllib</code> m... | -1 | 2016-10-04T16:48:58Z | 39,857,894 | <p>Here is a sample to get you started with <a href="http://docs.python-requests.org/en/master/" rel="nofollow"><code>requests</code></a>:</p>
<pre><code>import requests
resp = requests.get('http://httpbin.org/get')
if resp.ok:
print (resp.text)
else:
print ("Boo! {}".format(resp.status_code))
print (resp... | 2 | 2016-10-04T16:57:42Z | [
"python",
"html",
"url"
] |
use asyncio update some data timely and present via aiohttp? | 39,857,796 | <p>I am in trying to write a snippet to study Python asyncio. The basic idea is:</p>
<ol>
<li><p>use a "simple" web server (aiohttp) to present some data to user </p></li>
<li><p>the data return to user will change promptly</p></li>
</ol>
<p>here is the code:</p>
<pre><code>import asyncio
import random
from aiohtt... | 2 | 2016-10-04T16:51:40Z | 39,859,949 | <p>The main problem is that you forget the statement <code>global userfeed</code> in both <code>data_updater</code> and <code>web_handle</code> functions. So, according to <a href="http://stackoverflow.com/a/292502/5050917">how python resolves scopes</a>, in <code>web_handle</code> it was referring to the global variab... | 1 | 2016-10-04T19:08:17Z | [
"python",
"python-asyncio",
"aiohttp"
] |
how to pass elements in a list to a function in a for-loop | 39,857,807 | <p>I'm trying to print the pressure of each city. </p>
<p>Instead of using the cities in the list, it is returning the pressure of a city called 'city'. </p>
<p>Super new to this and can't find an answer to something this specific. thanks!!!!!!</p>
<pre><code>import pyowm
owm = pyowm.OWM('eb68e3b0c908251771e67882d... | 0 | 2016-10-04T16:52:19Z | 39,857,939 | <p>Use better names and things will become clearer:</p>
<pre><code>import pyowm
owm = pyowm.OWM('eb68e3b0c908251771e67882d7a8ddff')
cities = ["tokyo", "jakarta"]
for city in cities:
weather = owm.weather_at_place(city).get_weather()
print (weather.get_pressure()['press'])
</code></pre>
<p>Changes and ration... | 2 | 2016-10-04T17:00:39Z | [
"python",
"for-loop"
] |
how to pass elements in a list to a function in a for-loop | 39,857,807 | <p>I'm trying to print the pressure of each city. </p>
<p>Instead of using the cities in the list, it is returning the pressure of a city called 'city'. </p>
<p>Super new to this and can't find an answer to something this specific. thanks!!!!!!</p>
<pre><code>import pyowm
owm = pyowm.OWM('eb68e3b0c908251771e67882d... | 0 | 2016-10-04T16:52:19Z | 39,858,097 | <p>Hanley, I hope you don't mind I rewrote your code.</p>
<pre><code>import pyowm
owm = pyowm.OWM('eb68e3b0c908251771e67882d7a8ddff')
cities = ["tokyo", "jakarta"]
for city in cities:
city_weather = owm.weather_at_place(city)
weather = city_weather.get_weather()
print(weather.get_pressure()['press'])
</c... | 0 | 2016-10-04T17:11:06Z | [
"python",
"for-loop"
] |
Combine multiple json merging duplicates and adding values for a specific key in python | 39,857,854 | <p>I've looked around for a method to do this, but I can only find bits and pieces and keep getting stuck.
I want to add two sets of json, retaining all properties but adding the <code>total</code> value if a duplicate <code>owner</code> value exists.</p>
<pre><code>json1 = [{"total":101,"owner":"User1","type":8,"team... | 0 | 2016-10-04T16:54:49Z | 39,859,286 | <p>Try this, although this wont be the best solution.</p>
<pre><code>def merge_json(json1, json2):
data = {}
for val in json1+json2:
key = val["owner"]
if key in data:
data[key]['total'] = data[key]['total']+val['total']
else:
data[key] = val
return list(data... | 0 | 2016-10-04T18:25:52Z | [
"python",
"json",
"merge"
] |
Get Deferred from dbpool.runQuery instead of data with Twisted and Oracle | 39,857,898 | <p>I am trying to get some data from Oracle, using Twisted and runQuery and keep getting Deferred instead of actual data.
How can this be solved?
Some code (I excluded some unnecessary parts, but the idea should be clear):</p>
<pre><code>from twisted.enterprise import adbapi
from twisted.internet import defer
import s... | 0 | 2016-10-04T16:57:56Z | 39,862,455 | <p>You get a Deferred because you're calling an <code>inlineCallback</code> which always returns a Deferred. You're also misinterpreting what <code>yield</code> does. It doesn't actually return a value from an <code>inlinceCallback</code> it just wait's for a result. Use <code>defer.returnValue()</code> to return a val... | 0 | 2016-10-04T22:02:06Z | [
"python",
"oracle",
"twisted",
"deferred"
] |
Applying a function to a DataFrame column returns NoneType | 39,857,949 | <p>I have a DataFrame with source IP addresses and I want to check if they belong to a documented CIDR range. </p>
<pre><code>netflow_df2["sip"].head(10)
timestamp
2016-10-04 16:24:58 40.101.X.X
2016-10-04 16:24:58 40.101.X.X
2016-10-04 16:24:58 40.101.X.X
2016-10-04 16:24:58 67.X.X.X
2016-10-04 16:24:5... | 0 | 2016-10-04T17:01:21Z | 39,860,011 | <p>The problem is that I use the <code>defaultdict</code> in the <code>netmap</code> function wrong. This yields the corrects results:</p>
<pre><code>def netmap(ip, network_lookup_dict):
for key, value in network_lookup_dict.iteritems():
try:
if ipaddress.ip_address(unicode(ip)) in ipaddress.i... | 0 | 2016-10-04T19:11:31Z | [
"python",
"pandas",
"networking"
] |
OAuth and redirect_uri in offline Python script | 39,858,027 | <p>I'm currently trying to write a Python script that will use Deviantart's API to automatically shuffle my favourites. To do that I need to first log in in my script. Deviantart uses OAuth2 authentication, which requires a redirect_uri, which as I understand it is supposed to be the server where my application is runn... | 0 | 2016-10-04T17:06:00Z | 39,858,388 | <p>You are supposed to get authorization token using received code. This token will be used to access DeviantArt afterwards. </p>
<p>Refer to <a href="https://www.deviantart.com/developers/authentication" rel="nofollow">https://www.deviantart.com/developers/authentication</a> (section "Using The Authorization Code Gra... | 1 | 2016-10-04T17:29:50Z | [
"python",
"oauth",
"oauth-2.0",
"deviantart-api"
] |
OAuth and redirect_uri in offline Python script | 39,858,027 | <p>I'm currently trying to write a Python script that will use Deviantart's API to automatically shuffle my favourites. To do that I need to first log in in my script. Deviantart uses OAuth2 authentication, which requires a redirect_uri, which as I understand it is supposed to be the server where my application is runn... | 0 | 2016-10-04T17:06:00Z | 39,865,646 | <p>If your application is offline, you cannot use the Authorization Code nor the Implicit grant type: both flows require a redirection URI. </p>
<p>As your python script cannot be reached from the Internet and because Deviantart does not allow the use of another grant type (except Client Credentials, but not relevant ... | 1 | 2016-10-05T04:50:25Z | [
"python",
"oauth",
"oauth-2.0",
"deviantart-api"
] |
Why am I getting an infinite for loop? | 39,858,118 | <p>For this python problem I am taking in one argument an int, this is the max length of a list I am going to be appending to. Starting with an int value of 1, I want to iterate through the list appending two more linear values until the max length is reached. </p>
<p>I am getting an infinite loop or something similar... | 0 | 2016-10-04T17:12:15Z | 39,858,313 | <p>You are adding to the list as you loop over it. A list iterator simply increments a position counter and returns the value at that index until the index doesn't exist. It doesn't keep track of the length of the list up-front. In your case, by adding more elements to the end, the iterator never reaches an index that ... | 1 | 2016-10-04T17:25:10Z | [
"python",
"loops"
] |
Python multiprocessing dies in the middle | 39,858,119 | <p>I run a <code>python</code> program on <strong>CentOS VPS Server</strong>. I am running this program for last few months & I am facing this problem from the beginning. </p>
<p>I usually run this python program from crontab. The program does the following things everyday sequentially. </p>
<ol>
<li>Connect to a... | 0 | 2016-10-04T17:12:17Z | 39,858,860 | <p>I have also faced the same problem. After doing a lot of research I concluded, Firefox is not good option for multiprocessing. Better use <strong>PhantomJS</strong> or <strong>Chrome Driver</strong>. In my case when I was saw ps or top, I was getting Zombie Firefox process. </p>
| 0 | 2016-10-04T17:58:43Z | [
"python",
"linux",
"selenium",
"firefox",
"multiprocessing"
] |
I need help making a triangle that generates using user input by making the user enter the number of rows | 39,858,146 | <p>It should look like this but reversed and the first column indented</p>
<pre><code>OOOOOOO
OOOOOO
OOOOO
OOOO
OOO
OO
O
</code></pre>
<p>Every time I attempt to do it I always get this code iteration and I don't know where I am going wrong.</p>
<p>Here is what I got so far</p>
<pre... | -1 | 2016-10-04T17:13:57Z | 39,858,297 | <p>You can do in this way:</p>
<pre><code>line = int(input('Please enter how many lines you want: '))
vec = [i for i in range(1,line+1)]
for elem in vec: print("\t"+"O"*elem)
</code></pre>
<p>Output example:</p>
<p><a href="http://i.stack.imgur.com/l1Vx6.png" rel="nofollow"><img src="http://i.stack.imgur.com/l1Vx6.... | 1 | 2016-10-04T17:24:26Z | [
"python",
"for-loop",
"nested-loops"
] |
I need help making a triangle that generates using user input by making the user enter the number of rows | 39,858,146 | <p>It should look like this but reversed and the first column indented</p>
<pre><code>OOOOOOO
OOOOOO
OOOOO
OOOO
OOO
OO
O
</code></pre>
<p>Every time I attempt to do it I always get this code iteration and I don't know where I am going wrong.</p>
<p>Here is what I got so far</p>
<pre... | -1 | 2016-10-04T17:13:57Z | 39,858,328 | <pre><code>line = int(input('number of lines'))
for i in range(1, line + 1):
a = 'O' * ((line + 1) - i)
b = " "*(i)
print(b + a)
</code></pre>
<p>I don't understand what 'first column indented' means but this posts what you want I believe. </p>
<p>for <code>line = 5</code>
this prints </p>
<pre><code> ... | 0 | 2016-10-04T17:26:01Z | [
"python",
"for-loop",
"nested-loops"
] |
I need help making a triangle that generates using user input by making the user enter the number of rows | 39,858,146 | <p>It should look like this but reversed and the first column indented</p>
<pre><code>OOOOOOO
OOOOOO
OOOOO
OOOO
OOO
OO
O
</code></pre>
<p>Every time I attempt to do it I always get this code iteration and I don't know where I am going wrong.</p>
<p>Here is what I got so far</p>
<pre... | -1 | 2016-10-04T17:13:57Z | 39,858,390 | <p>Well here goes my version of the solution</p>
<pre><code>line = int(raw_input('Please enter how many lines you want: '))
k=''
for r in range(line):
k=k+'0'
for r in range(line):
print k
k=k[0:len(k)-1]
k=' '+k
</code></pre>
<p>The terminal output looks like this</p>
<pre><code>Please enter how man... | 0 | 2016-10-04T17:29:52Z | [
"python",
"for-loop",
"nested-loops"
] |
Basic Python function | 39,858,150 | <p>I am trying to complete two different questions but cannot get them to work. Please help me understand where I went wrong.</p>
<p>1) For each number between 1 and 100, odds should be normal and even numbers should print out the word "Billy". Must start at 1 not 0 and include the number 100. Here's my answer (I know... | -2 | 2016-10-04T17:14:14Z | 39,858,177 | <p>try this</p>
<pre><code>for i in range(1,101):
if i % 2 == 0:
print('Billy') #you missed quote marks here
else:
print(i)
</code></pre>
<p>(bad indentation, and missing quote marks)</p>
<p>and </p>
<pre><code>name = input("What is your name?")
if name == "Joe":
print("Hi Joe :)")
eli... | 0 | 2016-10-04T17:16:30Z | [
"python"
] |
TypeError: Expected bytes in Flask app | 39,858,161 | <p>I am trying to implement a simple flask app which will pass a json file to the front end, but got an error as following:</p>
<pre><code>> 127.0.0.1 - - [04/Oct/2016 17:53:02] "GET /test HTTP/1.1" 500 - Traceback (most recent call last): File
> "/Users/michelleshieh/anaconda2/lib/python2.7/site-packages/flas... | 0 | 2016-10-04T17:14:58Z | 39,858,612 | <p>You are returning a Python object other than a <code>bytes</code> object here:</p>
<pre><code>return app.response_class(data, content_type='application/json')
</code></pre>
<p>That's not a JSON response, that's an <em>unencoded</em> Python list or dictionary.</p>
<p>Just return the JSON data <em>without</em> deco... | 0 | 2016-10-04T17:42:44Z | [
"python",
"json",
"flask"
] |
Do statement not working in jinja | 39,858,191 | <p>I'm altering an existing web interface to view ROBOT doc libraries, which uses a mixture of jinja (Python inside HTML) and HTML. I have never worked with jinja or HTML before and am having issues getting even a simple test case to work. When the browser loads the docs, I want our project's directory structure for th... | 1 | 2016-10-04T17:17:38Z | 39,858,522 | <p>From the <a href="http://jinja.pocoo.org/docs/dev/templates/#expression-statement" rel="nofollow">template documentation</a>:</p>
<blockquote>
<h3>Expression Statement</h3>
<p>If the expression-statement extension is loaded, a tag called <code>do</code> is available that works exactly like the regular variab... | 0 | 2016-10-04T17:38:10Z | [
"python",
"html",
"jinja2"
] |
Python 3.5: NLTK Download Default URL will not change | 39,858,195 | <p>I've updated the DEFAULT_URL in downloader.py and I'm still getting the following error. I originally tried just nltk.downloader() and the file browser updated but when I tried to download, it still reverted back to the github site.</p>
<pre><code>DEFAULT_URL = 'http://nltk.org/nltk_data/'
</code></pre>
<p>.</p>
... | 0 | 2016-10-04T17:17:57Z | 39,875,376 | <p>The problem comes from your proxy. I can't say what's wrong with your proxy configuration, but initializing a downloader with a custom download url works as intended (there is no need to modify the nltk source in <code>nltk/downloader.py</code>):</p>
<pre><code>dl = nltk.downloader.Downloader("http://example.com/my... | 1 | 2016-10-05T13:30:51Z | [
"python",
"nltk"
] |
Python Sounddevice.play() on Threads | 39,858,212 | <p>I am having some problems to play the sounddevice on a Thread. I import the sounddevice as sd at the beginning. Then during running I want to play a tone on a thread using the ASIO sound card. All the configurations I need to do on the thread works well. However, when I want to play the tone I got the following Erro... | 0 | 2016-10-04T17:18:52Z | 40,045,505 | <p>This seems to be a platform-specific problem. I just tried it with ALSA/Linux and it works fine. With ASIO, you probably have to do the library initialization (which happens during <code>import</code> time) in the same thread you are using later to create the stream (which <code>play()</code> does for you)?</p>
<bl... | 0 | 2016-10-14T14:21:10Z | [
"python",
"multithreading",
"python-sounddevice"
] |
How can i save RDD to a single parquet file? | 39,858,238 | <p>I work with pyspark 2.0, hadoop 2.7.2.
And here is my code:</p>
<pre><code>def func(df):
new_df = pd.DataFrame(df['id'])
new_df['num'] = new_df['num'] * 12
return new_df
set = sqlContext.read.parquet("data_set.parquet")
columns = set.columns
map_res = set.rdd.mapPartitions(lambda iter_: func(pd.DataFra... | 2 | 2016-10-04T17:20:43Z | 39,859,509 | <p>There are only 2 ways to do this: </p>
<p>One is use <code>"coalesce(1)"</code>
This will make sure that all the data is saved into 1 file rather than multiple files (200 is the spark default no of partitions) use <code>dataframe.write.save("/this/is/path")</code>. </p>
<p>The other option is write the output to a... | 0 | 2016-10-04T18:40:42Z | [
"python",
"hadoop",
"apache-spark",
"pyspark",
"rdd"
] |
How can i save RDD to a single parquet file? | 39,858,238 | <p>I work with pyspark 2.0, hadoop 2.7.2.
And here is my code:</p>
<pre><code>def func(df):
new_df = pd.DataFrame(df['id'])
new_df['num'] = new_df['num'] * 12
return new_df
set = sqlContext.read.parquet("data_set.parquet")
columns = set.columns
map_res = set.rdd.mapPartitions(lambda iter_: func(pd.DataFra... | 2 | 2016-10-04T17:20:43Z | 39,876,160 | <p>I suggest this:</p>
<pre><code>dataframes = []
#creating index
map_res = map_res.zipWithIndex()
# setting index as key
map_res = map_res.map(lambda x: (x[1],x[0]))
# creating one spark df per element
for i in range(0, map_res.count()):
partial_dataframe_pd = map_res.lookup(i)
partial_dataframe = sqlContext... | 1 | 2016-10-05T14:05:33Z | [
"python",
"hadoop",
"apache-spark",
"pyspark",
"rdd"
] |
Multiple functions on class-based views flask | 39,858,256 | <p>maybe I'm misunderstanding class-based views on Flask. I come from a PHP/Laravel background. On Laravel I can define a controller class where I can response different json data, views (templates on Flask), etc. So the only thing I do is define a route and associate that route to a specific method on a controller cla... | 1 | 2016-10-04T17:22:12Z | 39,859,447 | <p>Based on my laravel/flask project experience, the classy code of controller/view are same. You can try <a href="https://github.com/apiguy/flask-classy" rel="nofollow">flask-classy</a> extension</p>
<p>Below is an example based on <code>flask-classy</code>.</p>
<p><strong>Directory</strong></p>
<pre><code>.
ââ... | 1 | 2016-10-04T18:36:24Z | [
"python",
"flask"
] |
Fail to map the output of a generator to a function in multiprocessing with python-2.7 | 39,858,279 | <p>Here is my code:</p>
<pre><code>from multiprocessing import Pool
user_list = [1, 2, 3, 4, 5]
def gen_pair():
for u1 in reversed(user_list):
for u2 in reversed(list(range(1, u1))):
yield (u1, u2)
def cal_sim(u_pair):
u1, u2 = u_pair
sim = sim_f(df[u1], df[u2])
return sim
poo... | 1 | 2016-10-04T17:23:26Z | 39,860,909 | <p>You have an infinite recursion here:</p>
<pre><code>def cal_sim(u_pair):
u1, u2 = u_pair
sim = cal_sim(df[u1], df[u2])
return sim
</code></pre>
<p>Because <code>cal_sim</code> calls <code>cal_sim</code> without any end condition.</p>
<p>There is also a problem with the parameters, because <code>cal_si... | 0 | 2016-10-04T20:07:45Z | [
"python",
"python-2.7",
"multiprocessing"
] |
Narcissistic number | 39,858,316 | <p>Today I saw an interesting task. To make a program which outputs all "narcissistic numbers" (all digits are raised to the power of 3). My program has this code</p>
<pre><code>for number in range(1, 408):
result = 0
for digit in str(number):
result += int(digit) ** 3
if result == number:
... | 0 | 2016-10-04T17:25:19Z | 39,858,359 | <p>You're checking whether <code>result==number</code> after each digit in the number. You probably want this check in the outer <code>for</code> loop. As it is, it sees that 370 = 3**3 + 7**3, but it is also 3**3 + 7**3 + 0**3, so it's printed on both of those iterations.</p>
| 0 | 2016-10-04T17:28:07Z | [
"python",
"python-3.x"
] |
Narcissistic number | 39,858,316 | <p>Today I saw an interesting task. To make a program which outputs all "narcissistic numbers" (all digits are raised to the power of 3). My program has this code</p>
<pre><code>for number in range(1, 408):
result = 0
for digit in str(number):
result += int(digit) ** 3
if result == number:
... | 0 | 2016-10-04T17:25:19Z | 39,858,420 | <p>You should unindent the last <code>if</code> statement, which runs after each digit:</p>
<pre><code>for number in range(1, 408):
result = 0
for digit in str(number):
result += int(digit) ** 3
if result == number:
print(number)
</code></pre>
<p>As another answer notes, this can give you ... | 0 | 2016-10-04T17:31:12Z | [
"python",
"python-3.x"
] |
Test variables INSIDE a view function - no return | 39,858,344 | <p>I'm new to Django + Python so I'm not sure how much of this question will make sense.</p>
<p>Basically, I'm working on a project (not created by me) that has a function within a views.py file. The purpose of this view function is not to give a HTTP response but to send an email. </p>
<p>It accepts a request as a p... | 0 | 2016-10-04T17:26:55Z | 39,858,583 | <p>One way to approach this would be to make your own fake version of <code>send_email_template()</code> that does nothing except verify that it was called with the desired argument values, and raises an exception if they are wrong.</p>
<p>Then, in your test setup, you would <em>replace</em> the real <code>send_email_... | 1 | 2016-10-04T17:41:22Z | [
"python",
"django",
"testing"
] |
Stored salted token and token comparison | 39,858,364 | <p>I'm generating an url composed of a single use token, and sending it to a user by e-mail. The user should click this link and be redirected to a page which will validate the token and do some actions. </p>
<p>On the database side, I'm storing this token (hashed and salted, for security reasons). The problem is I'm ... | 2 | 2016-10-04T17:28:12Z | 39,859,024 | <p>Using a simple string equality check of two hashed and salted tokens will not work. The <a href="https://docs.djangoproject.com/en/1.10/topics/auth/passwords/#django.contrib.auth.hashers.check_password" rel="nofollow">Django docs for password management</a> offer a very simple method in the <code>django.contrib.auth... | 1 | 2016-10-04T18:08:30Z | [
"python",
"django"
] |
Python data display with graph | 39,858,501 | <p>I am just dipping my toes into Python and have had help on here to get a live updating Matplotlib graph to work for me. This program uses animation to pull data from a dynamically growing CSV file with data that looks like the following:</p>
<pre><code>TimeStamp, ReadCount, Antenna, Protocol, RSSI, EPC, Sensor
09/2... | 1 | 2016-10-04T17:36:30Z | 39,859,405 | <p>To get you started, there are probably some questions to be answered first.</p>
<ol>
<li>How live is live? Should it update in real time? In this case the use of <code>FuncAnimation</code> is probably a bad idea. <em>Answer: yes, real time</em></li>
<li>How fast does it have to be, that is, how many updates per sec... | 2 | 2016-10-04T18:33:55Z | [
"python",
"matplotlib"
] |
How to handle NA values when tokenizing the contents of a data frame? | 39,858,543 | <p>I have a pandas dataframe and I am trying to tokenize the contents of each row. </p>
<pre><code>import pandas as pd
import nltk as nk
from nltk import word_tokenize
TextData = pd.read_csv('TextData.csv')
TextData['tokenized_summary'] = TextData.apply(lambda row: nk.word_tokenize(row['Summary']), axis=1)
</code></p... | 0 | 2016-10-04T17:39:10Z | 39,858,706 | <p>You can use <code>fillna()</code> to replace NaN with a specified value:</p>
<pre><code>import pandas as pd
import nltk as nk
from nltk import word_tokenize
TextData = pd.read_csv('TextData.csv')
TextData.fillna('some value') # or just: TextData['Summary'].fillna('some value')
TextData['tokenized_summary'] = TextD... | 1 | 2016-10-04T17:48:44Z | [
"python",
"pandas",
"nltk"
] |
convert a text data to csv python | 39,858,622 | <p>I have a long text file where i was able to extract these lines by grabing just the ones that contain the word "Average":</p>
<pre><code>Average time per layer:
Average Forward pass: 4013.65 ms.
Average Backward pass: 7425.13 ms.
Average Forward-Backward: 11480.2 ms.
</code></pre>
<p>Here is what I need in a csv f... | 0 | 2016-10-04T17:43:39Z | 39,858,711 | <p>You can use a <a href="https://www.regex101.com/r/O4njRs/1" rel="nofollow">regex</a> on data like this:</p>
<pre><code>txt='''\
Average time per layer:
Average Forward pass: 4013.65 ms.
Average Backward pass: 7425.13 ms.
Average Forward-Backward: 11480.2 ms.'''
import re
for k,v in re.findall(r'^([^:]+):\s*(\d+\.... | 0 | 2016-10-04T17:49:01Z | [
"python",
"csv"
] |
convert a text data to csv python | 39,858,622 | <p>I have a long text file where i was able to extract these lines by grabing just the ones that contain the word "Average":</p>
<pre><code>Average time per layer:
Average Forward pass: 4013.65 ms.
Average Backward pass: 7425.13 ms.
Average Forward-Backward: 11480.2 ms.
</code></pre>
<p>Here is what I need in a csv f... | 0 | 2016-10-04T17:43:39Z | 39,858,880 | <p>It would help to show us what output you are getting versus what you expect. However it looks to me like you are writing <code>str(entry)</code> to a file, where <code>entry</code> is a dict, and expecting it to render as a csv line. I suspect it will look a little more similar to one JSON object per line.</p>
<p>W... | 0 | 2016-10-04T17:59:47Z | [
"python",
"csv"
] |
What tool or algorithm should I use to generate words from a keyword which is at a given DamerauâLevenshtein distance? | 39,858,659 | <p>Damerau-Levenshtein distance is like:</p>
<pre><code>"abcd", "aacd" => 1 DL distance
"abcd", "aadc" => 2 DL distance
</code></pre>
<ul>
<li>More about editdistance: <a href="https://pypi.python.org/pypi/editdistance" rel="nofollow">https://pypi.python.org/pypi/editdistance</a></li>
<li>More about Damerau-Lev... | 0 | 2016-10-04T17:45:49Z | 39,858,843 | <p>Look at this Norvig's article: <a href="http://norvig.com/spell-correct.html" rel="nofollow">How to Write a Spelling Corrector</a>.</p>
<p>It contains the exact code that you need:</p>
<pre><code>def edits1(word):
"All edits that are one edit away from `word`."
letters = 'abcdefghijklmnopqrstuvwxyz'
... | 2 | 2016-10-04T17:58:04Z | [
"python",
"edit-distance"
] |
Python 3.5.1 - Much needed advice with a year old piece of code | 39,858,707 | <p>I've been trying to create a turn-based RPG using what meager knowledge of Python I have scince early 2015, but I abandoned the project because of a problem with this piece of code:</p>
<pre><code>pattack=""
pnote=""
pdmg=0
ppriority=0
selectmove=int(input("Select move number 1-4"))
if selectmove==1:
pattack=... | -2 | 2016-10-04T17:48:44Z | 39,858,772 | <pre><code>print(int("Used the move "+pattack+"\nDealt "+str(pdmg)+" Damage\nHas a priority of "+str(ppriority)+"\nMove description: *NOT FINAL*\n"+pnote+" "))
</code></pre>
<p>That line should be:</p>
<pre><code>print("Used the move "+pattack+"\nDealt "+str(pdmg)+" Damage\nHas a priority of "+str(ppriority)+"\nMove ... | 1 | 2016-10-04T17:52:20Z | [
"python",
"python-3.x"
] |
Python 3.5.1 - Much needed advice with a year old piece of code | 39,858,707 | <p>I've been trying to create a turn-based RPG using what meager knowledge of Python I have scince early 2015, but I abandoned the project because of a problem with this piece of code:</p>
<pre><code>pattack=""
pnote=""
pdmg=0
ppriority=0
selectmove=int(input("Select move number 1-4"))
if selectmove==1:
pattack=... | -2 | 2016-10-04T17:48:44Z | 39,858,883 | <p>In your last <code>print</code> line, you don't need the <code>int()</code> call: it's only used to convert a value into an integer, which that string is not.</p>
| 0 | 2016-10-04T18:00:04Z | [
"python",
"python-3.x"
] |
incorrect http protocol shown by chrome developer tools? | 39,858,729 | <p>I am checking the http protcol in use for this site <a href="http://www.dlf.in/" rel="nofollow">http://www.dlf.in/</a>
Chrome developer tools shows it to be http/1.1 as in the image below.</p>
<p>However the command line tool <a href="https://www.npmjs.com/package/is-http2-cli" rel="nofollow">is-http2</a> or alpn i... | 0 | 2016-10-04T17:50:05Z | 39,859,241 | <p>That site doesn't have HTTPS on it. Browsers only support HTTP/2 over HTTPS despite the spec allowing it over HTTP in theory.</p>
| 0 | 2016-10-04T18:22:41Z | [
"python",
"google-chrome",
"http2",
"http-1.1",
"alpn"
] |
incorrect http protocol shown by chrome developer tools? | 39,858,729 | <p>I am checking the http protcol in use for this site <a href="http://www.dlf.in/" rel="nofollow">http://www.dlf.in/</a>
Chrome developer tools shows it to be http/1.1 as in the image below.</p>
<p>However the command line tool <a href="https://www.npmjs.com/package/is-http2-cli" rel="nofollow">is-http2</a> or alpn i... | 0 | 2016-10-04T17:50:05Z | 39,859,372 | <p>Using <code>telnet</code> and <code>HTTPie</code> to send HTTP requests (both 1.0 and 1.1), the web server responds with:</p>
<blockquote>
<p>HTTP/1.1 200 OK</p>
</blockquote>
<p>I tried it with 2.0 and got:</p>
<blockquote>
<p>HTTP/1.1 505 HTTP Version Not Supported</p>
</blockquote>
| 0 | 2016-10-04T18:31:26Z | [
"python",
"google-chrome",
"http2",
"http-1.1",
"alpn"
] |
Stopwatch implementing python | 39,858,802 | <p>I got this code for an assignment:</p>
<pre><code>from stop_watch import StopWatch
size = 1000000
stopWatch = StopWatch()
sum = 0
for i in range(1, size + 1):
sum += i
stopWatch.stop()
print("The loop time is", stopWatch.get_elapsed_time(), "milliseconds")
</code></pre>
<p>I have to create a class which gener... | 0 | 2016-10-04T17:54:39Z | 39,858,851 | <p>You can't name your functions and your properties the same thing. When you do <code>self.stop = time.time()</code>, you overwrite the function <code>stop</code>.</p>
<p>You need to change the name of the internal fields.</p>
<pre><code>import time
class StopWatch:
def __init__(self):
self.start_time =... | 5 | 2016-10-04T17:58:24Z | [
"python",
"python-3.x"
] |
scipy.io.loadmat returns MemoryError for big matlab structures | 39,858,857 | <p>I want to open and process some big .mat files in python. The scipy.io.loadmat function is perfect for that purpose. However, the function returns MemoryError when the .mat files are big. The problem might be due to the python version I use (Python 2.7.10 32 bits, interfaced with spyder). This problem has already be... | 0 | 2016-10-04T17:58:32Z | 39,858,926 | <p>See the documentation here: <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.io.loadmat.html" rel="nofollow">http://docs.scipy.org/doc/scipy/reference/generated/scipy.io.loadmat.html</a></p>
<p>You can pass a list of variable names to read from the file:</p>
<pre><code>scipy.io.loadmat("myfile.ma... | 2 | 2016-10-04T18:02:38Z | [
"python",
"matlab",
"scipy",
"32-bit"
] |
Run build for C++ code (make) in Python script | 39,858,958 | <p>I keep running into an error when I want to compile code written in C++ using Python script to run "make" in x directory. Compiling the code takes about few seconds so I am using time module to have the script sleep for 60 seconds to finish compiling the code.</p>
<p><strong>Here is the code:</strong></p>
<pre><co... | 0 | 2016-10-04T18:04:45Z | 39,859,223 | <p>I actually figured it out and able to run the build process by using the following code:</p>
<pre><code>import subprocess
from time import sleep
def make_ut_adsmain():
subprocess.Popen(["make"], stdout=subprocess.PIPE, cwd="../../ads/main/unitest")
sleep(60)
make_ut_adsmain()
</code></pre>
<p>Note... | 1 | 2016-10-04T18:21:03Z | [
"python",
"c++",
"shell",
"scripting"
] |
create panda dataframe and append values in for loop | 39,858,961 | <p>I have a list from which I would like to iterate over and create tuples in a pandas dataframe in order to imitate sliding window of size 4. What I am trying to do is:</p>
<pre><code>tuples = pd.DataFrame()
for index, row in expertsDF.iterrows():
newlst = row['name']
counter = 0
for x in newlst:
... | 1 | 2016-10-04T18:05:03Z | 39,860,977 | <p>Is this close?</p>
<pre><code>import pandas as pd
tuples = pd.DataFrame(columns=['A', 'B', 'C', 'D'])
newlst = "abcdefg"
i = 0
for x in newlst:
if i < len(newlst) - 3:
t = pd.DataFrame([[x, newlst[i + 1], newlst[i + 2], newlst[i + 3]]],
columns=['A', 'B', 'C', 'D'])
tuple... | 1 | 2016-10-04T20:13:38Z | [
"python",
"list",
"dataframe",
"append"
] |
create panda dataframe and append values in for loop | 39,858,961 | <p>I have a list from which I would like to iterate over and create tuples in a pandas dataframe in order to imitate sliding window of size 4. What I am trying to do is:</p>
<pre><code>tuples = pd.DataFrame()
for index, row in expertsDF.iterrows():
newlst = row['name']
counter = 0
for x in newlst:
... | 1 | 2016-10-04T18:05:03Z | 39,861,302 | <p>How about creating the DataFrame from Series objects?</p>
<pre><code>import pandas as pd
data_list = list(map(lambda x: 'var{}'.format(x),range(0,100)))
df = pd.Series(data_list[0:97]).to_frame(name='A')
df['B'] = pd.Series(data_list[1:98])
df['C'] = pd.Series(data_list[2:99])
df['D'] = pd.Series(data_list[3:100])... | 1 | 2016-10-04T20:36:02Z | [
"python",
"list",
"dataframe",
"append"
] |
Time Comparison Multithreading | 39,859,010 | <p>I have a program that reads some input text files and write all of them into one separate file. I used two threads so it runs faster!
I tried the following python code with both one thread and two threads! Why when I run with one thread it runs faster than when I run it with two threads?</p>
<p><div class="snippet"... | 0 | 2016-10-04T18:07:19Z | 39,859,832 | <p>You have several problems I'll get to in a moment, but generally your program is disk-bound (it can't go faster than your hard drive) so even a properly threaded program isn't any faster. It can be hard to measure disk performance because of the file system cache: You run this once with threads and you go at hard dr... | 0 | 2016-10-04T18:59:55Z | [
"python",
"multithreading"
] |
Matrix in python with a set column | 39,859,062 | <p>So I'm trying to make a 2x3 matrix with the output </p>
<pre><code> >>>l([1980, 1981, 1982])
>>>[[1., 1980], [1., 1981], [1.,1982]]
</code></pre>
<p>However the output I'm getting is:</p>
<pre><code> >>>l([1980, 1981, 1982])
>>>[1.0, [1980, 1981, 1982]]
</code></p... | 0 | 2016-10-04T18:11:16Z | 39,859,106 | <p>Here's a nice way to do it with a list comprehension:</p>
<pre><code>def l(x):
return [[1., e] for e in x]
</code></pre>
| 4 | 2016-10-04T18:13:59Z | [
"python",
"list",
"matrix"
] |
Matrix in python with a set column | 39,859,062 | <p>So I'm trying to make a 2x3 matrix with the output </p>
<pre><code> >>>l([1980, 1981, 1982])
>>>[[1., 1980], [1., 1981], [1.,1982]]
</code></pre>
<p>However the output I'm getting is:</p>
<pre><code> >>>l([1980, 1981, 1982])
>>>[1.0, [1980, 1981, 1982]]
</code></p... | 0 | 2016-10-04T18:11:16Z | 39,859,107 | <p>What you want is </p>
<pre><code>def l(x):
xl = []
for i in range(len(x)):
xl.append([1., x[i]])
return xl
</code></pre>
<p>Or, since there is no need to use the index <code>i</code> for anything other than indexing the elements of <code>x</code>, you can use:</p>
<pre><code>def l(x):
... | 1 | 2016-10-04T18:14:07Z | [
"python",
"list",
"matrix"
] |
Matrix in python with a set column | 39,859,062 | <p>So I'm trying to make a 2x3 matrix with the output </p>
<pre><code> >>>l([1980, 1981, 1982])
>>>[[1., 1980], [1., 1981], [1.,1982]]
</code></pre>
<p>However the output I'm getting is:</p>
<pre><code> >>>l([1980, 1981, 1982])
>>>[1.0, [1980, 1981, 1982]]
</code></p... | 0 | 2016-10-04T18:11:16Z | 39,859,184 | <p>You can use <code>map</code> also:</p>
<pre><code>>>> li=[1980, 1981, 1982]
>>> map(lambda e: [1.0]+[e], li)
[[1.0, 1980], [1.0, 1981], [1.0, 1982]]
</code></pre>
<p>Or, if you don't mind a list of tuples:</p>
<pre><code>>>> zip((1.0,)*len(li),li)
[(1.0, 1980), (1.0, 1981), (1.0, 1982)]... | 0 | 2016-10-04T18:19:08Z | [
"python",
"list",
"matrix"
] |
Directories - Why is this erroring out? | 39,859,092 | <p>I am building a few directories for a program I am working on, but they keep erroring out when used within the game and without of it. Each line throws out the same error (<code>Syntax Error: invalid syntax</code>) and I am wondering why. The lines are:</p>
<pre><code>secretpassageunearthed = 'No'
pickedup = {'broo... | 0 | 2016-10-04T18:13:14Z | 39,859,146 | <p>You can't use <code>=</code> to assign in a dictionary</p>
<p>Change <code>=</code> to <code>:</code> and this should work:</p>
<pre><code>secretpassageunearthed = 'No'
pickedup = {'broom': '0', 'rope': '0', 'torch': '0', 'coffin': '0', 'skeleton' : '0', 'key2': '0', 'rock': '0', 'key1': '0', 'mailbox': '0', 'inst... | 0 | 2016-10-04T18:16:52Z | [
"python",
"directory",
"adventure"
] |
Directories - Why is this erroring out? | 39,859,092 | <p>I am building a few directories for a program I am working on, but they keep erroring out when used within the game and without of it. Each line throws out the same error (<code>Syntax Error: invalid syntax</code>) and I am wondering why. The lines are:</p>
<pre><code>secretpassageunearthed = 'No'
pickedup = {'broo... | 0 | 2016-10-04T18:13:14Z | 39,859,238 | <p>As others have said, the problem is that you used <code>=</code> instead of <code>:</code> to assign a dictionary item.</p>
<p>When you saw the error message, you may not have noticed that Python was trying to tell you exactly where the error was:</p>
<pre><code> File "adventure.py", line 1
pickedup = {'coffi... | 0 | 2016-10-04T18:22:24Z | [
"python",
"directory",
"adventure"
] |
Directories - Why is this erroring out? | 39,859,092 | <p>I am building a few directories for a program I am working on, but they keep erroring out when used within the game and without of it. Each line throws out the same error (<code>Syntax Error: invalid syntax</code>) and I am wondering why. The lines are:</p>
<pre><code>secretpassageunearthed = 'No'
pickedup = {'broo... | 0 | 2016-10-04T18:13:14Z | 39,859,265 | <p>The <a href="https://www.python.org/dev/peps/pep-0008/#id19" rel="nofollow">python style guide</a> recommends keeping lines < 72 characters. Personally, I aim for 78. If you do that, your code is easier to read and as a bonus, its easier to spot problems. So for example, if you file was </p>
<pre><code>secretpas... | 0 | 2016-10-04T18:24:54Z | [
"python",
"directory",
"adventure"
] |
Lower the brightness of all RGB pixels by 20% in Python? | 39,859,109 | <p>I have been trying to teach myself more advanced methods in Python but can't seem to find anything similar to this problem to base my code off of. </p>
<p>First question: Is this only way to display an image in the terminal to install Pillow? I would prefer not to, as I'm trying to then teach what I learn to a very... | 0 | 2016-10-04T18:14:17Z | 39,859,171 | <p>To save the image as a file, there's an example on the documentation:</p>
<pre><code>from PIL import ImageFile
fp = open("lena.pgm", "rb")
p = ImageFile.Parser()
while 1:
s = fp.read(1024)
if not s:
break
p.feed(s)
im = p.close()
im.save("copy.jpg")
</code></pre>
<p>The key function is <co... | 0 | 2016-10-04T18:18:29Z | [
"python",
"image"
] |
What pandas function does change the column type in an "inline" manner? | 39,859,118 | <p>I know that the following commands could help change the column type:</p>
<pre><code>df['date'] = str(df['date'])
df['A'] = pd.to_datetime(df['A'])
df['A'] = df.A.astype(np.datetime64)
</code></pre>
<p>But do you know a better way to change the column type in an inline manner to make it in one line following wi... | 1 | 2016-10-04T18:14:59Z | 39,859,167 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.assign.html" rel="nofollow">assign</a>:</p>
<pre><code>df.assign(A=pd.to_datetime(df['A']))
</code></pre>
<hr>
<pre><code>df = pd.DataFrame({'A': ['20150101', '20140702'], 'B': [1, 2]})
df
Out:
A B
0 20150101 ... | 2 | 2016-10-04T18:18:14Z | [
"python",
"pandas"
] |
How to set axis values in matplotlib | 39,859,178 | <p>This is my first attempt to use <code>matplotlib</code> and failing... I have lists of data as:</p>
<p><code>years = [1985, 1986, 1987, 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014]</code> </p>
<p><c... | 0 | 2016-10-04T18:18:46Z | 39,859,695 | <p>Are you sure that you want a histogram and not a simple bar chart? Something like this:</p>
<pre><code>plt.bar(years,temps, 1, color='r')
plt.title('Temp_histogram')
plt.xlabel('year')
plt.ylabel('temp')
plt.grid(True)
plt.show()
</code></pre>
<p><a href="http://i.stack.imgur.com/kJmvp.png" rel="nofollow"><img src... | 1 | 2016-10-04T18:52:34Z | [
"python",
"matplotlib"
] |
Python access to default parameters at init time | 39,859,208 | <p>The first part of my question is how can i access to the pre-set default parameters of a class to use their value as other arguments? What i want to do is something like this:</p>
<pre><code>class C:
def __init__(self, size_hint = (0, 0), **kwargs):
self.size_hint = size_hint
</code></pre>
<p>and then... | -1 | 2016-10-04T18:20:03Z | 39,859,254 | <p>Here's the answer to your first question (use <a href="https://docs.python.org/3/library/inspect.html#inspect.signature" rel="nofollow"><code>inspect.signature</code></a>):</p>
<pre><code>import inspect
class C:
def __init__(self, size_hint = (0, 0), **kwargs):
self.size_hint = size_hint
assert inspe... | 0 | 2016-10-04T18:23:38Z | [
"python",
"class",
"python-3.x",
"kwargs"
] |
How to use HTML5 color picker in Django admin | 39,859,224 | <p>I'm trying to implement the HTML5 colorpicker in Django's admin page.</p>
<p>Here is my model:</p>
<pre><code>#model.py
...
class Category(models.Model):
...
color = models.CharField(max_length=7)
</code></pre>
<p>Here is the form:</p>
<pre><code>#form.py
from django.forms import ModelForm
from django.f... | 1 | 2016-10-04T18:21:26Z | 39,864,918 | <p>I found the answer in the documentation:</p>
<p>The extra class in forms.py was not necessary</p>
<pre><code>#form.py
from django.forms import ModelForm
from django.forms.widgets import TextInput
from .models import Category
class CategoryForm(ModelForm):
class Meta:
model = Category
fields = ... | 1 | 2016-10-05T03:22:06Z | [
"python",
"django",
"html5"
] |
KeyError : APP_SETTINGS | 39,859,234 | <p>I'm getting a <code>KeyError</code>, this is the <code>apache2/error.log</code>:</p>
<pre><code>tail /var/log/apache2/error.log
[Tue Oct 04 18:07:13.305780 2016] [wsgi:error] [pid 15459:tid 140052675933952] [client 174.58.31.189:56852] mod_wsgi (pid=15459): Target WSGI script '/var/www/FlaskApp/flaskapp.wsgi' canno... | 0 | 2016-10-04T18:22:06Z | 39,860,850 | <p>There isn't a way to readily set environment variables in the startup environment for Apache. You would normally set them from the WSGI script file explicitly, or indirectly by having them in some separate file and have the WSGI script file read that and set them for you based on what was set in that separate file. ... | 0 | 2016-10-04T20:04:22Z | [
"python",
"python-3.x",
"flask",
"apache2",
"flask-sqlalchemy"
] |
Receive a shell command as an OptionParser string argument | 39,859,287 | <p>I am using OptionParser(), and define the following:</p>
<pre><code>parser.add_option("--cmd", dest="command", help="command to run")
</code></pre>
<p>However, if i provide a complex shell command, such as :</p>
<pre><code>python shell.py --cmd "for i in `seq 1 10`; do xxx; done"
</code></pre>
<p>And internally ... | 0 | 2016-10-04T18:25:56Z | 39,859,517 | <p>When invoking:</p>
<pre><code>python shell.py --cmd "for i in `seq 1 10`; do xxx; done"
</code></pre>
<p>The shell first substitute the command enclosed in ` with its output. Thus, the command you actually invoke is:</p>
<pre><code>python shell.py --cmd "for i in 1
2
3
4
5
6
7
8
9
10; do ..."
</code></pre>
<hr>
... | 1 | 2016-10-04T18:41:16Z | [
"python",
"shell",
"optionparser"
] |
setup.py "nice to have" dependency modules | 39,859,289 | <p>I'm looking at a setup.py file that looks a bit like this one:</p>
<pre><code>#!/usr/bin/env python
from setuptools import setup, find_packages
import sys
if sys.argv[1] == 'test':
import multiprocessing, logging
from billiard import util
with open('requirements.txt') as f:
required = f.read().splitli... | 0 | 2016-10-04T18:26:06Z | 39,859,335 | <p>You can declare optional dependencies as <a href="https://setuptools.readthedocs.io/en/latest/setuptools.html#declaring-extras-optional-features-with-their-own-dependencies" rel="nofollow">extras in your setup.py</a></p>
| 2 | 2016-10-04T18:29:22Z | [
"python",
"python-2.7",
"setuptools",
"distutils",
"leveldb"
] |
correct way to obtain the rest of the parameters of URL in Django rest framework | 39,859,308 | <p>Hi everyone I am using Django rest framework to create an API</p>
<p>In my URLs.py file I have this</p>
<pre><code> url(r'^cpuProjects/$', cpuProjectsViewSet.as_view({'get': 'list'})),
url(r'^cpuProjects/(?P<project_name>[a-zA-Z0-9]+)$', cpuProjectsViewSet.as_view({'get': 'retrieve'})),
</code></pre>
<p... | 0 | 2016-10-04T18:27:16Z | 39,859,564 | <p>You have that entire path of the url wrapped in this same regex named group. You can instead separate the trailing part by putting it in a different group:</p>
<pre><code>url(r'^cpuProjects/(?P<project_name>[a-zA-Z0-9]+)/(?P<status>[a-zA-Z0-9]+)$', ...),
</code></pre>
<p>And in your view:</p>
<pre><co... | 1 | 2016-10-04T18:44:00Z | [
"python",
"django",
"django-rest-framework",
"django-cms"
] |
Same Python code , different performance | 39,859,331 | <p>I wrote this code in Python and there's something driving me crazy. The same code when I put in function, give me different results!! How that can be? This is the code in the main and the same code in a function</p>
<pre><code>def iterateTesting(k):
Accuracy = []
for t in range(0,10):
train_data,tes... | -1 | 2016-10-04T18:28:59Z | 39,875,052 | <p>Problem solved by defining training and testing data as global variables in my function</p>
| 0 | 2016-10-05T13:17:06Z | [
"python",
"python-2.7",
"numpy",
"scikit-learn",
"kdtree"
] |
Need help finding average in this file (Python) | 39,859,346 | <p>I was given this file that opens up in excel which looks something like this:</p>
<pre><code>year interest inflation
1900 4.2 7.5
</code></pre>
<p>This goes on a lot further, all the way to 2008 if i remember right. We are suppose to write a function that accepts a single filename as a parameter and return... | -3 | 2016-10-04T18:30:00Z | 39,859,544 | <p>Can you try this code?</p>
<pre><code>def inflAvgMaxMin(file):
with open('thefilename', 'r') as f:
inflation = []
header = 1
for line in f:
if header != 1:
infl = line.split(",")[2]
inflation.append(float(infl))
... | -1 | 2016-10-04T18:42:47Z | [
"python",
"python-3.x",
"average"
] |
Don't install dependencies when performing `setup.py test` | 39,859,348 | <p>I want to do an offline installation of a python package. As part of the installation, I run the package's tests with <code>python3 setup.py test</code>. When I run the test command, setuptools fetches all of the unsatisfied dependencies from <code>pypi.python.org</code>. However I'm providing all of the package's d... | 1 | 2016-10-04T18:30:10Z | 39,860,943 | <p>OK, so here's one way to do it. It's possibly not the most elegant and it has some downsides, but it seems to work.</p>
<p>Create (or modify an existing) <code>setup.cfg</code> file with the following lines:</p>
<pre><code>[easy_install]
find_links = file:///dev/null
index_url = file:///dev/null
</code></pre>
<p>... | 0 | 2016-10-04T20:10:31Z | [
"python",
"setuptools"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.