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
sequence |
---|---|---|---|---|---|---|---|---|---|
convert coordinates into binary image python | 40,006,110 | <p>I made a GUI in which I can load an image from disk and convert the mouse motion ( drawing the contours ) into coordinates. Now I need to convert the coordinates into a binary image and I don't know how.
Here is my code:</p>
<pre><code>from Tkinter import *
from tkFileDialog import askopenfilename
from PIL import Image, ImageTk
import numpy as np
import cv2
class Browse_image :
def __init__ (self,master) :
frame = Frame(master)
frame.grid(sticky=W+E+N+S)
self.browse = Button(frame, text="Browse", command = lambda: browseim(self))
self.browse.grid(row=13, columnspan=1)
self.photo = PhotoImage(file="browse.png")
self.label = Label(frame, image=self.photo)
self.label.grid(row=1,rowspan=10)
self.label.bind('<B1-Motion>', self.mouseevent)
def mouseevent(self,event):
w=self.photo.width()
h=self.photo.height()
a = np.zeros(shape=(h,w))
#print event.x, event.y
a[event.x,event.y]=1
</code></pre>
<p>plt.imsave('binary.png', a, cmap=cm.gray)</p>
<pre><code>def browseim(self):
path = askopenfilename(filetypes=(("png files","*.png"),("jpeg files",
"*.jpeg")) )
if path:
img = Image.open(path)
self.photo = ImageTk.PhotoImage(img)
self.label.configure(image = self.photo)
#self.label.image = self.photo
root= Tk()
b= Browse_image(root)
root.mainloop()
</code></pre>
<p>`</p>
| 0 | 2016-10-12T18:43:39Z | 40,017,903 | <p>Your issue is that you are creating a new empty array at each mouse event with the line <code>a = np.zeros(shape=(h,w))</code> in mouseevent. To fix that you should have <code>a</code> declared in the <code>__init__</code> as an attribute (ie <code>self.a = np.zeros(shape=(h,w))</code>) so that you can acces and update it without overwriting it in your <code>mouseevent</code> function.</p>
| 0 | 2016-10-13T09:59:19Z | [
"python",
"tkinter"
] |
Can this python function be vectorized? | 40,006,169 | <p>I have been working on this function that generates some parameters I need for a simulation code I am developing and have hit a wall with enhancing its performance.</p>
<p>Profiling the code shows that this is the main bottleneck so any enhancements I can make to it however minor would be great.</p>
<p>I wanted to try to vectorize parts of this function but I am not sure if it is possible.</p>
<p>The main challenge is that the parameters that get stored in my array <code>params</code> depends upon the indices of params. The only straightforward solution to this I saw was using <code>np.ndenumerate</code>, but this seems to be pretty slow. </p>
<p>Is it possible to vectorize this type of operation where the values stored in the array depend upon where they are being stored? Or would it be smarter/faster to create a generator that would just give me the tuples of the array indices?</p>
<pre><code>import numpy as np
from scipy.sparse import linalg as LA
def get_params(num_bonds, energies):
"""
Returns the interaction parameters of different pairs of atoms.
Parameters
----------
num_bonds : ndarray, shape = (M, 20)
Sparse array containing the number of nearest neighbor bonds for
different pairs of atoms (denoted by their column) and next-
nearest neighbor bonds. Columns 0-9 contain nearest neighbors,
10-19 contain next-nearest neighbors
energies : ndarray, shape = (M, )
Energy vector corresponding to each atomic system stored in each
row of num_bonds.
"""
# -- Compute the bond energies
x = LA.lsqr(num_bonds, energies, show=False)[0]
params = np.zeros([4, 4, 4, 4, 4, 4, 4, 4, 4])
nn = {(0,0): x[0], (1,1): x[1], (2,2): x[2], (3,3): x[3], (0,1): x[4],
(1,0): x[4], (0,2): x[5], (2,0): x[5], (0,3): x[6], (3,0): x[6],
(1,2): x[7], (2,1): x[7], (1,3): x[8], (3,1): x[8], (2,3): x[9],
(3,2): x[9]}
nnn = {(0,0): x[10], (1,1): x[11], (2,2): x[12], (3,3): x[13], (0,1): x[14],
(1,0): x[14], (0,2): x[15], (2,0): x[15], (0,3): x[16], (3,0): x[16],
(1,2): x[17], (2,1): x[17], (1,3): x[18], (3,1): x[18], (2,3): x[19],
(3,2): x[19]}
"""
params contains the energy contribution of each site due to its
local environment. The shape is given by the number of possible atom
types and the number of sites in the lattice.
"""
for (i,j,k,l,m,jj,kk,ll,mm), val in np.ndenumerate(params):
params[i,j,k,l,m,jj,kk,ll,mm] = nn[(i,j)] + nn[(i,k)] + nn[(i,l)] + \
nn[(i,m)] + nnn[(i,jj)] + \
nnn[(i,kk)] + nnn[(i,ll)] + nnn[(i,mm)]
return np.ascontiguousarray(params)
</code></pre>
| 4 | 2016-10-12T18:47:04Z | 40,008,834 | <p>Here's a vectorized approach using <a href="https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow"><code>broadcasted</code></a> summations -</p>
<pre><code># Gather the elements sorted by the keys in (row,col) order of a dense
# 2D array for both nn and nnn
sidx0 = np.ravel_multi_index(np.array(nn.keys()).T,(4,4)).argsort()
a0 = np.array(nn.values())[sidx0].reshape(4,4)
sidx1 = np.ravel_multi_index(np.array(nnn.keys()).T,(4,4)).argsort()
a1 = np.array(nnn.values())[sidx1].reshape(4,4)
# Perform the summations keep the first axis aligned for nn and nnn parts
parte0 = a0[:,:,None,None,None] + a0[:,None,:,None,None] + \
a0[:,None,None,:,None] + a0[:,None,None,None,:]
parte1 = a1[:,:,None,None,None] + a1[:,None,:,None,None] + \
a1[:,None,None,:,None] + a1[:,None,None,None,:]
# Finally add up sums from nn and nnn for final output
out = parte0[...,None,None,None,None] + parte1[:,None,None,None,None]
</code></pre>
<p><strong>Runtime test</strong></p>
<p>Function defintions -</p>
<pre><code>def vectorized_approach(nn,nnn):
sidx0 = np.ravel_multi_index(np.array(nn.keys()).T,(4,4)).argsort()
a0 = np.array(nn.values())[sidx0].reshape(4,4)
sidx1 = np.ravel_multi_index(np.array(nnn.keys()).T,(4,4)).argsort()
a1 = np.array(nnn.values())[sidx1].reshape(4,4)
parte0 = a0[:,:,None,None,None] + a0[:,None,:,None,None] + \
a0[:,None,None,:,None] + a0[:,None,None,None,:]
parte1 = a1[:,:,None,None,None] + a1[:,None,:,None,None] + \
a1[:,None,None,:,None] + a1[:,None,None,None,:]
return parte0[...,None,None,None,None] + parte1[:,None,None,None,None]
def original_approach(nn,nnn):
params = np.zeros([4, 4, 4, 4, 4, 4, 4, 4, 4])
for (i,j,k,l,m,jj,kk,ll,mm), val in np.ndenumerate(params):
params[i,j,k,l,m,jj,kk,ll,mm] = nn[(i,j)] + nn[(i,k)] + nn[(i,l)] + \
nn[(i,m)] + nnn[(i,jj)] + \
nnn[(i,kk)] + nnn[(i,ll)] + nnn[(i,mm)]
return params
</code></pre>
<p>Setup inputs -</p>
<pre><code># Setup inputs
x = np.random.rand(30)
nn = {(0,0): x[0], (1,1): x[1], (2,2): x[2], (3,3): x[3], (0,1): x[4],
(1,0): x[4], (0,2): x[5], (2,0): x[5], (0,3): x[6], (3,0): x[6],
(1,2): x[7], (2,1): x[7], (1,3): x[8], (3,1): x[8], (2,3): x[9],
(3,2): x[9]}
nnn = {(0,0): x[10], (1,1): x[11], (2,2): x[12], (3,3): x[13], (0,1): x[14],
(1,0): x[14], (0,2): x[15], (2,0): x[15], (0,3): x[16], (3,0): x[16],
(1,2): x[17], (2,1): x[17], (1,3): x[18], (3,1): x[18], (2,3): x[19],
(3,2): x[19]}
</code></pre>
<p>Timings -</p>
<pre><code>In [98]: np.allclose(original_approach(nn,nnn),vectorized_approach(nn,nnn))
Out[98]: True
In [99]: %timeit original_approach(nn,nnn)
1 loops, best of 3: 884 ms per loop
In [100]: %timeit vectorized_approach(nn,nnn)
1000 loops, best of 3: 708 µs per loop
</code></pre>
<p>Welcome to <strong><code>1000x+</code></strong> speedup!</p>
| 3 | 2016-10-12T21:40:55Z | [
"python",
"performance",
"python-2.7",
"numpy",
"vectorization"
] |
storing the facebook login session | 40,006,188 | <p>I am successfully authenticating the user via facebook and getting their name in def fbconnect()</p>
<pre><code>print "username" ,login_session['username']
session.name=login_session['username']
print "session.name",session.name
</code></pre>
<p>But in my html, when I try check to see whether the user is logged in or not </p>
<pre><code>{% if session.name != '' %}
<a href="{{url_for('showLogin')}}">Click Here to Login</a>
{% else %}
<a href="{{url_for('fbdisconnect')}}">>Welcome {{session.name}}, Logout</a>
{% endif %}
</code></pre>
<p>It doesn't go to the Welcome name section, because session.name is '' What am I missing here? Thanks.</p>
<p>This is my python stuff</p>
<pre><code> @app.route('/fbconnect', methods=['POST'])
def fbconnect():
if request.args.get('state') != login_session['state']:
print "state not equal to login_session"
response = make_response(json.dumps('Invalid state parameter.'), 401)
response.headers['Content-Type'] = 'application/json'
return response
access_token = request.data
print "access token received %s " % access_token
app_id = json.loads(open('fb_client_secrets.json', 'r').read())[
'web']['app_id']
app_secret = json.loads(
open('fb_client_secrets.json', 'r').read())['web']['app_secret']
url = 'https://graph.facebook.com/oauth/access_token?grant_type=fb_exchange_token&client_id=%s&client_secret=%s&fb_exchange_token=%s' % (
app_id, app_secret, access_token)
h = httplib2.Http()
result = h.request(url, 'GET')[1]
# Use token to get user info from API
userinfo_url = "https://graph.facebook.com/v2.4/me"
print "userinfo_url", userinfo_url
# strip expire tag from access token
token = result.split("&")[0]
print "token", token
url = 'https://graph.facebook.com/v2.4/me?%s&fields=name,id,email' % token
h = httplib2.Http()
result = h.request(url, 'GET')[1]
# print "url sent for API access:%s"% url
# print "API JSON result: %s" % result
data = json.loads(result)
login_session['provider'] = 'facebook'
login_session['username'] = data["name"]
login_session['email'] = data["email"]
login_session['facebook_id'] = data["id"]
# The token must be stored in the login_session in order to properly logout, let's strip out the information before the equals sign in our token
stored_token = token.split("=")[1]
login_session['access_token'] = stored_token
# Get user picture
url = 'https://graph.facebook.com/v2.4/me/picture?%s&redirect=0&height=200&width=200' % token
h = httplib2.Http()
result = h.request(url, 'GET')[1]
data = json.loads(result)
login_session['picture'] = data["data"]["url"]
# see if user exists
user_id = getUserID(login_session['email'])
if not user_id:
user_id = createUser(login_session)
login_session['user_id'] = user_id
output = ''
output += '<h1>Welcome, '
output += login_session['username']
output += '!</h1>'
output += '<img src="'
output += login_session['picture']
output += ' " style = "width: 300px; height: 300px;border-radius: 150px;-webkit-border-radius: 150px;-moz-border-radius: 150px;"> '
flash("Now logged in as %s" % login_session['username'])
print "username" ,login_session['username']
session['name']=login_session['username']
print "session['name']",session['name']
return output
</code></pre>
<p>If I change the html to </p>
<pre><code>{% if login_session['username'] != '' %}
</code></pre>
<p>Then it says UndefinedError: 'login_session' is undefined</p>
| -1 | 2016-10-12T18:48:29Z | 40,008,567 | <p>It is working now using <code>session['username']</code> </p>
<p>I had to move some code around from one page to another to get it to work though. </p>
<p>Thanks for your help. </p>
| 0 | 2016-10-12T21:22:11Z | [
"python",
"flask",
"facebook-login"
] |
Keeping order of parameters in Python Post Request | 40,006,246 | <p>For some reason, I need to influence the ordering of the data in post-Request with the requests-library.</p>
<p>Consider this:</p>
<pre><code>data = {
'param1': "foo",
'param2': "bar",
}
print requests.post(url, data=data)
</code></pre>
<p>So param1 should be in the body before param2. A corresponding curl-Request would look like that:</p>
<pre><code>curl --data "param1=foo&param2=bar" https://url.com
</code></pre>
<p>However, a dict is unordered in Python, so the actual ordering may differ. Is there a way to tell the request-library, in which order the parameters should be sent? Maybe to give the parameters urlencoded?</p>
| 0 | 2016-10-12T18:51:43Z | 40,006,303 | <p>You can use an <a href="https://docs.python.org/2/library/collections.html#collections.OrderedDict" rel="nofollow"><code>OrderedDict</code></a> instead:</p>
<pre><code>from collections import OrderedDict
data = OrderedDict(param1="foo", param2="bar")
print requests.post(url, data=data)
</code></pre>
| 0 | 2016-10-12T18:55:33Z | [
"python",
"post",
"request"
] |
How to collect continuous data with Python Telnet | 40,006,258 | <p>I have a python script that connects to a Power Supply via a Telnet session. The flow of the script is as follows:</p>
<pre><code># Connect to Device
tn = telnetlib.Telnet(HOST,PORT)
# Turn On
tn.write("OUT 1\r")
# Get Current Voltage
current_voltage = tn.write("MV?\r")
# Turn Off
tn.write("OUT 0\r")
</code></pre>
<p>What I'd like to do is be able to get the Current Voltage every t milliseconds(ms) and be able to display it on my Tkinter GUI until the device is commanded to be turned off. Ideally I'd like to display it on a chart such that I have Voltage vs. time, but i can live with just a dynamic text display for now. The <code>current_voltage</code> variable will store a string representing the current voltage value. What is the best way I can accomplish this? Thanks.</p>
| 0 | 2016-10-12T18:52:37Z | 40,006,501 | <p>Every millisecond is probably more than tkinter can handle. It depends a bit on how expensive it is to fetch the voltage. If it takes longer than a millisecond, you're going to need threads or multiprocessing. </p>
<p>The simplest solution is to use <code>after</code> to schedule the retrieval of the data every millisecond, though again, I'm not sure it can keep up. The problem is that the event loop needs time to process events, and giving it such a tiny window of time when it's not fetching voltages may result in a laggy GUI.</p>
<p>The general technique is to write a function that does some work, and then calls <code>after</code> to have itself called again in the future. </p>
<p>For example:</p>
<pre><code>root = tk.Tk()
...
def get_voltage():
<your code to get the voltage goes here>
# get the voltage again in one millisecond
root.after(1, get_voltage)
...
get_voltage()
root.mainloop()
</code></pre>
<p>the other choice is to use threads, where you have a thread that does nothing but get the voltage information and put it on a queue. Then, using the same technique as above, you can pull the latest voltage(s) off of the queue for display.</p>
| 2 | 2016-10-12T19:07:51Z | [
"python",
"tkinter",
"telnet"
] |
How to filter a pandas dataframe based on the length of a entry | 40,006,276 | <p>In a pandas dataframe I have a field 'amp' that should be populated by a list of length 495. Is there a panda-ic way to quickly filter on this length, such that all rows with field 'amp' are not equal to 495 are dropped?</p>
<p>I tried</p>
<pre><code>df[len(df['amp']) == 495]
</code></pre>
<p>and this returned</p>
<pre><code>KeyError: False
</code></pre>
<p>Thanks in advance.</p>
| 1 | 2016-10-12T18:53:47Z | 40,006,292 | <p>Try this:</p>
<pre><code>df[df['amp'].str.len() == 495]
</code></pre>
<p>Demo:</p>
<pre><code>In [77]: df
Out[77]:
a
0 [1, 2, 3, 4, 5]
1 [1, 2, 3]
2 [-1]
In [78]: df.a.str.len()
Out[78]:
0 5
1 3
2 1
Name: a, dtype: int64
In [79]: df[df.a.str.len() == 3]
Out[79]:
a
1 [1, 2, 3]
</code></pre>
| 4 | 2016-10-12T18:55:04Z | [
"python",
"pandas",
"dataframe"
] |
How to filter a pandas dataframe based on the length of a entry | 40,006,276 | <p>In a pandas dataframe I have a field 'amp' that should be populated by a list of length 495. Is there a panda-ic way to quickly filter on this length, such that all rows with field 'amp' are not equal to 495 are dropped?</p>
<p>I tried</p>
<pre><code>df[len(df['amp']) == 495]
</code></pre>
<p>and this returned</p>
<pre><code>KeyError: False
</code></pre>
<p>Thanks in advance.</p>
| 1 | 2016-10-12T18:53:47Z | 40,006,452 | <p>If you specifically need <code>len</code>, then @MaxU's answer is best.</p>
<p>For a more general solution, you can use the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.map.html" rel="nofollow">map</a> method of a Series.</p>
<pre><code>df[df['amp'].map(len) == 495]
</code></pre>
<p>This will apply <code>len</code> to each element, which is what you want. With this method, you can use any arbitrary function, not just <code>len</code>.</p>
| 2 | 2016-10-12T19:04:29Z | [
"python",
"pandas",
"dataframe"
] |
How two recursion function in program works? | 40,006,300 | <p>I am learning Recursion and understand single recursion like Factorial . I am facing problem to understand how two recursive function works ? I am trying to understand this code :</p>
<pre><code>def countdown(n,m):
if n == 0: # this is the base case
return # return, instead of making more recursive calls
print("before recursion",n)
countdown(n - 1,m) # first recursive call
print("first recursion",n)
countdown(n - 1,m)
print("Second recursion",n) # second recursive call
countdown(3,4)
</code></pre>
<p>And the output is :</p>
<pre><code>before recursion 3
before recursion 2
before recursion 1
first recursion 1
Second recursion 1
first recursion 2
before recursion 1
first recursion 1
Second recursion 1
Second recursion 2
first recursion 3
before recursion 2
before recursion 1
first recursion 1
Second recursion 1
first recursion 2
before recursion 1
first recursion 1
Second recursion 1
Second recursion 2
Second recursion 3
</code></pre>
<p>I tried to understand with visual python :</p>
<p><a href="http://pythontutor.com/visualize.html#code=def%20countdown(n,m%29%3A%0A%0A%20%20%20%20if%20n%20%3D%3D%200%3A%20%20%23%20this%20is%20the%20base%20case%0A%20%20%20%20%20%20%20%20return%20%20%23%20return,%20instead%20of%20making%20more%20recursive%20calls%0A%20%20%20%20print(%22before%20recursion%22,n%29%0A%0A%20%20%20%20countdown(n%20-%201,m%29%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%23%20first%20recursive%20call%0A%20%20%20%20print(%22first%20recursion%22,n%29%20%20%20%20%20%20%20%0A%20%20%20%20countdown(n%20-%201,m%29%0A%20%20%20%20print(%22Second%20recursion%22,n%29%20%20%20%20%20%20%20%20%20%20%20%20%23%20second%20recursive%20call%0A%0A%0A%0Acountdown(3,4%29&cumulative=false&curInstr=0&heapPrimitives=false&mode=display&origin=opt-frontend.js&py=3&rawInputLstJSON=%5B%5D&textReferences=false" rel="nofollow">Visualize Python code live</a></p>
<p>I am understanding first recursion process but when second recursion start , I am facing problem to understand behaviour of second recursion </p>
<p>Let me explain what i am not understanding :</p>
<p>Ok so this is situation where first recursion finish after finding this base condition (n==0)</p>
<p><a href="https://i.stack.imgur.com/9R6aV.png" rel="nofollow"><img src="https://i.stack.imgur.com/9R6aV.png" alt="First recursion found base condition"></a></p>
<p>Now here second recursion start work</p>
<p><a href="https://i.stack.imgur.com/U7oHo.png" rel="nofollow"><img src="https://i.stack.imgur.com/U7oHo.png" alt="enter image description here"></a></p>
<p>, My confusion is until i have learned "below part of recursion would not execute until recursion found its base condition so first recursion didn't print <code>"first recursion 1"</code> until it found base condition in this program , i understand this point clearly. But now when second recursion start working it print immediately <code>"Second recursion 1"</code>(<code>print("Second recursion",n)</code> ) without completing recursion ?? My main confusion is this.</p>
<p>If you are confuse please see step 36 to 43 here <a href="http://pythontutor.com/visualize.html#code=def%20countdown(n,m%29%3A%0A%0A%20%20%20%20if%20n%20%3D%3D%200%3A%20%20%23%20this%20is%20the%20base%20case%0A%20%20%20%20%20%20%20%20return%20%20%23%20return,%20instead%20of%20making%20more%20recursive%20calls%0A%20%20%20%20print(%22before%20recursion%22,n%29%0A%0A%20%20%20%20countdown(n%20-%201,m%29%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%23%20first%20recursive%20call%0A%20%20%20%20print(%22first%20recursion%22,n%29%20%20%20%20%20%20%20%0A%20%20%20%20countdown(n%20-%201,m%29%0A%20%20%20%20print(%22Second%20recursion%22,n%29%20%20%20%20%20%20%20%20%20%20%20%20%23%20second%20recursive%20call%0A%0A%0A%0Acountdown(3,4%29&cumulative=false&curInstr=0&heapPrimitives=false&mode=display&origin=opt-frontend.js&py=3&rawInputLstJSON=%5B%5D&textReferences=false" rel="nofollow">Visualize Python code live</a></p>
<p>If i understand this then i would be able to understand tower of hanoi problem. But i want to understand first how second recursion work in program.</p>
| -2 | 2016-10-12T18:55:24Z | 40,006,672 | <p>You can visualize the sequence of calls and returns in a tree like this:</p>
<p><a href="https://i.stack.imgur.com/yLESp.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/yLESp.jpg" alt="enter image description here"></a></p>
<p>The calls traverse this tree left to right, depth first:</p>
<p><a href="https://i.stack.imgur.com/piBm7.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/piBm7.jpg" alt="enter image description here"></a></p>
<p>Hopes this helps your intuition a bit. 'Arrow down' is call, 'arrow up' is return. Each function call has it's own lump of data, called a 'stack frame'. That's were' your n is remembered FOR THAT CALL. With each call a new stack frame is created. With each return the stack frame of the function you return from is destroyed. If you're 3 calls deep, you'll have 3 stack frames, containing e.g. n == 3, n == 2, n == 1 respectively.</p>
<p>At the deepest point, look at the green arrows:</p>
<p><a href="https://i.stack.imgur.com/fTDRu.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/fTDRu.jpg" alt="enter image description here"></a></p>
<p>Have added green arrows to illustrate the point where the first recursion terminates and the second begins. Since traversal is depth first it starts at the lowest point, not at the root / top</p>
| 0 | 2016-10-12T19:17:32Z | [
"python",
"python-3.x",
"recursion"
] |
How two recursion function in program works? | 40,006,300 | <p>I am learning Recursion and understand single recursion like Factorial . I am facing problem to understand how two recursive function works ? I am trying to understand this code :</p>
<pre><code>def countdown(n,m):
if n == 0: # this is the base case
return # return, instead of making more recursive calls
print("before recursion",n)
countdown(n - 1,m) # first recursive call
print("first recursion",n)
countdown(n - 1,m)
print("Second recursion",n) # second recursive call
countdown(3,4)
</code></pre>
<p>And the output is :</p>
<pre><code>before recursion 3
before recursion 2
before recursion 1
first recursion 1
Second recursion 1
first recursion 2
before recursion 1
first recursion 1
Second recursion 1
Second recursion 2
first recursion 3
before recursion 2
before recursion 1
first recursion 1
Second recursion 1
first recursion 2
before recursion 1
first recursion 1
Second recursion 1
Second recursion 2
Second recursion 3
</code></pre>
<p>I tried to understand with visual python :</p>
<p><a href="http://pythontutor.com/visualize.html#code=def%20countdown(n,m%29%3A%0A%0A%20%20%20%20if%20n%20%3D%3D%200%3A%20%20%23%20this%20is%20the%20base%20case%0A%20%20%20%20%20%20%20%20return%20%20%23%20return,%20instead%20of%20making%20more%20recursive%20calls%0A%20%20%20%20print(%22before%20recursion%22,n%29%0A%0A%20%20%20%20countdown(n%20-%201,m%29%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%23%20first%20recursive%20call%0A%20%20%20%20print(%22first%20recursion%22,n%29%20%20%20%20%20%20%20%0A%20%20%20%20countdown(n%20-%201,m%29%0A%20%20%20%20print(%22Second%20recursion%22,n%29%20%20%20%20%20%20%20%20%20%20%20%20%23%20second%20recursive%20call%0A%0A%0A%0Acountdown(3,4%29&cumulative=false&curInstr=0&heapPrimitives=false&mode=display&origin=opt-frontend.js&py=3&rawInputLstJSON=%5B%5D&textReferences=false" rel="nofollow">Visualize Python code live</a></p>
<p>I am understanding first recursion process but when second recursion start , I am facing problem to understand behaviour of second recursion </p>
<p>Let me explain what i am not understanding :</p>
<p>Ok so this is situation where first recursion finish after finding this base condition (n==0)</p>
<p><a href="https://i.stack.imgur.com/9R6aV.png" rel="nofollow"><img src="https://i.stack.imgur.com/9R6aV.png" alt="First recursion found base condition"></a></p>
<p>Now here second recursion start work</p>
<p><a href="https://i.stack.imgur.com/U7oHo.png" rel="nofollow"><img src="https://i.stack.imgur.com/U7oHo.png" alt="enter image description here"></a></p>
<p>, My confusion is until i have learned "below part of recursion would not execute until recursion found its base condition so first recursion didn't print <code>"first recursion 1"</code> until it found base condition in this program , i understand this point clearly. But now when second recursion start working it print immediately <code>"Second recursion 1"</code>(<code>print("Second recursion",n)</code> ) without completing recursion ?? My main confusion is this.</p>
<p>If you are confuse please see step 36 to 43 here <a href="http://pythontutor.com/visualize.html#code=def%20countdown(n,m%29%3A%0A%0A%20%20%20%20if%20n%20%3D%3D%200%3A%20%20%23%20this%20is%20the%20base%20case%0A%20%20%20%20%20%20%20%20return%20%20%23%20return,%20instead%20of%20making%20more%20recursive%20calls%0A%20%20%20%20print(%22before%20recursion%22,n%29%0A%0A%20%20%20%20countdown(n%20-%201,m%29%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%23%20first%20recursive%20call%0A%20%20%20%20print(%22first%20recursion%22,n%29%20%20%20%20%20%20%20%0A%20%20%20%20countdown(n%20-%201,m%29%0A%20%20%20%20print(%22Second%20recursion%22,n%29%20%20%20%20%20%20%20%20%20%20%20%20%23%20second%20recursive%20call%0A%0A%0A%0Acountdown(3,4%29&cumulative=false&curInstr=0&heapPrimitives=false&mode=display&origin=opt-frontend.js&py=3&rawInputLstJSON=%5B%5D&textReferences=false" rel="nofollow">Visualize Python code live</a></p>
<p>If i understand this then i would be able to understand tower of hanoi problem. But i want to understand first how second recursion work in program.</p>
| -2 | 2016-10-12T18:55:24Z | 40,007,010 | <p><strong>Short answer</strong>: You see "first recursion" and "second recursion" so early in the output because, in the process of making a recursive call to <code>countdown(3)</code> you eventually make a call to <code>countdown(1)</code>, which itself makes two recursive calls to <code>countdown(0)</code> which complete immediately.</p>
<p>I'll focus on the first part of the output and hand-simulate to explain how we got there:</p>
<p><code>
before recursion 3
before recursion 2
before recursion 1
first recursion 1
Second recursion 1
</code></p>
<p>Then, walking through a call to <code>countdown(3)</code> (I'm ignoring the <code>m</code> argument because it does not appear to be relevant here) looks like:</p>
<ul>
<li>Call <code>countdown(3)</code>
<ul>
<li>Check if 3=0 (it doesn't, don't return)</li>
<li>Print "before recursion 3" (in output above)</li>
<li>Call <code>countdown(2)</code>
<ul>
<li>Check if 2=0 (it doesn't, don't return)</li>
<li>Print "before recursion 2" (in output above)</li>
<li>Call <code>countdown(1)</code>
<ul>
<li>Check if 1=0 (it doesn't, don't return)</li>
<li>Print "before recursion 1" (in output above)</li>
<li>Call <code>countdown(0)</code>
<ul>
<li>Check if 0=0 and return because yes, it does</li>
</ul></li>
<li>Print "first recursion 1"</li>
<li>Call <code>countdown(0)</code>
<ul>
<li>Check if 0=0 and return because yes, it does</li>
</ul></li>
<li>Print "second recursion 1"</li>
</ul></li>
</ul></li>
</ul></li>
</ul>
<p>You can proceed from there to explain the rest of the output, but I think this gets far enough to illustrate what is happening in the area where you're confused.</p>
| 1 | 2016-10-12T19:40:57Z | [
"python",
"python-3.x",
"recursion"
] |
How two recursion function in program works? | 40,006,300 | <p>I am learning Recursion and understand single recursion like Factorial . I am facing problem to understand how two recursive function works ? I am trying to understand this code :</p>
<pre><code>def countdown(n,m):
if n == 0: # this is the base case
return # return, instead of making more recursive calls
print("before recursion",n)
countdown(n - 1,m) # first recursive call
print("first recursion",n)
countdown(n - 1,m)
print("Second recursion",n) # second recursive call
countdown(3,4)
</code></pre>
<p>And the output is :</p>
<pre><code>before recursion 3
before recursion 2
before recursion 1
first recursion 1
Second recursion 1
first recursion 2
before recursion 1
first recursion 1
Second recursion 1
Second recursion 2
first recursion 3
before recursion 2
before recursion 1
first recursion 1
Second recursion 1
first recursion 2
before recursion 1
first recursion 1
Second recursion 1
Second recursion 2
Second recursion 3
</code></pre>
<p>I tried to understand with visual python :</p>
<p><a href="http://pythontutor.com/visualize.html#code=def%20countdown(n,m%29%3A%0A%0A%20%20%20%20if%20n%20%3D%3D%200%3A%20%20%23%20this%20is%20the%20base%20case%0A%20%20%20%20%20%20%20%20return%20%20%23%20return,%20instead%20of%20making%20more%20recursive%20calls%0A%20%20%20%20print(%22before%20recursion%22,n%29%0A%0A%20%20%20%20countdown(n%20-%201,m%29%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%23%20first%20recursive%20call%0A%20%20%20%20print(%22first%20recursion%22,n%29%20%20%20%20%20%20%20%0A%20%20%20%20countdown(n%20-%201,m%29%0A%20%20%20%20print(%22Second%20recursion%22,n%29%20%20%20%20%20%20%20%20%20%20%20%20%23%20second%20recursive%20call%0A%0A%0A%0Acountdown(3,4%29&cumulative=false&curInstr=0&heapPrimitives=false&mode=display&origin=opt-frontend.js&py=3&rawInputLstJSON=%5B%5D&textReferences=false" rel="nofollow">Visualize Python code live</a></p>
<p>I am understanding first recursion process but when second recursion start , I am facing problem to understand behaviour of second recursion </p>
<p>Let me explain what i am not understanding :</p>
<p>Ok so this is situation where first recursion finish after finding this base condition (n==0)</p>
<p><a href="https://i.stack.imgur.com/9R6aV.png" rel="nofollow"><img src="https://i.stack.imgur.com/9R6aV.png" alt="First recursion found base condition"></a></p>
<p>Now here second recursion start work</p>
<p><a href="https://i.stack.imgur.com/U7oHo.png" rel="nofollow"><img src="https://i.stack.imgur.com/U7oHo.png" alt="enter image description here"></a></p>
<p>, My confusion is until i have learned "below part of recursion would not execute until recursion found its base condition so first recursion didn't print <code>"first recursion 1"</code> until it found base condition in this program , i understand this point clearly. But now when second recursion start working it print immediately <code>"Second recursion 1"</code>(<code>print("Second recursion",n)</code> ) without completing recursion ?? My main confusion is this.</p>
<p>If you are confuse please see step 36 to 43 here <a href="http://pythontutor.com/visualize.html#code=def%20countdown(n,m%29%3A%0A%0A%20%20%20%20if%20n%20%3D%3D%200%3A%20%20%23%20this%20is%20the%20base%20case%0A%20%20%20%20%20%20%20%20return%20%20%23%20return,%20instead%20of%20making%20more%20recursive%20calls%0A%20%20%20%20print(%22before%20recursion%22,n%29%0A%0A%20%20%20%20countdown(n%20-%201,m%29%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%23%20first%20recursive%20call%0A%20%20%20%20print(%22first%20recursion%22,n%29%20%20%20%20%20%20%20%0A%20%20%20%20countdown(n%20-%201,m%29%0A%20%20%20%20print(%22Second%20recursion%22,n%29%20%20%20%20%20%20%20%20%20%20%20%20%23%20second%20recursive%20call%0A%0A%0A%0Acountdown(3,4%29&cumulative=false&curInstr=0&heapPrimitives=false&mode=display&origin=opt-frontend.js&py=3&rawInputLstJSON=%5B%5D&textReferences=false" rel="nofollow">Visualize Python code live</a></p>
<p>If i understand this then i would be able to understand tower of hanoi problem. But i want to understand first how second recursion work in program.</p>
| -2 | 2016-10-12T18:55:24Z | 40,007,957 | <p>Another little trick you can use to see what comes from calls at which level: pass an argument that increases with recursion depth to make it easy to associate output with particular calls. I'm going to use a string argument called <code>indent</code>, and add two spaces for each level of indentation.</p>
<p>I've taken the liberty of changing the code layout a little bit, to conform with standard PEP 8 style (not essential, but it shows you care about standards ;-).</p>
<pre><code>def countdown(n, m, indent=""):
"Recurse uselessly for better understanding of recursion."
if n == 0: # this is the base case
return # return nothing, negating the point a bit
print(indent, "before recursion", n)
countdown(n - 1, m, indent + " ")
print(indent, "first recursion", n)
countdown(n - 1, m)
print(indent, "Second recursion", n, indent + " ")
countdown(3, 4)
</code></pre>
<p>The output from running this code is</p>
<pre><code> before recursion 3
before recursion 2
before recursion 1
first recursion 1
Second recursion 1
first recursion 2
before recursion 1
first recursion 1
Second recursion 1
Second recursion 2
first recursion 3
before recursion 2
before recursion 1
first recursion 1
Second recursion 1
first recursion 2
before recursion 1
first recursion 1
Second recursion 1
Second recursion 2
Second recursion 3
</code></pre>
<p>Hopefully this will allow you to sort out who's doing what and in which order.</p>
| 1 | 2016-10-12T20:39:56Z | [
"python",
"python-3.x",
"recursion"
] |
How two recursion function in program works? | 40,006,300 | <p>I am learning Recursion and understand single recursion like Factorial . I am facing problem to understand how two recursive function works ? I am trying to understand this code :</p>
<pre><code>def countdown(n,m):
if n == 0: # this is the base case
return # return, instead of making more recursive calls
print("before recursion",n)
countdown(n - 1,m) # first recursive call
print("first recursion",n)
countdown(n - 1,m)
print("Second recursion",n) # second recursive call
countdown(3,4)
</code></pre>
<p>And the output is :</p>
<pre><code>before recursion 3
before recursion 2
before recursion 1
first recursion 1
Second recursion 1
first recursion 2
before recursion 1
first recursion 1
Second recursion 1
Second recursion 2
first recursion 3
before recursion 2
before recursion 1
first recursion 1
Second recursion 1
first recursion 2
before recursion 1
first recursion 1
Second recursion 1
Second recursion 2
Second recursion 3
</code></pre>
<p>I tried to understand with visual python :</p>
<p><a href="http://pythontutor.com/visualize.html#code=def%20countdown(n,m%29%3A%0A%0A%20%20%20%20if%20n%20%3D%3D%200%3A%20%20%23%20this%20is%20the%20base%20case%0A%20%20%20%20%20%20%20%20return%20%20%23%20return,%20instead%20of%20making%20more%20recursive%20calls%0A%20%20%20%20print(%22before%20recursion%22,n%29%0A%0A%20%20%20%20countdown(n%20-%201,m%29%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%23%20first%20recursive%20call%0A%20%20%20%20print(%22first%20recursion%22,n%29%20%20%20%20%20%20%20%0A%20%20%20%20countdown(n%20-%201,m%29%0A%20%20%20%20print(%22Second%20recursion%22,n%29%20%20%20%20%20%20%20%20%20%20%20%20%23%20second%20recursive%20call%0A%0A%0A%0Acountdown(3,4%29&cumulative=false&curInstr=0&heapPrimitives=false&mode=display&origin=opt-frontend.js&py=3&rawInputLstJSON=%5B%5D&textReferences=false" rel="nofollow">Visualize Python code live</a></p>
<p>I am understanding first recursion process but when second recursion start , I am facing problem to understand behaviour of second recursion </p>
<p>Let me explain what i am not understanding :</p>
<p>Ok so this is situation where first recursion finish after finding this base condition (n==0)</p>
<p><a href="https://i.stack.imgur.com/9R6aV.png" rel="nofollow"><img src="https://i.stack.imgur.com/9R6aV.png" alt="First recursion found base condition"></a></p>
<p>Now here second recursion start work</p>
<p><a href="https://i.stack.imgur.com/U7oHo.png" rel="nofollow"><img src="https://i.stack.imgur.com/U7oHo.png" alt="enter image description here"></a></p>
<p>, My confusion is until i have learned "below part of recursion would not execute until recursion found its base condition so first recursion didn't print <code>"first recursion 1"</code> until it found base condition in this program , i understand this point clearly. But now when second recursion start working it print immediately <code>"Second recursion 1"</code>(<code>print("Second recursion",n)</code> ) without completing recursion ?? My main confusion is this.</p>
<p>If you are confuse please see step 36 to 43 here <a href="http://pythontutor.com/visualize.html#code=def%20countdown(n,m%29%3A%0A%0A%20%20%20%20if%20n%20%3D%3D%200%3A%20%20%23%20this%20is%20the%20base%20case%0A%20%20%20%20%20%20%20%20return%20%20%23%20return,%20instead%20of%20making%20more%20recursive%20calls%0A%20%20%20%20print(%22before%20recursion%22,n%29%0A%0A%20%20%20%20countdown(n%20-%201,m%29%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%23%20first%20recursive%20call%0A%20%20%20%20print(%22first%20recursion%22,n%29%20%20%20%20%20%20%20%0A%20%20%20%20countdown(n%20-%201,m%29%0A%20%20%20%20print(%22Second%20recursion%22,n%29%20%20%20%20%20%20%20%20%20%20%20%20%23%20second%20recursive%20call%0A%0A%0A%0Acountdown(3,4%29&cumulative=false&curInstr=0&heapPrimitives=false&mode=display&origin=opt-frontend.js&py=3&rawInputLstJSON=%5B%5D&textReferences=false" rel="nofollow">Visualize Python code live</a></p>
<p>If i understand this then i would be able to understand tower of hanoi problem. But i want to understand first how second recursion work in program.</p>
| -2 | 2016-10-12T18:55:24Z | 40,016,427 | <p>Again and again I would suggest not to use any visual tool, just have a look at the code itself! First of all the m value for what is needed in this example??? </p>
<p>Second and most important...as explained in the other post you have to think about a python STACK and going into iteration.
<a href="http://stackoverflow.com/questions/39994167/what-happen-after-recursion-found-base-condition/39994500?noredirect=1#comment67290669_39994500http://">http://stackoverflow.com/questions/39994167/what-happen-after-recursion-found-base-condition/39994500?noredirect=1#comment67290669_39994500</a> </p>
<p>In your program what you are doing is:
1) going down using --> countdown(n - 1,m) # first recursive call
before recursion 3
before recursion 2
before recursion 1</p>
<p>2) When you n = 1 you will call last time countdown(0,m) (I hope this is fine for you that n-1 = 0 now) and thus the function will just return. Then you will come back in the stack with n = 1 </p>
<pre><code>print("first recursion",n)
countdown(n - 1,m)
print("Second recursion",n) # second recursive call
</code></pre>
<p>Now you will print "first recursion 1" as showed from your output, and then going to the countdown again with countdown(0,m) that imply to return again. Thus you will go again back in your stack with n = 1 and print: "Second recursion 1".</p>
<p>Your function for n = 1 is again finished. Then you have to go to your stack and check that you had n = 2 and you were still at</p>
<pre><code> countdown(n - 1,m) # first recursive call
</code></pre>
<p>Hope this is clear for you. Then you follow to the next step and print "first recursion 2" and you go again into countdown(1,m) again n = 2 ==> n-1 = 1.
This will print "before recursion 1" and go ahead to countdown(0,m) that will return and you will go back at that point. </p>
<p>Continue this for all the steps and you will get the output you got!!
Last but not least I don't like to be downgrade, if you are not trying to follow each step :-) so this is my last explanation. Have a nice day!</p>
| 0 | 2016-10-13T08:53:22Z | [
"python",
"python-3.x",
"recursion"
] |
How two recursion function in program works? | 40,006,300 | <p>I am learning Recursion and understand single recursion like Factorial . I am facing problem to understand how two recursive function works ? I am trying to understand this code :</p>
<pre><code>def countdown(n,m):
if n == 0: # this is the base case
return # return, instead of making more recursive calls
print("before recursion",n)
countdown(n - 1,m) # first recursive call
print("first recursion",n)
countdown(n - 1,m)
print("Second recursion",n) # second recursive call
countdown(3,4)
</code></pre>
<p>And the output is :</p>
<pre><code>before recursion 3
before recursion 2
before recursion 1
first recursion 1
Second recursion 1
first recursion 2
before recursion 1
first recursion 1
Second recursion 1
Second recursion 2
first recursion 3
before recursion 2
before recursion 1
first recursion 1
Second recursion 1
first recursion 2
before recursion 1
first recursion 1
Second recursion 1
Second recursion 2
Second recursion 3
</code></pre>
<p>I tried to understand with visual python :</p>
<p><a href="http://pythontutor.com/visualize.html#code=def%20countdown(n,m%29%3A%0A%0A%20%20%20%20if%20n%20%3D%3D%200%3A%20%20%23%20this%20is%20the%20base%20case%0A%20%20%20%20%20%20%20%20return%20%20%23%20return,%20instead%20of%20making%20more%20recursive%20calls%0A%20%20%20%20print(%22before%20recursion%22,n%29%0A%0A%20%20%20%20countdown(n%20-%201,m%29%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%23%20first%20recursive%20call%0A%20%20%20%20print(%22first%20recursion%22,n%29%20%20%20%20%20%20%20%0A%20%20%20%20countdown(n%20-%201,m%29%0A%20%20%20%20print(%22Second%20recursion%22,n%29%20%20%20%20%20%20%20%20%20%20%20%20%23%20second%20recursive%20call%0A%0A%0A%0Acountdown(3,4%29&cumulative=false&curInstr=0&heapPrimitives=false&mode=display&origin=opt-frontend.js&py=3&rawInputLstJSON=%5B%5D&textReferences=false" rel="nofollow">Visualize Python code live</a></p>
<p>I am understanding first recursion process but when second recursion start , I am facing problem to understand behaviour of second recursion </p>
<p>Let me explain what i am not understanding :</p>
<p>Ok so this is situation where first recursion finish after finding this base condition (n==0)</p>
<p><a href="https://i.stack.imgur.com/9R6aV.png" rel="nofollow"><img src="https://i.stack.imgur.com/9R6aV.png" alt="First recursion found base condition"></a></p>
<p>Now here second recursion start work</p>
<p><a href="https://i.stack.imgur.com/U7oHo.png" rel="nofollow"><img src="https://i.stack.imgur.com/U7oHo.png" alt="enter image description here"></a></p>
<p>, My confusion is until i have learned "below part of recursion would not execute until recursion found its base condition so first recursion didn't print <code>"first recursion 1"</code> until it found base condition in this program , i understand this point clearly. But now when second recursion start working it print immediately <code>"Second recursion 1"</code>(<code>print("Second recursion",n)</code> ) without completing recursion ?? My main confusion is this.</p>
<p>If you are confuse please see step 36 to 43 here <a href="http://pythontutor.com/visualize.html#code=def%20countdown(n,m%29%3A%0A%0A%20%20%20%20if%20n%20%3D%3D%200%3A%20%20%23%20this%20is%20the%20base%20case%0A%20%20%20%20%20%20%20%20return%20%20%23%20return,%20instead%20of%20making%20more%20recursive%20calls%0A%20%20%20%20print(%22before%20recursion%22,n%29%0A%0A%20%20%20%20countdown(n%20-%201,m%29%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%23%20first%20recursive%20call%0A%20%20%20%20print(%22first%20recursion%22,n%29%20%20%20%20%20%20%20%0A%20%20%20%20countdown(n%20-%201,m%29%0A%20%20%20%20print(%22Second%20recursion%22,n%29%20%20%20%20%20%20%20%20%20%20%20%20%23%20second%20recursive%20call%0A%0A%0A%0Acountdown(3,4%29&cumulative=false&curInstr=0&heapPrimitives=false&mode=display&origin=opt-frontend.js&py=3&rawInputLstJSON=%5B%5D&textReferences=false" rel="nofollow">Visualize Python code live</a></p>
<p>If i understand this then i would be able to understand tower of hanoi problem. But i want to understand first how second recursion work in program.</p>
| -2 | 2016-10-12T18:55:24Z | 40,050,809 | <p>You are confuse because you are visualizing two recursion with single stack , You have to know that Every recursion function store values its own stack , It means if you have two recursion there will be two stack , if you have three recursion there would be three stack. </p>
<p>Now back to the question , I have written a post about how multiple Recursion works in single program and have <a href="http://www.cryptroix.com/understanding-multiple-recursion/" rel="nofollow">explained step by step here with two stacks.</a> </p>
<p>You have to understand :</p>
<ul>
<li>There are two types of recursion :
<ul>
<li>Head Recursion</li>
<li>Tail Recursion</li>
</ul></li>
</ul>
<p>In Head recursion recursive call first find its base condition then execute rest of code. </p>
<pre><code>def head_recursion(x):
if x==0:
return
else:
head_recursion(x-1)
print("Head Recursion",x)
head_recursion(3)
</code></pre>
<p>it will print :</p>
<pre><code>Head Recursion 1
Head Recursion 2
Head Recursion 3
</code></pre>
<p>In tail recursion , Everything execute first after recursion call main function. It means In tail recursion Recursive call is last thing in function.</p>
<pre><code>def head_recursion(x):
if x==0:
return
else:
print("Head Recursion",x)
head_recursion(x-1)
head_recursion(3)
</code></pre>
<p>it will print :</p>
<pre><code>Head Recursion 3
Head Recursion 2
Head Recursion 1
</code></pre>
<p>In your code both recursion are Head recursion , So if both recursion keep executing until both find base condition and stack returned all values.</p>
<p>You have to understand what is different between calling and returning values of recursion.</p>
<p>Go through this link and understand whole process how two recursion works in single program.</p>
<p><a href="http://www.cryptroix.com/understanding-multiple-recursion/" rel="nofollow">understanding multiple recursion</a></p>
| 2 | 2016-10-14T19:36:57Z | [
"python",
"python-3.x",
"recursion"
] |
Applying UDFs on GroupedData in PySpark (with functioning python example) | 40,006,395 | <p>I have this python code that runs locally in a pandas dataframe:</p>
<pre><code>df_result = pd.DataFrame(df
.groupby('A')
.apply(lambda x: myFunction(zip(x.B, x.C), x.name))
</code></pre>
<p>I would like to run this in PySpark, but having trouble dealing with pyspark.sql.group.GroupedData object.</p>
<p>I've tried the following:</p>
<pre><code>sparkDF
.groupby('A')
.agg(myFunction(zip('B', 'C'), 'A'))
</code></pre>
<p>which returns</p>
<pre><code>KeyError: 'A'
</code></pre>
<p>I presume because 'A' is no longer a column and I can't find the equivalent for x.name.</p>
<p>And then</p>
<pre><code>sparkDF
.groupby('A')
.map(lambda row: Row(myFunction(zip('B', 'C'), 'A')))
.toDF()
</code></pre>
<p>but get the following error:</p>
<pre><code>AttributeError: 'GroupedData' object has no attribute 'map'
</code></pre>
<p>Any suggestions would be really appreciated!</p>
| 3 | 2016-10-12T19:01:10Z | 40,030,740 | <p>What you are trying to is write a UDAF (User Defined Aggregate Function) as opposed to a UDF (User Defined Function). UDAFs are functions that work on data grouped by a key. Specifically they need to define how to merge multiple values in the group in a single partition, and then how to merge the results across partitions for key. There is currently no way in python to implement a UDAF, they can only be implemented in scala. </p>
<p>But, you can work around it in Python. You can use collect set to gather your grouped values and then use a regular UDF to do what you want with them. The only caveat is collect_set only works on primative values, so you will need to encode them down to a string.</p>
<pre><code>from pyspark.sql.types import StringType
from pyspark.sql.functions import col, collect_set, concat_ws, udf
def myFunc(data_list):
for val in data_list:
b, c = data.split(',')
# do something
return <whatever>
myUdf = udf(myFunc, StringType())
df.withColumn('data', concat_ws(',', col('B'), col('C'))) \
.groupBy('A').agg(collect_list('data').alias('data'))
.withColumn('data', myUdf('data'))
</code></pre>
<p>Use collect_set if you want deduping. Also, if you have lots of values for some of your keys, this will be slow because all values for a key will need to be collected in a single partition somewhere on your cluster. If your end result is a value you build by combining the values per key in some way (for example summing them) it might be faster to implement it using the <a href="http://spark.apache.org/docs/1.6.2/api/python/pyspark.html#pyspark.RDD.aggregateByKey" rel="nofollow">RDD aggregateByKey</a> method which lets you build an intermediate value for each key in a partition before shuffling data around.</p>
| 0 | 2016-10-13T20:50:36Z | [
"python",
"apache-spark",
"pyspark",
"spark-dataframe"
] |
Efficient way to find the index of repeated sequence in a list? | 40,006,438 | <p>I have a large list of numbers in python, and I want to write a function that finds sections of the list where the same number is repeated more than n times. For example, if n is 3 then my function should return the following results for the following examples:</p>
<blockquote>
<p>When applied to example = [1,2,1,1,1,1,2,3] the function should return [(2,6)], because example[2:6] is a sequence containing all the same value.</p>
<p>When applied to example = [0,0,0,7,3,2,2,2,2,1] the function should return [(0,3), (5,9)] because both example[0:3] and example[5:9] contain repeated sequences of the same value.</p>
<p>When applied to example = [1,2,1,2,1,2,1,2,1,2] the function should return [] because there is no sequence of three or more elements that are all the same number.</p>
</blockquote>
<p>I know I could write a bunch of loops to get what I want, but that seems kind of inefficient, and I was wondering if there was an easier option to obtain what I wanted.</p>
| 2 | 2016-10-12T19:03:22Z | 40,006,579 | <p>Use <code>itertools.groupby</code> and <code>enumerate</code>:</p>
<pre><code>>>> from itertools import groupby
>>> n = 3
>>> x = [1,2,1,1,1,1,2,3]
>>> grouped = (list(g) for _,g in groupby(enumerate(x), lambda t:t[1]))
>>> [(g[0][0], g[-1][0] + 1) for g in grouped if len(g) >= n]
[(2, 6)]
>>> x = [0,0,0,7,3,2,2,2,2,1]
>>> grouped = (list(g) for _,g in groupby(enumerate(x), lambda t:t[1]))
>>> [(g[0][0], g[-1][0] + 1) for g in grouped if len(g) >= n]
[(0, 3), (5, 9)]
</code></pre>
<p>To understand groupby: just realize that each iteration returns the value of the key, which is used to group the elements of the iterable, along with a new lazy-iterable that will iterate over the group.</p>
<pre><code>>>> list(groupby(enumerate(x), lambda t:t[1]))
[(0, <itertools._grouper object at 0x7fc90a707bd0>), (7, <itertools._grouper object at 0x7fc90a707ad0>), (3, <itertools._grouper object at 0x7fc90a707950>), (2, <itertools._grouper object at 0x7fc90a707c10>), (1, <itertools._grouper object at 0x7fc90a707c50>)]
</code></pre>
| 2 | 2016-10-12T19:12:22Z | [
"python",
"python-3.x"
] |
Efficient way to find the index of repeated sequence in a list? | 40,006,438 | <p>I have a large list of numbers in python, and I want to write a function that finds sections of the list where the same number is repeated more than n times. For example, if n is 3 then my function should return the following results for the following examples:</p>
<blockquote>
<p>When applied to example = [1,2,1,1,1,1,2,3] the function should return [(2,6)], because example[2:6] is a sequence containing all the same value.</p>
<p>When applied to example = [0,0,0,7,3,2,2,2,2,1] the function should return [(0,3), (5,9)] because both example[0:3] and example[5:9] contain repeated sequences of the same value.</p>
<p>When applied to example = [1,2,1,2,1,2,1,2,1,2] the function should return [] because there is no sequence of three or more elements that are all the same number.</p>
</blockquote>
<p>I know I could write a bunch of loops to get what I want, but that seems kind of inefficient, and I was wondering if there was an easier option to obtain what I wanted.</p>
| 2 | 2016-10-12T19:03:22Z | 40,006,830 | <p>You can do this in a single loop by following the current algorithm:</p>
<pre><code>def find_pairs (array, n):
result_pairs = []
prev = idx = 0
count = 1
for i in range (0, len(array)):
if(i > 0):
if(array[i] == prev):
count += 1
else:
if(count >= n):
result_pairs.append((idx, i))
else:
prev = array[i]
idx = i
count = 1
else:
prev = array[i]
idx = i
return result_pairs
</code></pre>
<p>And you call the function like this: <code>find_pairs(list, n)</code>. The is the most efficient way you can perform this task, as it has complexity O(len(array)). I think is pretty simple to understand, but if you have any doubts just ask.</p>
| 1 | 2016-10-12T19:28:23Z | [
"python",
"python-3.x"
] |
Efficient way to find the index of repeated sequence in a list? | 40,006,438 | <p>I have a large list of numbers in python, and I want to write a function that finds sections of the list where the same number is repeated more than n times. For example, if n is 3 then my function should return the following results for the following examples:</p>
<blockquote>
<p>When applied to example = [1,2,1,1,1,1,2,3] the function should return [(2,6)], because example[2:6] is a sequence containing all the same value.</p>
<p>When applied to example = [0,0,0,7,3,2,2,2,2,1] the function should return [(0,3), (5,9)] because both example[0:3] and example[5:9] contain repeated sequences of the same value.</p>
<p>When applied to example = [1,2,1,2,1,2,1,2,1,2] the function should return [] because there is no sequence of three or more elements that are all the same number.</p>
</blockquote>
<p>I know I could write a bunch of loops to get what I want, but that seems kind of inefficient, and I was wondering if there was an easier option to obtain what I wanted.</p>
| 2 | 2016-10-12T19:03:22Z | 40,007,290 | <p>You could use this. Note that your question is ambiguous as to the role of n. I assume here that a series of <em>n</em> equal values should be matched. If it should have at least <em>n+1</em> values, then replace <code>>=</code> by <code>></code>:</p>
<pre><code>def monotoneRanges(a, n):
idx = [i for i, v in enumerate(a) if not i or a[i-1] != v] + [len(a)]
return [r for r in zip(idx, idx[1:]) if r[1] >= r[0]+n]
# example call
res = monotoneRanges([0,0,0,7,3,2,2,2,2,1], 3)
print(res)
</code></pre>
<p>Outputs:</p>
<pre><code>[(0, 3), (5, 9)]
</code></pre>
| 0 | 2016-10-12T19:58:35Z | [
"python",
"python-3.x"
] |
Converting to list of dictionary | 40,006,439 | <p>I have a text file filled with place data provided by twitter api. Here is the sample data of 2 lines</p>
<pre><code>{'country': 'United Kingdom', 'full_name': 'Dorridge, England', 'id': '31fe56e2e7d5792a', 'country_code': 'GB', 'name': 'Dorridge', 'attributes': {}, 'contained_within': [], 'place_type': 'city', 'bounding_box': {'coordinates': [[[-1.7718518, 52.3635912], [-1.7266702, 52.3635912], [-1.7266702, 52.4091167], [-1.7718518, 52.4091167]]], 'type': 'Polygon'}, 'url': 'https://api.twitter.com/1.1/geo/id/31fe56e2e7d5792a.json'}
{'country': 'India', 'full_name': 'New Delhi, India', 'id': '317fcc4b21a604d5', 'country_code': 'IN', 'name': 'New Delhi', 'attributes': {}, 'contained_within': [], 'place_type': 'city', 'bounding_box': {'coordinates': [[[76.84252, 28.397657], [77.347652, 28.397657], [77.347652, 28.879322], [76.84252, 28.879322]]], 'type': 'Polygon'}, 'url': 'https://api.twitter.com/1.1/geo/id/317fcc4b21a604d5.json'}
</code></pre>
<p>I want 'country', 'name' and 'cordinates' filed of each line.In order to do this we need to iterate line by line the entire file.so i append each line to a list</p>
<pre><code>data = []
with open('place.txt','r') as f:
for line in f:
data.append(line)
</code></pre>
<p>when i checked the data type it shows as 'str' instead of 'dict'.</p>
<pre><code>type(data[0])
str
data[0].keys()
AttributeError: 'str' object has no attribute 'keys'
</code></pre>
<p>how to fix this so that it can be saved as list of dictionaries.</p>
<p>Originally tweets were encoded and decoded by following code:</p>
<pre><code>f.write(jsonpickle.encode(tweet._json, unpicklable=False) + '\n') #encoded and saved to a .txt file
tweets.append(jsonpickle.decode(line)) # decoding
</code></pre>
<p>And place data file is saved by following code:</p>
<pre><code>fName = "place.txt"
newLine = "\n"
with open(fName, 'a', encoding='utf-8') as f:
for i in range(len(tweets)):
f.write('{}'.format(tweets[i]['place']) +'\n')
</code></pre>
| 0 | 2016-10-12T19:03:26Z | 40,006,546 | <p>In your case you should use <code>json</code> to do the data parsing. But if you have a problem with <code>json</code> (which is almost impossible since we are talking about an API ), then in general to convert from string to dictionary you can do:</p>
<pre><code>>>> import ast
>>> x = "{'country': 'United Kingdom', 'full_name': 'Dorridge, England', 'id': '31fe56e2e7d5792a', 'country_code': 'GB', 'name': 'Dorridge', 'attributes': {}, 'contained_within': [], 'place_type': 'city', 'bounding_box': {'coordinates': [[[-1.7718518, 52.3635912], [-1.7266702, 52.3635912], [-1.7266702, 52.4091167], [-1.7718518, 52.4091167]]], 'type': 'Polygon'}, 'url': 'https://api.twitter.com/1.1/geo/id/31fe56e2e7d5792a.json'}
"
>>> d = ast.literal_eval(x)
>>> d
</code></pre>
<p><code>d</code> now is a dictionary instead of a string.
<strong>But</strong> again if your data are in json format python has a built-in lib to handle <a href="https://docs.python.org/2/library/json.html#module-json" rel="nofollow">json</a> format, <strong>and is better and safer to use json than ast.</strong></p>
<p>For example if you get a response let's say <code>resp</code> you could simply do:</p>
<pre><code>response = json.loads(resp)
</code></pre>
<p>and now you could parse <code>response</code> as a dictionary.</p>
| 2 | 2016-10-12T19:10:15Z | [
"python",
"dictionary"
] |
Converting to list of dictionary | 40,006,439 | <p>I have a text file filled with place data provided by twitter api. Here is the sample data of 2 lines</p>
<pre><code>{'country': 'United Kingdom', 'full_name': 'Dorridge, England', 'id': '31fe56e2e7d5792a', 'country_code': 'GB', 'name': 'Dorridge', 'attributes': {}, 'contained_within': [], 'place_type': 'city', 'bounding_box': {'coordinates': [[[-1.7718518, 52.3635912], [-1.7266702, 52.3635912], [-1.7266702, 52.4091167], [-1.7718518, 52.4091167]]], 'type': 'Polygon'}, 'url': 'https://api.twitter.com/1.1/geo/id/31fe56e2e7d5792a.json'}
{'country': 'India', 'full_name': 'New Delhi, India', 'id': '317fcc4b21a604d5', 'country_code': 'IN', 'name': 'New Delhi', 'attributes': {}, 'contained_within': [], 'place_type': 'city', 'bounding_box': {'coordinates': [[[76.84252, 28.397657], [77.347652, 28.397657], [77.347652, 28.879322], [76.84252, 28.879322]]], 'type': 'Polygon'}, 'url': 'https://api.twitter.com/1.1/geo/id/317fcc4b21a604d5.json'}
</code></pre>
<p>I want 'country', 'name' and 'cordinates' filed of each line.In order to do this we need to iterate line by line the entire file.so i append each line to a list</p>
<pre><code>data = []
with open('place.txt','r') as f:
for line in f:
data.append(line)
</code></pre>
<p>when i checked the data type it shows as 'str' instead of 'dict'.</p>
<pre><code>type(data[0])
str
data[0].keys()
AttributeError: 'str' object has no attribute 'keys'
</code></pre>
<p>how to fix this so that it can be saved as list of dictionaries.</p>
<p>Originally tweets were encoded and decoded by following code:</p>
<pre><code>f.write(jsonpickle.encode(tweet._json, unpicklable=False) + '\n') #encoded and saved to a .txt file
tweets.append(jsonpickle.decode(line)) # decoding
</code></pre>
<p>And place data file is saved by following code:</p>
<pre><code>fName = "place.txt"
newLine = "\n"
with open(fName, 'a', encoding='utf-8') as f:
for i in range(len(tweets)):
f.write('{}'.format(tweets[i]['place']) +'\n')
</code></pre>
| 0 | 2016-10-12T19:03:26Z | 40,006,583 | <p>You can use list like this</p>
<pre><code>mlist= list()
for i in ndata.keys():
mlist.append(i)
</code></pre>
| 0 | 2016-10-12T19:12:32Z | [
"python",
"dictionary"
] |
Converting to list of dictionary | 40,006,439 | <p>I have a text file filled with place data provided by twitter api. Here is the sample data of 2 lines</p>
<pre><code>{'country': 'United Kingdom', 'full_name': 'Dorridge, England', 'id': '31fe56e2e7d5792a', 'country_code': 'GB', 'name': 'Dorridge', 'attributes': {}, 'contained_within': [], 'place_type': 'city', 'bounding_box': {'coordinates': [[[-1.7718518, 52.3635912], [-1.7266702, 52.3635912], [-1.7266702, 52.4091167], [-1.7718518, 52.4091167]]], 'type': 'Polygon'}, 'url': 'https://api.twitter.com/1.1/geo/id/31fe56e2e7d5792a.json'}
{'country': 'India', 'full_name': 'New Delhi, India', 'id': '317fcc4b21a604d5', 'country_code': 'IN', 'name': 'New Delhi', 'attributes': {}, 'contained_within': [], 'place_type': 'city', 'bounding_box': {'coordinates': [[[76.84252, 28.397657], [77.347652, 28.397657], [77.347652, 28.879322], [76.84252, 28.879322]]], 'type': 'Polygon'}, 'url': 'https://api.twitter.com/1.1/geo/id/317fcc4b21a604d5.json'}
</code></pre>
<p>I want 'country', 'name' and 'cordinates' filed of each line.In order to do this we need to iterate line by line the entire file.so i append each line to a list</p>
<pre><code>data = []
with open('place.txt','r') as f:
for line in f:
data.append(line)
</code></pre>
<p>when i checked the data type it shows as 'str' instead of 'dict'.</p>
<pre><code>type(data[0])
str
data[0].keys()
AttributeError: 'str' object has no attribute 'keys'
</code></pre>
<p>how to fix this so that it can be saved as list of dictionaries.</p>
<p>Originally tweets were encoded and decoded by following code:</p>
<pre><code>f.write(jsonpickle.encode(tweet._json, unpicklable=False) + '\n') #encoded and saved to a .txt file
tweets.append(jsonpickle.decode(line)) # decoding
</code></pre>
<p>And place data file is saved by following code:</p>
<pre><code>fName = "place.txt"
newLine = "\n"
with open(fName, 'a', encoding='utf-8') as f:
for i in range(len(tweets)):
f.write('{}'.format(tweets[i]['place']) +'\n')
</code></pre>
| 0 | 2016-10-12T19:03:26Z | 40,006,896 | <blockquote>
<p>Note: Single quotes are not valid JSON.</p>
</blockquote>
<p>I have never tried Twitter API. Looks like your data are not valid JSON. Here is a simple preprocess method to replace <code>'</code>(single quote) into <code>"</code>(double quote)</p>
<pre><code>data = "{'country': 'United Kingdom', ... }"
json_data = data.replace('\'', '\"')
dict_data = json.loads(json_data)
dict_data.keys()
# [u'full_name', u'url', u'country', ... ]
</code></pre>
| 1 | 2016-10-12T19:33:10Z | [
"python",
"dictionary"
] |
Converting to list of dictionary | 40,006,439 | <p>I have a text file filled with place data provided by twitter api. Here is the sample data of 2 lines</p>
<pre><code>{'country': 'United Kingdom', 'full_name': 'Dorridge, England', 'id': '31fe56e2e7d5792a', 'country_code': 'GB', 'name': 'Dorridge', 'attributes': {}, 'contained_within': [], 'place_type': 'city', 'bounding_box': {'coordinates': [[[-1.7718518, 52.3635912], [-1.7266702, 52.3635912], [-1.7266702, 52.4091167], [-1.7718518, 52.4091167]]], 'type': 'Polygon'}, 'url': 'https://api.twitter.com/1.1/geo/id/31fe56e2e7d5792a.json'}
{'country': 'India', 'full_name': 'New Delhi, India', 'id': '317fcc4b21a604d5', 'country_code': 'IN', 'name': 'New Delhi', 'attributes': {}, 'contained_within': [], 'place_type': 'city', 'bounding_box': {'coordinates': [[[76.84252, 28.397657], [77.347652, 28.397657], [77.347652, 28.879322], [76.84252, 28.879322]]], 'type': 'Polygon'}, 'url': 'https://api.twitter.com/1.1/geo/id/317fcc4b21a604d5.json'}
</code></pre>
<p>I want 'country', 'name' and 'cordinates' filed of each line.In order to do this we need to iterate line by line the entire file.so i append each line to a list</p>
<pre><code>data = []
with open('place.txt','r') as f:
for line in f:
data.append(line)
</code></pre>
<p>when i checked the data type it shows as 'str' instead of 'dict'.</p>
<pre><code>type(data[0])
str
data[0].keys()
AttributeError: 'str' object has no attribute 'keys'
</code></pre>
<p>how to fix this so that it can be saved as list of dictionaries.</p>
<p>Originally tweets were encoded and decoded by following code:</p>
<pre><code>f.write(jsonpickle.encode(tweet._json, unpicklable=False) + '\n') #encoded and saved to a .txt file
tweets.append(jsonpickle.decode(line)) # decoding
</code></pre>
<p>And place data file is saved by following code:</p>
<pre><code>fName = "place.txt"
newLine = "\n"
with open(fName, 'a', encoding='utf-8') as f:
for i in range(len(tweets)):
f.write('{}'.format(tweets[i]['place']) +'\n')
</code></pre>
| 0 | 2016-10-12T19:03:26Z | 40,007,167 | <p>You should use python json library for parsing and getting the value.
In python it's quite easy.</p>
<pre><code>import json
x = '{"country": "United Kingdom", "full_name": "Dorridge, England", "id": "31fe56e2e7d5792a", "country_code": "GB", "name": "Dorridg", "attributes": {}, "contained_within": [], "place_type": "city", "bounding_box": {"coordinates": [[[-1.7718518, 52.3635912], [-1.7266702, 52.3635912], [-1.7266702, 52.4091167], [-1.7718518, 52.4091167]]], "type": "Polygon"}, "url": "https://api.twitter.com/1.1/geo/id/31fe56e2e7d5792a.json"}'
y = json.loads(x)
print(y["country"],y["name"],y["bounding_box"]["coordinates"])
</code></pre>
| 1 | 2016-10-12T19:51:42Z | [
"python",
"dictionary"
] |
How to test if WindowStaysOnTopHint flag is set in windowFlags? | 40,006,533 | <p>Is this supposed to return a boolean value?</p>
<pre><code>>>> win.windowFlags() & QtCore.Qt.WindowStaysOnTopHint
<PyQt4.QtCore.WindowFlags object at 0x7ad0578>
</code></pre>
<p>I already knew that</p>
<pre><code># enable always on top
win.windowFlags() | QtCore.Qt.WindowStaysOnTopHint
# disable it
win.windowFlags() & ~QtCore.Qt.WindowStaysOnTopHint
# toggle it
win.windowFlags() ^ QtCore.Qt.WindowStaysOnTopHint
</code></pre>
| 1 | 2016-10-12T19:09:48Z | 40,007,740 | <p>The <code>WindowFlags</code> object is an OR'd together set of flags from the <code>WindowType</code> enum. The <code>WindowType</code> is just a subclass of <code>int</code>, and the <code>WindowFlags</code> object also supports <code>int</code> operations.</p>
<p>You can test for the presence of a flag like this:</p>
<pre><code>>>> bool(win.windowFlags() & QtCore.Qt.WindowStaysOnTopHint)
False
</code></pre>
<p>or like this:</p>
<pre><code>>>> int(win.windowFlags() & QtCore.Qt.WindowStaysOnTopHint) != 0
False
</code></pre>
<p>In general, <code>&</code> returns the value itself when present, or zero when absent:</p>
<pre><code>>>> flags = 1 | 2 | 4
>>> flags
7
>>> flags & 2
2
>>> flags & 8
0
</code></pre>
| 1 | 2016-10-12T20:26:19Z | [
"python",
"pyqt",
"bit-manipulation",
"flags",
"always-on-top"
] |
subplot2grid with seaborn overwrites same ax | 40,006,587 | <p>What is the correct way of specifying the ax where I want a chart to go?</p>
<p>Currently I'm trying to plot different heatmaps, each one in a different ax. But when trying this it just plots the 2 charts one on top of the other. </p>
<pre><code>import seaborn as sns
import matplotlib.pyplot as plt
fig3 = plt.figure(figsize=(12,10))
ax1 = plt.subplot2grid((11,2),(0,0), rowspan=3, colspan=1)
ax2 = plt.subplot2grid((11,2),(4,0), rowspan=3, colspan=1)
ax1 = sns.heatmap(dict_pivots['df_pivot_10_win_2_thres'], square=False, cmap="RdYlBu",
linewidths=0.1, annot=True, annot_kws={"size":12})
ax2 = sns.heatmap(dict_pivots['df_pivot_5_win_2_thres'], square=False, cmap="RdYlBu",
linewidths=0.1, annot=True, annot_kws={"size":12})
</code></pre>
<p>and this is how it looks:
<a href="https://i.stack.imgur.com/n0WMZ.png" rel="nofollow"><img src="https://i.stack.imgur.com/n0WMZ.png" alt="enter image description here"></a></p>
| 0 | 2016-10-12T19:12:44Z | 40,090,122 | <p>You just need to pass your Axes objects to the <code>heatmap</code> function:</p>
<pre><code>import seaborn as sns
import matplotlib.pyplot as plt
fig3 = plt.figure(figsize=(12,10))
ax1 = plt.subplot2grid((11,2),(0,0), rowspan=3, colspan=1)
ax2 = plt.subplot2grid((11,2),(4,0), rowspan=3, colspan=1)
ax1 = sns.heatmap(dict_pivots['df_pivot_10_win_2_thres'],
square=False, cmap="RdYlBu",
linewidths=0.1, annot=True,
annot_kws={"size":12},
ax=ax1) # <-- here
ax2 = sns.heatmap(dict_pivots['df_pivot_5_win_2_thres'],
square=False, cmap="RdYlBu",
linewidths=0.1, annot=True,
annot_kws={"size":12},
ax=ax2) # <-- and here
</code></pre>
| 0 | 2016-10-17T15:20:11Z | [
"python",
"matplotlib",
"seaborn"
] |
Get count of list items that meet a condition with Jinja2 | 40,006,617 | <p>I have a list of dictionaries where each dict has a boolean entry. I want to display the items that are <code>True</code>, along with the count of those items. I'm using the <code>selectattr</code> filter, but it returns a generator, and calling <code>|length</code> on it raise an error. How can I get the length of the items returned from <code>selectattr</code> in Jinja?</p>
<pre><code>my_list = [{foo=False, ...}, {foo=True, ...}, ...]
</code></pre>
<pre><code>{{ my_list|selectattr('foo', 'equalto', True)|length }}
</code></pre>
| 1 | 2016-10-12T19:14:07Z | 40,006,705 | <p>There is a <code>list</code> filter that will transform a generator into a list. So:</p>
<pre><code>{{ my_list|selectattr('foo')|list|length }}
</code></pre>
| 3 | 2016-10-12T19:20:09Z | [
"python",
"flask",
"jinja2"
] |
Passing an array where single value is expected? | 40,006,652 | <p>I am trying to implement simple optimization problem in Python. I am currently struggling with the following error:</p>
<p><strong>Value Error</strong>: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()</p>
<p>As far as I understand, this means that I am somewhere trying to plug in an array where only single value can be accepted. Nevertheless, I haven't managed to come up with a solution, nor have I discovered where is the problem.</p>
<p>My code follows</p>
<pre><code>def validationCurve(X, y, Xval, yval):
#[lmbda_vec, error_train, error_val] =
# VALIDATIONCURVE(X, y, Xval, yval) returns the train and
# validation errors (in error_train, error_val) for different
# values of lmbda. Given the training set (X,y) and validation
# set (Xval, yval).
lmbda_vec = [0, 0.001, 0.003, 0.01, 0.03, 0.1, 0.3, 1];
m = len(y);
X = numpy.concatenate((numpy.ones((m,1)), X), axis = 1);
n = len(Xval);
Xval = numpy.concatenate((numpy.ones((n,1)), Xval), axis = 1);
error_train = numpy.zeros((len(lmbda_vec), 1));
error_val = numpy.zeros((len(lmbda_vec), 1));
for i in range(0,len(lmbda_vec)):
lmbda = lmbda_vec[i];
theta = trainLinearReg(X, y, lmbda);
error_train[i] = linearRegCostFunction(X, y, theta, lmbda);
error_val[i] = linearRegCostFunction(Xval, yval, theta, lmbda);
return lmbda_vec, error_train, error_val
def trainLinearReg(X, y, lmbda):
#[theta] = TRAINLINEARREG (X, y, lmbda) trains linear
# regression usingthe dataset (X, y) and regularization
# parameter lmbda. Returns the trained parameters theta.
alpha = 1 # learning rate
num_iters = 200 # number of iterations
initial_theta = (numpy.zeros((len(X[0,:]),1))) #initial guess
#Create "short hand" for the cost function to be minimized
costFunction = lambda t: linearRegCostFunction(X, y, t, lmbda);
#Minimize using Conjugate Gradient
theta = minimize(costFunction, initial_theta, method = 'Newton-CG',
jac = True, options = {'maxiter': 200})
return theta
def linearRegCostFunction(X, y, theta, lmbda):
# [J, grad] = LINEARREGCOSTFUNCTION(X, y, theta, lmbda)
# computes the cost of using theta as the parameter for
# linear regression to fit the data points in X and y.
# Returns the cost in J and the gradient in grad.
# Initialize some useful values
m, n = X.shape; # number of training examples
J = 0;
grad = numpy.zeros((n ,1))
J = numpy.dot((y- X @ theta).T, (y-X @ theta)) +
lmbda*(theta[1:].T @ theta[1:])
J = J/m
grad = (X.T @ (y - X @ theta))/m
grad [1:] += (lmbda*theta[1:])/m
grad = grad[:];
return grad
</code></pre>
<p>I am trying to obtain an optimal regularization parameter by computing cost function and minimizing with respect to theta.
My input values are:</p>
<pre><code>X.shape = (100,25), y.shape = (100,1)
Xval.shape = (55,25), yval.shape = (55,1)
</code></pre>
<p>Outputted errors are:</p>
<pre><code> --> 129 lmbda_vec , error_train, error_val = validationCurve(Xtrain, ytrain, Xva
lid, yvalid )
---> 33 theta = trainLinearReg(X, y, lmbda);
---> 49 theta = minimize(costFunction, initial_theta,
method = 'Newton-CG', jac = True, options = {'maxiter': 200})
</code></pre>
<p>Later I won't to use the optimized model to predict y on new X.
<strong>Could you please advice me where is the problem in my code?</strong></p>
<p>Also, if you observe any points for improvement in my code, please let me know. I will be glad to hear and improve.</p>
<p>Thank you!</p>
| -1 | 2016-10-12T19:16:11Z | 40,009,140 | <p>Nimitz14 hit the general explanation: you've supplied an array where a scalar is required. This caused a run-time error. The problem is how to fix it from here.</p>
<p>First, try slapping your favourite debugger on the problem, so you can stop the program at useful spots and figure out exactly <em>what</em> array is causing the problem. This should help you determine where it originated.</p>
<p>Failing that, place some strategic print statements along the call route, printing each argument just before the function call. Then examine the signature (call sequence) of each function, and see where you might have given an array in place of a scalar. I don't see it, but ...</p>
<p>Is it possible that you've somehow redefined <strong>True</strong> as an array?</p>
| 0 | 2016-10-12T22:04:38Z | [
"python",
"numpy",
"machine-learning",
"scipy",
"regression"
] |
How to check if command were done? | 40,006,653 | <p>I'am trying to do some stuff with git. I wonder how would I make the <strong>if statement</strong> argument to check if that command were done correctly:</p>
<pre><code>git checkout master && git reset --hard && git fetch && git pull
</code></pre>
<p>I was trying with check if output is equal to if statement but I guess it's a bad idea. Here is a code:</p>
<pre><code>#!/usr/bin/python3
import os
import subprocess
import time
while True:
x = subprocess.getoutput("git checkout master && git reset --hard && git fetch && git pull")
if x is "Some text":
print('Some actions there')
time.sleep(3600)
</code></pre>
<p>So I wonder is there any way to check if command where done or not.</p>
| 0 | 2016-10-12T19:16:15Z | 40,007,143 | <p>Use <a href="https://docs.python.org/3/library/subprocess.html" rel="nofollow">subprocess</a> module, but execute each of your command with <a href="https://docs.python.org/3/library/subprocess.html#subprocess.Popen" rel="nofollow">Popen</a> or <a href="https://docs.python.org/3/library/subprocess.html#subprocess.run" rel="nofollow">run</a>. I would recommend the latter, as its returned type has useful <a href="https://docs.python.org/3/library/subprocess.html#subprocess.CompletedProcess.check_returncode" rel="nofollow">check_returncode()</a> method. Use <a href="https://docs.python.org/3/library/shlex.html#shlex.split" rel="nofollow">shlex.split()</a> to turn command into list of its parts.</p>
<p>Basically what you want to do is something like:</p>
<pre><code>import subprocess, shlex
for (cmd in ("git checkout master", "git reset --hard", "git fetch", "git pull")):
subprocess.run(shlex.split(cmd)).check_returncode()
</code></pre>
<p>Disclaimer: this was written ad-hoc and not tested. It is only supposed to show you how to get there, not do that for you all the way.</p>
| 0 | 2016-10-12T19:50:26Z | [
"python",
"linux",
"python-3.x"
] |
How to find the mean of a list | 40,006,697 | <p>I'm very new to python and trying to write some code so that the user enters something. If it's an integer it's sorted into the Numbers list, if it's a string it goes into the String list. </p>
<p>I want to be able to find the mean of all the numbers that are in the list and print out the result.
And in the String section I want to be able to print out everything within the string and its length.
User types 'save' to exit and if input is valid that's caught.</p>
<pre><code>Numbers = []
String = []
while(True):
user_input = input("What's your input? ")
if user_input == "save":
break
elif user_input.isdigit():
Numbers.append(user_input)
for i in range(len(Numbers)):
Numbers[i] = int(Numbers[i])
print(sum(Numbers)/len(Numbers)
elif isinstance(user_input, str):
String.append(user_input)
print(String)
print (len(String)-1)
else:
print("Invalid input.")
break
</code></pre>
| 0 | 2016-10-12T19:19:18Z | 40,006,745 | <p>You are using <code>Length</code>, which has not been defined. I think what you wanted was</p>
<pre><code>print(sum(Numbers)/len(Numbers))
</code></pre>
<p>and you probably don't want it inside the loop, but just after it (although that might be another typo).</p>
| 0 | 2016-10-12T19:22:50Z | [
"python",
"list",
"python-3.x"
] |
How to find the mean of a list | 40,006,697 | <p>I'm very new to python and trying to write some code so that the user enters something. If it's an integer it's sorted into the Numbers list, if it's a string it goes into the String list. </p>
<p>I want to be able to find the mean of all the numbers that are in the list and print out the result.
And in the String section I want to be able to print out everything within the string and its length.
User types 'save' to exit and if input is valid that's caught.</p>
<pre><code>Numbers = []
String = []
while(True):
user_input = input("What's your input? ")
if user_input == "save":
break
elif user_input.isdigit():
Numbers.append(user_input)
for i in range(len(Numbers)):
Numbers[i] = int(Numbers[i])
print(sum(Numbers)/len(Numbers)
elif isinstance(user_input, str):
String.append(user_input)
print(String)
print (len(String)-1)
else:
print("Invalid input.")
break
</code></pre>
| 0 | 2016-10-12T19:19:18Z | 40,006,784 | <p>There is good thing called <a href="https://docs.python.org/3/library/statistics.html#statistics.mean" rel="nofollow"><code>statistics.mean</code></a>:</p>
<pre><code>from statistics import mean
mean(your_list)
</code></pre>
| 1 | 2016-10-12T19:25:09Z | [
"python",
"list",
"python-3.x"
] |
How to find the mean of a list | 40,006,697 | <p>I'm very new to python and trying to write some code so that the user enters something. If it's an integer it's sorted into the Numbers list, if it's a string it goes into the String list. </p>
<p>I want to be able to find the mean of all the numbers that are in the list and print out the result.
And in the String section I want to be able to print out everything within the string and its length.
User types 'save' to exit and if input is valid that's caught.</p>
<pre><code>Numbers = []
String = []
while(True):
user_input = input("What's your input? ")
if user_input == "save":
break
elif user_input.isdigit():
Numbers.append(user_input)
for i in range(len(Numbers)):
Numbers[i] = int(Numbers[i])
print(sum(Numbers)/len(Numbers)
elif isinstance(user_input, str):
String.append(user_input)
print(String)
print (len(String)-1)
else:
print("Invalid input.")
break
</code></pre>
| 0 | 2016-10-12T19:19:18Z | 40,006,897 | <pre><code>#use isalpha to check enterted input is string or not
#isalpha returns a boolean value
Numbers = []
String = []
while(True):
user_input = input("input : ")
if user_input == "save":
break
elif user_input.isdigit():
Numbers.append(int(user_input))
print(sum(Numbers)/len(Numbers))
elif user_input.isalpha():
String.append(user_input)
print(String)
print (len(String))
else:
print("Invalid input.")
break
</code></pre>
| 1 | 2016-10-12T19:33:15Z | [
"python",
"list",
"python-3.x"
] |
Sarsa algorithm, why Q-values tend to zero? | 40,006,763 | <p>I'm trying to implement Sarsa algorithm for solving a Frozen Lake environment from OpenAI gym. I've started soon to work with this but I think I understand it. </p>
<p>I also understand how Sarsa algorithm works, there're many sites where to find a pseudocode, and I get it. I've implemented this algorithm in my problem following all the steps, but when I check the final Q function after all the episodes I notice that all values tend to zero and I don't know why.</p>
<p>Here is my code, I hope someone can tell me why that happens.</p>
<pre><code>import gym
import random
import numpy as np
env = gym.make('FrozenLake-v0')
#Initialize the Q matrix 16(rows)x4(columns)
Q = np.zeros([env.observation_space.n, env.action_space.n])
for i in range(env.observation_space.n):
if (i != 5) and (i != 7) and (i != 11) and (i != 12) and (i != 15):
for j in range(env.action_space.n):
Q[i,j] = np.random.rand()
#Epsilon-Greedy policy, given a state the agent chooses the action that it believes has the best long-term effect with probability 1-eps, otherwise, it chooses an action uniformly at random. Epsilon may change its value.
bestreward = 0
epsilon = 0.1
discount = 0.99
learning_rate = 0.1
num_episodes = 50000
a = [0,0,0,0,0,0,0,0,0,0]
for i_episode in range(num_episodes):
# Observe current state s
observation = env.reset()
currentState = observation
# Select action a using a policy based on Q
if np.random.rand() <= epsilon: #pick randomly
currentAction = random.randint(0,env.action_space.n-1)
else: #pick greedily
currentAction = np.argmax(Q[currentState, :])
totalreward = 0
while True:
env.render()
# Carry out an action a
observation, reward, done, info = env.step(currentAction)
if done is True:
break;
# Observe reward r and state s'
totalreward += reward
nextState = observation
# Select action a' using a policy based on Q
if np.random.rand() <= epsilon: #pick randomly
nextAction = random.randint(0,env.action_space.n-1)
else: #pick greedily
nextAction = np.argmax(Q[nextState, :])
# update Q with Q-learning
Q[currentState, currentAction] += learning_rate * (reward + discount * Q[nextState, nextAction] - Q[currentState, currentAction])
currentState = nextState
currentAction = nextAction
print "Episode: %d reward %d best %d epsilon %f" % (i_episode, totalreward, bestreward, epsilon)
if totalreward > bestreward:
bestreward = totalreward
if i_episode > num_episodes/2:
epsilon = epsilon * 0.9999
if i_episode >= num_episodes-10:
a.insert(0, totalreward)
a.pop()
print a
for i in range(env.observation_space.n):
print "-----"
for j in range(env.action_space.n):
print Q[i,j]
</code></pre>
| 3 | 2016-10-12T19:23:48Z | 40,016,555 | <p>When a episode ends you are breaking the while loop before updating the Q function. Therefore, when the reward received by the agent is different from zero (the agent has reached the goal state), the Q function is never updated in that reward.</p>
<p>You should check for the end of the episode in the last part of the while loop.</p>
| 1 | 2016-10-13T08:59:38Z | [
"python",
"reinforcement-learning",
"sarsa"
] |
ActiveMQ Java Broker, Python Client | 40,006,811 | <p>I have for legacy reasons a Java activeMQ implementation of the Broker/Publisher over vanilla tcp transport protocol. I wish to connect a Python client to it, however all the "stomp" based documentation doesn't seem to have it, not over the stomp protcol, and when I try the basic examples I get the error on the Java Broker side:</p>
<pre><code>[ActiveMQ Transport: tcp:///127.0.0.1:62860@5001] WARN org.apache.activemq.broker.TransportConnection.Transport - Transport Connection to: tcp://127.0.0.1:62860 failed: java.io.IOException: Unknown data type: 80
</code></pre>
<p>The Broker code is very vanilla in Java:</p>
<pre><code> String localVMurl = "vm://localhost";
String remoterURL = "tcp://localhost:5001";
BrokerService broker = new BrokerService();
broker.addConnector(localVMurl);
broker.addConnector(remoterURL);
broker.setAdvisorySupport(true);
broker.start();
ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(localVMurl+"?create=false");
Connection connection = connectionFactory.createConnection();
</code></pre>
<p>and the Python just fails. I can't seem to find anything online using just basic "tcp://localhost:" connections from Python. Am I doing something wrong here? </p>
<pre><code>import stomp
class MyListener(stomp.ConnectionListener):
def on_error(self, headers, message):
print('received an error "%s"' % message)
def on_message(self, headers, message):
print('received a message "%s"' % message)
conn = stomp.Connection(host_and_ports = [('localhost', 5001)])
conn.start()
conn.connect('admin', 'password', wait=True)
</code></pre>
<p>and I get the error:</p>
<pre><code>IndexError: list index out of range
</code></pre>
| 0 | 2016-10-12T19:26:41Z | 40,009,001 | <p>Without seeing the broker configuration it is a bit tricky to answer but from the error I'd guess you are trying to connect a STOMP client to the OpenWire transport which won't work, you need to have a STOMP TransportConnector configured on the broker and point the STOMP client there.</p>
<p>See the <a href="http://activemq.apache.org/stomp.html" rel="nofollow">ActiveMQ STOMP</a> documentation.</p>
<p>To add STOMP support for an embedded broker you'd do something along the lines of:</p>
<pre><code>brokerService.addConnector("stomp://0.0.0.0:61613");
</code></pre>
| 0 | 2016-10-12T21:53:24Z | [
"java",
"python",
"tcp",
"activemq",
"stomp"
] |
cannot install python using brew | 40,006,880 | <p>Trying to install python using the following command:</p>
<p><code>brew install python</code></p>
<p>But unfortunately I am getting the following error:</p>
<pre><code>>brew install python
==> Downloading https://homebrew.bintray.com/bottles/python-2.7.12_2.el_capitan.
Already downloaded: /Users/maguerra/Library/Caches/Homebrew/python-2.7.12_2.el_capitan.bottle.tar.gz
==> Pouring python-2.7.12_2.el_capitan.bottle.tar.gz
==> Using the sandbox
==> /usr/local/Cellar/python/2.7.12_2/bin/python -s setup.py --no-user-cfg insta
Last 15 lines from /Users/maguerra/Library/Logs/Homebrew/python/post_install.01.python:
copying setuptools/command/rotate.py -> build/lib/setuptools/command
copying setuptools/command/saveopts.py -> build/lib/setuptools/command
copying setuptools/command/sdist.py -> build/lib/setuptools/command
copying setuptools/command/setopt.py -> build/lib/setuptools/command
copying setuptools/command/test.py -> build/lib/setuptools/command
copying setuptools/command/upload.py -> build/lib/setuptools/command
copying setuptools/command/upload_docs.py -> build/lib/setuptools/command
creating build/lib/setuptools/extern
copying setuptools/extern/__init__.py -> build/lib/setuptools/extern
copying setuptools/script (dev).tmpl -> build/lib/setuptools
copying setuptools/script.tmpl -> build/lib/setuptools
running install_lib
copying build/lib/easy_install.py -> /usr/local/lib/python2.7/site-packages
copying build/lib/pkg_resources/__init__.py -> /usr/local/lib/python2.7/site-packages/pkg_resources
error: [Errno 13] Permission denied: '/usr/local/lib/python2.7/site- packages/pkg_resources/__init__.py'
Warning: The post-install step did not complete successfully
You can try again using `brew postinstall python`
==> Caveats
Pip and setuptools have been installed. To update them
pip install --upgrade pip setuptools
You can install Python packages with
pip install <package>
They will install into the site-package directory
/usr/local/lib/python2.7/site-packages
See: https://github.com/Homebrew/brew/blob/master/docs/Homebrew-and Python.md
.app bundles were installed.
Run `brew linkapps python` to symlink these to /Applications.
==> Summary
í ¼í½º /usr/local/Cellar/python/2.7.12_2: 3,150 files, 42.5M
</code></pre>
<p>Has anyone seen this before, or now how to address this issue in order to complete the python installation process? </p>
| 0 | 2016-10-12T19:32:01Z | 40,015,590 | <p>The error message says you donât have permission to write under <code>/usr/local/lib/python2.7/site-packages/pkg_resources</code>.</p>
<p>The following steps should work:</p>
<ol>
<li><p>Remove your broken Python install:</p>
<pre><code>brew uninstall python
</code></pre></li>
<li><p>Ensure you own that directory:</p>
<pre><code>sudo chown -R $(whoami):admin /usr/local/lib/python2.7/site-packages
</code></pre></li>
<li><p>Retry:</p>
<pre><code>brew install python
</code></pre></li>
</ol>
| 0 | 2016-10-13T08:10:29Z | [
"python",
"install",
"homebrew"
] |
Table contents missing during extraction with selenium and phantomjs | 40,006,881 | <p>I am trying to extract data from the following table. However, the program returns an empty table with the "/table>". Notice that there are two classes with tbpopt, hence I am using "style" as an additional descriptor for the second one. The first tblopt shows up fine, the problem is with the second one. Thanks in advance.</p>
<pre><code>import time; import os; import os.path
import pandas as pd
from bs4 import BeautifulSoup, Tag
from selenium import webdriver
from selenium.webdriver.support.ui import Select
browser = webdriver.PhantomJS(r'C:\Users\abdurrub\Anaconda3\Scripts\phantomjs.exe')
browser.get('http://www.moneycontrol.com/stocks/fno/view_option_chain.php')
time.sleep(2)
soup = BeautifulSoup(browser.page_source, "lxml")
table = soup.select_one("table.tblopt")
print(soup.find('table', attrs={'class':'tblopt', 'style' :'width:100%;*width:100%'}))
</code></pre>
<p>My output is</p>
<pre><code><table border="0" cellpadding="0" cellspacing="0" class="tblopt" style="width:100%;*width:100%">
</table>
</code></pre>
| 0 | 2016-10-12T19:32:03Z | 40,007,628 | <p>If there are always two tables of <code>class='tblopt'</code> you could do something along the lines of:</p>
<pre><code>from selenium import webdriver
from bs4 import BeautifulSoup
if __name__ == '__main__':
url = 'http://www.moneycontrol.com/stocks/fno/view_option_chain.php?sc_id=IRI&sel_exp_date=2016-10-27'
driver = webdriver.PhantomJS('<yourPathToPhantomJS>')
driver.get(url)
html = driver.page_source
soup = BeautifulSoup(html)
tbls = soup.find_all('table', {'class': 'tblopt'})
print(tbls[0].get_text())
print(tbls[1].get_text())
</code></pre>
| 1 | 2016-10-12T20:19:11Z | [
"python",
"selenium",
"web-scraping",
"phantomjs"
] |
Find integer row-index from pandas index | 40,006,902 | <p>The following code find index where df['A'] == 1</p>
<pre><code>import pandas as pd
import numpy as np
import random
index = range(10)
random.shuffle(index)
df = pd.DataFrame(np.zeros((10,1)).astype(int), columns = ['A'], index = index)
df.A.iloc[3:6] = 1
df.A.iloc[6:] = 2
print df
print df.loc[df['A'] == 1].index.tolist()
</code></pre>
<p>It returns pandas index correctly. How do I get the integer index ([3,4,5]) instead using pandas API?</p>
<pre><code> A
8 0
4 0
6 0
3 1
7 1
1 1
5 2
0 2
2 2
9 2
[3, 7, 1]
</code></pre>
| 1 | 2016-10-12T19:33:25Z | 40,007,069 | <p>No need for numpy, you're right. Just pure python with a listcomp:</p>
<p>Just find the indexes where the values are 1</p>
<pre><code>print([i for i,x in enumerate(df['A'].values) if x == 1])
</code></pre>
| 1 | 2016-10-12T19:44:48Z | [
"python",
"pandas",
"dataframe",
"row",
"indices"
] |
Find integer row-index from pandas index | 40,006,902 | <p>The following code find index where df['A'] == 1</p>
<pre><code>import pandas as pd
import numpy as np
import random
index = range(10)
random.shuffle(index)
df = pd.DataFrame(np.zeros((10,1)).astype(int), columns = ['A'], index = index)
df.A.iloc[3:6] = 1
df.A.iloc[6:] = 2
print df
print df.loc[df['A'] == 1].index.tolist()
</code></pre>
<p>It returns pandas index correctly. How do I get the integer index ([3,4,5]) instead using pandas API?</p>
<pre><code> A
8 0
4 0
6 0
3 1
7 1
1 1
5 2
0 2
2 2
9 2
[3, 7, 1]
</code></pre>
| 1 | 2016-10-12T19:33:25Z | 40,007,111 | <p>Here is one way:</p>
<pre><code>df.reset_index().index[df.A == 1].tolist()
</code></pre>
<p>This re-indexes the data frame with <code>[0, 1, 2, ...]</code>, then extracts the integer index values based on the boolean mask <code>df.A == 1</code>.</p>
<hr>
<p><strong>Edit</strong> Credits to @Max for the <code>index[df.A == 1]</code> idea.</p>
| 1 | 2016-10-12T19:48:09Z | [
"python",
"pandas",
"dataframe",
"row",
"indices"
] |
Find integer row-index from pandas index | 40,006,902 | <p>The following code find index where df['A'] == 1</p>
<pre><code>import pandas as pd
import numpy as np
import random
index = range(10)
random.shuffle(index)
df = pd.DataFrame(np.zeros((10,1)).astype(int), columns = ['A'], index = index)
df.A.iloc[3:6] = 1
df.A.iloc[6:] = 2
print df
print df.loc[df['A'] == 1].index.tolist()
</code></pre>
<p>It returns pandas index correctly. How do I get the integer index ([3,4,5]) instead using pandas API?</p>
<pre><code> A
8 0
4 0
6 0
3 1
7 1
1 1
5 2
0 2
2 2
9 2
[3, 7, 1]
</code></pre>
| 1 | 2016-10-12T19:33:25Z | 40,007,170 | <p>what about?</p>
<pre><code>In [12]: df.index[df.A == 1]
Out[12]: Int64Index([3, 7, 1], dtype='int64')
</code></pre>
<p>or (depending on your goals):</p>
<pre><code>In [15]: df.reset_index().index[df.A == 1]
Out[15]: Int64Index([3, 4, 5], dtype='int64')
</code></pre>
<p>Demo:</p>
<pre><code>In [11]: df
Out[11]:
A
8 0
4 0
6 0
3 1
7 1
1 1
5 2
0 2
2 2
9 2
In [12]: df.index[df.A == 1]
Out[12]: Int64Index([3, 7, 1], dtype='int64')
In [15]: df.reset_index().index[df.A == 1]
Out[15]: Int64Index([3, 4, 5], dtype='int64')
</code></pre>
| 3 | 2016-10-12T19:51:50Z | [
"python",
"pandas",
"dataframe",
"row",
"indices"
] |
waitforbuttonpress() matplotlib possible bug | 40,006,924 | <p>Consider a refreshed figure inside a loop as per the following code:</p>
<pre><code>import matplotlib.pyplot as plt
def fun_example():
plt.ion()
for ite in range(3):
x = np.linspace(-2,6,100)
y = (ite+1)*x
figura = plt.figure(1)
plt.plot(x,y,'-b')
plt.waitforbuttonpress()
plt.close()
#endfor ite
#enddef fun_example
if __name__ == '__main__':
fun_example()
#endif main
</code></pre>
<p>The idea is to inspect the figure with the mouse (for example, during debugging use the zoom option in the toolbar of the figure), and once it is done, press a button to go on with the code. At least in my case (windows 7, python 3.4.4, spyder 3.0.0dev), if I intend to mouse click in the graph for zooming, the effect is the same than press-button. In other words <em>waitforbuttonpress()</em> returns <em>True</em>, and the figure is gone.</p>
<p>Any suggestion? might it be a bug? Thank all of you in advance.</p>
| 0 | 2016-10-12T19:34:45Z | 40,006,994 | <p>As per <a href="http://matplotlib.org/api/figure_api.html#matplotlib.figure.Figure.waitforbuttonpress" rel="nofollow">the documentation</a>, <code>.waitforbuttonpress()</code> will return <code>True</code> if a key was pressed, and <code>False</code> if a mouse button was pressed. Therefore, what you want is probably something like this:</p>
<pre><code>while True:
if plt.waitforbuttonpress():
break
</code></pre>
| 1 | 2016-10-12T19:39:28Z | [
"python",
"matplotlib",
"figure"
] |
PySpark: How to write a Spark dataframe having a column with type SparseVector into CSV file? | 40,006,929 | <p>I have a spark dataframe which has one column with type spark.mllib.linalg.SparseVector:</p>
<p>1) how can I write it into a csv file?</p>
<p>2) how can I print all the vectors?</p>
| 2 | 2016-10-12T19:35:18Z | 40,008,799 | <ol>
<li><a href="https://github.com/databricks/spark-csv" rel="nofollow">https://github.com/databricks/spark-csv</a></li>
<li><p><code>df2 = df1.map(lambda row: row.yourVectorCol)</code></p>
<p>OR <code>df1.map(lambda row: row[1])</code></p>
<p>where you either have a named column or just refer to the column by its position in the row.</p>
<p>Then, to <em>print</em> it, you can <code>df2.collect()</code></p></li>
</ol>
<p>Without more information, this may be helpful to you, or not helpful enough to you. Please elaborate a bit.</p>
| 0 | 2016-10-12T21:38:57Z | [
"python",
"apache-spark",
"pyspark"
] |
has no attribute validate_on_submit: How to use wtforms-alchemy's ModelForm in a flask handler / view | 40,006,943 | <p>I'm trying to switch <code>from wtforms.ext.sqlalchemy.orm import model_form</code> to using wtforms_alchemy ModelForm: </p>
<pre><code>from wtforms_alchemy import ModelForm
</code></pre>
<p>I'm failing miserably... and I've been unsuccessful searching for a working example of that uses wtforms_alchemy which shows both the handler and the model.</p>
<p>Using model_form works for me: Here's my working code using model forms:</p>
<p><strong>The model script (python):</strong></p>
<pre><code>from app import db
class Test(db.Model):
id = db.Column(db.Integer, primary_key=True)
test1 = db.Column(db.String())
test2 = db.Column(db.String())
</code></pre>
<p><strong>The handler script (python, flask, model_form):</strong></p>
<pre><code>from flask.ext.wtf import Form
from wtforms.ext.sqlalchemy.orm import model_form
from wtforms import validators
from app import app
from app import db
from app.models import *
@app.route('/', methods=['GET', 'POST'])
@login_required
def index():
TestForm = model_form(Test, base_class = Form, db_session=db.session, field_args = {
'test1' : {
'validators' : [validators.Length(max=1)]
}
})
form = TestForm()
if form.validate_on_submit():
flash("success")
new_test = Test()
form.populate_obj(new_test)
db.session.add(new_test)
db.session.commit()
return redirect(url_for("index"))
return render_template("main.html", form=form)
</code></pre>
<p>The template (uses mako):</p>
<pre><code><form class="form" action="/" method="POST">
% for f in form:
%if f.widget.input_type != 'hidden':
<dt>${ f.label }</dt>
% endif
<dd>
${f}
% if f.errors:
<div class="flashes alert alert-danger">
<a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
% for e in f.errors:
<p>${e}</p>
% endfor
</div>
% endif
</dd>
% endfor
<input type="submit" value="go">
</form>
</code></pre>
<p>When I try to change my handler script page over to using ModelForm with this code (below) I get a <strong>'TestForm' object has no attribute 'validate_on_submit'</strong> error</p>
<p><strong>The handler script (python, flask, ModelForm):</strong></p>
<pre><code>from flask.ext.wtf import Form
from wtforms_alchemy import ModelForm
from wtforms import validators
from app import app
from app import db
from app.models import *
class TestForm(ModelForm):
class Meta:
model = Test
@app.route('/', methods=['GET', 'POST'])
@login_required
def index():
form = TestForm()
if form.validate_on_submit():
flash("success")
new_test = Test()
form.populate_obj(new_test)
db.session.add(new_test)
db.session.commit()
return redirect(url_for("index"))
return render_template("main.html", form=form)
</code></pre>
<p>What am I missing?</p>
| 0 | 2016-10-12T19:36:11Z | 40,028,029 | <p>Nevermind.</p>
<p>Although I had tried using</p>
<pre><code>from wtforms_alchemy import model_form_factory
</code></pre>
<p>prior to this post, it decided to work when I put it back, but after the ModelForm import instead of before it.</p>
<p>Whatever.</p>
| 0 | 2016-10-13T18:07:34Z | [
"python",
"sqlalchemy",
"flask-sqlalchemy",
"wtforms"
] |
Unwanted looping occurring on first function | 40,006,944 | <pre><code>def load():
name=0
count=0
totalpr=0
name=input("Enter stock name OR -999 to Quit: ")
while name != '-999':
count=count+1
shares=int(input("Enter number of shares: "))
pp=float(input("Enter purchase price: "))
sp=float(input("Enter selling price: "))
commission=float(input("Enter commission: "))
name=input("Enter stock name OR -999 to Quit: ")
def calc():
totalpr=0
amount_paid=shares*pp
commission_paid_purchase=amount_paid*commission
amount_sold=shares*sp
commission_paid_sale=amount_sold*commission
profit_loss=(amount_sold - commission_paid_sale) -(amount_paid + commission_paid_purchase)
totalpr=totalpr+profit_loss
def display():
print("\nStock Name:", name)
print("Amount paid for the stock: $", format(amount_paid, '10,.2f'))
print("Commission paid on the purchase: $", format(commission_paid_purchase, '10,.2f'))
print("Amount the stock sold for: $", format(amount_sold, '10,.2f'))
print("Commission paid on the sale: $", format(commission_paid_sale, '10,.2f'))
print("Profit (or loss if negative): $", format(profit_loss, '10,.2f'))
print("Total Profit is $", format(totalpr, '10,.2f'))
def main():
load()
calc()
display()
main()
</code></pre>
<p>Immediately after commission is entered, the program should run the calculations and display the information accordingly. But right now, it's simply looping and not displaying/calculating anything. </p>
<p>I would like to maintain the structure of program itself --</p>
<pre><code>def main():
load()
calc()
display()
</code></pre>
<p>But there is something else impeding the program from carrying the results of load into calc and then into display in that order. </p>
<p>My inexperienced (this is for a class) thought? It might be something with kicking out of the while loop after the stock information is loaded. There isn't (in my opinion) anything telling the program to move onto calc() and then move onto display()...I thought it was being achieved with the def main(): sequence but I could be wrong. </p>
<p>This is what the output should look like: </p>
<pre><code>============== RESTART: C:\Users\ELSSAAAAA\Desktop\Sample.py ==============
Enter stock name OR -999 to Quit: GOOGLE
Enter number of shares: 10000
Enter purchase price: 30
Enter selling price: 300
Enter commission: 0.04
Stock Name: GOOGLE
Amount paid for the stock: $ 300,000.00
Commission paid on the purchase: $ 12,000.00
Amount the stock sold for: $ 3,000,000.00
Commission paid on the sale: $ 120,000.00
Profit (or loss if negative): $ 2,568,000.00
Enter stock name OR -999 to Quit: AMAZON
Enter number of shares: 10000
Enter purchase price: 25
Enter selling price: 250
Enter commission: 0.04
Stock Name: AMAZON
Amount paid for the stock: $ 250,000.00
Commission paid on the purchase: $ 10,000.00
Amount the stock sold for: $ 2,500,000.00
Commission paid on the sale: $ 100,000.00
Profit (or loss if negative): $ 2,140,000.00
Enter stock name OR -999 to Quit: -999
Total Profit is $ 14,260,000.00
</code></pre>
| 0 | 2016-10-12T19:36:13Z | 40,007,710 | <p>First you have to define all variables globally or pass it as a parameter,
and then you have to call your function inside your while loop.For simplicity I am defining it as a global variable.</p>
<pre><code>shares = 0
pp = 0
sp = 0
commission = 0
name = ""
amount_paid = 0
profit_loss = 0
totalpr = 0
commission_paid_purchase = 0
commission_paid_sale = 0
amount_sold = 0
def load():
name=0
count=0
totalpr=0
name=input("Enter stock name OR -999 to Quit: ")
while name != '-999':
count=count+1
shares=int(input("Enter number of shares: "))
pp=float(input("Enter purchase price: "))
sp=float(input("Enter selling price: "))
commission=float(input("Enter commission: "))
calc()
display()
name=input("Enter stock name OR -999 to Quit: ")
def calc():
totalpr=0
amount_paid=shares*pp
commission_paid_purchase=amount_paid*commission
amount_sold=shares*sp
commission_paid_sale=amount_sold*commission
profit_loss=(amount_sold - commission_paid_sale) -(amount_paid + commission_paid_purchase)
totalpr=totalpr+profit_loss
def display():
print("\nStock Name:", name)
print("Amount paid for the stock: $", format(amount_paid, '10,.2f'))
print("Commission paid on the purchase: $", format(commission_paid_purchase, '10,.2f'))
print("Amount the stock sold for: $", format(amount_sold, '10,.2f'))
print("Commission paid on the sale: $", format(commission_paid_sale, '10,.2f'))
print("Profit (or loss if negative): $", format(profit_loss, '10,.2f'))
print("Total Profit is $", format(totalpr, '10,.2f'))
def main():
load()
calc()
display()
main()
</code></pre>
| -1 | 2016-10-12T20:25:00Z | [
"python",
"function",
"python-3.x",
"while-loop"
] |
New to Python 3 - Unable to get program to move to the next module | 40,006,949 | <p>I am new to Python and am trying to get a program to move from one defined module to the next. The first module is working just fine but will not move to the def calcAverage module. I have attached both the code and the result. I only have the sum set up in the first module to verify that it was calculating correctly. This info will be returned and printed into a table. (Sorry if I am not using the correct terminology.) I'm very new to this.</p>
<p>Here is the result:
Enter the first test score.89
Enter the second test score.94
Enter the third test score.100
Enter the fourth test score.88
Enter the fifth test score.96
467</p>
<blockquote>
<blockquote>
<p>>
Nothing happens after this.</p>
</blockquote>
</blockquote>
<p>Here is the code:</p>
<p>` # This program will calculate the average of five test scores.</p>
<pre><code># Print my name
print('Beth Salvatore')
# Assign corresponding letter grade.
A_score = 90
B_score = 80
C_score = 70
D_score = 60
def main():
# Get five test scores. Get first score.
test1 = int(input('Enter the first test score.'))
# Get second score.
test2 = int(input('Enter the second test score.'))
# Get third score.
test3 = int(input('Enter the third test score.'))
# Get fourth score.
test4 = int(input('Enter the fourth test score.'))
# Get fifth score.
test5 = int(input('Enter the fifth test score.'))
# Add all scores.
x = [test1, test2, test3, test4, test5]
total = sum(x)
print (total)
# Return the total of all tests.
return total
def calcAverage(score1, score2, score3, score4, score5):
# Find the average of all tests.
calcAverage = (total) /5.0
return calcAverage
print('The average test score is %', calcAverage)
def determineGrade(score):
# Assign a letter grade to the average.
if score >= A_score:
print('A')
else:
if score >= B_score:
print('B')
else:
if score >= C_score:
print ('C')
else:
if score >= D_score:
print('D')
else:
print('F')
# Return the letter grade
return score
#Print the tests and corresponding grades in a table.
print('score \t\t numeric grade \t letter grade')
print('---------------------') \
print('score 1:' test1, score)
print('score 2:' test2, score)
print('score 3:' test3, score)
print('score 4:' test4, score)
print('score 5:' test1, score)
# Call the main function.
main()`
</code></pre>
| 0 | 2016-10-12T19:36:27Z | 40,007,029 | <p>def must be declared before the call of <em>main()</em>.
You're OK.</p>
<p>But you never called <em>calcAverage()</em> nor <em>determineGrade()</em> into the def of your <strong>main</strong>.</p>
<p>If your <em>return(total)</em> into your <strong>main</strong>, then use <em>print(main())</em> (with no sense at all).</p>
<p>Or, if you <em>print(total</em>) in your <strong>main</strong>, use <em>total=test1+test2+...+test5</em> before.</p>
<p>That's all at this point.</p>
<blockquote>
<p>total = test1+test2+test3+test4+test5</p>
<p>print (total)</p>
</blockquote>
<pre><code># Return the total of all tests.
# return total
# because you rarely return a int via a main, until you call the main from elsewhere
</code></pre>
<p>Just add <em>determineGrade(total)</em> into your main after <em>print(total)</em></p>
| 0 | 2016-10-12T19:42:20Z | [
"python",
"module"
] |
need help to read a file in python | 40,007,002 | <p>I am new to python but I have learned lots of stuff, but I found difficulty to read a JSON file. I need to read it in a way to access a particular data in this file. The file contain a data as follow: </p>
<pre><code>[
29723,
5426523,
"this book need to be printed",
"http://amzn.to/U60TaF"
][
29723,
807242528,
"ready for shipping",
"http://nblo.gs/HNpn"
]
</code></pre>
<p>my code is: </p>
<pre><code>FI = open(file_name, 'r')
for line in FI:
tweet = json.loads(line)
print(tweet)
</code></pre>
<p>The output is only the last line which is the link, I don't know way. </p>
| 0 | 2016-10-12T19:40:20Z | 40,007,054 | <p>Try</p>
<pre><code>data = json.load(open(file_name))
</code></pre>
| 2 | 2016-10-12T19:43:50Z | [
"python"
] |
Pandas DataFrame shift columns by date to create lag values | 40,007,033 | <p>I have a dataframe:</p>
<pre><code>df = pd.DataFrame({'year':[2000,2000,2000,2001,2001,2002,2002,2002],'ID':['a','b','c','a','b','a','b','c'],'values':[1,2,3,4,5,7,8,9]})
</code></pre>
<p><a href="https://i.stack.imgur.com/lKcOh.png" rel="nofollow"><img src="https://i.stack.imgur.com/lKcOh.png" alt="enter image description here"></a></p>
<p>I would like to create a column that has the lag value of each ID-year, for example, ID'a' in 2000 has a value of 1, so ID'a' in 2001 should have a pre-value of 1. The key point is that if an ID doesn't have an value in the previous year (so the year is not continuous for some ID), then the pre-value should be NaN, instead of having the value from two years ago. For example, ID'c' doesn't show up in 2001, then for 2002, ID'c' should have pre-value = NaN.
Ideally, the final output should look like the following:
<a href="https://i.stack.imgur.com/MBY73.png" rel="nofollow"><img src="https://i.stack.imgur.com/MBY73.png" alt="enter image description here"></a></p>
<p>I tried the df.groupby(['ID'])['values'].shift(1), but it gives the following:
<a href="https://i.stack.imgur.com/I2ybO.png" rel="nofollow"><img src="https://i.stack.imgur.com/I2ybO.png" alt="enter image description here"></a></p>
<p>The problem is that when ID'c' doesn't have a value one year ago, the value two years ago is used. I also tried multiindex shift, which gives me the same result. </p>
<pre><code>df.set_index(['year','ID'], inplace = True)
df.groupby(level=1)['values'].shift(1)
</code></pre>
<p>The thing that works is the answer mentioned <a href="http://stackoverflow.com/questions/34699779/pandas-dataframe-shift-column-by-date">here</a>. But since my dataframe is fairly large, the merge kills the kernel. So far, I haven't figured out a better way to do it. I hope I explained my problem clearly. </p>
| 1 | 2016-10-12T19:42:32Z | 40,007,751 | <p>Suppose the <code>year</code> column is unique for each id, i.e, there are no duplicated years for each specific id, then you can shift the value firstly and then replace shifted values where the difference between the year at the current row and previous row is not equal to <code>1</code> with <code>NaN</code>:</p>
<pre><code>import pandas as pd
import numpy as np
df['pre_value'] = df.groupby('ID')['values'].shift(1)
df['pre_value'] = df.pre_value.where(df.groupby('ID').year.diff() == 1, np.nan)
df
</code></pre>
<p><a href="https://i.stack.imgur.com/ySQTI.png" rel="nofollow"><img src="https://i.stack.imgur.com/ySQTI.png" alt="enter image description here"></a></p>
| 2 | 2016-10-12T20:27:09Z | [
"python",
"pandas",
"dataframe",
"panel-data"
] |
Pandas DataFrame shift columns by date to create lag values | 40,007,033 | <p>I have a dataframe:</p>
<pre><code>df = pd.DataFrame({'year':[2000,2000,2000,2001,2001,2002,2002,2002],'ID':['a','b','c','a','b','a','b','c'],'values':[1,2,3,4,5,7,8,9]})
</code></pre>
<p><a href="https://i.stack.imgur.com/lKcOh.png" rel="nofollow"><img src="https://i.stack.imgur.com/lKcOh.png" alt="enter image description here"></a></p>
<p>I would like to create a column that has the lag value of each ID-year, for example, ID'a' in 2000 has a value of 1, so ID'a' in 2001 should have a pre-value of 1. The key point is that if an ID doesn't have an value in the previous year (so the year is not continuous for some ID), then the pre-value should be NaN, instead of having the value from two years ago. For example, ID'c' doesn't show up in 2001, then for 2002, ID'c' should have pre-value = NaN.
Ideally, the final output should look like the following:
<a href="https://i.stack.imgur.com/MBY73.png" rel="nofollow"><img src="https://i.stack.imgur.com/MBY73.png" alt="enter image description here"></a></p>
<p>I tried the df.groupby(['ID'])['values'].shift(1), but it gives the following:
<a href="https://i.stack.imgur.com/I2ybO.png" rel="nofollow"><img src="https://i.stack.imgur.com/I2ybO.png" alt="enter image description here"></a></p>
<p>The problem is that when ID'c' doesn't have a value one year ago, the value two years ago is used. I also tried multiindex shift, which gives me the same result. </p>
<pre><code>df.set_index(['year','ID'], inplace = True)
df.groupby(level=1)['values'].shift(1)
</code></pre>
<p>The thing that works is the answer mentioned <a href="http://stackoverflow.com/questions/34699779/pandas-dataframe-shift-column-by-date">here</a>. But since my dataframe is fairly large, the merge kills the kernel. So far, I haven't figured out a better way to do it. I hope I explained my problem clearly. </p>
| 1 | 2016-10-12T19:42:32Z | 40,009,361 | <p>a <code>reindex</code> approach</p>
<pre><code>def reindex_min_max(df):
mn = df.year.min()
mx = df.year.max() + 1
d = df.set_index('year').reindex(pd.RangeIndex(mn, mx, name='year'))
return pd.concat([d, d['values'].shift().rename('pre_value')], axis=1)
df.groupby('ID')[['year', 'values']].apply(reindex_min_max) \
.sort_index(level=[1, 0]).dropna(subset=['values']).reset_index()
</code></pre>
<p><a href="https://i.stack.imgur.com/WZCmJ.png" rel="nofollow"><img src="https://i.stack.imgur.com/WZCmJ.png" alt="enter image description here"></a></p>
| 0 | 2016-10-12T22:23:57Z | [
"python",
"pandas",
"dataframe",
"panel-data"
] |
Converting DictVectorizer to TfIdfVectorizer | 40,007,062 | <p>I need to convert some data that I have in this format into a term document matrix: <a href="http://pastebin.com/u1A7v1CV" rel="nofollow">http://pastebin.com/u1A7v1CV</a></p>
<p>Essentially, each row represents a document represented as word_label_id and frequency. The words corresponding to each word_label_id are in a different file. </p>
<p>I want to convert this into a term document matrix so that I can vectorize the data and cluster it. </p>
<p>I have managed to convert the data to a dictionary and use DictVectorizer to get a one-hot encoded sparse representation because someone suggested I do this in the following way: </p>
<pre><code>data = []
with open('../data/input.mat', 'r') as file:
for i, line in enumerate(file):
l = line.split()
d = dict([(k, v) for k, v in zip(l[::2], l[1::2])])
data.append(d)
v = DictVectorizer(sparse=True, dtype=float)
X = v.fit_transform(data)
</code></pre>
<p>This is what the output looks like: </p>
<pre><code> (0, 1312) 1.0
(0, 2704) 1.0
(0, 3322) 1.0
(0, 3492) 1.0
(0, 3506) 1.0
(0, 3660) 1.0
(0, 3674) 1.0
(0, 3813) 1.0
(0, 4782) 1.0
(0, 4827) 1.0
(0, 5208) 1.0
(0, 5721) 1.0
(0, 6105) 1.0
(0, 6907) 1.0
(0, 7252) 1.0
(0, 7615) 1.0
(0, 7890) 1.0
(0, 7891) 1.0
(0, 7906) 1.0
(0, 7935) 1.0
(0, 7954) 1.0
(0, 7962) 1.0
(0, 7986) 1.0
(0, 8000) 1.0
(0, 8012) 1.0
: :
(8579, 50731) 1.0
(8579, 51298) 1.0
(8579, 51686) 1.0
(8579, 51732) 1.0
(8579, 52439) 1.0
(8579, 52563) 1.0
(8579, 52621) 1.0
(8579, 52980) 1.0
(8579, 53013) 1.0
(8579, 53018) 1.0
(8579, 53155) 1.0
(8579, 53180) 1.0
(8579, 53317) 1.0
(8579, 53739) 1.0
(8579, 54114) 1.0
(8579, 54444) 1.0
(8579, 54489) 1.0
(8579, 54922) 1.0
(8579, 55074) 1.0
(8579, 55164) 1.0
(8579, 55311) 1.0
(8579, 55741) 1.0
(8579, 56010) 1.0
(8579, 56062) 1.0
(8579, 56946) 1.0
</code></pre>
<p>I don't know what this means and how to interpret it. Is this equivalent to the sparse matrix that you get out of <code>TfIdfVectorizer</code> in scikit-learn? </p>
<p>My next steps on this dataset are supposed to be feature selection and k-means clustering. I just don't know how to use the <code>DictVectorizer</code> or the <code>data</code> dictionary to proceed. </p>
| 0 | 2016-10-12T19:44:18Z | 40,007,715 | <p>The output of the DictVectorizer is a SciPy sparse matrix just as you would have from TfIdfVectorizer. You can proceed with the feature selection and k-means clustering steps.</p>
| 1 | 2016-10-12T20:25:15Z | [
"python",
"scikit-learn",
"k-means",
"tf-idf",
"dictvectorizer"
] |
Dask/hdf5: Read by group? | 40,007,106 | <p>I must read in and operate independently over many chunks of a large dataframe/numpy array. However, these chunks are chosen in a specific, non-uniform manner and are broken naturally into groups within a hdf5 file. Each group is small enough to fit into memory (though even without restriction, I suppose the standard chunking procedure should suffice.) </p>
<p>Specifically, instead of </p>
<pre><code> f = h5py.File('myfile.hdf5')
x = da.from_array(f['/data'], chunks=(1000, 1000))
</code></pre>
<p>I want something closer to (pseudocode):</p>
<pre><code> f = h5py.File('myfile.hdf5')
x = da.from_array(f, chunks=(f['/data1'], f['/data2'], ...,))
</code></pre>
<p><a href="http://dask.pydata.org/en/latest/delayed-collections.html" rel="nofollow">http://dask.pydata.org/en/latest/delayed-collections.html</a> I believe hints this is possible but I am still reading into and understanding dask/hdf5.</p>
<p>My previous implementation uses a number of CSV files and reads them in as needed with its own multi-processing logic. I would like to collapse all this functionality into dask with hdf5.</p>
<p>Is chunking by hdf5 group/read possible and my line of thought ok?</p>
| 2 | 2016-10-12T19:47:55Z | 40,007,327 | <p>I would read many dask.arrays from many groups as single-chunk dask.arrays and then concatenate or stack those groups.</p>
<h3>Read many dask.arrays</h3>
<pre><code>f = h5py.File(...)
dsets = [f[dset] for dset in datasets]
arrays = [da.from_array(dset, chunks=dset.shape) for dset in dsets]
</code></pre>
<h3>Alternatively, use a lock to defend HDF5</h3>
<p>HDF5 is not threadsafe, so lets use a lock to defend it from parallel reads. I haven't actually checked to see if this is necessary or not when reading across different groups.</p>
<pre><code>from threading import Lock
lock = Lock()
arrays = [da.from_array(dset, chunks=dset.shape, lock=lock)
for dset in dsets]
</code></pre>
<h3>Stack or Concatenate arrays together</h3>
<pre><code>array = da.concatenate(arrays, axis=0)
</code></pre>
<p>See <a href="http://dask.pydata.org/en/latest/array-stack.html" rel="nofollow">http://dask.pydata.org/en/latest/array-stack.html</a></p>
<h3>Or use dask.delayed</h3>
<p>You could also, as you suggest, use <a href="http://dask.pydata.org/en/latest/delayed.html" rel="nofollow">dask.delayed</a> to do the first step in reading single-chunk dask.arrays</p>
| 1 | 2016-10-12T20:00:43Z | [
"python",
"hdf5",
"h5py",
"dask"
] |
Python or Numpy Approach to MATLAB's "cellfun" | 40,007,120 | <p>Is there a python or numpy approach similar to MATLABs "cellfun"? I want to apply a function to an object which is a MATLAB cell array with ~300k cells of different lengths. </p>
<p>A very simple example:</p>
<pre><code>>>> xx = [(4,2), (1,2,3)]
>>> yy = np.exp(xx)
Traceback (most recent call last):
File "<pyshell#47>", line 1, in <module>
yy = np.exp(xx)
AttributeError: 'tuple' object has no attribute 'exp'
</code></pre>
| 0 | 2016-10-12T19:48:59Z | 40,007,257 | <p>The most readable/maintainable approach will probably be to use a <a href="https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions" rel="nofollow">list comprehension</a>:</p>
<pre><code>yy = [ np.exp(xxi) for xxi in xx ]
</code></pre>
<p>That relies on <code>numpy.exp</code> to implicitly convert each tuple into a <code>numpy.ndarray</code>, which in turn means that you'll get a list of <code>numpy.ndarray</code>s back rather than a list of tuples. That's probably OK for nearly all purposes, but if you absolutely have to have tuples that's also easy enough to arrange:</p>
<pre><code>yy = [ tuple(np.exp(xxi)) for xxi in xx ]
</code></pre>
<p>For some purposes (e.g. to avoid memory bottlenecks) you may prefer to use a <a href="https://docs.python.org/2/reference/expressions.html#generator-expressions" rel="nofollow">generator expression</a> rather than a list comprehension (round brackets instead of square).</p>
| 3 | 2016-10-12T19:57:05Z | [
"python",
"numpy",
"elementwise-operations"
] |
Python or Numpy Approach to MATLAB's "cellfun" | 40,007,120 | <p>Is there a python or numpy approach similar to MATLABs "cellfun"? I want to apply a function to an object which is a MATLAB cell array with ~300k cells of different lengths. </p>
<p>A very simple example:</p>
<pre><code>>>> xx = [(4,2), (1,2,3)]
>>> yy = np.exp(xx)
Traceback (most recent call last):
File "<pyshell#47>", line 1, in <module>
yy = np.exp(xx)
AttributeError: 'tuple' object has no attribute 'exp'
</code></pre>
| 0 | 2016-10-12T19:48:59Z | 40,007,984 | <p>MATLAB cells were it's attempt to handle general lists like a real language. But being MATLAB they have to be 2d. But in general, in Python uses lists where MATLAB uses cells. <code>numpy</code> arrays with <code>dtype=object</code> behave similarly, adding multidimensions.</p>
<p>Taking the object array route, I can use <code>frompyfunc</code> to apply this function to elements of a list or array:</p>
<pre><code>In [231]: np.frompyfunc(np.exp,1,1)([(4,2),(1,2,3)])
Out[231]:
array([array([ 54.59815003, 7.3890561 ]),
array([ 2.71828183, 7.3890561 , 20.08553692])], dtype=object)
In [232]: np.frompyfunc(np.exp,1,1)([(4,2),(1,2)])
Out[232]:
array([[54.598150033144236, 7.3890560989306504],
[2.7182818284590451, 7.3890560989306504]], dtype=object)
</code></pre>
<p>In the 2nd case the result is (2,2), in the first (2,) shape. That's because of how <code>np.array([...])</code> handles those 2 inputs.</p>
<p>List comprehensions are just as fast, and probably give better control. Or at least can be more predictable.</p>
| 2 | 2016-10-12T20:41:17Z | [
"python",
"numpy",
"elementwise-operations"
] |
Duplicate element from for loop in BeautifulSoup | 40,007,131 | <p>Given the code:</p>
<pre><code>import urllib
import urllib.request
from bs4 import BeautifulSoup
from urllib.request import urlopen
def make_soup(url):
thepage = urllib.request.urlopen(url)
soupdata = BeautifulSoup(thepage, "html.parser")
return soupdata
soup = make_soup("https://www.wellstar.org/locations/pages/wellstar-acworth-practices.aspx")
for table in soup.findAll("table", class_ = "s4-wpTopTable"):
for specialty in table.findAll("div", class_ = "PurpleBackgroundHeading"):
specialty = specialty.get_text(strip = True)
for name in table.findAll(class_ = "WS_Location_Name"):
name = name.get_text()
print(specialty, " - ", name)
</code></pre>
<p>This code yields the properly looped location name coupled with the improperly looped specialty name. For example, the previous code produces:</p>
<pre><code>Urology - Center for Spine Interventions, PC
Urology - WellStar Medical GroupCardiovascular Medicine
</code></pre>
<p>With <code>Urology - Georgia Urology</code> being the last couple produced. How can I be sure to create pairs of Specialties and Location Names that correspond to reality?</p>
| 0 | 2016-10-12T19:49:42Z | 40,007,496 | <p>could it be the indentation?
How should the for loops be nested?
in python I would expect something like:</p>
<pre><code>for tabele ...:
for specialty ...:
spe..
for name ...:
name ...
print ...
</code></pre>
<p>or</p>
<pre><code>for tabele ...:
for specialty ...:
spe..
for name ...:
name ...
print ...
</code></pre>
| 0 | 2016-10-12T20:10:57Z | [
"python",
"web-scraping",
"beautifulsoup"
] |
Format nested list python | 40,007,245 | <pre><code>list=[['name1', 'maths,english'], ['name2', 'maths,science']]
</code></pre>
<p>I have a nested list that likes something like this, I am trying to work out how to format it so that the out put would be something like the following:</p>
<pre><code>name1, maths,english
name2, maths,science
</code></pre>
<p>I have tried using regex to no avail. How would I go about formatting or manipulating the list output to get something like the above?</p>
| 0 | 2016-10-12T19:56:18Z | 40,007,268 | <p>Iterate over your groups and join the items from each group using a comma.</p>
<pre><code>groups = [['name1', 'maths,english'], ['name2', 'maths,science']]
for group in groups:
print ', '.join(group)
</code></pre>
| 5 | 2016-10-12T19:57:34Z | [
"python"
] |
How do I make window visiable/invisible at runtime? | 40,007,305 | <p>I am using kivy to create a small Gui for my python program. This Gui is not always visible. So I start it with these settings:</p>
<pre><code>Config.set('graphics', 'borderless', True)
Config.set('graphics', 'resizable', False)
Config.set('graphics', 'window_state', 'hidden')
</code></pre>
<p>However: Somewhere in my program I want to make the window visible again. How do I do that? I couldnt find anything that changes configuration at runtime.</p>
| 1 | 2016-10-12T19:59:40Z | 40,007,463 | <p>It seems that if you are using the SDL provider you have a <strong>hide & show</strong> functions on the Window object</p>
<p>from the kivy.core.window docs:</p>
<pre><code>hide() Added in 1.9.0
Hides the window. This method should be used on desktop platforms only.
Note
This feature requires the SDL2 window provider and is currently only supported on desktop platforms.
show()¶Added in 1.9.0
Shows the window. This method should be used on desktop platforms only.
Note
This feature requires the SDL2 window provider and is currently only supported on desktop platforms.
</code></pre>
| 2 | 2016-10-12T20:09:06Z | [
"python",
"kivy"
] |
How do I make window visiable/invisible at runtime? | 40,007,305 | <p>I am using kivy to create a small Gui for my python program. This Gui is not always visible. So I start it with these settings:</p>
<pre><code>Config.set('graphics', 'borderless', True)
Config.set('graphics', 'resizable', False)
Config.set('graphics', 'window_state', 'hidden')
</code></pre>
<p>However: Somewhere in my program I want to make the window visible again. How do I do that? I couldnt find anything that changes configuration at runtime.</p>
| 1 | 2016-10-12T19:59:40Z | 40,007,538 | <p>I'm not familiar with Kivy, but it looks like you just need to set it to visible.</p>
<p><code>window_state</code>: string , one of 'visible', 'hidden', 'maximized' \
or 'minimized'</p>
<p>from:
<a href="https://kivy.org/docs/_modules/kivy/config.html" rel="nofollow">https://kivy.org/docs/_modules/kivy/config.html</a></p>
<p>Looking at this github post: <a href="https://github.com/kivy/kivy/issues/3637" rel="nofollow">https://github.com/kivy/kivy/issues/3637</a></p>
<p>The method they're using is .hide() and .show().</p>
| 1 | 2016-10-12T20:14:01Z | [
"python",
"kivy"
] |
Repeat the same analysis for TWO files in a lot of directories | 40,007,468 | <p>I have a lot of data stored in two files found in folders with the structure shown on this <a href="https://i.stack.imgur.com/zfFZW.png" rel="nofollow">pic</a>.
I wrote a small python script to process the two files in Subdir1 and would like to repeat it over Dir, so each Subdir gets visited. I searched stackoverflow and looked at ways of doing it:
-either with bash (using a for loop to run the python script on all files)
-or using os.walk() and walk Dir</p>
<p>The problem is that I have two files: I am getting some data from File_1, and some data from File_2, combining the two and then writing the resulting astropy Table (or dataframe) to a file. I can do this over one subdirectory. Any ideas how to do this for all the folders? </p>
<p>I can handle repeating tasks when there is only file per folder.
Thanks.</p>
| 0 | 2016-10-12T20:09:15Z | 40,007,562 | <p>Something like this:</p>
<pre><code>subdirs = glob.glob("Dir/*/.")
for subdir in subdirs:
file1 = os.path.join(subdir, "File_1")
file2 = os.path.join(subdir, "File_2")
result = os.path.join(subdir, "result.txt")
with open(file1, "rt") as input_file1:
with open(file2, "rt") as input_file2:
with open(result, "wt") as output_file:
# your computations go here:
# input_file1.read()
# output_file.write("these are my results")
</code></pre>
| 0 | 2016-10-12T20:15:25Z | [
"python",
"bash"
] |
running local server .py prompts a text editor instead of opening page | 40,007,469 | <p>I have a file which currently works on my production site as mysite.com/pages/lister.py.</p>
<p>I am trying to build a local version of the site. The index.php works and other pages work, but when I go to a .py page like: localhost/pages/lister.py it doesnt change the site, it just asks if I want to use gedit to open the file.</p>
<p>My guess is that my local config is off somewhere, but I do not know where to start when approaching this problem. </p>
<p>NOTES:</p>
<p>I am running a lamp server which I downloaded using <code>sudo apt-get install lamp-server^</code></p>
<p>and my apache config is <code>/etc/apache2/sites-available/000-default.conf</code> and contains:</p>
<pre><code><VirtualHost *:80>
ServerAdmin webmaster@localhost
DocumentRoot /var/www/
<Directory /var/www/>
Options ExecCGI Indexes FollowSymLinks MultiViews
AllowOverride None
Order allow,deny
allow from all
AddHandler cgi-script .py
</Directory>
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
</code></pre>
<p><strong>EDIT 1</strong></p>
<p>This may be the solution to my question but its not really working yet so idk yet.</p>
<p>I ran</p>
<pre><code>sudo a2enmod cgi
sudo service apache2 restart
</code></pre>
<p>and now it gives:</p>
<p>Internal Server Error</p>
<p>The server encountered an internal error or misconfiguration and was unable to complete your request.</p>
<p>Please contact the server administrator at webmaster@localhost to inform them of the time this error occurred, and the actions you performed just before this error.</p>
<p>More information about this error may be available in the server error log.
Apache/2.4.18 (Ubuntu) Server at localhost Port 80</p>
| 1 | 2016-10-12T20:09:16Z | 40,008,360 | <p>My configuration for .pl and .py scripts that write HTML directly out to a page is the following:</p>
<pre><code><Directory "[put production path here]">
Options Indexes FollowSymLinks ExecCGI
AllowOverride All
Require all granted
</Directory>
</code></pre>
<p>As I'm new to full stack work, I'm not sure if this is appropriate for your situation, but it might be worth a try.</p>
| 0 | 2016-10-12T21:07:04Z | [
"php",
"python",
"lamp"
] |
Python tile based game (2d array) player movement | 40,007,549 | <p>I'm making a rougelike in pygame, and I'm having trouble with player movement in a grid. This sample program shows how I plan to do it:</p>
<pre><code>class P:
def __init__(self, standing_on):
self.standing_on = standing_on
self.row, self.column = 4, 4
def __str__(self):
return "@"
class G:
walkable = True
def __str__(self):
return "â"
class W:
walkable = False
def __str__(self):
return "|"
p = P(G())
game_map = [
[W(), W(), W(), W(), W(), W(), W(), W(), W(), W()],
[W(), G(), G(), G(), G(), G(), G(), G(), G(), W()],
[W(), G(), G(), G(), G(), G(), G(), G(), G(), W()],
[W(), G(), G(), G(), G(), G(), G(), G(), G(), W()],
[W(), G(), G(), G(), G(), G(), G(), G(), G(), W()],
[W(), G(), G(), G(), G(), G(), G(), G(), G(), W()],
[W(), G(), p, G(), G(), G(), G(), G(), G(), W()],
[W(), G(), G(), G(), G(), G(), G(), G(), G(), W()],
[W(), G(), G(), G(), G(), G(), G(), G(), G(), W()],
[W(), W(), W(), W(), W(), W(), W(), W(), W(), W()]
]
def print_map():
for column in range(10):
for row in range(10):
print(game_map[column][row], end="")
print()
def move_up():
temp = p.row - 1
if game_map[temp][p.column].walkable:
game_map[p.column][p.row] = p.standing_on
p.column -= 1
p.standing_on = game_map[p.column][p.row]
game_map[p.column][p.row] = p
print_map()
print(p.row, p.column, "\n")
move_up()
print_map()
print(p.row, p.column, "\n")
move_up()
print_map()
print(p.row, p.column, "\n")
</code></pre>
<ul>
<li>p = player</li>
<li>g = grass</li>
<li>w = wall</li>
</ul>
<p>and the output:</p>
<pre><code>||||||||||
|ââââââââ|
|ââââââââ|
|ââââââââ|
|ââââââââ|
|ââââââââ|
|â@ââââââ|
|ââââââââ|
|ââââââââ|
||||||||||
4 4
||||||||||
|ââââââââ|
|ââââââââ|
|âââ@ââââ|
|ââââââââ|
|ââââââââ|
|â@ââââââ|
|ââââââââ|
|ââââââââ|
||||||||||
4 3
||||||||||
|ââââââââ|
|âââ@ââââ|
|ââââââââ|
|ââââââââ|
|ââââââââ|
|â@ââââââ|
|ââââââââ|
|ââââââââ|
||||||||||
4 2
</code></pre>
<p>The numbers under the map represent the players coordinates. I start at 4, 4 (note that its 0 indexed) and move up twice. When displayed the map is completely wrong though, and I have tested it in my actual game and get the same bug, using images instead of text. Any idea whats going on?</p>
| 1 | 2016-10-12T20:14:35Z | 40,007,890 | <p>The problem is your starting position. You need to draw a map without your player and then place the player on the map. Here is the solution that works:</p>
<pre><code>class P:
def __init__(self, standing_on):
self.standing_on = standing_on
self.row, self.column = 4, 4
def __str__(self):
return "@"
class G:
walkable = True
def __str__(self):
return "â"
class W:
walkable = False
def __str__(self):
return "|"
p = P(G())
game_map = [
[W(), W(), W(), W(), W(), W(), W(), W(), W(), W()],
[W(), G(), G(), G(), G(), G(), G(), G(), G(), W()],
[W(), G(), G(), G(), G(), G(), G(), G(), G(), W()],
[W(), G(), G(), G(), G(), G(), G(), G(), G(), W()],
[W(), G(), G(), G(), G(), G(), G(), G(), G(), W()],
[W(), G(), G(), G(), G(), G(), G(), G(), G(), W()],
[W(), G(), G(), G(), G(), G(), G(), G(), G(), W()],
[W(), G(), G(), G(), G(), G(), G(), G(), G(), W()],
[W(), G(), G(), G(), G(), G(), G(), G(), G(), W()],
[W(), W(), W(), W(), W(), W(), W(), W(), W(), W()]
]
def print_map():
game_map[p.column][p.row] = p
for column in range(10):
for row in range(10):
print(game_map[column][row], end="")
print()
def move_up():
temp = p.row - 1
if game_map[temp][p.column].walkable:
game_map[p.column][p.row] = p.standing_on
p.column -= 1
p.standing_on = game_map[p.column][p.row]
print_map()
print(p.row, p.column, "\n")
move_up()
print_map()
print(p.row, p.column, "\n")
move_up()
print_map()
print(p.row, p.column, "\n")
</code></pre>
| 1 | 2016-10-12T20:35:22Z | [
"python",
"pygame"
] |
Using Qt Designer files in python script | 40,007,626 | <p>I need to open a dialog from <em>login.py</em>, then if successful, the dialog will close and open a main-window from <em>home.py</em>. I need to do this with a file created by Qt Designer with pyuic4. In summary, I need to call <em>login.py</em> and <em>home.py</em> though <em>main.py</em>.</p>
<p>Code of <em>main.py</em>:</p>
<pre><code>from PyQt4 import QtGui, QtCore
import sqlite3, time
from login import Ui_Dialog
from home import Ui_MainWindow
# Here I need to know how to call login.py, and
# after logged in, how to change to home.py
class RunApp():
pass
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
window = RunApp()
sys.exit(app.exec_())
</code></pre>
<p>Code of <em>login.py</em>:</p>
<pre><code>class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName(_fromUtf8("Dialog"))
Dialog.resize(194, 156)
</code></pre>
<p>Code of <em>home.py</em>:</p>
<pre><code>class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(635, 396)
MainWindow.setAutoFillBackground(False)
</code></pre>
<p><strong>Update:</strong>
<strong>Thanks my friends ;) Worked for me with this code:</strong></p>
<pre><code># -*- coding: utf-8 -*-
from PyQt4 import QtGui, QtCore
from login import Ui_Dialog
from home import Ui_MainWindow
import sqlite3, time, sys, os
class MyLogin(QtGui.QDialog):
def __init__(self):
super().__init__()
self.ui = Ui_Dialog()
self.ui.setupUi(self)
self.ui.buttonBox.accepted.connect(self.openHome)
def openHome(self):
ui2 = MyHome()
ui2.show()
ui2.exec_()
class MyHome(QtGui.QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
self.ui2 = Ui_MainWindow()
self.ui2.setupUi(self)
if __name__=='__main__':
root = QtGui.QApplication(sys.argv)
app = MyLogin()
app.show()
root.exec_()
</code></pre>
| 0 | 2016-10-12T20:19:01Z | 40,010,245 | <p>Create a class that derives from <code>QWidget</code>, and in its <code>__init__</code> instantiate the ui class, then call <code>setupUi(self)</code> on it. </p>
<pre><code>class RunApp():
pass
class MyDialog(QWidget):
def __init__(self, parent=None):
super().__init__()
self.ui = Ui_Dialog()
self.ui.setupUi(self)
# do same for Ui_MainWindow via class MyMainWindow(QWidget)
...
</code></pre>
<p>This is explained in </p>
<ul>
<li><a href="http://doc.qt.io/qt-5/designer-using-a-ui-file.html" rel="nofollow">Qt docs</a> (you'll have to do the usual C++ -> Python translation)</li>
<li><a href="https://doc.qt.io/qt-5/examples-designer.html" rel="nofollow">Qt examples for Designer</a> (you'll have to do the usual C++ -> Python translation)</li>
<li><a href="https://github.com/pyqt/examples" rel="nofollow">PyQt examples</a></li>
</ul>
| 0 | 2016-10-13T00:04:31Z | [
"python",
"pyqt",
"qt-designer",
"pyuic"
] |
Using Qt Designer files in python script | 40,007,626 | <p>I need to open a dialog from <em>login.py</em>, then if successful, the dialog will close and open a main-window from <em>home.py</em>. I need to do this with a file created by Qt Designer with pyuic4. In summary, I need to call <em>login.py</em> and <em>home.py</em> though <em>main.py</em>.</p>
<p>Code of <em>main.py</em>:</p>
<pre><code>from PyQt4 import QtGui, QtCore
import sqlite3, time
from login import Ui_Dialog
from home import Ui_MainWindow
# Here I need to know how to call login.py, and
# after logged in, how to change to home.py
class RunApp():
pass
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
window = RunApp()
sys.exit(app.exec_())
</code></pre>
<p>Code of <em>login.py</em>:</p>
<pre><code>class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName(_fromUtf8("Dialog"))
Dialog.resize(194, 156)
</code></pre>
<p>Code of <em>home.py</em>:</p>
<pre><code>class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(635, 396)
MainWindow.setAutoFillBackground(False)
</code></pre>
<p><strong>Update:</strong>
<strong>Thanks my friends ;) Worked for me with this code:</strong></p>
<pre><code># -*- coding: utf-8 -*-
from PyQt4 import QtGui, QtCore
from login import Ui_Dialog
from home import Ui_MainWindow
import sqlite3, time, sys, os
class MyLogin(QtGui.QDialog):
def __init__(self):
super().__init__()
self.ui = Ui_Dialog()
self.ui.setupUi(self)
self.ui.buttonBox.accepted.connect(self.openHome)
def openHome(self):
ui2 = MyHome()
ui2.show()
ui2.exec_()
class MyHome(QtGui.QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
self.ui2 = Ui_MainWindow()
self.ui2.setupUi(self)
if __name__=='__main__':
root = QtGui.QApplication(sys.argv)
app = MyLogin()
app.show()
root.exec_()
</code></pre>
| 0 | 2016-10-12T20:19:01Z | 40,010,686 | <p>For login page of PyQt based application. i would suggest use <a href="http://pyqt.sourceforge.net/Docs/PyQt4/qstackedwidget.html" rel="nofollow">QstackedWidget</a></p>
<blockquote>
<p>Page1 in stackedwidget for login page </p>
<p>Page2 in stackwidget for home screen</p>
</blockquote>
<p>all you need is a simple login function that will varify the user name and password and allow user to move to home screen.</p>
<p>you can change the current index to open home screen.</p>
<pre><code> self.stackedWidget.setCurrentIndex(1)
</code></pre>
| 0 | 2016-10-13T01:02:48Z | [
"python",
"pyqt",
"qt-designer",
"pyuic"
] |
Python: how to create sublists through loop? | 40,007,691 | <p>I have a long list containing elements that value from 0 to 100.
What I want to do is find all the positions where my elements take on values [0,2]. Then find out all the positions of the values between 2 and 4, etc up to 98 and 100.</p>
<p>Let's call the list containing the values ''list''. And let's call the resulting list p_x. Where x indicates which interval we are finding the positions of.</p>
<p>I managed to get what i want this way:
p_61 = N.where((list >= 60) & (list <= 62)) </p>
<p>My question now is: how do i loop this, so that i get as a result all the p_x's that I want?</p>
| -2 | 2016-10-12T20:23:59Z | 40,007,811 | <pre><code>import itertools
l = list(range(10))
## If you just want the values:
print([(x,y) for (x,y) in itertools.combinations(l, 2) if abs(x-y)==2])
## If you want the positions:
for i, x in enumerate(l):
for j, y in enumerate(l):
if j <= i:
continue
if abs(x-y) == 2:
print(i, j)
## If you want them stored in lists in a dictionary:
d = {}
for i, x in enumerate(l):
for j, y in enumerate(l):
if j <= i:
continue
if abs(x-y) == 2:
k = 'p_{}'.format(x+1)
try:
d[k].append((i,j))
except KeyError:
d[k] = [(i,j)]
</code></pre>
| 0 | 2016-10-12T20:30:54Z | [
"python",
"list",
"loops"
] |
Digital Image Processing via Python | 40,007,759 | <p>I am starting a new project with a friend of mine, we want to design a system that would alert the driver if the car is diverting from its original path and its dangerous.
so in a nutshell we have to design a real-time algorithm that would take pictures from the camera and process them. All of this will be done in Python.
I was wondering if anyone has any advises for us or maybe point out some stuff that we have to consider</p>
<p>Cheers !</p>
| 0 | 2016-10-12T20:27:34Z | 40,007,828 | <p>You can search for this libraries: dlib, PIL (pillow), opencv and scikit learn image. This libraries are image processing libraries for python.</p>
<p>Hope it helps.</p>
| 0 | 2016-10-12T20:31:44Z | [
"python",
"image-processing"
] |
Why tensor flow could not load csv | 40,007,785 | <p>I just installed tensor flow using pip and I try to run the following tutorial:</p>
<p><a href="https://www.tensorflow.org/versions/r0.11/tutorials/tflearn/index.html" rel="nofollow">https://www.tensorflow.org/versions/r0.11/tutorials/tflearn/index.html</a></p>
<pre><code># Data sets
IRIS_TRAINING = "iris_training.csv"
IRIS_TEST = "iris_test.csv"
# Load datasets.
training_set = tf.contrib.learn.datasets.base.load_csv(filename=IRIS_TRAINING,
target_dtype=np.int)
test_set = tf.contrib.learn.datasets.base.load_csv(filename=IRIS_TEST,
target_dtype=np.int)
</code></pre>
<p>But I have error:</p>
<pre><code> training_set = tf.contrib.learn.datasets.base.load_csv(filename=IRIS_TRAINING,
AttributeError: 'module' object has no attribute 'load_csv'
</code></pre>
<p>I read some answer saying that I need to use pandas dataframe? But shouldn't everything just works as in the tutorial? That is so strange! I should not be the only one facing this issue right?</p>
<p>Here's the whole code as in the tutorial:</p>
<pre><code>from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
import numpy as np
# Data sets
IRIS_TRAINING = "iris_training.csv"
IRIS_TEST = "iris_test.csv"
# Load datasets.
training_set = tf.contrib.learn.datasets.base.load_csv(filename=IRIS_TRAINING,
target_dtype=np.int)
test_set = tf.contrib.learn.datasets.base.load_csv(filename=IRIS_TEST,
target_dtype=np.int)
# Specify that all features have real-value data
feature_columns = [tf.contrib.layers.real_valued_column("", dimension=4)]
# Build 3 layer DNN with 10, 20, 10 units respectively.
classifier = tf.contrib.learn.DNNClassifier(feature_columns=feature_columns,
hidden_units=[10, 20, 10],
n_classes=3,
model_dir="/tmp/iris_model")
# Fit model.
classifier.fit(x=training_set.data,
y=training_set.target,
steps=2000)
# Evaluate accuracy.
accuracy_score = classifier.evaluate(x=test_set.data,
y=test_set.target)["accuracy"]
print('Accuracy: {0:f}'.format(accuracy_score))
# Classify two new flower samples.
new_samples = np.array(
[[6.4, 3.2, 4.5, 1.5], [5.8, 3.1, 5.0, 1.7]], dtype=float)
y = classifier.predict(new_samples)
print('Predictions: {}'.format(str(y)))
</code></pre>
| 0 | 2016-10-12T20:29:25Z | 40,009,254 | <p>since my version is 11... They removed load_csv in 11 without changing the tutorial... I have to run version 0.10.0rc0 just to run the tutorial.</p>
| 0 | 2016-10-12T22:15:40Z | [
"python",
"tensorflow"
] |
Why tensor flow could not load csv | 40,007,785 | <p>I just installed tensor flow using pip and I try to run the following tutorial:</p>
<p><a href="https://www.tensorflow.org/versions/r0.11/tutorials/tflearn/index.html" rel="nofollow">https://www.tensorflow.org/versions/r0.11/tutorials/tflearn/index.html</a></p>
<pre><code># Data sets
IRIS_TRAINING = "iris_training.csv"
IRIS_TEST = "iris_test.csv"
# Load datasets.
training_set = tf.contrib.learn.datasets.base.load_csv(filename=IRIS_TRAINING,
target_dtype=np.int)
test_set = tf.contrib.learn.datasets.base.load_csv(filename=IRIS_TEST,
target_dtype=np.int)
</code></pre>
<p>But I have error:</p>
<pre><code> training_set = tf.contrib.learn.datasets.base.load_csv(filename=IRIS_TRAINING,
AttributeError: 'module' object has no attribute 'load_csv'
</code></pre>
<p>I read some answer saying that I need to use pandas dataframe? But shouldn't everything just works as in the tutorial? That is so strange! I should not be the only one facing this issue right?</p>
<p>Here's the whole code as in the tutorial:</p>
<pre><code>from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
import numpy as np
# Data sets
IRIS_TRAINING = "iris_training.csv"
IRIS_TEST = "iris_test.csv"
# Load datasets.
training_set = tf.contrib.learn.datasets.base.load_csv(filename=IRIS_TRAINING,
target_dtype=np.int)
test_set = tf.contrib.learn.datasets.base.load_csv(filename=IRIS_TEST,
target_dtype=np.int)
# Specify that all features have real-value data
feature_columns = [tf.contrib.layers.real_valued_column("", dimension=4)]
# Build 3 layer DNN with 10, 20, 10 units respectively.
classifier = tf.contrib.learn.DNNClassifier(feature_columns=feature_columns,
hidden_units=[10, 20, 10],
n_classes=3,
model_dir="/tmp/iris_model")
# Fit model.
classifier.fit(x=training_set.data,
y=training_set.target,
steps=2000)
# Evaluate accuracy.
accuracy_score = classifier.evaluate(x=test_set.data,
y=test_set.target)["accuracy"]
print('Accuracy: {0:f}'.format(accuracy_score))
# Classify two new flower samples.
new_samples = np.array(
[[6.4, 3.2, 4.5, 1.5], [5.8, 3.1, 5.0, 1.7]], dtype=float)
y = classifier.predict(new_samples)
print('Predictions: {}'.format(str(y)))
</code></pre>
| 0 | 2016-10-12T20:29:25Z | 40,032,112 | <p>The function <code>tf.contrib.learn.datasets.base.load_csv()</code> was removed in TensorFlow release 0.11. Depending on whether the file has a header or not (and the Iris dataset does have a header), the replacement functions are:</p>
<ul>
<li><a href="https://github.com/tensorflow/tensorflow/blob/fcab4308002412e38c1a6d5c6145119f04540d45/tensorflow/contrib/learn/python/learn/datasets/base.py#L38" rel="nofollow"><code>tf.contrib.learn.datasets.base.load_csv_with_headers()</code></a></li>
<li><a href="https://github.com/tensorflow/tensorflow/blob/fcab4308002412e38c1a6d5c6145119f04540d45/tensorflow/contrib/learn/python/learn/datasets/base.py#L57" rel="nofollow"><code>tf.contrib.learn.datasets.base.load_csv_without_headers()</code></a></li>
</ul>
| 1 | 2016-10-13T22:33:04Z | [
"python",
"tensorflow"
] |
Speeding up nested loops in python | 40,007,800 | <p>How can I speed up this code in python?</p>
<pre><code>while ( norm_corr > corr_len ):
correlation = 0.0
for i in xrange(6):
for j in xrange(6):
correlation += (p[i] * T_n[j][i]) * ((F[j] - Fbar) * (F[i] - Fbar))
Integral += correlation
T_n =np.mat(T_n) * np.mat(TT)
T_n = T_n.tolist()
norm_corr = correlation / variance
</code></pre>
<p>Here, TT is a fixed 6x6 matrix, p is a fixed 1x6 matrix, and F is fixed 1x6 matrix. T_n is the nth power of TT. </p>
<p>This while loop might be repeated for 10^4 times.</p>
| 0 | 2016-10-12T20:30:27Z | 40,007,999 | <p>The way to do these things quickly is to use Numpy's built-in functions and operators to perform the operations. Numpy is implemented internally with optimized C code and if you set up your computation properly, it will run much faster.</p>
<p>But leveraging Numpy effectively can sometimes be tricky. It's called "vectorizing" your code - you have to figure out how to express it in a way that acts on whole arrays, rather than with explicit loops.</p>
<p>For example in your loop you have <code>p[i] * T_n[j][i]</code>, which IMHO can be done with a vector-by-matrix multiplication: if v is 1x6 and m is 6x6 then <code>v.dot(m)</code> is 1x6 that computes dot products of <code>v</code> with the columns of <code>m</code>. You can use transposes and reshapes to work in different dimensions, if necessary.</p>
| 0 | 2016-10-12T20:41:54Z | [
"python",
"performance",
"loops"
] |
getpass.getpass() function in Python not working? | 40,007,802 | <p>Running on Windows 7 and using PyCharm 2016.2.3 if that matters at all.</p>
<p>Anyway, I'm trying to write a program that sends an email to recipients, but I want the console to prompt for a password to login.</p>
<p>I heard that <code>getpass.getpass()</code> can be used to hide the input. </p>
<p>Here is my code:</p>
<pre><code>import smtplib
import getpass
import sys
print('Starting...')
SERVER = "localhost"
FROM = "[email protected]"
while True:
password = getpass.getpass()
try:
smtpObj = smtplib.SMTP(SERVER)
smtpObj.login(FROM, password)
break
except smtplib.SMTPAuthenticationError:
print("Wrong Username/Password.")
except ConnectionRefusedError:
print("Connection refused.")
sys.exit()
TO = ["[email protected]"]
SUBJECT = "Hello!"
TEXT = "msg text"
message = """\
From: %s
To: %s
Subject: %s
%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
smtpObj.sendmail(FROM, TO, message)
smtpObj.close()
print("Successfully sent email")
</code></pre>
<p>But when I run my code, here is the output:</p>
<pre><code> Starting...
/Nothing else appears/
</code></pre>
<p>I know the default prompt for <code>getpass()</code> is <code>'Password:'</code> but I get the same result even when I pass it a prompt string.</p>
<p>Any suggestions?</p>
<p>EDIT: The code continues to run indefinitely after it prints the string, but nothing else appears and no emails are sent.</p>
| 0 | 2016-10-12T20:30:35Z | 40,008,031 | <p>The problem you have is that you are launching it via PyCharm, which has it's own console (and is not the console used by <code>getpass</code>)</p>
<p>Running the code via a command prompt should work</p>
| 1 | 2016-10-12T20:44:27Z | [
"python"
] |
Multiprocessing | Multithreading ffmpeg in python | 40,007,815 | <p>I am developing a <a href="https://github.com/lordcantide/Alien-FFMPEG-Transcoder-Framework-for-HDHomeRun-PRIME" rel="nofollow">python WSGI script</a> to interface with an HDHomeRun Prime. In a perfect world it will pass URI values as commands to FFMPEG and display the resulting stream in a browser. I have the "show stuff in browser" and the "pass instructions to FFMPEG" parts working fine, but I do not have them working simultaneously.</p>
<p>1) Given that this middleware is being used to transcode MPEG-2 to h.264, does it make more sense to use multiprocessing or multithread to start and stop the respective processes?</p>
<p>2) If the WSGI script is brokering the initiation of FFMPEG feeds (if the input feed isn't already brokered) and connecting clients to the associated FFServer streams, does mean I'll need to use some sort of pool to keep track of the middleware's activities?</p>
| 0 | 2016-10-12T20:31:02Z | 40,014,136 | <p>I don't really understand your whole process, but IMO you should start with <code>multithreading</code>, as it is much easier to setup (variables are shared like usual in Python). IF that doesn't meet your requirement (e.g not fast enough), you can move to <code>multiprocessing</code> but it will increase the complexity if you never used <code>multiprocessing</code> in Python (no communication between <code>process</code>, need to use <code>queues</code> or shared variables).</p>
<p>Setup your threads :</p>
<pre><code>import threading
a = threading.Thread(target = func, args=(vars))
a.start()
</code></pre>
<p>A nice tutorial <a href="https://pymotw.com/2/threading/" rel="nofollow">here.</a></p>
<p>You should also know about python's <a href="https://en.wikipedia.org/wiki/Global_interpreter_lock" rel="nofollow">GIL</a> to understand what you are doing in Threading/multiprocessing .</p>
| 0 | 2016-10-13T06:50:22Z | [
"python",
"ffmpeg",
"wsgi",
"python-multithreading",
"python-multiprocessing"
] |
How to save lists that have been changed during execution? | 40,007,864 | <p>So, Im making a text based Rpg (very similar to Progress Quest). The only lists worth saving are the weapons and items lists as well as your name and class. At the beginning of the game, you get those two lists emptied and your name reset to 0.</p>
<p><code>weapons = []</code> That is how it starts.</p>
<p><code>weapons = ["sword", "bow", "staff"]</code> That is how it ends.</p>
<p>I want a way to be able to start the same or a copy of the program with those elements saved. How do I do that? The following is the entire script... and please note, I'm making this just for fun and so i know ways to make it better and bigger; please, just comment on the topic im posting about.</p>
<pre><code>import time
import random
allThings = ["gold coin", "Silver Coin", "Copper Coin", "Twinkies",
"Human Tissue", "Stuffed Bear", "Hulk Toy", "Pen", "Bobblehead",
"Charger", "Lenovo Thinkpad Modle T420",
"Stephen King Book: Full Dark, No Stars", "Toy Laser Gun",
"Car Keys", "Alarm Clock", "Casio Watch", "Python Manual",
"Tissues", "Screws", "Spare CDs", "USB Flash Drive", "Spoon",
"Fork", "Kitchen Knife", "BasketBall", "Paper Bag",
"Crubled Paper", "Water Bottle", "Technical Document",
"Plastic Glove", "Toy Bus", "Gas Canister", "Bracelet",
"Space Suit", "Nuclear Bomb", "Test Tubes", "Light Bulb",
"Mirror", "Gun Powder", "Arrow", "Human Brain", "Human Heart",
"Human Kidney", "Human Lung", "Human Stomach"]
Enemies = ["a Corrupted Police Officer", "A Half-Lizard", "A Dog",
"A Failed Surgery Client"]
inv = []
Equip = []
EquipAll = ["Sharp Stick", "Sharp Metal Scrap", "Pin", "Pencil", "Raw Thick
Stick", "Moddified Stick", "Grandpa's Axe", "Cursed Axe", "Fine
Blade", "Wooden Sword", "BB Gun", "Nerf Gun", "Human Arm", "22.
Caliber Pistol", "45. Caliber Pistol", "Colt 45.", "9mm Pistol",
"Ice Staff", "Fire Staff", "5.66mm Bullpup Rifle", "7.22 Assault
Rifle", "357. Magnum", "44. Magnum", "FAL Rifle", "7.62mm Rifle",
"308. Rifle", "Laser Kilo Gun", "Laser Mega Gun",
"Laser Deca Gun", "Laser Hecto Gun", "Laser Giga Gun",
"Laser Tera Gun", "Laser Peta Gun", "Laser Exa Gun",
"Laser Zeta Gun", "Laser Yotta Gun", "Inferno Blade",
"Blade of the Red Dragon", "Frag Granade", "Spear", "Shotgun",
"308. Sniper Rifle", "Bow", "Attack Dog", "Rolling Pin"]
chance = ["1", "2", "3", "4", "5"]
debt = 1000000
name = 0
c = 0
x = 0
y = 0
def Start():
global debt
if len(inv)<10:
x = random.choice(allThings)
print "*********************************************************************"
print("You came across and executed " + random.choice(Enemies) + " ...")
time.sleep(5)
print "--------------------------------------------------------------------"
print("You found " + x + " ...")
inv.append(x)
c = random.choice(chance)
if c == ("1"):
print "----------------------------------------------------------------"
y = random.choice(EquipAll)
print("You found " + y + " as a weapon...")
Equip.append(y)
print "****************************************************************"
print "\n"
print "////////////////////////////////////////"
print("Name: " + name + " Race: " + race)
print"____________________________"
print("Debt due: " + str(debt))
print"____________________________"
print "Items: \n"
print inv
print "___________________________"
print "Weapons: \n"
print Equip
print "////////////////////////////////////////"
time.sleep(7)
print "\n"
print "\n"
print "\n"
print "\n"
print "\n"
print "\n"
print "\n"
print "\n"
print "\n"
print "\n"
Start()
elif len(inv)>9:
print "+++++++++++++++++++++++"
print "+Going to pawn shop...+"
print "+++++++++++++++++++++++"
time.sleep(5)
print("Selling " + str(inv) + " ...")
inv[:] = []
time.sleep(13)
print "\n"
print "Items sold. You got $10"
debt = debt - 10
time.sleep(5)
print "Heading back to the world"
time.sleep(10)
print "\n"
print "\n"
print "\n"
print "\n"
Start()
print "-------------------THE 2017 Executioner------------------------"
print"Select your name:"
name = raw_input()
print "\n"
print "Select your race: Half-Lizard, Octopus, etc (You can even make one up):"
race = raw_input()
print "\n"
print "One last thing... are you a man or a woman?"
sex = raw_input()
print "\n"
print "******************************************************************************"
print "****************************Your Story Begins Here****************************"
print "******************************************************************************"
print "\n"
print "\n"
print "Underground Medical Files:"
print "\n"
print("Our latest client, " + name + ", has suffered a terrible accident..."
+ name + " was brought here by some friends... We set up a 'full body "
"surgery' for this " + sex + " ..." + name + " decided to become a "
+ race + ".... this is the most expensive surgery we have ever done"
"... We thought " + name + " would be able to pay for it... But after "
"we said that they were in debt.... well, the client went full-on "
"beserk .... Now this " + race + " is going around the world doing "
"who-knows-what...." + "\n" + " Signed, /\\@..... Director of the "
"illegal underground Hospital and Surgeries")
xcv = raw_input("Press Enter to Begin...")
print "\n"
print "\n"
print "Loading..."
time.sleep(30)
print "\n"
Start()
</code></pre>
| 0 | 2016-10-12T20:33:28Z | 40,007,908 | <p>The canonical way to do this in Python is with the <code>pickle</code> module. For Python 3 the <a href="https://docs.python.org/3.5/library/pickle.html" rel="nofollow">documentation is here</a>. An example from this documentation:</p>
<pre><code>import pickle
# An arbitrary collection of objects supported by pickle.
data = {
'a': [1, 2.0, 3, 4+6j],
'b': ("character string", b"byte string"),
'c': {None, True, False}
}
with open('data.pickle', 'wb') as f:
# Pickle the 'data' dictionary using the highest protocol available.
pickle.dump(data, f, pickle.HIGHEST_PROTOCOL)
</code></pre>
<p>This example saves a nested data structure (a dict with some lists, sets and tuples in it) into a file named <code>data.pickle</code>. Here's how it can be loaded back:</p>
<pre><code>import pickle
with open('data.pickle', 'rb') as f:
# The protocol version used is detected automatically, so we do not
# have to specify it.
data = pickle.load(f)
</code></pre>
| 3 | 2016-10-12T20:36:43Z | [
"python",
"list",
"save"
] |
python pandas - identify row of rolling maximum value from panel? | 40,007,866 | <p>Does Panel have anything like pan.idxmax(axis='items') which could return the row # or index for the largest value as in the question linked below which piRSquared answered perfectly? </p>
<p><a href="http://stackoverflow.com/questions/40000718/python-pandas-possible-to-compare-3-dfs-of-same-shape-using-wheremax-is-thi">Link to original question</a></p>
<p>Thanks!</p>
| 1 | 2016-10-12T20:33:30Z | 40,026,017 | <p>consider the <code>pd.Panel</code> <code>p</code></p>
<pre><code>dfs = dict(
one=pd.DataFrame(np.random.randint(1, 10, (5, 5))),
two=pd.DataFrame(np.random.randint(1, 10, (5, 5))),
three=pd.DataFrame(np.random.randint(1, 10, (5, 5))),
)
p = pd.Panel(dfs)
p.to_frame().unstack()
</code></pre>
<p><a href="https://i.stack.imgur.com/i5lzc.png" rel="nofollow"><img src="https://i.stack.imgur.com/i5lzc.png" alt="enter image description here"></a></p>
<hr>
<p>the <code>pd.Panel</code> object doesn't have an <code>idxmax</code> method. But the underlying numpy array does have the <code>argmax</code> method. I've built this custom function to leverage that.</p>
<pre><code>def idxmax(pn, axis=0):
indices = pd.Series(['items', 'major_axis', 'minor_axis'])
idx, col = indices.drop(axis)
return pd.DataFrame(pn.values.argmax(axis),
pn.__getattribute__(idx),
pn.__getattribute__(col))
</code></pre>
<hr>
<p><strong><em>usage</em></strong> </p>
<pre><code>idxmax(p, 0)
</code></pre>
<p><a href="https://i.stack.imgur.com/yv19F.png" rel="nofollow"><img src="https://i.stack.imgur.com/yv19F.png" alt="enter image description here"></a></p>
<pre><code>idxmax(p, 1)
</code></pre>
<p><a href="https://i.stack.imgur.com/g6DCM.png" rel="nofollow"><img src="https://i.stack.imgur.com/g6DCM.png" alt="enter image description here"></a></p>
<pre><code>idxmax(p, 2)
</code></pre>
<p><a href="https://i.stack.imgur.com/Yj7QL.png" rel="nofollow"><img src="https://i.stack.imgur.com/Yj7QL.png" alt="enter image description here"></a></p>
| 1 | 2016-10-13T16:10:43Z | [
"python",
"pandas",
"max",
"panel",
"vectorization"
] |
Why Python pickling library complain about class member that doesn't exist? | 40,008,010 | <p>I have the following simple class definition:</p>
<pre><code>def apmSimUp(i):
return APMSim(i)
def simDown(sim):
sim.close()
class APMSimFixture(TestCase):
def setUp(self):
self.pool = multiprocessing.Pool()
self.sims = self.pool.map(
apmSimUp,
range(numCores)
)
def tearDown(self):
self.pool.map(
simDown,
self.sims
)
</code></pre>
<p>Where class APMSim is defined purely by plain simple python primitive types (string, list etc.) the only exception is a static member, which is a multiprocessing manager.list</p>
<p>However, when I try to execute this class, I got the following error information:</p>
<pre><code>Error
Traceback (most recent call last):
File "/home/peng/git/datapassport/spookystuff/mav/pyspookystuff_test/mav/__init__.py", line 77, in setUp
range(numCores)
File "/usr/lib/python2.7/multiprocessing/pool.py", line 251, in map
return self.map_async(func, iterable, chunksize).get()
File "/usr/lib/python2.7/multiprocessing/pool.py", line 567, in get
raise self._value
MaybeEncodingError: Error sending result: '[<pyspookystuff.mav.sim.APMSim object at 0x7f643c4ca8d0>]'. Reason: 'TypeError("can't pickle thread.lock objects",)'
</code></pre>
<p>Which is strange as thread.lock cannot be found anywhere, I strictly avoid any multithreading component (as you can see, only multiprocessing component is used). And none of these component exist in my class, or only as static member, what should I do to make this class picklable?</p>
<p>BTW, is there a way to exclude a black sheep member from pickling? Like Java's @transient annotation?</p>
<p>Thanks a lot for any help!</p>
<p><strong>UPDATE</strong>: The following is my full APMSim class, please see if you find anything that violates it picklability:</p>
<pre><code>usedINums = mav.manager.list()
class APMSim(object):
global usedINums
@staticmethod
def nextINum():
port = mav.nextUnused(usedINums, range(0, 254))
return port
def __init__(self, iNum):
# type: (int) -> None
self.iNum = iNum
self.args = sitl_args + ['-I' + str(iNum)]
@staticmethod
def create():
index = APMSim.nextINum()
try:
result = APMSim(index)
return result
except Exception as ee:
usedINums.remove(index)
raise
@lazy
def _sitl(self):
sitl = SITL()
sitl.download('copter', '3.3')
sitl.launch(self.args, await_ready=True, restart=True)
print("launching .... ", sitl.p.pid)
return sitl
@lazy
def sitl(self):
self.setParamAndRelaunch('SYSID_THISMAV', self.iNum + 1)
return self._sitl
def _getConnStr(self):
return tcp_master(self.iNum)
@lazy
def connStr(self):
self.sitl
return self._getConnStr()
def setParamAndRelaunch(self, key, value):
wd = self._sitl.wd
print("relaunching .... ", self._sitl.p.pid)
v = connect(self._getConnStr(), wait_ready=True) # if use connStr will trigger cyclic invocation
v.parameters.set(key, value, wait_ready=True)
v.close()
self._sitl.stop()
self._sitl.launch(self.args, await_ready=True, restart=True, wd=wd, use_saved_data=True)
v = connect(self._getConnStr(), wait_ready=True)
# This fn actually rate limits itself to every 2s.
# Just retry with persistence to get our first param stream.
v._master.param_fetch_all()
v.wait_ready()
actualValue = v._params_map[key]
assert actualValue == value
v.close()
def close(self):
self._sitl.stop()
usedINums.remove(self.iNum)
</code></pre>
<p>lazy decorator is from this library:</p>
<p><a href="https://docs.python.org/2/tutorial/classes.html#generator-expressions" rel="nofollow">https://docs.python.org/2/tutorial/classes.html#generator-expressions</a></p>
| 0 | 2016-10-12T20:42:42Z | 40,008,066 | <p>It would help to see how your class looks, but if it has methods from <code>multiprocessing</code> you may have issues just pickling it by default. Multiprocessing objects can use locks as well, and these are (obviously) unpickle-able.</p>
<p>You can customize pickling with the <a href="https://docs.python.org/dev/library/pickle.html?highlight=pickle#object.__getstate__" rel="nofollow"><code>__getstate__</code></a> method, or <code>__reduce__</code> (documented in the same place).</p>
| 0 | 2016-10-12T20:47:14Z | [
"python",
"serialization",
"pickle"
] |
Problems importing imblearn python package on ipython notebook | 40,008,015 | <p>I installed <a href="https://github.com/glemaitre/imbalanced-learn" rel="nofollow">https://github.com/glemaitre/imbalanced-learn</a> on windows powershell using pip install,conda and github. But when im on ipython notebook and i try importing the package using :</p>
<pre><code>from unbalanced_dataset import UnderSampler, OverSampler, SMOTE
</code></pre>
<p>I get the error:</p>
<hr>
<pre><code>ImportError Traceback (most recent call last) <ipython-input-9-ad6fd7440a05> in <module>()
----> 1 from imbalanced_learn import UnderSampler, OverSampler, SMOTE
ImportError: No module named imbalanced_learn
</code></pre>
<p>New to using windows for python, do i have to install the package in some folder?</p>
<p>Thanks!</p>
| 0 | 2016-10-12T20:42:45Z | 40,008,278 | <p>Try this:</p>
<pre><code>from imblearn import under_sampling, over_sampling
</code></pre>
<p>In order to import <code>SMOTE</code>:</p>
<pre><code>from imblearn.over_sampling import SMOTE
</code></pre>
<p>Or datasets:</p>
<pre><code>from imblearn.datasets import ...
</code></pre>
| 0 | 2016-10-12T21:01:38Z | [
"python",
"python-2.7",
"powershell",
"jupyter-notebook"
] |
scipy curve_fit strange result | 40,008,017 | <p>I am trying to fit a distribution with scipy's curve_fit. I tried to fit a one component exponential function which resulted in an almost straight line (see figure). I also tried a two component exponential fit which seemed to work nicely. Two components just means that a part of the equation repeats with different input parameters. Anyway, here is the one component fit function:</p>
<pre><code>def Exponential(Z,w0,z0,Z0):
z = Z - Z0
termB = (newsigma**2 + z*z0) / (numpy.sqrt(2.0)*newsigma*z0)
termA = (newsigma**2 - z*z0) / (numpy.sqrt(2.0)*newsigma*z0)
return w0/2.0 * numpy.exp(-(z**2 / (2.0*newsigma**2))) * (numpy.exp(termA**2)*erfc(termA) + numpy.exp(termB**2)*erfc(termB))
</code></pre>
<p>and the fitting is done with</p>
<pre><code>fitexp = curve_fit(Exponential,newx,y2)
</code></pre>
<p>Then I tried something, just to try it out. I took two parameters of the two component fit, but did not use them in the calculation.</p>
<pre><code>def ExponentialNew(Z,w0,z0,w1,z1,Z0):
z = Z - Z0
termB = (newsigma**2 + z*z0) / (numpy.sqrt(2.0)*newsigma*z0)
termA = (newsigma**2 - z*z0) / (numpy.sqrt(2.0)*newsigma*z0)
return w0/2.0 * numpy.exp(-(z**2 / (2.0*newsigma**2))) * (numpy.exp(termA**2)*erfc(termA) + numpy.exp(termB**2)*erfc(termB))
</code></pre>
<p>And suddenly this works.</p>
<p><a href="https://i.stack.imgur.com/jhq0S.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/jhq0S.jpg" alt="enter image description here"></a></p>
<p>Now, my quation is. WHY? As you can see, there is absolutely no difference in the calculation of the fit. It just gets two extra variables that are not used. Should this not get the same result?</p>
| 0 | 2016-10-12T20:42:49Z | 40,008,187 | <p>In my experience <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html" rel="nofollow"><code>curve_fit</code></a> can sometimes act up and stick with the initial values for the parameters. I would suspect that in your case adding a few fake parameters changed the heuristics of how the relevant parameters are being initialized (although this contradicts the documentation's statement that with no initial values given, they all default to 1).</p>
<p>It helps a lot in obtaining reliable fits if you specify reasonable bounds and initial values for your fitting parameters (I mean the <code>p0</code> and <code>bounds</code> keywords). The fact that the default starting values should all be <code>1</code> suggests that for most use cases, the default won't cut it.</p>
| 0 | 2016-10-12T20:54:36Z | [
"python",
"scipy"
] |
How to find methods which are only defined in a subclass, in Python 2.7? | 40,008,155 | <p>Is there a clean way to get methods only defined in a subclass that not defined in parent class?</p>
<pre><code>class Parent(object):
def method_of_parent(self):
pass
class SubClass(Parent):
def method_of_subclass(self):
pass
# desired:
>>> print(get_subclass_methods(SubClass))
['method_of_subclass',]
</code></pre>
| 3 | 2016-10-12T20:52:32Z | 40,008,332 | <p>I think there are many corner cases but here is one of solutions.</p>
<pre><code>import inspect
class Parent(object):
def method_of_parent(self):
pass
class SubClass(Parent):
def method_of_subclass(self):
pass
def get_subclass_methods(child_cls):
parents = inspect.getmro(child_cls)[1:]
parents_methods = set()
for parent in parents:
members = inspect.getmembers(parent, predicate=inspect.ismethod)
parents_methods.update(members)
child_methods = set(inspect.getmembers(child_cls, predicate=inspect.ismethod))
child_only_methods = child_methods - parents_methods
return [m[0] for m in child_only_methods]
print(get_subclass_methods(SubClass))
</code></pre>
<p>Result</p>
<pre><code>['method_of_subclass']
</code></pre>
| 3 | 2016-10-12T21:05:22Z | [
"python",
"python-2.7",
"methods",
"subclass"
] |
python error parsing json | 40,008,219 | <p>I'm trying to parse the information found in this link here: <a href="http://stats.nba.com/stats/playergamelog?DateFrom=&DateTo=&LeagueID=00&PlayerID=203518&Season=2016-17&SeasonType=Pre+Season" rel="nofollow">http://stats.nba.com/stats/playergamelog?DateFrom=&DateTo=&LeagueID=00&PlayerID=203518&Season=2016-17&SeasonType=Pre+Season</a></p>
<p>What I want to pull is the information under rowSet (so 0, 1, 2, etc will be one entry) <a href="https://i.stack.imgur.com/aW5cS.png" rel="nofollow"><img src="https://i.stack.imgur.com/aW5cS.png" alt="enter image description here"></a></p>
<p>Code I'm using: </p>
<pre><code>import requests
urlPlayerLog = "http://stats.nba.com/stats/playergamelog?DateFrom=&DateTo=&LeagueID=00&PlayerID=203518&Season=2016-17&SeasonType=Pre+Season"
responses = requests.get(urlPlayerLog)
dataGameLogs = responses.json()['resultSets'][0]['rowSet']
</code></pre>
<p>This was working for me for months and then one day I kept getting the following error:
<a href="https://i.stack.imgur.com/WXYXt.png" rel="nofollow"><img src="https://i.stack.imgur.com/WXYXt.png" alt="enter image description here"></a></p>
<p>Which made me think the issue was with dataGameLogs = responses.json()['resultSets'][0]['rowSet'] , but unsure why that is returning an error...</p>
| 0 | 2016-10-12T20:57:31Z | 40,008,954 | <p>The webpage might be expecting a web browser to request the data from the URL. Try adding a user-agent to your request.</p>
<pre><code>import requests
HEADERS = {'user-agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:35.0) Gecko/20100101 Firefox/31.0'}
urlPlayerLog = "http://stats.nba.com/stats/playergamelog?DateFrom=&DateTo=&LeagueID=00&PlayerID=203518&Season=2016-17&SeasonType=Pre+Season"
responses = requests.get(urlPlayerLog, headers=HEADERS)
dataGameLogs = responses.json()['resultSets'][0]['rowSet']
</code></pre>
| 1 | 2016-10-12T21:50:03Z | [
"python",
"json",
"django"
] |
Latest versions of Python 3 and PyQt5 working on Windows XP 32bit | 40,008,236 | <p>I developed a program with Python 3 64bit and PyQt5 on Debian 64bit (of course it works on Linux and Windows 10 64bit). The problem is I cannot find the last version (if it exists at all) of PyQt5 working on Windows XP 32bit. As I have read, it seems that Python version 3.4.4 is the newest/latest to work with Windows XP, and it is currently working.</p>
<p>I tried <code>pip3 install PyQt5</code>, but with no luck. I get: </p>
<blockquote>
<p>$ pip3 install PyQt5</p>
<p>Collecting PyQt5</p>
<p>Could not find a version that satisfies the requierement PyQt5 (from versions:)</p>
<p>No matching distribution for PyQt5</p>
</blockquote>
<p>I looked at the official website of <a href="https://www.riverbankcomputing.com/software/pyqt/download5" rel="nofollow" title="Pyqt5">PyQt5</a>, without luck, to find some kind of installer. It may be there somewhere, but I'm used to just making a <code>pip3 install [package]</code>, and done.</p>
| 0 | 2016-10-12T20:59:12Z | 40,008,706 | <p>You can find an archive of earlier installers and source code on sourceforge:</p>
<ul>
<li><a href="https://sourceforge.net/projects/pyqt/files/PyQt5/" rel="nofollow">https://sourceforge.net/projects/pyqt/files/PyQt5/</a></li>
</ul>
<p>The latest 32bit Windows installer for Python-3.4 seems to be for PyQt-5.5.1.</p>
| 0 | 2016-10-12T21:31:38Z | [
"python",
"windows",
"python-3.x",
"windows-xp",
"pyqt5"
] |
How to process panel data for use in a recurrent neural network (RNN) | 40,008,240 | <p>I have been doing some research on recurrent neural networks, but I am having trouble understanding if and how they could be used to analyze panel data (meaning cross-sectional data that is captured at different periods in time for several subjects -- see sample data below for example).Most examples of RNNs I have seen have to do with sequences of text, rather than true panel data, so I'm not sure if they are applicable to this type of data.</p>
<p>Sample data:</p>
<pre><code>ID TIME Y X1 X2 X3
1 1 5 3 0 10
1 2 5 2 2 6
1 3 6 6 3 11
2 1 2 2 7 2
2 2 3 3 1 19
2 3 3 8 6 1
3 1 7 0 2 0
</code></pre>
<p>If I want to predict Y at a particular time given the covariates X1, X2 and X3 (as well as their values in previous time periods), can this kind of sequence be evaluated by a recurrent neural network? If so, do you have any resources or ideas on how to turn this type of data into feature vectors and matching labels that can be passed to an RNN (I'm using Python, but am open to other implementations).</p>
| 0 | 2016-10-12T20:59:32Z | 40,009,286 | <p>I find no reason in being able to train neural network with panel data. What neural network does is that it maps one set of values with other set of values who have non-linear relation. In a time series a value at a particular instance depends on previous occuring values. Example: your pronunciation of a letter may vary depending on what letter you pronounced just earlier. For time series prediction Recurrent Neural Network outperforms feed-forward neural networks. How we train time series with a regular feed-forward network is illustrated in this picture. <a href="http://www.obitko.com/tutorials/neural-network-prediction/images/train.gif" rel="nofollow">Image</a></p>
<p>In RNN we can create a feedback loop in the internal states of the network and that's why RNN is better at predicting time series.
In your example data one thing to consider : do values of x1, x2, x3 have effect on y1 or vice-versa ? If it doesn't then you can train your model as such x1,x2,x3, y4 are same type of data i.e train them independently using same network (subject to experimentation). If your target is to predict a value where their values of one has effect on another i.e correlated you can convert them to one dimensional data where single time frame contains all variants of sample type. Another way might be train four neural networks where first three map their time series using RNN and last one is a feed-forward network which takes 2 inputs from 2 time series output and maps to 3rd time series output and do this for all possible combinations. (still subject to experimentation as we can't surely predict the performance of neural network model without experimenting)</p>
<p><strong>Reading suggestion:</strong> Read about "Granger causality", might help you a bit.</p>
| 0 | 2016-10-12T22:17:33Z | [
"python",
"recurrent-neural-network",
"panel-data"
] |
Need Help in python3, Wnat to set variables like they are increasing | 40,008,273 | <p>any ideas how to take middle number and put in middle of min and max?</p>
<pre><code>x=input('Pirveli: ')
y=input('Meore: ')
z=input('Mesame: ')
list = (ord(x),ord(y),ord(z))
print(min(list),(MIDDLENUMBER HERE),max(list))
</code></pre>
<p>any ideas?</p>
| -3 | 2016-10-12T21:01:19Z | 40,008,294 | <p>Yes. You can sort the list, and you'll get what you need.</p>
<pre><code>> lst = [4, 5, 3]
> lst.sort()
> lst
[3, 4, 5]
</code></pre>
<p>You can also use <code>sorted</code> in a more general way on iterable objects. For example, given a tuple with <code>x</code>, <code>y</code>, <code>z</code>:</p>
<pre><code>> x = 6
> y = 2
> z = 3
> sorted((x, y, z))
[2, 3, 6]
</code></pre>
| 2 | 2016-10-12T21:02:49Z | [
"python"
] |
Repeat a string n times and print n lines of it | 40,008,279 | <p>i've been stuck on a question for some time now:</p>
<p>I'm looking to create a python function that consumes a string and a positive integer. The function will print the string n times, for n lines. I <strong>cannot</strong> use loops, i must only use recursion</p>
<p>e.g.</p>
<pre><code>repeat("hello", 3)
hellohellohello
hellohellohello
hellohellohello
</code></pre>
<p>whenever i try to make a function that does this, the function decreases the length of the string, progressively:</p>
<p>e.g.</p>
<pre><code>repeat("hello", 3)
hellohellohello
hellohello
hello
</code></pre>
<p>here's what my code looks like:</p>
<pre><code>def repeat(a, n):
if n == 0:
print(a*n)
else:
print(a*n)
repeat(a, n-1)
</code></pre>
<p>any help would be appreciated, thanks!</p>
| 1 | 2016-10-12T21:01:41Z | 40,008,347 | <p>Try this</p>
<pre><code>def f(string, n, c=0):
if c < n:
print(string * n)
f(string, n, c=c + 1)
f('abc', 3)
</code></pre>
| 3 | 2016-10-12T21:06:10Z | [
"python",
"recursion"
] |
Repeat a string n times and print n lines of it | 40,008,279 | <p>i've been stuck on a question for some time now:</p>
<p>I'm looking to create a python function that consumes a string and a positive integer. The function will print the string n times, for n lines. I <strong>cannot</strong> use loops, i must only use recursion</p>
<p>e.g.</p>
<pre><code>repeat("hello", 3)
hellohellohello
hellohellohello
hellohellohello
</code></pre>
<p>whenever i try to make a function that does this, the function decreases the length of the string, progressively:</p>
<p>e.g.</p>
<pre><code>repeat("hello", 3)
hellohellohello
hellohello
hello
</code></pre>
<p>here's what my code looks like:</p>
<pre><code>def repeat(a, n):
if n == 0:
print(a*n)
else:
print(a*n)
repeat(a, n-1)
</code></pre>
<p>any help would be appreciated, thanks!</p>
| 1 | 2016-10-12T21:01:41Z | 40,008,351 | <p>You were really close.</p>
<pre><code>def repeat(a, n):
def rep(a, c):
if c > 0:
print(a)
rep(a, c - 1)
return rep(a * n, n)
print(repeat('ala', 2))
alaala
alaala
</code></pre>
<p>A function with closure would do the job.</p>
| 0 | 2016-10-12T21:06:15Z | [
"python",
"recursion"
] |
Repeat a string n times and print n lines of it | 40,008,279 | <p>i've been stuck on a question for some time now:</p>
<p>I'm looking to create a python function that consumes a string and a positive integer. The function will print the string n times, for n lines. I <strong>cannot</strong> use loops, i must only use recursion</p>
<p>e.g.</p>
<pre><code>repeat("hello", 3)
hellohellohello
hellohellohello
hellohellohello
</code></pre>
<p>whenever i try to make a function that does this, the function decreases the length of the string, progressively:</p>
<p>e.g.</p>
<pre><code>repeat("hello", 3)
hellohellohello
hellohello
hello
</code></pre>
<p>here's what my code looks like:</p>
<pre><code>def repeat(a, n):
if n == 0:
print(a*n)
else:
print(a*n)
repeat(a, n-1)
</code></pre>
<p>any help would be appreciated, thanks!</p>
| 1 | 2016-10-12T21:01:41Z | 40,008,383 | <p>So you just need extra argument that will tell you how many times you already ran that function, and it should have default value, because in first place function must take two arguments(<code>str</code> and positive number).</p>
<pre><code>def repeat(a, n, already_ran=0):
if n == 0:
print(a*(n+already_ran))
else:
print(a*(n+already_ran))
repeat(a, n-1, already_ran+1)
repeat('help', 3)
</code></pre>
<p>Output</p>
<pre><code>helphelphelp
helphelphelp
helphelphelp
helphelphelp
</code></pre>
| 1 | 2016-10-12T21:08:33Z | [
"python",
"recursion"
] |
Repeat a string n times and print n lines of it | 40,008,279 | <p>i've been stuck on a question for some time now:</p>
<p>I'm looking to create a python function that consumes a string and a positive integer. The function will print the string n times, for n lines. I <strong>cannot</strong> use loops, i must only use recursion</p>
<p>e.g.</p>
<pre><code>repeat("hello", 3)
hellohellohello
hellohellohello
hellohellohello
</code></pre>
<p>whenever i try to make a function that does this, the function decreases the length of the string, progressively:</p>
<p>e.g.</p>
<pre><code>repeat("hello", 3)
hellohellohello
hellohello
hello
</code></pre>
<p>here's what my code looks like:</p>
<pre><code>def repeat(a, n):
if n == 0:
print(a*n)
else:
print(a*n)
repeat(a, n-1)
</code></pre>
<p>any help would be appreciated, thanks!</p>
| 1 | 2016-10-12T21:01:41Z | 40,008,384 | <p>You should (optionally) pass a 3rd parameter that handles the decrementing of how many lines are left:</p>
<pre><code>def repeat(string, times, lines_left=None):
print(string * times)
if(lines_left is None):
lines_left = times
lines_left = lines_left - 1
if(lines_left > 0):
repeat(string, times, lines_left)
</code></pre>
| 1 | 2016-10-12T21:08:34Z | [
"python",
"recursion"
] |
Repeat a string n times and print n lines of it | 40,008,279 | <p>i've been stuck on a question for some time now:</p>
<p>I'm looking to create a python function that consumes a string and a positive integer. The function will print the string n times, for n lines. I <strong>cannot</strong> use loops, i must only use recursion</p>
<p>e.g.</p>
<pre><code>repeat("hello", 3)
hellohellohello
hellohellohello
hellohellohello
</code></pre>
<p>whenever i try to make a function that does this, the function decreases the length of the string, progressively:</p>
<p>e.g.</p>
<pre><code>repeat("hello", 3)
hellohellohello
hellohello
hello
</code></pre>
<p>here's what my code looks like:</p>
<pre><code>def repeat(a, n):
if n == 0:
print(a*n)
else:
print(a*n)
repeat(a, n-1)
</code></pre>
<p>any help would be appreciated, thanks!</p>
| 1 | 2016-10-12T21:01:41Z | 40,008,504 | <p>One liner</p>
<pre><code>def repeat(a,n):
print((((a*n)+'\n')*n)[:-1])
</code></pre>
<p>Let's split this up</p>
<ol>
<li><code>a*n</code> repeats string <code>n</code> times, which is what you want in one line</li>
<li><code>+'\n'</code> adds a new line to the string so that you can go to the next line</li>
<li><code>*n</code> because you need to repeat it <code>n</code> times</li>
<li>the <code>[:-1]</code> is to remove the last <code>\n</code> as <code>print</code> puts a new-line by default. </li>
</ol>
| 2 | 2016-10-12T21:17:17Z | [
"python",
"recursion"
] |
Looping through table to calculate separations - Python | 40,008,450 | <p>Okay so I have a table of xy coordinates for a bunch of different points like this:</p>
<blockquote>
<pre><code> ID X Y
1 403.294 111.401
2 1771.424 62.183
3 804.812 71.674
4 2066.54 43.456
5 2208.55 40.907
</code></pre>
</blockquote>
<p>Each row represents an object with its ID, X, and Y listed. In reality, my table contains about 1345 rows. What I'm trying to do is loop through each row and calculate the separation of that object from all other objects in the table which I'll eventually use to make a histogram. What I have so far is: </p>
<pre><code>sep_dat = np.zeros(shape=(5,5)) #create array for writing into
dat = np.loadtxt('SEA_mini_test.tab') #table of data
IDs = dat[:,0]
X_dat = dat[:,1]
X_dat = np.sort(X_dat)
Y_dat = dat[:,2]
Y_dat = np.sort(Y_dat)
for i, x, y in zip(xrange(len(X_dat)), X_dat, Y_dat):
sep_dat[i] = math.sqrt((x-X_dat)**2+(y-Y_dat)**2)
np.savetxt('SEA_mini_seps.dat', sep_dat, fmt='%10.9f')
</code></pre>
<p>But I have yet to get it to run successfully. The last error I got was: </p>
<blockquote>
<p>TypeError: only length-1 arrays can be converted to Python scalars</p>
</blockquote>
<p>So how can I get this to run properly? </p>
<p>And how could I get it to ignore itself when its doing the calculations? Like for object 1 (row 1) I don't want it to calculate the separation from itself. I tried adding the IDs into zip and adding an if statement inside the for loop before the calculation like <code>if id != id:</code> but that wouldn't work. Does anyone have an idea on how I could do this?</p>
<p>And another question I had was, how could I write all the data into a flattened array? Right now, I have it create an empty array of zeros that I write over with the calculated values, but in the end I get a (5,5) array. But I want a (5,1) so that I can plot it as a histogram. Any ideas?</p>
| 0 | 2016-10-12T21:13:25Z | 40,008,592 | <p>The error occurs because math.sqrt() can only take a float value, if you pass an np.array it will attempt to convert to a float. This only works if the array contains a single value.</p>
<pre><code>> math.sqrt(np.array([2]))
1.4142135623730951
> math.sqrt(np.array([2,1])) Traceback (most recent call last):
File "<ipython-input-49-f9a9c77bfbdf>", line 1, in <module>
math.sqrt(np.array([2,1]))
TypeError: only length-1 arrays can be converted to Python scalars
</code></pre>
<p>You can use np.sqrt() which will return an array of square roots.</p>
<pre><code>> x = np.arange(1,5) #[1,2,3,4]
> y = x[::-1] #[4,3,2,1]
> z = x**2 + y**2 #[1*1+4*4,...,4*4+1*1]
> np.sqrt(z)
array([ 4.12310563, 3.60555128, 3.60555128, 4.12310563])
</code></pre>
<p>If this is the desired behaviour</p>
| 1 | 2016-10-12T21:24:06Z | [
"python",
"loops",
"numpy"
] |
Rename colum header from another dataframe | 40,008,455 | <p>I have two dataframes where 1, 2, 3 is the connection between the dataframes:</p>
<pre><code> 1 2 3
2016-10-03 12 10 10
2016-10-04 4 4 5
......
and
name year
1 apple 2001
2 lemon 2002
3 kiwi 1990
</code></pre>
<p>The end result should be:</p>
<pre><code> apple lemon kiwi
2016-10-03 12 10 10
2016-10-04 4 4 5
......
</code></pre>
<p>I can't figure out how to do this. </p>
| 0 | 2016-10-12T21:13:47Z | 40,008,663 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.rename.html" rel="nofollow"><code>rename</code></a>, which does not require the two DataFrames to have the keys in the same order:</p>
<pre><code>df1 = df1.rename(columns=df2['name'])
</code></pre>
| 0 | 2016-10-12T21:28:44Z | [
"python",
"pandas",
"dataframe"
] |
yes/no input loop, issues with with correct looping | 40,008,477 | <p>I'm programming a short guessing game. But, I have no idea how prevent incorrect input (yes/no), preventing user to go forward. Here's a WORKING code. Tried with while True but it only messes the input even more. The furthest is that else, that notifies the player, but the q count move forward. </p>
<pre><code># -*- coding: cp1250 -*-
import sys
def genVprasanja ():
yes = set(['yes','y', ''])
no = set(['no','n'])
testQ = ['hello1', 'hello33112', 'hello332', 'hello2', 'hello4','hellomore', 'ANSWER', 'hello1', 'hello33112', 'hello332', 'hello2', 'hello4','hellomore', 'ANSWER2', 'hello1', 'hello33112', 'hello332', 'hello2', 'hello4','hellomore', 'ANSWER3']
points = 5
total = 0
for x in range(0,3):
for y in xrange(len(testQ)):
reply = str(raw_input('\n'+str(abs(y-5))+ ' - ' + testQ[y]+' (y/n) --> ')).lower().strip()
if reply in yes:
print '\ncorect!\n\nAnswer is :',testQ[5], '\n\nPoints: ',points, '\n'
total = total + points
print 'Total: ', total, '\n'
break
elif reply in no:
points = points - 1
if points != 0:
print '\nwrong!', '\n\nNext question for: ',points
else:
print '\nThe end!\n\n' 'Every anwser is wrong!\n\nYou got 0 points.\n\Correct answer is:', testQ[5],'\n\n'
total = total + points
print 'SKUPNE TOÄKE: ', total
break
else:
sys.stdout.write("\nPlease press 'RETURN' or 'N'\n")
points = 5
genVprasanja()
</code></pre>
<p>Edit:</p>
<p>Every player gets to answer three sets of 5 questions. They receive questions until they say yes. If they say no 5 times the loop ends (3x times) - I'm using <code>var points</code> to count. </p>
<p>But if they input and incorrect words (not no and not yes) the input question repeats itself asking them again (until they enter a valid answer). After that they get THE SAME question they failed to validly answer.</p>
| 0 | 2016-10-12T21:15:32Z | 40,008,780 | <p>You need a 'while' in here somewhere, once you hit the end of the 'for' block it will go to the next value in the range.</p>
<pre><code>for y in xrange(len(testQ)):
bGoodInput = False
while not bGoodInput:
reply = str(raw_input('\n'+str(abs(y-5))+ ' - ' + testQ[y]+' (y/n) --> ')).lower().strip()
if reply in yes:
...
bGoodInput = True
elif reply in no:
...
bGoodInput = True
else:
...
</code></pre>
| 0 | 2016-10-12T21:37:29Z | [
"python",
"loops"
] |
yes/no input loop, issues with with correct looping | 40,008,477 | <p>I'm programming a short guessing game. But, I have no idea how prevent incorrect input (yes/no), preventing user to go forward. Here's a WORKING code. Tried with while True but it only messes the input even more. The furthest is that else, that notifies the player, but the q count move forward. </p>
<pre><code># -*- coding: cp1250 -*-
import sys
def genVprasanja ():
yes = set(['yes','y', ''])
no = set(['no','n'])
testQ = ['hello1', 'hello33112', 'hello332', 'hello2', 'hello4','hellomore', 'ANSWER', 'hello1', 'hello33112', 'hello332', 'hello2', 'hello4','hellomore', 'ANSWER2', 'hello1', 'hello33112', 'hello332', 'hello2', 'hello4','hellomore', 'ANSWER3']
points = 5
total = 0
for x in range(0,3):
for y in xrange(len(testQ)):
reply = str(raw_input('\n'+str(abs(y-5))+ ' - ' + testQ[y]+' (y/n) --> ')).lower().strip()
if reply in yes:
print '\ncorect!\n\nAnswer is :',testQ[5], '\n\nPoints: ',points, '\n'
total = total + points
print 'Total: ', total, '\n'
break
elif reply in no:
points = points - 1
if points != 0:
print '\nwrong!', '\n\nNext question for: ',points
else:
print '\nThe end!\n\n' 'Every anwser is wrong!\n\nYou got 0 points.\n\Correct answer is:', testQ[5],'\n\n'
total = total + points
print 'SKUPNE TOÄKE: ', total
break
else:
sys.stdout.write("\nPlease press 'RETURN' or 'N'\n")
points = 5
genVprasanja()
</code></pre>
<p>Edit:</p>
<p>Every player gets to answer three sets of 5 questions. They receive questions until they say yes. If they say no 5 times the loop ends (3x times) - I'm using <code>var points</code> to count. </p>
<p>But if they input and incorrect words (not no and not yes) the input question repeats itself asking them again (until they enter a valid answer). After that they get THE SAME question they failed to validly answer.</p>
| 0 | 2016-10-12T21:15:32Z | 40,008,786 | <p><code>while True:</code> will work, you need to <code>break</code> out of the loop once the conditions have been met.</p>
<pre><code>while True:
reply = str(raw_input('\n' + str(abs(y - 5)) + ' - ' + testQ[y] + ' (y/n) --> ')).lower().strip()
if reply in yes or reply in no:
break
</code></pre>
<p>Based on the updated scope, try this, it seems the <code>break</code> may have caused you issues:</p>
<pre><code>reply = False
while reply not in yes and reply not in no:
reply = str(raw_input('\n' + str(abs(y - 5)) + ' - ' + testQ[y] + ' (y/n) --> ')).lower().strip()
</code></pre>
| 1 | 2016-10-12T21:38:12Z | [
"python",
"loops"
] |
Printing from lists | 40,008,526 | <p>I've got 3 different lists, all the data inside is coming from an external CSV file which works although how do I print each name with each number next to them</p>
<pre><code>name = []
number1 = []
number2 = []
</code></pre>
<p>for example expected output is, although I'm unsure how I would do this</p>
<pre><code>LOOP (12) as there is 12 names and numbers in each lsit
Test, 5, 20
</code></pre>
| -5 | 2016-10-12T21:18:42Z | 40,008,630 | <p>You are probably looking for something like this:</p>
<pre><code>name = ["Test1", "Test2", "Test3"]
number1 = [1,2,3]
number2 = [4,5,6]
k=0
for v in name:
print(v + ", " + str(number1[k]) + ", " + str(number2[k]))
k+=1
</code></pre>
<p><strong>EDIT</strong></p>
<p>As MSeifert mentioned in the comment bellow here is better solution with enumerate:</p>
<pre><code>name = ["Test1", "Test2", "Test3"]
number1 = [1,2,3]
number2 = [4,5,6]
for k,v in enumerate(name):
print(v + ", " + str(number1[k]) + ", " + str(number2[k]))
</code></pre>
| 1 | 2016-10-12T21:26:45Z | [
"python",
"list"
] |
Printing from lists | 40,008,526 | <p>I've got 3 different lists, all the data inside is coming from an external CSV file which works although how do I print each name with each number next to them</p>
<pre><code>name = []
number1 = []
number2 = []
</code></pre>
<p>for example expected output is, although I'm unsure how I would do this</p>
<pre><code>LOOP (12) as there is 12 names and numbers in each lsit
Test, 5, 20
</code></pre>
| -5 | 2016-10-12T21:18:42Z | 40,009,091 | <p>Here's a way to do it using zip:</p>
<pre><code>for triplet in zip(name, number1, number2):
print(", ".join(map(str, triplet)))
</code></pre>
<p>triplet is a 3-tuple <code>(a, b, c)</code> with the corresponding element from the 3 lists (in other words, they are zipped)</p>
| 1 | 2016-10-12T22:00:47Z | [
"python",
"list"
] |
Trying to install pycrypto on mac OS El capitan 10.11.6 | 40,008,571 | <p>Trying to install pycrypto, running into an error </p>
<p>When i run </p>
<pre><code>> sudo pip install pycrypto
</code></pre>
<p>I get </p>
<blockquote>
<p>Command "/usr/bin/python -u -c "import setuptools,
tokenize;<strong>file</strong>='/private/tmp/pip-build-tTSWlY/pycrypto/setup.py';exec(compile(getattr(tokenize,
'open', open)(<strong>file</strong>).read().replace('\r\n', '\n'), <strong>file</strong>,
'exec'))" install --record /tmp/pip-f6nrNy-record/install-record.txt
--single-version-externally-managed --compile" failed with error code 1 in /private/tmp/pip-build-tTSWlY/pycrypto/</p>
</blockquote>
| -2 | 2016-10-12T21:22:27Z | 40,009,161 | <p>Using <a href="http://conda.pydata.org/miniconda.html" rel="nofollow">miniconda</a>, you can simply do:</p>
<p><code>conda install pycrypto</code></p>
| 0 | 2016-10-12T22:06:17Z | [
"python",
"osx",
"terminal",
"osx-elcapitan",
"pycrypto"
] |
How to convert some string fields in list to integer in Python? | 40,008,661 | <p>I have a string list and want to convert last value to integer, </p>
<pre><code>[['wind turbine', 'feed induction generator', '16'],
['wind turbine', 'dynamic model', '6'],
['electrical model', 'dynamic model', '4']]
</code></pre>
<p>I want just convert last fields to integer. </p>
<p>results something like this:</p>
<pre><code>[['wind turbine', 'feed induction generator', 16 ],
['wind turbine', 'dynamic model', 6 ],
['electrical model', 'dynamic model', 4 ]]
</code></pre>
| -5 | 2016-10-12T21:28:25Z | 40,008,971 | <pre><code>L = [['wind turbine', 'feed induction generator', '16'],['wind turbine', 'dynamic model', '6'],['electrical model', 'dynamic model', '4']]
for i in L:
i[-1] = int(i[-1])
print(L)
</code></pre>
<p>hope this helps</p>
| -2 | 2016-10-12T21:51:16Z | [
"python"
] |
How to convert some string fields in list to integer in Python? | 40,008,661 | <p>I have a string list and want to convert last value to integer, </p>
<pre><code>[['wind turbine', 'feed induction generator', '16'],
['wind turbine', 'dynamic model', '6'],
['electrical model', 'dynamic model', '4']]
</code></pre>
<p>I want just convert last fields to integer. </p>
<p>results something like this:</p>
<pre><code>[['wind turbine', 'feed induction generator', 16 ],
['wind turbine', 'dynamic model', 6 ],
['electrical model', 'dynamic model', 4 ]]
</code></pre>
| -5 | 2016-10-12T21:28:25Z | 40,008,991 | <p>Update : Added support for float numbers. </p>
<p>We can use <code>isdigit()</code> for positive int and <code>str(x).startswith('-') and x[1:].isdigit()</code> for negative int as well as <code>isFloat(aNumber)</code> for float numbers. </p>
<p>Below code works with both positive and negative int.</p>
<pre><code>myList = [['wind turbine', 'feed induction generator', '16'],
['wind turbine', 'dynamic model', '6'],
['electrical model', 'dynamic model', '4']]
def isFloat(aNumber):
try:
float(aNumber)
return True
except:
return False
finalList = []
for subList in myList:
aList = []
for x in subList:
if x.isdigit():
aList.append(int(x))
elif str(x).startswith('-') and x[1:].isdigit():
aList.append(int(x))
elif isFloat(x):
aList.append(float(x))
else:
aList.append(x)
finalList.append(aList)
print finalList
</code></pre>
<p><strong>Output:</strong></p>
<blockquote>
<p>Python 2.7.9 (default, Dec 10 2014, 12:24:55) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.</p>
<blockquote>
<blockquote>
<p>=================================================</p>
<p>[['wind turbine', 'feed induction generator', 16], ['wind turbine', 'dynamic model', 6], ['electrical model', 'dynamic model', 4]]</p>
</blockquote>
</blockquote>
</blockquote>
| -2 | 2016-10-12T21:52:38Z | [
"python"
] |
How can I define a Nix environment that defaults to Python 3.5 | 40,008,731 | <p>I have defined a the following environment in <code>default.nix</code>:</p>
<pre><code>with import <nixpkgs> {};
stdenv.mkDerivation rec {
name = "env";
env = buildEnv { name = name; paths = buildInputs; };
buildInputs = [
python35
python35Packages.pyyaml
];
}
</code></pre>
<p>If I run <code>nix-shell</code>, <code>python</code> will still be the system python at <code>/usr/bin/python</code> (running on Ubuntu) while <code>python3</code> is a symlink to the Python 3.5 binary installed by Nix. Is there a way to define the environment so that <code>python</code> is pointing to the Nix Python 3.5?</p>
| 1 | 2016-10-12T21:33:56Z | 40,016,749 | <p>One simple solution could be to add a shell hook to your environment, to define an alias from <code>python</code> to <code>python3</code>. This alias will be active only when you run <code>nix-shell</code>:</p>
<pre><code>with import <nixpkgs> {};
stdenv.mkDerivation rec {
name = "env";
env = buildEnv { name = name; paths = buildInputs; };
buildInputs = [
python35
python35Packages.pyyaml
];
# Customizable development shell setup
shellHook = ''
alias python='python3'
'';
}
</code></pre>
| 1 | 2016-10-13T09:10:15Z | [
"python",
"nix"
] |
Export multiple scraped files in python from beautiful soup to a cvs file | 40,008,742 | <p>I have a csv list of urls that I need to scrape and organize into a csv file. I want the data from each url to be a row in the csv file. I have about 19000 urls to scrape, but am trying to figure this out using only handful. I am able to scrape the files and view them in the terminal, but when I export them to the csv file only the last file appears. </p>
<p>The urls appear in the csv file as:</p>
<p><a href="http://www.gpo.gov/fdsys/pkg/CREC-2005-01-26/html/CREC-2005-01-26-pt1-PgH199-6.htm" rel="nofollow">http://www.gpo.gov/fdsys/pkg/CREC-2005-01-26/html/CREC-2005-01-26-pt1-PgH199-6.htm</a></p>
<p><a href="http://www.gpo.gov/fdsys/pkg/CREC-2005-01-26/html/CREC-2005-01-26-pt1-PgH200-3.htm" rel="nofollow">http://www.gpo.gov/fdsys/pkg/CREC-2005-01-26/html/CREC-2005-01-26-pt1-PgH200-3.htm</a></p>
<p>I have a feeling I am doing something wrong with my loop, but can't seem to figure out where. Any help would be greatly appreciated!</p>
<p>Here is what I'm working with so far: </p>
<pre><code>import urllib
from bs4 import BeautifulSoup
import csv
import re
import pandas as pd
import requests
with open('/Users/test/Dropbox/one_minute_json/Extracting Data/a_2005_test.csv') as f:
reader = csv.reader(f)
for row in reader:
html = urllib.urlopen(row[0])
r = requests.get(html)
soup = BeautifulSoup(r, "lxml")
for item in soup:
volume = int(re.findall(r"Volume (\d{1,3})", soup.title.text)[0])
print(volume)
issue = int(re.findall(r"Issue (\d{1,3})", soup.title.text)[0])
print(issue)
date = re.findall(r"\((.*?)\)", soup.title.text)[0]
print(date)
page = re.findall(r"\[Page (.*?)]", soup.pre.text.split('\n')[3])[0]
print(page)
title = soup.pre.text.split('\n\n ')[1].strip()
print(title)
name = soup.pre.text.split('\n ')[2]
print(name)
text = soup.pre.text.split(')')[2]
print(text)
df = pd.DataFrame()
df['volume'] = [volume]
df['issue'] = [issue]
df['date'] = [date]
df['page'] = [page]
df['title'] = [title]
df['name'] = [name]
df['text'] = [text]
df.to_csv('test_scrape.csv', index=False)
</code></pre>
<p>Thanks!</p>
| 0 | 2016-10-12T21:34:47Z | 40,112,614 | <p>Your indenting is completely off, try the following:</p>
<pre><code>from bs4 import BeautifulSoup
import csv
import re
import pandas as pd
import requests
with open('/Users/test/Dropbox/one_minute_json/Extracting Data/a_2005_test.csv') as f:
reader = csv.reader(f)
index = 0
df = pd.DataFrame(columns=["Volume", "issue", "date", "page", "title", "name", "text"])
for row in reader:
r = requests.get(row[0])
soup = BeautifulSoup(r.text, "lxml")
for item in soup:
volume = int(re.findall(r"Volume (\d{1,3})", soup.title.text)[0])
issue = int(re.findall(r"Issue (\d{1,3})", soup.title.text)[0])
date = re.findall(r"\((.*?)\)", soup.title.text)[0]
page = re.findall(r"\[Page (.*?)]", soup.pre.text.split('\n')[3])[0]
title = soup.pre.text.split('\n\n ')[1].strip()
name = soup.pre.text.split('\n ')[2]
text = soup.pre.text.split(')')[2]
row = [volume, issue, date, page, title, name, text]
df.loc[index] = row
index += 1
df.to_csv('test_scrape.csv', index=False)
</code></pre>
| 0 | 2016-10-18T15:43:33Z | [
"python",
"csv",
"beautifulsoup"
] |
Analogs for Placeholder from Django-CMS or Streamfield from Wagtail without cms itself | 40,008,775 | <p>I often need to implement rich content editing in my django projects. There are a lot of different wysiwyg-editors, but they are not good for creating complex content structure. Placeholder from Django-CMS or Streamfield from Wagtail can do it much better, but I don't want to add whole CMS to my project, because it brings a lot of unnecessary stuff into interface.</p>
<p>All I need is just a field with ordered list of widgets inside + editing interface for it. Can you suggest something?</p>
| 0 | 2016-10-12T21:37:09Z | 40,009,135 | <p>Django CMS is very modular - you do not need to bring in the whole URL and page management interface.</p>
<p>You can enhance your existing models with Django CMS's placeholder fields and use the rich structure mode and plugins only, for example:</p>
<pre><code>from django.db import models
from cms.models.fields import PlaceholderField
class MyModel(models.Model):
# your fields
my_placeholder = PlaceholderField('placeholder_name')
# your methods
</code></pre>
<p>Example taken from <a href="http://docs.django-cms.org/en/release-3.3.x/how_to/placeholders.html" rel="nofollow">Django CMS documentation</a>.</p>
| 0 | 2016-10-12T22:04:13Z | [
"python",
"django",
"wysiwyg",
"django-cms",
"wagtail-streamfield"
] |
Script for replacing digits | 40,008,777 | <p>I have a file that has content as below</p>
<pre><code>a b c 123.67989
aa bb cc 56789.38475
b c a 56789.3456
bb cc aa 0.12409124
c a b 0.0123123
</code></pre>
<p>I am trying to remove digits after the <code>.</code> in the each line. Is there is a way to do this using regular expressions in Python?
Code I wrote
f1 = open('filename.txt','r')</p>
<p>for line in f1:</p>
<pre><code> words = line.split()
print(words[3])
</code></pre>
<p>I am trying retrieve last row information and I keep getting error list indices out of range</p>
| -3 | 2016-10-12T21:37:20Z | 40,008,906 | <p>I didn't use regular expressions but maybe this helps:</p>
<pre><code>text = "a b c 123.67989 \n" \
"aa bb cc 56789.38475 \n" \
"b c a 56789.3456 \n" \
"bb cc aa 0.12409124 \n" \
"c a b 0.0123123"
lines = text.splitlines()
for line in lines:
line_without_digits = line.split('.')[0]
print(line_without_digits)
</code></pre>
<p><strong>EDIT</strong></p>
<p>Example with first digit after ".":</p>
<pre><code>text = "a b c 123.67989 \n" \
"aa bb cc 56789.38475 \n" \
"b c a 56789.3456 \n" \
"bb cc aa 0.12409124 \n" \
"c a b 0.0123123"
lines = text.splitlines()
for line in lines:
line_split = line.split('.')
line_without_digits = line_split[0] + "." + line_split[1][0]
print(line_without_digits)
</code></pre>
| 1 | 2016-10-12T21:46:55Z | [
"python",
"python-3.x"
] |
Script for replacing digits | 40,008,777 | <p>I have a file that has content as below</p>
<pre><code>a b c 123.67989
aa bb cc 56789.38475
b c a 56789.3456
bb cc aa 0.12409124
c a b 0.0123123
</code></pre>
<p>I am trying to remove digits after the <code>.</code> in the each line. Is there is a way to do this using regular expressions in Python?
Code I wrote
f1 = open('filename.txt','r')</p>
<p>for line in f1:</p>
<pre><code> words = line.split()
print(words[3])
</code></pre>
<p>I am trying retrieve last row information and I keep getting error list indices out of range</p>
| -3 | 2016-10-12T21:37:20Z | 40,008,978 | <p>No regex here, either, but:</p>
<pre><code>with open( "C:/TestFile.txt", 'r' ) as file:
lines = file.readlines()
out_lines = []
out_file = open( "C:/TestFile2.txt", "w" )
for i in range( len( lines ) ):
out_lines.append( lines[ i ].split( "." )[0] )
for line in out_lines:
out_file.write( "%s\n" % line )
</code></pre>
<p>To access the numbers after the decimal, just access the second part of the split:</p>
<p>Python supports offset notation on strings, and you can access the second part of the split.</p>
<pre><code>for i in range( len( lines ) ):
parts = lines[ i ].split( "." )
out_lines.append( parts[0] )
first_decimal = parts[1][0]
</code></pre>
<p>Or, if your goal is to round the values in the 4th column, something like this may be what you want:</p>
<pre><code>for i in range( len( lines ) ):
parts = lines[i].split()
if len( parts ) == 0:
out_lines.append( "" )
continue
out_lines.append( parts[0].ljust( 5 ) + parts[1].ljust( 4 ) + parts[2].ljust( 5 ) + format( float( parts[3] ), '.1f' ) )
</code></pre>
| 0 | 2016-10-12T21:51:51Z | [
"python",
"python-3.x"
] |
Script for replacing digits | 40,008,777 | <p>I have a file that has content as below</p>
<pre><code>a b c 123.67989
aa bb cc 56789.38475
b c a 56789.3456
bb cc aa 0.12409124
c a b 0.0123123
</code></pre>
<p>I am trying to remove digits after the <code>.</code> in the each line. Is there is a way to do this using regular expressions in Python?
Code I wrote
f1 = open('filename.txt','r')</p>
<p>for line in f1:</p>
<pre><code> words = line.split()
print(words[3])
</code></pre>
<p>I am trying retrieve last row information and I keep getting error list indices out of range</p>
| -3 | 2016-10-12T21:37:20Z | 40,013,738 | <p>Get only digits with one decimal value:</p>
<pre><code>import re
text = """
a b c 123.67989
aa bb cc 56789.38475
b c a 56789.3456
bb cc aa 0.12409124
c a b 0.0123123
"""
digits = re.findall(r'\d+\.\d{1}', text)
print(digits)
# prints: ['123.6', '56789.3', '56789.3', '0.1', '0.0']
</code></pre>
| 0 | 2016-10-13T06:26:31Z | [
"python",
"python-3.x"
] |
Odd behavior with python basemap and pcolormesh | 40,008,778 | <p>I'm trying to plot longitudinal strips of binned data by making a numpy.meshgrid, converting the coordinates to map x,y coordinates using Basemap(), and then making a pcolormesh which is applied over the map. Code is for Python 2.7:</p>
<pre><code>import numpy as np
from mpl_toolkits.basemap import Basemap, shiftgrid, addcyclic
import matplotlib.pyplot as plt
lon_tics = np.linspace(0, 360.0, 60)
lat_tics = np.linspace(-90.0, 90.0, 30)
map_bins = np.zeros((60,30), dtype = np.int)
bin15 = np.random.randint(0,20,30) #we should see 2 strips
bin45 = np.random.randint(0,20,30) #but we get lots of strange results
map_bins[15] = bin15
map_bins[45] = bin45
m = Basemap(projection='moll',lon_0= -120,resolution='c') #NOTE changing lon_0 has weird results!
lon_bins_2d, lat_bins_2d = np.meshgrid(lon_tics, lat_tics)
xs, ys = m(lon_bins_2d, lat_bins_2d)
plt.pcolormesh(xs, ys, np.transpose(map_bins))
plt.colorbar()
m.drawparallels(np.arange(-90.,120.,30.), labels = [True])
m.drawmeridians(np.arange(0.,360.,60.), labels = [False])
plt.show()
</code></pre>
<p>This is giving some very weird behavior. By changing either what bins the data is in, where lon_0 is set by the Basemap() instantiation, or how the lat/lon bins are defined we will get differing behavior, such as:</p>
<ul>
<li>No longitudinal strips</li>
<li>1 longitudinal strips</li>
<li>2 longitudinal strips (expected behavior) (pictured: made with lon_0=-120)</li>
<li>'Smeared' bin to edge of map (pictured: made with lon_0=98)</li>
</ul>
<p>I've been trying to resolve this issue for some time; can anyone see what I am doing wrong?</p>
<p>Thanks for reading.</p>
<p><a href="https://i.stack.imgur.com/bX0TH.png" rel="nofollow">Correct output</a></p>
<p><a href="https://i.stack.imgur.com/tvZMW.png" rel="nofollow">Smear</a></p>
| 0 | 2016-10-12T21:37:26Z | 40,062,415 | <p>After some additional looking around I stumbled across this post: <a href="https://stackoverflow.com/questions/18186047/map-projection-and-forced-interpolation">Map projection and forced interpolation</a></p>
<p>This solved my problems for now, so I'm linking in case someone else runs into this issue.</p>
| 0 | 2016-10-15T17:59:09Z | [
"python",
"numpy",
"matplotlib",
"matplotlib-basemap"
] |
Schedule table updates in Django | 40,008,788 | <p>How do you schedule updating the contents of a database table in Django based on time of day. For example every 5 minutes Django will call a REST api to update contents of a table.</p>
| 1 | 2016-10-12T21:38:23Z | 40,009,025 | <p>I think this is likely best accomplished by writing a server-side python script and adding a cronjob </p>
| 0 | 2016-10-12T21:55:21Z | [
"python",
"django",
"django-models"
] |
Schedule table updates in Django | 40,008,788 | <p>How do you schedule updating the contents of a database table in Django based on time of day. For example every 5 minutes Django will call a REST api to update contents of a table.</p>
| 1 | 2016-10-12T21:38:23Z | 40,009,031 | <p>Based upon your question, I am not 100% clear what you are looking for. But, assuming you are looking to run some sort of a task every 5 minutes (that will make calls to the DB), then I <strong>highly</strong> suggest you look at <a href="http://www.celeryproject.org/" rel="nofollow">Celery</a>. </p>
<p>It is a robust task schedules, with <a href="http://docs.celeryproject.org/en/latest/django/first-steps-with-django.html" rel="nofollow">specific Django integration</a>. Once you get thru the <a href="http://docs.celeryproject.org/en/latest/getting-started/introduction.html" rel="nofollow">getting started</a> documentation, what you want to look at in particular is called <a href="http://docs.celeryproject.org/en/latest/userguide/periodic-tasks.html" rel="nofollow">CELERYBEAT_SCHEDULE</a>. This allows you to sort of setup cron like calls.</p>
<p>This has a lot of <a href="http://stackoverflow.com/a/16234656/1036843">benefits over cron</a>, and for most use cases I find it to be a better alternative. Scalability is a huge feature for me.</p>
<p>Good luck!</p>
| 1 | 2016-10-12T21:56:02Z | [
"python",
"django",
"django-models"
] |
Sentinel not working properly | 40,008,800 | <pre><code>def load():
global name
global count
global shares
global pp
global sp
global commission
name=input("Enter stock name OR -999 to Quit: ")
count =0
while name != '-999':
count=count+1
shares=int(input("Enter number of shares: "))
pp=float(input("Enter purchase price: "))
sp=float(input("Enter selling price: "))
commission=float(input("Enter commission: "))
calc()
display()
name=input("\nEnter stock name OR -999 to Quit: ")
def calc():
global amount_paid
global amount_sold
global profit_loss
global commission_paid_sale
global commission_paid_purchase
amount_paid=shares*pp
commission_paid_purchase=amount_paid*commission
amount_sold=shares*sp
commission_paid_sale=amount_sold*commission
profit_loss=(amount_sold - commission_paid_sale) -(amount_paid + commission_paid_purchase)
def display():
print("\nStock Name:", name)
print("Amount paid for the stock: $", format(amount_paid, '10,.2f'))
print("Commission paid on the purchase: $", format(commission_paid_purchase, '10,.2f'))
print("Amount the stock sold for: $", format(amount_sold, '10,.2f'))
print("Commission paid on the sale: $", format(commission_paid_sale, '10,.2f'))
print("Profit (or loss if negative): $", format(profit_loss, '10,.2f'))
def main():
load()
calc()
display()
main()
</code></pre>
<p>Sentinel "works" in the sense that it ends the program, but not without outputting the previous stock's data (that is erroneous). I would like the sentinel to immediately stop the program and kick to ">>>" after entering '-999'. Here is what the output looks like:</p>
<pre><code>============= RESTART: C:\Users\ElsaTime\Desktop\answer2.py =============
Enter stock name OR -999 to Quit: M$FT
Enter number of shares: 1000
Enter purchase price: 15
Enter selling price: 150
Enter commission: 0.03
Stock Name: M$FT
Amount paid for the stock: $ 15,000.00
Commission paid on the purchase: $ 450.00
Amount the stock sold for: $ 150,000.00
Commission paid on the sale: $ 4,500.00
Profit (or loss if negative): $ 130,050.00
Enter stock name OR -999 to Quit: -999
Stock Name: -999
Amount paid for the stock: $ 15,000.00
Commission paid on the purchase: $ 450.00
Amount the stock sold for: $ 150,000.00
Commission paid on the sale: $ 4,500.00
Profit (or loss if negative): $ 130,050.00
>>>
</code></pre>
| 0 | 2016-10-12T21:38:57Z | 40,008,909 | <p>Remove <code>calc()</code> and <code>display()</code> from <code>main()</code>. You're already doing those things in <code>load()</code>.</p>
| 1 | 2016-10-12T21:47:02Z | [
"python",
"python-3.x",
"sentinel"
] |
how to save/crop detected faces in dlib python | 40,008,806 | <p>i want to save the detected face in dlib by cropping the rectangle do
anyone have any idea how can i crop it. i am using dlib first time and
having so many problems. i also want to run the fisherface algorithm on
the detected faces but it is giving me type error when i pass the detected rectangle to pridictor.
i seriously need help in this issue.</p>
<pre><code>import cv2, sys, numpy, os
import dlib
from skimage import io
import json
import uuid
import random
from datetime import datetime
from random import randint
#predictor_path = sys.argv[1]
fn_haar = 'haarcascade_frontalface_default.xml'
fn_dir = 'att_faces'
size = 4
detector = dlib.get_frontal_face_detector()
#predictor = dlib.shape_predictor(predictor_path)
options=dlib.get_frontal_face_detector()
options.num_threads = 4
options.be_verbose = True
win = dlib.image_window()
# Part 1: Create fisherRecognizer
print('Training...')
# Create a list of images and a list of corresponding names
(images, lables, names, id) = ([], [], {}, 0)
for (subdirs, dirs, files) in os.walk(fn_dir):
for subdir in dirs:
names[id] = subdir
subjectpath = os.path.join(fn_dir, subdir)
for filename in os.listdir(subjectpath):
path = subjectpath + '/' + filename
lable = id
images.append(cv2.imread(path, 0))
lables.append(int(lable))
id += 1
(im_width, im_height) = (112, 92)
# Create a Numpy array from the two lists above
(images, lables) = [numpy.array(lis) for lis in [images, lables]]
# OpenCV trains a model from the images
model = cv2.createFisherFaceRecognizer(0,500)
model.train(images, lables)
haar_cascade = cv2.CascadeClassifier(fn_haar)
webcam = cv2.VideoCapture(0)
webcam.set(5,30)
while True:
(rval, frame) = webcam.read()
frame=cv2.flip(frame,1,0)
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
mini = cv2.resize(gray, (gray.shape[1] / size, gray.shape[0] / size))
dets = detector(gray, 1)
print "length", len(dets)
print("Number of faces detected: {}".format(len(dets)))
for i, d in enumerate(dets):
print("Detection {}: Left: {} Top: {} Right: {} Bottom: {}".format(
i, d.left(), d.top(), d.right(), d.bottom()))
cv2.rectangle(gray, (d.left(), d.top()), (d.right(), d.bottom()), (0, 255, 0), 3)
'''
#Try to recognize the face
prediction = model.predict(dets)
print "Recognition Prediction" ,prediction'''
win.clear_overlay()
win.set_image(gray)
win.add_overlay(dets)
if (len(sys.argv[1:]) > 0):
img = io.imread(sys.argv[1])
dets, scores, idx = detector.run(img, 1, -1)
for i, d in enumerate(dets):
print("Detection {}, score: {}, face_type:{}".format(
d, scores[i], idx[i]))
</code></pre>
| 2 | 2016-10-12T21:39:12Z | 40,019,580 | <p>Please use minimal-working sample code to get answers faster. </p>
<p>After you have detected face - you have a rect. So <strong>you can crop image and save with opencv functions</strong>:</p>
<pre><code> img = cv2.imread("test.jpg")
dets = detector.run(img, 1)
for i, d in enumerate(dets):
print("Detection {}, score: {}, face_type:{}".format(
d, scores[i], idx[i]))
crop = img[d.top():d.botton(), t.left():d.right()]
cv2.imwrite("cropped.jpg", crop)
</code></pre>
| -1 | 2016-10-13T11:21:04Z | [
"python",
"opencv",
"face-detection",
"face-recognition",
"dlib"
] |
how to save/crop detected faces in dlib python | 40,008,806 | <p>i want to save the detected face in dlib by cropping the rectangle do
anyone have any idea how can i crop it. i am using dlib first time and
having so many problems. i also want to run the fisherface algorithm on
the detected faces but it is giving me type error when i pass the detected rectangle to pridictor.
i seriously need help in this issue.</p>
<pre><code>import cv2, sys, numpy, os
import dlib
from skimage import io
import json
import uuid
import random
from datetime import datetime
from random import randint
#predictor_path = sys.argv[1]
fn_haar = 'haarcascade_frontalface_default.xml'
fn_dir = 'att_faces'
size = 4
detector = dlib.get_frontal_face_detector()
#predictor = dlib.shape_predictor(predictor_path)
options=dlib.get_frontal_face_detector()
options.num_threads = 4
options.be_verbose = True
win = dlib.image_window()
# Part 1: Create fisherRecognizer
print('Training...')
# Create a list of images and a list of corresponding names
(images, lables, names, id) = ([], [], {}, 0)
for (subdirs, dirs, files) in os.walk(fn_dir):
for subdir in dirs:
names[id] = subdir
subjectpath = os.path.join(fn_dir, subdir)
for filename in os.listdir(subjectpath):
path = subjectpath + '/' + filename
lable = id
images.append(cv2.imread(path, 0))
lables.append(int(lable))
id += 1
(im_width, im_height) = (112, 92)
# Create a Numpy array from the two lists above
(images, lables) = [numpy.array(lis) for lis in [images, lables]]
# OpenCV trains a model from the images
model = cv2.createFisherFaceRecognizer(0,500)
model.train(images, lables)
haar_cascade = cv2.CascadeClassifier(fn_haar)
webcam = cv2.VideoCapture(0)
webcam.set(5,30)
while True:
(rval, frame) = webcam.read()
frame=cv2.flip(frame,1,0)
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
mini = cv2.resize(gray, (gray.shape[1] / size, gray.shape[0] / size))
dets = detector(gray, 1)
print "length", len(dets)
print("Number of faces detected: {}".format(len(dets)))
for i, d in enumerate(dets):
print("Detection {}: Left: {} Top: {} Right: {} Bottom: {}".format(
i, d.left(), d.top(), d.right(), d.bottom()))
cv2.rectangle(gray, (d.left(), d.top()), (d.right(), d.bottom()), (0, 255, 0), 3)
'''
#Try to recognize the face
prediction = model.predict(dets)
print "Recognition Prediction" ,prediction'''
win.clear_overlay()
win.set_image(gray)
win.add_overlay(dets)
if (len(sys.argv[1:]) > 0):
img = io.imread(sys.argv[1])
dets, scores, idx = detector.run(img, 1, -1)
for i, d in enumerate(dets):
print("Detection {}, score: {}, face_type:{}".format(
d, scores[i], idx[i]))
</code></pre>
| 2 | 2016-10-12T21:39:12Z | 40,025,317 | <p>Should be like this:</p>
<pre><code>crop_img = img_full[d.top():d.bottom(),d.left():d.right()]
</code></pre>
| 0 | 2016-10-13T15:35:58Z | [
"python",
"opencv",
"face-detection",
"face-recognition",
"dlib"
] |
Running Jupyter/IPython document on Zepplin | 40,008,886 | <p>I have a large set of existing documents running on Jupyter. I want to move to Zeppelin.</p>
<p>I assume Jupyter pages run in Zeppelin, but I can't find any documentation. Has anyone tried this? Does it work? Anyone have a useful link?</p>
<p>Thanks
Peter</p>
| 1 | 2016-10-12T21:44:42Z | 40,019,541 | <p>Jupyter's ipynb is json file. You can find <a href="http://nbformat.readthedocs.io/en/latest/" rel="nofollow">The Jupyter Notebook Format</a></p>
<p>Zeppelin's note.json is also json format. Each notebook has an folder(notebook id) and note.json. </p>
<p>It should be possible to convert with a small application. I think most important information shall be.</p>
<blockquote>
<p>cells(jupyter) -> paragraphs(Zeppelin)</p>
<p>cell -> paragraph</p>
<p>cell_type -> %... in text</p>
<p>source -> text</p>
</blockquote>
| 0 | 2016-10-13T11:19:10Z | [
"python",
"apache-spark",
"jupyter",
"apache-zeppelin"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.