title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags list |
|---|---|---|---|---|---|---|---|---|---|
What is the proper way of testing throttling in DRF? | 39,309,046 | <p>What is the proper way of testing throttling in DRF? I coulnd't find out any answer to this question on the net. I want to have separate tests for each endpoint since each one has custom requests limits (ScopedRateThrottle).</p>
<p>The important thing is that it can't affect other tests - they have to somehow run without throttling and limiting.</p>
| 1 | 2016-09-03T16:29:37Z | 39,350,391 | <p>Like people already mentioned, this doesn't exactly fall within the scope of unit tests, but still, how about simply doing something like this:</p>
<pre><code>from django.core.urlresolvers import reverse
from django.test import override_settings
from rest_framework.test import APITestCase, APIClient
class ThrottleApiTests(APITestCase):
# make sure to override your settings for testing
TESTING_THRESHOLD = '5/min'
# THROTTLE_THRESHOLD is the variable that you set for DRF DEFAULT_THROTTLE_RATES
@override_settings(THROTTLE_THRESHOLD=TESTING_THRESHOLD)
def test_check_health(self):
client = APIClient()
# some end point you want to test (in this case it's a public enpoint that doesn't require authentication
_url = reverse('check-health')
# this is probably set in settings in you case
for i in range(0, self.TESTING_THRESHOLD):
client.get(_url)
# this call should err
response = client.get(_url)
# 429 - too many requests
self.assertEqual(response.status_code, 429)
</code></pre>
<p>Also, regarding your concerns of side-effects, as long as you do user creation in <code>setUp</code> or <code>setUpTestData</code>, tests will be isolated (as they should), so no need to worry about 'dirty' data or scope in that sense.</p>
<p>Regarding <a href="https://docs.djangoproject.com/en/1.10/topics/testing/overview/#other-test-conditions" rel="nofollow">cache clearing between tests</a>, I would just add <code>cache.clear()</code> in <code>tearDown</code> or try and clear the <a href="http://www.django-rest-framework.org/api-guide/throttling/#setting-up-the-cache" rel="nofollow">specific key defined for throttling</a>.</p>
| 0 | 2016-09-06T13:35:30Z | [
"python",
"django",
"testing",
"django-rest-framework",
"throttling"
] |
Python Simon Game: I Got Stuck Finishing the Sequence | 39,309,130 | <p>I'm finally finishing my Simon Game, but I have some doubts about how to complete the sequence.</p>
<p>Edit: As you asked I have edited my post. Here I will post my code as it was before this post. So here are my actual problems.</p>
<p>1) I don't know how to add one number to the sequence after each turn.</p>
<p>2) The first turn works fine, but I don't know how to start the next turn, I've tried to call again the function after checking the sequence but it doesn't worked.</p>
<p>The necessary code for the two things:</p>
<pre><code>from Tkinter import *
import Tkinter
import random
base = Tkinter.Tk()
fr = Tkinter.Frame(base, bg='black', width='238', height='250')
score = Tkinter.Label(base, bg='black', fg='white', text='Score:')
score.place(x = 30, y = 15)
s = 0
scoreNum = Tkinter.Label(base, bg='black', fg='white', text = s)
scoreNum.place(x = 70, y = 15)
clicks = []
color = 0
def yellowClick():
yellow.configure(activebackground='yellow3')
yellow.after(500, lambda: yellow.configure(activebackground='yellow'))
global clicks
global color
color = 1
clicks.append(color)
yellow = Tkinter.Button(base, bd='0', highlightthickness='0',
width='7', height='5', activebackground='yellow',
bg='yellow3', command = yellowClick)
yellow.place(x = 30, y = 50)
def blueClick():
blue.configure(activebackground='medium blue')
blue.after(500, lambda: blue.configure(activebackground='blue'))
global clicks
global color
color = 2
clicks.append(color)
blue = Tkinter.Button(base, bd='0', highlightthickness='0',
width='7', height='5', activebackground='blue',
bg='medium blue', command = blueClick)
blue.place(x = 125, y = 50)
def redClick():
red.configure(activebackground='red3')
red.after(500, lambda: red.configure(activebackground='red'))
global clicks
global color
color = 3
clicks.append(color)
red = Tkinter.Button(base, bd='0', highlightthickness='0',
width='7', height='5', activebackground='red',
bg = 'red3', command = redClick)
red.place(x = 30, y = 145)
def greenClick():
green.configure(activebackground='dark green')
green.after(500, lambda: green.configure(activebackground='green4'))
global clicks
global color
color = 4
clicks.append(color)
green = Tkinter.Button(base, bd='0', highlightthickness='0',
width='7', height='5', activebackground='green4',
bg='dark green', command = greenClick)
green.place(x = 125, y = 145)
def scoreUp():
global s
s = s + 1
scoreNum.configure(text = s)
sequence = []
def checkSequence():
global clicks
global sequence
if clicks == sequence:
scoreUp()
def showSequence():
global sequence
global clicks
global check
r = random.randint(1, 4)
if r == 1:
yellow.configure(bg='yellow')
yellow.after(1000, lambda: yellow.configure(bg='yellow3'))
sequence.append(r)
base.after(5000, checkSequence)
elif r == 2:
blue.configure(bg='blue')
blue.after(1000, lambda: blue.configure(bg='medium blue'))
sequence.append(r)
base.after(5000, checkSequence)
elif r == 3:
red.configure(bg='red')
red.after(1000, lambda: red.configure(bg='red3'))
sequence.append(r)
base.after(5000, checkSequence)
elif r == 4:
green.configure(bg='green4')
green.after(1000, lambda: green.configure(bg='dark green'))
sequence.append(r)
base.after(5000, checkSequence)
base.after(2000, showSequence)
fr.pack()
base.resizable(False, False)
base.mainloop()
</code></pre>
<p>The checkSequence function is activated by time because I could not find another way to do it.</p>
| 1 | 2016-09-03T16:37:15Z | 39,317,854 | <p>Here is the code based on furas' solution in the comments</p>
<pre><code>def showSequence():
global sequence
number_added = True
r = random.randint(1, 4)
if r == 1:
elif r == 2:
elif r == 3:
elif r == 4:
else:
number_added = False
return number_added # this will be True if a number was added, False if not
</code></pre>
<p>And to call the function:</p>
<pre><code>number_added = showSequence()
if number_added:
# stop sequence here
</code></pre>
<p>You also said you don't know how to stop it, try this:</p>
<pre><code>import sys
sys.exit()
</code></pre>
<p>This will immediately stop the function you're currently in</p>
| 0 | 2016-09-04T14:15:53Z | [
"python",
"tkinter"
] |
Python Simon Game: I Got Stuck Finishing the Sequence | 39,309,130 | <p>I'm finally finishing my Simon Game, but I have some doubts about how to complete the sequence.</p>
<p>Edit: As you asked I have edited my post. Here I will post my code as it was before this post. So here are my actual problems.</p>
<p>1) I don't know how to add one number to the sequence after each turn.</p>
<p>2) The first turn works fine, but I don't know how to start the next turn, I've tried to call again the function after checking the sequence but it doesn't worked.</p>
<p>The necessary code for the two things:</p>
<pre><code>from Tkinter import *
import Tkinter
import random
base = Tkinter.Tk()
fr = Tkinter.Frame(base, bg='black', width='238', height='250')
score = Tkinter.Label(base, bg='black', fg='white', text='Score:')
score.place(x = 30, y = 15)
s = 0
scoreNum = Tkinter.Label(base, bg='black', fg='white', text = s)
scoreNum.place(x = 70, y = 15)
clicks = []
color = 0
def yellowClick():
yellow.configure(activebackground='yellow3')
yellow.after(500, lambda: yellow.configure(activebackground='yellow'))
global clicks
global color
color = 1
clicks.append(color)
yellow = Tkinter.Button(base, bd='0', highlightthickness='0',
width='7', height='5', activebackground='yellow',
bg='yellow3', command = yellowClick)
yellow.place(x = 30, y = 50)
def blueClick():
blue.configure(activebackground='medium blue')
blue.after(500, lambda: blue.configure(activebackground='blue'))
global clicks
global color
color = 2
clicks.append(color)
blue = Tkinter.Button(base, bd='0', highlightthickness='0',
width='7', height='5', activebackground='blue',
bg='medium blue', command = blueClick)
blue.place(x = 125, y = 50)
def redClick():
red.configure(activebackground='red3')
red.after(500, lambda: red.configure(activebackground='red'))
global clicks
global color
color = 3
clicks.append(color)
red = Tkinter.Button(base, bd='0', highlightthickness='0',
width='7', height='5', activebackground='red',
bg = 'red3', command = redClick)
red.place(x = 30, y = 145)
def greenClick():
green.configure(activebackground='dark green')
green.after(500, lambda: green.configure(activebackground='green4'))
global clicks
global color
color = 4
clicks.append(color)
green = Tkinter.Button(base, bd='0', highlightthickness='0',
width='7', height='5', activebackground='green4',
bg='dark green', command = greenClick)
green.place(x = 125, y = 145)
def scoreUp():
global s
s = s + 1
scoreNum.configure(text = s)
sequence = []
def checkSequence():
global clicks
global sequence
if clicks == sequence:
scoreUp()
def showSequence():
global sequence
global clicks
global check
r = random.randint(1, 4)
if r == 1:
yellow.configure(bg='yellow')
yellow.after(1000, lambda: yellow.configure(bg='yellow3'))
sequence.append(r)
base.after(5000, checkSequence)
elif r == 2:
blue.configure(bg='blue')
blue.after(1000, lambda: blue.configure(bg='medium blue'))
sequence.append(r)
base.after(5000, checkSequence)
elif r == 3:
red.configure(bg='red')
red.after(1000, lambda: red.configure(bg='red3'))
sequence.append(r)
base.after(5000, checkSequence)
elif r == 4:
green.configure(bg='green4')
green.after(1000, lambda: green.configure(bg='dark green'))
sequence.append(r)
base.after(5000, checkSequence)
base.after(2000, showSequence)
fr.pack()
base.resizable(False, False)
base.mainloop()
</code></pre>
<p>The checkSequence function is activated by time because I could not find another way to do it.</p>
| 1 | 2016-09-03T16:37:15Z | 39,362,560 | <p>I've answered this question already but you still had some problems, here is the full and complete code. I've made it more efficient and fixed the problems :)</p>
<p>This is working I've tested it. Just comment if there is anything you need to know</p>
<pre><code>import Tkinter # you don't need to import Tkinter again, from ... import * moves all the functions from ... into your program
import random
base = Tkinter.Tk()
fr = Tkinter.Frame(base, bg='black', width='238', height='250')
fr.pack()
score = Tkinter.Label(base, bg='black', fg='white', text='Score:')
score.place(x = 30, y = 15)
scoreNum = Tkinter.Label(base, bg='black', fg='white', text = 0)
scoreNum.place(x = 70, y = 15)
global sequence
global clicks
global s
sequence = []
clicks = []
s = 0
yellow = Tkinter.Button(base, bd='0', highlightthickness='0',
width='7', height='5', activebackground='yellow',
bg='yellow3', command = lambda *args: Click(yellow, "yellow", "yellow3", 1))
blue = Tkinter.Button(base, bd='0', highlightthickness='0',
width='7', height='5', activebackground='blue',
bg='medium blue', command = lambda *args: Click(blue, "blue", "medium blue", 2))
red = Tkinter.Button(base, bd='0', highlightthickness='0',
width='7', height='5', activebackground='red',
bg = 'red3', command = lambda *args: Click(red, "red", "red3", 3))
green = Tkinter.Button(base, bd='0', highlightthickness='0',
width='7', height='5', activebackground='green4',
bg='dark green', command = lambda *args: Click(green, "green", "dark green", 4))
yellow.place(x = 30, y = 50)
blue.place(x = 125, y = 50)
red.place(x = 30, y = 145)
green.place(x = 125, y = 145)
def Click(button, colour1, colour2, number): # these arguments change so that you don't have to copy the function 10 times
global clicks
yellow.configure(activebackground=colour2)
yellow.after(500, lambda: yellow.configure(activebackground=colour1))
clicks.append(number)
checkSequence() # why not do this straight away?
def checkSequence():
global clicks
global sequence
global s
print("clicks: "+str(clicks)) # debug
print("sequence: "+str(sequence))
if clicks != sequence[:len(clicks)]: # if all their clicks so far e.g. [1, 2, 4, 3] DONT fit with the sequence e.g. [3, 2, 4, 3, 2, 1]
print(" ...Incorrect!")
s = 0
scoreNum.configure(text = 0)
sequence = []
clicks = []
base.after(1000, showSequence) # now move to the next value in the sequence
elif clicks == sequence: # they have completed a sequence
print(" ...Match!")
s = s + 1
scoreNum.configure(text = s)
clicks = []
base.after(1000, showSequence) # now move to the next value in the sequence
def showSequence():
global sequence
global clicks
r = random.randint(1, 4)
if r == 1:
yellow.configure(bg='yellow')
yellow.after(1000, lambda: yellow.configure(bg='yellow3'))
elif r == 2:
blue.configure(bg='blue')
blue.after(1000, lambda: blue.configure(bg='medium blue'))
elif r == 3:
red.configure(bg='red')
red.after(1000, lambda: red.configure(bg='red3'))
elif r == 4:
green.configure(bg='green')
green.after(1000, lambda: green.configure(bg='dark green'))
sequence.append(r) # you don't need this in all the if statements, it always happens
base.after(100, showSequence)
base.resizable(False, False)
base.mainloop()
</code></pre>
<p>NOTE: I'm using python 3.4.1 so I changed all the tkinters to Tkinter</p>
| 1 | 2016-09-07T06:25:44Z | [
"python",
"tkinter"
] |
Simple index on DATE and TIME columns | 39,309,165 | <p>I have a CSV containing data that looks like this:</p>
<pre><code><DATE> <TIME> <OPEN> <LOW> <HIGH> <CLOSE>
2001-01-03 00:00:00 0.9507 0.9505 0.9509 0.9506
....
2015-05-13 02:00:00 0.9496 0.9495 0.9509 0.9505
</code></pre>
<p>I want to create an index on <DATE> and <TIME> but retain the two columns as normal columns so I can reference them. </p>
<p>As the data is stored in a CSV I am not sure how I could parse the 2 columns (DATE and TIME) into one before creating the dataframe. </p>
<p>I've had a look at many answers but they seems convoluted for what I am trying to do, and I have became convinced I am missing the simple solution</p>
<pre><code>Context around what lead me to this:
</code></pre>
<p>The proper way I've identified setting a new value (for when I am computing rolling mean values) is:</p>
<pre><code>df.set_value('index', 'column', value)
</code></pre>
<p>Because my index is currently just on date, referencing the index for a particular row (say, the 1st row) means many values are set instead of one</p>
| 2 | 2016-09-03T16:40:59Z | 39,309,256 | <p><strong>UPDATE:</strong></p>
<pre><code>In [170]: df = pd.read_csv('/path/to/file.csv', parse_dates={'TIMESTAMP': ['DATE','TIME']}).set_index('TIMESTAMP')
In [171]: df
Out[171]:
OPEN LOW HIGH CLOSE
TIMESTAMP
2001-01-03 00:00:00 0.9507 0.9505 0.9509 0.9506
2001-01-03 01:00:00 0.9507 0.9505 0.9509 0.9506
2001-01-03 02:00:00 0.9507 0.9505 0.9509 0.9506
2001-01-03 03:00:00 0.9507 0.9505 0.9509 0.9506
2001-01-03 04:00:00 0.9507 0.9505 0.9509 0.9506
2001-01-04 00:00:00 0.9507 0.9505 0.9509 0.9506
2001-01-04 01:00:00 0.9507 0.9505 0.9509 0.9506
2001-01-04 02:00:00 0.9507 0.9505 0.9509 0.9506
In [172]: df.index.dtype
Out[172]: dtype('<M8[ns]')
</code></pre>
<p><strong>OLD answer:</strong></p>
<p>you can do it this way:</p>
<pre><code>In [155]: df
Out[155]:
a b c
0 0 0 3
1 1 2 0
2 2 2 3
3 1 0 0
4 1 3 2
5 4 0 1
6 2 0 3
7 2 1 2
8 3 3 4
9 0 0 3
In [156]: df.join(df.ix[:, :2], rsuffix='_idx').set_index((df.ix[:, :2].columns + '_idx').tolist())
Out[156]:
a b c
a_idx b_idx
0 0 0 0 3
1 2 1 2 0
2 2 2 2 3
1 0 1 0 0
3 1 3 2
4 0 4 0 1
2 0 2 0 3
1 2 1 2
3 3 3 3 4
0 0 0 0 3
</code></pre>
<p>BUT, you don't really need it, because it's redundant - you still have your data in the index and can use it...</p>
| 2 | 2016-09-03T16:52:07Z | [
"python",
"pandas",
"numpy",
"dataframe"
] |
Flask-Admin refresh files list | 39,309,227 | <p>The <a href="https://github.com/flask-admin/flask-admin/blob/master/examples/forms/app.py" rel="nofollow">Flask-Admin form tutorial code</a> creates a list from the files in a directory. This is the populating of the list: </p>
<pre><code>def build_sample_db():
# Populating the pdf files
db.drop_all()
db.create_all()
for i in [1, 2, 3]:
file = File()
file.name = "Example " + str(i)
file.path = "example_" + str(i) + ".pdf"
db.session.add(file)
db.session.commit()
return
if __name__ == '__main__':
# Build a sample db on the fly, if one does not exist yet.
build_sample_db()
# Start app
app.run(debug=True)
</code></pre>
<p>I've changed the code for populating to this: </p>
<pre><code># get all files in a directory
def build_sample_db():
db.drop_all()
db.create_all()
# It lists the files in a directory
ls_output = next(os.walk('/home/bor/flask-admin/examples/forms/files/'))[2]
for f in ls_output:
file = File()
file.path = f
db.session.add(file)
db.session.commit()
return
</code></pre>
<p>It lists the whole directory without hard-coded values. But it refreshes only on the start of the app.</p>
<p><a href="http://examples.flask-admin.org/forms/admin/file/" rel="nofollow">Forms in Flask-Admin</a> is the example and how it looks. </p>
<p>The view is added here:</p>
<pre><code> admin.add_view(FileView(File, db.session))
</code></pre>
<p>Files view:</p>
<pre><code>class FileView(sqla.ModelView):
# Pass additional parameters to 'path' to FileUploadField constructor
form_args = {
'path': {
'label': 'File',
'base_path': file_path,
'allow_overwrite': False
}
}
# No
def __init__():
db.drop_all()
db.create_all()
ls_output = next(os.walk('/home/bor/flask-admin/examples/forms/files/'))[2]
for f in ls_output:
file = File()
file.path = f
db.session.add(file)
db.session.commit()
</code></pre>
<p>Where to add the code for populating, so it can be refreshed and the files in the dir taken again? Database would be recreated as well just for the example.
I don't want to create a new view, but to refresh this.</p>
| 0 | 2016-09-03T16:48:33Z | 39,329,336 | <p>Override your view's <code>index_view</code> method. Something like (untested) :</p>
<pre><code>from flask_admin import expose
class FileView(sqla.ModelView):
# Pass additional parameters to 'path' to FileUploadField constructor
form_args = {
'path': {
'label': 'File',
'base_path': file_path,
'allow_overwrite': False
}
}
@expose('/')
def index_view(self):
db.drop_all()
db.create_all()
ls_output = next(os.walk('/home/bor/flask-admin/examples/forms/files/'))[2]
for f in ls_output:
file = File()
file.path = f
db.session.add(file)
db.session.commit()
return super(FileView, self).index_view()
</code></pre>
| 1 | 2016-09-05T11:10:42Z | [
"python",
"flask",
"flask-admin"
] |
Flask-Admin refresh files list | 39,309,227 | <p>The <a href="https://github.com/flask-admin/flask-admin/blob/master/examples/forms/app.py" rel="nofollow">Flask-Admin form tutorial code</a> creates a list from the files in a directory. This is the populating of the list: </p>
<pre><code>def build_sample_db():
# Populating the pdf files
db.drop_all()
db.create_all()
for i in [1, 2, 3]:
file = File()
file.name = "Example " + str(i)
file.path = "example_" + str(i) + ".pdf"
db.session.add(file)
db.session.commit()
return
if __name__ == '__main__':
# Build a sample db on the fly, if one does not exist yet.
build_sample_db()
# Start app
app.run(debug=True)
</code></pre>
<p>I've changed the code for populating to this: </p>
<pre><code># get all files in a directory
def build_sample_db():
db.drop_all()
db.create_all()
# It lists the files in a directory
ls_output = next(os.walk('/home/bor/flask-admin/examples/forms/files/'))[2]
for f in ls_output:
file = File()
file.path = f
db.session.add(file)
db.session.commit()
return
</code></pre>
<p>It lists the whole directory without hard-coded values. But it refreshes only on the start of the app.</p>
<p><a href="http://examples.flask-admin.org/forms/admin/file/" rel="nofollow">Forms in Flask-Admin</a> is the example and how it looks. </p>
<p>The view is added here:</p>
<pre><code> admin.add_view(FileView(File, db.session))
</code></pre>
<p>Files view:</p>
<pre><code>class FileView(sqla.ModelView):
# Pass additional parameters to 'path' to FileUploadField constructor
form_args = {
'path': {
'label': 'File',
'base_path': file_path,
'allow_overwrite': False
}
}
# No
def __init__():
db.drop_all()
db.create_all()
ls_output = next(os.walk('/home/bor/flask-admin/examples/forms/files/'))[2]
for f in ls_output:
file = File()
file.path = f
db.session.add(file)
db.session.commit()
</code></pre>
<p>Where to add the code for populating, so it can be refreshed and the files in the dir taken again? Database would be recreated as well just for the example.
I don't want to create a new view, but to refresh this.</p>
| 0 | 2016-09-03T16:48:33Z | 39,333,703 | <p><a href="https://github.com/flask-admin/flask-admin/blob/master/examples/file/app.py" rel="nofollow">Flask-Admin file example</a> also answers the question. The files refresh, only the database is not added, but that's OK: </p>
<pre><code>from flask_admin.contrib import fileadmin
# irrelevant code removed - see in the link
if __name__ == '__main__':
# Create directory
path = op.join(op.dirname(__file__), 'files')
try:
os.mkdir(path)
except OSError:
pass
# Create admin interface
admin = admin.Admin(app, 'Example: Files')
# Another way to add view
admin.add_view(fileadmin.FileAdmin(path, '/files/', name='Files'))
# Start app
app.run(debug=True)
</code></pre>
| 0 | 2016-09-05T15:27:20Z | [
"python",
"flask",
"flask-admin"
] |
how to remove the first occurence of an integer in a list | 39,309,238 | <p>this is my code:</p>
<pre><code>positions = []
for i in lines[2]:
if i not in positions:
positions.append(i)
print (positions)
print (lines[1])
print (lines[2])
</code></pre>
<p>the output is: </p>
<pre><code>['1', '2', '3', '4', '5']
['is', 'the', 'time', 'this', 'ends']
['1', '2', '3', '4', '1', '5']
</code></pre>
<p>I would want my output of the variable "positions" to be; ['2','3','4','1','5']
so instead of removing the second duplicate from the variable "lines[2]" it should remove the first duplicate.</p>
| 1 | 2016-09-03T16:49:57Z | 39,309,267 | <p>You'll need to first detect what values are duplicated before you can build <code>positions</code>. Use an <code>itertools.Counter()</code> object to test if a value has been seen more than once:</p>
<pre><code>from itertools import Counter
counts = Counter(lines[2])
positions = []
for i in lines[2]:
counts[i] -= 1
if counts[i] == 0:
# only add if this is the 'last' value
positions.append(i)
</code></pre>
<p>This'll work for any number of repetitions of values; only the last value to appear is ever used.</p>
<p>You could also reverse the list, and track what you have already seen with a set, which is faster than testing against the list:</p>
<pre><code>positions = []
seen = set()
for i in reversed(lines[2]):
if i not in seen:
# only add if this is the first time we see the value
positions.append(i)
seen.add(i)
positions = positions[::-1] # reverse the output list
</code></pre>
<p>Both approaches require two iterations; the first to create the <code>counts</code> mapping, the second to reverse the output list. Which is faster will depend on the size of <code>lines[2]</code> and the number of duplicates in it, and wether or not you are using Python 3 (where <code>Counter</code> performance was significantly improved).</p>
| 3 | 2016-09-03T16:54:15Z | [
"python",
"python-3.x"
] |
how to remove the first occurence of an integer in a list | 39,309,238 | <p>this is my code:</p>
<pre><code>positions = []
for i in lines[2]:
if i not in positions:
positions.append(i)
print (positions)
print (lines[1])
print (lines[2])
</code></pre>
<p>the output is: </p>
<pre><code>['1', '2', '3', '4', '5']
['is', 'the', 'time', 'this', 'ends']
['1', '2', '3', '4', '1', '5']
</code></pre>
<p>I would want my output of the variable "positions" to be; ['2','3','4','1','5']
so instead of removing the second duplicate from the variable "lines[2]" it should remove the first duplicate.</p>
| 1 | 2016-09-03T16:49:57Z | 39,309,302 | <p>You can reverse your list, create the positions and then reverse it back as mentioned by @tobias_k in the comment:</p>
<pre><code>lst = ['1', '2', '3', '4', '1', '5']
positions = []
for i in reversed(lst):
if i not in positions:
positions.append(i)
list(reversed(positions))
# ['2', '3', '4', '1', '5']
</code></pre>
| 4 | 2016-09-03T16:58:02Z | [
"python",
"python-3.x"
] |
how to remove the first occurence of an integer in a list | 39,309,238 | <p>this is my code:</p>
<pre><code>positions = []
for i in lines[2]:
if i not in positions:
positions.append(i)
print (positions)
print (lines[1])
print (lines[2])
</code></pre>
<p>the output is: </p>
<pre><code>['1', '2', '3', '4', '5']
['is', 'the', 'time', 'this', 'ends']
['1', '2', '3', '4', '1', '5']
</code></pre>
<p>I would want my output of the variable "positions" to be; ['2','3','4','1','5']
so instead of removing the second duplicate from the variable "lines[2]" it should remove the first duplicate.</p>
| 1 | 2016-09-03T16:49:57Z | 39,309,848 | <p>you can use a dictionary to save the last position of the element and then build a new list with that information</p>
<pre><code>>>> data=['1', '2', '3', '4', '1', '5']
>>> temp={ e:i for i,e in enumerate(data) }
>>> sorted(temp, key=lambda x:temp[x])
['2', '3', '4', '1', '5']
>>>
</code></pre>
| 0 | 2016-09-03T17:58:47Z | [
"python",
"python-3.x"
] |
Migrating sales from xl to odoo using XML-RPC | 39,309,268 | <p>Im trying to migrate sales order from excel sheet to odoo using xmlrpc so far i have the products working,client working but when i try to insert the sale order i get this error</p>
<pre><code>Traceback (most recent call last):
File "/home/oasis/PycharmProjects/somig/migrator.py", line 75, in <module>
'validity_date':"2016-01-18",
File "/usr/lib/python2.7/xmlrpclib.py", line 1243, in __call__
return self.__send(self.__name, args)
File "/usr/lib/python2.7/xmlrpclib.py", line 1602, in __request
verbose=self.__verbose
File "/usr/lib/python2.7/xmlrpclib.py", line 1283, in request
return self.single_request(host, handler, request_body, verbose)
File "/usr/lib/python2.7/xmlrpclib.py", line 1316, in single_request
return self.parse_response(response)
File "/usr/lib/python2.7/xmlrpclib.py", line 1493, in parse_response
return u.close()
File "/usr/lib/python2.7/xmlrpclib.py", line 800, in close
raise Fault(**self._stack[0])
xmlrpclib.Fault: <Fault 1: 'Traceback (most recent call last):\n File "/usr/lib/python2.7/dist-packages/openerp/service/wsgi_server.py", line 56, in xmlrpc_return\n result = openerp.http.dispatch_rpc(service, method, params)\n File "/usr/lib/python2.7/dist-packages/openerp/http.py", line 114, in dispatch_rpc\n result = dispatch(method, params)\n File "/usr/lib/python2.7/dist-packages/openerp/service/model.py", line 37, in dispatch\n res = fn(db, uid, *params)\n File "/usr/lib/python2.7/dist-packages/openerp/service/model.py", line 173, in execute_kw\n return execute(db, uid, obj, method, *args, **kw or {})\n File "/usr/lib/python2.7/dist-packages/openerp/service/model.py", line 118, in wrapper\n return f(dbname, *args, **kwargs)\n File "/usr/lib/python2.7/dist-packages/openerp/service/model.py", line 181, in execute\n res = execute_cr(cr, uid, obj, method, *args, **kw)\n File "/usr/lib/python2.7/dist-packages/openerp/service/model.py", line 170, in execute_cr\n return getattr(object, method)(cr, uid, *args, **kw)\n File "/usr/lib/python2.7/dist-packages/openerp/api.py", line 250, in wrapper\n return old_api(self, *args, **kwargs)\n File "/usr/lib/python2.7/dist-packages/openerp/api.py", line 354, in old_api\n result = method(recs, *args, **kwargs)\n File "/usr/lib/python2.7/dist-packages/openerp/addons/sale/sale.py", line 232, in create\n result = super(SaleOrder, self).create(vals)\n File "/usr/lib/python2.7/dist-packages/openerp/api.py", line 248, in wrapper\n return new_api(self, *args, **kwargs)\n File "/usr/lib/python2.7/dist-packages/openerp/addons/mail/models/mail_thread.py", line 233, in create\n thread = super(MailThread, self).create(values)\n File "/usr/lib/python2.7/dist-packages/openerp/api.py", line 248, in wrapper\n return new_api(self, *args, **kwargs)\n File "/usr/lib/python2.7/dist-packages/openerp/models.py", line 4157, in create\n record = self.browse(self._create(old_vals))\n File "/usr/lib/python2.7/dist-packages/openerp/api.py", line 248, in wrapper\n return new_api(self, *args, **kwargs)\n File "/usr/lib/python2.7/dist-packages/openerp/api.py", line 490, in new_api\n result = method(self._model, cr, uid, *args, **old_kwargs)\n File "/usr/lib/python2.7/dist-packages/openerp/models.py", line 4301, in _create\n tuple([u[2] for u in updates if len(u) > 2])\n File "/usr/lib/python2.7/dist-packages/openerp/sql_db.py", line 141, in wrapper\n return f(self, *args, **kwargs)\n File "/usr/lib/python2.7/dist-packages/openerp/sql_db.py", line 220, in execute\n res = self._obj.execute(query, params)\nProgrammingError: column "partner_id" is of type integer but expression is of type integer[]\nLINE 1: ...1, NULL, \'draft\', 6, 1, 1, \'2016-09-03 16:50:24\', ARRAY[6], ...\n ^\nHINT: You will need to rewrite or cast the expression.\n\n'>
Process finished with exit code 1
</code></pre>
<p>my code is the following</p>
<pre><code>import psycopg2
import psycopg2.extras
import pyexcel_xls
import pyexcel as pe
from pyexcel_xls import get_data
from datetime import datetime
import xmlrpclib
import json
url = 'http://localhost:8070'
db = 'fresh'
username = 'admin'
password = 'odoo'
#data = get_data("salesorder.xls")
#print(json.dumps(data))
records = pe.get_records(file_name="salesorder.xls")
for record in records:
print record['name']
names = record['name']
print record['location']
print record['zip']
print record['republic']
dates = record['date']
print dates
print datetime.strptime(dates,'%d/%M/%Y')
lastdat=datetime.strptime(dates,'%d/%M/%Y')
print record['product']
productname= record['product']
#Check if the customer is in or else insert him
common = xmlrpclib.ServerProxy('{}/xmlrpc/2/common'.format(url))
uid = common.authenticate(db, username, password, {})
output = common.version()
models = xmlrpclib.ServerProxy('{}/xmlrpc/2/object'.format(url))
partnerids = models.execute_kw(db, uid, password,
'res.partner', 'search', [[['name', '=', record['name']]]])
if partnerids:
print partnerids
else:
newpartn = models.execute_kw(db, uid, password, 'res.partner', 'create', [{
'name': names,
}])
partnerids=newpartn
print partnerids
#Check if a product is in else insert a new product
common = xmlrpclib.ServerProxy('{}/xmlrpc/2/common'.format(url))
uid = common.authenticate(db, username, password, {})
output = common.version()
models = xmlrpclib.ServerProxy('{}/xmlrpc/2/object'.format(url))
productids = models.execute_kw(db, uid, password,
'product.product', 'search', [[['name', '=', record['product']]]])
if productids:
print productids
else:
newproduct = models.execute_kw(db, uid, password, 'product.product', 'create', [{
'name': productname,
'default_code': partnerids
}])
productids=newproduct
print productids
uid = common.authenticate(db, username, password, {})
print output
models = xmlrpclib.ServerProxy('{}/xmlrpc/2/object'.format(url))
id = models.execute_kw(db, uid, password, 'sale.order', 'create', [{
'partner_id': partnerids,
# 'name': names,
'validity_date':"2016-01-18",
#'payment_term_id':1,
# 'user_id':"1"
# 'state':"sale"
}])
print id
</code></pre>
<p>the 75th line is the one of validity date</p>
| 0 | 2016-09-03T16:54:22Z | 39,309,633 | <p>I think the issue is that you execute a search for partnerids which will result in an array. However if you do not find any you create a partner which is represented by an integer. You then assign partnerids to the partner_id in your sale.order. </p>
<p>Sometimes you are assigning it an integer and other times an array, depending on if you are using the partnerids from the search or the newly created partner.</p>
<p>If you are sure that your search for partnerids will never result in two partners having the same name then you can use the first record returned in your search which I display below. I reassigned partnerids on a second line simply to illustrate the difference. </p>
<p>If you are not sure if you have duplicates this will be the wrong thing to do and you should refine your search to select the correct partner.</p>
<pre><code> partnerids = models.execute_kw(db, uid, password,
'res.partner', 'search', [[['name', '=', record['name']]]])
partnerids = partnerids[0] if partnerids else False
if partnerids:
print partnerids
else:
newpartn = models.execute_kw(db, uid, password, 'res.partner', 'create', [{
'name': names,
}])
partnerids=newpartn
</code></pre>
| 1 | 2016-09-03T17:38:29Z | [
"python",
"openerp",
"xml-rpc"
] |
Migrating sales from xl to odoo using XML-RPC | 39,309,268 | <p>Im trying to migrate sales order from excel sheet to odoo using xmlrpc so far i have the products working,client working but when i try to insert the sale order i get this error</p>
<pre><code>Traceback (most recent call last):
File "/home/oasis/PycharmProjects/somig/migrator.py", line 75, in <module>
'validity_date':"2016-01-18",
File "/usr/lib/python2.7/xmlrpclib.py", line 1243, in __call__
return self.__send(self.__name, args)
File "/usr/lib/python2.7/xmlrpclib.py", line 1602, in __request
verbose=self.__verbose
File "/usr/lib/python2.7/xmlrpclib.py", line 1283, in request
return self.single_request(host, handler, request_body, verbose)
File "/usr/lib/python2.7/xmlrpclib.py", line 1316, in single_request
return self.parse_response(response)
File "/usr/lib/python2.7/xmlrpclib.py", line 1493, in parse_response
return u.close()
File "/usr/lib/python2.7/xmlrpclib.py", line 800, in close
raise Fault(**self._stack[0])
xmlrpclib.Fault: <Fault 1: 'Traceback (most recent call last):\n File "/usr/lib/python2.7/dist-packages/openerp/service/wsgi_server.py", line 56, in xmlrpc_return\n result = openerp.http.dispatch_rpc(service, method, params)\n File "/usr/lib/python2.7/dist-packages/openerp/http.py", line 114, in dispatch_rpc\n result = dispatch(method, params)\n File "/usr/lib/python2.7/dist-packages/openerp/service/model.py", line 37, in dispatch\n res = fn(db, uid, *params)\n File "/usr/lib/python2.7/dist-packages/openerp/service/model.py", line 173, in execute_kw\n return execute(db, uid, obj, method, *args, **kw or {})\n File "/usr/lib/python2.7/dist-packages/openerp/service/model.py", line 118, in wrapper\n return f(dbname, *args, **kwargs)\n File "/usr/lib/python2.7/dist-packages/openerp/service/model.py", line 181, in execute\n res = execute_cr(cr, uid, obj, method, *args, **kw)\n File "/usr/lib/python2.7/dist-packages/openerp/service/model.py", line 170, in execute_cr\n return getattr(object, method)(cr, uid, *args, **kw)\n File "/usr/lib/python2.7/dist-packages/openerp/api.py", line 250, in wrapper\n return old_api(self, *args, **kwargs)\n File "/usr/lib/python2.7/dist-packages/openerp/api.py", line 354, in old_api\n result = method(recs, *args, **kwargs)\n File "/usr/lib/python2.7/dist-packages/openerp/addons/sale/sale.py", line 232, in create\n result = super(SaleOrder, self).create(vals)\n File "/usr/lib/python2.7/dist-packages/openerp/api.py", line 248, in wrapper\n return new_api(self, *args, **kwargs)\n File "/usr/lib/python2.7/dist-packages/openerp/addons/mail/models/mail_thread.py", line 233, in create\n thread = super(MailThread, self).create(values)\n File "/usr/lib/python2.7/dist-packages/openerp/api.py", line 248, in wrapper\n return new_api(self, *args, **kwargs)\n File "/usr/lib/python2.7/dist-packages/openerp/models.py", line 4157, in create\n record = self.browse(self._create(old_vals))\n File "/usr/lib/python2.7/dist-packages/openerp/api.py", line 248, in wrapper\n return new_api(self, *args, **kwargs)\n File "/usr/lib/python2.7/dist-packages/openerp/api.py", line 490, in new_api\n result = method(self._model, cr, uid, *args, **old_kwargs)\n File "/usr/lib/python2.7/dist-packages/openerp/models.py", line 4301, in _create\n tuple([u[2] for u in updates if len(u) > 2])\n File "/usr/lib/python2.7/dist-packages/openerp/sql_db.py", line 141, in wrapper\n return f(self, *args, **kwargs)\n File "/usr/lib/python2.7/dist-packages/openerp/sql_db.py", line 220, in execute\n res = self._obj.execute(query, params)\nProgrammingError: column "partner_id" is of type integer but expression is of type integer[]\nLINE 1: ...1, NULL, \'draft\', 6, 1, 1, \'2016-09-03 16:50:24\', ARRAY[6], ...\n ^\nHINT: You will need to rewrite or cast the expression.\n\n'>
Process finished with exit code 1
</code></pre>
<p>my code is the following</p>
<pre><code>import psycopg2
import psycopg2.extras
import pyexcel_xls
import pyexcel as pe
from pyexcel_xls import get_data
from datetime import datetime
import xmlrpclib
import json
url = 'http://localhost:8070'
db = 'fresh'
username = 'admin'
password = 'odoo'
#data = get_data("salesorder.xls")
#print(json.dumps(data))
records = pe.get_records(file_name="salesorder.xls")
for record in records:
print record['name']
names = record['name']
print record['location']
print record['zip']
print record['republic']
dates = record['date']
print dates
print datetime.strptime(dates,'%d/%M/%Y')
lastdat=datetime.strptime(dates,'%d/%M/%Y')
print record['product']
productname= record['product']
#Check if the customer is in or else insert him
common = xmlrpclib.ServerProxy('{}/xmlrpc/2/common'.format(url))
uid = common.authenticate(db, username, password, {})
output = common.version()
models = xmlrpclib.ServerProxy('{}/xmlrpc/2/object'.format(url))
partnerids = models.execute_kw(db, uid, password,
'res.partner', 'search', [[['name', '=', record['name']]]])
if partnerids:
print partnerids
else:
newpartn = models.execute_kw(db, uid, password, 'res.partner', 'create', [{
'name': names,
}])
partnerids=newpartn
print partnerids
#Check if a product is in else insert a new product
common = xmlrpclib.ServerProxy('{}/xmlrpc/2/common'.format(url))
uid = common.authenticate(db, username, password, {})
output = common.version()
models = xmlrpclib.ServerProxy('{}/xmlrpc/2/object'.format(url))
productids = models.execute_kw(db, uid, password,
'product.product', 'search', [[['name', '=', record['product']]]])
if productids:
print productids
else:
newproduct = models.execute_kw(db, uid, password, 'product.product', 'create', [{
'name': productname,
'default_code': partnerids
}])
productids=newproduct
print productids
uid = common.authenticate(db, username, password, {})
print output
models = xmlrpclib.ServerProxy('{}/xmlrpc/2/object'.format(url))
id = models.execute_kw(db, uid, password, 'sale.order', 'create', [{
'partner_id': partnerids,
# 'name': names,
'validity_date':"2016-01-18",
#'payment_term_id':1,
# 'user_id':"1"
# 'state':"sale"
}])
print id
</code></pre>
<p>the 75th line is the one of validity date</p>
| 0 | 2016-09-03T16:54:22Z | 39,315,389 | <p>The Error message says:</p>
<blockquote>
<p>ProgrammingError: column "partner_id" is of type integer but expression is of type integer[].</p>
</blockquote>
<p>Just give <code>partnerids</code> as an integer: </p>
<pre><code>if partnerids:
partnerids = partnerids[0]
print partnerids
</code></pre>
| 0 | 2016-09-04T09:17:38Z | [
"python",
"openerp",
"xml-rpc"
] |
Python Elasticsearch urllib3 exception | 39,309,299 | <p>I have to use python-elasticsearch library on a machine where I could only execute programs. I am trying to use elasticsearch module by appending sys.path as mentioned below. I am facing below issue. It looks like the problem related to what is mentioned here
<a href="https://github.com/elastic/elasticsearch-py/issues/253" rel="nofollow">https://github.com/elastic/elasticsearch-py/issues/253</a> . But how do I resolve this when I dont have sudo access or any sort of upgrade access.</p>
<p>**Note :**I don't have sudo access on this machine so I cannot have venv, pip etc.</p>
<pre><code> import sys
sys.path.append('/tmp/elasticpy/elasticsearch-2.3.0')
from elasticsearch import Elasticsearch
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/tmp/elasticpy/elasticsearch-2.3.0/elasticsearch/__init__.py", line 17, in <module>
from .client import Elasticsearch
File "/tmp/elasticpy/elasticsearch-2.3.0/elasticsearch/client/__init__.py", line 5, in <module>
from ..transport import Transport
File "/tmp/elasticpy/elasticsearch-2.3.0/elasticsearch/transport.py", line 4, in <module>
from .connection import Urllib3HttpConnection
File "/tmp/elasticpy/elasticsearch-2.3.0/elasticsearch/connection/__init__.py", line 3, in <module>
from .http_urllib3 import Urllib3HttpConnection
File "/tmp/elasticpy/elasticsearch-2.3.0/elasticsearch/connection/http_urllib3.py", line 2, in <module>
import urllib3
ImportError: No module named urllib3
</code></pre>
| 0 | 2016-09-03T16:57:51Z | 39,350,543 | <p>@nehal Thanks for your suggestion I was able to get it fixed. Please find the
series of steps I used to install</p>
<ol>
<li>Used easy_install to install package pip</li>
<li>Appended PYTHONPATH</li>
<li>used pip to install virtualenv</li>
<li>Activated new virtualenv</li>
<li><p>Installed elasticsearch using pip</p>
<pre><code>export PYTHONPATH="${PYTHONPATH}:/tmp/pytest/"
easy_install --install-dir /tmp/pytest/ pip
pip install virtualenv --prefix /tmp/pytest/
export PATH="${PATH}:/tmp/pytest:/tmp/pytest/bin"
export PYTHONPATH="${PYTHONPATH}:/tmp/pytest/lib/python2.7/site-packages"
cd /tmp/
virtualenv venv
source venv/bin/activate
pip install elasticsearch
</code></pre></li>
</ol>
| 0 | 2016-09-06T13:42:26Z | [
"python",
"python-2.7",
"elasticsearch",
"urllib3"
] |
Why does this piece of code gets slower with time? | 39,309,327 | <p>I'm trying to preprocess my images adding them to a 4D array. It starts off right but it gets slower with time, I thought this was due to my CPU but I tried running it on a GPU on the cloud and it still gets slower. Is this due to RAM? How can I optimize this to run faster?</p>
<pre><code>import tensorflow as tf
import os
import glob
import numpy as np
from PIL import Image
from random import randint
sess = tf.InteractiveSession()
def process_image(filename):
im = Image.open(filename)
array = np.array(im,dtype=np.uint8)
#Resize and normalize
resized = tf.image.resize_images(array, size[0], size[1], method = 0)
normalized = tf.image.per_image_whitening(resized)
result = sess.run(normalized)
return result
counter_train = 0
counter_val = 0
for i, foldername in enumerate(foldernames):
ind = 0
index = randint(ind,ind+29)
for j, filename in enumerate(glob.glob(foldername + '*.ppm')):
print filename
result = process_image(filename)
if j == index:
npX_val[counter_val]=result
npClass_val[counter_val]=i
ind += 30
index = randint(ind,ind+29)
counter_val += 1
else:
npX_train[counter_train]=result
npClass_train[counter_train]=i
counter_train += 1
print counter_val
print counter_train
</code></pre>
<p>I also ran pyinstrument and I get this</p>
<pre><code>3.160 <module> process.py:1
ââ 2.763 <module> tensorflow/__init__.py:19
ââ 2.761 <module> tensorflow/python/__init__.py:26
ââ 2.144 <module> tensorflow/contrib/__init__.py:15
â ââ 0.955 <module> tensorflow/contrib/learn/__init__.py:65
â â ââ 0.953 <module> tensorflow/contrib/learn/python/__init__.py:16
â â ââ 0.950 <module> tensorflow/contrib/learn/python/learn/__init__.py:16
â â ââ 0.889 <module> tensorflow/contrib/learn/python/learn/estimators/__init__.py:16
â â â ââ 0.789 <module> tensorflow/contrib/learn/python/learn/estimators/autoencoder.py:16
â â â â ââ 0.770 <module> tensorflow/contrib/learn/python/learn/estimators/base.py:16
â â â â ââ 0.764 <module> tensorflow/contrib/learn/python/learn/estimators/estimator.py:16
â â â â ââ 0.729 <module> tensorflow/contrib/learn/python/learn/learn_io/__init__.py:16
â â â â ââ 0.724 <module> tensorflow/contrib/learn/python/learn/learn_io/pandas_io.py:16
â â â â ââ 0.724 <module> pandas/__init__.py:5
â â â â ââ 0.307 <module> pandas/core/api.py:5
â â â â â ââ 0.283 <module> pandas/core/groupby.py:1
â â â â â ââ 0.268 <module> pandas/core/frame.py:10
â â â â â ââ 0.135 <module> pandas/core/series.py:3
â â â â â â ââ 0.116 <module> pandas/tools/plotting.py:3
â â â â â â ââ 0.112 <module> pandas/tseries/converter.py:1
â â â â â â ââ 0.061 <module> matplotlib/__init__.py:101
â â â â â â ââ 0.044 <module> matplotlib/dates.py:111
â â â â â ââ 0.102 <module> pandas/core/generic.py:2
â â â â â ââ 0.085 <module> pandas/core/internals.py:1
â â â â â ââ 0.075 <module> pandas/sparse/array.py:3
â â â â â ââ 0.070 <module> pandas/core/ops.py:5
â â â â â ââ 0.066 <module> pandas/computation/__init__.py:2
â â â â â ââ 0.065 <module> numexpr/__init__.py:22
â â â â ââ 0.123 <module> pytz/__init__.py:9
â â â â â ââ 0.110 <module> pkg_resources/__init__.py:15
â â â â â ââ 0.037 _call_aside pkg_resources/__init__.py:2938
â â â â â â ââ 0.037 _initialize_master_working_set pkg_resources/__init__.py:2953
â â â â â ââ 0.036 load_module pkg_resources/extern/__init__.py:34
â â â â ââ 0.114 <module> pandas/core/config_init.py:11
â â â â â ââ 0.083 <module> pandas/formats/format.py:2
â â â â â ââ 0.032 <module> pandas/core/index.py:2
â â â â ââ 0.067 <module> pandas/io/api.py:3
â â â ââ 0.053 <module> tensorflow/contrib/learn/python/learn/estimators/linear.py:16
â â â ââ 0.051 <module> tensorflow/contrib/linear_optimizer/__init__.py:20
â â â ââ 0.043 <module> tensorflow/contrib/linear_optimizer/python/ops/sdca_ops.py:15
â â ââ 0.033 <module> tensorflow/contrib/learn/python/learn/dataframe/__init__.py:16
â ââ 0.711 <module> tensorflow/contrib/distributions/__init__.py:73
â â ââ 0.508 <module> tensorflow/contrib/distributions/python/ops/chi2.py:15
â â â ââ 0.506 <module> tensorflow/contrib/distributions/python/ops/gamma.py:15
â â â ââ 0.506 <module> tensorflow/contrib/framework/__init__.py:58
â â â ââ 0.498 <module> tensorflow/contrib/framework/python/ops/__init__.py:15
â â â ââ 0.489 <module> tensorflow/contrib/framework/python/ops/embedding_ops.py:15
â â â ââ 0.487 <module> tensorflow/contrib/layers/__init__.py:79
â â â ââ 0.482 <module> tensorflow/contrib/layers/python/layers/__init__.py:15
â â â ââ 0.172 <module> tensorflow/contrib/layers/python/layers/layers.py:17
â â â â ââ 0.160 <module> tensorflow/python/ops/standard_ops.py:17
â â â â ââ 0.061 <module> tensorflow/python/ops/gradients.py:15
â â â ââ 0.131 <module> tensorflow/contrib/layers/python/layers/optimizers.py:15
â â â â ââ 0.127 <module> tensorflow/python/training/training.py:137
â â â â ââ 0.035 <module> tensorflow/python/training/adadelta.py:16
â â â â ââ 0.035 <module> tensorflow/python/training/training_ops.py:16
â â â ââ 0.069 <module> tensorflow/contrib/layers/python/layers/feature_column.py:68
â â â ââ 0.053 <module> tensorflow/contrib/layers/python/layers/embedding_ops.py:15
â â â â ââ 0.050 <module> tensorflow/contrib/layers/python/ops/sparse_feature_cross_op.py:15
â â â â ââ 0.045 load_op_library tensorflow/python/framework/load_library.py:40
â â â ââ 0.048 <module> tensorflow/contrib/layers/python/layers/target_column.py:16
â â â ââ 0.046 <module> tensorflow/contrib/metrics/__init__.py:135
â â â ââ 0.039 <module> tensorflow/contrib/metrics/python/ops/metric_ops.py:19
â â â ââ 0.037 <module> tensorflow/contrib/metrics/python/ops/set_ops.py:15
â â â ââ 0.034 load_op_library tensorflow/python/framework/load_library.py:40
â â ââ 0.161 <module> tensorflow/contrib/distributions/python/ops/bernoulli.py:15
â â ââ 0.158 <module> tensorflow/python/ops/nn.py:271
â â ââ 0.087 <module> tensorflow/python/ops/init_ops.py:16
â â ââ 0.085 <module> tensorflow/python/ops/nn_ops.py:15
â â ââ 0.060 <module> tensorflow/python/ops/gen_nn_ops.py:4
â â ââ 0.057 _InitOpDefLibrary tensorflow/python/ops/gen_nn_ops.py:1630
â â ââ 0.054 Merge google/protobuf/text_format.py:291
â â ââ 0.052 MergeLines google/protobuf/text_format.py:331
â â ââ 0.052 _ParseOrMerge google/protobuf/text_format.py:350
â â ââ 0.052 _MergeField google/protobuf/text_format.py:374
â â ââ 0.052 _MergeField google/protobuf/text_format.py:374
â â ââ 0.038 _MergeField google/protobuf/text_format.py:374
â ââ 0.265 <module> tensorflow/contrib/bayesflow/__init__.py:18
â â ââ 0.264 <module> tensorflow/contrib/bayesflow/python/ops/stochastic_graph.py:38
â â ââ 0.145 <module> tensorflow/python/ops/array_ops.py:70
â â â ââ 0.068 <module> tensorflow/python/ops/gen_math_ops.py:4
â â â â ââ 0.065 _InitOpDefLibrary tensorflow/python/ops/gen_math_ops.py:2378
â â â â ââ 0.063 Merge google/protobuf/text_format.py:291
â â â â ââ 0.063 MergeLines google/protobuf/text_format.py:331
â â â â ââ 0.063 _ParseOrMerge google/protobuf/text_format.py:350
â â â â ââ 0.063 _MergeField google/protobuf/text_format.py:374
â â â â ââ 0.059 _MergeField google/protobuf/text_format.py:374
â â â â ââ 0.052 _MergeField google/protobuf/text_format.py:374
â â â ââ 0.045 <module> tensorflow/python/ops/gen_array_ops.py:4
â â â ââ 0.039 _InitOpDefLibrary tensorflow/python/ops/gen_array_ops.py:2677
â â â ââ 0.038 Merge google/protobuf/text_format.py:291
â â â ââ 0.038 MergeLines google/protobuf/text_format.py:331
â â â ââ 0.038 _ParseOrMerge google/protobuf/text_format.py:350
â â â ââ 0.038 _MergeField google/protobuf/text_format.py:374
â â â ââ 0.035 _MergeField google/protobuf/text_format.py:374
â â ââ 0.085 <module> tensorflow/python/ops/math_ops.py:210
â ââ 0.071 <module> tensorflow/contrib/slim/__init__.py:18
â â ââ 0.046 <module> tensorflow/contrib/slim/python/slim/data/tfexample_decoder.py:20
â â ââ 0.036 TFExampleDecoder tensorflow/contrib/slim/python/slim/data/tfexample_decoder.py:273
â ââ 0.051 <module> tensorflow/contrib/quantization/__init__.py:16
â â ââ 0.050 <module> tensorflow/contrib/quantization/python/__init__.py:15
â ââ 0.045 <module> tensorflow/contrib/copy_graph/__init__.py:20
â ââ 0.043 <module> tensorflow/contrib/copy_graph/python/util/copy_elements.py:27
ââ 0.299 <module> numpy/__init__.py:106
â ââ 0.235 <module> numpy/add_newdocs.py:10
â ââ 0.230 <module> numpy/lib/__init__.py:1
â ââ 0.160 <module> numpy/lib/type_check.py:3
â ââ 0.158 <module> numpy/core/__init__.py:1
â ââ 0.036 <module> numpy/testing/__init__.py:7
ââ 0.151 <module> tensorflow/python/pywrap_tensorflow.py:11
â ââ 0.148 swig_import_helper tensorflow/python/pywrap_tensorflow.py:13
ââ 0.072 <module> tensorflow/core/framework/graph_pb2.py:4
ââ 0.039 <module> tensorflow/python/platform/test.py:57
</code></pre>
| 0 | 2016-09-03T17:01:16Z | 39,309,525 | <p>I don't know much about TensorFlow, but I believe the problem is <code>process_image</code> is using a bunch of globals, particularly <code>tf</code>. Every time it's called you're running TensorFlow on an ever increasing set of images. First there's <a href="https://en.wikipedia.org/wiki/1_%2B_2_%2B_3_%2B_4_%2B_%E2%8B%AF" rel="nofollow">1, then 2, then 3, then 4, 5, 6, ...</a></p>
<pre><code>1 + 2 + 3 + 4 + 5 + ... + n = n ( n + 1 ) / 2
</code></pre>
<p>So by 100 images you've actually processed 5,050. This is an O(n<sup>2</sup>) algorithm which means its runtime (and, in this case, memory) will grow exponentially as the number of images increases.</p>
<p>Again, I don't know much about TensorFlow, but perhaps leaving calling <code>sess.run</code> for the end makes more sense? Though you appear to be interested in the intermediate results?</p>
<p>And, as a very good rule of thumb, avoid globals. It's hard to tell them apart from local variables, they break the neat encapsulation of functions making the program hard to understand, and they and lead to accumulation problems like this.</p>
| 1 | 2016-09-03T17:25:34Z | [
"python",
"performance",
"numpy",
"tensorflow"
] |
Unable to feed value for placeholder tensor | 39,309,367 | <p>I have written a simple version bidirectional lstm for sentence classification. But it keeps giving me "You must feed a value for placeholder tensor 'train_x'" error and it seems this come from the variable initialization step. </p>
<pre><code>data = load_data(FLAGS.data)
model = RNNClassifier(FLAGS)
init = tf.initialize_all_variables()
with tf.Session() as sess:
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(sess=sess, coord=coord)
sess.run(init)
print("Graph initialized..")
print()
np.random.seed(FLAGS.random_state)
for epoch in range(FLAGS.max_max_epoch):
loss = sess.run(model.cost, feed_dict={model.train_x: data.train_x, model.train_y: data.train_y,
model.embedding_placeholder: data.glove_vec})
print("Epoch {:2d}: Loss = {:.6f} = {:.5f}".format(epoch+1, loss))
coord.request_stop()
coord.join(threads)
</code></pre>
<p>And the <code>RNNClassifier</code> class code (in a different directory):</p>
<pre><code>class RNNClassifier:
def __init__(self, FLAGS):
self.params = FLAGS
with tf.device("/cpu:0"):
self.train_x = tf.placeholder(tf.int32, [6248, 42], name='train_x')
self.train_y = tf.placeholder(tf.int32, [6248, 3], name='train_y')
self.embedding_placeholder = tf.placeholder(tf.float32, [1193515, 100])
with tf.variable_scope('forward_lstm'):
lstm_fw_cell = tf.nn.rnn_cell.LSTMCell(num_units=self.params.num_hidden, use_peepholes=False,
activation=tf.nn.relu, forget_bias=0.0,
state_is_tuple=True)
with tf.variable_scope('backward_lstm'):
lstm_bw_cell = tf.nn.rnn_cell.LSTMCell(num_units=self.params.num_hidden, use_peepholes=False,
activation=tf.nn.relu, forget_bias=0.0,
state_is_tuple=True)
fw_initial_state = lstm_fw_cell.zero_state(self.params.batch_size, tf.float32)
bw_initial_state = lstm_bw_cell.zero_state(self.params.batch_size, tf.float32)
self._initial_state = [fw_initial_state, bw_initial_state]
with tf.device("/cpu:0"), tf.variable_scope('softmax'):
self.W = tf.get_variable('W', [self.params.num_hidden*2, self.params.num_classes])
self.b = tf.get_variable('b', [self.params.num_classes], initializer=tf.constant_initializer(0.0))
batched_inputs, batched_labels = self.batch_data()
embed_inputs = self.use_embedding(batched_inputs)
rnn_outputs, output_state_fw, output_state_bw = tf.nn.bidirectional_rnn(
cell_fw=lstm_fw_cell,
cell_bw=lstm_bw_cell,
inputs=embed_inputs,
initial_state_fw=fw_initial_state,
initial_state_bw=bw_initial_state
)
logits = tf.matmul(rnn_outputs[-1], self.W) + self.b
self._cost = cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits, tf.cast(batched_labels, tf.float32)))
optimizer = tf.train.AdamOptimizer(learning_rate=0.05).minimize(cost)
def batch_data(self):
# inputs = tf.convert_to_tensor(train_x, dtype=tf.int32)
# labels = tf.convert_to_tensor(train_y, dtype=tf.int32)
batched_inputs, batched_labels = tf.train.batch(
tensors=[self._train_x, self._train_y],
batch_size=self.params.batch_size,
dynamic_pad=True,
enqueue_many=True,
name='batching'
)
return batched_inputs, batched_labels
def use_embedding(self, batched_inputs):
with tf.device("/cpu:0"), tf.name_scope("input_embedding"):
embedding = tf.get_variable("embedding", shape=[1193515, 100], trainable=False)
embedding_init = embedding.assign(self.embedding_placeholder)
embed_inputs = tf.split(1, self.params.seq_len, tf.nn.embedding_lookup(embedding_init, batched_inputs))
embed_inputs = [tf.squeeze(input_, [1]) for input_ in embed_inputs]
return embed_inputs
@property
def cost(self):
return self._cost
</code></pre>
<p><strong>The output (including the error):</strong></p>
<pre><code>I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:925] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
I tensorflow/core/common_runtime/gpu/gpu_init.cc:102] Found device 0 with properties:
name: GeForce GTX 750 Ti
major: 5 minor: 0 memoryClockRate (GHz) 1.0845
pciBusID 0000:01:00.0
Total memory: 2.00GiB
Free memory: 1.41GiB
I tensorflow/core/common_runtime/gpu/gpu_init.cc:126] DMA: 0
I tensorflow/core/common_runtime/gpu/gpu_init.cc:136] 0: Y
I tensorflow/core/common_runtime/gpu/gpu_device.cc:839] Creating TensorFlow device (/gpu:0) -> (device: 0, name: GeForce GTX 750 Ti, pci bus id: 0000:01:00.0)
E tensorflow/core/client/tensor_c_api.cc:485] You must feed a value for placeholder tensor 'train_x' with dtype int32 and shape [6248,42]
[[Node: train_x = Placeholder[dtype=DT_INT32, shape=[6248,42], _device="/job:localhost/replica:0/task:0/cpu:0"]()]]
Graph initialized..
W tensorflow/core/framework/op_kernel.cc:936] Out of range: PaddingFIFOQueue '_0_batching/padding_fifo_queue' is closed and has insufficient elements (requested 50, current size 0)
[[Node: batching = QueueDequeueMany[_class=["loc:@batching/padding_fifo_queue"], component_types=[DT_INT32, DT_INT32], timeout_ms=-1, _device="/job:localhost/replica:0/task:0/cpu:0"](batching/padding_fifo_queue, batching/n)]]
W tensorflow/core/framework/op_kernel.cc:936] Out of range: PaddingFIFOQueue '_0_batching/padding_fifo_queue' is closed and has insufficient elements (requested 50, current size 0)
[[Node: batching = QueueDequeueMany[_class=["loc:@batching/padding_fifo_queue"], component_types=[DT_INT32, DT_INT32], timeout_ms=-1, _device="/job:localhost/replica:0/task:0/cpu:0"](batching/padding_fifo_queue, batching/n)]]
E tensorflow/core/client/tensor_c_api.cc:485] PaddingFIFOQueue '_0_batching/padding_fifo_queue' is closed and has insufficient elements (requested 50, current size 0)
[[Node: batching = QueueDequeueMany[_class=["loc:@batching/padding_fifo_queue"], component_types=[DT_INT32, DT_INT32], timeout_ms=-1, _device="/job:localhost/replica:0/task:0/cpu:0"](batching/padding_fifo_queue, batching/n)]]
[[Node: batching/_9 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/gpu:0", send_device="/job:localhost/replica:0/task:0/cpu:0", send_device_incarnation=1, tensor_name="edge_1191_batching", tensor_type=DT_INT32, _device="/job:localhost/replica:0/task:0/gpu:0"]()]]
Traceback (most recent call last):
File "train_lstm.py", line 66, in <module>
model.embedding_placeholder: data.glove_vec})
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 382, in run
run_metadata_ptr)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 655, in _run
feed_dict_string, options, run_metadata)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 723, in _do_run
target_list, options, run_metadata)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 743, in _do_call
raise type(e)(node_def, op, message)
tensorflow.python.framework.errors.OutOfRangeError: PaddingFIFOQueue '_0_batching/padding_fifo_queue' is closed and has insufficient elements (requested 50, current size 0)
[[Node: batching = QueueDequeueMany[_class=["loc:@batching/padding_fifo_queue"], component_types=[DT_INT32, DT_INT32], timeout_ms=-1, _device="/job:localhost/replica:0/task:0/cpu:0"](batching/padding_fifo_queue, batching/n)]]
[[Node: batching/_9 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/gpu:0", send_device="/job:localhost/replica:0/task:0/cpu:0", send_device_incarnation=1, tensor_name="edge_1191_batching", tensor_type=DT_INT32, _device="/job:localhost/replica:0/task:0/gpu:0"]()]]
Caused by op u'batching', defined at:
File "train_lstm.py", line 49, in <module>
model = RNNClassifier(FLAGS)
File "/home/ccrmad/Code/TDLSTM/models/rnn_classifier.py", line 34, in __init__
batched_inputs, batched_labels = self.batch_data()
File "/home/ccrmad/Code/TDLSTM/models/rnn_classifier.py", line 74, in batch_data
name='batching'
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/training/input.py", line 595, in batch
dequeued = queue.dequeue_many(batch_size, name=name)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/data_flow_ops.py", line 435, in dequeue_many
self._queue_ref, n=n, component_types=self._dtypes, name=name)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/gen_data_flow_ops.py", line 867, in _queue_dequeue_many
timeout_ms=timeout_ms, name=name)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/op_def_library.py", line 703, in apply_op
op_def=op_def)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 2310, in create_op
original_op=self._default_original_op, op_def=op_def)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 1232, in __init__
self._traceback = _extract_stack()
</code></pre>
<p>I have tried move the <code>train_x</code> and <code>train_y</code> placeholder initialization before <code>init = tf.initialize_all_variables()</code> and feed them to RNNClassifier() as two args but it still give the same error. Why?</p>
| 13 | 2016-09-03T17:05:58Z | 39,440,287 | <p>This is what I did.. </p>
<p>I could change the way I initialised my input variables as:</p>
<pre><code>data = load_data(FLAGS.data)
model = RNNClassifier(FLAGS, data)
init = tf.initialize_all_variables()
with tf.Session() as sess:
sess.run(init)
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(sess=sess, coord=coord)
for epoch in range(FLAGS.max_max_epoch):
sess.run(model.train_step)
loss, acc = sess.run([model.mean_cost, model.accuracy])
print("Epoch {:2d}: Loss = {:.6f}; Training Accuracy = {:.5f}".format(epoch+1, loss, acc))
print()
coord.request_stop()
coord.join(threads)
</code></pre>
<p>And in RNNClassifier class I could replace </p>
<pre><code> self.train_x = tf.placeholder(tf.int32, [6248, 42], name='train_x')
self.train_y = tf.placeholder(tf.int32, [6248, 3], name='train_y')
self.embedding_placeholder = tf.placeholder(tf.float32, [1193515, 100])
</code></pre>
<p>(and remove <code>use_embedding()</code>) to</p>
<pre><code>def __init__(self, FLAGS, data):
self._train_x = tf.convert_to_tensor(data.train_x, dtype=tf.int32)
self._train_y = tf.convert_to_tensor(data.train_y, dtype=tf.int32)
embedding = tf.get_variable("embedding", shape=self.embedding_shape, trainable=False)
self.embedding_init = embedding.assign(data.glove_vec)
</code></pre>
<p>This way everything is initialised with <code>RNNClassifier(FLAGS, data)</code> before making the call to the queue runners. </p>
<p>I still don't know why the previous way aka using placeholders, didn't work. I have checked the dtype and data shape, they all match. <a href="http://stackoverflow.com/questions/35532457/tensorflow-placeholder-variable-for-integer-or-boolean-isnt-working">This post</a> seems to have a similar problem and the "answer" suggests to replace placeholder with tf.Variable. I have tried this -> input values can now be fed but obvs it doesn't work as placeholders do and only feed the initialised values..</p>
<p><strong>UPDATE:</strong> I think the error might be caused by operating inputs batching in the RNNClassifier class, that somehow effected feeding input data into the graph (<em>again please correct me if you know the cause to the error, thanks!</em>). I have instead relocated my batching and embedding functions onto my main code before initialising my session, this way I think it makes sure all inputs are defined to the main pipeline and batching&prefetching would be handled inside the tf graph (by not using placeholders).</p>
<p>Here's my code:</p>
<pre><code>def batch(x, y):
with tf.device("/cpu:0"):
x = tf.convert_to_tensor(x, dtype=tf.int32)
y = tf.convert_to_tensor(y, dtype=tf.int32)
batched_x, batched_y = tf.train.batch(
tensors=[x, y],
batch_size=50,
dynamic_pad=True,
enqueue_many=True,
name='batching'
)
return (batched_x, batched_y)
def embed(df):
with tf.device("/cpu:0"), tf.variable_scope("embed"):
embedding = tf.get_variable("embedding", shape=df.embed_shape, trainable=False)
embedding_init = embedding.assign(df.embed_vec)
return embedding_init
data = load_data(FLAGS.data)
pretrained_embed = embed(data)
batched_train_x, batched_train_y = batch(data.train_x, data.train_y)
batched_test_x, batched_test_y = batch(data.train_x, data.train_y)
model = RNNClassifier(FLAGS, pretrained_embed)
logits = model.inference(batched_train_x)
test_pred = model.inference(batched_test_x, reuse=True)
loss = model.loss(logits, batched_train_y)
test_loss = model.loss(test_pred, batched_test_y)
train_op = model.training(loss[0])
init = tf.group(tf.initialize_all_variables(),
tf.initialize_local_variables())
with tf.Session() as sess:
t0 = time.time()
sess.run(init)
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(sess=sess, coord=coord)
np.random.seed(FLAGS.random_state)
for epoch in range(FLAGS.max_max_epoch):
_, output = sess.run([train_op, loss])
loss_value, acc = output
print("Epoch {:2d}: Loss = {:.6f}; Training Accuracy = {:.5f}".format(epoch+1, loss_value, acc))
print()
coord.request_stop()
coord.join(threads)
</code></pre>
<p>And the RNNClassifier:</p>
<pre><code>class RNNClassifier:
def __init__(self, FLAGS, embedding_init):
self.batch_size = FLAGS.batch_size
self.num_hidden = FLAGS.num_hidden
self.num_classes = FLAGS.num_classes
self.seq_len = FLAGS.seq_len
self.embedding_init = embedding_init
def inference(self, batched_inputs, reuse=None):
embed_inputs = tf.nn.embedding_lookup(self.embedding_init, tf.transpose(batched_inputs))
with tf.variable_scope('hidden', reuse=reuse):
with tf.variable_scope('forward_lstm'):
lstm_fw_cell = tf.nn.rnn_cell.LSTMCell(num_units=self.num_hidden, use_peepholes=False,
activation=tf.nn.relu, forget_bias=0.0,
initializer=tf.random_uniform_initializer(-1.0, 1.0),
state_is_tuple=True)
lstm_fw_cell = tf.nn.rnn_cell.DropoutWrapper(cell=lstm_fw_cell, input_keep_prob=0.7)
with tf.variable_scope('backward_lstm'):
lstm_bw_cell = tf.nn.rnn_cell.LSTMCell(num_units=self.num_hidden, use_peepholes=False,
activation=tf.nn.relu, forget_bias=0.0,
initializer=tf.random_uniform_initializer(-1.0, 1.0),
state_is_tuple=True)
lstm_bw_cell = tf.nn.rnn_cell.DropoutWrapper(cell=lstm_bw_cell, input_keep_prob=0.7)
fw_initial_state = lstm_fw_cell.zero_state(self.batch_size, tf.float32)
bw_initial_state = lstm_bw_cell.zero_state(self.batch_size, tf.float32)
rnn_outputs, output_state_fw, output_state_bw = tf.nn.bidirectional_rnn(
cell_fw=lstm_fw_cell,
cell_bw=lstm_bw_cell,
inputs=tf.unpack(embed_inputs),
# sequence_length=self.seq_len,
initial_state_fw=fw_initial_state,
initial_state_bw=bw_initial_state
)
with tf.variable_scope('output', reuse=reuse):
with tf.variable_scope('softmax'):
W = tf.get_variable('W', [self.num_hidden*2, self.num_classes],
initializer=tf.truncated_normal_initializer(stddev=0.1))
b = tf.get_variable('b', [self.num_classes], initializer=tf.constant_initializer(0.1))
logits = tf.matmul(rnn_outputs[-1], W) + b
return logits
def loss(self, logits, labels):
cost = tf.nn.softmax_cross_entropy_with_logits(logits, tf.cast(labels, tf.float32))
# self.total_cost = tf.reduce_sum(self.cost)
mean_cost = tf.reduce_mean(cost)
correct_pred = tf.equal(tf.argmax(logits, 1), tf.argmax(labels, 1))
accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))
return mean_cost, accuracy
def training(self, cost):
optimizer = tf.train.AdamOptimizer(learning_rate=0.001)
train_op = optimizer.minimize(cost)
return train_op
</code></pre>
<p>On a side note, I wish the Tensorflow community on stackoverflow would be more active..</p>
| 0 | 2016-09-11T20:21:28Z | [
"python",
"tensorflow"
] |
Unable to feed value for placeholder tensor | 39,309,367 | <p>I have written a simple version bidirectional lstm for sentence classification. But it keeps giving me "You must feed a value for placeholder tensor 'train_x'" error and it seems this come from the variable initialization step. </p>
<pre><code>data = load_data(FLAGS.data)
model = RNNClassifier(FLAGS)
init = tf.initialize_all_variables()
with tf.Session() as sess:
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(sess=sess, coord=coord)
sess.run(init)
print("Graph initialized..")
print()
np.random.seed(FLAGS.random_state)
for epoch in range(FLAGS.max_max_epoch):
loss = sess.run(model.cost, feed_dict={model.train_x: data.train_x, model.train_y: data.train_y,
model.embedding_placeholder: data.glove_vec})
print("Epoch {:2d}: Loss = {:.6f} = {:.5f}".format(epoch+1, loss))
coord.request_stop()
coord.join(threads)
</code></pre>
<p>And the <code>RNNClassifier</code> class code (in a different directory):</p>
<pre><code>class RNNClassifier:
def __init__(self, FLAGS):
self.params = FLAGS
with tf.device("/cpu:0"):
self.train_x = tf.placeholder(tf.int32, [6248, 42], name='train_x')
self.train_y = tf.placeholder(tf.int32, [6248, 3], name='train_y')
self.embedding_placeholder = tf.placeholder(tf.float32, [1193515, 100])
with tf.variable_scope('forward_lstm'):
lstm_fw_cell = tf.nn.rnn_cell.LSTMCell(num_units=self.params.num_hidden, use_peepholes=False,
activation=tf.nn.relu, forget_bias=0.0,
state_is_tuple=True)
with tf.variable_scope('backward_lstm'):
lstm_bw_cell = tf.nn.rnn_cell.LSTMCell(num_units=self.params.num_hidden, use_peepholes=False,
activation=tf.nn.relu, forget_bias=0.0,
state_is_tuple=True)
fw_initial_state = lstm_fw_cell.zero_state(self.params.batch_size, tf.float32)
bw_initial_state = lstm_bw_cell.zero_state(self.params.batch_size, tf.float32)
self._initial_state = [fw_initial_state, bw_initial_state]
with tf.device("/cpu:0"), tf.variable_scope('softmax'):
self.W = tf.get_variable('W', [self.params.num_hidden*2, self.params.num_classes])
self.b = tf.get_variable('b', [self.params.num_classes], initializer=tf.constant_initializer(0.0))
batched_inputs, batched_labels = self.batch_data()
embed_inputs = self.use_embedding(batched_inputs)
rnn_outputs, output_state_fw, output_state_bw = tf.nn.bidirectional_rnn(
cell_fw=lstm_fw_cell,
cell_bw=lstm_bw_cell,
inputs=embed_inputs,
initial_state_fw=fw_initial_state,
initial_state_bw=bw_initial_state
)
logits = tf.matmul(rnn_outputs[-1], self.W) + self.b
self._cost = cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits, tf.cast(batched_labels, tf.float32)))
optimizer = tf.train.AdamOptimizer(learning_rate=0.05).minimize(cost)
def batch_data(self):
# inputs = tf.convert_to_tensor(train_x, dtype=tf.int32)
# labels = tf.convert_to_tensor(train_y, dtype=tf.int32)
batched_inputs, batched_labels = tf.train.batch(
tensors=[self._train_x, self._train_y],
batch_size=self.params.batch_size,
dynamic_pad=True,
enqueue_many=True,
name='batching'
)
return batched_inputs, batched_labels
def use_embedding(self, batched_inputs):
with tf.device("/cpu:0"), tf.name_scope("input_embedding"):
embedding = tf.get_variable("embedding", shape=[1193515, 100], trainable=False)
embedding_init = embedding.assign(self.embedding_placeholder)
embed_inputs = tf.split(1, self.params.seq_len, tf.nn.embedding_lookup(embedding_init, batched_inputs))
embed_inputs = [tf.squeeze(input_, [1]) for input_ in embed_inputs]
return embed_inputs
@property
def cost(self):
return self._cost
</code></pre>
<p><strong>The output (including the error):</strong></p>
<pre><code>I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:925] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
I tensorflow/core/common_runtime/gpu/gpu_init.cc:102] Found device 0 with properties:
name: GeForce GTX 750 Ti
major: 5 minor: 0 memoryClockRate (GHz) 1.0845
pciBusID 0000:01:00.0
Total memory: 2.00GiB
Free memory: 1.41GiB
I tensorflow/core/common_runtime/gpu/gpu_init.cc:126] DMA: 0
I tensorflow/core/common_runtime/gpu/gpu_init.cc:136] 0: Y
I tensorflow/core/common_runtime/gpu/gpu_device.cc:839] Creating TensorFlow device (/gpu:0) -> (device: 0, name: GeForce GTX 750 Ti, pci bus id: 0000:01:00.0)
E tensorflow/core/client/tensor_c_api.cc:485] You must feed a value for placeholder tensor 'train_x' with dtype int32 and shape [6248,42]
[[Node: train_x = Placeholder[dtype=DT_INT32, shape=[6248,42], _device="/job:localhost/replica:0/task:0/cpu:0"]()]]
Graph initialized..
W tensorflow/core/framework/op_kernel.cc:936] Out of range: PaddingFIFOQueue '_0_batching/padding_fifo_queue' is closed and has insufficient elements (requested 50, current size 0)
[[Node: batching = QueueDequeueMany[_class=["loc:@batching/padding_fifo_queue"], component_types=[DT_INT32, DT_INT32], timeout_ms=-1, _device="/job:localhost/replica:0/task:0/cpu:0"](batching/padding_fifo_queue, batching/n)]]
W tensorflow/core/framework/op_kernel.cc:936] Out of range: PaddingFIFOQueue '_0_batching/padding_fifo_queue' is closed and has insufficient elements (requested 50, current size 0)
[[Node: batching = QueueDequeueMany[_class=["loc:@batching/padding_fifo_queue"], component_types=[DT_INT32, DT_INT32], timeout_ms=-1, _device="/job:localhost/replica:0/task:0/cpu:0"](batching/padding_fifo_queue, batching/n)]]
E tensorflow/core/client/tensor_c_api.cc:485] PaddingFIFOQueue '_0_batching/padding_fifo_queue' is closed and has insufficient elements (requested 50, current size 0)
[[Node: batching = QueueDequeueMany[_class=["loc:@batching/padding_fifo_queue"], component_types=[DT_INT32, DT_INT32], timeout_ms=-1, _device="/job:localhost/replica:0/task:0/cpu:0"](batching/padding_fifo_queue, batching/n)]]
[[Node: batching/_9 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/gpu:0", send_device="/job:localhost/replica:0/task:0/cpu:0", send_device_incarnation=1, tensor_name="edge_1191_batching", tensor_type=DT_INT32, _device="/job:localhost/replica:0/task:0/gpu:0"]()]]
Traceback (most recent call last):
File "train_lstm.py", line 66, in <module>
model.embedding_placeholder: data.glove_vec})
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 382, in run
run_metadata_ptr)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 655, in _run
feed_dict_string, options, run_metadata)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 723, in _do_run
target_list, options, run_metadata)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 743, in _do_call
raise type(e)(node_def, op, message)
tensorflow.python.framework.errors.OutOfRangeError: PaddingFIFOQueue '_0_batching/padding_fifo_queue' is closed and has insufficient elements (requested 50, current size 0)
[[Node: batching = QueueDequeueMany[_class=["loc:@batching/padding_fifo_queue"], component_types=[DT_INT32, DT_INT32], timeout_ms=-1, _device="/job:localhost/replica:0/task:0/cpu:0"](batching/padding_fifo_queue, batching/n)]]
[[Node: batching/_9 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/gpu:0", send_device="/job:localhost/replica:0/task:0/cpu:0", send_device_incarnation=1, tensor_name="edge_1191_batching", tensor_type=DT_INT32, _device="/job:localhost/replica:0/task:0/gpu:0"]()]]
Caused by op u'batching', defined at:
File "train_lstm.py", line 49, in <module>
model = RNNClassifier(FLAGS)
File "/home/ccrmad/Code/TDLSTM/models/rnn_classifier.py", line 34, in __init__
batched_inputs, batched_labels = self.batch_data()
File "/home/ccrmad/Code/TDLSTM/models/rnn_classifier.py", line 74, in batch_data
name='batching'
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/training/input.py", line 595, in batch
dequeued = queue.dequeue_many(batch_size, name=name)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/data_flow_ops.py", line 435, in dequeue_many
self._queue_ref, n=n, component_types=self._dtypes, name=name)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/gen_data_flow_ops.py", line 867, in _queue_dequeue_many
timeout_ms=timeout_ms, name=name)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/op_def_library.py", line 703, in apply_op
op_def=op_def)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 2310, in create_op
original_op=self._default_original_op, op_def=op_def)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 1232, in __init__
self._traceback = _extract_stack()
</code></pre>
<p>I have tried move the <code>train_x</code> and <code>train_y</code> placeholder initialization before <code>init = tf.initialize_all_variables()</code> and feed them to RNNClassifier() as two args but it still give the same error. Why?</p>
| 13 | 2016-09-03T17:05:58Z | 39,479,736 | <p>It looks like the problem is in this method, in <code>RNNClassifier</code>:</p>
<pre><code>def batch_data(self):
# ...
batched_inputs, batched_labels = tf.train.batch(
tensors=[self._train_x, self._train_y],
batch_size=self.params.batch_size,
dynamic_pad=True,
enqueue_many=True,
name='batching')
</code></pre>
<p>The two tensor arguments to <a href="https://www.tensorflow.org/versions/r0.10/api_docs/python/io_ops.html#batch" rel="nofollow"><code>tf.train.batch()</code></a> are <code>self._train_x</code> and <code>self._train_y</code>. In the <code>RNNClassifier</code> constructor, it seems like you create these as <a href="https://www.tensorflow.org/versions/r0.10/api_docs/python/io_ops.html#placeholder" rel="nofollow"><code>tf.placeholder()</code></a> tensors:</p>
<pre><code>def __init__(self, FLAGS):
# ...
with tf.device("/cpu:0"):
self.train_x = tf.placeholder(tf.int32, [6248, 42], name='train_x')
self.train_y = tf.placeholder(tf.int32, [6248, 3], name='train_y')
</code></pre>
<p>...though I'm assuming that the difference between <code>self._train_x</code> and <code>self.train_x</code> is a copy-paste error, because <code>self._train_x</code> doesn't seem to be defined anywhere else.</p>
<p>Now, one of the surprising things about <code>tf.train.batch()</code> is that it consumes its inputs in a completely separate thread, called a "queue runner", and started when you call <a href="https://www.tensorflow.org/versions/r0.10/api_docs/python/train.html#start_queue_runners" rel="nofollow"><code>tf.train.start_queue_runners()</code></a>. This thread calls <a href="https://www.tensorflow.org/versions/r0.10/api_docs/python/client.html#Session.run" rel="nofollow"><code>Session.run()</code></a> on a subgraph that depends on your placeholders, but doesn't know how to feed these placeholders, so it is this call that fails, leading to the error you are seeing.</p>
<p>How then should you fix it? One option would be to use a <a href="https://github.com/tensorflow/tensorflow/blob/450e9386e0cc4b81b49adb9184859411f43ef259/tensorflow/contrib/learn/python/learn/dataframe/queues/feeding_queue_runner.py" rel="nofollow">"feeding queue runner"</a>, for which there is experimental support. A simpler option would be to use the <a href="https://www.tensorflow.org/versions/r0.10/api_docs/python/io_ops.html#slice_input_producer" rel="nofollow"><code>tf.train.slice_input_producer()</code></a> to produce slices from your input data, as follows:</p>
<pre><code>def batch_data(self, train_x, train_y):
input_slice, label_slice = tf.train.slice_input_producer([train_x, train_y])
batched_inputs, batched_labels = tf.train.batch(
tensors=[input_slice, label_slice],
batch_size=self.params.batch_size,
dynamic_pad=False, # All rows are the same shape.
enqueue_many=False, # tf.train.slice_input_producer() produces one row at a time.
name='batching')
return batched_inputs, batched_labels
# ...
# Create batches from the entire training data, where `array_input` and
# `array_labels` are two NumPy arrays.
batched_inputs, batched_labels = model.batch_data(array_input, array_labels)
</code></pre>
| 0 | 2016-09-13T22:10:34Z | [
"python",
"tensorflow"
] |
How to sum and to mean one DataFrame to create another DataFrame | 39,309,435 | <p>After creating DataFrame with some duplicated cell values in the column <strong>Name</strong>:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'Name': ['Will','John','John','John','Alex'],
'Payment': [15, 10, 10, 10, 15],
'Duration': [30, 15, 15, 15, 20]})
</code></pre>
<p><a href="http://i.stack.imgur.com/MEFnO.png"><img src="http://i.stack.imgur.com/MEFnO.png" alt="enter image description here"></a></p>
<p>I would like to proceed by creating another DataFrame where the duplicated values in <strong>Name</strong> column are consolidated leaving no duplicates. At the same time I want
to sum the payments values John made. I proceed with:</p>
<pre><code>df_sum = df.groupby('Name', axis=0).sum().reset_index()
</code></pre>
<p><a href="http://i.stack.imgur.com/7i89K.png"><img src="http://i.stack.imgur.com/7i89K.png" alt="enter image description here"></a></p>
<p>But since <code>df.groupby('Name', axis=0).sum()</code> command applies the sum function to every column in DataFrame the <strong>Duration</strong> (of the visit in minutes) column is processed as well. Instead I would like to get an average values for the <strong>Duration</strong> column. So I would need to use <code>mean()</code> method, like so:</p>
<pre><code>df_mean = df.groupby('Name', axis=0).mean().reset_index()
</code></pre>
<p><a href="http://i.stack.imgur.com/iojOc.png"><img src="http://i.stack.imgur.com/iojOc.png" alt="enter image description here"></a></p>
<p>But with <code>mean()</code> function the column <strong>Payment</strong> is now showing the average payment values John made and not the sum of all the payments. </p>
<p>How to create a DataFrame where Duration values show the average values while the Payment values show the sum?</p>
| 6 | 2016-09-03T17:14:09Z | 39,309,481 | <p>You can apply different functions to different columns with groupby.agg:</p>
<pre><code>df.groupby('Name').agg({'Duration': 'mean', 'Payment': 'sum'})
Out:
Payment Duration
Name
Alex 15 20
John 30 15
Will 15 30
</code></pre>
| 8 | 2016-09-03T17:19:47Z | [
"python",
"pandas",
"dataframe"
] |
Extracting text within frame tree in html | 39,309,488 | <p>I would like to scrape a frame within a website (<a href="https://www.harris.com/careers/jobs" rel="nofollow">https://www.harris.com/careers/jobs</a>). THe Xpath for the location for the first listed job position is </p>
<pre><code>/html/body/center/table[2]/tbody/tr/td/form/table[3]/tbody/tr[3]/td/table/tbody/tr[3]/td[4]/span
</code></pre>
<p>I am attempting to extract the text within the span using lxml library in Python. My code is currently as follows</p>
<pre><code>from lxml import html
import requests
page = requests.get('https://www.harris.com/careers/jobs')
tree = html.fromstring(page.content)
location = tree.xpath('/html/body/center/table[2]/tbody/tr/td/form/table[3]/tbody/tr[3]/td/table/tbody/tr[3]/td[4]/span/text()')
</code></pre>
<p>Unfortunately the command </p>
<pre><code>print(test)
</code></pre>
<p>yields the following</p>
<pre><code>[]
</code></pre>
<p>I'm quite sure theres something wrong with the Xpath and that it can be improved to extract the text i need. Any help would be appreciated. Thanks.</p>
| -1 | 2016-09-03T17:20:44Z | 39,344,273 | <p>Here I will give working code for that:</p>
<pre><code>from selenium.webdriver.common.keys import Keys
from selenium import webdriver
import time
driver=webdriver.Chrome('./chromedriver.exe')
try:
driver.get("https://www.harris.com/careers/jobs")
driver.switch_to.frame("frmJobs");
time.sleep(5)
#s = driver.find_element_by_id("searchbuttonBtn__a")
s = driver.find_element_by_xpath("//input[@class='submitbutton']")
driver.execute_script("return arguments[0].scrollIntoView();",s)
print s.get_attribute("value")
s.send_keys("\n")
time.sleep(10)
for a in driver.find_elements_by_xpath("//td[@class='listheadingbackground']/table/tbody/tr/td[2]/span/a"):
print a.get_attribute("href")
except Exception as e:
print e
driver.quit()
</code></pre>
| 0 | 2016-09-06T08:34:14Z | [
"python",
"xpath",
"web-scraping",
"lxml",
"python-3.5"
] |
How to access the same JSON file from both javascript and python? | 39,309,558 | <p>NOTE: This is not for web programming. We use javascript to interface with low level hardware, hence let's not go with jQuery APIs etc.</p>
<p>I have a javascript file that performs a sequence of actions on a device, and I have a python file that will be invoked later to validate these actions. There is a set of hardware information hard-coded in both javascript file and python file. I want to avoid this duplication of information by putting these info into a JSON file so both can access it.</p>
<pre><code>// Javascript
var hardware_info = JSON.parse(load('hardware.json'));
// load() is probably not standard javascript API, but it basically copies that code into the existing script.
</code></pre>
<p>Already failed by this step because '<code>hardware.json</code>' is not using javascript syntax...</p>
<p>I already validated the json using jshint/jslint, <code>hardware.json</code> looks like this:</p>
<pre><code>{
"hardware1": {
"ID": "xxx"
},
"hardware2": {
"ID": "yyy"
}
}
</code></pre>
<p>The following Python works well for accessing the json, there is not much to it:</p>
<pre><code>with open('hardware.json', 'r') as f:
data = json.load(f)
</code></pre>
| 2 | 2016-09-03T17:29:50Z | 39,309,697 | <p>It looks like <code>load()</code> <em>executes</em> the specified file, not read it and return the contents. If this is your <em>only</em> option to read another file, then I suggest you use <a href="https://en.wikipedia.org/wiki/JSONP" rel="nofollow">JSONP</a> instead of JSON.</p>
<p>JSONP works by adding a <em>callback</em> around the data. Instead of:</p>
<pre><code>{"key": "value"}
</code></pre>
<p>the file contains a function call with the data being passed in:</p>
<pre><code>callback({"key": "value"});
</code></pre>
<p>This is meant to be executed by a JavaScript engine, causing it to execute the callback. <code>load()</code> would execute your file, and the callback function would be called as a result, passing in the data.</p>
<p>When used on the web, you'd call a JSONP service and pass in the name of the callback the service should add, but when just sharing a configuration file between a JS engine and Python, you'd hardcode that callback name.</p>
<p>In Python, you'd have to strip off the callback text before loading it as JSON data. That could be as easy as just removing the first N and last M characters:</p>
<pre><code>with open('hardware.json', 'r') as f:
jsonp_data = f.read()
# remove first 9 and last 3 characters to remove JSONP callback
data = json.loads(jsonp_data[9:-3])
</code></pre>
<p>A little more sophisticated technique could use newlines:</p>
<pre><code>callback(
{"key": "value"}
);
</code></pre>
<p>to make it easier to remove the first and last line in Python. Or you could use <code>jsonp_data.partition('(')[-1].jsonp.rpartition(')')[0]</code> to take everything between the first <code>(</code> and the last <code>)</code> character in the string. Etc.</p>
| 2 | 2016-09-03T17:44:31Z | [
"javascript",
"python",
"json"
] |
How to get a name of Column or change the name of existing? | 39,309,615 | <p>I have a task to build a function "removePunctuation" that strips the punctuation and as result pass this test:</p>
<pre><code># TEST Capitalization and punctuation (4b)
testPunctDF = sqlContext.createDataFrame([(" The Elephant's 4 cats. ",)])
testPunctDF.show()
Test.assertEquals(testPunctDF.select(removePunctuation(col('_1'))).first()[0],
'the elephants 4 cats',
'incorrect definition for removePunctuation function')
</code></pre>
<p>This is what i managed to write. </p>
<pre><code>def removePunctuation(column):
"""Removes punctuation, changes to lower case, and strips leading and trailing spaces.
Note:
Only spaces, letters, and numbers should be retained. Other characters should should be
eliminated (e.g. it's becomes its). Leading and trailing spaces should be removed after
punctuation is removed.
Args:
column (Column): A Column containing a sentence.
Returns:
Column: A Column named 'sentence' with clean-up operations applied.
"""
return lower(trim(regexp_replace("column_name", "[\W_]+"," "))).alias("sentence");
</code></pre>
<p>But i still can not make function regexp_replace to use alias "sentence". I am getting this error:</p>
<blockquote>
<p>AnalysisException: u"cannot resolve 'sentence' given input columns:
[_1];"</p>
</blockquote>
| 1 | 2016-09-03T17:36:30Z | 39,309,732 | <p>I would try:</p>
<pre><code>stringWithPunctuation.translate(None, string.punctuation)
</code></pre>
<p>which uses <a href="/questions/tagged/c" class="post-tag" title="show questions tagged 'c'" rel="tag">c</a> under the hood, simply the best in terms of efficiency!</p>
<hr>
<p>Your attempt:</p>
<pre><code>return lower(trim(regexp_replace(, "[\W_]+"," "))).alias("sentence");
</code></pre>
<p>doesn't seem to use the parameter <code>column</code> anywhere, which may explain the error.</p>
| 2 | 2016-09-03T17:47:50Z | [
"python",
"string",
"apache-spark",
"distributed-computing",
"punctuation"
] |
How to get a name of Column or change the name of existing? | 39,309,615 | <p>I have a task to build a function "removePunctuation" that strips the punctuation and as result pass this test:</p>
<pre><code># TEST Capitalization and punctuation (4b)
testPunctDF = sqlContext.createDataFrame([(" The Elephant's 4 cats. ",)])
testPunctDF.show()
Test.assertEquals(testPunctDF.select(removePunctuation(col('_1'))).first()[0],
'the elephants 4 cats',
'incorrect definition for removePunctuation function')
</code></pre>
<p>This is what i managed to write. </p>
<pre><code>def removePunctuation(column):
"""Removes punctuation, changes to lower case, and strips leading and trailing spaces.
Note:
Only spaces, letters, and numbers should be retained. Other characters should should be
eliminated (e.g. it's becomes its). Leading and trailing spaces should be removed after
punctuation is removed.
Args:
column (Column): A Column containing a sentence.
Returns:
Column: A Column named 'sentence' with clean-up operations applied.
"""
return lower(trim(regexp_replace("column_name", "[\W_]+"," "))).alias("sentence");
</code></pre>
<p>But i still can not make function regexp_replace to use alias "sentence". I am getting this error:</p>
<blockquote>
<p>AnalysisException: u"cannot resolve 'sentence' given input columns:
[_1];"</p>
</blockquote>
| 1 | 2016-09-03T17:36:30Z | 39,309,742 | <p>Surprisingly I was able just to pass column object in <code>regexp_replace()</code> args instead of column name. </p>
| 1 | 2016-09-03T17:48:31Z | [
"python",
"string",
"apache-spark",
"distributed-computing",
"punctuation"
] |
How do I multithread SQL Queries in python such that I obtain the results of all of the queries | 39,309,714 | <p>Is there a way to use threads to simultaneously perform the SQL queries so I can cut down on processing time of my code below? Is there a better method to perform the same result as below without using the pandas module? Given the size of the data sets I am working with I cannot store the entire dataset in memory and I have found looping over the rows of a SELECT * FROM statement and comparing them against the list I am querying with adds to the processing time.</p>
<pre><code># DATABASE layout
# _____________________________________________________________
# | id | name | description |
# |_____________|____________________|__________________________|
# | 1 | John | Credit Analyst |
# | 2 | Jane | Doctor |
# | ... | ... | ... |
# | 5000000 | Mohammed | Dentist |
# |_____________|____________________|__________________________|
import sqlite3
SEARCH_IDS = [x for x in range(15000)]
DATABASE_NAME = 'db.db'
def chunks(wholeList, chunkSize=999):
"""Yield successive n-sized chunks from wholeList."""
for i in range(0, len(wholeList), chunkSize):
yield wholeList[i:i + chunkSize]
def search_database_for_matches(listOfIdsToMatch):
'''Takes a list of ids and returns the rows'''
conn = sqlite3.connect(DATABASE_NAME)
cursor = conn.cursor()
sql = "SELECT id, name, description FROM datatable WHERE id IN ({})".format(', '.join(["?" for x in listOfIdsToMatch]))
cursor.execute(sql,tuple(listOfIdsToMatch))
rows = cursor.fetchall()
return rows
def arrange(orderOnList,listToBeOrdered,defaultReturnValue='N/A'):
'''Takes a list of ids in the desired order and list of tuples which have ids as the first items.
the list of tuples is aranged into a new list corresponding to the order of the source list'''
from collections import OrderedDict
resultList=[defaultReturnValue for x in orderOnList]
indexLookUp = OrderedDict( [ ( value , key ) for key , value in enumerate( orderOnList ) ] )
for item in listToBeOrdered:
resultList[indexLookUp[item[0]]]=item
return resultList
def main():
results=[]
for chunk in chunks(SEARCH_IDS,999):
results += search_database_for_matches(chunk)
results = arrange(SEARCH_IDS,results)
print(results)
if __name__ == '__main__': main()
</code></pre>
| 0 | 2016-09-03T17:46:26Z | 39,310,039 | <p>Some advices:</p>
<p>Instead of reading the records by chucks using a iterator, you ought to use pagination. </p>
<p>See this questions:</p>
<ul>
<li><a href="http://stackoverflow.com/questions/14468586/efficient-paging-in-sqlite-with-millions-of-records">Efficient paging in SQLite with millions of records</a></li>
<li><a href="http://stackoverflow.com/questions/3325515/sqlite-limit-offset-query">Sqlite LIMIT / OFFSET query</a></li>
</ul>
<p>If you're using multithreading / multiprocessing make sure your database can support it.
See: <a href="https://www.sqlite.org/threadsafe.html" rel="nofollow">SQLite And Multiple Threads</a></p>
<p>To implement what you want you can use a pool of workers which work on each chunk. See <a href="https://docs.python.org/3/library/multiprocessing.html#using-a-pool-of-workers" rel="nofollow">Using a pool of workers</a> in the Python documentation. </p>
<p>Example:</p>
<pre><code>Import multiprocessing
with multiprocessing.pool.Pool(process = 4) as pool:
result = pool.map(search_database_for_match, [for chunk in chunks(SEARCH_IDS,999)])
</code></pre>
| 1 | 2016-09-03T18:18:35Z | [
"python",
"multithreading",
"sqlite3"
] |
PyCharm Edu introduction course, string multiplication | 39,309,791 | <p>I'm new to Python and currently running the "Introduction to Python" course for PyCharm Edu. I'm having a problem with the following task (strings -> string multiplication)</p>
<blockquote>
<p>Python supports a string-by-number multiplication (but not the other
way around!). </p>
<p>Use hello to get the
"hellohellohellohellohellohellohellohellohellohello" string ("hello"
repeated 10 times).</p>
</blockquote>
<p>The default given code is </p>
<pre><code>hello = "hello"
ten_of_hellos = hello operator 10
print(ten_of_hellos)
</code></pre>
<p>so I just replace the word operator with the * sign, so I have</p>
<pre><code>hello = "hello"
ten_of_hellos = hello * 10
print(ten_of_hellos)
</code></pre>
<p>but I get an error saying "use multiplication". Any idea of what I'm doing wrong?</p>
| 1 | 2016-09-03T17:53:04Z | 39,311,871 | <p>You are doing it right. They maybe are trying to teach you the difference between the string "hello" and The variable.</p>
| 0 | 2016-09-03T22:28:16Z | [
"python",
"pycharm"
] |
PyCharm Edu introduction course, string multiplication | 39,309,791 | <p>I'm new to Python and currently running the "Introduction to Python" course for PyCharm Edu. I'm having a problem with the following task (strings -> string multiplication)</p>
<blockquote>
<p>Python supports a string-by-number multiplication (but not the other
way around!). </p>
<p>Use hello to get the
"hellohellohellohellohellohellohellohellohellohello" string ("hello"
repeated 10 times).</p>
</blockquote>
<p>The default given code is </p>
<pre><code>hello = "hello"
ten_of_hellos = hello operator 10
print(ten_of_hellos)
</code></pre>
<p>so I just replace the word operator with the * sign, so I have</p>
<pre><code>hello = "hello"
ten_of_hellos = hello * 10
print(ten_of_hellos)
</code></pre>
<p>but I get an error saying "use multiplication". Any idea of what I'm doing wrong?</p>
| 1 | 2016-09-03T17:53:04Z | 39,333,904 | <p>If anyone else is completing the PyCharm Edu tutorial I noticed a problem with the string_multiplication exercise. When attempting to complete the solution an error messsage "Use multiplication" occurs. This is due to the source code of the PyCharm project. For anyone interested the solution is to go into you file system directory where the program is located:</p>
<p><a href="http://i.stack.imgur.com/IVss0.png" rel="nofollow"><img src="http://i.stack.imgur.com/IVss0.png" alt="enter image description here"></a></p>
<p>Open the .py file and insert the missing "else" (highlighted in gray):
<a href="http://i.stack.imgur.com/3ynHI.png" rel="nofollow"><img src="http://i.stack.imgur.com/3ynHI.png" alt="enter image description here"></a></p>
<p>Click the Check Task button in PyCharm Edu to see the solution is complete.</p>
<p>This was a solution found by GitHub user lbilger. <a href="https://github.com/JetBrains/pycharm-courses/pull/11/commits/32b4d3e9adc32e7b9c6a293e4c6e2bcc29b35210" rel="nofollow" title="Solution">Source</a></p>
| 5 | 2016-09-05T15:40:52Z | [
"python",
"pycharm"
] |
PyCharm Edu introduction course, string multiplication | 39,309,791 | <p>I'm new to Python and currently running the "Introduction to Python" course for PyCharm Edu. I'm having a problem with the following task (strings -> string multiplication)</p>
<blockquote>
<p>Python supports a string-by-number multiplication (but not the other
way around!). </p>
<p>Use hello to get the
"hellohellohellohellohellohellohellohellohellohello" string ("hello"
repeated 10 times).</p>
</blockquote>
<p>The default given code is </p>
<pre><code>hello = "hello"
ten_of_hellos = hello operator 10
print(ten_of_hellos)
</code></pre>
<p>so I just replace the word operator with the * sign, so I have</p>
<pre><code>hello = "hello"
ten_of_hellos = hello * 10
print(ten_of_hellos)
</code></pre>
<p>but I get an error saying "use multiplication". Any idea of what I'm doing wrong?</p>
| 1 | 2016-09-03T17:53:04Z | 39,629,930 | <p>There was a missing else in the code that was fixed Aug 13, 2016 (<a href="https://github.com/lbilger/pycharm-courses/commit/32b4d3e9adc32e7b9c6a293e4c6e2bcc29b35210" rel="nofollow">see commit on github</a>). However, the current Version: 2016.2.3 Released: September 6, 2016 is still missing the 'else' in the test.py file for lesson3, task2. </p>
<p>The easiest fix is to open the tests.py file in a text editor or IDE, copy and paste the updated code from <a href="https://github.com/lbilger/pycharm-courses/blob/32b4d3e9adc32e7b9c6a293e4c6e2bcc29b35210/introduction_course/lesson3/task2/tests.py" rel="nofollow">github</a>, save the file, then re-run the check. You shouldn't need to re-start PyCharm. When you re-run the checker, it should pass immediately. </p>
<p>If you have trouble locating the file on a PC. You can use your computers search tool to search ThisPC for PyCharmIntroduction. It will be in the same sub folder shown by the previous post: lesson3 -> task2 -> tests.py</p>
<p>Various answers will pass:</p>
<pre><code>hello = "hello"
ten_of_hellos = hello * 10
print(ten_of_hellos)
</code></pre>
<p>OR </p>
<pre><code>ten_of_hellos = "hello" * 10
print(ten_of_hellos)
</code></pre>
<p>OR even (not recommended but shown to demonstrate parameters to pass) </p>
<pre><code>ten_of_hellos = "hello" * 10
print("hellohellohellohellohellohellohellohellohellohello")
</code></pre>
| 0 | 2016-09-22T03:49:59Z | [
"python",
"pycharm"
] |
Number guessing game, unable to take the next guess | 39,309,804 | <p>Here is the concept of my game, the computer randomly generates a number from 1-100 and the player has to guess that number. If the number they guess is higher or lower the computer tells them so.</p>
<p>I added some code to make sure that the guess that the user enters is a number, but for some reason, it only works for their first guess. </p>
<pre><code>import random
x = random.randint(1, 100)
guess = input("Guess the number")
while guess.isnumeric() == True:
if x > int(guess):
print("Too low, guess again")
guess = input("Guess the number")
if x < int(guess):
print("Too high, guess again")
guess = input("Guess the number")
if x == int(guess):
print ("That is correct!")
break
if guess.isnumeric() == False:
print("Please enter a valid number")
guess = input("Guess the number")
</code></pre>
<p>I don't really know how to else to explain it. But for example, if I guess the number 20 as my first guess, it would output too high or too low depending on the randomly generated number, but after that, if I input a bunch of random letters it would give me an error that the guess could not be compared to the randomly generated number.</p>
| 1 | 2016-09-03T17:54:08Z | 39,309,841 | <p>You need to surround your guessing logic in another loop that continues until the guess is correct.</p>
<p>pseudocode:</p>
<pre><code>choose_target_answer
while player_has_not_guessed_answer
get_player_guess
if player_guess_is_valid
respond_to_player_guess
else
give_error_message
</code></pre>
| 1 | 2016-09-03T17:58:07Z | [
"python",
"random"
] |
Number guessing game, unable to take the next guess | 39,309,804 | <p>Here is the concept of my game, the computer randomly generates a number from 1-100 and the player has to guess that number. If the number they guess is higher or lower the computer tells them so.</p>
<p>I added some code to make sure that the guess that the user enters is a number, but for some reason, it only works for their first guess. </p>
<pre><code>import random
x = random.randint(1, 100)
guess = input("Guess the number")
while guess.isnumeric() == True:
if x > int(guess):
print("Too low, guess again")
guess = input("Guess the number")
if x < int(guess):
print("Too high, guess again")
guess = input("Guess the number")
if x == int(guess):
print ("That is correct!")
break
if guess.isnumeric() == False:
print("Please enter a valid number")
guess = input("Guess the number")
</code></pre>
<p>I don't really know how to else to explain it. But for example, if I guess the number 20 as my first guess, it would output too high or too low depending on the randomly generated number, but after that, if I input a bunch of random letters it would give me an error that the guess could not be compared to the randomly generated number.</p>
| 1 | 2016-09-03T17:54:08Z | 39,309,866 | <p>I've fixed your code for you. Try this:</p>
<pre><code>import random
x = random.randint(1, 100)
while True:
try:
guess = int(raw_input("Guess the number: "))
except ValueError:
print("Not a valid number, try again!")
continue
if guess < x:
print("Too low, guess again")
elif guess > x:
print("Too high, guess again")
elif x == guess:
print ("That is correct!")
break
</code></pre>
<p>You don't need to prompt the user for input after every guess, that's what the first input prompt is for. Because we are specifying <code>while True</code>, the user will get prompted to input a number every single time unless they enter the correct number, which in that case, we <code>break</code> the infinite loop.</p>
<p>Additionally, we can put the input statement in a <code>try</code> block, because we are casting the input as an integer right there. If the user enters a string, the program would otherwise fail if it tried to cast it as an integer, but if we <code>except ValueError:</code> and then <code>continue</code>, we will alert the user that their input is invalid, and then prompt them for input once again.</p>
| 2 | 2016-09-03T18:00:57Z | [
"python",
"random"
] |
Number guessing game, unable to take the next guess | 39,309,804 | <p>Here is the concept of my game, the computer randomly generates a number from 1-100 and the player has to guess that number. If the number they guess is higher or lower the computer tells them so.</p>
<p>I added some code to make sure that the guess that the user enters is a number, but for some reason, it only works for their first guess. </p>
<pre><code>import random
x = random.randint(1, 100)
guess = input("Guess the number")
while guess.isnumeric() == True:
if x > int(guess):
print("Too low, guess again")
guess = input("Guess the number")
if x < int(guess):
print("Too high, guess again")
guess = input("Guess the number")
if x == int(guess):
print ("That is correct!")
break
if guess.isnumeric() == False:
print("Please enter a valid number")
guess = input("Guess the number")
</code></pre>
<p>I don't really know how to else to explain it. But for example, if I guess the number 20 as my first guess, it would output too high or too low depending on the randomly generated number, but after that, if I input a bunch of random letters it would give me an error that the guess could not be compared to the randomly generated number.</p>
| 1 | 2016-09-03T17:54:08Z | 39,309,906 | <p>Your <code>if</code> statements are all independent:</p>
<pre><code>if x > int(guess):
print("Too low, guess again")
guess = input("Guess the number")
if x < int(guess):
print("Too high, guess again")
guess = input("Guess the number")
if x == int(guess):
print ("That is correct!")
break
</code></pre>
<p>The second and third <code>if</code> statements will <em>always</em> test <code>guess</code> again, even if the first <code>if</code> test matched. And if the first <code>if</code> test matched and you entered a non-numeric <code>guess</code> value, those two tests will fail as the <code>int()</code> call will throw a <code>ValueError</code> exception.</p>
<p>You could tell Python that the tests are interdependent by using <code>elif</code> and <code>else</code>; now Python will only execute the <em>first matching block</em>, and skip the others entirely:</p>
<pre><code>if x > int(guess):
print("Too low, guess again")
guess = input("Guess the number")
elif x < int(guess):
print("Too high, guess again")
guess = input("Guess the number")
else:
print ("That is correct!")
break
</code></pre>
<p>This means that execution continuous <em>after</em> the <code>else</code> block when either the <code>if</code> or <code>elif</code> tests matched.</p>
<p>Note that I used <code>else</code> at the end; if the number is neither too high nor too low, the number <em>must</em> be equal, there is no other option. There is no need to test for that explicitly.</p>
<p>You are now repeating yourself however. You are asking for a guess in 3 different places. You could ask <em>once</em> and let the loop take care of asking for a new value:</p>
<pre><code>while True:
while True:
guess = input("Guess the number:")
if guess.isnumeric():
break
print("Not a valid number, try again!")
guess = int(guess)
if x > guess:
print("Too low, guess again")
elif x < guess:
print("Too high, guess again")
else:
print ("That is correct!")
break
</code></pre>
<p>That's a lot less repetition already; a separate <code>while</code> loop asks for a number until it is actually numeric, and <code>guess</code> is converted to <code>int()</code> just once.</p>
<p>You could remove that nested <code>while True:</code> and just use the outer one here, the result would be the same, provided you use the <code>continue</code> keyword to skip the rest of the loop when you don't have a numeric value:</p>
<pre><code>while True:
guess = input("Guess the number:")
if not guess.isnumeric():
print("Not a valid number, try again!")
continue # skip to the top of the loop again, so ask again
guess = int(guess)
if x > guess:
print("Too low, guess again")
elif x < guess:
print("Too high, guess again")
else:
print ("That is correct!")
break
</code></pre>
| 2 | 2016-09-03T18:04:37Z | [
"python",
"random"
] |
ValueError: script argument must be unicode. - Python3.5, SQLite3 | 39,309,820 | <p>I'm writing following python script:</p>
<pre class="lang-py prettyprint-override"><code>import sqlite3
import sys
if len(sys.argv) < 2:
print("Error: You must supply at least SQL script.")
print("Usage: %s table.db ./sql-dump.sql" % (sys.argv[0]))
sys.exit(1)
script_path = sys.argv[1]
if len(sys.argv) == 3:
db = sys.argv[2]
else:
db = ":memory:"
try:
con = sqlite3.connect(db)
with con:
cur = con.cursor()
with open(script_path,'rb') as f:
cur.executescript(f.read())
except sqlite3.Error as err:
print("Error occured: %s" % err)
</code></pre>
<p>I saved this program as <strong>sqlite_import.py</strong>.
I have a database file named <strong>test.db</strong> and a SQL file <strong>world.sql</strong>.
Now I tried to run program as:</p>
<pre class="lang-py prettyprint-override"><code>sqlite_import.py test.db world.sql
</code></pre>
<p>But it shows me error like following:</p>
<pre class="lang-py prettyprint-override"><code>Traceback (most recent call last):
File "C:\Users\Jarvis\OneDrive\Documents\Python\Python Data Visualization Cookbook, 2E\2 Knowing Your Data\sqlite_import.py", line 21, in <module>
cur.executescript(f.read())
ValueError: script argument must be unicode.
</code></pre>
<p>Help me to fix this.</p>
| 0 | 2016-09-03T17:55:47Z | 39,309,873 | <p>You opened the script file as <em>binary</em>:</p>
<pre><code>with open(script_path,'rb') as f:
</code></pre>
<p>This produces a <code>b'...'</code> bytes value, not a Unicode <code>str</code> object. Remove the <code>b</code>, and perhaps add an <code>encoding</code> argument to specific what codec to use to decode the data with.</p>
| 0 | 2016-09-03T18:01:46Z | [
"python",
"unicode",
"sqlite3"
] |
Is assigning a,b = c,a the same as b,a = a,c? | 39,309,928 | <p>Is assigning </p>
<pre><code>a,b = c,a
</code></pre>
<p>the same as </p>
<pre><code>b,a = a,c
</code></pre>
<p>It seems to be the same for the simple case where <code>a</code>, <code>b</code>, and <code>c</code> are numbers.</p>
<p>Is there a case where this fails?</p>
| 1 | 2016-09-03T18:06:28Z | 39,309,959 | <p>No, there is no case where this fails. The two statements are exactly equivalent, because <code>a</code> and <code>b</code> are <em>independent</em>.</p>
<p>That's because the right-hand side values are put on the stack <em>first</em> before assignment takes place (from left to right). Assigning to <code>a</code> before <code>b</code> makes no difference, because <code>a</code> and <code>b</code> are entirely different names, and assignment to either one first won't affect the other.</p>
<p>So the first statement:</p>
<pre><code>a,b = c,a
</code></pre>
<p>is executed as (psuedo-bytecode<sup>*</sup>)</p>
<pre><code>PUSH C ON STACK
PUSH A ON STACK
SWAP TOP TWO VALUES OF STACK
POP TOP OF STACK, STORE IN A
POP TOP OF STACK, STORE IN B
</code></pre>
<p>while the second</p>
<pre><code>b,a = a,c
</code></pre>
<p>is executed as</p>
<pre><code>PUSH A ON STACK
PUSH C ON STACK
SWAP TOP TWO VALUES OF STACK
POP TOP OF STACK, STORE IN B
POP TOP OF STACK, STORE IN A
</code></pre>
<p>It doesn't matter what type the values referenced by <code>a</code>, <code>b</code> or <code>c</code> are.</p>
<p>Things can get more confusing if you were to <a href="https://stackoverflow.com/questions/13657704/simple-assignment-operator-become-complicated-in-python">chain assignments</a> and / or <a href="https://stackoverflow.com/questions/32127908/python-assignment-operator-precedence-a-b-ab-5">mix in subscriptions</a>. In all those cases the names being assigned to are not independent, and people usually don't realise that all assignment takes place <em>after</em> the right-hand side expression has been executed and that assignment takes place from left to right after that.</p>
<hr>
<p><sup>*</sup> See <a href="https://stackoverflow.com/questions/21047524/how-does-swapping-of-members-in-the-python-tuples-a-b-b-a-work-internally">How does swapping of members in the python tuples (a,b)=(b,a) work internally?</a> for actual bytecode examples.</p>
| 5 | 2016-09-03T18:10:02Z | [
"python",
"python-2.7"
] |
Is assigning a,b = c,a the same as b,a = a,c? | 39,309,928 | <p>Is assigning </p>
<pre><code>a,b = c,a
</code></pre>
<p>the same as </p>
<pre><code>b,a = a,c
</code></pre>
<p>It seems to be the same for the simple case where <code>a</code>, <code>b</code>, and <code>c</code> are numbers.</p>
<p>Is there a case where this fails?</p>
| 1 | 2016-09-03T18:06:28Z | 39,309,961 | <p>It's the same in all cases, no matter what you're working with. So long as statements are equivalent (like yours are), the result will be the same.</p>
| 1 | 2016-09-03T18:10:14Z | [
"python",
"python-2.7"
] |
Is assigning a,b = c,a the same as b,a = a,c? | 39,309,928 | <p>Is assigning </p>
<pre><code>a,b = c,a
</code></pre>
<p>the same as </p>
<pre><code>b,a = a,c
</code></pre>
<p>It seems to be the same for the simple case where <code>a</code>, <code>b</code>, and <code>c</code> are numbers.</p>
<p>Is there a case where this fails?</p>
| 1 | 2016-09-03T18:06:28Z | 39,309,974 | <p>Short Answer ----- "Yes"..
a,b = c,a means a=c and b=a ...
b,a = a,c means b=a and a=c</p>
| 0 | 2016-09-03T18:11:38Z | [
"python",
"python-2.7"
] |
(PyQT) How can I make sure values in all following spinboxes are higher than the last | 39,309,929 | <p>The following is an example of inputs that could potentially be added.</p>
<p>value 0: [ 0 ] [ 100 ]
<br>value 1: [ 200 ] [ 300 ]
<br>value 2: [ 400 ] [ 500 ]</p>
<p>The above is correct</p>
<p>value 0: [ 0 ] [ 800 ]
<br>value 1: [ 700 ] [ 600 ]
<br>value 2: [ 500 ] [ 400 ]</p>
<p>The above is incorrect: Make sure each value is higher than the last</p>
<p>The code below has each value that the user inputs added to an array. </p>
<pre><code>def val_norm(self, MainWindow, count):
self.verticalLayout_2 = QtGui.QVBoxLayout()
self.verticalLayout_2.setMargin(11)
self.verticalLayout_2.setSpacing(6)
self.verticalLayout_2.setObjectName(_fromUtf8("verticalLayout_2"))
self.horizontalLayout_2 = QtGui.QHBoxLayout()
self.horizontalLayout_2.setMargin(11)
self.horizontalLayout_2.setSpacing(6)
self.horizontalLayout_2.setObjectName(_fromUtf8("horizontalLayout_2"))
self.norm_label = QtGui.QLabel(self.Normalization)
self.norm_label.setObjectName(_fromUtf8("norm_label"))
self.horizontalLayout_2.addWidget(self.norm_label)
self.norm_spinBox_[(count*2)-1] = QtGui.QSpinBox(self.Normalization) # All the left side boxes
self.norm_spinBox_[(count*2)] = QtGui.QSpinBox(self.Normalization) # All the right side boxes
self.norm_spinBox_[(count*2)-1].setMaximum(1000) # set the maximums for the left side
self.norm_spinBox_[(count*2)].setMaximum(1000) # set the maximums for the right side
self.horizontalLayout_2.addWidget(self.norm_spinBox_[(count*2)-1]) # adding the actual object to UI (left)
self.horizontalLayout_2.addWidget(self.norm_spinBox_[(count*2)]) # adding the actual object to UI (right)
self.verticalLayout_2.addLayout(self.horizontalLayout_2) # setting up layout
self.verticalLayout.addLayout(self.verticalLayout_2) # setting up layout
# for debugging purposes
self.norm_spinBox_[(count*2)-1].editingFinished.connect(lambda: print(self.norm_spinBox_[(count*2)-1].text()))
self.norm_spinBox_[(count*2)].editingFinished.connect(lambda: print(self.norm_spinBox_[(count*2)].text()))
self.norm_label.setText(_translate("MainWindow", "Value {}".format(self.count), None))
self.count += 1
if self.norm_spinBox_[(count*2)-1].text() > self.norm_spinBox_[count*2].text():
print("That's wrong!")
</code></pre>
<p>I thought that using an if statement would work, but I'm clearly misguided on how I should be approaching this. Correct me if I'm wrong, but I'm thinking it's not working because I'm not connecting the if statement to each box after it's been edited. </p>
<pre><code>if self.norm_spinBox_[(count*2)-1].text() > self.norm_spinBox_[count*2].text():
print("That's wrong!")
</code></pre>
| 0 | 2016-09-03T18:06:34Z | 39,315,901 | <p>you could use the <code>valueChanged()</code> signal of <code>QSpinBox</code> to <code>setMinimum()</code> of the following spinboxes according to the value of the former spinbox, so the spinboxes only accept values >= minimum, here a working example:</p>
<pre><code>import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class SpinboxWidget(QWidget):
def __init__(self, parent=None):
QWidget.__init__(self, parent)
self.layout = QVBoxLayout()
# self.signalMapper = QSignalMapper(self)
# self.signalMapper.mapped[str].connect(self.setspbMin)
self.addSpinboxes(10) # add an arbitrary number of spinboxes
self.setLayout(self.layout)
def addSpinboxes(self, n):
spb = []
for i in range(n):
# objectname = 'spinbox_{}'.format(i)
spinbox = QSpinBox()
# spinbox.setObjectName(objectname) # to identify the spinbox later
spinbox.setMaximum(100)
# spinbox.valueChanged.connect(self.signalMapper.map)
# self.signalMapper.setMapping(spinbox, objectname) # sends the objectname with his mapped() signal
spb.append(spinbox) # added in edit
self.layout.addWidget(spinbox)
for i in range(n-1):
spb[i].valueChanged.connect(spb[i + 1].setMinimum)
'''
def setspbMin(self, identifier):
spinbox = self.findChild(QSpinBox,identifier) # don't use QObject.sender() see Documentation
nextIndex = int(identifier.lstrip('spinbox_')) + 1
nextIdentifier = 'spinbox_{}'.format(nextIndex)
nextSpinbox = self.findChild(QSpinBox,nextIdentifier)
try:
nextSpinbox.setMinimum(spinbox.value())
except AttributeError:
pass
'''
if __name__ == '__main__':
app = QApplication(sys.argv)
app.setStyle('plastique')
widget = SpinboxWidget()
widget.setWindowTitle('Spinbox Tester')
widget.show()
sys.exit(app.exec_())
</code></pre>
<p><strong>edit:</strong>
as suggested by ekhumoro signalMapper is not necessary -> outcommented lines are no longer needed. the <code>valueChanged</code>-signal is connected to <code>setMinimum()</code> of the following spinbox. </p>
| 2 | 2016-09-04T10:21:56Z | [
"python",
"pyqt"
] |
What I sure method I used to authenticate in webpy? | 39,309,937 | <p>Hello I have an application on my localhost, the application is made with webpy, this application is an administration panel, cpanel style, I can only access because it is running on 127.0.0.1</p>
<p>Now I would like to use it on my public server.</p>
<p>But you need a very secure method of authentication with webpy.</p>
<p>Would use 3 friends and I would then be four to eight users.</p>
<p>How to accomplish this? Can you make a certificate-based method?</p>
<p>o could be stored in blowfish passwords?</p>
<p>I think that as few users are is not necessarily a complex database, perhaps sqlite is enough.</p>
<p>Thank you</p>
| 0 | 2016-09-03T18:07:54Z | 39,314,255 | <ul>
<li><p>To use SSL: Add the following lines to the the web.py main file.</p>
<p><code>from web.wsgiserver import CherryPyWSGIServer
CherryPyWSGIServer.ssl_certificate = "/path/to/ssl_certificate" CherryPyWSGIServer.ssl_private_key = "/path/to/ssl_private_key"</code></p>
<p>which allows you to use https, it sets SSL support in built-in cherrypy server web.py. Refer <a href="http://webpy.org/cookbook/ssl" rel="nofollow">this</a>.</p></li>
<li><p>To use SQLite use the <a href="http://webpy.readthedocs.io/en/latest/db.html" rel="nofollow">interface</a> given by web.py using sqlite3<br>
library.</p>
<p><code>db = web.database(dbn="sqlite", db="dbname")</code></p></li>
<li><p>You can use <a href="http://webpy.org/cookbook/userauthbasic" rel="nofollow">basic authentication</a> provided by web.py if needed.</p></li>
<li><p>Either you can directly run your web.py application in the server
using: (This limits the concurrent requests to 10)</p>
<p><code>python code.py</code></p>
<p>or you can use Fastcgi deployment through lighttpd is what web.py has recommended for production use. Refer <a href="http://webpy.org/install" rel="nofollow">this</a>.</p></li>
</ul>
| 0 | 2016-09-04T06:44:03Z | [
"python",
"security",
"web.py"
] |
Does particular string match strings in text file | 39,310,010 | <p>I have a text file containing many words (single word on each line). I have to read in each word, modify the words, and then check if the modified word matches any of the words in the file. I am having trouble with the last part (it is the hasMatch method in my code). It sounds simple enough and I know what I should do, but whatever I try does not work.</p>
<pre><code>#read in textfile
myFile = open('good_words.txt')
#function to remove first and last character in string, and reverse string
def modifyString(str):
rmFirstLast = str[1:len(str)-2] #slicing first and last char
reverseStr = rmFirstLast[::-1] #reverse string
return reverseStr
#go through list of words to determine if any string match modified string
def hasMatch(modifiedStr):
for line in myFile:
if line == modifiedStr:
print(modifiedStr + " found")
else:
print(modifiedStr + "not found")
for line in myFile:
word = str(line) #save string in line to a variable
#only modify strings that are greater than length 3
if len(word) >= 4:
#global modifiedStr #make variable global
modifiedStr = modifyString(word) #do string modification
hasMatch(modifiedStr)
myFile.close()
</code></pre>
| -1 | 2016-09-03T18:15:21Z | 39,310,053 | <p>Several problems here</p>
<ol>
<li>you have to strip the lines or you get linefeed/CR chars that fail the match</li>
<li>you have to read the file once and for all or the file iterator runs out after the first time</li>
<li>the speed is bad: sped up for the search using a <code>set</code> instead of a <code>list</code></li>
<li>the slicing is overly complicated and wrong: <code>str[1:-1]</code> does it (thanks to those who commented my answer)</li>
<li>The whole code is really to long & complex. I summed it up in a few lines.</li>
</ol>
<p>code:</p>
<pre><code>#read in textfile
myFile = open('good_words.txt')
# make a set (faster search), remove linefeeds
lines = set(x.strip() for x in myFile)
myFile.close()
# iterate on the lines
for word in lines:
#only consider strings that are greater than length 3
if len(word) >= 4:
modifiedStr = word[1:-1][::-1] #do string modification
if modifiedStr in lines:
print(modifiedStr + " found (was "+word+")")
else:
print(modifiedStr + " not found")
</code></pre>
<p>I tested the program on a list of common english words and I got those matches:</p>
<pre><code>so found (was most)
or found (was from)
no found (was long)
on found (was know)
to found (was both)
</code></pre>
<p>Edit: another version which drops the <code>set</code> and uses <code>bisect</code> on the sorted list to avoid hashing/hash collisions.</p>
<pre><code>import os,bisect
#read in textfile
myFile = open("good_words.txt"))
lines = sorted(x.strip() for x in myFile) # make a sorted list, remove linefeeds
myFile.close()
result=[]
for word in lines:
#only modify strings that are greater than length 3
if len(word) >= 4:
modifiedStr = word[1:-1][::-1] #do string modification
# search where to insert the modified word
i=bisect.bisect_left(lines,modifiedStr)
# if can be inserted and word is actually at this position: found
if i<len(lines) and lines[i]==modifiedStr:
print(modifiedStr + " found (was "+word+")")
else:
print(modifiedStr + " not found")
</code></pre>
| 2 | 2016-09-03T18:19:46Z | [
"python",
"string",
"python-2.7"
] |
Does particular string match strings in text file | 39,310,010 | <p>I have a text file containing many words (single word on each line). I have to read in each word, modify the words, and then check if the modified word matches any of the words in the file. I am having trouble with the last part (it is the hasMatch method in my code). It sounds simple enough and I know what I should do, but whatever I try does not work.</p>
<pre><code>#read in textfile
myFile = open('good_words.txt')
#function to remove first and last character in string, and reverse string
def modifyString(str):
rmFirstLast = str[1:len(str)-2] #slicing first and last char
reverseStr = rmFirstLast[::-1] #reverse string
return reverseStr
#go through list of words to determine if any string match modified string
def hasMatch(modifiedStr):
for line in myFile:
if line == modifiedStr:
print(modifiedStr + " found")
else:
print(modifiedStr + "not found")
for line in myFile:
word = str(line) #save string in line to a variable
#only modify strings that are greater than length 3
if len(word) >= 4:
#global modifiedStr #make variable global
modifiedStr = modifyString(word) #do string modification
hasMatch(modifiedStr)
myFile.close()
</code></pre>
| -1 | 2016-09-03T18:15:21Z | 39,310,086 | <p>In your code, you're not slicing just the first and last character but the first and last two characters.</p>
<pre><code>rmFirstLast = str[1:len(str)-2]
</code></pre>
<p>Change that to:</p>
<pre><code>rmFirstLast = str[1:len(str)-1]
</code></pre>
| 0 | 2016-09-03T18:23:57Z | [
"python",
"string",
"python-2.7"
] |
how to match items between 2 different lists | 39,310,062 | <p>I have 2 different lists:</p>
<pre><code>['2', '1']
['equals', 'x']
</code></pre>
<p>I want to match the items so 2 = "equals" and 1 = "x" in order to recreate the original sentence "x equals x", also i have a third list which is:</p>
<pre><code>['1', '2', '1']
</code></pre>
<p>I need the third list to recreate the original sentence since it has all the positions, to do this I thought of making the numbers equal to the words such as 1 = "x" and printing the list of numbers in order to have the full sentence. The problem is i do not know how to make the numbers equal to the words. Thanks for the help in advance</p>
| 0 | 2016-09-03T18:20:35Z | 39,310,093 | <p>A dictionary might be what you need here which maps keys to values. You can create a dictionary from the first two lists by zipping them. And with this dictionary, it should be fairly straight forward to map any list of numbers to words:</p>
<pre><code>mapping = dict(zip(['2', '1'], ['equals', 'x']))
mapping
# {'1': 'x', '2': 'equals'}
[mapping.get(num) for num in ['1', '2', '1']]
# ['x', 'equals', 'x']
</code></pre>
<p>To make the list a sentence, use <code>join</code> method:</p>
<pre><code>" ".join(mapping.get(num) for num in ['1', '2', '1'])
# 'x equals x'
</code></pre>
| 1 | 2016-09-03T18:24:39Z | [
"python",
"list",
"python-2.7",
"python-3.x"
] |
Unexpected output from "mimic" function exercise from Google Python Class | 39,310,164 | <p>First of all, apologies if some stupid error lies ahead: I have just started to ("re")learn Python (I am using Python 2.7).</p>
<p>I have completed one exercise from the Google Python Class, called "mimic", but I'm sometimes getting some strange results and I would like to understand why this is happening.</p>
<p>The exercise asks the following things:</p>
<p>1) Read in the file specified on the command line.</p>
<p>2) Build a "mimic" dict that maps each word that appears in the file to a list of all the words that immediately follow that word in the file. The list of words can be be in any order and should include duplicates. So for example the key "and" might have the list ["then", "best", "then", "after", ...] listing all the words which came after "and" in the text. We'll say that the empty string is what comes before the first word in the file.</p>
<p>3) With the mimic dict, it's fairly easy to emit random text that mimics the original. Print a word, then look up what words might come next and pick one at random as the next work. Use the empty string as the first word to prime things.
If we ever get stuck with a word that is not in the dict, go back to the empty string to keep things moving.</p>
<p>This is my code:</p>
<pre><code>import random
import sys
def mimic_dict(filename):
"""Returns mimic dict mapping each word to list of words which follow it."""
d = {}
with open(filename) as f:
text = f.read()
words = text.split()
i = 0
for i in range(len(words) - 1):
if words[i] not in d:
d[words[i]] = [words[i + 1]]
else:
d[words[i]].append(words[i+1])
i += 1
d[''] = words[0]
return d
def print_mimic(d, word):
"""Given mimic dict and start word, prints 200 random words."""
mimic_text = []
while len(mimic_text) < 200:
if word in d:
next_word = random.choice(d[word])
mimic_text.append(next_word)
word = next_word
else:
word = ''
print ' '.join(mimic_text)
# Provided main(), calls mimic_dict() and mimic()
def main():
if len(sys.argv) != 2:
print 'usage: ./mimic.py file-to-read'
sys.exit(1)
dict = mimic_dict(sys.argv[1])
print_mimic(dict, '')
if __name__ == '__main__':
main()
</code></pre>
<p>Now, the problem is that if I feed this mimic function with a very simple text file, <a href="https://www.dropbox.com/s/kanodc7q74kj05i/small.txt?dl=0" rel="nofollow">small.txt</a>, which contains this:</p>
<pre><code>We are not what we should be
We are not what we need to be
But at least we are not what we used to be
-- Football Coach
</code></pre>
<p>the output looks like this:</p>
<pre><code>e W e W W W W W e e e e e W e W [...]
</code></pre>
<p>That is, a random sequence of the letters of the first word.</p>
<p>But, if I run it on a much longer file (<a href="https://www.dropbox.com/s/hwajarrejovpz77/alice.txt?dl=0" rel="nofollow">alice.txt</a>, that contains the whole text from Alice in Wonderland), I get some random letters at the beginning (and sometimes not even those letters), but then somehow it works, here are some examples:</p>
<p>Run 1 output (truncated):</p>
<pre><code>l i ' s l e ' ' i ' e s e c s ' A large flower-pot that the next[...]
</code></pre>
<p>Run 2 output (truncated):</p>
<pre><code>i i i A little door, staring at all,' said in fact, [...]
</code></pre>
<p>Run 3 output (truncated):</p>
<pre><code> A Caucus-Race and she found out of Hearts,[...]
</code></pre>
<p>It seems that once it gets to the letter "A" it starts working as expected, but I really can't understand what's going on before getting to that letter.
I am sure there is just a stupid bug somewhere, but I can't find it, and I would be really thankful if some gentle soul could take some time to help me understand what's going on here.</p>
<p>Thank you very much!</p>
| 0 | 2016-09-03T18:34:25Z | 39,310,369 | <p>You missed two characters.</p>
<p><code>d[''] = words[0]</code> should be <code>d[''] = [words[0]]</code>.</p>
| 1 | 2016-09-03T19:00:29Z | [
"python",
"python-2.7"
] |
Peewee - Update an entry with a dictionary | 39,310,191 | <p>I found <a href="https://stackoverflow.com/questions/22750439/peewee-how-to-convert-a-dict-into-a-model">this handy answer</a> on how to <strong>create</strong> a new table entry using a dictionary.</p>
<p>Now i'd like to <strong>update</strong> an entry with the same method. but i don't know how to adress the specific table entry that i'd like to update. </p>
<p>My current version looks like this:</p>
<pre><code>entries = Fruit.select().order_by(Fruit.name.desc())
#... all entries are listed with the index number
entry_index = int(input("Please enter entry number: "))
#...
entry_index -= 1
name = "Banana"
color = "yellow"
if input('Update entry? [Yn] ').lower() != 'n':
entries[entry_index].name = name
entries[entry_index].color = color
</code></pre>
<p>As you can see i adress every field explicitly.
I would like to put the variables (name, color) in a dictionary and update the entry at position "entry_index" with the fore-mentioned double-star-shortcut <a href="https://stackoverflow.com/questions/22750439/peewee-how-to-convert-a-dict-into-a-model">like in this answer</a>.
But i can't find a <a href="http://docs.peewee-orm.com/en/latest/peewee/querying.html#updating-existing-records" rel="nofollow">proper method in the docs</a>. </p>
<p>Does anyone know how to accomplish that?</p>
<p>Thanks for your help!</p>
<p>Muff</p>
| 1 | 2016-09-03T18:38:22Z | 39,311,315 | <p>The double star shortcut is a python thing. It allows you to expand a dictionary into key-word arguments in a method. That means you can do something like this:</p>
<pre><code>fruit = { "name": "Banana", "color": "yellow"}
some_method(**fruit)
</code></pre>
<p>which would be the equivelent of doing:</p>
<pre><code>some_method(name="Banana", color="yellow")
</code></pre>
<p>I don't think that's helpful to you here though. You've already updated the values on the selected entry and all you need to do next is save them.</p>
<p><a href="http://docs.peewee-orm.com/en/latest/peewee/querying.html#updating-existing-records" rel="nofollow">According to the peewee docs</a>, once you have created an instance, any calls to save will cause that instance to be updated. That means you only need to call the <code>save</code> method to update the values you've changed. If you add a final <code>entries[entry_index].save()</code>, that should persist those changes.</p>
| 1 | 2016-09-03T21:04:51Z | [
"python",
"dictionary",
"peewee"
] |
Peewee - Update an entry with a dictionary | 39,310,191 | <p>I found <a href="https://stackoverflow.com/questions/22750439/peewee-how-to-convert-a-dict-into-a-model">this handy answer</a> on how to <strong>create</strong> a new table entry using a dictionary.</p>
<p>Now i'd like to <strong>update</strong> an entry with the same method. but i don't know how to adress the specific table entry that i'd like to update. </p>
<p>My current version looks like this:</p>
<pre><code>entries = Fruit.select().order_by(Fruit.name.desc())
#... all entries are listed with the index number
entry_index = int(input("Please enter entry number: "))
#...
entry_index -= 1
name = "Banana"
color = "yellow"
if input('Update entry? [Yn] ').lower() != 'n':
entries[entry_index].name = name
entries[entry_index].color = color
</code></pre>
<p>As you can see i adress every field explicitly.
I would like to put the variables (name, color) in a dictionary and update the entry at position "entry_index" with the fore-mentioned double-star-shortcut <a href="https://stackoverflow.com/questions/22750439/peewee-how-to-convert-a-dict-into-a-model">like in this answer</a>.
But i can't find a <a href="http://docs.peewee-orm.com/en/latest/peewee/querying.html#updating-existing-records" rel="nofollow">proper method in the docs</a>. </p>
<p>Does anyone know how to accomplish that?</p>
<p>Thanks for your help!</p>
<p>Muff</p>
| 1 | 2016-09-03T18:38:22Z | 39,319,387 | <p>To update an object, you can:</p>
<pre><code>entry = entries_index[idx]
entry.something = 'new value'
entry.another_thing = 'another thing'
entry.save()
</code></pre>
<p>Alternatively:</p>
<pre><code>Entry.update(**{'something': 'new value', 'another_thing': 'another'}).where(Entry.id == entry.id).execute()
</code></pre>
<p>All of this is covered in the docs, please give them a thorough read. Follow the quick-start step by step and I think you will have a clearer idea of how to use peewee.</p>
| 1 | 2016-09-04T17:00:50Z | [
"python",
"dictionary",
"peewee"
] |
Entering Data in tkinter frames | 39,310,212 | <p>I'm writing a program to keep the score of a 14-1 billiard(pool) match. Since I needed multiple windows I used tkinter frames. The frames for 2 pages work with out difficulty. My problem is entering data. The first item to be entered in each players name. Both text boxes appear on the screen, and data can be entered. If I try to display the data after entering it I get nothing. I have been working on this for days. And I sure someone can look at it, and say hey knuckle head you did do this right. Would appropriate some help. </p>
<pre><code>import tkinter as tk
from tkinter import *
TITLE_FONT = ("Helvetica", 18, "bold")
TITLE_FONT_LINE2 = ("Helvetica", 14, "bold")
class SampleApp(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
# the container is where we'll stack a bunch of frames
# on top of each other, then the one we want visible
# will be raised above the others
container = tk.Frame(self)
container.pack(side="top", fill="both", expand=True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self.frames = {}
for F in (StartPage, PageOne, PageTwo):
page_name = F.__name__
frame = F(parent=container, controller=self)
self.frames[page_name] = frame
# put all of the pages in the same location;
# the one on the top of the stacking order
# will be the one that is visible.
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame("StartPage")
def show_frame(self, page_name):
'''Show a frame for the given page name'''
frame = self.frames[page_name]
frame.tkraise()
class StartPage(tk.Frame):
def __init__(self, parent, controller):
player1 = StringVar()
player2 = StringVar()
game_balls = IntVar()
tk.Frame.__init__(self, parent)
self.controller = controller
self.configure(background='green')
self.controller.title('Billard Score Keeping')
label1 = tk.Label(self,text="This Program is for Scoring 14-1 Straight Pool", font=TITLE_FONT, bg = 'green')
label1.pack()
label = tk.Label(self, text="Championship 14-1 Match is 150 Balls", font=TITLE_FONT_LINE2, bg = 'green')
label.pack()
label2 = tk.Label(self,text="Player One Name ", font=TITLE_FONT_LINE2, bg = 'green').place(x=45,y=70)
label3 = tk.Label(self,text='Player Two Name', font=TITLE_FONT_LINE2, bg = 'green').place(x=445,y=70)
label4 = tk.Label(self,text='Enter Number of Balls in Match', font=TITLE_FONT_LINE2, bg = 'green').place(x=185,y=110)
# Here is where I'm Having difficulty:
self.entry = tk.Entry(self, text=player1, width=7, font=TITLE_FONT_LINE2).place(x=60,y=100)
self.entry = tk.Entry(self,text=player2, width=7, font=TITLE_FONT_LINE2).place(x=480,y=100)
self.entry = tk.Entry(self,text=game_balls, width=4, font=TITLE_FONT_LINE2).place(x=275,y=140)
button1 = tk.Button(self, text="Go to Page One",
command=lambda: controller.show_frame("PageOne"))
button2 = tk.Button(self, text="Go to Page Two",
command=lambda: controller.show_frame("PageTwo"))
button1.place(x=275,y=440)
button2.place(x=275,y=540)
class PageOne(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
self.controller.geometry('615x615+415+190')
label = tk.Label(self, text="This is page 1", font=TITLE_FONT)
label.pack(side="top", fill="x", pady=10)
button = tk.Button(self, text="Go to the start page",
command=lambda: controller.show_frame("StartPage"))
button.pack()
class PageTwo(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(self, text="This is page 2", font=TITLE_FONT)
label.pack(side="top", fill="x", pady=10)
button = tk.Button(self, text="Go to the start page",
command=lambda: controller.show_frame("StartPage"))
button.pack()
if __name__ == "__main__":
app = SampleApp()
app.mainloop()
</code></pre>
| 0 | 2016-09-03T18:40:12Z | 39,310,371 | <p>Your code and your post is so messy.
About your problem: I refer you to use GET method, from each entry box take data with using GET method, next ascribe it into a variable, it's simplest way to take a data from entry box. In applications like yours, I make button near entry box, and in command attribute I do something like this</p>
<pre><code>bttn = Button(self, text='enter', command=self.txt_box.get(0, END))
</code></pre>
| -1 | 2016-09-03T19:00:30Z | [
"python",
"tkinter"
] |
Entering Data in tkinter frames | 39,310,212 | <p>I'm writing a program to keep the score of a 14-1 billiard(pool) match. Since I needed multiple windows I used tkinter frames. The frames for 2 pages work with out difficulty. My problem is entering data. The first item to be entered in each players name. Both text boxes appear on the screen, and data can be entered. If I try to display the data after entering it I get nothing. I have been working on this for days. And I sure someone can look at it, and say hey knuckle head you did do this right. Would appropriate some help. </p>
<pre><code>import tkinter as tk
from tkinter import *
TITLE_FONT = ("Helvetica", 18, "bold")
TITLE_FONT_LINE2 = ("Helvetica", 14, "bold")
class SampleApp(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
# the container is where we'll stack a bunch of frames
# on top of each other, then the one we want visible
# will be raised above the others
container = tk.Frame(self)
container.pack(side="top", fill="both", expand=True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self.frames = {}
for F in (StartPage, PageOne, PageTwo):
page_name = F.__name__
frame = F(parent=container, controller=self)
self.frames[page_name] = frame
# put all of the pages in the same location;
# the one on the top of the stacking order
# will be the one that is visible.
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame("StartPage")
def show_frame(self, page_name):
'''Show a frame for the given page name'''
frame = self.frames[page_name]
frame.tkraise()
class StartPage(tk.Frame):
def __init__(self, parent, controller):
player1 = StringVar()
player2 = StringVar()
game_balls = IntVar()
tk.Frame.__init__(self, parent)
self.controller = controller
self.configure(background='green')
self.controller.title('Billard Score Keeping')
label1 = tk.Label(self,text="This Program is for Scoring 14-1 Straight Pool", font=TITLE_FONT, bg = 'green')
label1.pack()
label = tk.Label(self, text="Championship 14-1 Match is 150 Balls", font=TITLE_FONT_LINE2, bg = 'green')
label.pack()
label2 = tk.Label(self,text="Player One Name ", font=TITLE_FONT_LINE2, bg = 'green').place(x=45,y=70)
label3 = tk.Label(self,text='Player Two Name', font=TITLE_FONT_LINE2, bg = 'green').place(x=445,y=70)
label4 = tk.Label(self,text='Enter Number of Balls in Match', font=TITLE_FONT_LINE2, bg = 'green').place(x=185,y=110)
# Here is where I'm Having difficulty:
self.entry = tk.Entry(self, text=player1, width=7, font=TITLE_FONT_LINE2).place(x=60,y=100)
self.entry = tk.Entry(self,text=player2, width=7, font=TITLE_FONT_LINE2).place(x=480,y=100)
self.entry = tk.Entry(self,text=game_balls, width=4, font=TITLE_FONT_LINE2).place(x=275,y=140)
button1 = tk.Button(self, text="Go to Page One",
command=lambda: controller.show_frame("PageOne"))
button2 = tk.Button(self, text="Go to Page Two",
command=lambda: controller.show_frame("PageTwo"))
button1.place(x=275,y=440)
button2.place(x=275,y=540)
class PageOne(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
self.controller.geometry('615x615+415+190')
label = tk.Label(self, text="This is page 1", font=TITLE_FONT)
label.pack(side="top", fill="x", pady=10)
button = tk.Button(self, text="Go to the start page",
command=lambda: controller.show_frame("StartPage"))
button.pack()
class PageTwo(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(self, text="This is page 2", font=TITLE_FONT)
label.pack(side="top", fill="x", pady=10)
button = tk.Button(self, text="Go to the start page",
command=lambda: controller.show_frame("StartPage"))
button.pack()
if __name__ == "__main__":
app = SampleApp()
app.mainloop()
</code></pre>
| 0 | 2016-09-03T18:40:12Z | 39,310,695 | <p>I can't see any attempt to access the contents of the text entry widgets. As such your code does exactly what I'd expect it to do.</p>
<p>If you want to read the contents of a text entry widget you should create a <code>StringVar</code> to hold the contents</p>
<pre><code>self.playerone = StringVar()
self.entry1 = ttk.Entry(parent, textvariable=playerone)
</code></pre>
<p>The content of the entry can then be read from the content of the <code>playerone</code> variable for example <code>playeronename = self.playerone.get()</code> (Of course the variable must use the fully qualified name with the namespace)</p>
<p>There is documenation on the entry widget at <a href="http://www.tkdocs.com/tutorial/widgets.html#entry" rel="nofollow">http://www.tkdocs.com/tutorial/widgets.html#entry</a> and <a href="http://effbot.org/tkinterbook/entry.htm" rel="nofollow">http://effbot.org/tkinterbook/entry.htm</a></p>
| 0 | 2016-09-03T19:40:59Z | [
"python",
"tkinter"
] |
Implementing a modified do-while loop in Python i.e. do at least once and another time at the end of the loop? | 39,310,229 | <p>I am having problems implementing something that equates a do while loop.</p>
<p><strong>PROBLEM DESCRIPTION</strong></p>
<p>I am scraping a site and the results pages are paginated, i.e.</p>
<pre><code>1, 2, 3, 4, 5, .... NEXT
</code></pre>
<p>I am iterating through the pages using a test condition for the existence of the <code>NEXT</code> link. If there is one results page, There is no <code>NEXT</code> link so I will just scrape that first page. If there is more than one page, the last page also has no <code>NEXT</code> link. So the scraper function would also work on that page. The scraping function is called <code>findRecords()</code></p>
<p>So I am isolating my <code>NEXT</code> link using:</p>
<pre><code>next_link = driver.find_element(By.XPATH, "//a[contains(text(),'Next')][@style='text-decoration:underline; cursor: pointer;']")
</code></pre>
<p>So I want to run a loop that performs the scrape at least once (when there is one or more results page). I am also clicking the <code>NEXT</code> button using a click() function. The code I have so far is: </p>
<pre><code>while True:
findRecords()
next_link = driver.find_element(By.XPATH, "//a[contains(text(),'Next')][@style='text-decoration:underline; cursor: pointer;']")
if not next_link:
break
next_link.click()
</code></pre>
<p>This is not working. Well, it works and it scrapes but when it reaches the last page it give me a <code>NoSuchElementException</code> as follows:</p>
<blockquote>
<p>Traceback (most recent call last):
File "try.py", line 47, in
next_link = driver.find_element(By.XPATH, "//a[contains(text(),'Next')][@style='text-decoration:underline; cursor: pointer;']")
File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 752, in find_element
'value': value})['value']
File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 236, in execute
self.error_handler.check_response(response)
File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/errorhandler.py", line 192, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//a[contains(text(),'Next')][@style='text-decoration:underline; cursor: pointer;']"}
(Session info: chrome=53.0.2785.89)
(Driver info: chromedriver=2.20.353124 (035346203162d32c80f1dce587c8154a1efa0c3b),platform=Linux 3.13.0-92-generic x86_64)</p>
</blockquote>
<p>I know it's true that the element does not exist on that last page, because like i said before, the <code>NEXT</code> element does not exist on the last page.</p>
<p>So how do i fix my while loop to be able to scrape a single page result and/or that last page when the condition is not true and also elegantly break out of the while loop without giving me that hideous error?</p>
<p>PS: Other than the while loop above, I have also tried the following:</p>
<pre><code>is_continue = True
while is_continue:
findRecords()
next_link = driver.find_element(By.XPATH, "//a[contains(text(),'Next')][@style='text-decoration:underline; cursor: pointer;']")
if next_link:
is_continue = True
next_link.click()
else:
is_continue = False
</code></pre>
<p>And if it is any help, here is my scraper function <code>findRecords()</code> as well:</p>
<pre><code>def findRecords():
filename = "sam_" + letter + ".csv"
bsObj = BeautifulSoup(driver.page_source, "html.parser")
tableList = bsObj.find_all("table", {"class":"width100 menu_header_top_emr"})
tdList = bsObj.find_all("td", {"class":"menu_header width100"})
for table,td in zip(tableList,tdList):
a = table.find_all("span", {"class":"results_body_text"})
b = td.find_all("span", {"class":"results_body_text"})
with open(filename, "a") as csv_file:
csv_file.write(', '.join(tag.get_text().strip() for tag in a+b) +'\n')
</code></pre>
| 0 | 2016-09-03T18:41:31Z | 39,310,322 | <p>When you are searching for next link change code to find_elements which will return a list of size 1 if Next is present else list of size 0 but no exception.</p>
<pre><code>next_link = driver.find_elements(By.XPATH, "//a[contains(text(),'Next')][@style='text-decoration:underline; cursor: pointer;']")
</code></pre>
<p>You need to put in place logic to access the Next webelement from this list now.</p>
| 2 | 2016-09-03T18:53:41Z | [
"python",
"loops",
"selenium",
"for-loop",
"while-loop"
] |
Implementing a modified do-while loop in Python i.e. do at least once and another time at the end of the loop? | 39,310,229 | <p>I am having problems implementing something that equates a do while loop.</p>
<p><strong>PROBLEM DESCRIPTION</strong></p>
<p>I am scraping a site and the results pages are paginated, i.e.</p>
<pre><code>1, 2, 3, 4, 5, .... NEXT
</code></pre>
<p>I am iterating through the pages using a test condition for the existence of the <code>NEXT</code> link. If there is one results page, There is no <code>NEXT</code> link so I will just scrape that first page. If there is more than one page, the last page also has no <code>NEXT</code> link. So the scraper function would also work on that page. The scraping function is called <code>findRecords()</code></p>
<p>So I am isolating my <code>NEXT</code> link using:</p>
<pre><code>next_link = driver.find_element(By.XPATH, "//a[contains(text(),'Next')][@style='text-decoration:underline; cursor: pointer;']")
</code></pre>
<p>So I want to run a loop that performs the scrape at least once (when there is one or more results page). I am also clicking the <code>NEXT</code> button using a click() function. The code I have so far is: </p>
<pre><code>while True:
findRecords()
next_link = driver.find_element(By.XPATH, "//a[contains(text(),'Next')][@style='text-decoration:underline; cursor: pointer;']")
if not next_link:
break
next_link.click()
</code></pre>
<p>This is not working. Well, it works and it scrapes but when it reaches the last page it give me a <code>NoSuchElementException</code> as follows:</p>
<blockquote>
<p>Traceback (most recent call last):
File "try.py", line 47, in
next_link = driver.find_element(By.XPATH, "//a[contains(text(),'Next')][@style='text-decoration:underline; cursor: pointer;']")
File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 752, in find_element
'value': value})['value']
File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 236, in execute
self.error_handler.check_response(response)
File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/errorhandler.py", line 192, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//a[contains(text(),'Next')][@style='text-decoration:underline; cursor: pointer;']"}
(Session info: chrome=53.0.2785.89)
(Driver info: chromedriver=2.20.353124 (035346203162d32c80f1dce587c8154a1efa0c3b),platform=Linux 3.13.0-92-generic x86_64)</p>
</blockquote>
<p>I know it's true that the element does not exist on that last page, because like i said before, the <code>NEXT</code> element does not exist on the last page.</p>
<p>So how do i fix my while loop to be able to scrape a single page result and/or that last page when the condition is not true and also elegantly break out of the while loop without giving me that hideous error?</p>
<p>PS: Other than the while loop above, I have also tried the following:</p>
<pre><code>is_continue = True
while is_continue:
findRecords()
next_link = driver.find_element(By.XPATH, "//a[contains(text(),'Next')][@style='text-decoration:underline; cursor: pointer;']")
if next_link:
is_continue = True
next_link.click()
else:
is_continue = False
</code></pre>
<p>And if it is any help, here is my scraper function <code>findRecords()</code> as well:</p>
<pre><code>def findRecords():
filename = "sam_" + letter + ".csv"
bsObj = BeautifulSoup(driver.page_source, "html.parser")
tableList = bsObj.find_all("table", {"class":"width100 menu_header_top_emr"})
tdList = bsObj.find_all("td", {"class":"menu_header width100"})
for table,td in zip(tableList,tdList):
a = table.find_all("span", {"class":"results_body_text"})
b = td.find_all("span", {"class":"results_body_text"})
with open(filename, "a") as csv_file:
csv_file.write(', '.join(tag.get_text().strip() for tag in a+b) +'\n')
</code></pre>
| 0 | 2016-09-03T18:41:31Z | 39,310,602 | <p>You should try using <code>find_elements</code>, it would return either list of WebElement or empty list. So just check its length as below :-</p>
<pre><code>while True:
findRecords()
next_link = driver.find_elements(By.XPATH, "//a[contains(text(),'Next')][@style='text-decoration:underline; cursor: pointer;']")
if len(next_link) == 0:
break
next_link[0].click()
</code></pre>
| 1 | 2016-09-03T19:28:23Z | [
"python",
"loops",
"selenium",
"for-loop",
"while-loop"
] |
Setting a proxy using python, selenium, and phantomJS | 39,310,307 | <p>I have tried the solution posted by Alex on the following page but I keep getting this error.
<a href="http://stackoverflow.com/questions/14699718/how-do-i-set-a-proxy-for-phantomjs-ghostdriver-in-python-webdriver/">How do I set a proxy for phantomjs/ghostdriver in python webdriver?</a></p>
<p>I have phantomJS in my PATH.</p>
<pre><code>File "C:\Users\sri19\Desktop\Gui OSRS\testphantomproxy.py", line 21, in <module>
driver = webdriver.PhantomJS(service_args=phan_args, desired_capabilities=dcap)
File "C:\Python27\Lib\site-packages\selenium\webdriver\phantomjs\webdriver.py", line 52, in __init__
self.service.start()
File "C:\Python27\Lib\site-packages\selenium\webdriver\common\service.py", line 86, in start
self.assert_process_still_running()
File "C:\Python27\Lib\site-packages\selenium\webdriver\common\service.py", line 99, in assert_process_still_running
% (self.path, return_code)
selenium.common.exceptions.WebDriverException: Message: Service phantomjs unexpectedly exited. Status code was: -1
</code></pre>
<p>Here is my current test script</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.common.proxy import *
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import StaleElementReferenceException, TimeoutException
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.webdriver.common.keys import Keys
import sys
singleproxy = "88.157.149.250:8080"
proxytype = "http"
user_agent = ("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4) " + "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.57 Safari/537.36")
phan_args = ['--proxy=88.157.149.250:8080', 'proxy-type=http']
print "step 1"
dcap = dict(DesiredCapabilities.PHANTOMJS)
dcap["phantomjs.page.settings.userAgent"] = user_agent
print "step 2"
driver = webdriver.PhantomJS(service_args=phan_args, desired_capabilities=dcap)
driver.get("https://www.whatismyip.com/")
print "step 3"
print driver.current_url
htmlpage = driver.page_source
print htmlpage.encode(sys.stdout.encoding, errors='replace')
</code></pre>
<p>Can anyone help me understand why I am receiving this error? When I applied this proxy to chromedriver (through a different method) it worked. So it cannot be the proxy. </p>
| 0 | 2016-09-03T18:51:28Z | 39,310,375 | <p>Whelp... Made a small mistake.</p>
<p>The following line
phan_args = ['--proxy=88.157.149.250:8080', 'proxy-type=http']
should be
phan_args = ['--proxy=88.157.149.250:8080', '--proxy-type=http']</p>
| 0 | 2016-09-03T19:01:12Z | [
"python",
"selenium",
"proxy",
"phantomjs"
] |
Merge Sort not happening correctly - Python | 39,310,370 | <p>Sorting is not happening correctly. Can some one help on sorting with this approach. Also please let me know where I am going wrong. I am new to Python so I am doing this myself. I am using the usual approach as we do in C or other languages.</p>
<pre><code>base =[5,4,3,2,1]
def splitarray (low, high):
if low < high:
mid = (high+low)/2
splitarray (low, mid)
splitarray (mid+1,high)
merge(low,mid,high)
else:
return
def merge(low,mid,high):
print("merge " +str(low) + " - " +str(mid)+" - "+ str(high))
result = [0]*len(base)
k = 0
i=low
j=mid+1
l=0
while i <= mid and j <= high:
if (base[i] < base[j]):
result[k]= base[i]
k+=1
i += 1
if (base[i] > base[j]) :
result[k]= base[j]
j += 1
k += 1
while i <= mid:
result[k]= base[i]
k += 1
i += 1
while j <= high:
result[k]= base[j]
#count = count + mid - i
j += 1
k += 1
print result
l = low
k= 0
while l <= high:
base[l] = result[l]
l += 1
print base
splitarray(0,len(base)-1)
</code></pre>
| 2 | 2016-09-03T19:00:29Z | 39,310,884 | <p>Visually the way the algorithm operates is:<a href="http://i.stack.imgur.com/obJIB.png" rel="nofollow"><img src="http://i.stack.imgur.com/obJIB.png" alt="enter image description here"></a></p>
<p>So the most obvious way to implement merge sort is to return a new list for each merge. Maybe that can be optimized to what it seems like you're trying to do, which is to operate on a single top level <code>result</code>. But if you do it this way you can't just append to <code>result</code> at each level of merging. Because at the bottom level of the recursion you'll add four elements, then at the middle level you'll add four, then at the top level you'll add another four. It's too many. If you do it this way you should instead have a fixed <code>result</code> size and operate on its indices throughout the entire execution.</p>
<p>A second mistake is that you are reading through an unmodified <code>base</code> for every merge. The precondition at each merge step is that the two lists being merged are already sorted. If you're implementing the algorithm in the obvious way you can just use the return values from deeper merges. If you're implementing the algorithm in some optimized way using a top level <code>result</code>, then you should be reading from <code>result</code>, not <code>base</code>.</p>
| 2 | 2016-09-03T20:05:30Z | [
"python",
"mergesort"
] |
Merge Sort not happening correctly - Python | 39,310,370 | <p>Sorting is not happening correctly. Can some one help on sorting with this approach. Also please let me know where I am going wrong. I am new to Python so I am doing this myself. I am using the usual approach as we do in C or other languages.</p>
<pre><code>base =[5,4,3,2,1]
def splitarray (low, high):
if low < high:
mid = (high+low)/2
splitarray (low, mid)
splitarray (mid+1,high)
merge(low,mid,high)
else:
return
def merge(low,mid,high):
print("merge " +str(low) + " - " +str(mid)+" - "+ str(high))
result = [0]*len(base)
k = 0
i=low
j=mid+1
l=0
while i <= mid and j <= high:
if (base[i] < base[j]):
result[k]= base[i]
k+=1
i += 1
if (base[i] > base[j]) :
result[k]= base[j]
j += 1
k += 1
while i <= mid:
result[k]= base[i]
k += 1
i += 1
while j <= high:
result[k]= base[j]
#count = count + mid - i
j += 1
k += 1
print result
l = low
k= 0
while l <= high:
base[l] = result[l]
l += 1
print base
splitarray(0,len(base)-1)
</code></pre>
| 2 | 2016-09-03T19:00:29Z | 39,313,429 | <p>The issue with your current (updated) code appears to be with the last loop:</p>
<pre><code>l = low
k= 0
while l <= high:
base[l] = result[l]
l += 1
</code></pre>
<p>Here you're copying the values from the <code>results</code> list to the <code>base</code> list. However, the results are all at the start of <code>results</code>, not at the same coordinates you want them to go in <code>base</code>. You seem to have <em>almost</em> got it right since you're setting <code>k</code> to zero, but you don't end up using <code>k</code> in the loop.</p>
<p>Try:</p>
<pre><code>l = low
k= 0
while l <= high:
base[l] = result[k] # read the result from index k, not l
l += 1
k += 1 # increment k as well
</code></pre>
<p>This should work as intended. Note that while this will do the sorting correctly, this isn't a very elegant way of sorting in Python. To start with, you can only sort the one global variable <code>base</code>, not any list (it would be much nicer to pass the list as a parameter). However, since this looks like something you've written mostly for the learning experience, I'll leave further improvements up to you.</p>
| 1 | 2016-09-04T04:00:15Z | [
"python",
"mergesort"
] |
Parsing text into it's own field, counting, and reshaping select fields to wide format | 39,310,464 | <p>I'm doing an analysis using Python to see how long we are keeping conversations in our social media channels by counting the number of interactions and reading the messages.</p>
<p>I'm thinking the approach would be to make the first table look like the second table. Steps to get there:</p>
<ol>
<li>Parse our the @username into it's own field. 99% of the time, our responses start with @username</li>
<li>Count the number of times the @username shows up - this indicates the number of messages we send the user</li>
<li>Turn the inbound and outbound messages from long to wide format. Not certain how many fields I'd have to create but as long as I know the technique, I can worry about the # of fields later.</li>
</ol>
<p>Right now timestamp isn't that important to me but it could be in the future. Regardless, I would use the same technique as the inbound and outbound messages</p>
<p>Before table</p>
<pre>
Inbound Message Outbound message Inbound Time Outbound Time Account
Hello, how are you @userA I'm good! mm/dd/yy hh:mm mm/dd/yy hh:mm FB
Where is the cat? @userB what cat? mm/dd/yy hh:mm mm/dd/yy hh:mm Twitter
What is a pie @user3 it is a food mm/dd/yy hh:mm mm/dd/yy hh:mm Twitter
The black cat @userB I don't know mm/dd/yy hh:mm mm/dd/yy hh:mm Twitter
</pre>
<p>After table</p>
<pre>
User Messages Account Inbound 1 Outbound 1 Inbound 2 Outbound 2 Inbound 3 Outbound 3
userA 1 FB Hello, how are you @user1 I'm good! null null null null
userB 2 Twitter Where is the cat? @user2 what cat? The black cat @user2 I don't know null null
user3 1 Twitter What is a pie @user3 it is a food null null null null
</pre>
| 2 | 2016-09-03T19:11:46Z | 39,311,887 | <p>Your transformation process should include several steps, I will give an idea only to one of them.</p>
<p>Concerning user extraction:
First you should apply <code>re.sub(pattern, repl, string)</code> function from the <strong>re</strong> package to the raws in the Outbound message column (in a loop). The <code>sub</code> function works together with the <code>compile</code> function, where the regular expression is specified:</p>
<pre><code>import re
# x - your string
# here you write your regular expression: a whitespace between a number and a word character (not syntax characters).
y = re.compile(r"([0-9])(\s)(\w)")
# here you replace the second capture group from the regex the whitespace with a _ symbol
y.sub('_\2',x)
</code></pre>
<p>, where you replace a whitespace with a <code>"_"</code>. In the next step you can split the cells on the <code>"_"</code> character:</p>
<pre><code>import re
# x - your data
re.split('_', x)
</code></pre>
<p>Further examples for both functions you can find <a href="http://stackoverflow.com/questions/6711567/how-to-use-python-regex-to-replace-using-captured-group">here</a> and <a href="http://stackoverflow.com/questions/10974932/python-split-string-based-on-regular-expression">here</a>.</p>
<p><strong>EDIT:</strong></p>
<p>Since your user id doesn't always have numbers, you should apply another logic at extracting it from the Outbound message column. You can extract the first word from the string either with: <code>x.split(' ', 1)[0]</code>, where x - your string, to get the first word of the strin, or with a regex: <code>^\S*</code></p>
| 1 | 2016-09-03T22:31:07Z | [
"python",
"pandas",
"dataframe",
"aggregate",
"reshape"
] |
Parsing text into it's own field, counting, and reshaping select fields to wide format | 39,310,464 | <p>I'm doing an analysis using Python to see how long we are keeping conversations in our social media channels by counting the number of interactions and reading the messages.</p>
<p>I'm thinking the approach would be to make the first table look like the second table. Steps to get there:</p>
<ol>
<li>Parse our the @username into it's own field. 99% of the time, our responses start with @username</li>
<li>Count the number of times the @username shows up - this indicates the number of messages we send the user</li>
<li>Turn the inbound and outbound messages from long to wide format. Not certain how many fields I'd have to create but as long as I know the technique, I can worry about the # of fields later.</li>
</ol>
<p>Right now timestamp isn't that important to me but it could be in the future. Regardless, I would use the same technique as the inbound and outbound messages</p>
<p>Before table</p>
<pre>
Inbound Message Outbound message Inbound Time Outbound Time Account
Hello, how are you @userA I'm good! mm/dd/yy hh:mm mm/dd/yy hh:mm FB
Where is the cat? @userB what cat? mm/dd/yy hh:mm mm/dd/yy hh:mm Twitter
What is a pie @user3 it is a food mm/dd/yy hh:mm mm/dd/yy hh:mm Twitter
The black cat @userB I don't know mm/dd/yy hh:mm mm/dd/yy hh:mm Twitter
</pre>
<p>After table</p>
<pre>
User Messages Account Inbound 1 Outbound 1 Inbound 2 Outbound 2 Inbound 3 Outbound 3
userA 1 FB Hello, how are you @user1 I'm good! null null null null
userB 2 Twitter Where is the cat? @user2 what cat? The black cat @user2 I don't know null null
user3 1 Twitter What is a pie @user3 it is a food null null null null
</pre>
| 2 | 2016-09-03T19:11:46Z | 39,314,625 | <p><strong><em>Note</em></strong><br>
You need to <code>groupby</code> <code>user</code> and <code>df.Account</code> because it is possible to have messages from different accounts for the same user.</p>
<pre><code># helper function to flatten multiindex objects
def flatten_multiindex(midx, sep=' '):
n = midx.nlevels
tups = zip(*[midx.get_level_values(i).astype(str) for i in range(n)])
return pd.Index([sep.join(tup) for tup in tups])
in_out = ['Inbound Message', 'Outbound message']
# this gets a fresh ordering for each group
handler = lambda df: df.reset_index(drop=True)
# Use regular expression to extract user
user = df['Outbound message'].str.extract(r'(?P<User>@\w+)', expand=False)
df1 = df.groupby([user, df.Account])[in_out].apply(handler) \
.unstack().sort_index(1, 1)
df1.columns = flatten_multiindex(df1.columns)
# I separated getting group sizes from long to wide pivot
messages = df.groupby([user, df.Account]).size().to_frame('Messages')
pd.concat([messages, df1], axis=1)
</code></pre>
<p><a href="http://i.stack.imgur.com/e0S1P.png" rel="nofollow"><img src="http://i.stack.imgur.com/e0S1P.png" alt="enter image description here"></a></p>
<pre><code>pd.concat([messages, df1], axis=1).reset_index()
</code></pre>
<p><a href="http://i.stack.imgur.com/YIETr.png" rel="nofollow"><img src="http://i.stack.imgur.com/YIETr.png" alt="enter image description here"></a></p>
<hr>
<p>Breaking down the helper function</p>
<pre><code># helper function to flatten multiindex objects
def flatten_multiindex(midx, sep=' '):
# get the number of levels in the index
n = midx.nlevels
# for each level in the index, get the values and
# convert it to strings so I can later ' '.join on it
#
# zip forms the tuples so I can pass each result to ' '.join
tups = zip(*[midx.get_level_values(i).astype(str) for i in range(n)])
# do the ' '.join and return as an index object
return pd.Index([sep.join(tup) for tup in tups])
</code></pre>
| 1 | 2016-09-04T07:37:30Z | [
"python",
"pandas",
"dataframe",
"aggregate",
"reshape"
] |
Python Freezing: general process and user input? | 39,310,494 | <p>I'm relatively new to the process of freezing and packaging code, and one of my concerns with freezing my project is how I'd deal with user input. I have a main file in a project that deals with physics stuff with an input area like this: </p>
<pre><code>#Coil(center, radius, normal vector, current, scene, loops(default=1), pitch(default=1))
#Example coil:
r = Coil(vector(0, 0, 0), 10, vector(0, 1, 1), 10, d, 10, 0.5)
</code></pre>
<p>So after I package the file with py2exe or anything similar I find, is there a way to have the user input like the above, or do I need to create a user interface for that before packaging the code? Thanks!</p>
| 0 | 2016-09-03T19:15:19Z | 39,313,975 | <p>Once your code is frozen the contents of the code can no longer be changed, (without going back to the original code), but there are a number of strategies that you can use:</p>
<ul>
<li>Prompt the user for <em>missing</em> parameters one at a time - <em>makes the program hard to use</em></li>
<li>Allow the user to supply the parameters on the command line e.g.: using <a href="https://docs.python.org/3/library/argparse.html" rel="nofollow">argparse</a> - <em>enables batch calling of your code - can be combined with the above</em></li>
<li>Allow the user to supply a file containing the parameters this could be one per line, a line of comma separated parameters and call your function once per line or a multitude of other options like xml, ini format, etc. - <em>better batch calling - this can be combined with both of the above and you could have a <code>--file</code> option</em></li>
<li>All of the above <em>Possibly the best option</em></li>
<li>Provide a GUI input for parameters using Tinker, QT or wxPython <em>often the most work can still be combined with the above</em></li>
<li>You <em>can</em> implement a plug-in like architecture to supply default code but also allow the user to supply alternative code but there are security concerns.</li>
<li>You could leave the above code out of your frozen application but include it as a .py file that the user could modify <strong><em>beware</em></strong> <em>the user will have the full power of python available, including any libraries that your application includes which can make for malicious changes</em></li>
<li>You can write your own little language to allow the user to supply the items needed using e.g. by using <a href="https://github.com/igordejanovic/textX" rel="nofollow">TextX</a> or just about any of the tools listed <a href="https://wiki.python.org/moin/LanguageParsing" rel="nofollow">here</a> then allow the user to supply input file(s).</li>
</ul>
<p>Reading between the lines it looks like the user specifies a number of object instances which are then created and processed so a little pseudo language that you parse, <em>either from command line parameters or from a file</em>, would be the way to go. Then you parse, (and validate), the input and for each object create an instance and add it to a list. Then <em>once the input has been consumed</em> process all of the instances in the list.</p>
| 1 | 2016-09-04T05:59:52Z | [
"python",
"python-2.7",
"vpython",
"code-freeze"
] |
Getting an error "could not broadcast input array from shape (252,4) into shape (4)" in optimization | 39,310,546 | <p>I a relatively new to python scipy library. I was trying to use the scipy.optimize to find the maximum value of the sharpe() function in the following code</p>
<pre><code>def sharpe(dr, wts):
portfolio=np.ones(dr.shape[0])
dr[0:]=wts*dr[0:]
sharpe_ratio=-np.mean(np.sum(dr, axis=1))/np.std(np.sum(dr, axis=1))
return sharpe_ratio
def wts_con(wts):
return wts[0]+wts[1]+wts[2]+wts[3]-1
def sharpe_optimize(dr, sharpe_func):
wts_guess=np.array([0.25,0.25,0.25,0.25])
con=[{"type":"eq", "fun":wts_con}]
bnds=((0,1),(0,1),(0,1),(0,1))
result=spo.minimize(sharpe_func, wts_guess, args=(dr,), method="SLSQP", constraints=con, bounds=bnds, options={"disp":True})
return result
</code></pre>
<p>In the above code dr is a size(252,4) array and wts is a size(4) array</p>
<p>I am getting the following error in line 3 when I call the sharpe_optimize() function</p>
<blockquote>
<p>could not broadcast input array from shape (252,4) into shape (4)</p>
</blockquote>
| 0 | 2016-09-03T19:20:58Z | 39,314,478 | <p>I think you need to swap the arguments in your definition of the <code>sharpe</code> function. It is defined as <code>sharpe(dr,wts)</code> but then it looks like you call minimize as <code>sharpe(wts,dr)</code> based on your use of <code>args</code>. Edit: I have just seen that this is pointed out in the above comments!</p>
| 0 | 2016-09-04T07:18:08Z | [
"python",
"optimization",
"scipy"
] |
Python stacked histogram grouped data | 39,310,559 | <p>How can I create a stacked Histogram like this:
<a href="http://i.stack.imgur.com/vVKq3.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/vVKq3.jpg" alt="enter image description here"></a></p>
<pre><code>import numpy as np
import pylab as P
import matplotlib.pyplot as plt
import matplotlib
matplotlib.style.use('ggplot')
%pylab inline
pylab.rcParams['figure.figsize'] = (15, 4)
mu, sigma = 200, 25
x = mu + sigma*P.randn(1000,2)
n, bins, patches = P.hist(x, 10, normed=1, histtype='bar', stacked=True)
P.show()
</code></pre>
<p>For grouped data.</p>
<pre><code>import pandas as pd
df1 = pd.DataFrame({'A': [1,2,3,4,5,6,7,8,9],'group': [1,0,0,0,0,1,1,1,1]})
</code></pre>
<p>As
<code>df1.A.hist(by=df1.group, bins='doane', stacked=True)</code> or</p>
<pre><code>df1.A.hist(by=df1.group, bins='doane')
</code></pre>
<p>only result in:
<a href="http://i.stack.imgur.com/x8rEK.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/x8rEK.jpg" alt="enter image description here"></a></p>
| 4 | 2016-09-03T19:22:05Z | 39,311,219 | <p>You can <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.pivot.html" rel="nofollow"><code>pivot</code></a> your DataFrame so that each group is in a different column and then generate the histogram.</p>
<pre><code>df1 = pd.DataFrame({'A': [1,2,3,4,5,6,7,8,9],'group': [1,0,0,0,0,1,1,1,1]})
df1.pivot(columns='group', values='A').plot.hist(stacked=True)
</code></pre>
<p><a href="http://i.stack.imgur.com/Rzt52.png" rel="nofollow"><img src="http://i.stack.imgur.com/Rzt52.png" alt="enter image description here"></a></p>
<p>Edit: Added the <code>stacked=True</code> parameter to <code>hist()</code></p>
| 3 | 2016-09-03T20:51:10Z | [
"python",
"pandas",
"plot",
"visualization"
] |
sqlite3 in Python: is manual string formatting safe for selecting or updating variable columns? | 39,310,731 | <p>It is well known that one shouldn't assemble SQL queries using native string operations, but instead use prepared statements with placeholders for variables. The sqlite3 in Python handle this this way:</p>
<pre><code>c.execute('UPDATE stock SET price = ? WHERE symbol = ?', the_price, the_symbol)
</code></pre>
<p>The limit of this approach is that there is no way to set parameters for the columns that are selected or updated. In the above example, the price column is updated. However, other requests would update another column in the same fashion. Each of these requests would be pretty much the same except for the name of the column. Therefore, in respect to DRY (Don't Repeat Yourself), it becomes very tempting to do the following:</p>
<pre><code>if my_col in LIST_OK_COLUMNS:
c.execute('UPDATE stock SET {} = ? WHERE symbol = ?'.format(my_col), the_symbol, the_price)
</code></pre>
<p>Still, this is a query being built using native string operations, which is unsafe according to the documentation.</p>
<p>What is the most standard way to do this properly?</p>
| 0 | 2016-09-03T19:45:27Z | 39,315,081 | <p>If any of the strings you're inserting directly into the SQL statement might be controlled by the user, you have a problem.</p>
<p>For values, you can use SQL parameters.</p>
<p>There is no such mechamism for table/column names (because asking the user for these names usually does not happen; SQL was designed before there was the evil internet with half of the app running on the untrusted client).</p>
<p>To make a column name such as <code>price = -100 WHERE 1 OR symbol = ? --</code> harmless, you have to properly escape it:</p>
<pre><code>def sql_escape_identifier(s):
return '"' + s.replace('"', '""') + '"'
c.execute('UPDATE stock SET {} = ...'.format(sql_escape_identifier(my_col)), ...
</code></pre>
| 0 | 2016-09-04T08:42:45Z | [
"python",
"sqlite3"
] |
Log file creation in Python vs Shell | 39,310,892 | <p>I am having a difficult time to understand log creation on Python. I come from shell programming and trying to see if a similarity exists b/w shell and Python logging</p>
<p>In shell- I have a driver script where I describe the log location and name . Log from all the scripts that I call from the diver will be directed to the log</p>
<p>Example
driver script.ksh</p>
<pre><code>#!bin/ksh
master_log_file = home/path1/masterlog
call script1
script1.ksh >> master_log_file
</code></pre>
<p>how do i same thing in python</p>
<p>Example
driver script.py</p>
<pre><code>#!bin/env/python
#create master log file
# call script1.py
script1.py >> master_log_file
</code></pre>
| 0 | 2016-09-03T20:06:20Z | 39,310,928 | <p>Best way to create logs in python is with a logging library documented here: <a href="https://docs.python.org/3/library/logging.html" rel="nofollow">https://docs.python.org/3/library/logging.html</a> </p>
<p>It's pretty sofisticated and can be a pain to set up when you want to your logging to be sofisticated (log different levels to different outputs etc). But once you get it working properly, it can do some amazing things for you, logs the origin (module), you can pass an argument to just log certain level (info) for normal running and another (develop - with loads of details) for another. </p>
<p>For example, one of my scripts logged info stuff to stdout, so I had logs of what was going on easily readable, while it also logged debug stuff to a file, so when a bug appears, I could see log information from all the libraries etc. That wouldn't be practical in stdout, because it wrote whole objects out and everything. </p>
| 0 | 2016-09-03T20:11:41Z | [
"python",
"shell",
"logging"
] |
Retrieving a specific line of text | 39,310,902 | <pre><code><li class="b-list__box-list-item b-list__box-list-item_type_block">
<i class="b-list__box-item-title b-list__box-item-title_type_width">
Height:
</i>
6' 2"
</li>
</code></pre>
<p>For the above, I only want to retrieve 6'2" and ignore "height." my code</p>
<pre><code>stat_one = stat_table_one.find_all("li", {"class": "b-list__box-list-item b-list__box-list-item_type_block"})
for li in stat_one:
print li.get_text()
</code></pre>
<p>This code pulls "Height" and 6'2". Is there a way to just get 6'2"?</p>
| 0 | 2016-09-03T20:09:05Z | 39,310,977 | <pre><code>In [1]: from bs4 import BeautifulSoup
In [2]: h = """<li class="b-list__box-list-item b-list__box-list-item_type_block">
...: <i class="b-list__box-item-title b-list__box-item-title_type_width">
...: Height:
...: </i>
...: 6' 2"
...: </li>
...: """
In [3]: soup = BeautifulSoup(h,"html.parser")
In [4]: "".join(soup.find("li").find_all(text=True, recursive=False)).strip()
Out[4]: u'6\' 2"'
</code></pre>
<p>You dont want the child text so don't look recursively.</p>
| 1 | 2016-09-03T20:17:25Z | [
"python",
"beautifulsoup"
] |
Error details: Field `af` does not exist | 39,310,919 | <p>I am getting this error for 2 days.
I have read any links regarding the same error and each time no effect.</p>
<p>I am trying simple inheritance
Here is my <code>employee.py</code> file</p>
<pre><code>class Employee(models.Model):
_inherit = 'hr.employee'
_description = "Inherited modules"
af = fields.Char(string="AF")
</code></pre>
<p>Here is my <code>employee.xml</code> file</p>
<pre><code><openerp>
<data>
<record id="hr_employee_contact_form_view" model="ir.ui.view">
<field name="name">hr.employee</field>
<field name="model">hr.employee</field>
<field name="inherit_id" ref="hr.view_employee_form" />
<field name="arch" type="xml">
<notebook position="inside">
<page string="Contact">
<group>
<field name="af"/>
</group>
</page>
</notebook>
</field>
</record>
<record model="ir.actions.act_window" id="employee_list_action">
<field name="name">Contacts</field>
<field name="res_model">hr.employee</field>
<field name="view_mode">tree,form</field>
</record>
<menuitem id="configuration_menu" name="Configuration"
parent="main_ayda_project_menu"/>
<menuitem id="contact_menu" name="Employee"
parent="configuration_menu"
action="employee_list_action"/>
</data>
</openerp>
</code></pre>
<p>Here is my <code>__openerp__.py</code> file</p>
<pre><code># -*- coding: utf-8 -*-
{
'name': "Smart Gateway",
'summary': """ Smart Gateway """,
'description': """
Long description of module's purpose
""",
'author': "My Company",
'website': "http://www.yourcompany.com",
'category': 'Uncategorized',
'version': '0.1',
'depends': ['base',
'hr'],
'data': [
# 'security/ir.model.access.csv',
# 'views/views.xml',
'views/templates.xml',
'views/contact_master/contact.xml',
'views/employee.xml'
],
# only loaded in demonstration mode
'demo': [
'demo/demo.xml',
],
}
</code></pre>
<p>And here is my <code>__init__.py</code> file</p>
<pre><code>from . import controllers
from . import models
</code></pre>
<p>I have taken care of dependency also still getting this error.</p>
<pre><code>ParseError: "Invalid view definition
Error details:
Field `af` does not exist
Error context:
View `hr.employee`
[view_id: 1859, xml_id: n/a, model: hr.employee, parent_id: 352]
None" while parsing file:///C:/Odoo%209.0-20160127/server/openerp/addons/ayda_project/views/employee.xml:3, near
<record id="hr_employee_contact_form_view" model="ir.ui.view">
<field name="name">hr.employee</field>
<field name="model">hr.employee</field>
<field name="inherit_id" ref="hr.view_employee_form"/>
<field name="arch" type="xml">
<notebook position="inside">
<page string="Contact">
<group>
<field name="af"/>
</group>
</page>
</notebook>
</field>
</record>
</code></pre>
| 0 | 2016-09-03T20:10:46Z | 39,310,990 | <p>Add your employee.py file into an __init__.py file in the same directory.
If it is in the same directory as your other .py files.</p>
<pre><code>from . import controllers
from . import models
from . import employee
</code></pre>
<p>Update your addon</p>
| 1 | 2016-09-03T20:19:33Z | [
"python",
"orm",
"openerp",
"odoo-8",
"odoo-9"
] |
Error details: Field `af` does not exist | 39,310,919 | <p>I am getting this error for 2 days.
I have read any links regarding the same error and each time no effect.</p>
<p>I am trying simple inheritance
Here is my <code>employee.py</code> file</p>
<pre><code>class Employee(models.Model):
_inherit = 'hr.employee'
_description = "Inherited modules"
af = fields.Char(string="AF")
</code></pre>
<p>Here is my <code>employee.xml</code> file</p>
<pre><code><openerp>
<data>
<record id="hr_employee_contact_form_view" model="ir.ui.view">
<field name="name">hr.employee</field>
<field name="model">hr.employee</field>
<field name="inherit_id" ref="hr.view_employee_form" />
<field name="arch" type="xml">
<notebook position="inside">
<page string="Contact">
<group>
<field name="af"/>
</group>
</page>
</notebook>
</field>
</record>
<record model="ir.actions.act_window" id="employee_list_action">
<field name="name">Contacts</field>
<field name="res_model">hr.employee</field>
<field name="view_mode">tree,form</field>
</record>
<menuitem id="configuration_menu" name="Configuration"
parent="main_ayda_project_menu"/>
<menuitem id="contact_menu" name="Employee"
parent="configuration_menu"
action="employee_list_action"/>
</data>
</openerp>
</code></pre>
<p>Here is my <code>__openerp__.py</code> file</p>
<pre><code># -*- coding: utf-8 -*-
{
'name': "Smart Gateway",
'summary': """ Smart Gateway """,
'description': """
Long description of module's purpose
""",
'author': "My Company",
'website': "http://www.yourcompany.com",
'category': 'Uncategorized',
'version': '0.1',
'depends': ['base',
'hr'],
'data': [
# 'security/ir.model.access.csv',
# 'views/views.xml',
'views/templates.xml',
'views/contact_master/contact.xml',
'views/employee.xml'
],
# only loaded in demonstration mode
'demo': [
'demo/demo.xml',
],
}
</code></pre>
<p>And here is my <code>__init__.py</code> file</p>
<pre><code>from . import controllers
from . import models
</code></pre>
<p>I have taken care of dependency also still getting this error.</p>
<pre><code>ParseError: "Invalid view definition
Error details:
Field `af` does not exist
Error context:
View `hr.employee`
[view_id: 1859, xml_id: n/a, model: hr.employee, parent_id: 352]
None" while parsing file:///C:/Odoo%209.0-20160127/server/openerp/addons/ayda_project/views/employee.xml:3, near
<record id="hr_employee_contact_form_view" model="ir.ui.view">
<field name="name">hr.employee</field>
<field name="model">hr.employee</field>
<field name="inherit_id" ref="hr.view_employee_form"/>
<field name="arch" type="xml">
<notebook position="inside">
<page string="Contact">
<group>
<field name="af"/>
</group>
</page>
</notebook>
</field>
</record>
</code></pre>
| 0 | 2016-09-03T20:10:46Z | 39,311,862 | <p>Add <code>from . import employee</code> to <code>__init__.py</code> inside <code>models</code> folder. </p>
<p><code>models/__init__.py</code> file: </p>
<pre><code>...
from . import employee
</code></pre>
| 0 | 2016-09-03T22:27:03Z | [
"python",
"orm",
"openerp",
"odoo-8",
"odoo-9"
] |
What's the fastest way to find all occurences of the substring in large string in python | 39,310,956 | <p>Edited to clarify input/output. I think this will be somewhat slow no matter what, but up until now I haven't really considered speed in my python scripts, and I'm trying to figure out ways to speed up operations like these.</p>
<p>My input is pickled dictionaries of the genome sequences. I'm currently working with two genomes, the budding yeast genome (11.5 MB on disk), and the human genome (2.8 GB on disk). These dictionaries have the form:</p>
<pre><code>seq_d = { 'chr1' : 'ATCGCTCGCTGCTCGCT', 'chr2' : 'CGATCAGTCATGCATGCAT',
'chr3' : 'ACTCATCATCATCATACTGGC' }
</code></pre>
<p>I want to find all single-base instances of a nucleotide(s) in both strands of the genome. Where the <code>+</code> strand refers to the sequence in the above dictionary, and the <code>-</code> strand is the reverse complement of the sequences. My output is a nested dictionary, where the top level <code>keys</code> are <code>+</code> or <code>-</code>, the nested <code>keys</code> are chromosome names, and the values are lists of 0-indexed positions:</p>
<pre><code>nts = 'T'
test_d = {'+': {'chr3': [2, 5, 8, 11, 14, 17], 'chr2': [3, 7, 10, 14, 18],
'chr1': [1, 5, 9, 12, 16]}, '-': {'chr3': [0, 4, 7, 10, 13, 15],
'chr2': [2, 5, 9, 13, 17], 'chr1': [0]}}
</code></pre>
<p><code>test_d</code> defines a set of positions to examine in a large Illumina sequencing dataset later in the script.</p>
<p>My first attempt uses <code>enumerate</code>, and iteration.</p>
<pre><code>import time
import numpy as np
rev_comps = { 'A' : 'T', 'T' : 'A', 'G' : 'C', 'C' : 'G', 'N' : 'N'}
test_d = { '+' : {}, '-' : {}}
nts = 'T'
s = time.time()
for chrom in seq_d:
plus_pos, minus_pos = [], []
chrom_seq = seq_d[chrom]
for pos, nt in enumerate(chrom_seq):
if nt in nts:
plus_pos.append(pos)
if rev_comps[nt] in nts:
minus_pos.append(pos)
test_d['+'][chrom] = plus_pos
test_d['-'][chrom] = minus_pos
e = time.time()
print 'The serial version took {} minutes...'.format((e-s)/60)
</code></pre>
<p>The output for yeast:</p>
<pre><code>The serial version took 0.0455190300941 minutes...
</code></pre>
<p>The output for human:</p>
<pre><code>The serial version took 10.1694028815 minutes...
</code></pre>
<p>I tried using numpy arrays rather than <code>enumerate()</code> and iteration:</p>
<pre><code>s = time.time()
for chrom in seq_d:
chrom_seq = np.array(list(seq_d[chrom]))
nts = list(nts)
rev_nts = [rev_comps[nt] for nt in nts]
plus_pos = list(np.where(np.in1d(chrom_seq, nts) == True)[0])
minus_pos = list(np.where(np.in1d(chrom_seq, rev_nts) == True)[0])
test_d['+'][chrom] = plus_pos
test_d['-'][chrom] = minus_pos
e = time.time()
print 'The numpy version took {} minutes...'.format((e-s)/60)
</code></pre>
<p>The output for yeast:</p>
<pre><code>The numpy version took 0.0309354345004 minutes...
</code></pre>
<p>The output for human:</p>
<pre><code>The numpy version took 9.86174853643 minutes...
</code></pre>
<p>Why does the numpy version lose its performance advantage for the larger human genome? Is there a faster way to do this? I tried implementing a version using <code>multiprocessing.Pool</code>, but that's slower than either version:</p>
<pre><code>def getTestHelper(chrom_seq, nts, rev_comp):
rev_comps = { 'A' : 'T', 'T' : 'A', 'G' : 'C', 'C' : 'G', 'N' : 'N'}
if rev_comp:
nts = [rev_comps[nt] for nt in nts]
else:
nts = list(nts)
chrom_seq = np.array(list(chrom_seq))
mask = np.in1d(chrom_seq, nts)
pos_l = list(np.where(mask == True)[0])
return pos_l
s = time.time()
pool = Pool(4)
plus_pos = pool.map(functools.partial(getTestHelper, nts=nts, rev_comp=False), seq_d.values())
minus_pos = pool.map(functools.partial(getTestHelper, nts=nts, rev_comp=True), seq_d.values())
e = time.time()
print 'The parallel version took {} minutes...'.format((e-s)/60)
</code></pre>
<p>I haven't run this on the human genome, but the yeast version is slower:</p>
<pre><code>The parallel version took 0.652778700987 minutes...
</code></pre>
| 2 | 2016-09-03T20:15:08Z | 39,311,165 | <h2>Use built-ins</h2>
<p>Instead of manually iterating through your long string, try <a href="https://docs.python.org/3/library/stdtypes.html#str.find" rel="nofollow"><code>str.find</code></a> or <a href="https://docs.python.org/3/library/stdtypes.html#str.index" rel="nofollow"><code>str.index</code></a>. Don't slice the string yourself, use these methods' built-in slicing.</p>
<p>This also ditches <code>enumerate</code>-ing, although that shouldn't be costly anyway.</p>
<p>Also, you could use <code>set</code> to store indices, not list - additions could be faster.</p>
<p>You would have to do it twice, though, to find both your nucleotide and its complement. Of course, look up the complement outside of the loop.</p>
<h2>Try regular expressions</h2>
<p>You could also try <a href="https://docs.python.org/3/library/re.html" rel="nofollow">regular expressions</a> to do the same thing (if you are going to try this, try both 2 regex (for "T" and "A") and one for "T|A").</p>
<p>Also, instead of doing</p>
<pre><code>for chrom in seq_d:
</code></pre>
<p>You could do</p>
<pre><code>for chromosome_number, chomosome in seq_d.items():
</code></pre>
<p>Which has little to do with performance, but makes the code more readable.</p>
| 3 | 2016-09-03T20:44:17Z | [
"python"
] |
What's the fastest way to find all occurences of the substring in large string in python | 39,310,956 | <p>Edited to clarify input/output. I think this will be somewhat slow no matter what, but up until now I haven't really considered speed in my python scripts, and I'm trying to figure out ways to speed up operations like these.</p>
<p>My input is pickled dictionaries of the genome sequences. I'm currently working with two genomes, the budding yeast genome (11.5 MB on disk), and the human genome (2.8 GB on disk). These dictionaries have the form:</p>
<pre><code>seq_d = { 'chr1' : 'ATCGCTCGCTGCTCGCT', 'chr2' : 'CGATCAGTCATGCATGCAT',
'chr3' : 'ACTCATCATCATCATACTGGC' }
</code></pre>
<p>I want to find all single-base instances of a nucleotide(s) in both strands of the genome. Where the <code>+</code> strand refers to the sequence in the above dictionary, and the <code>-</code> strand is the reverse complement of the sequences. My output is a nested dictionary, where the top level <code>keys</code> are <code>+</code> or <code>-</code>, the nested <code>keys</code> are chromosome names, and the values are lists of 0-indexed positions:</p>
<pre><code>nts = 'T'
test_d = {'+': {'chr3': [2, 5, 8, 11, 14, 17], 'chr2': [3, 7, 10, 14, 18],
'chr1': [1, 5, 9, 12, 16]}, '-': {'chr3': [0, 4, 7, 10, 13, 15],
'chr2': [2, 5, 9, 13, 17], 'chr1': [0]}}
</code></pre>
<p><code>test_d</code> defines a set of positions to examine in a large Illumina sequencing dataset later in the script.</p>
<p>My first attempt uses <code>enumerate</code>, and iteration.</p>
<pre><code>import time
import numpy as np
rev_comps = { 'A' : 'T', 'T' : 'A', 'G' : 'C', 'C' : 'G', 'N' : 'N'}
test_d = { '+' : {}, '-' : {}}
nts = 'T'
s = time.time()
for chrom in seq_d:
plus_pos, minus_pos = [], []
chrom_seq = seq_d[chrom]
for pos, nt in enumerate(chrom_seq):
if nt in nts:
plus_pos.append(pos)
if rev_comps[nt] in nts:
minus_pos.append(pos)
test_d['+'][chrom] = plus_pos
test_d['-'][chrom] = minus_pos
e = time.time()
print 'The serial version took {} minutes...'.format((e-s)/60)
</code></pre>
<p>The output for yeast:</p>
<pre><code>The serial version took 0.0455190300941 minutes...
</code></pre>
<p>The output for human:</p>
<pre><code>The serial version took 10.1694028815 minutes...
</code></pre>
<p>I tried using numpy arrays rather than <code>enumerate()</code> and iteration:</p>
<pre><code>s = time.time()
for chrom in seq_d:
chrom_seq = np.array(list(seq_d[chrom]))
nts = list(nts)
rev_nts = [rev_comps[nt] for nt in nts]
plus_pos = list(np.where(np.in1d(chrom_seq, nts) == True)[0])
minus_pos = list(np.where(np.in1d(chrom_seq, rev_nts) == True)[0])
test_d['+'][chrom] = plus_pos
test_d['-'][chrom] = minus_pos
e = time.time()
print 'The numpy version took {} minutes...'.format((e-s)/60)
</code></pre>
<p>The output for yeast:</p>
<pre><code>The numpy version took 0.0309354345004 minutes...
</code></pre>
<p>The output for human:</p>
<pre><code>The numpy version took 9.86174853643 minutes...
</code></pre>
<p>Why does the numpy version lose its performance advantage for the larger human genome? Is there a faster way to do this? I tried implementing a version using <code>multiprocessing.Pool</code>, but that's slower than either version:</p>
<pre><code>def getTestHelper(chrom_seq, nts, rev_comp):
rev_comps = { 'A' : 'T', 'T' : 'A', 'G' : 'C', 'C' : 'G', 'N' : 'N'}
if rev_comp:
nts = [rev_comps[nt] for nt in nts]
else:
nts = list(nts)
chrom_seq = np.array(list(chrom_seq))
mask = np.in1d(chrom_seq, nts)
pos_l = list(np.where(mask == True)[0])
return pos_l
s = time.time()
pool = Pool(4)
plus_pos = pool.map(functools.partial(getTestHelper, nts=nts, rev_comp=False), seq_d.values())
minus_pos = pool.map(functools.partial(getTestHelper, nts=nts, rev_comp=True), seq_d.values())
e = time.time()
print 'The parallel version took {} minutes...'.format((e-s)/60)
</code></pre>
<p>I haven't run this on the human genome, but the yeast version is slower:</p>
<pre><code>The parallel version took 0.652778700987 minutes...
</code></pre>
| 2 | 2016-09-03T20:15:08Z | 39,311,383 | <p>Finds the longest chromosome string, and creates an empty array with one row per chromosome, and columns up to the longest one in the dictionary. Then it puts each chromosome into its own row, where you can call <code>np.where</code> on the whole array</p>
<pre><code>import numpy as np
longest_chrom = max([len(x) for x in seq_d.values()])
genome_data = np.zeros((len(seq_d), dtype=str, longest_chrom)
for index, entry in enumerate(seq_d):
gen_string = list(seq_d[entry]
genome_data[index, :len(gen_string) + 1] = gen_string
nuc_search = "T"
nuc_locs = np.where(genome_data == nuc_search)
</code></pre>
<p>Using this method, it's slightly different for strings of > 1 nucleotide, but I'm sure it's achievable in only a couple more steps.</p>
| 0 | 2016-09-03T21:13:19Z | [
"python"
] |
What's the fastest way to find all occurences of the substring in large string in python | 39,310,956 | <p>Edited to clarify input/output. I think this will be somewhat slow no matter what, but up until now I haven't really considered speed in my python scripts, and I'm trying to figure out ways to speed up operations like these.</p>
<p>My input is pickled dictionaries of the genome sequences. I'm currently working with two genomes, the budding yeast genome (11.5 MB on disk), and the human genome (2.8 GB on disk). These dictionaries have the form:</p>
<pre><code>seq_d = { 'chr1' : 'ATCGCTCGCTGCTCGCT', 'chr2' : 'CGATCAGTCATGCATGCAT',
'chr3' : 'ACTCATCATCATCATACTGGC' }
</code></pre>
<p>I want to find all single-base instances of a nucleotide(s) in both strands of the genome. Where the <code>+</code> strand refers to the sequence in the above dictionary, and the <code>-</code> strand is the reverse complement of the sequences. My output is a nested dictionary, where the top level <code>keys</code> are <code>+</code> or <code>-</code>, the nested <code>keys</code> are chromosome names, and the values are lists of 0-indexed positions:</p>
<pre><code>nts = 'T'
test_d = {'+': {'chr3': [2, 5, 8, 11, 14, 17], 'chr2': [3, 7, 10, 14, 18],
'chr1': [1, 5, 9, 12, 16]}, '-': {'chr3': [0, 4, 7, 10, 13, 15],
'chr2': [2, 5, 9, 13, 17], 'chr1': [0]}}
</code></pre>
<p><code>test_d</code> defines a set of positions to examine in a large Illumina sequencing dataset later in the script.</p>
<p>My first attempt uses <code>enumerate</code>, and iteration.</p>
<pre><code>import time
import numpy as np
rev_comps = { 'A' : 'T', 'T' : 'A', 'G' : 'C', 'C' : 'G', 'N' : 'N'}
test_d = { '+' : {}, '-' : {}}
nts = 'T'
s = time.time()
for chrom in seq_d:
plus_pos, minus_pos = [], []
chrom_seq = seq_d[chrom]
for pos, nt in enumerate(chrom_seq):
if nt in nts:
plus_pos.append(pos)
if rev_comps[nt] in nts:
minus_pos.append(pos)
test_d['+'][chrom] = plus_pos
test_d['-'][chrom] = minus_pos
e = time.time()
print 'The serial version took {} minutes...'.format((e-s)/60)
</code></pre>
<p>The output for yeast:</p>
<pre><code>The serial version took 0.0455190300941 minutes...
</code></pre>
<p>The output for human:</p>
<pre><code>The serial version took 10.1694028815 minutes...
</code></pre>
<p>I tried using numpy arrays rather than <code>enumerate()</code> and iteration:</p>
<pre><code>s = time.time()
for chrom in seq_d:
chrom_seq = np.array(list(seq_d[chrom]))
nts = list(nts)
rev_nts = [rev_comps[nt] for nt in nts]
plus_pos = list(np.where(np.in1d(chrom_seq, nts) == True)[0])
minus_pos = list(np.where(np.in1d(chrom_seq, rev_nts) == True)[0])
test_d['+'][chrom] = plus_pos
test_d['-'][chrom] = minus_pos
e = time.time()
print 'The numpy version took {} minutes...'.format((e-s)/60)
</code></pre>
<p>The output for yeast:</p>
<pre><code>The numpy version took 0.0309354345004 minutes...
</code></pre>
<p>The output for human:</p>
<pre><code>The numpy version took 9.86174853643 minutes...
</code></pre>
<p>Why does the numpy version lose its performance advantage for the larger human genome? Is there a faster way to do this? I tried implementing a version using <code>multiprocessing.Pool</code>, but that's slower than either version:</p>
<pre><code>def getTestHelper(chrom_seq, nts, rev_comp):
rev_comps = { 'A' : 'T', 'T' : 'A', 'G' : 'C', 'C' : 'G', 'N' : 'N'}
if rev_comp:
nts = [rev_comps[nt] for nt in nts]
else:
nts = list(nts)
chrom_seq = np.array(list(chrom_seq))
mask = np.in1d(chrom_seq, nts)
pos_l = list(np.where(mask == True)[0])
return pos_l
s = time.time()
pool = Pool(4)
plus_pos = pool.map(functools.partial(getTestHelper, nts=nts, rev_comp=False), seq_d.values())
minus_pos = pool.map(functools.partial(getTestHelper, nts=nts, rev_comp=True), seq_d.values())
e = time.time()
print 'The parallel version took {} minutes...'.format((e-s)/60)
</code></pre>
<p>I haven't run this on the human genome, but the yeast version is slower:</p>
<pre><code>The parallel version took 0.652778700987 minutes...
</code></pre>
| 2 | 2016-09-03T20:15:08Z | 39,312,394 | <p>To be honest, I think you've been doing the right things.</p>
<p>There are a few more tweaks you can make to your code, though. In general, when performance is key, only do the bare minimum in your innermost loops. Looking through your code, there are still some quick optimizations left on this front:</p>
<ol>
<li>Use if...elif instead of if...if.</li>
<li>Don't use lists where you don't have to - e.g. just a single string is sufficient for nts and the reverse.</li>
<li>Don't evaluate the same result multiple times - e.g. the reverse lookup.</li>
</ol>
<p>I'm guessing that your problem with multi-processing is down to the serialization of these very large strings, offsetting any performance gain you might have from running in parallel. However, there may be another way to do this - see <a href="http://stackoverflow.com/questions/11442191/parallelizing-a-numpy-vector-operation">Parallelizing a Numpy vector operation</a>. I can't verify as I am having difficulty installing <code>numexpr</code>.</p>
<p>Putting them together and trying out some of the other suggestions in this trail, I get the following results:</p>
<pre><code>$ python test.py
Original serial took 0.08330821593602498 minutes...
Using sets took 0.09072601397832235 minutes...
Using built-ins took 0.061421032746632895 minutes...
Using regex took 0.11649663050969442 minutes...
Optimized serial took 0.05909080108006795 minutes...
Original numpy took 0.04050511916478475 minutes...
Optimized numpy took 0.03438538312911987 minutes...
</code></pre>
<p>My code is as follows.</p>
<pre><code>import time
import numpy as np
from random import choice
import re
# Create single large chromosome for the test...
seq = ""
for i in range(10000000):
seq += choice("ATGCN")
seq_d = {"Chromosome1": seq}
rev_comps = { 'A' : 'T', 'T' : 'A', 'G' : 'C', 'C' : 'G', 'N' : 'N'}
nts = 'T'
# Original serial implementation
def serial():
test_d = { '+' : {}, '-' : {}}
for chrom in seq_d:
plus_pos, minus_pos = [], []
chrom_seq = seq_d[chrom]
for pos, nt in enumerate(chrom_seq):
if nt in nts:
plus_pos.append(pos)
if rev_comps[nt] in nts:
minus_pos.append(pos)
test_d['+'][chrom] = plus_pos
test_d['-'][chrom] = minus_pos
# Optimized for single character tests
def serial2():
test_d = {'+': {}, '-': {}}
rev_nts = rev_comps[nts]
for chrom in seq_d:
plus_pos, minus_pos = [], []
chrom_seq = seq_d[chrom]
for pos, nt in enumerate(chrom_seq):
if nt == nts:
plus_pos.append(pos)
elif nt == rev_nts:
minus_pos.append(pos)
test_d['+'][chrom] = plus_pos
test_d['-'][chrom] = minus_pos
# Use sets instead of lists
def set_style():
test_d = { '+' : {}, '-' : {}}
for chrom in seq_d:
plus_pos, minus_pos = set(), set()
chrom_seq = seq_d[chrom]
for pos, nt in enumerate(chrom_seq):
if nt in nts:
plus_pos.add(pos)
if rev_comps[nt] in nts:
minus_pos.add(pos)
test_d['+'][chrom] = plus_pos
test_d['-'][chrom] = minus_pos
# Use regex to find either nucleotide...
def regex_it():
test_d = { '+' : {}, '-' : {}}
search = re.compile("(T|A)")
for chrom in seq_d:
pos = 0
plus_pos, minus_pos = [], []
chrom_seq = seq_d[chrom]
for sub_seq in search.split(chrom_seq):
if len(sub_seq) == 0:
continue
if sub_seq[0] == 'T':
plus_pos.append(pos)
elif sub_seq[0] == 'A':
minus_pos.append(pos)
pos += len(sub_seq)
test_d['+'][chrom] = plus_pos
test_d['-'][chrom] = minus_pos
# Use str.find instead of iteration
def use_builtins():
test_d = { '+' : {}, '-' : {}}
for chrom in seq_d:
plus_pos, minus_pos = [], []
chrom_seq = seq_d[chrom]
start = 0
while True:
pos = chrom_seq.find("T", start)
if pos == -1:
break
plus_pos.append(pos)
start = pos + 1
start = 0
while True:
pos = chrom_seq.find("A", start)
if pos == -1:
break
minus_pos.append(pos)
start = pos + 1
test_d['+'][chrom] = plus_pos
test_d['-'][chrom] = minus_pos
# Original numpy implementation
def numpy1():
test_d = { '+' : {}, '-' : {}}
for chrom in seq_d:
chrom_seq = np.array(list(seq_d[chrom]))
for_nts = list(nts)
rev_nts = [rev_comps[nt] for nt in nts]
plus_pos = list(np.where(np.in1d(chrom_seq, for_nts) == True)[0])
minus_pos = list(np.where(np.in1d(chrom_seq, rev_nts) == True)[0])
test_d['+'][chrom] = plus_pos
test_d['-'][chrom] = minus_pos
# Optimized for single character look-ups
def numpy2():
test_d = {'+': {}, '-': {}}
rev_nts = rev_comps[nts]
for chrom in seq_d:
chrom_seq = np.array(list(seq_d[chrom]))
plus_pos = np.where(chrom_seq == nts)
minus_pos = np.where(chrom_seq == rev_nts)
test_d['+'][chrom] = plus_pos
test_d['-'][chrom] = minus_pos
for fn, name in [
(serial, "Original serial"),
(set_style, "Using sets"),
(use_builtins, "Using built-ins"),
(regex_it, "Using regex"),
(serial2, "Optimized serial"),
(numpy1, "Original numpy"),
(numpy2, "Optimized numpy")]:
s = time.time()
fn()
e = time.time()
print('{} took {} minutes...'.format(name, (e-s)/60))
</code></pre>
| 1 | 2016-09-04T00:04:33Z | [
"python"
] |
How to align nodes and edges in networkx | 39,310,983 | <p>I am going through an O'Reilly data science book and it gives you the python code to more or less create this node viz ...</p>
<p><a href="http://i.stack.imgur.com/Cg5Bn.png" rel="nofollow"><img src="http://i.stack.imgur.com/Cg5Bn.png" alt="enter image description here"></a></p>
<p>But it doesn't tell you how to make the viz as its not really relevant to the subject but I wanted to take a crack at it anyway and so far this is as close as I've come </p>
<pre><code>users = [
{ "id": 0, "name": "Hero" },
{ "id": 1, "name": "Dunn" },
{ "id": 2, "name": "Sue" },
{ "id": 3, "name": "Chi" },
{ "id": 4, "name": "Thor" },
{ "id": 5, "name": "Clive" },
{ "id": 6, "name": "Hicks" },
{ "id": 7, "name": "Devin" },
{ "id": 8, "name": "Kate" },
{ "id": 9, "name": "Klein" },
{ "id": 10, "name": "Jen" }
]
friendships = [(0, 1), (0, 2), (1, 2), (1, 3), (2, 3), (3, 4),
(4, 5), (5, 6), (5, 7), (6, 8), (7, 8), (8, 9)]
import networkx as nx
import matplotlib as plt
%matplotlib inline
G=nx.Graph()
G.add_nodes_from([user["id"] for user in users])
G.add_edges_from(friendships)
pos = nx.spring_layout(G)
nx.draw_networkx(G, pos, node_size=1000)
</code></pre>
<p><a href="http://i.stack.imgur.com/xqxB7.png" rel="nofollow"><img src="http://i.stack.imgur.com/xqxB7.png" alt="enter image description here"></a></p>
<p>This is brand new to me both python and networkx - I can't seem to figure out from their documentation what actual graph I should be using - I tried just about every one of them and none get me there - is it possible in networkx to align nodes this way and what is the correct graph to use?</p>
<p>Is networkx the right tool for this job is there a better python lib for this task?</p>
<p><strong>UPDATE</strong></p>
<p>@Aric answer was perfect but I made a couple changes to make the nodes match the data rather than the static type array. I don't think this is the 'best' way to do the calculation someone with more python experience would know better. I played with the minimum sizes and positions for a bit and STILL I could not get it pixel perfect but still I'm pretty happy with the end result</p>
<pre><code>import networkx as nx
import matplotlib.pyplot as plt
G=nx.Graph()
G.add_nodes_from([user["id"] for user in users])
G.add_edges_from(friendships)
pos = {0: [0,0],
1: [4,-0.35],
2: [4,0.35],
3: [8,0],
4: [12,0],
5: [16,0],
6: [20,0.35],
7: [20,-0.35],
8: [24,0],
9: [28,0],
10: [32,0]}
nodes = [user["id"] for user in users]
def calcSize(node):
minSize = 450
friends = number_of_friends(node)
if friends <= 0:
return minSize
return minSize * friends
node_size = [(calcSize(user)) for user in users]
nx.draw_networkx(G, pos, nodelist=nodes, node_size=node_size, node_color='#c4daef')
plt.ylim(-1,1)
plt.axis('off')
</code></pre>
| 1 | 2016-09-03T20:19:08Z | 39,317,347 | <p>You can so something similar with NetworkX. You'll need use a different layout method than "spring_layout" or set the node positions explicitly like this:</p>
<pre><code>import networkx as nx
import matplotlib.pyplot as plt
G=nx.Graph()
G.add_nodes_from([user["id"] for user in users])
G.add_edges_from(friendships)
pos = {0: [0,0],
1: [1,-0.25],
2: [1,0.25],
3: [2,0],
4: [3,0],
5: [4,0],
6: [5,0.25],
7: [5,-0.25],
8: [6,0],
9: [7,0],
10: [8,0]}
nodes = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
node_size = [500, 1000, 1000, 1000, 500, 1000, 500, 500 , 1000, 300, 300]
nx.draw_networkx(G, pos, nodelist=nodes, node_size=node_size, node_color='#c4daef')
plt.ylim(-1,1)
plt.axis('off')
</code></pre>
<p><a href="http://i.stack.imgur.com/AilUV.png" rel="nofollow"><img src="http://i.stack.imgur.com/AilUV.png" alt="enter image description here"></a></p>
| 1 | 2016-09-04T13:20:12Z | [
"python",
"matplotlib",
"networkx"
] |
Q : Python time | 39,311,047 | <p>I would like to use ·time()· to launch an event. An example would be to <code>print("test")</code> for 3 seconds. For that I did this: </p>
<pre><code>from time import time, sleep
from random import random
t = time()
n = 3
print(n, time() - t)
for i in range(100):
sleep(0.04)
print(time() - t)
if time() - t > n:
print("test")
break
</code></pre>
<p>and it works! But in my game, in a while loop, it does not work... Why not?</p>
| 0 | 2016-09-03T20:26:36Z | 39,311,131 | <p>If I've understood correctly, it seems you don't know how to run a simple gameloop and run some test code after 3 seconds, here's some naive approach:</p>
<pre><code>from time import time, sleep
from random import random
start_time = time()
n = 3
while True:
elapsed_time = time() - start_time
sleep(0.04)
print(elapsed_time)
if elapsed_time > n:
print("test")
break
</code></pre>
| 0 | 2016-09-03T20:39:25Z | [
"python",
"python-2.7",
"time"
] |
Q : Python time | 39,311,047 | <p>I would like to use ·time()· to launch an event. An example would be to <code>print("test")</code> for 3 seconds. For that I did this: </p>
<pre><code>from time import time, sleep
from random import random
t = time()
n = 3
print(n, time() - t)
for i in range(100):
sleep(0.04)
print(time() - t)
if time() - t > n:
print("test")
break
</code></pre>
<p>and it works! But in my game, in a while loop, it does not work... Why not?</p>
| 0 | 2016-09-03T20:26:36Z | 39,311,357 | <p>if you want to achieve something else during the 3 second delay period, rather than just going round a while loop, try using a time-delayed thread. For example, the following </p>
<pre><code>import threading
import time
def afterThreeSec():
print("test")
return
t1 = threading.Timer(3, afterThreeSec)
t1.setName('t1')
t1.start()
print ("main")
time.sleep(1)
print ("main")
time.sleep(1)
print ("main")
time.sleep(1)
print ("main")
time.sleep(1)
print ("main")
</code></pre>
<p>gives the output:</p>
<pre><code>main
main
main
test
main
main
</code></pre>
| 0 | 2016-09-03T21:09:49Z | [
"python",
"python-2.7",
"time"
] |
How does distutils determine what binary files to copy? | 39,311,094 | <p>I have a <code>setup</code> command defined like this for distutils (using py2app for Mac OS X, if it matters):</p>
<pre><code>setup(...,
extensions=Extension('tracking_funcs',
['tracking_funcs/tracking_funcs.pyx'],
include_dirs=[numpyincludedirs,]),
Extension('_psutil_osx',
sources = ['psutil/_psutil_osx.c',
'psutil/_psutil_common.c',
'psutil/arch/osx/process_info.c'],
define_macros=[('PSUTIL_VERSION', int(get_psutilver().replace('.', '')))],
extra_link_args=['-framework', 'CoreFoundation',
'-framework', 'IOKit']),
Extension('_psutil_posix',
sources = ['psutil/_psutil_posix.c'])],
...)
</code></pre>
<p>It builds all three extensions correctly:</p>
<pre><code>...
building 'tracking_funcs' extension
creating build/bdist.macosx-10.6-x86_64/temp.macosx-10.6-x86_64-2.7/tracking_funcs
/usr/bin/clang -fno-strict-aliasing -fno-common -dynamic -arch i386 -arch x86_64 -g -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -I/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/numpy/core/include -I/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c tracking_funcs/tracking_funcs.c -o build/bdist.macosx-10.6-x86_64/temp.macosx-10.6-x86_64-2.7/tracking_funcs/tracking_funcs.o
... (some compiler warnings) ...
42 warnings generated.
/usr/bin/clang -bundle -undefined dynamic_lookup -arch i386 -arch x86_64 -g build/bdist.macosx-10.6-x86_64/temp.macosx-10.6-x86_64-2.7/tracking_funcs/tracking_funcs.o -o build/bdist.macosx-10.6-x86_64/lib.macosx-10.6-x86_64-2.7/tracking_funcs.so
building '_psutil_osx' extension
creating build/bdist.macosx-10.6-x86_64/temp.macosx-10.6-x86_64-2.7/psutil
... (some compiler warnings) ...
2 warnings generated.
/usr/bin/clang -fno-strict-aliasing -fno-common -dynamic -arch i386 -arch x86_64 -g -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -DPSUTIL_VERSION=400 -I/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c psutil/_psutil_common.c -o build/bdist.macosx-10.6-x86_64/temp.macosx-10.6-x86_64-2.7/psutil/_psutil_common.o
/usr/bin/clang -fno-strict-aliasing -fno-common -dynamic -arch i386 -arch x86_64 -g -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -DPSUTIL_VERSION=400 -I/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c psutil/arch/osx/process_info.c -o build/bdist.macosx-10.6-x86_64/temp.macosx-10.6-x86_64-2.7/psutil/arch/osx/process_info.o
/usr/bin/clang -bundle -undefined dynamic_lookup -arch i386 -arch x86_64 -g build/bdist.macosx-10.6-x86_64/temp.macosx-10.6-x86_64-2.7/psutil/_psutil_osx.o build/bdist.macosx-10.6-x86_64/lib.macosx-10.6-x86_64-2.7/_psutil_osx.so -framework CoreFoundation -framework IOKit
building '_psutil_posix' extension
/usr/bin/clang -fno-strict-aliasing -fno-common -dynamic -arch i386 -arch x86_64 -g -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -I/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c psutil/_psutil_posix.c -o build/bdist.macosx-10.6-x86_64/temp.macosx-10.6-x86_64-2.7/psutil/_psutil_posix.o
/usr/bin/clang -bundle -undefined dynamic_lookup -arch i386 -arch x86_64 -g build/bdist.macosx-10.6-x86_64/temp.macosx-10.6-x86_64-2.7/psutil/_psutil_posix.o -o build/dist.macosx-10.6-x86_64/lib.macosx-10.6-x86_64-2.7/_psutil_posix.so
...
</code></pre>
<p>Then it copies the built binaries into the package destination, but it only copies two of the three extensions:</p>
<pre><code>...
copying file /.../build/bdist.macosx-10.6-x86_64/lib.macosx-10.6-x86_64-2.7/tracking_funcs.so -> /.../dist/my.app/Contents/Resources/lib/python2.7/lib-dynload/tracking_funcs.so
copying file /.../build/bdist.macosx-10.6-x86_64/lib.macosx-10.6-x86_64-2.7/_psutil_posix.so -> /.../dist/my.app/Contents/Resources/lib/python2.7/lib-dynload/_psutil_posix.so
...
</code></pre>
<p>Then my application crashes because it can't find the third extension at runtime.</p>
<p>How can I debug this? Where does distutils get its dependency tree from, if not from the list of extensions I define? Perhaps the bug is in py2app rather than distutils itself?</p>
| 0 | 2016-09-03T20:34:14Z | 39,550,233 | <p>Py2app <a href="https://pythonhosted.org/py2app/implementation.html" rel="nofollow">uses</a> <a href="http://pythonhosted.org/modulegraph/index.html" rel="nofollow">modulegraph</a> to recursively build a source tree containing all the dependencies of all the dependencies of your project. Running py2app with the <a href="https://bitbucket.org/ronaldoussoren/py2app/src/149c25c413420120d3f383a9e854a17bc10d96fd/py2app/build_app.py?at=default&fileviewer=file-view-default#build_app.py-355" rel="nofollow"><code>debug-modulegraph</code></a> flag set will print a bunch of debugging information to the console and drop into <a href="https://bitbucket.org/ronaldoussoren/py2app/src/149c25c413420120d3f383a9e854a17bc10d96fd/py2app/build_app.py?at=default&fileviewer=file-view-default#build_app.py-945" rel="nofollow">a breakpoint</a> that allow you to browse the contents of the module graph:</p>
<pre><code>$ python setup.py py2app --debug-modulegraph
...
(Pdb) for item in mf.flatten(): print item
</code></pre>
<p>This will probably show something like <code>(MissingModule) psutil._psutil_osx</code> in its output, which means modulegraph isn't able to find the import path for that extension.</p>
<p>Modulegraph exposes a public function called <a href="https://bitbucket.org/ronaldoussoren/modulegraph/src/967aeeadd7a56f0bc3ea20fdb4d63d391fea0504/modulegraph/modulegraph.py?at=default&fileviewer=file-view-default#modulegraph.py-344" rel="nofollow"><code>addPackagePath</code></a> that will allow you to give it additional hints as to where it should look for files in particular packages. In this case, adding something like this in <code>setup.py</code> should resolve the issue:</p>
<pre><code>from modulegraph import modulegraph
modulegraph.addPackagePath('psutil', 'build/bdist.macosx-10.6-x86_64/lib.macosx-10.6-x86_64-2.7/psutil/')
</code></pre>
| 0 | 2016-09-17T18:20:09Z | [
"python",
"distutils",
"py2app"
] |
Is my threading proper ? if yes then why code is not working? | 39,311,172 | <p>I am creating an alarm clock in python using PyQt4 and in that I am using LCD display widget, which display current updating time. For that I am using threading. But I am new to it so the problem is I have no clue how to debug that thing.</p>
<p>This is my code</p>
<pre><code>import sys
from PyQt4 import QtGui, uic
import time
import os
from threading import Thread
class MyWindow(QtGui.QMainWindow):
def __init__(self):
super(MyWindow, self).__init__()
uic.loadUi('AlarmClock_UI.ui', self)
self.show()
self.comboBox.setCurrentIndex(0)
self.comboBox.currentIndexChanged.connect(self.getSelection)
self.lineEdit.setText('Please select the reminder type')
timeThread = Thread(target = self.showTime())
timeThread.start()
def getSelection(self):
if self.comboBox.currentIndex() == 1:
self.lineEdit.setText('Select the alarm time of your choice')
elif self.comboBox.currentIndex() == 2:
self.lineEdit.setText('Use those dials to adjust hour and minutes')
else:
self.lineEdit.setText('Please select the reminder type')
def showTime(self):
showTime = time.strftime('%H:%M:%S')
self.lcdNumber.display(showTime)
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
window = MyWindow()
sys.exit(app.exec_())
</code></pre>
<p>I tried while loop in <code>showTime()</code> function then it was not even loading GUI just running in the background.
Thanks :)</p>
| 0 | 2016-09-03T20:45:19Z | 39,313,242 | <p>Qt does not support doing GUI operations in threads other than the main thread. So when you call self.lcddisplay.display(showTime) from within the context of your spawned thread, that is an error and Qt will not work correctly.</p>
<p>As tdelaney suggested in his comment, the best way to handle this sort of thing is to use a QTimer to emit a signal at the appropriate intervals, and update your lcddisplay in the slot that signal is connected to. </p>
<p>(if you insist on using threads, however, e.g. as a learning exercise, then your spawned thread would need to send a message to the main thread to tell the main thread to do the display update, rather than trying to do the update itself)</p>
| 0 | 2016-09-04T03:21:13Z | [
"python",
"multithreading",
"pyqt4",
"lcd"
] |
Is my threading proper ? if yes then why code is not working? | 39,311,172 | <p>I am creating an alarm clock in python using PyQt4 and in that I am using LCD display widget, which display current updating time. For that I am using threading. But I am new to it so the problem is I have no clue how to debug that thing.</p>
<p>This is my code</p>
<pre><code>import sys
from PyQt4 import QtGui, uic
import time
import os
from threading import Thread
class MyWindow(QtGui.QMainWindow):
def __init__(self):
super(MyWindow, self).__init__()
uic.loadUi('AlarmClock_UI.ui', self)
self.show()
self.comboBox.setCurrentIndex(0)
self.comboBox.currentIndexChanged.connect(self.getSelection)
self.lineEdit.setText('Please select the reminder type')
timeThread = Thread(target = self.showTime())
timeThread.start()
def getSelection(self):
if self.comboBox.currentIndex() == 1:
self.lineEdit.setText('Select the alarm time of your choice')
elif self.comboBox.currentIndex() == 2:
self.lineEdit.setText('Use those dials to adjust hour and minutes')
else:
self.lineEdit.setText('Please select the reminder type')
def showTime(self):
showTime = time.strftime('%H:%M:%S')
self.lcdNumber.display(showTime)
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
window = MyWindow()
sys.exit(app.exec_())
</code></pre>
<p>I tried while loop in <code>showTime()</code> function then it was not even loading GUI just running in the background.
Thanks :)</p>
| 0 | 2016-09-03T20:45:19Z | 39,335,590 | <p>As has been said elsewhere, you do not need to use threading for this, as a simple timer will do. Here is a basic demo script:</p>
<pre><code>import sys
from PyQt4 import QtCore, QtGui
class Clock(QtGui.QLCDNumber):
def __init__(self):
super(Clock, self).__init__(8)
self.timer = QtCore.QTimer(self)
self.timer.timeout.connect(self.showTime)
self.timer.start(1000)
self.showTime()
def showTime(self):
time = QtCore.QTime.currentTime()
self.display(time.toString('hh:mm:ss'))
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
window = Clock()
window.setWindowTitle('Clock')
window.setGeometry(500, 100, 400, 100)
window.show()
sys.exit(app.exec_())
</code></pre>
| 0 | 2016-09-05T17:55:44Z | [
"python",
"multithreading",
"pyqt4",
"lcd"
] |
Django Internationalization (I18N) not changing text | 39,311,230 | <p>I created an simple website to test internationalization, but I can't make it work the way I wanted. I would like to change messages in my views.py without checking the <strong>request.LANGUAGE_CODE</strong> (which is showing correctly).</p>
<p>I can go to the urls with prefix <strong>/en/</strong> and <strong>/pt-br/</strong> but they don't change the text in the template. </p>
<p>I tried running </p>
<pre><code>django-admin makemessages --locale=pt_BR
</code></pre>
<p>I changed the lines</p>
<pre><code>#: mytest/views.py:7
msgid "Welcome to my site."
msgstr "Bem vindo ao meu site."
</code></pre>
<p>ran </p>
<pre><code>django-admin compilemessages --locale=pt_BR
</code></pre>
<p>PS: (even though it is wrong, I tried django-admin makemessages/compilemessages --locale=pt-br as well)</p>
<p>What I changed in <strong>settings.py</strong> (added my app, added locale middleware, added some internalization settings)</p>
<pre><code>INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'mytest'
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
# Internationalization
# https://docs.djangoproject.com/en/1.10/topics/i18n/
LOCALE_PATHS = [
os.path.join(BASE_DIR, 'locale/translations/'),
]
LANGUAGE_CODE = 'en-us'
from django.utils.translation import ugettext_lazy as _
LANGUAGES = [
('pt-br', _('Portuguese')),
('en', _('English')),
]
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
</code></pre>
<p><strong>views.py</strong></p>
<pre><code>from django.shortcuts import render
from django.utils.translation import ugettext_lazy as _
def index(request):
print(request.LANGUAGE_CODE) #this shows correctly the prefix in the url
output = _("Welcome to my site.")
context = {"test_translate": output}
return render(request, "mytest/index.html", context)
</code></pre>
<p><strong>urls.py</strong> </p>
<pre><code>from django.conf.urls.i18n import i18n_patterns
from mytest import views
urlpatterns = [
]
urlpatterns += i18n_patterns(
url(r'^$', views.index, name='index'),
)
</code></pre>
| 0 | 2016-09-03T20:52:44Z | 39,313,487 | <p>I think my path was not correct. I believe the extra slash was wrong... I deleted /translations/ from the LOCALE_PATH and it is working now.</p>
<pre><code>LOCALE_PATHS = [
os.path.join(BASE_DIR, 'locale'),
]
</code></pre>
<p>Then I run</p>
<pre><code>django-admin compilemessages -l pt_BR
</code></pre>
<p>Modify the *.po generated and run</p>
<pre><code>django-admin compilemessages -l pt_BR
</code></pre>
<p>I also renamed <strong>en-us</strong> to <strong>en</strong> in <code>LANGUAGE_CODE = 'en-us'</code></p>
| 0 | 2016-09-04T04:13:02Z | [
"python",
"django",
"django-i18n"
] |
Fitting text into a rectangle (width x by height y) with tkinter | 39,311,244 | <p>I'm trying to make a program which will fit text into a rectangle (x by y) depending on the text, the font and the font size</p>
<p>Here is the code</p>
<pre><code>def fit_text(screen, width, height, text, font):
measure_frame = Frame(screen) # frame
measure_frame.pack()
measure_frame.pack_forget()
measure = Label(measure_frame, font = font) # make a blank label
measure.grid(row = 0, column = 0) # put it in the frame
##########################################################
# make a certain number of lines
##########################################################
words = text.split(" ")
lines = []
num = 0
previous = 0
while num <= len(words):
measure.config(text = " ".join(words[previous:num])) # change text
line_width = measure.winfo_width() # get the width
print(line_width)
if line_width >= width: # if the line is now too long
lines.append(" ".join(words[previous:num - 1])) # add the last vsion which wasn't too long
previous = num - 1 # previous is now different
num = num + 1 # next word
lines.append(" ".join(words[previous:])) # add the rest of it
return "\n".join(lines)
from tkinter import *
window = Tk()
screen = Canvas(window)
screen.pack()
text = fit_text(screen, 200, 80, "i want to fit this text into a rectangle which is 200 pixels by 80 pixels", ("Purisa", 12))
screen.create_rectangle(100, 100, 300, 180)
screen.create_text(105, 105, text = text, font = ("Purisa", 12), anchor = "nw")
</code></pre>
<p>The problem with this is no matter what text is in the label the result from <code>measure.winfo_width()</code> is always 1. <a href="http://stackoverflow.com/questions/3950687/how-to-find-out-the-current-widget-size-in-tkinter">Here is where I found this from</a> but it doesn't seem to work for me</p>
| 0 | 2016-09-03T20:55:00Z | 39,311,345 | <p>The widget will not have a width until it is packed. You need to put the label into the frame, then pack it, then forget it.</p>
| 1 | 2016-09-03T21:08:17Z | [
"python",
"fonts",
"tkinter",
"widget",
"pixels"
] |
Fitting text into a rectangle (width x by height y) with tkinter | 39,311,244 | <p>I'm trying to make a program which will fit text into a rectangle (x by y) depending on the text, the font and the font size</p>
<p>Here is the code</p>
<pre><code>def fit_text(screen, width, height, text, font):
measure_frame = Frame(screen) # frame
measure_frame.pack()
measure_frame.pack_forget()
measure = Label(measure_frame, font = font) # make a blank label
measure.grid(row = 0, column = 0) # put it in the frame
##########################################################
# make a certain number of lines
##########################################################
words = text.split(" ")
lines = []
num = 0
previous = 0
while num <= len(words):
measure.config(text = " ".join(words[previous:num])) # change text
line_width = measure.winfo_width() # get the width
print(line_width)
if line_width >= width: # if the line is now too long
lines.append(" ".join(words[previous:num - 1])) # add the last vsion which wasn't too long
previous = num - 1 # previous is now different
num = num + 1 # next word
lines.append(" ".join(words[previous:])) # add the rest of it
return "\n".join(lines)
from tkinter import *
window = Tk()
screen = Canvas(window)
screen.pack()
text = fit_text(screen, 200, 80, "i want to fit this text into a rectangle which is 200 pixels by 80 pixels", ("Purisa", 12))
screen.create_rectangle(100, 100, 300, 180)
screen.create_text(105, 105, text = text, font = ("Purisa", 12), anchor = "nw")
</code></pre>
<p>The problem with this is no matter what text is in the label the result from <code>measure.winfo_width()</code> is always 1. <a href="http://stackoverflow.com/questions/3950687/how-to-find-out-the-current-widget-size-in-tkinter">Here is where I found this from</a> but it doesn't seem to work for me</p>
| 0 | 2016-09-03T20:55:00Z | 39,311,963 | <p>The problem with your code is that you're using the width of a widget, but the width will be 1 until the widget is actually laid out on the screen and made visible, since the actual width depends on a number of factors that aren't present until that happens.</p>
<p>You don't need to put the text in a widget in order to measure it. You can pass a string to <code>font.measure()</code> and it will return the amount of space required to render that string in the given font.</p>
<p>For python 3.x you can import the <code>Font</code> class like this:</p>
<pre><code>from tkinter.font import Font
</code></pre>
<p>For python 2.x you import it from the <code>tkFont</code> module:</p>
<pre><code>from tkFont import Font
</code></pre>
<p>You can then create an instance of <code>Font</code> so that you can get information about that font:</p>
<pre><code>font = Font(family="Purisa", size=18)
length = font.measure("Helli, world")
print "result:", length
</code></pre>
<p>You can also get the height of a line in a given font with the <code>font.metrics()</code> method, giving it the argument "linespace":</p>
<pre><code>height = font.metrics("linespace")
</code></pre>
| 1 | 2016-09-03T22:46:46Z | [
"python",
"fonts",
"tkinter",
"widget",
"pixels"
] |
Fitting text into a rectangle (width x by height y) with tkinter | 39,311,244 | <p>I'm trying to make a program which will fit text into a rectangle (x by y) depending on the text, the font and the font size</p>
<p>Here is the code</p>
<pre><code>def fit_text(screen, width, height, text, font):
measure_frame = Frame(screen) # frame
measure_frame.pack()
measure_frame.pack_forget()
measure = Label(measure_frame, font = font) # make a blank label
measure.grid(row = 0, column = 0) # put it in the frame
##########################################################
# make a certain number of lines
##########################################################
words = text.split(" ")
lines = []
num = 0
previous = 0
while num <= len(words):
measure.config(text = " ".join(words[previous:num])) # change text
line_width = measure.winfo_width() # get the width
print(line_width)
if line_width >= width: # if the line is now too long
lines.append(" ".join(words[previous:num - 1])) # add the last vsion which wasn't too long
previous = num - 1 # previous is now different
num = num + 1 # next word
lines.append(" ".join(words[previous:])) # add the rest of it
return "\n".join(lines)
from tkinter import *
window = Tk()
screen = Canvas(window)
screen.pack()
text = fit_text(screen, 200, 80, "i want to fit this text into a rectangle which is 200 pixels by 80 pixels", ("Purisa", 12))
screen.create_rectangle(100, 100, 300, 180)
screen.create_text(105, 105, text = text, font = ("Purisa", 12), anchor = "nw")
</code></pre>
<p>The problem with this is no matter what text is in the label the result from <code>measure.winfo_width()</code> is always 1. <a href="http://stackoverflow.com/questions/3950687/how-to-find-out-the-current-widget-size-in-tkinter">Here is where I found this from</a> but it doesn't seem to work for me</p>
| 0 | 2016-09-03T20:55:00Z | 39,312,199 | <p>I've actually stumbled across a way of doing this through trial and error</p>
<p>By using <code>measure.update_idletasks()</code> it calculates the width properly and it works! Bryan Oakley definitely has a more efficient way of doing it though but I think this method will be useful in other situations</p>
<p>P.S. I wouldn't mind some votes to get a nice, shiny, bronze, self-learner badge ;)</p>
| 1 | 2016-09-03T23:27:05Z | [
"python",
"fonts",
"tkinter",
"widget",
"pixels"
] |
Clicking on xpath button with Selenium on Python | 39,311,292 | <p>i used Selenium IDE on Firefox to find the <a href="http://i.stack.imgur.com/bcLp8.jpg" rel="nofollow">xpath of buttons.</a> The next step is to click the button on Python. I tried inserting the xpath in the code below, but no luck. I do not know how to change the xpath so that it fits to the code below.</p>
<pre><code>browser.find_element_by_xpath('')
</code></pre>
<p>Any help is appreciated!</p>
| 0 | 2016-09-03T21:02:05Z | 39,314,664 | <p>Be careful with quotes and double quotes, use double outside and simple inside, for example</p>
<pre><code>"//*[@class='myClass']"
</code></pre>
<p>Try this:</p>
<pre><code>browser.find_element_by_xpath("(//button[@type='button'])[20ââ9]")
</code></pre>
<p>You should get the selector manually in another way, this selector is not reliable at all, if any of the previous button is missing you will click the wrong button.</p>
| 1 | 2016-09-04T07:42:41Z | [
"python",
"python-3.x",
"selenium",
"xpath",
"selenium-webdriver"
] |
How can I avoid repetition in python/kivy? | 39,311,323 | <p>I have been trying to make an app that have many functions associate to one buttons each. This way, if I have 70 buttons I have 70 different functions. I want to add, the respective value, when I click respective button, to a respective variable label (I am using numericproperty). As the change between this functions is only in this numeric value, I would like to make this in a more inteligent way than I did. Have anybody one suggestion of better way to do it without I have to repeat my code? Very thanks everybody, and part of my code is bellow.</p>
<p>.py</p>
<pre><code>class SegundoScreen(Screen):
def __init__(self, **kwargs):
self.name = 'dois'
super(Screen,self).__init__(**kwargs)
def mucarela(self, *args):
screen4 = self.manager.get_screen('carrinho')
screen4.btn1 = BubbleButton(text="Muçarela", font_size='20dp', size_hint=(1,None), background_normal='1.png', background_down='2.png')
screen4.lb1 = Label(text="25,00", font_size='20dp', size_hint=(1,None))
screen4.ids.lb5.value += 25
screen4.ids.grid.add_widget(screen4.btn1)
screen4.ids.grid.add_widget(screen4.lb1)
def catupiry(self, *args):
screen4 = self.manager.get_screen('carrinho')
screen4.btn2 = BubbleButton(text="Catupiry",font_size='20dp', size_hint=(1,None), background_normal='2.png', background_down='1.png')
screen4.lb2 = Label(text="25,00",font_size='20dp', size_hint=(1,None))
screen4.ids.lb5.value += 25
screen4.ids.grid.add_widget(screen4.btn2)
screen4.ids.grid.add_widget(screen4.lb2)
def peru(self, *args):
screen4 = self.manager.get_screen('carrinho')
screen4.btn2 = BubbleButton(text="Peito de peru",font_size='20dp', size_hint=(1,None), background_normal='1.png', background_down='2.png')
screen4.lb2 = Label(text="95,00",font_size='20dp', size_hint=(1,None))
screen4.ids.lb5.value += 35
screen4.ids.grid.add_widget(screen4.btn2)
screen4.ids.grid.add_widget(screen4.lb2)
</code></pre>
<p>[...]</p>
<p>and .kv</p>
<pre><code>StackLayout:
orientation: 'tb-lr'
ScrollView:
size_hint: (1, .9)
pos_hint:{'x': .0, 'y': .0}
GridLayout:
cols: 2
padding: 45, 50
spacing: 25, 50
size_hint: (1, 1)
size_hint_y: None
height: self.minimum_height
width: 500
Label:
text: "[b]Escolha[/b]\n[i]Sabor[/i]"
markup: True
font_size: '20dp'
size_hint_y: None
height: self.texture_size[1]
Label:
text: "[b]Preço\n[/b] [i](R$)[/i]"
markup: True
font_size: '20dp'
size_hint_y: None
height: self.texture_size[1]
Button:
text: "[b]Muçarela[/b]\n[i]Muçarela, tomate\n e orégano[/i]"
markup: True
font_size: '20dp'
size_hint_y: None
height: self.texture_size[1]
background_normal:'1.png'
background_down:'2.png'
on_press: root.mucarela()
Label:
text: "25,00"
markup: True
font_size: '20dp'
size_hint_y: None
height: self.texture_size[1]
Button:
text: "[b]Catupiry[/b]\n[i]Catupiry, azeitona\n e tomate[/i]"
markup: True
font_size: '20dp'
size_hint_y: None
height: self.texture_size[1]
background_normal:'2.png'
background_down:'1.png'
on_press: root.catupiry()
Label:
text: "25,00"
markup: True
font_size: '20dp'
size_hint_y: None
height: self.texture_size[1]
Button:
text: "[b]Peito de peru[/b]\n[i]Muçarela, peito de peru\n e tomate[/i]"
markup: True
font_size: '20dp'
size_hint_y: None
height: self.texture_size[1]
background_normal:'1.png'
background_down:'2.png'
on_press: root.peru()
Label:
text: "35,00"
markup: True
font_size: '20dp'
size_hint_y: None
height: self.texture_size[1]
Button:
text: "[b]Portuguesa[/b]\n[i]Muçarela, presunto,\n cebola e ovo[/i]"
markup: True
font_size: '20dp'
size_hint_y: None
height: self.texture_size[1]
background_normal:'2.png'
background_down:'1.png'
on_press: root.portuguesa()
Label:
text: "27,00"
markup: True
font_size: '20dp'
size_hint_y: None
height: self.texture_size[1]
Button:
text: "[b]Toscana[/b]\n[i]Calabresa moÃda, muçarela\ne parmesão[/i]"
markup: True
font_size: '20dp'
size_hint_y: None
height: self.texture_size[1]
background_normal:'1.png'
background_down:'2.png'
on_press: root.toscana()
Label:
text: "35,00"
markup: True
font_size: '20dp'
size_hint_y: None
height: self.texture_size[1]
</code></pre>
<p>and I have more one class form that is just one label numericpropertie whose change the value when respective button has clicked. As the change is only in this label, I am locking for how can I take the price value from the text label, and flavor name from the text button. Very thanks.</p>
| 0 | 2016-09-03T21:06:18Z | 39,317,460 | <p>for your .kv file I recommend using Classes like</p>
<pre><code><MyButton@Button>:
markup: True
font_size: '20dp'
size_hint_y: None
</code></pre>
<p>then in your code you could use instances of MyButton which could minify your code a little bit.</p>
| 0 | 2016-09-04T13:32:13Z | [
"python",
"kivy"
] |
Measure Tomcat's Shutdown Interval | 39,311,344 | <p>I am trying to measure my Tomcat server shutdown interval and write it to the log. I'm trying to use the following Python code:</p>
<pre><code> log_times.append(datetime.now().strftime(TIME_PATTERN)) # logs start time
subprocess.check_call(['service', 'tomcat7', 'stop'])
pid = subprocess.Popen(['pgrep', '-utomcat7'], stdout=subprocess.PIPE).communicate()[0]
while (pid != ''):
log.info('pgrep found tomcat process: %s', pid)
pid = subprocess.Popen(['pgrep', '-utomcat7'], stdout=subprocess.PIPE).communicate()[0]
log_times.append(datetime.now().strftime(TIME_PATTERN)) # logs tomcat shutdown time
</code></pre>
<p>Is there a better \ accurate way to do this ?</p>
| 0 | 2016-09-03T21:08:08Z | 39,312,079 | <p>You can try use a bash script. For example stop_tomcat.sh:</p>
<pre><code>START=$(date +%s.%N)
service tomcat7 stop
END=$(date +%s.%N)
DIFF=$(echo "$END - $START" | bc)
echo $DIFF
</code></pre>
<p>Change permissions :</p>
<pre><code>chmod 755
</code></pre>
<p>call it from python and take it stdout :</p>
<pre><code>time = subprocess.Popen(['./stop_tomcat.sh'], stdout=subprocess.PIPE).communicate()[0]
</code></pre>
<p>More details about measuring time in bash <a href="http://unix.stackexchange.com/a/12069">http://unix.stackexchange.com/a/12069</a>. </p>
| 0 | 2016-09-03T23:07:18Z | [
"java",
"python",
"tomcat"
] |
sleekxmpp with ejabberd muc | 39,311,417 | <p>I want to make a muc scprit with sleekxmpp and ejabberd use.
What should I do?</p>
<p>I tried this tutorial to understand eating sleekxmpp <a href="http://sleekxmpp.com/getting_started/echobot.html" rel="nofollow">http://sleekxmpp.com/getting_started/echobot.html</a>
but, number of connected users at the ejabberd panel kept getting pulled over 0</p>
<p>code:</p>
<pre><code>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import logging
import getpass
from optparse import OptionParser
import sleekxmpp
# Python versions before 3.0 do not use UTF-8 encoding
# by default. To ensure that Unicode is handled properly
# throughout SleekXMPP, we will set the default encoding
# ourselves to UTF-8.
if sys.version_info < (3, 0):
reload(sys)
sys.setdefaultencoding('utf8')
else:
raw_input = input
class EchoBot(sleekxmpp.ClientXMPP):
"""
A simple SleekXMPP bot that will echo messages it
receives, along with a short thank you message.
"""
def __init__(self, jid, password):
sleekxmpp.ClientXMPP.__init__(self, jid, password)
# The session_start event will be triggered when
# the bot establishes its connection with the server
# and the XML streams are ready for use. We want to
# listen for this event so that we we can initialize
# our roster.
self.add_event_handler("session_start", self.start)
# The message event is triggered whenever a message
# stanza is received. Be aware that that includes
# MUC messages and error messages.
self.add_event_handler("message", self.message)
def start(self, event):
"""
Process the session_start event.
Typical actions for the session_start event are
requesting the roster and broadcasting an initial
presence stanza.
Arguments:
event -- An empty dictionary. The session_start
event does not provide any additional
data.
"""
self.send_presence()
self.get_roster()
def message(self, msg):
"""
Process incoming message stanzas. Be aware that this also
includes MUC messages and error messages. It is usually
a good idea to check the messages's type before processing
or sending replies.
Arguments:
msg -- The received message stanza. See the documentation
for stanza objects and the Message stanza to see
how it may be used.
"""
if msg['type'] in ('chat', 'normal'):
msg.reply("Thanks for sending\n%(body)s" % msg).send()
if __name__ == '__main__':
# Setup the command line arguments.
optp = OptionParser()
# Output verbosity options.
optp.add_option('-q', '--quiet', help='set logging to ERROR',
action='store_const', dest='loglevel',
const=logging.ERROR, default=logging.INFO)
optp.add_option('-d', '--debug', help='set logging to DEBUG',
action='store_const', dest='loglevel',
const=logging.DEBUG, default=logging.INFO)
optp.add_option('-v', '--verbose', help='set logging to COMM',
action='store_const', dest='loglevel',
const=5, default=logging.INFO)
# JID and password options.
optp.add_option("-j", "--jid", dest="jid",
help="JID to use")
optp.add_option("-p", "--password", dest="password",
help="password to use")
opts, args = optp.parse_args()
# Setup logging.
logging.basicConfig(level=opts.loglevel,
format='%(levelname)-8s %(message)s')
if opts.jid is None:
opts.jid = raw_input("Username: ")
if opts.password is None:
opts.password = getpass.getpass("Password: ")
# Setup the EchoBot and register plugins. Note that while plugins may
# have interdependencies, the order in which you register them does
# not matter.
xmpp = EchoBot(opts.jid, opts.password)
xmpp.register_plugin('xep_0030') # Service Discovery
xmpp.register_plugin('xep_0004') # Data Forms
xmpp.register_plugin('xep_0060') # PubSub
xmpp.register_plugin('xep_0199') # XMPP Ping
# If you are working with an OpenFire server, you may need
# to adjust the SSL version used:
# xmpp.ssl_version = ssl.PROTOCOL_SSLv3
# If you want to verify the SSL certificates offered by a server:
# xmpp.ca_certs = "path/to/ca/cert"
# Connect to the XMPP server and start processing XMPP stanzas.
if xmpp.connect():
# If you do not have the dnspython library installed, you will need
# to manually specify the name of the server if it does not match
# the one in the JID. For example, to use Google Talk you would
# need to use:
#
# if xmpp.connect(('talk.google.com', 5222)):
# ...
xmpp.process(block=True)
print("Done")
else:
print("Unable to connect.")
</code></pre>
<p>console output:</p>
<pre><code>DEBUG Loaded Plugin: RFC 6120: Stream Feature: STARTTLS
DEBUG Loaded Plugin: RFC 6120: Stream Feature: Resource Binding
DEBUG Loaded Plugin: RFC 3920: Stream Feature: Start Session
DEBUG Loaded Plugin: RFC 6121: Stream Feature: Roster Versioning
DEBUG Loaded Plugin: RFC 6121: Stream Feature: Subscription Pre-Approval
DEBUG Loaded Plugin: RFC 6120: Stream Feature: SASL
DEBUG Loaded Plugin: XEP-0030: Service Discovery
DEBUG Loaded Plugin: XEP-0004: Data Forms
DEBUG Loaded Plugin: XEP-0082: XMPP Date and Time Profiles
DEBUG Loaded Plugin: XEP-0131: Stanza Headers and Internet Metadata
DEBUG Loaded Plugin: XEP-0060: Publish-Subscribe
DEBUG Loaded Plugin: XEP-0199: XMPP Ping
DEBUG Connecting to 192.168.1.103:5222
DEBUG Event triggered: connected
DEBUG ==== TRANSITION disconnected -> connected
DEBUG Starting HANDLER THREAD
DEBUG Loading event runner
DEBUG SEND (IMMED): <stream:stream to='192.168.1.103' xmlns:stream='http://etherx.jabber.org/streams' xmlns='jabber:client' xml:lang='en' version='1.0'>
DEBUG RECV: <stream:stream from="localhost" id="3423333123714766535" xml:lang="en">
WARNING Legacy XMPP 0.9 protocol detected.
DEBUG Event triggered: legacy_protocol
DEBUG RECV: <stream:error xmlns="http://etherx.jabber.org/streams"><host-unknown xmlns="urn:ietf:params:xml:ns:xmpp-streams" /></stream:error>
DEBUG Event triggered: stream_error
DEBUG End of stream recieved
DEBUG reconnecting...
DEBUG Event triggered: session_end
DEBUG SEND (IMMED): </stream:stream>
INFO Waiting for </stream:stream> from server
DEBUG Event triggered: socket_error
DEBUG Event triggered: disconnected
DEBUG ==== TRANSITION connected -> disconnected
DEBUG connecting...
DEBUG Waiting 1.98786049338 seconds before connecting.
</code></pre>
| 0 | 2016-09-03T21:16:52Z | 39,315,726 | <p>Here is the problem:</p>
<pre class="lang-xml prettyprint-override"><code>DEBUG SEND (IMMED): <stream:stream to='192.168.1.103' xmlns:stream='http://etherx.jabber.org/streams' xmlns='jabber:client' xml:lang='en' version='1.0'>
DEBUG RECV: <stream:stream from="localhost" id="3423333123714766535" xml:lang="en">
WARNING Legacy XMPP 0.9 protocol detected.
DEBUG Event triggered: legacy_protocol
DEBUG RECV: <stream:error xmlns="http://etherx.jabber.org/streams"><host-unknown xmlns="urn:ietf:params:xml:ns:xmpp-streams" /></stream:error>
DEBUG Event triggered: stream_error
DEBUG End of stream recieved
</code></pre>
<p>Your client is opening a stream to <code>192.168.1.103</code>, but you get a response that says it is from <code>localhost</code>, and then you get a <code>host-unknown</code> error. (I presume you entered the JID as <code>echobot@192.168.1.103</code>?)</p>
<p>Your ejabberd is configured to use the hostname <code>localhost</code>. Change that to <code>192.168.1.103</code> in the configuration file, and you'll be able to connect using that "hostname".</p>
<p>Alternatively, you could enter the JID as <code>echobot@localhost</code>, and force the connection to use a different host, by doing what the comment in the code says about Google Talk:</p>
<pre class="lang-py prettyprint-override"><code>if xmpp.connect(('192.168.1.103', 5222)):
</code></pre>
<p>This would work with the current ejabberd configuration.</p>
| 0 | 2016-09-04T10:00:31Z | [
"python",
"xmpp",
"ejabberd",
"multiuserchat"
] |
Running Ipython Notebook on Mac | 39,311,481 | <p>Have a question.</p>
<p>I know that Ipython Notebook can be opened by entering <code>ipython notebook</code> in terminal on macOS. But is there another option to run it? for example, using some nice app or smth.</p>
<p>Thanks!</p>
| 0 | 2016-09-03T21:24:14Z | 39,326,867 | <p>If you are using Anaconda, you can use the <a href="https://docs.continuum.io/anaconda-launcher/" rel="nofollow">anaconda launcher</a>. If you don't have it, you can install it with:</p>
<pre><code>conda install launcher
</code></pre>
<p>This will install an application called Launcher which will give you a GUI to launch notebooks (and other things).</p>
| 0 | 2016-09-05T08:47:41Z | [
"python",
"osx",
"ipython",
"anaconda",
"jupyter-notebook"
] |
How to scrape value from page that loads dynamicaly? | 39,311,545 | <p>The homepage of the website I'm trying to scrape displays four tabs, one of which reads "[Number] Available Jobs". I'm interested in scraping the [Number] value. When I inspect the page in Chrome, I can see the value enclosed within a <code><span></code> tag.</p>
<p><a href="http://i.stack.imgur.com/xeirT.png" rel="nofollow"><img src="http://i.stack.imgur.com/xeirT.png" alt="enter image description here"></a></p>
<p>However, there is nothing enclosed in that <code><span></code> tag when I view the page source directly. I was planning on using the Python <code>requests</code> module to make an HTTP GET request and then use regex to capture the value from the returned content. This is obviously not possible if the content doesn't contain the number I need.</p>
<p>My questions are:</p>
<ol>
<li><p>What is happening here? How can a value be dynamically loaded into a
page, displayed, and then not appear within the HTML source?</p></li>
<li><p>If the value doesn't appear in the page source, what can I do to
reach it?</p></li>
</ol>
| 0 | 2016-09-03T21:36:14Z | 39,311,664 | <p>1.A value can be loaded dynamically with ajax, ajax loads asynchronously that means that the rest of the site does not wait for ajax to be rendered, that's why when you get the DOM the elements loaded with ajax does not appear in it.</p>
<p>2.For scraping dynamic content you should use selenium, <a href="http://thiagomarzagao.com/2013/11/12/webscraping-with-selenium-part-1/" rel="nofollow">here a tutorial</a> </p>
| 0 | 2016-09-03T21:54:32Z | [
"python",
"html",
"httprequest",
"httpresponse"
] |
How to scrape value from page that loads dynamicaly? | 39,311,545 | <p>The homepage of the website I'm trying to scrape displays four tabs, one of which reads "[Number] Available Jobs". I'm interested in scraping the [Number] value. When I inspect the page in Chrome, I can see the value enclosed within a <code><span></code> tag.</p>
<p><a href="http://i.stack.imgur.com/xeirT.png" rel="nofollow"><img src="http://i.stack.imgur.com/xeirT.png" alt="enter image description here"></a></p>
<p>However, there is nothing enclosed in that <code><span></code> tag when I view the page source directly. I was planning on using the Python <code>requests</code> module to make an HTTP GET request and then use regex to capture the value from the returned content. This is obviously not possible if the content doesn't contain the number I need.</p>
<p>My questions are:</p>
<ol>
<li><p>What is happening here? How can a value be dynamically loaded into a
page, displayed, and then not appear within the HTML source?</p></li>
<li><p>If the value doesn't appear in the page source, what can I do to
reach it?</p></li>
</ol>
| 0 | 2016-09-03T21:36:14Z | 39,311,673 | <p>If the content doesn't appear in the page source then it is probably generated using javascript. For example the site might have a REST API that lists jobs, and the Javascript code could request the jobs from the API and use it to create the node in the DOM and attach it to the available jobs. That's just one possibility.</p>
<p>One way to scrap this information is to figure out how that javascript works and make your python scraper do the same thing (for example, if there is a simple REST API it is using, you just need to make a request to that same URL). Often that is not so easy, so another alternative is to do your scraping using a javascript capable browser like selenium.</p>
<p>One final thing I want to mention is <a href="http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454">that regular expressions are a fragile way to parse HTML</a>, you should generally prefer to use a library like BeautifulSoup.</p>
| 2 | 2016-09-03T21:55:37Z | [
"python",
"html",
"httprequest",
"httpresponse"
] |
How to scrape value from page that loads dynamicaly? | 39,311,545 | <p>The homepage of the website I'm trying to scrape displays four tabs, one of which reads "[Number] Available Jobs". I'm interested in scraping the [Number] value. When I inspect the page in Chrome, I can see the value enclosed within a <code><span></code> tag.</p>
<p><a href="http://i.stack.imgur.com/xeirT.png" rel="nofollow"><img src="http://i.stack.imgur.com/xeirT.png" alt="enter image description here"></a></p>
<p>However, there is nothing enclosed in that <code><span></code> tag when I view the page source directly. I was planning on using the Python <code>requests</code> module to make an HTTP GET request and then use regex to capture the value from the returned content. This is obviously not possible if the content doesn't contain the number I need.</p>
<p>My questions are:</p>
<ol>
<li><p>What is happening here? How can a value be dynamically loaded into a
page, displayed, and then not appear within the HTML source?</p></li>
<li><p>If the value doesn't appear in the page source, what can I do to
reach it?</p></li>
</ol>
| 0 | 2016-09-03T21:36:14Z | 39,324,761 | <ol>
<li>for data that load dynamically you should look for an xhr request in the networks and if you can make that data productive for you than voila!! </li>
<li>you can you phantom js, it's a headless browser and it captures the html of that page with the dynamically loaded content. </li>
</ol>
| 0 | 2016-09-05T06:10:40Z | [
"python",
"html",
"httprequest",
"httpresponse"
] |
Can't import my own module distributed with distutils | 39,311,658 | <p>I'd like to package my application to share it between several projects.
My setup.py looks like this:</p>
<pre><code># -*- coding: utf-8 -*-
from distutils.core import setup
setup(
name='foo_bar',
version='1.0',
py_modules=['foo_bar'],
install_requires=[
'bitstring==3.1.5',
'pytz==2016.4',
'wheel==0.24.0', ]
)
</code></pre>
<p>Then I run command</p>
<pre><code>python setup.py sdist
</code></pre>
<p>that creates tar.gz file for me</p>
<p>I'm having trouble with using my foo_bar application. I'm installing it into separate virtualenv via pip</p>
<pre><code>pip install dist/foo_bar.tar.gz
</code></pre>
<p>and output of pip freeze suggests that it is installed</p>
<pre><code>foo-bar==1.0
bitstring==3.1.5
pytz==2016.4
wheel==0.24.0
</code></pre>
<p>When I try to import this module in python console</p>
<pre><code>import foo_bar
</code></pre>
<p>I get <code>ImportError: No module named 'foo_bar'</code></p>
<p>What I'm missing?</p>
<p>Edit:</p>
<p>My file structure looks like this:</p>
<pre><code>foo_bar
âââ dist
â  âââ foo_bar-1.0.tar.gz
âââ __init__.py
âââ MANIFEST
âââ bar.py
âââ requirements.txt
âââ setup.py
</code></pre>
| 1 | 2016-09-03T21:52:38Z | 39,407,522 | <p>Could you provide your directory structure? Are you in the same virtualenv when you're trying to import your module? Why are you using <code>py_modules</code> and not <code>packages</code>?</p>
<p>Moreover, you're trying to import <code>foo_bar</code>, however there is no <code>foo_bar.py</code> in your package! Try to rename <code>bar.py</code> to that name.</p>
<p>Note: I've never used packages this way. Usually you create a package (directory with <code>__init__.py</code> file) on the same level as <code>setup.py</code> is. This means, that you would create another <code>foo_bar</code> dir in you project and there you would place <code>bar.py</code>. Then you would import it like <code>import foo_bar.bar</code>.</p>
| 1 | 2016-09-09T08:50:22Z | [
"python",
"pip",
"importerror",
"distutils"
] |
Beautifulsoup - scraping everything but table data | 39,311,702 | <p>Hi I'm new to python and currently trying to download data from a table on a website (<a href="http://www.pa.org.mt/AppList?ReceivedDate=2016-8-31" rel="nofollow">http://www.pa.org.mt/AppList?ReceivedDate=2016-8-31</a>)</p>
<p>I've tried many different solutions but everything I try keeps returning an empty list. I read that the problem might be that the table is loaded using Javascript however when I switch off Javascript the table remains, and I can obviously see the data I want when I view the source code. </p>
<p>I am using python 2.7</p>
<p>When I run this code:</p>
<pre><code>from bs4 import BeautifulSoup
import urllib2
url = 'http://www.pa.org.mt/AppList?ReceivedDate=2016-8-31
page = urllib2.urlopen(url)
soup = BeautifulSoup(page, 'html.parser')
print soup
</code></pre>
<p>Where the table should be I get:</p>
<pre><code><link href="appsearch/main.css" rel="stylesheet" type="text/css" />
<TABLE id="Table1" cellSpacing="1" cellPadding="1" width="100%" border="0">
<TR>
<TD align=center>
<br />
<br />
</TD>
</TR>
<TR>
<TD>
</TD>
</TR>
</TABLE>
</code></pre>
<p>When I view the page source code however I can see the information I want (I've copied and pasted a small part of it </p>
<pre><code><TD align=center>
<p align='center' class='H1'><u>Planning Authority Applications Received (Planning Applications Outside Development Zone)</u></p><p align='center'>Result For Date 2016-8-31</p><p align='center'>Result output on 03/09/2016 23:23:29</p><strong><i>Disclaimer</strong>: The information ....in accordance with the Development Planning Act.</i>
<br />
<br />
</TD>
</TR>
<TR>
<TD>
<table class='formTable'><tr><td class='sectionHeading' colspan=2>Application Details</td></tr></table><table class='formTable'><TR><td class='sectionHeading'>Case Number</td><td class='sectionHeading'>Location</td><td class='sectionHeading'>Proposal</td><td class='sectionHeading'>Applicant</td><td class='sectionHeading'>Architect</td><td class='sectionHeading'>Case Category</td><td class='sectionHeading'>Local Council</td></tr><TR><td class='fieldData'><a href='SearchPA?Systemkey=166837&CaseFullRef=PA/05054/1
</code></pre>
<p>I would be great if you could give me any suggestions or point me in the direction of any material that might help me out. </p>
<p>As I said earlier, I'm new to both python and stackoverflow so my apologies if a similar question has already been answered or if I haven't given the right information. </p>
<p>Thanks</p>
| 2 | 2016-09-03T22:01:06Z | 39,312,342 | <p>If you clear your cache and go directly to <em><a href="http://www.pa.org.mt/appsreceived?month=01/08/2016" rel="nofollow">http://www.pa.org.mt/appsreceived?month=01/08/2016</a></em> you see no data at all just like you see in your own output:</p>
<p><a href="http://i.stack.imgur.com/2Wo7T.png" rel="nofollow"><img src="http://i.stack.imgur.com/2Wo7T.png" alt="enter image description here"></a></p>
<p>You need to use a session and visit the page preceding the page you want first:</p>
<pre><code>import requests
head = {"User-Agent":"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36"}
with requests.Session() as s:
s.headers.update(head)
s.get("http://www.pa.org.mt/appsreceived?CaseType=PA&Category=PAI")
r2 = (s.get("http://www.pa.org.mt/AppList?ReceivedDate=2016-8-31"))
print(r2.content)
</code></pre>
<p>Now the next problem, the html is broken so html.parse will not get what you want:</p>
<pre><code>In [4]: with requests.Session() as s:
...: s.headers.update(head)
...: r= s.get("http://www.pa.org.mt/appsreceived?CaseType=PA&Category=PAI")
...: page = (s.get("http://www.pa.org.mt/AppList?ReceivedDate=2016-8-31").content)
...: soup = BeautifulSoup(page, 'html.parser')
...: print(soup.select_one("#Table1"))
...:
<table border="0" cellpadding="1" cellspacing="1" id="Table1" width="100%">
<tr>
<td align="center">
<p align="center" class="H1"><u>Planning Authority Applications Received (Planning Applications Within Development Zone)</u></p><p align="center">Result For Date 2016-8-31</p><p align="center">Result output on 04/09/2016 01:56:44</p><strong><i>Disclaimer</i></strong>: The information below has been extracted from an on-line database and is meant only for your general guidance.The Planning Authority disclaims any responsibility for any inaccuracies there may be on this site. If you wish to verify the correctness of any information then you are advised to contact us directly. Furtheremore, in the event of any discrepancies between the information contained on this site and official printed communication then the latter is to prevail, in accordance with the Development Planning Act.</td></tr></table>
</code></pre>
<p><em>lxml</em> or <em>html5lib</em> will, I won't add the output as it is quite large but using either parser will give you the full table data.</p>
| 2 | 2016-09-03T23:53:47Z | [
"python",
"html",
"css",
"beautifulsoup"
] |
creating a for loop where xpath increases | 39,311,773 | <p>I am trying to create a for loop where xpath buttons are to be clicked for x times. There is a list of xpathes</p>
<pre><code>(//button[@type='button'])[47]
(//button[@type='button'])[65]
(//button[@type='button'])[83]
(//button[@type='button'])[101]
(//button[@type='button'])[119]
</code></pre>
<p>So the numbers in xpathes increases by 18 and this goes up to millions.
The Program i'm trying to create will ask me how many times to click the xpath buttons. Let's say i input 5 times. Here's where i have my problem. I can't make a for loop where the number increases by 18 everytime it clicks an xpath button. I tried</p>
<pre><code>browser.find_element_by_xpath("(//button[@type='button'])[int(x)]").click()
</code></pre>
<p>so that i can add 18 to integer x, but failed. Any help is appreciated.
Here is what the code will look like</p>
<pre><code>print('How many times do you want to click?')
times = input()
x = 47
for i in range(0,int(times), 18):
browser.find_element_by_xpath("(//button[@type='button'])['str(x)']").click()
</code></pre>
<p>To be more specific, </p>
<p>first i type in x = 47 then i type in, </p>
<p><code>browser.find_element_by_xpath("(//button[@type='button'])[inâât(x)]").click()</code> </p>
<p>and syntax error. but when i type in </p>
<p><code>browser.find_element_by_xpath("(//button[@type='button'])[47ââ]").click()</code> </p>
<p>it runs normally. I'm trying to change the number '47' with a variable i assigned.</p>
<p>Here is the Syntax error: </p>
<pre><code>Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
browser.find_element_by_xpath("(//button[@type='button'])[int(x)]").click()
File "C:\Python35\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 293, in find_element_by_xpath
return self.find_element(by=By.XPATH, value=xpath)
File "C:\Python35\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 752, in find_element
'value': value})['value']
File "C:\Python35\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 236, in execute
self.error_handler.check_response(response)
File "C:\Python35\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 192, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.InvalidSelectorException: Message: invalid selector: Unable to locate an element with the xpath expression (//button[@type='button'])[int(x)] because of the following error:
SyntaxError: Failed to execute 'evaluate' on 'Document': The string '(//button[@type='button'])[int(x)]' is not a valid XPath expression.
(Session info: chrome=52.0.2743.116)
(Driver info: chromedriver=2.23.409699 (49blablablablablbalb5129),platform=Windows NT 6.3.9600 x86_64)
</code></pre>
| 2 | 2016-09-03T22:13:06Z | 39,311,851 | <p>You need to use string formatting to construct a valid XPath query, eg:</p>
<pre><code>build_xpath = "(//button[@type='button'])[{}]".format
for n in range(47, 47 + 18 * times, 18):
brower.find_element_by_xpath(build_xpath(n)).click()
</code></pre>
| 1 | 2016-09-03T22:25:43Z | [
"python",
"python-3.x",
"xpath"
] |
How can I create a figure with optimal resolution for printing? | 39,311,794 | <p>I'm rather fond of <a href="https://upload.wikimedia.org/wikipedia/commons/thumb/5/50/Logistic_Bifurcation_map_High_Resolution.png/800px-Logistic_Bifurcation_map_High_Resolution.png" rel="nofollow">The Logistic Map' Period Doubling Bifurcation</a> and would like to print it on a canvas.</p>
<p>I can create the plot in python, but need some help preparing figure properties so that it has suitable resolution to be printed. My code right ow produces some jagged lines.</p>
<p>Here is my code:</p>
<p>import numpy as np
import matplotlib.pyplot as plt</p>
<pre><code># overall image properties
width, height, dpi = 2560, 1440, 96
picture_background = 'white'
aspect_ratio = width / height
plt.close('all')
R = np.linspace(3.5,4,5001)
fig = plt.figure(figsize=(width / dpi, height / dpi), frameon=False)
ylim = -0.1,1.1
ax = plt.Axes(fig, [0, 0, 1, 1], xlim = (3.4,4))
ax.set_axis_off()
fig.add_axes(ax)
for r in R:
x = np.zeros(5001)
x[0] = 0.1
for i in range(1,len(x)):
x[i] = r*x[i-1]*(1-x[i-1])
ax.plot(r*np.ones(2500),x[-2500:],marker = '.', markersize= 0.01,color = 'grey', linestyle = 'none')
plt.show()
plt.savefig('figure.eps', dpi=dpi, bbox_inches=0, pad_inches=0, facecolor=picture_background)
</code></pre>
<p>Here is what the code produces:</p>
<p><a href="http://i.stack.imgur.com/kqm6B.png" rel="nofollow"><img src="http://i.stack.imgur.com/kqm6B.png" alt="enter image description here"></a></p>
<p>As you can see, some of the lines to the far left of the plot are rather jagged.</p>
<p>How can I create this figure so that the resolution is suitable to be printed on a variety of frame dimensions?</p>
| 0 | 2016-09-03T22:15:55Z | 39,320,429 | <p>I think the source of the jaggies is underlying pixel size + that you are drawing this using very small 'point' markers. The pixels that the line are going through are getting fully saturated so you get the 'jaggy'.</p>
<p>A somewhat better way to plot this data is to do the binning ahead of time and then have mpl plot a heat map:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
plt.ion()
width, height, dpi = 2560 / 2, 1440 / 2, 96 # cut to so SO will let me upload result
aspect_ratio = width / height
fig, ax = plt.subplots(figsize=(width / dpi, height / dpi), frameon=False,
tight_layout=True)
ylim = -0.1, 1.1
ax.axis('off')
# make heatmap at double resolution
accumulator = np.zeros((height, width), dtype=np.uint64)
burn_in_count = 25000
N = 25000
R = np.linspace(3.5, 4, width)
x = 0.1 * np.ones_like(R)
row_indx = np.arange(len(R), dtype='uint')
# do all of the r values in parallel
for j in range(burn_in_count):
x = R * x * (1 - x)
for j in range(N):
x = R * x * (1 - x)
col_indx = (height * x).astype('int')
accumulator[col_indx, row_indx] += 1
im = ax.imshow(accumulator, cmap='gray_r',
norm=mcolors.LogNorm(), interpolation='none')
</code></pre>
<p><a href="http://i.stack.imgur.com/uii6n.png" rel="nofollow"><img src="http://i.stack.imgur.com/uii6n.png" alt="log scaled logistic map"></a></p>
<p>Note that this is log-scaled, if you just want to see what pixels are hit</p>
<p>use </p>
<pre><code>im = ax.imshow(accumulator>0, cmap='gray_r', interpolation='nearest')
</code></pre>
<p><a href="http://i.stack.imgur.com/TroiA.png" rel="nofollow"><img src="http://i.stack.imgur.com/TroiA.png" alt="logistic map 'hits'"></a></p>
<p>but these still have issues of the jaggies and (possibly worse) sometimes the narrow lines get aliased out.</p>
<p>This is the sort of problem that <a href="https://github.com/bokeh/datashader" rel="nofollow">datashader</a> or <a href="https://github.com/bokeh/datashader" rel="nofollow">rasterized scatter</a> is intended to solve by re-binning the data at draw time in an intelligent way (<a href="https://github.com/bokeh/datashader/pull/200" rel="nofollow">see this PR for a prototype datashader/mpl integartion</a>). Both of those are still prototype/proof-of-concept, but usable.</p>
<p><a href="http://matplotlib.org/examples/event_handling/viewlims.html" rel="nofollow">http://matplotlib.org/examples/event_handling/viewlims.html</a> which re-compute the Mandelbrot set on zoom might also be of interest to you. </p>
| 1 | 2016-09-04T18:56:24Z | [
"python",
"matplotlib",
"figure"
] |
django 1.10 media images don't show | 39,311,816 | <p>I have had django media images working in an existing django 1.7 project by adding the following to site urls.py:</p>
<pre><code>urlpatterns = patters(
url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),
)
</code></pre>
<p>This url structure doesn't work in django 1.10 and so I changed it to the reccommended here <a href="http://stackoverflow.com/questions/5517950/django-media-url-and-media-root">Django MEDIA_URL and MEDIA_ROOT</a>:</p>
<pre><code>urlpatterns = [
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
</code></pre>
<p><strong>This fails to render any uploaded media images. Is there an equivalent media url patter for django 1.10 I can use?</strong></p>
| 1 | 2016-09-03T22:18:20Z | 39,331,676 | <p>You can use this:
(<a href="https://docs.djangoproject.com/en/1.10/howto/static-files/" rel="nofollow">Django docs 1.10 Serving files uploaded by a user during development</a>)</p>
<pre><code>urlpatterns = [
...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
</code></pre>
<p>OR you can use this (if you only want it in development with the Debug = True in you'r settings): <a href="https://docs.djangoproject.com/en/1.10/ref/views/" rel="nofollow">Django docs 1.10 Serving files in development</a></p>
<pre><code>if settings.DEBUG:
urlpatterns += [
url(r'^media/(?P<path>.*)$', serve, {
'document_root': settings.MEDIA_ROOT,
}),
]
</code></pre>
<p>For me the <strong>{{ MEDIA_URL }}</strong> didn't work anymore in my template file, I used the <strong>{% get_media_prefix %}</strong>:</p>
<p>Ex.: </p>
<pre><code><img src="{% get_media_prefix %}{{ product.image }}">
</code></pre>
| 0 | 2016-09-05T13:27:51Z | [
"python",
"django",
"django-staticfiles",
"django-media",
"django-1.10"
] |
Programmatically generate if elif elif elif else | 39,311,998 | <p>I would like to condense some wet code that looks like this:</p>
<pre><code>if slips[i] < 3000:
ac.setBackgroundColor(wheel['slip'], 0, 0, 0)
# setBackgroundOpacity deliberately omitted here
elif slips[i] < 3700:
ac.setBackgroundColor(wheel['slip'], .2, .4, .2)
ac.setBackgroundOpacity(wheel['slip'], 1)
elif slips[i] < 4100:
ac.setBackgroundColor(wheel['slip'], 0, 1, 0)
ac.setBackgroundOpacity(wheel['slip'], 1)
elif slips[i] < 4500:
ac.setBackgroundColor(wheel['slip'], 0, 0, 1)
ac.setBackgroundOpacity(wheel['slip'], 1)
else:
ac.setBackgroundColor(wheel['slip'], 1, 0, 0)
ac.setBackgroundOpacity(wheel['slip'], 1)
</code></pre>
<p>Each time this snippet of code is repeated, the only things that change are the background canvas (<code>wheel['slip']</code> in this case), and the numbers in the if elif else's.</p>
<p>My first thought to dry this up was to make something that could be used like this:</p>
<pre><code>if_replacer(wheel['slip'], slips[i], 3000, 3700, 4100, 4500)
def if_replacer(canvas, value, *args):
# idunno
</code></pre>
<p>My question is, how would I programmatically generate the if elif else's? I know I could hard-code it like so:</p>
<pre><code>def if_replacer(canvas, value, c1, c2, c3, c4):
if value < c1:
ac.setBackgroundColor(canvas, 0, 0, 0)
return
elif value < c2:
ac.setBackgroundColor(canvas, .2, .4, .2)
elif value < c3:
ac.setBackgroundColor(canvas, 0, 1, 0)
elif value < c4:
ac.setBackgroundColor(canvas, 0, 0, 1)
else:
ac.setBackgroundColor(canvas, 1, 0, 0)
ac.setBackgroundOpacity(canvas, 1)
</code></pre>
<p>But I'm interested if there is a succinct and Pythonic method to accomplish this.</p>
<p>edit: A lot of excellent answers, but alas I can only mark one of them as accepted (though all valid solutions were upvoted). I accepted the answer that I implemented in my code, but for anyone else who stumbles across this question, do take a look at the other solutions, they're all excellent. And, thanks to everyone who wrote an answer.</p>
| 2 | 2016-09-03T22:52:49Z | 39,312,115 | <p>Here's one possible solution.</p>
<pre><code>def least_bound_index(value, bounds):
"""return the least index such that value < bounds[i], or else len(bounds)"""
for i, b in enumerate(bounds):
if value < b:
return i
return i+1
bounds = [3000, 3700, 4100, 4500]
bgcolors = [(0, 0, 0), (.2, .4, .2), (0, 1, 0), (0, 0, 1), (1, 0, 0)]
i = least_bound_index(slips[i], bounds)
ac.setBackgroundColor(wheel['slip'], *bgcolors[i])
if i > 0:
ac.setBackgroundOpacity(wheel['slip'], 1)
</code></pre>
<p>Note that <code>least_bound_index</code> could also be called <code>index_between</code> because you could imagine [a, b, c, d] on a number line, and it would tell you where the value lands out of these choices:</p>
<pre><code> a b c d
^ ^ ^ ^ ^
0 1 2 3 4
</code></pre>
| 2 | 2016-09-03T23:14:30Z | [
"python",
"if-statement",
"dry"
] |
Programmatically generate if elif elif elif else | 39,311,998 | <p>I would like to condense some wet code that looks like this:</p>
<pre><code>if slips[i] < 3000:
ac.setBackgroundColor(wheel['slip'], 0, 0, 0)
# setBackgroundOpacity deliberately omitted here
elif slips[i] < 3700:
ac.setBackgroundColor(wheel['slip'], .2, .4, .2)
ac.setBackgroundOpacity(wheel['slip'], 1)
elif slips[i] < 4100:
ac.setBackgroundColor(wheel['slip'], 0, 1, 0)
ac.setBackgroundOpacity(wheel['slip'], 1)
elif slips[i] < 4500:
ac.setBackgroundColor(wheel['slip'], 0, 0, 1)
ac.setBackgroundOpacity(wheel['slip'], 1)
else:
ac.setBackgroundColor(wheel['slip'], 1, 0, 0)
ac.setBackgroundOpacity(wheel['slip'], 1)
</code></pre>
<p>Each time this snippet of code is repeated, the only things that change are the background canvas (<code>wheel['slip']</code> in this case), and the numbers in the if elif else's.</p>
<p>My first thought to dry this up was to make something that could be used like this:</p>
<pre><code>if_replacer(wheel['slip'], slips[i], 3000, 3700, 4100, 4500)
def if_replacer(canvas, value, *args):
# idunno
</code></pre>
<p>My question is, how would I programmatically generate the if elif else's? I know I could hard-code it like so:</p>
<pre><code>def if_replacer(canvas, value, c1, c2, c3, c4):
if value < c1:
ac.setBackgroundColor(canvas, 0, 0, 0)
return
elif value < c2:
ac.setBackgroundColor(canvas, .2, .4, .2)
elif value < c3:
ac.setBackgroundColor(canvas, 0, 1, 0)
elif value < c4:
ac.setBackgroundColor(canvas, 0, 0, 1)
else:
ac.setBackgroundColor(canvas, 1, 0, 0)
ac.setBackgroundOpacity(canvas, 1)
</code></pre>
<p>But I'm interested if there is a succinct and Pythonic method to accomplish this.</p>
<p>edit: A lot of excellent answers, but alas I can only mark one of them as accepted (though all valid solutions were upvoted). I accepted the answer that I implemented in my code, but for anyone else who stumbles across this question, do take a look at the other solutions, they're all excellent. And, thanks to everyone who wrote an answer.</p>
| 2 | 2016-09-03T22:52:49Z | 39,312,121 | <p>In case 'setBackgroundOpacity' was omitted by mistake or it doesn't matter if it is included in the first case as well, this is a solution you might be looking for:</p>
<pre><code>color_map = [ (3000, 0, 0, 0),
(3700, .2, .4, .2),
(4100, 0, 1, 0),
(4500, 0, 0, 1),
(10**10, 1, 0, 0) ]
for i, (c, r, g, b) in enumerate(color_map):
if value < c:
ac.setBackgroundColor(wheel['slip'], r, g, b)
if i > 0:
ac.setBackgroundOpacity(wheel['slip'], 1)
break
</code></pre>
<p>Edit: saw the comment about the setBackgroundOpacity function</p>
<p>Edit2: Fixed the typo and added an alternative solution to 10**10 </p>
<pre><code>color_map = [ (3000, 0, 0, 0),
(3700, .2, .4, .2),
(4100, 0, 1, 0),
(4500, 0, 0, 1),
(float("inf"), 1, 0, 0) ]
for i, (c, r, g, b) in enumerate(color_map):
if value < c:
ac.setBackgroundColor(wheel['slip'], r, g, b)
if i > 0:
ac.setBackgroundOpacity(wheel['slip'], 1)
break
</code></pre>
| 2 | 2016-09-03T23:14:50Z | [
"python",
"if-statement",
"dry"
] |
Programmatically generate if elif elif elif else | 39,311,998 | <p>I would like to condense some wet code that looks like this:</p>
<pre><code>if slips[i] < 3000:
ac.setBackgroundColor(wheel['slip'], 0, 0, 0)
# setBackgroundOpacity deliberately omitted here
elif slips[i] < 3700:
ac.setBackgroundColor(wheel['slip'], .2, .4, .2)
ac.setBackgroundOpacity(wheel['slip'], 1)
elif slips[i] < 4100:
ac.setBackgroundColor(wheel['slip'], 0, 1, 0)
ac.setBackgroundOpacity(wheel['slip'], 1)
elif slips[i] < 4500:
ac.setBackgroundColor(wheel['slip'], 0, 0, 1)
ac.setBackgroundOpacity(wheel['slip'], 1)
else:
ac.setBackgroundColor(wheel['slip'], 1, 0, 0)
ac.setBackgroundOpacity(wheel['slip'], 1)
</code></pre>
<p>Each time this snippet of code is repeated, the only things that change are the background canvas (<code>wheel['slip']</code> in this case), and the numbers in the if elif else's.</p>
<p>My first thought to dry this up was to make something that could be used like this:</p>
<pre><code>if_replacer(wheel['slip'], slips[i], 3000, 3700, 4100, 4500)
def if_replacer(canvas, value, *args):
# idunno
</code></pre>
<p>My question is, how would I programmatically generate the if elif else's? I know I could hard-code it like so:</p>
<pre><code>def if_replacer(canvas, value, c1, c2, c3, c4):
if value < c1:
ac.setBackgroundColor(canvas, 0, 0, 0)
return
elif value < c2:
ac.setBackgroundColor(canvas, .2, .4, .2)
elif value < c3:
ac.setBackgroundColor(canvas, 0, 1, 0)
elif value < c4:
ac.setBackgroundColor(canvas, 0, 0, 1)
else:
ac.setBackgroundColor(canvas, 1, 0, 0)
ac.setBackgroundOpacity(canvas, 1)
</code></pre>
<p>But I'm interested if there is a succinct and Pythonic method to accomplish this.</p>
<p>edit: A lot of excellent answers, but alas I can only mark one of them as accepted (though all valid solutions were upvoted). I accepted the answer that I implemented in my code, but for anyone else who stumbles across this question, do take a look at the other solutions, they're all excellent. And, thanks to everyone who wrote an answer.</p>
| 2 | 2016-09-03T22:52:49Z | 39,312,167 | <pre><code>c = [[0,0,0],[.2,.4,.2],[0,1,0],[0,0,1]]
threshold = [3000,3700,4100,4500]
if slips[i] >= 4500:
ac.setBackgroundColor(wheel['slip'],1,0,0)
else:
for x in range(4):
if slips[i] < threshold[x]:
ac.setBackgroundColor(wheel['slip'],c[x][0],c[x][1],c[x][2])
break
if slips[i] >= 3000:
ac.setBackgroundOpacity(wheel['slip'], 1)
</code></pre>
<p>This is one alternative, but I do personally prefer @mpurg's answer.</p>
| 1 | 2016-09-03T23:21:51Z | [
"python",
"if-statement",
"dry"
] |
Programmatically generate if elif elif elif else | 39,311,998 | <p>I would like to condense some wet code that looks like this:</p>
<pre><code>if slips[i] < 3000:
ac.setBackgroundColor(wheel['slip'], 0, 0, 0)
# setBackgroundOpacity deliberately omitted here
elif slips[i] < 3700:
ac.setBackgroundColor(wheel['slip'], .2, .4, .2)
ac.setBackgroundOpacity(wheel['slip'], 1)
elif slips[i] < 4100:
ac.setBackgroundColor(wheel['slip'], 0, 1, 0)
ac.setBackgroundOpacity(wheel['slip'], 1)
elif slips[i] < 4500:
ac.setBackgroundColor(wheel['slip'], 0, 0, 1)
ac.setBackgroundOpacity(wheel['slip'], 1)
else:
ac.setBackgroundColor(wheel['slip'], 1, 0, 0)
ac.setBackgroundOpacity(wheel['slip'], 1)
</code></pre>
<p>Each time this snippet of code is repeated, the only things that change are the background canvas (<code>wheel['slip']</code> in this case), and the numbers in the if elif else's.</p>
<p>My first thought to dry this up was to make something that could be used like this:</p>
<pre><code>if_replacer(wheel['slip'], slips[i], 3000, 3700, 4100, 4500)
def if_replacer(canvas, value, *args):
# idunno
</code></pre>
<p>My question is, how would I programmatically generate the if elif else's? I know I could hard-code it like so:</p>
<pre><code>def if_replacer(canvas, value, c1, c2, c3, c4):
if value < c1:
ac.setBackgroundColor(canvas, 0, 0, 0)
return
elif value < c2:
ac.setBackgroundColor(canvas, .2, .4, .2)
elif value < c3:
ac.setBackgroundColor(canvas, 0, 1, 0)
elif value < c4:
ac.setBackgroundColor(canvas, 0, 0, 1)
else:
ac.setBackgroundColor(canvas, 1, 0, 0)
ac.setBackgroundOpacity(canvas, 1)
</code></pre>
<p>But I'm interested if there is a succinct and Pythonic method to accomplish this.</p>
<p>edit: A lot of excellent answers, but alas I can only mark one of them as accepted (though all valid solutions were upvoted). I accepted the answer that I implemented in my code, but for anyone else who stumbles across this question, do take a look at the other solutions, they're all excellent. And, thanks to everyone who wrote an answer.</p>
| 2 | 2016-09-03T22:52:49Z | 39,312,237 | <p>My take on it (untested as to the actual <code>ac...</code> calls):</p>
<pre><code>from functools import partial
mapping = [
(3000, (0, 0, 0), None),
(3700, (.2, .4, .2), 1),
(4100, (0, 1, 0), 1),
(4500, (0, 0, 1), 1),
(float('inf'), (1, 0, 0), 1)
]
def if_replacer(canvas, value, mapping):
set_color = partial(ac.setBackgroundColor, canvas)
set_opacity = partial(ac.setBackgroundOpacity, canvas)
for limit, vals, opacity in lookup:
if value < limit:
set_color(*vals)
if opacity is not None:
set_opacity(opacity)
break
</code></pre>
<p>Then if for some reason you do have to pick up new ranges, then you can do something like:</p>
<pre><code>from bisect import insort_left
insort_left(mapping, (4300, (1, 1, 1), 0))
</code></pre>
<p>Which'll update <code>mapping</code> to be:</p>
<pre><code>[(3000, (0, 0, 0), None),
(3700, (0.2, 0.4, 0.2), 1),
(4100, (0, 1, 0), 1),
(4300, (1, 1, 1), 0),
(4500, (0, 0, 1), 1),
(inf, (1, 0, 0), 1)]
</code></pre>
| 1 | 2016-09-03T23:32:34Z | [
"python",
"if-statement",
"dry"
] |
django - How to change existing code to ModelForm instance | 39,312,031 | <p>New to Django and this is my first web application.</p>
<p>I'm having trouble with django's ModelForm feature and I wanted to know:</p>
<p>How do I modify my code so that I can create an instance of ModelForm, and specifically, how can I extract the form data to upload to the backend? I will need to reference this instance at a later time to re-populate the same data in an <code>update_profile</code> view but the updation can only happen once the user is logged in (after signup and profile creation).</p>
<p>For the editing section, do I use <code>pk=some_record.pk</code>? Very confused, any help is appreciated.</p>
<p>The model I'm working with <code>CustomerDetail</code> has a foreign key field <code>customer</code> which references the <code>Customer</code> model:</p>
<pre><code>class CustomerDetail(models.Model):
phone_regex = RegexValidator(regex = r'^\d{10}$', message = "Invalid format! E.g. 4088385778")
date_regex = RegexValidator(regex = r'^(\d{2})[/.-](\d{2})[/.-](\d{2})$', message = "Invalid format! E.g. 05/16/91")
customer = models.OneToOneField(Customer,
on_delete=models.CASCADE,
primary_key=True,)
address = models.CharField(max_length=100)
date_of_birth = models.CharField(validators = [date_regex], max_length = 10, blank = True)
company = models.CharField(max_length=30)
home_phone = models.CharField(validators = [phone_regex], max_length = 10, blank = True)
work_phone = models.CharField(validators = [phone_regex], max_length = 10, blank = True)
def __str__(self):
return str(self.customer)
</code></pre>
<p>Here is a snippet of <code>views.py</code>:</p>
<pre><code>def create_profile(request):
if request.POST:
address = request.POST['address']
date_of_birth = request.POST['date_of_birth']
company = request.POST['company']
home_phone = request.POST['home_phone']
work_phone = request.POST['work_phone']
custprofdata = CustomerDetail(address = address, date_of_birth = date_of_birth, company = company, home_phone = home_phone, work_phone = work_phone)
custprofdata.save()
output = {'address': address, 'dateofbirth': date_of_birth, 'company': company, 'homephone': home_phone, 'workphone': work_phone}
return render(request, 'newuser/profile_created.html', output)
else:
return redirect(create_profile)
</code></pre>
<p>And here is a snippet of the form part of the respective <code>create_profile.html</code>:</p>
<pre><code><form action = "{% url 'create_profile' %}" class="create_profile" role="form" method = "post">
{% csrf_token %}
<div class="form-group">
<label for="address" class="col-md-3 control-label">Address</label>
<div class="col-md-9">
<input type="text" class="form-control" name="address" placeholder="777 Park St" />
</div>
</div>
<div class="form-group">
<label for="date-of-birth" class="col-md-3 control-label">Date Of Birth</label>
<div class="col-md-9">
<input type="text" class="form-control" name="date_of_birth" placeholder="09/12/82" />
</div>
</div>
<div class="form-group">
<label for="company" class="col-md-3 control-label">Company</label>
<div class="col-md-9">
<input type="text" class="form-control" name="company" placeholder="Oracle">
</div>
</div>
<div class="form-group">
<label for="home-phone" class="col-md-3 control-label">Home Phone</label>
<div class="col-md-9">
<input type="text" class="form-control" name="home_phone" placeholder="4082992788">
</div>
</div>
<div class="form-group">
<label for="work-phone" class="col-md-3 control-label">Work Phone</label>
<div class="col-md-9">
<input type="text" class="form-control" name="work_phone" placeholder="6690039955">
</div>
</div>
<div class="form-group">
<div class="col-md-offset-3 col-md-9">
<button type = "create" class="btn btn-success" form = "create_profile"> Submit </button>
</div>
</div>
</form>
</code></pre>
| 2 | 2016-09-03T22:58:55Z | 39,312,324 | <p>Implementing a basic ModelForm is just a matter of the following:</p>
<pre><code>from django.forms import ModelForm
from .models import CustomerDetail
class CustomerDetailForm(ModelForm):
class Meta:
model = CustomerDetail
fields = ['address', 'date_of_birth', 'company', 'home_phone', 'work_phone',]
</code></pre>
<p><a href="https://docs.djangoproject.com/en/1.10/topics/forms/modelforms/#a-full-example" rel="nofollow">https://docs.djangoproject.com/en/1.10/topics/forms/modelforms/#a-full-example</a></p>
<p>But I suggest you also switch to using a Class Based View (CBV) - the CreateView will do the same as your existing view with much less code, with an implicit ModelForm (which you can customise by providing your own ModelForm class with <code>form_class = YourFormClass</code> if you want).</p>
<p><a href="https://docs.djangoproject.com/en/1.10/ref/class-based-views/generic-editing/#createview" rel="nofollow">https://docs.djangoproject.com/en/1.10/ref/class-based-views/generic-editing/#createview</a></p>
<p><a href="https://ccbv.co.uk/projects/Django/1.10/django.views.generic.edit/CreateView/" rel="nofollow">https://ccbv.co.uk/projects/Django/1.10/django.views.generic.edit/CreateView/</a></p>
| 1 | 2016-09-03T23:49:55Z | [
"python",
"django",
"modelform"
] |
django - How to change existing code to ModelForm instance | 39,312,031 | <p>New to Django and this is my first web application.</p>
<p>I'm having trouble with django's ModelForm feature and I wanted to know:</p>
<p>How do I modify my code so that I can create an instance of ModelForm, and specifically, how can I extract the form data to upload to the backend? I will need to reference this instance at a later time to re-populate the same data in an <code>update_profile</code> view but the updation can only happen once the user is logged in (after signup and profile creation).</p>
<p>For the editing section, do I use <code>pk=some_record.pk</code>? Very confused, any help is appreciated.</p>
<p>The model I'm working with <code>CustomerDetail</code> has a foreign key field <code>customer</code> which references the <code>Customer</code> model:</p>
<pre><code>class CustomerDetail(models.Model):
phone_regex = RegexValidator(regex = r'^\d{10}$', message = "Invalid format! E.g. 4088385778")
date_regex = RegexValidator(regex = r'^(\d{2})[/.-](\d{2})[/.-](\d{2})$', message = "Invalid format! E.g. 05/16/91")
customer = models.OneToOneField(Customer,
on_delete=models.CASCADE,
primary_key=True,)
address = models.CharField(max_length=100)
date_of_birth = models.CharField(validators = [date_regex], max_length = 10, blank = True)
company = models.CharField(max_length=30)
home_phone = models.CharField(validators = [phone_regex], max_length = 10, blank = True)
work_phone = models.CharField(validators = [phone_regex], max_length = 10, blank = True)
def __str__(self):
return str(self.customer)
</code></pre>
<p>Here is a snippet of <code>views.py</code>:</p>
<pre><code>def create_profile(request):
if request.POST:
address = request.POST['address']
date_of_birth = request.POST['date_of_birth']
company = request.POST['company']
home_phone = request.POST['home_phone']
work_phone = request.POST['work_phone']
custprofdata = CustomerDetail(address = address, date_of_birth = date_of_birth, company = company, home_phone = home_phone, work_phone = work_phone)
custprofdata.save()
output = {'address': address, 'dateofbirth': date_of_birth, 'company': company, 'homephone': home_phone, 'workphone': work_phone}
return render(request, 'newuser/profile_created.html', output)
else:
return redirect(create_profile)
</code></pre>
<p>And here is a snippet of the form part of the respective <code>create_profile.html</code>:</p>
<pre><code><form action = "{% url 'create_profile' %}" class="create_profile" role="form" method = "post">
{% csrf_token %}
<div class="form-group">
<label for="address" class="col-md-3 control-label">Address</label>
<div class="col-md-9">
<input type="text" class="form-control" name="address" placeholder="777 Park St" />
</div>
</div>
<div class="form-group">
<label for="date-of-birth" class="col-md-3 control-label">Date Of Birth</label>
<div class="col-md-9">
<input type="text" class="form-control" name="date_of_birth" placeholder="09/12/82" />
</div>
</div>
<div class="form-group">
<label for="company" class="col-md-3 control-label">Company</label>
<div class="col-md-9">
<input type="text" class="form-control" name="company" placeholder="Oracle">
</div>
</div>
<div class="form-group">
<label for="home-phone" class="col-md-3 control-label">Home Phone</label>
<div class="col-md-9">
<input type="text" class="form-control" name="home_phone" placeholder="4082992788">
</div>
</div>
<div class="form-group">
<label for="work-phone" class="col-md-3 control-label">Work Phone</label>
<div class="col-md-9">
<input type="text" class="form-control" name="work_phone" placeholder="6690039955">
</div>
</div>
<div class="form-group">
<div class="col-md-offset-3 col-md-9">
<button type = "create" class="btn btn-success" form = "create_profile"> Submit </button>
</div>
</div>
</form>
</code></pre>
| 2 | 2016-09-03T22:58:55Z | 39,312,516 | <p>After creating CustomerDetailForm as @John Carter said, you might want to change your view.py to the following</p>
<pre class="lang-py prettyprint-override"><code>
def create_profile(request):
if request.POST:
form = CustomerDetailForm(request.POST)
if form.is_valid():
## save data in database ##
return render(request, 'newuser/profile_created.html', {form:form})
else:
return redirect(create_profile)
</code></pre>
| 1 | 2016-09-04T00:29:08Z | [
"python",
"django",
"modelform"
] |
Why is ''.join() faster than += in Python? | 39,312,099 | <p>I'm able to find a bevy of information online (on Stack Overflow and otherwise) about how it's a very inefficient and bad practice to use <code>+</code> or <code>+=</code> for concatenation in Python.</p>
<p>I can't seem to find WHY <code>+=</code> is so inefficient. Outside of a mention <a href="http://stackoverflow.com/a/1350289/3903011" title="What is the most efficient string concatenation method in python?">here</a> that "it's been optimized for 20% improvement in certain cases" (still not clear what those cases are), I can't find any additional information.</p>
<p>What is happening on a more technical level that makes <code>''.join()</code> superior to other Python concatenation methods?</p>
| 55 | 2016-09-03T23:11:19Z | 39,312,172 | <p>Let's say you have this code to build up a string from three strings:</p>
<pre><code>x = 'foo'
x += 'bar' # 'foobar'
x += 'baz' # 'foobarbaz'
</code></pre>
<p>In this case, Python first needs to allocate and create <code>'foobar'</code> before it can allocate and create <code>'foobarbaz'</code>.</p>
<p>So for each <code>+=</code> that gets called, the entire contents of the string and whatever is getting added to it need to be copied into an entirely new memory buffer. In other words, if you have <code>N</code> strings to be joined, you need to allocate approximately <code>N</code> temporary strings and the first substring gets copied ~N times. The last substring only gets copied once, but on average, each substring gets copied <code>~N/2</code> times.</p>
<p>With <code>.join</code>, Python can play a number of tricks since the intermediate strings do not need to be created. <a href="http://en.wikipedia.org/wiki/CPython">CPython</a> figures out how much memory it needs up front and then allocates a correctly-sized buffer. Finally, it then copies each piece into the new buffer which means that each piece is only copied once.</p>
<hr>
<p>There are other viable approaches which could lead to better performance for <code>+=</code> in some cases. E.g. if the internal string representation is actually a <a href="https://en.wikipedia.org/wiki/Rope_(data_structure)"><code>rope</code></a> or if the runtime is actually smart enough to somehow figure out that the temporary strings are of no use to the program and optimize them away.</p>
<p>However, CPython certainly does <em>not</em> do these optimizations reliably (though it may for a <a href="http://stackoverflow.com/questions/39312099/why-is-join-faster-than-in-python/39312172?noredirect=1#comment65960978_39314264">few corner cases</a>) and since it is the most common implementation in use, many best-practices are based on what works well for CPython. Having a standardized set of norms also makes it easier for other implementations to focus their optimization efforts as well.</p>
| 72 | 2016-09-03T23:22:51Z | [
"python",
"optimization"
] |
Why is ''.join() faster than += in Python? | 39,312,099 | <p>I'm able to find a bevy of information online (on Stack Overflow and otherwise) about how it's a very inefficient and bad practice to use <code>+</code> or <code>+=</code> for concatenation in Python.</p>
<p>I can't seem to find WHY <code>+=</code> is so inefficient. Outside of a mention <a href="http://stackoverflow.com/a/1350289/3903011" title="What is the most efficient string concatenation method in python?">here</a> that "it's been optimized for 20% improvement in certain cases" (still not clear what those cases are), I can't find any additional information.</p>
<p>What is happening on a more technical level that makes <code>''.join()</code> superior to other Python concatenation methods?</p>
| 55 | 2016-09-03T23:11:19Z | 39,314,264 | <p>I think this behaviour is best explained in <a href="https://www.lua.org/pil/11.6.html">Lua's string buffer chapter</a>.</p>
<p>To rewrite that explanation in context of Python, let's start with an innocent code snippet (a derivative of the one at Lua's docs):</p>
<pre><code>s = ""
for l in some_list:
s += l
</code></pre>
<p>Assume that each <code>l</code> is 20 bytes and the <code>s</code> has already been parsed to a size of 50 KB. When Python concatenates <code>s + l</code> it creates a new string with 50,020 bytes and copies 50 KB from <code>s</code> into this new string. That is, for each new line, the program moves 50 KB of memory, and growing. After reading 100 new lines (only 2 KB), the snippet has already moved more than 5 MB of memory. To make things worse, after the assignment</p>
<pre><code>s += l
</code></pre>
<p>the old string is now garbage. After two loop cycles, there are two old strings making a total of more than 100 KB of garbage. So, the language compiler decides to run its garbage collector and frees those 100 KB. The problem is that this will happen every two cycles and the program will run its garbage collector two thousand times before reading the whole list. Even with all this work, its memory usage will be a large multiple of the list's size.</p>
<p>And, at the end:</p>
<blockquote>
<p>This problem is not peculiar to Lua: Other languages with true garbage
collection, and where strings are immutable objects, present a similar
behavior, Java being the most famous example. (Java offers the
structure <code>StringBuffer</code> to ameliorate the problem.)</p>
</blockquote>
<p>Python strings are also <a href="http://stackoverflow.com/a/9098038/1190388">immutable objects</a>.</p>
| 5 | 2016-09-04T06:44:35Z | [
"python",
"optimization"
] |
if statements not executing | 39,312,193 | <p>New to the language and this rock paper scissors thing is the first thing I've ever done in python so im aware the code is inefficient and nooby but any pointers will be appreciated! Basically im getting a response as if none of the if statements are being executed and found = False is staying as such throughout the whole program! So the output is "You drew with your opponent" even when I know from debugging that MyChoice and aiChoice are valid and not drawing.</p>
<pre><code>import time as t
import random as r
import os
os.system('@Color 0a')
aiWins = 0
MyWins = 0
Rock = 1
Paper = 2
Scissors = 3
found = False
#welcome text
print("\nWelcome to rock paper scissors")
t.sleep(1)
print("\nPlease enter a username")
user = input("> ")
def aiCheck(aiWins):
if aiWins > 5:
print("Unfortunately the computer has bested you this time! Try again.")
def myCheck(MyWins):
if MyWins > 5:
print("Congratulations you have won the game!")
def whowon(found, MyChoice, aiChoice, myWins, aiWins):
print (MyChoice)
print (aiChoice)
if MyChoice == 1 and aiChoice == 3:
found = True
t.sleep(2)
print('You chose rock and your opponent chose scissors! You win!')
MyWins = MyWins + 1
elif MyChoice == 2 and aiChoice == 1:
found = True
t.sleep(2)
print('You chose paper and your opponent chose rock! You win!')
MyWins = MyWins + 1
elif MyChoice == 3 and aiChoice == 2:
found = True
t.sleep(2)
print ('You chose scissors and your opponent chose paper! You win!')
MyWins = MyWins + 1
elif MyChoice == 3 and aiChoice == 1:
found = True
t.sleep(2)
print('You chose scissors and your opponent chose rock! You lose!')
aiWins = aiWins + 1
elif MyChoice == 1 and aiChoice == 2:
found = True
t.sleep(2)
print('You chose rock and your opponent chose paper! You lose!')
aiWins = aiWins + 1
elif MyChoice == 2 and aiChoice == 3:
found = True
t.sleep(2)
print ('You chose paper and your opponent chose scissors! You lose!')
aiWins = aiWins + 1
if found == False:
print("You drew with your opponent")
return found
return MyWins
return aiWins
print("\nOptions!")
t.sleep(1)
print('\n1. Rock')
print('2. Paper')
print('3. Scissors')
print('\nEnter the number that correlates with your choice')
MyChoice = input('> ')
aiChoice = r.randint(1,3)
whowon(found, MyChoice, aiChoice, MyWins, aiWins)
</code></pre>
| -2 | 2016-09-03T23:26:02Z | 39,312,227 | <p>This should solve your problem:</p>
<pre><code>MyChoice = int(input('> '))
</code></pre>
<p>You were comparing strings (MyChoice) and integers (aiChoice).</p>
| 1 | 2016-09-03T23:30:42Z | [
"python",
"python-3.x"
] |
if statements not executing | 39,312,193 | <p>New to the language and this rock paper scissors thing is the first thing I've ever done in python so im aware the code is inefficient and nooby but any pointers will be appreciated! Basically im getting a response as if none of the if statements are being executed and found = False is staying as such throughout the whole program! So the output is "You drew with your opponent" even when I know from debugging that MyChoice and aiChoice are valid and not drawing.</p>
<pre><code>import time as t
import random as r
import os
os.system('@Color 0a')
aiWins = 0
MyWins = 0
Rock = 1
Paper = 2
Scissors = 3
found = False
#welcome text
print("\nWelcome to rock paper scissors")
t.sleep(1)
print("\nPlease enter a username")
user = input("> ")
def aiCheck(aiWins):
if aiWins > 5:
print("Unfortunately the computer has bested you this time! Try again.")
def myCheck(MyWins):
if MyWins > 5:
print("Congratulations you have won the game!")
def whowon(found, MyChoice, aiChoice, myWins, aiWins):
print (MyChoice)
print (aiChoice)
if MyChoice == 1 and aiChoice == 3:
found = True
t.sleep(2)
print('You chose rock and your opponent chose scissors! You win!')
MyWins = MyWins + 1
elif MyChoice == 2 and aiChoice == 1:
found = True
t.sleep(2)
print('You chose paper and your opponent chose rock! You win!')
MyWins = MyWins + 1
elif MyChoice == 3 and aiChoice == 2:
found = True
t.sleep(2)
print ('You chose scissors and your opponent chose paper! You win!')
MyWins = MyWins + 1
elif MyChoice == 3 and aiChoice == 1:
found = True
t.sleep(2)
print('You chose scissors and your opponent chose rock! You lose!')
aiWins = aiWins + 1
elif MyChoice == 1 and aiChoice == 2:
found = True
t.sleep(2)
print('You chose rock and your opponent chose paper! You lose!')
aiWins = aiWins + 1
elif MyChoice == 2 and aiChoice == 3:
found = True
t.sleep(2)
print ('You chose paper and your opponent chose scissors! You lose!')
aiWins = aiWins + 1
if found == False:
print("You drew with your opponent")
return found
return MyWins
return aiWins
print("\nOptions!")
t.sleep(1)
print('\n1. Rock')
print('2. Paper')
print('3. Scissors')
print('\nEnter the number that correlates with your choice')
MyChoice = input('> ')
aiChoice = r.randint(1,3)
whowon(found, MyChoice, aiChoice, MyWins, aiWins)
</code></pre>
| -2 | 2016-09-03T23:26:02Z | 39,312,232 | <p><code>input</code> returns a string so you must wrap <code>MyString</code> with an integer converter like so:</p>
<pre><code>MyChoice = int(input("> "))
</code></pre>
<p>Since a string cannot be accurately compared to an integer, <code>found</code> isn't being set to True, thus <code>found</code> is False, leading to it reporting a draw.</p>
<p>Next, you can't return multiple things with separate return statements, and in this case there's no need since you don't do anything with the return values. If you do want to return the values, you can return with a tuple:</p>
<pre><code>return (found, MyWins, aiWins)
</code></pre>
<p>A note: parameter names do not have to be the same as global variables. Parameter variables are local variables that act as placeholders for what you actually pass in. You also have redundant parameters. found, MyChoice, and aiChoice don't need to be passed. </p>
| 1 | 2016-09-03T23:31:34Z | [
"python",
"python-3.x"
] |
if statements not executing | 39,312,193 | <p>New to the language and this rock paper scissors thing is the first thing I've ever done in python so im aware the code is inefficient and nooby but any pointers will be appreciated! Basically im getting a response as if none of the if statements are being executed and found = False is staying as such throughout the whole program! So the output is "You drew with your opponent" even when I know from debugging that MyChoice and aiChoice are valid and not drawing.</p>
<pre><code>import time as t
import random as r
import os
os.system('@Color 0a')
aiWins = 0
MyWins = 0
Rock = 1
Paper = 2
Scissors = 3
found = False
#welcome text
print("\nWelcome to rock paper scissors")
t.sleep(1)
print("\nPlease enter a username")
user = input("> ")
def aiCheck(aiWins):
if aiWins > 5:
print("Unfortunately the computer has bested you this time! Try again.")
def myCheck(MyWins):
if MyWins > 5:
print("Congratulations you have won the game!")
def whowon(found, MyChoice, aiChoice, myWins, aiWins):
print (MyChoice)
print (aiChoice)
if MyChoice == 1 and aiChoice == 3:
found = True
t.sleep(2)
print('You chose rock and your opponent chose scissors! You win!')
MyWins = MyWins + 1
elif MyChoice == 2 and aiChoice == 1:
found = True
t.sleep(2)
print('You chose paper and your opponent chose rock! You win!')
MyWins = MyWins + 1
elif MyChoice == 3 and aiChoice == 2:
found = True
t.sleep(2)
print ('You chose scissors and your opponent chose paper! You win!')
MyWins = MyWins + 1
elif MyChoice == 3 and aiChoice == 1:
found = True
t.sleep(2)
print('You chose scissors and your opponent chose rock! You lose!')
aiWins = aiWins + 1
elif MyChoice == 1 and aiChoice == 2:
found = True
t.sleep(2)
print('You chose rock and your opponent chose paper! You lose!')
aiWins = aiWins + 1
elif MyChoice == 2 and aiChoice == 3:
found = True
t.sleep(2)
print ('You chose paper and your opponent chose scissors! You lose!')
aiWins = aiWins + 1
if found == False:
print("You drew with your opponent")
return found
return MyWins
return aiWins
print("\nOptions!")
t.sleep(1)
print('\n1. Rock')
print('2. Paper')
print('3. Scissors')
print('\nEnter the number that correlates with your choice')
MyChoice = input('> ')
aiChoice = r.randint(1,3)
whowon(found, MyChoice, aiChoice, MyWins, aiWins)
</code></pre>
| -2 | 2016-09-03T23:26:02Z | 39,312,258 | <p>Firstly, these are already global variables. No need to use them as parameters. </p>
<pre><code>aiWins = 0
MyWins = 0
found = False
</code></pre>
<p>Now, you can define the method like so and use the <code>global</code> keyword to ensure you're using those global variables. </p>
<pre><code>def whowon(MyChoice, aiChoice):
global aiWins
global MyWins
global found
print (MyChoice)
print (aiChoice)
# etc...
</code></pre>
<p>Then, those return statements aren't really needed. Plus any function ends at the first return statement anyway. </p>
<p>Lastly, <code>input()</code> returns a string, so your if statements are comparing integers to strings, which is false, therefore they are executing as intended. </p>
<p>To fix the problem, you need to cast the input to an integer before you compare. You can either do that directly on the input method</p>
<pre><code>MyChoice = int(input("> "))
</code></pre>
<p>Or directly on the parameter </p>
<pre><code>whowon(int(MyChoice), aiChoice)
</code></pre>
<p>Or on each of the variables in the if statements within the function. Up to you </p>
| -1 | 2016-09-03T23:37:00Z | [
"python",
"python-3.x"
] |
Applying comma seperator formatting to an entire DataFrame in python 3 | 39,312,218 | <p>I want to format all numbers in a DataFrame to have comma seperators (e.g. 1,000,000 instead of 1000000). It can be applied to a single number using <code>'{:,}'.format(number)</code>. Naively applying the same to a DataFrame gives the error</p>
<pre><code> TypeError: non-empty format string passed to object.__format__
</code></pre>
<p>Is there a way to efficiently apply the same formatting to a DataFrame? Thanks!</p>
| 2 | 2016-09-03T23:29:35Z | 39,312,274 | <p>Use <code>applymap</code></p>
<pre><code>df = pd.DataFrame(np.random.randint(1000, 10000, (5, 5)))
df.applymap('{:,}'.format)
</code></pre>
<p><a href="http://i.stack.imgur.com/ikJ1k.png" rel="nofollow"><img src="http://i.stack.imgur.com/ikJ1k.png" alt="enter image description here"></a></p>
| 4 | 2016-09-03T23:40:21Z | [
"python",
"python-3.x",
"pandas",
"dataframe",
"formatting"
] |
Extracting user information from tweets using Python | 39,312,316 | <p>I am trying to extract some user information from the tweets I have downloaded. Below is the code that I am using, however, it only returns "None" in the list for all the tweets.</p>
<pre><code>map(lambda test: test['place']['country'] , data)
</code></pre>
<p>Also, tried the following:- </p>
<pre><code>map(lambda test: test.get('place').get('country'), data)
</code></pre>
<p>I am relatively new to Python. It will be really helpful if someone can please help me understand if I am missing something here. </p>
| 0 | 2016-09-03T23:48:12Z | 39,327,095 | <p>This will just be due to the fact that the vast majority of tweets do not seem to carry the 'place' data - Its nearly always set to None.</p>
<p>Your best bet for a location would be to use the location key inside the 'user' section of the data dump - but even that isnt always filled out (You would have to try/except to handle TypeErrors for None type objects. See below for what I use within my listener.</p>
<pre><code>def on_data(self, data):
tweet = json.loads(data)
print "\n\n ***********************************"
try:
print tweet['created_at'][:19] + ' - ' + tweet["text"] + ' - ' + tweet['user']['location']
except TypeError:
print tweet['created_at'][:19] + ' - ' + tweet["text"] + ' - ' 'No Location Given'
return True
</code></pre>
<p>Hope this helps you on your way!</p>
| 0 | 2016-09-05T09:01:32Z | [
"python",
"python-2.7",
"python-3.x",
"twitter"
] |
How do I execute a Python script based off user inputed fields from a Website | 39,312,358 | <p>Using the following python.py file below as an example, how could a user on a website form select the position from something like a dropdown field or the user could input WR, RB, QB themselves. (position="WR" is currently what is in the code below) and click submit and the code will execute the query into a table?</p>
<p>I am using Wordpress on one server with MySQL. On another server, I am using Python and PostgreSQL. Thank you for any help you can provide.</p>
<pre><code>import nfldb
db = nfldb.connect() q = nfldb.Query(db) q.game(season_year=2015, season_type='Regular')
q.player(position="WR")
q.play(receiving_rec=1)
def inside(field, stat):
cutoff = nfldb.FieldPosition.from_str(field)
return lambda play: play.yardline + getattr(play, stat) >= cutoff plays = filter(inside('OPP 20', 'receiving_yds'), q.as_plays())
for p in plays:
print p
</code></pre>
| 1 | 2016-09-03T23:57:48Z | 39,312,471 | <p>I'm no expert, but be able to run code in response to any user interaction on your website, there should be some kind of web service running that would run your code.
The general idea would be to first have the Wordpress server able to send out a "GET" to your postgre server, and be able to receive its answer.
Then I would create a Web Service on your PostgreSQL (something like <a href="http://flask.pocoo.org/" rel="nofollow">Flask</a> would be just fine, if you want you have the excellent tutorial by <a href="http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world" rel="nofollow">Miguel Grinberg</a>) so it can receive the request, run the code you mention and then send the response to the Wordpress+MySQL.</p>
<p>Hope I'm pointing you in the right direction.</p>
| 0 | 2016-09-04T00:20:10Z | [
"php",
"python",
"sql",
"wordpress",
"postgresql"
] |
Trying to sort a list of tuples in python first by date then by greatest number | 39,312,362 | <p>I have a list of tuples and I am trying to sort by date and then by the greatest number. So basically when you have two dates that are the same it will then put the tuple with the greatest number first. See example below. </p>
<p><strong>My list of tuples</strong></p>
<pre><code>dataLst = [["Mike", 50, "08/10/2016"], ["Bob", 100, "08/10/2016"], ["Dave", 500, "08/01/2016"], ["Paul", -50, "08/20/2016"], ["Sam", 250, "08/30/2016"]]
</code></pre>
<p><strong>I then sort the list by the dates in the tuples.</strong></p>
<pre><code>sDataLst = sorted(dataLst, key=operator.itemgetter(2))
</code></pre>
<p><strong>I then sort the sorted list by the numbers in reverse order.</strong></p>
<pre><code>sorted(sDataLst,key=operator.itemgetter(1), reverse=True)
</code></pre>
<p><strong>When I print the sorted list I get the following.</strong></p>
<pre><code>print sDataLst
[['Dave', 500, '08/01/2016'], ['Mike', 50, '08/10/2016'], ['Bob', 100, '08/10/2016'], ['Paul', -50, '08/20/2016'], ['Sam', 250, '08/30/2016']]
</code></pre>
<p>If you look at the second and third item in the list which have the same date they should be reversed because the number in the third item is greater then the one in the second item. What I am looking for as a result is the following.</p>
<pre><code>[['Dave', 500, '08/01/2016'], ['Bob', 100, '08/10/2016'], ['Mike', 50, '08/10/2016'], ['Paul', -50, '08/20/2016'], ['Sam', 250, '08/30/2016']]
</code></pre>
<p>Any help on this would be greatly appreciated.</p>
<p>Thanks</p>
| 2 | 2016-09-03T23:58:30Z | 39,312,403 | <p>You cannot compare the dates as strings because of the order <em>mm/dd/yyyy</em>, you could use <em>datetime</em> to : </p>
<pre><code>from datetime import datetime
strp = datetime.strptime
srted = sorted(dataLst, key=lambda sub: (strp(sub[2],"%m/%d/%Y"), -sub[1]))
</code></pre>
<p>Or just split and reverse the order of the date to <em>yyyy, mm, dd:</em></p>
<pre><code>def iso(sub):
mm, dd, yy = sub.split("/")
return yy, mm, dd
srted = sorted(dataLst, key=lambda sub: (iso(sub[2]), -sub[1]))
</code></pre>
<p>Both give you the same output:</p>
<pre><code> In [24]: sorted(dataLst, key=lambda sub: (iso( sub[2]), -sub[1]))Out[24]:
[['Dave', 500, '08/01/2016'],
['Bob', 100, '08/10/2016'],
['Mike', 50, '08/10/2016'],
['Paul', -50, '08/20/2016'],
['Sam', 250, '08/30/2016']]
In [25]: sorted(dataLst, key=lambda sub: (strp(sub[2],"%m/%d/%Y"), -sub[1]))
Out[25]:
[['Dave', 500, '08/01/2016'],
['Bob', 100, '08/10/2016'],
['Mike', 50, '08/10/2016'],
['Paul', -50, '08/20/2016'],
['Sam', 250, '08/30/2016']]
</code></pre>
<p>The difference is splitting is way faster as you can see below:</p>
<pre><code>In [28]: timeit sorted(dataLst, key=lambda sub: (strp(sub[2],"%m/%d/%Y"), -sub[1]))
10000 loops, best of 3: 66.4 µs per loop
In [29]: timeit sorted(dataLst, key=lambda sub: (iso( sub[2]), -sub[1]))
100000 loops, best of 3: 4.97 µs per loop
</code></pre>
| 2 | 2016-09-04T00:06:25Z | [
"python",
"list",
"sorting"
] |
Trying to sort a list of tuples in python first by date then by greatest number | 39,312,362 | <p>I have a list of tuples and I am trying to sort by date and then by the greatest number. So basically when you have two dates that are the same it will then put the tuple with the greatest number first. See example below. </p>
<p><strong>My list of tuples</strong></p>
<pre><code>dataLst = [["Mike", 50, "08/10/2016"], ["Bob", 100, "08/10/2016"], ["Dave", 500, "08/01/2016"], ["Paul", -50, "08/20/2016"], ["Sam", 250, "08/30/2016"]]
</code></pre>
<p><strong>I then sort the list by the dates in the tuples.</strong></p>
<pre><code>sDataLst = sorted(dataLst, key=operator.itemgetter(2))
</code></pre>
<p><strong>I then sort the sorted list by the numbers in reverse order.</strong></p>
<pre><code>sorted(sDataLst,key=operator.itemgetter(1), reverse=True)
</code></pre>
<p><strong>When I print the sorted list I get the following.</strong></p>
<pre><code>print sDataLst
[['Dave', 500, '08/01/2016'], ['Mike', 50, '08/10/2016'], ['Bob', 100, '08/10/2016'], ['Paul', -50, '08/20/2016'], ['Sam', 250, '08/30/2016']]
</code></pre>
<p>If you look at the second and third item in the list which have the same date they should be reversed because the number in the third item is greater then the one in the second item. What I am looking for as a result is the following.</p>
<pre><code>[['Dave', 500, '08/01/2016'], ['Bob', 100, '08/10/2016'], ['Mike', 50, '08/10/2016'], ['Paul', -50, '08/20/2016'], ['Sam', 250, '08/30/2016']]
</code></pre>
<p>Any help on this would be greatly appreciated.</p>
<p>Thanks</p>
| 2 | 2016-09-03T23:58:30Z | 39,312,405 | <p>You need to reverse the order of the sorts - the "tie-breakers" are done before the "main" sort which works because Python's sort is stable, so they retain the order of the tiebreaker when sorted into the main order, eg:</p>
<pre><code>from datetime import datetime
from operator import itemgetter
dataLst = [["Mike", 50, "08/10/2016"], ["Bob", 100, "08/10/2016"], ["Dave", 500, "08/01/2016"], ["Paul", -50, "08/20/2016"], ["Sam", 250, "08/30/2016"]]
# Sort the tie breaker first
dataLst.sort(key=itemgetter(1), reverse=True)
# Sort on the main key - here we'll use `strptime` to sort as a proper date
dataLst.sort(key=lambda L: datetime.strptime(L[2], '%m/%d/%Y'))
</code></pre>
<p>This gives:</p>
<pre><code>[['Dave', 500, '08/01/2016'],
['Bob', 100, '08/10/2016'],
['Mike', 50, '08/10/2016'], # Bob and Mike properly ordered...
['Paul', -50, '08/20/2016'],
['Sam', 250, '08/30/2016']]
</code></pre>
| 2 | 2016-09-04T00:06:37Z | [
"python",
"list",
"sorting"
] |
Trying to sort a list of tuples in python first by date then by greatest number | 39,312,362 | <p>I have a list of tuples and I am trying to sort by date and then by the greatest number. So basically when you have two dates that are the same it will then put the tuple with the greatest number first. See example below. </p>
<p><strong>My list of tuples</strong></p>
<pre><code>dataLst = [["Mike", 50, "08/10/2016"], ["Bob", 100, "08/10/2016"], ["Dave", 500, "08/01/2016"], ["Paul", -50, "08/20/2016"], ["Sam", 250, "08/30/2016"]]
</code></pre>
<p><strong>I then sort the list by the dates in the tuples.</strong></p>
<pre><code>sDataLst = sorted(dataLst, key=operator.itemgetter(2))
</code></pre>
<p><strong>I then sort the sorted list by the numbers in reverse order.</strong></p>
<pre><code>sorted(sDataLst,key=operator.itemgetter(1), reverse=True)
</code></pre>
<p><strong>When I print the sorted list I get the following.</strong></p>
<pre><code>print sDataLst
[['Dave', 500, '08/01/2016'], ['Mike', 50, '08/10/2016'], ['Bob', 100, '08/10/2016'], ['Paul', -50, '08/20/2016'], ['Sam', 250, '08/30/2016']]
</code></pre>
<p>If you look at the second and third item in the list which have the same date they should be reversed because the number in the third item is greater then the one in the second item. What I am looking for as a result is the following.</p>
<pre><code>[['Dave', 500, '08/01/2016'], ['Bob', 100, '08/10/2016'], ['Mike', 50, '08/10/2016'], ['Paul', -50, '08/20/2016'], ['Sam', 250, '08/30/2016']]
</code></pre>
<p>Any help on this would be greatly appreciated.</p>
<p>Thanks</p>
| 2 | 2016-09-03T23:58:30Z | 39,312,877 | <p>Similar to @Ninja Puppy's answer, but in one sort iteration, not two:</p>
<pre><code>dataLst.sort(key=lambda l: (datetime.strptime(l[2], '%m/%d/%Y'), -l[1]))
</code></pre>
| 0 | 2016-09-04T01:52:14Z | [
"python",
"list",
"sorting"
] |
How to merge multiple files? | 39,312,470 | <p>My files are in txt format and I wrote a short code to merge all three into a single one. Input files are (1) 18.8MB with over 16K columns, (2) 18.8MB with over 16K columns and (3) 10.5MB with over 7K columns. The code works, however it only merges first two files and creates output file. The data from the third input file is not included. What is wrong here and is there any limit regarding the size for txt files?</p>
<pre><code>filenames = ['/Users/icalic/Desktop/chr_1/out_chr1_firstset.txt', '/Users/icalic/Desktop/chr_1/out_chr1_secondset.txt', '/Users/icalic/Desktop/chr_1/out_chr1_thirdset.txt']
with open('/Users/icalic/Desktop/chr1_allfinal.txt', 'w') as outfile:
for fname in filenames:
with open(fname) as infile:
for line in infile:
outfile.write(line)
</code></pre>
| 0 | 2016-09-04T00:20:01Z | 39,312,486 | <p>Simply use <a href="https://docs.python.org/3/library/fileinput.html" rel="nofollow"><code>fileinput</code></a> from the standard library:</p>
<pre><code>import fileinput
filenames = [ '...' ]
with open(output_file, 'w') as file_out, fileinput.input(filenames) as file_in:
file_out.writelines(file_in)
</code></pre>
<p>If you ever need finer control over memory use or need to handle binaries, use <code>shutil.copyfileobj</code>:</p>
<pre><code>filenames = [ '...' ]
buffer_length = 1024*1024*10 # 10 MB
with open('output_file.txt', 'wb') as out_file:
for filename in filenames:
with open(filename, 'rb') as in_file:
shutil.copyfileobj(in_file, out_file, buffer_length)
</code></pre>
| 2 | 2016-09-04T00:23:30Z | [
"python",
"python-3.x"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.