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 |
|---|---|---|---|---|---|---|---|---|---|
/n in beautiful soup text
| 39,322,134
|
<p>I'm trying to get the transcript for a youtube video for some NLP work, and I think I can get it fine, but there are also a couple of issues. For example: </p>
<pre><code>from xml.etree import cElementTree as ET
from bs4 import BeautifulSoup as bs
from urllib2 import urlopen
URL = 'http://video.google.com/timedtext?lang=en&v=KDHuWxy53uM'
def make_soup(url):
html = urlopen(url).read()
return bs(html, "lxml")
soup = make_soup(URL)
takeaways = soup.findAll('text')
All_text = []
for i in takeaways:
root = ET.fromstring(str(i))
reslist = list(root.iter())
try:
result = ' '.join([element.text for element in reslist])
except:
pass
All_text.append(result)
</code></pre>
<p>Sample result for one of the lines:</p>
<pre><code>'Let&#39;s learn a little bit\nabout the dot product.'
</code></pre>
<p>This seems ok to get the transcript, but I also get the /n which are the return characters from the xml and I also get this weird character in place of the apostrophes, which I think is due to encoding?</p>
<p>Anybody know how I can clean both of these up? As always, thank you all so much for any help you can give.</p>
| 2
|
2016-09-04T22:47:12Z
| 39,322,217
|
<p>&#39 - is unescaped HTML code , in <strong>python 3.2</strong> and above use </p>
<pre><code>import html
html.unescape(<your_string>)
</code></pre>
| 1
|
2016-09-04T23:05:32Z
|
[
"python",
"beautifulsoup"
] |
/n in beautiful soup text
| 39,322,134
|
<p>I'm trying to get the transcript for a youtube video for some NLP work, and I think I can get it fine, but there are also a couple of issues. For example: </p>
<pre><code>from xml.etree import cElementTree as ET
from bs4 import BeautifulSoup as bs
from urllib2 import urlopen
URL = 'http://video.google.com/timedtext?lang=en&v=KDHuWxy53uM'
def make_soup(url):
html = urlopen(url).read()
return bs(html, "lxml")
soup = make_soup(URL)
takeaways = soup.findAll('text')
All_text = []
for i in takeaways:
root = ET.fromstring(str(i))
reslist = list(root.iter())
try:
result = ' '.join([element.text for element in reslist])
except:
pass
All_text.append(result)
</code></pre>
<p>Sample result for one of the lines:</p>
<pre><code>'Let&#39;s learn a little bit\nabout the dot product.'
</code></pre>
<p>This seems ok to get the transcript, but I also get the /n which are the return characters from the xml and I also get this weird character in place of the apostrophes, which I think is due to encoding?</p>
<p>Anybody know how I can clean both of these up? As always, thank you all so much for any help you can give.</p>
| 2
|
2016-09-04T22:47:12Z
| 39,322,569
|
<p>The <code>\n</code> are newlines which you will have to manually replace if you don't want them, the <a href="http://www.w3schools.com/html/html_entities.asp">html entities</a> can be unescaped with <a href="https://docs.python.org/2/library/htmlparser.html">HTMLParser</a> using python2 or <a href="http://import%20html%20html.unescape(%3Cyour_string%3E)">html.parser</a> using python3 as mentioned in the other answer. </p>
<p>Also since you are parsing <em>xml</em> and you have <em>lxml</em> installed, your code can be simplified to:</p>
<pre><code>import lxml.etree as et
from HTMLParser import HTMLParser
unescape = HTMLParser().unescape
URL = 'http://video.google.com/timedtext?lang=en&v=KDHuWxy53uM'
tree = et.parse(URL)
print([unescape(t.replace("\n", " ")) for t in tree.xpath('//text/text()')])
</code></pre>
<p>Which would give you:</p>
<pre><code>[u"Let's learn a little bit about the dot product.", 'The dot product, frankly, out of the two ways of multiplying', 'vectors, I think is the easier one.', 'So what does the dot product do?', u"Why don't I give you the definition, and then I'll give", 'you an intuition.', u"So if I have two vectors; vector a dot vector b-- that's", 'how I draw my arrows.', 'I can draw my arrows like that.', 'That is equal to the magnitude of vector a times the', 'magnitude of vector b times cosine of the', 'angle between them.', 'Now where does this come from?', 'This might seem a little arbitrary, but I think with a', 'visual explanation, it will make a little bit more sense.', 'So let me draw, arbitrarily, these two vectors.', 'So that is my vector a-- nice big and fat vector.', u"It's good for showing the point.", 'And let me draw vector b like that.', 'Vector b.', 'And then let me draw the cosine, or let me, at least,', 'draw the angle between them.', 'This is theta.', u"So there's two ways of view this.", 'Let me label them.', 'This is vector a.', u"I'm trying to be color consistent.", 'This is vector b.', u"So there's two ways of viewing this product.", 'You could view it as vector a-- because multiplication is', 'associative, you could switch the order.', 'So this could also be written as, the magnitude of vector a', u"times cosine of theta, times-- and I'll do it in color", 'appropriate-- vector b.', 'And this times, this is the dot product.', u"I almost don't have to write it.", 'This is just regular multiplication, because these', 'are all scalar quantities.', u"When you see the dot between vectors, you're talking about", 'the vector dot product.', 'So if we were to just rearrange this expression this', 'way, what does it mean?', 'What is a cosine of theta?', 'Let me ask you a question.', 'If I were to drop a right angle, right here,', u"perpendicular to b-- so let's just drop a right angle", 'there-- cosine of theta soh-coh-toa so, cah cosine--', 'is equal to adjacent of a hypotenuse, right?', u"Well, what's the adjacent?", u"It's equal to this.", 'And the hypotenuse is equal to the magnitude of a, right?', 'Let me re-write that.', 'So cosine of theta-- and this applies to the a vector.', 'Cosine of theta of this angle is equal to ajacent, which', u"is-- I don't know what you could call this-- let's call", 'this the projection of a onto b.', u"It's like if you were to shine a light perpendicular to b--", 'if there was a light source here and the light was', 'straight down, it would be the shadow of a onto b.', 'Or you could almost think of it as the part of a that goes', 'in the same direction of b.', 'So this projection, they call it-- at least the way I get', 'the intuition of what a projection is, I kind of view', 'it as a shadow.', 'If you had a light source that came up perpendicular, what', 'would be the shadow of that vector on to this one?', 'So if you think about it, this shadow right here-- you could', 'call that, the projection of a onto b.', u"Or, I don't know.", u"Let's just call it, a sub b.", u"And it's the magnitude of it, right?", u"It's how much of vector a goes on vector b over-- that's the", 'adjacent side-- over the hypotenuse.', 'The hypotenuse is just the magnitude of vector a.', u"It's just our basic calculus.", 'Or another way you could view it, just multiply both sides', 'by the magnitude of vector a.', 'You get the projection of a onto b, which is just a fancy', 'way of saying, this side; the part of a that goes in the', 'same direction as b-- is another way to say it-- is', 'equal to just multiplying both sides times the magnitude of a', 'is equal to the magnitude of a, cosine of theta.', 'Which is exactly what we have up here.', 'And the definition of the dot product.', 'So another way of visualizing the dot product is, you could', 'replace this term with the magnitude of the projection of', 'a onto b-- which is just this-- times the', 'magnitude of b.', u"That's interesting.", u"All the dot product of two vectors is-- let's just take", 'one vector.', u"Let's figure out how much of that vector-- what component", u"of it's magnitude-- goes in the same direction as the", u"other vector, and let's just multiply them.", 'And where is that useful?', 'Well, think about it.', 'What about work?', 'When we learned work in physics?', 'Work is force times distance.', u"But it's not just the total force", 'times the total distance.', u"It's the force going in the same", 'direction as the distance.', u"You should review the physics playlist if you're watching", u"this within the calculus playlist. Let's say I have a", '10 newton object.', u"It's sitting on ice, so there's no friction.", u"We don't want to worry about fiction right now.", u"And let's say I pull on it.", u"Let's say my force vector-- This is my force vector.", u"Let's say my force vector is 100 newtons.", u"I'm making the numbers up.", '100 newtons.', u"And Let's say I slide it to the right, so my distance", 'vector is 10 meters parallel to the ground.', 'And the angle between them is equal to 60 degrees, which is', 'the same thing is pi over 3.', u"We'll stick to degrees.", u"It's a little bit more intuitive.", u"It's 60 degrees.", 'This distance right here is 10 meters.', 'So my question is, by pulling on this rope, or whatever, at', 'the 60 degree angle, with a force of 100 newtons, and', 'pulling this block to the right for 10 meters, how much', 'work am I doing?', 'Well, work is force times the distance, but not just the', 'total force.', 'The magnitude of the force in the direction of the distance.', u"So what's the magnitude of the force in the", 'direction of the distance?', 'It would be the horizontal component of this force', 'vector, right?', 'So it would be 100 newtons times the', 'cosine of 60 degrees.', 'It will tell you how much of that 100', 'newtons goes to the right.', 'Or another way you could view it if this', 'is the force vector.', 'And this down here is the distance vector.', 'You could say that the total work you performed is equal to', 'the force vector dot the distance vector, using the dot', 'product-- taking the dot product, to the force and the', 'distance factor.', 'And we know that the definition is the magnitude of', 'the force vector, which is 100 newtons, times the magnitude', 'of the distance vector, which is 10 meters, times the cosine', 'of the angle between them.', 'Cosine of the angle is 60 degrees.', u"So that's equal to 1,000 newton meters", 'times cosine of 60.', 'Cosine of 60 is what?', u"It's square root of 3 over 2.", 'Square root of 3 over 2, if I remember correctly.', 'So times the square root of 3 over 2.', 'So the 2 becomes 500.', 'So it becomes 500 square roots of 3 joules, whatever that is.', u"I don't know 700 something, I'm guessing.", u"Maybe it's 800 something.", u"I'm not quite sure.", 'But the important thing to realize is that the dot', 'product is useful.', 'It applies to work.', 'It actually calculates what component of what vector goes', 'in the other direction.', 'Now you could interpret it the other way.', 'You could say this is the magnitude of a', 'times b cosine of theta.', u"And that's completely valid.", u"And what's b cosine of theta?", 'Well, if you took b cosine of theta, and you could work this', u"out as an exercise for yourself, that's the amount of", u"the magnitude of the b vector that's", 'going in the a direction.', u"So it doesn't matter what order you go.", 'So when you take the cross product, it matters whether', 'you do a cross b, or b cross a.', u"But when you're doing the dot product, it doesn't matter", 'what order.', 'So b cosine theta would be the magnitude of vector b that', 'goes in the direction of a.', 'So if you were to draw a perpendicular line here, b', 'cosine theta would be this vector.', 'That would be b cosine theta.', 'The magnitude of b cosine theta.', 'So you could say how much of vector b goes in the same', 'direction as a?', 'Then multiply the two magnitudes.', 'Or you could say how much of vector a goes in the same', 'direction is vector b?', 'And then multiply the two magnitudes.', 'And now, this is, I think, a good time to just make sure', 'you understand the difference between the dot product and', 'the cross product.', 'The dot product ends up with just a number.', 'You multiply two vectors and all you have is a number.', 'You end up with just a scalar quantity.', 'And why is that interesting?', 'Well, it tells you how much do these-- you could almost say--', 'these vectors reinforce each other.', u"Because you're taking the parts of their magnitudes that", 'go in the same direction and multiplying them.', 'The cross product is actually almost the opposite.', u"You're taking their orthogonal components, right?", 'The difference was, this was a a sine of theta.', u"I don't want to mess you up this picture too much.", 'But you should review the cross product videos.', u"And I'll do another video where I actually compare and", 'contrast them.', u"But the cross product is, you're saying, let's multiply", 'the magnitudes of the vectors that are perpendicular to each', u"other, that aren't going in the same direction, that are", 'actually orthogonal to each other.', u"And then, you have to pick a direction since you're not", 'saying, well, the same direction that', u"they're both going in.", u"So you're picking the direction that's orthogonal to", 'both vectors.', u"And then, that's why the orientation matters and you", u"have to take the right hand rule, because there's actually", 'two vectors that are perpendicular to any other two', 'vectors in three dimensions.', u"Anyway, I'm all out of time.", u"I'll continue this, hopefully not too confusing, discussion", 'in the next video.', u"I'll compare and contrast the cross", 'product and the dot product.', 'See you in the next video.']
</code></pre>
<p>On a side note, if <code>result</code> did not get defined on the first iteration your code would error, if it did it on any other iteration you would get the last result appended again, you would need a <em>continue</em> where you have the <em>pass</em>, Also you should never use a blanket except, catch what you expect and print/log the error.</p>
| 5
|
2016-09-05T00:16:57Z
|
[
"python",
"beautifulsoup"
] |
Python GTK: Add a button to a GUI with another button
| 39,322,137
|
<p>I'm trying to add another button to my GUI by pressing a button on the GUI itself. Essentially I'm just trying to update it but I'm relatively new to OOP so I'm having issues with scope. </p>
<p>This is what I have so far...</p>
<pre><code> 1 #!/usr/bin/env python
2 import random, gi, sys
3 from gi.repository import Gtk
4 import itertools
23 class Deck:
24 """A sample card deck"""
25 def __init__(self):
26 deck = []
27 self.color_list = ["red", "green", "blue"]
28 for color in self.color_list:
29 for i in range (1,2):
30 deck.append((color, i))
31 self.deck = deck
32
33 def draw_card(self):
34 print self.deck
35 try:
36 card = self.deck.pop()
37 print self.deck
38 return card
39 except IndexError:
40 print "No cards in deck!"
41 return
56 class MyWindow(Gtk.Window):
57
58 def __init__(self):
59 Gtk.Window.__init__(self, title="RGB 3, 2, 1... GO!")
60 self.set_border_width(10)
61 self.set_size_request(450,150)
62
63 grid = Gtk.Grid()
64 self.add(grid)
65
66 draw_button = Gtk.Button(label="Draw Card")
67 draw_button.connect("clicked", self.on_draw_button_clicked)
68 grid.attach(draw_button,0,0,1,1)
69
70 end_button = Gtk.Button(label="End Game")
71 end_button.connect("clicked", self.on_stop_button_clicked)
72 grid.attach_next_to(end_button,draw_button,Gtk.PositionType.RIGHT,1,1)
73
74 update_button = Gtk.Button(label="Update")
75 update_button.connect("clicked", self.update, grid)
76 grid.attach_next_to(update_button,end_button,Gtk.PositionType.RIGHT,1,1)
77
78 def update(self, widget, grid):
79 card1_button = Gtk.Button(label="card1")
80 card1_button.connect("clicked", self.on_card1_button_clicked)
81 grid.attach_next_to(card1_button,draw_button,Gtk.PositionType.BOTTOM,3,1)
82
83 def on_draw_button_clicked(self, widget):
84 +--- 13 lines: card = my_deck.draw_card()----------------------------------------------------------------------------------------------------
97
98 def on_stop_button_clicked(self, widget):
99 Gtk.main_quit()
100
101 def on_card1_button_clicked(self, widget):
102 Gtk.main_quit()
121 # Objects must be instantiated here
122 my_deck = Deck()
123 print my_deck.deck
124 win = MyWindow()
125 win.connect("delete-event", Gtk.main_quit)
126 win.show_all()
127 Gtk.main()
</code></pre>
<p>When I run this, my GUI pops open. And when I hit my update button I get the following error: </p>
<pre><code>Traceback (most recent call last):
File "game1.py", line 85, in update
grid.attach_next_to(card1_button,draw_button,Gtk.PositionType.BOTTOM,3,1)
NameError: global name 'draw_button' is not defined
</code></pre>
<p>How do I get my update function to recognize the GUI/grid I've already created in the def <strong>init</strong> function? Is there a better way to do what I want? </p>
| 0
|
2016-09-04T22:48:02Z
| 39,322,649
|
<p>Define an <a href="https://docs.python.org/3/tutorial/classes.html#class-and-instance-variables" rel="nofollow">instance variable</a> in your <code>MyWindow</code> class to keep track of that button. </p>
<p>For example, in your code, whenever you see a <code>draw_button</code> change it to <code>self.draw_button</code>. It will let you track this button in other methods. This would look like:</p>
<pre><code>import random, gi, sys
from gi.repository import Gtk
import itertools
class Deck:
"""A sample card deck"""
def __init__(self):
deck = []
self.color_list = ["red", "green", "blue"]
for color in self.color_list:
for i in range(1,2):
deck.append((color, i))
self.deck = deck
def draw_card(self):
print self.deck
try:
card = self.deck.pop()
print self.deck
return card
except IndexError:
print "No cards in deck!"
return
class MyWindow(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self, title="RGB 3, 2, 1... GO!")
self.set_border_width(10)
self.set_size_request(450,150)
grid = Gtk.Grid()
self.add(grid)
# Here we create the instance variable and use it afterward
self.draw_button = Gtk.Button(label="Draw Card")
self.draw_button.connect("clicked", self.on_draw_button_clicked)
grid.attach(self.draw_button,0,0,1,1)
end_button = Gtk.Button(label="End Game")
end_button.connect("clicked", self.on_stop_button_clicked)
grid.attach_next_to(end_button, self.draw_button, Gtk.PositionType.RIGHT, 1, 1)
update_button = Gtk.Button(label="Update")
update_button.connect("clicked", self.update, grid)
grid.attach_next_to(card1_button, self.draw_button, Gtk.PositionType.BOTTOM, 3, 1)
def update(self, widget, grid):
card1_button = Gtk.Button(label="card1")
card1_button.connect("clicked", self.on_card1_button_clicked)
# Here we recall the value stored in self.draw_button
grid.attach_next_to(card1_button, self.draw_button, Gtk.PositionType.BOTTOM, 3, 1)
def on_draw_button_clicked(self, widget):
for x in range(13):
card = my_deck.draw_card()
def on_stop_button_clicked(self, widget):
Gtk.main_quit()
def on_card1_button_clicked(self, widget):
Gtk.main_quit()
# Objects must be instantiated here
my_deck = Deck()
print my_deck.deck
win = MyWindow()
win.connect("delete-event", Gtk.main_quit)
win.show_all()
Gtk.main()
</code></pre>
<p>But there are a few other problems in your code:</p>
<ul>
<li><p>I presume that you are using Gtk 3.0. If that's the case, you should require it before importing Gtk like this:</p>
<pre><code>gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
</code></pre></li>
<li><p>In <code>Deck.__init__()</code> you have used <code>range(1,2)</code> in a for-loop. The problem is that <code>range(1, 2)</code> is equivalent to <code>[1]</code> because you have asked for a range beginning at 1 but stopping just before 2. I'm not sure that was what you wanted.</p></li>
<li>You should add a <code>self.show_all()</code> at the end of your <code>MyWindow.update()</code> method otherwise you won't be able to see the freshly created button.</li>
<li>You should use <code>self.close()</code> instead of <code>Gtk.main_quit()</code> in your <code>MyWindow.on_stop_button_clicked()</code> and <code>MyWindow.on_card1_button_clicked()</code> methods otherwise your code won't be able to properly destroy your window when clicking those buttons.</li>
</ul>
<p>This is how this would look with these recommendations:</p>
<pre><code>import random, gi, sys
import itertools
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
class Deck:
"""A sample card deck"""
def __init__(self):
deck = []
self.color_list = ["red", "green", "blue"]
for color in self.color_list:
for i in range(1,2): # Check to see if this is valid
deck.append((color, i))
self.deck = deck
def draw_card(self):
print self.deck
try:
card = self.deck.pop()
print self.deck
return card
except IndexError:
print "No cards in deck!"
return
class MyWindow(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self, title="RGB 3, 2, 1... GO!")
self.set_border_width(10)
self.set_size_request(450,150)
grid = Gtk.Grid()
self.add(grid)
self.draw_button = Gtk.Button(label="Draw Card")
self.draw_button.connect("clicked", self.on_draw_button_clicked)
grid.attach(self.draw_button,0,0,1,1)
end_button = Gtk.Button(label="End Game")
end_button.connect("clicked", self.on_stop_button_clicked)
grid.attach_next_to(end_button, self.draw_button, Gtk.PositionType.RIGHT, 1, 1)
update_button = Gtk.Button(label="Update")
update_button.connect("clicked", self.update, grid)
grid.attach_next_to(update_button, end_button, Gtk.PositionType.RIGHT, 1, 1)
def update(self, widget, grid):
card1_button = Gtk.Button(label="card1")
card1_button.connect("clicked", self.on_card1_button_clicked)
grid.attach_next_to(card1_button, self.draw_button, Gtk.PositionType.BOTTOM, 3, 1)
self.show_all() # So that we can see the freshly created button
def on_draw_button_clicked(self, widget):
for x in range(13):
card = my_deck.draw_card()
def on_stop_button_clicked(self, widget):
self.close() # Instead of Gtk.main_quit()
def on_card1_button_clicked(self, widget):
self.close() # Instead of Gtk.main_quit()
# Objects must be instantiated here
my_deck = Deck()
print my_deck.deck
win = MyWindow()
win.connect("delete-event", Gtk.main_quit)
win.show_all()
Gtk.main()
</code></pre>
| 1
|
2016-09-05T00:35:02Z
|
[
"python",
"oop",
"gtk"
] |
compare two results (of many) from api data with django/python
| 39,322,150
|
<p>I'm learning django/python/css/etc... and while doing this, I've decided to build an app for my website that can pull simple movie data from TMDb. What I'm having trouble with is figuring out a way to add a way for the <strong>user to select two different movies, and once selected, see the differences between them (run time, budget, etc).</strong></p>
<p>I've got grabbing the data from the API covered in that doing a search for a movie on my site returns expected results. But now I'm having a really tough time trying to figure out <strong>how to select 1 item from the results to "save" it, search again, select the second movie, and have the comparison show up.</strong></p>
<p>I know it's pretty vague, but any help getting me pointed in the right direction would be greatly appreciated!</p>
<p>here's what I'm doing so far with the code:</p>
<p>views.py:</p>
<pre><code>from django.shortcuts import render
from django.conf import settings
from .forms import MovieSearch
import tmdbsimple as tmdb
tmdb.API_KEY = settings.TMDB_API_KEY
def search_movie(request):
"""
Search movie title and return 5 pages of results
"""
parsed_data = {'results': []}
if request.method == 'POST':
form = MovieSearch(request.POST)
if form.is_valid():
search = tmdb.Search()
query = form.cleaned_data['moviename']
response = search.movie(query=query)
for movie in response['results']:
parsed_data['results'].append(
{
'title': movie['title'],
'id': movie['id'],
'poster_path': movie['poster_path'],
'release_date': movie['release_date'][:-6],
'popularity': movie['popularity'],
'overview': movie['overview']
}
)
for i in range(2, 5 + 1):
response = search.movie(query=query, page=i)
for movie in response['results']:
parsed_data['results'].append(
{
'title': movie['title'],
'id': movie['id'],
'poster_path': movie['poster_path'],
'release_date': movie['release_date'][:-6],
'popularity': movie['popularity'],
'overview': movie['overview']
}
)
context = {
"form": form,
"parsed_data": parsed_data
}
return render(request, './moviecompare/movies.html', context)
else:
form = MovieSearch()
else:
form = MovieSearch()
return render(request, './moviecompare/compare.html', {"form": form})
def get_movie(request, movid):
"""
from search/movie results, get details by movie id (movid)
"""
movie = tmdb.Movies(movid)
response = movie.info()
context = {
'response': response
}
return render(request, './moviecompare/detail.html', context)
</code></pre>
<p>movies.html:</p>
<pre><code>{% extends 'moviecompare/compare.html' %}
{% block movies_returned %}
<div class="wrap">
<div class="compare-gallery">
{% for key in parsed_data.results|dictsortreversed:'release_date' %}
{% if key.poster_path and key.release_date and key.title and key.overview %}
<div class="gallery-item">
<img src="http://image.tmdb.org/t/p/w185/{{ key.poster_path }}">
<div class="gallery-text">
<div class="gallery-date"><h5><span><i class="material-icons">date_range</i></span> {{ key.release_date }}</h5></div>
<div class="gallery-title"><h3><a href="{% url 'compare:movie_detail' movid=key.id %}">{{ key.title }}</a></h3></div>
<div class="gallery-overview">{{ key.overview|truncatechars:80 }}</div>
</div>
</div>
{% endif %}
{% endfor %}
</div>
</div>
{% endblock %}
</code></pre>
<p>and I've got a simple detail.html that doesn't do anything just yet, but it's just for showing detail results for a single movie, so not important to get into yet as it'll just be styling.</p>
<p>I'd like for each result in the gallery to have a link to a details page for the movie(done), and also a select box (or similar) to select it as one of the comparison movies.</p>
<p>If I can just get some help on how to select two different movies from the search results, and compare those, I think I could work out a way to do the same with two separate movie searches. Thanks for any help!</p>
<p>edit: here's what I have so far on <a href="http://moniblog.pythonanywhere.com/compare/" rel="nofollow">pythonanywhere</a> - </p>
| 0
|
2016-09-04T22:51:17Z
| 39,482,880
|
<p>Assuming you want to be able to add movies from different searches (e.g. search for rambo, add rambo, search for south park, add south park), you can probably do something like:</p>
<pre><code>@require_POST
def save_compare(request, pk):
""" Async endpoint to add movies to comparison list """
movies = request.session.get('comparing_moviews', [])
movies.append(movies)
# if you only need the data the API served originally, you could also save that to a data-base when you read it from the API and use it here
request.session['comparing_movies'] = movies
return JsonResponse("")
def show_comparison(request):
""" show differing stats like "1 hour 3 mins longer """
mov1, mov2 = request.session.get('comparing_movies') # need to handle wrong number of selected
# not sure from the description how to look up the movies by id
mov1 = tmdb.Search().search(pk=mov1)
mov2 = tmdb.Search().search(pk=mov2)
return render_to_response("comparison.html", context={
"mov1": mov1, "mov2": mov2,
"length_diff": mov1['length'] - mov2['length']})
</code></pre>
<p>to give you the comparison stats you want. You'll also need <a href="https://docs.djangoproject.com/en/1.10/topics/http/sessions/" rel="nofollow">session middleware</a> installed.</p>
<p>From the search results page, you'll add a button that triggers an async js post to <code>save_compare</code> which starts accumulating a comparison list. When they're done, they can click "compare" or something on that list, which will render "comparison.html" with the two movies and the diff however you like it.</p>
<p>As an example of some calculation for your "comparison.html", you can grab the hours and minutes from the <code>length_diff</code> and render them as "X hours and y minutes longer."</p>
| 0
|
2016-09-14T05:11:58Z
|
[
"javascript",
"python",
"html",
"django"
] |
What is the most effective method of storing and recalling data?
| 39,322,242
|
<p>I've been wanting to build a pretty big project which pretty much mimics Twitter, I've just started it and have run into a little error with account creation. I was wondering what the best method of storing and recalling data is. I'm well aware I can use .txt files to do this, but then I've found it's trickier to make the program recognize the structure of the data.</p>
<pre><code>For example, the file might look like this:
acnt - twigman
pass - yellow
</code></pre>
<p>And the user creating an account might use the same name, and I would need to stop that, but I wouldn't know how to make the program know where the username starts and ends.</p>
<p>If I could use a database within the Python program, that would be a heck of a lot easier, it would mean the program can run as just one file and it would be easier to code. The program could also recognize the beginning and end of a user name without needing to write more script for it.</p>
<p>Thank you for your help.</p>
| 0
|
2016-09-04T23:11:02Z
| 39,322,289
|
<p>Connecting to a database is really the way to go here. This gets deep pretty fast, but as far as handling the python sytax it's fairly straightforward. This answer handles that subject well:</p>
<p><a href="http://stackoverflow.com/questions/372885/how-do-i-connect-to-a-mysql-database-in-python">How do I connect to a MySQL Database in Python?</a></p>
<p>If you are truly going to be interacting with real users, you should learn about how to properly secure their passwords via hashing or other methods. <strong>Storing passwords in plain text is a big no-no.</strong> Here's an interesting place to start for password hashing in Python:</p>
<p><a href="http://stackoverflow.com/questions/2572099/pythons-safest-method-to-store-and-retrieve-passwords-from-a-database">Python's safest method to store and retrieve passwords from a database</a></p>
| 0
|
2016-09-04T23:19:40Z
|
[
"python",
"database",
"import",
"export"
] |
What is the most effective method of storing and recalling data?
| 39,322,242
|
<p>I've been wanting to build a pretty big project which pretty much mimics Twitter, I've just started it and have run into a little error with account creation. I was wondering what the best method of storing and recalling data is. I'm well aware I can use .txt files to do this, but then I've found it's trickier to make the program recognize the structure of the data.</p>
<pre><code>For example, the file might look like this:
acnt - twigman
pass - yellow
</code></pre>
<p>And the user creating an account might use the same name, and I would need to stop that, but I wouldn't know how to make the program know where the username starts and ends.</p>
<p>If I could use a database within the Python program, that would be a heck of a lot easier, it would mean the program can run as just one file and it would be easier to code. The program could also recognize the beginning and end of a user name without needing to write more script for it.</p>
<p>Thank you for your help.</p>
| 0
|
2016-09-04T23:11:02Z
| 39,322,365
|
<p>Your expectations of Python are very low. That is great news because you are going to be very happy.</p>
<p>You can definitely use a database with Python. The simplest and quickest to set up as well as closest to what you described is a file database: SQLite. <a href="http://zetcode.com/db/sqlitepythontutorial/" rel="nofollow">Here</a> is a great tutorial to start.</p>
<p>If you want to stick to simpler than than, you can use the <a href="https://wiki.python.org/moin/UsingPickle" rel="nofollow">pickle module</a> or the <a href="https://docs.python.org/2/library/shelve.html" rel="nofollow">shelve module</a> to âpersistâ your data </p>
<p>Of course, once your database increases significantly in size, you can move on to MySQL or PostgreSQL or others.</p>
<p>I encourage you to check out database abstraction tools such as <a href="http://www.sqlalchemy.org/" rel="nofollow">SQLAlchemy</a> as they can make your life easier.</p>
<p>If you are building a web application, then why reinvent the wheel? Choose one from the <a href="https://wiki.python.org/moin/WebFrameworks" rel="nofollow">many Python web frameworks</a>. Some if not all of them abstract away the database so you can focus on your application and its features.</p>
| 1
|
2016-09-04T23:31:35Z
|
[
"python",
"database",
"import",
"export"
] |
What is the most effective method of storing and recalling data?
| 39,322,242
|
<p>I've been wanting to build a pretty big project which pretty much mimics Twitter, I've just started it and have run into a little error with account creation. I was wondering what the best method of storing and recalling data is. I'm well aware I can use .txt files to do this, but then I've found it's trickier to make the program recognize the structure of the data.</p>
<pre><code>For example, the file might look like this:
acnt - twigman
pass - yellow
</code></pre>
<p>And the user creating an account might use the same name, and I would need to stop that, but I wouldn't know how to make the program know where the username starts and ends.</p>
<p>If I could use a database within the Python program, that would be a heck of a lot easier, it would mean the program can run as just one file and it would be easier to code. The program could also recognize the beginning and end of a user name without needing to write more script for it.</p>
<p>Thank you for your help.</p>
| 0
|
2016-09-04T23:11:02Z
| 39,322,378
|
<p>Use SQLite or any other RDBMS like PostgreSQL.
To use Python with RDBMS:
<a href="https://wiki.python.org/moin/DatabaseInterfaces" rel="nofollow">https://wiki.python.org/moin/DatabaseInterfaces</a></p>
| 0
|
2016-09-04T23:34:55Z
|
[
"python",
"database",
"import",
"export"
] |
Execute and create one python script from another
| 39,322,308
|
<p>Suppose, I have a python script <code>test1.py</code> , executing of <code>test1.py</code> will create a copy of that file, let's say <code>test2.py</code> . Now, I want to run <code>test1.py</code> in such a way that first it will create <code>test2.py</code> and then will execute <code>test2.py</code> . </p>
<p>This is my <code>test1.py</code> python script looks like, </p>
<pre><code>import io
import shutil
import os
shutil.copy2('test1.py', 'test2.py')
os.system("test2.py")
</code></pre>
<p>But out is saying <code>test2.py: not found</code></p>
| 0
|
2016-09-04T23:22:33Z
| 39,322,356
|
<p>Run python with <code>test2.py</code> as it's first argument.</p>
<pre><code>os.system("python test2.py")
</code></pre>
<p>If you say what's your goal of this action. We can help you better.</p>
| 1
|
2016-09-04T23:30:59Z
|
[
"python"
] |
tf.train.shuffle_batch not working for me
| 39,322,441
|
<p>I'm trying to process my input data using the TensorFlow clean way (tf.train.shuffle_batch), most of this code I gathered from the tutorials with slight modifications like the decode_jpeg function.</p>
<pre><code>size = 32,32
classes = 43
train_size = 12760
batch_size = 100
max_steps = 10000
def read_and_decode(filename_queue):
reader = tf.TFRecordReader()
_, serialized_example = reader.read(filename_queue)
features = tf.parse_single_example(
serialized_example,
# Defaults are not specified since both keys are required.
features={
'image/encoded': tf.FixedLenFeature([], tf.string),
'image/class/label': tf.FixedLenFeature([], tf.int64),
'image/height': tf.FixedLenFeature([], tf.int64),
'image/width': tf.FixedLenFeature([], tf.int64),
})
label = tf.cast(features['image/class/label'], tf.int32)
reshaped_image = tf.image.decode_jpeg(features['image/encoded'])
reshaped_image = tf.image.resize_images(reshaped_image, size[0], size[1], method = 0)
reshaped_image = tf.image.per_image_whitening(reshaped_image)
return reshaped_image, label
def inputs(train, batch_size, num_epochs):
subset = "train"
tf_record_pattern = os.path.join(FLAGS.train_dir + '/GTSRB', '%s-*' % subset)
data_files = tf.gfile.Glob(tf_record_pattern)
filename_queue = tf.train.string_input_producer(
data_files, num_epochs=num_epochs)
# Even when reading in multiple threads, share the filename
# queue.
image, label = read_and_decode(filename_queue)
# Shuffle the examples and collect them into batch_size batches.
# (Internally uses a RandomShuffleQueue.)
# We run this in two threads to avoid being a bottleneck.
images, sparse_labels = tf.train.shuffle_batch(
[image, label], batch_size=batch_size, num_threads=2,
capacity=1000 + 3 * batch_size,
# Ensures a minimum amount of shuffling of examples.
min_after_dequeue=1000)
return images, sparse_labels
</code></pre>
<p>When I try to run</p>
<pre><code>batch_x, batch_y = inputs(True, 100,100)
</code></pre>
<p>I get the following error:</p>
<pre><code>---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-6-543290a0c903> in <module>()
----> 1 batch_x, batch_y = inputs(True, 100,100)
<ipython-input-5-a8c07c7fc263> in inputs(train, batch_size, num_epochs)
73 capacity=1000 + 3 * batch_size,
74 # Ensures a minimum amount of shuffling of examples.
---> 75 min_after_dequeue=1000)
76 #return image, label
77 return images, sparse_labels
/Users/Kevin/tensorflow/lib/python2.7/site-packages/tensorflow/python/training/input.pyc in shuffle_batch(tensors, batch_size, capacity, min_after_dequeue, num_threads, seed, enqueue_many, shapes, allow_smaller_final_batch, shared_name, name)
800 queue = data_flow_ops.RandomShuffleQueue(
801 capacity=capacity, min_after_dequeue=min_after_dequeue, seed=seed,
--> 802 dtypes=types, shapes=shapes, shared_name=shared_name)
803 _enqueue(queue, tensor_list, num_threads, enqueue_many)
804 full = (math_ops.cast(math_ops.maximum(0, queue.size() - min_after_dequeue),
/Users/Kevin/tensorflow/lib/python2.7/site-packages/tensorflow/python/ops/data_flow_ops.pyc in __init__(self, capacity, min_after_dequeue, dtypes, shapes, names, seed, shared_name, name)
580 """
581 dtypes = _as_type_list(dtypes)
--> 582 shapes = _as_shape_list(shapes, dtypes)
583 names = _as_name_list(names, dtypes)
584 # If shared_name is provided and an op seed was not provided, we must ensure
/Users/Kevin/tensorflow/lib/python2.7/site-packages/tensorflow/python/ops/data_flow_ops.pyc in _as_shape_list(shapes, dtypes, unknown_dim_allowed, unknown_rank_allowed)
70 if not unknown_dim_allowed:
71 if any([not shape.is_fully_defined() for shape in shapes]):
---> 72 raise ValueError("All shapes must be fully defined: %s" % shapes)
73 if not unknown_rank_allowed:
74 if any([shape.dims is None for shape in shapes]):
ValueError: All shapes must be fully defined: [TensorShape([Dimension(32), Dimension(32), Dimension(None)]), TensorShape([])]
</code></pre>
<p>I'm not sure what is causing this error, I imagine it has something to do with the way I'm processing my image because it shows that they have no dimensions when they should have 3 channels (RGB).</p>
| 0
|
2016-09-04T23:47:36Z
| 39,322,554
|
<p>The <a href="https://www.tensorflow.org/versions/r0.10/api_docs/python/io_ops.html#batching-at-the-end-of-an-input-pipeline" rel="nofollow">batching methods in TensorFlow</a> (<code>tf.train.batch()</code>, <code>tf.train.batch_join()</code>, <code>tf.train.shuffle_batch()</code>, and <code>tf.train.shuffle_batch_join()</code>) require that every element of the batch has the exact same shape*, so that they can be packed into dense tensors. In your code, it appears that the third dimension of the <code>image</code> tensor that you pass to <code>tf.train.shuffle_batch()</code> has unknown size. This corresponds to the number of channels in each image, which is 1 for monochrome images, 3 for color images, or 4 for color images with an alpha channel. If you pass an explicit <code>channels=N</code> (where <code>N</code> is 1, 3, or 4 as appropriate), this will give TensorFlow enough information about the shape of the image tensor to proceed.</p>
<hr>
<p> * With one exception: when you pass <code>dynamic_pad=True</code> to <code>tf.train.batch()</code> or <code>tf.train.batch_join()</code> the elements can have different shapes, but they must have the same rank. In general, this is used only for sequential data, rather than image data (where it will have undesirable behavior at the edges of the image).</p>
| 1
|
2016-09-05T00:14:04Z
|
[
"python",
"tensorflow"
] |
Creating a MongoDB-Backed RESTFul API With Python and Flask
| 39,322,466
|
<p>Im currently working on a MongoDB backed RESTFUL API with flask... However, Ive got a zone search query set up with find_one(), however as soon as I try making it a larger query with multiple results using find(), I get the following error on postman :</p>
<pre><code>UnboundLocalError: local variable 'output' referenced before assignment
</code></pre>
<p>this is the code that works, however it only returns one document from the query:</p>
<pre><code>@app.route('/active_jobs/<zone>', methods = ['GET'])
def get_one_zone(zone):
ajobs = mongo.db.ajobs
q = ajobs.find_One({'zone' : zone})
output = {}
output = ({
'zone': q['zone'], 'jobdate' : q['jobdate'],
'jobtime' : q['jobtime'],'client': q['client'],
})
return jsonify({output})
</code></pre>
<p>once I try to chage to get all results making it find() it doesnt work</p>
<pre><code>@app.route('/active_jobs/<zone>', methods = ['GET'])
def get_one_zone(zone):
ajobs = mongo.db.ajobs
q = ajobs.find({'zone' : zone})
output = {}
output = ({
'zone': q['zone'], 'jobdate' : q['jobdate'],
'jobtime' : q['jobtime'],'client': q['client'],
})
return jsonify({output})
</code></pre>
<p>Ps. Im a total newbie in the programming world so if you could use simple examples that would be much appreciated.</p>
| 0
|
2016-09-04T23:52:36Z
| 39,324,162
|
<p>This is probably because 'find_One' in mongo will return only 1 document as a dictionary whereas find will return multiple documents as a list of dictionaries. jsonify does not work on a list as seen here: <a href="http://stackoverflow.com/questions/12435297/how-do-i-jsonify-a-list-in-flask">How do I `jsonify` a list in Flask?</a>.</p>
<p>You can use json.dumps instead as the answers there suggest.</p>
| 0
|
2016-09-05T04:57:35Z
|
[
"python",
"mongodb",
"rest",
"api"
] |
Regex for unicode sentences without spaces using CountVectorizer
| 39,322,474
|
<p>I hope I don't have to provide an example set.</p>
<p>I have a 2D array where each array contains a set of words from sentences.</p>
<p>I am using a <a href="http://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.CountVectorizer.html" rel="nofollow">CountVectorizer</a> to effectively call <code>fit_transform</code> on the whole 2D array, such that I can build a vocabulary of words.</p>
<p>However, I have sentences like:</p>
<pre><code>u'Besides EU nations , Switzerland also made a high contribution at Rs 171 million LOCATION_SLOT~-nn+nations~-prep_besides nations~-prep_besides+made~prep_at made~prep_at+rs~num rs~num+NUMBER_SLOT'
</code></pre>
<p>And my current vectorizer is too strict at removing things like <code>~</code> and <code>+</code> as tokens. Whereas I want it to see each word in terms of <code>split()</code> a token in the vocab, i.e. <code>rs~num+NUMBER_SLOT</code> should be a word in itself in the vocab, as should <code>made</code>. At the same time, stopwords like <code>the</code> the <code>a</code> (the normal stopwords set) should be removed. </p>
<p>Current vectorizer: </p>
<pre><code>vectorizer = CountVectorizer(analyzer="word",stop_words=None,tokenizer=None,preprocessor=None,max_features=5000)
</code></pre>
<p>You can specify a <code>token_pattern</code> but I am not sure which one I could use to achieve my aims. Trying:</p>
<pre><code>token_pattern="[^\s]*"
</code></pre>
<p>Leads to a vocabulary of:</p>
<pre><code>{u'': 0, u'p~prep_to': 3764, u'de~dobj': 1107, u'wednesday': 4880, ...}
</code></pre>
<p>Which messes things up as <code>u''</code> is not something I want in my vocabulary.</p>
<p>What is the right token pattern for this type of <code>vocabulary_</code> I want to build?</p>
| 0
|
2016-09-04T23:54:20Z
| 39,330,430
|
<p>I have figured this out. The vectorizer was allowing 0 or more non-whitespace items - it should allow 1 or more. The correct <code>CountVectorizer</code> is:</p>
<pre><code>CountVectorizer(analyzer="word",token_pattern="[\S]+",tokenizer=None,preprocessor=None,stop_words=None,max_features=5000)
</code></pre>
| 0
|
2016-09-05T12:16:06Z
|
[
"python",
"nlp",
"scikit-learn",
"vectorization",
"tokenize"
] |
Bokeh's to_bokeh() ignores legend from matplotlib
| 39,322,522
|
<p>When converting a matplotlib plot into a bokeh html plot, I see that the legend in the matplotlib plot does not appear in the bokeh html plot. Below is an example. How can I get the legend to show up in bokeh? Thanks.</p>
<pre><code>import matplotlib.pyplot as plt
from bokeh.plotting import figure, show, output_file, save
from bokeh.mpl import to_bokeh
if __name__ == '__main__':
legend = ['x^2', '2x']
fig = plt.figure()
ax = fig.add_subplot(111)
plt.plot(range(10), [x*x for x in range(10)], '-o')
plt.plot(range(10), [2*x for x in range(10)], '-o')
plt.legend(legend, loc='upper left')
plt.show()
bk = to_bokeh(fig)
show(bk
</code></pre>
<p>)</p>
| 0
|
2016-09-05T00:05:19Z
| 39,334,503
|
<p>Bokeh's MPL compat capability is based on an experimental third-party library that is no longer actively maintained. The <code>to_bokeh</code> functionality is provided as-is, and with the explicit expectation that it currently provides only partial coverage. More comprehensive compatibility will depend on the implementation of <a href="https://github.com/matplotlib/matplotlib/wiki/MEP25" rel="nofollow">Matplotlib Enhancement Proposal 25</a> which would provide a stable and robust JSON serialization protocol for libraries like Bokeh to be able to interoperate with it. No work will be done on Bokeh's MPL compat until or if MEP25 is implemented. However, there has been no significant movement on MEP 25 in two years, so my strong recommendation, if you are looking to take advantage of Bokeh's features, is to use native Bokeh APIs such as <a href="http://bokeh.pydata.org/en/0.12.1/docs/user_guide/plotting.html" rel="nofollow"><code>bokeh.plotting</code></a> directly, and to not rely on <code>to_bokeh</code> for anything serious. </p>
| 0
|
2016-09-05T16:24:28Z
|
[
"python",
"matplotlib",
"bokeh"
] |
Exposing API Documentation Using Flask and Swagger
| 39,322,550
|
<p>I have build a small service with <code>flask</code> and already wrote a swagger yaml file to describe it's API. How can I expose the swagger file through the flask app?</p>
<p>I didn't mean to expose the file itself (<code>send_from_directory</code>) but to create new endpoint that will show it as swagger-ui (interactive, if possible)</p>
| 1
|
2016-09-05T00:12:57Z
| 39,532,160
|
<p>OK, this is what I did.</p>
<p>I used <code>flasgger</code> to and wrap my app with <code>flasgger.Swagger</code>. than I added 2 endpoints:</p>
<ol>
<li><code>/_api</code> serves the YAML file (with <code>send_from_directory</code>)</li>
<li><code>/api</code> redirects to the flasgger api <code>/apidocs/index.html?url=/api</code> I'm sure it can be done better, but I
failed to find it.</li>
</ol>
<p>github: <a href="https://github.com/eplaut/python-butler/blob/master/butler/butler.py#L119" rel="nofollow">https://github.com/eplaut/python-butler/blob/master/butler/butler.py#L119</a></p>
| 0
|
2016-09-16T12:59:52Z
|
[
"python",
"flask",
"swagger"
] |
Write a function that to sum the result of rolling two random dice n times
| 39,322,574
|
<p>Write a function DiceRoll(n) that inputs an integer n and produces n random numbers
between 1 and 6. Test your program for n = 12.</p>
<p>I got this for that : </p>
<pre><code>import random
def DiceRoll(n):
x=[random.randint(1,6) for _ in range(n)]
return x
</code></pre>
<p>Then,</p>
<p>Write a function TwoDiceRoll(n) that uses your function DiceRoll to sum the result of
rolling two random dice n times. Test your program for n = 12.</p>
<p>I do not have an idea how would I involve my DiceRoll function in order to get the sum. Would someone be able to help me out. </p>
| -4
|
2016-09-05T00:18:25Z
| 39,322,616
|
<p><strong>Code:</strong></p>
<pre><code>import random
def TwoDiceRoll(n):
d1=DiceRoll(n)
d2=DiceRoll(n)
dsum=[i+j for i,j in zip(d1, d2)]
return d1,d2,dsum
def DiceRoll(n):
x=[random.randint(1,6) for _ in range(n)]
return x
x=DiceRoll(12)
print x
d1,d2,dsum=TwoDiceRoll(12)
print d1, "\n", d2, "\n", dsum
</code></pre>
<p><strong>Example Output:</strong> </p>
<pre><code># It will be different everytime because of random function.
[3, 2, 3, 6, 4, 3, 5, 4, 4, 4, 2, 4]
[1, 4, 1, 2, 4, 1, 6, 5, 2, 6, 6, 5]
[4, 2, 3, 1, 6, 3, 1, 5, 5, 2, 6, 3]
[5, 6, 4, 3, 10, 4, 7, 10, 7, 8, 12, 8]
</code></pre>
| -1
|
2016-09-05T00:28:31Z
|
[
"python",
"sage",
"dice"
] |
Write a function that to sum the result of rolling two random dice n times
| 39,322,574
|
<p>Write a function DiceRoll(n) that inputs an integer n and produces n random numbers
between 1 and 6. Test your program for n = 12.</p>
<p>I got this for that : </p>
<pre><code>import random
def DiceRoll(n):
x=[random.randint(1,6) for _ in range(n)]
return x
</code></pre>
<p>Then,</p>
<p>Write a function TwoDiceRoll(n) that uses your function DiceRoll to sum the result of
rolling two random dice n times. Test your program for n = 12.</p>
<p>I do not have an idea how would I involve my DiceRoll function in order to get the sum. Would someone be able to help me out. </p>
| -4
|
2016-09-05T00:18:25Z
| 39,322,641
|
<p>Unsure of why you want to sum them but here you go! I am sure you are capable of wrapping this in a function!</p>
<pre><code>import random
def DiceRoll(n):
x=[random.randint(1,6) for _ in range(n)]
return x
d1 = DiceRoll(12)
d2 = DiceRoll(12)
print sum(d1+d2)
</code></pre>
| -1
|
2016-09-05T00:34:01Z
|
[
"python",
"sage",
"dice"
] |
Query regarding reactor.doSelect() and reactor.runUntilCurrent
| 39,322,614
|
<p>I am working on a game prototype using python twisted. Referring one of the books, I am currently using the following code to update the games </p>
<pre><code>def iterate(self):
now = time.time()
interval = now - self.beginFrame
self.beginFrame = now
# update the network
reactor.runUntilCurrent()
reactor.doSelect(0)
# update the games
for game in self.games:
game.update(interval)
</code></pre>
<p>However, the above code fails in ubuntu machine with error "AttributeError: 'EPollReactor' object has no attribute 'doSelect'" . I am using twisted 16.1.1 and following are my questions </p>
<p>1) I didn't find runUntilCurrent and doSelect methods in the documentation given in twistedmatrix, are these methods not available anymore?</p>
<p>2) Is reactor.iterate() replacement of doSelect() ?
3) From earlier posts I found that reactor.iterate() may make the application slow and buggy. What is the best way to handle situations where one requires fact UI updates?</p>
| 0
|
2016-09-05T00:28:08Z
| 39,323,476
|
<p>Twisted usually selects the epoll reactor by default. The <a href="https://twistedmatrix.com/documents/current/api/twisted.internet.selectreactor.SelectReactor.html#doSelect" rel="nofollow"><code>doSelect</code></a> function is available in the the <a href="https://twistedmatrix.com/documents/current/api/twisted.internet.selectreactor.html" rel="nofollow"><code>selectreactor</code></a>. To use the select reactor, first install the select reactor then import <code>twisted.internet.reactor</code>.</p>
<pre><code>from twisted.internet import selectreactor
selectreactor.install()
from twisted.internet import reactor
</code></pre>
<p>Select should work on most relevant operating systems which may be why your book uses it.</p>
<blockquote>
<p>1) I didn't find runUntilCurrent and doSelect methods in the documentation given in twistedmatrix</p>
</blockquote>
<p>You're not looking hard enough mate :D try searching through all the <a href="https://twistedmatrix.com/documents/current/api/moduleIndex.html" rel="nofollow">modules and class documents</a> next time.</p>
<blockquote>
<p>2) Is <code>reactor.iterate()</code> replacement of <code>doSelect()</code>.</p>
</blockquote>
<p>They both seem to do something similar, but I don't think they're intended to be replacements. Hopefully a Twisted core developer will see this question and correct me if I'm wrong.</p>
| 0
|
2016-09-05T03:19:26Z
|
[
"python",
"twisted"
] |
How to put Python loop output in a list
| 39,322,625
|
<p>As a beginner to Python(SAGE) I want to put the output of this for loop
into a list:</p>
<pre><code>for y in [0,8] :
for z in [0,1,2,3] :
x=y+z
print x
</code></pre>
<p>The output is </p>
<pre><code>0
1
2
3
8
9
10
11
</code></pre>
<p>(vertically). I want a list so I can use it for a later operation:
I want [1,2,3,8,9,10,11].
I found a similar question and I realize that the output is recalculated
each time. Is there a simple way to store them in a list? Following a suggestion for the other answer, I tried "append" like this, but it gives an error message:</p>
<pre><code>x=[]
for y in [0,2*3] :
for z in [0,1,2,3] :
x=y+z
x.append(x)
print x
</code></pre>
| -1
|
2016-09-05T00:30:24Z
| 39,322,664
|
<p>This should do the trick:</p>
<pre><code>lst = [y+z for y in [0,8] for z in [0,1,2,3]]
print(lst) # prints: [1,2,3,8,9,10,11]
</code></pre>
<p>The reason your code did not work, is because your using the variable <code>x</code> for two different things. you first assign it to a list, then you assign it to a integer.
So python thinks that <code>x</code> is a integer, and integers don't have the attribute <code>append()</code>. Thus Python raise an error. The remedy is just to name your variables different things. But you should use something more descriptive than <code>x</code>, <code>y</code>, and <code>z</code>, unless their 'throwaway' variables.</p>
| 1
|
2016-09-05T00:38:55Z
|
[
"python"
] |
How to put Python loop output in a list
| 39,322,625
|
<p>As a beginner to Python(SAGE) I want to put the output of this for loop
into a list:</p>
<pre><code>for y in [0,8] :
for z in [0,1,2,3] :
x=y+z
print x
</code></pre>
<p>The output is </p>
<pre><code>0
1
2
3
8
9
10
11
</code></pre>
<p>(vertically). I want a list so I can use it for a later operation:
I want [1,2,3,8,9,10,11].
I found a similar question and I realize that the output is recalculated
each time. Is there a simple way to store them in a list? Following a suggestion for the other answer, I tried "append" like this, but it gives an error message:</p>
<pre><code>x=[]
for y in [0,2*3] :
for z in [0,1,2,3] :
x=y+z
x.append(x)
print x
</code></pre>
| -1
|
2016-09-05T00:30:24Z
| 39,322,684
|
<p>Because you set variable <code>x</code> from <code>list</code> to <code>int</code> at this line: <code>x = y + z</code>.</p>
<p><code>for</code>-loops don't have scopes like a function or class, so if you set a variable out of the loop, the variable is the same as if it were in the loop.</p>
| 0
|
2016-09-05T00:45:20Z
|
[
"python"
] |
How to put Python loop output in a list
| 39,322,625
|
<p>As a beginner to Python(SAGE) I want to put the output of this for loop
into a list:</p>
<pre><code>for y in [0,8] :
for z in [0,1,2,3] :
x=y+z
print x
</code></pre>
<p>The output is </p>
<pre><code>0
1
2
3
8
9
10
11
</code></pre>
<p>(vertically). I want a list so I can use it for a later operation:
I want [1,2,3,8,9,10,11].
I found a similar question and I realize that the output is recalculated
each time. Is there a simple way to store them in a list? Following a suggestion for the other answer, I tried "append" like this, but it gives an error message:</p>
<pre><code>x=[]
for y in [0,2*3] :
for z in [0,1,2,3] :
x=y+z
x.append(x)
print x
</code></pre>
| -1
|
2016-09-05T00:30:24Z
| 39,322,689
|
<p>try this :</p>
<pre><code>import itertools
temp = [y+z for y,z in list(itertools.product([0,8], [0,1,2,3]))]
</code></pre>
| 0
|
2016-09-05T00:46:39Z
|
[
"python"
] |
How to put Python loop output in a list
| 39,322,625
|
<p>As a beginner to Python(SAGE) I want to put the output of this for loop
into a list:</p>
<pre><code>for y in [0,8] :
for z in [0,1,2,3] :
x=y+z
print x
</code></pre>
<p>The output is </p>
<pre><code>0
1
2
3
8
9
10
11
</code></pre>
<p>(vertically). I want a list so I can use it for a later operation:
I want [1,2,3,8,9,10,11].
I found a similar question and I realize that the output is recalculated
each time. Is there a simple way to store them in a list? Following a suggestion for the other answer, I tried "append" like this, but it gives an error message:</p>
<pre><code>x=[]
for y in [0,2*3] :
for z in [0,1,2,3] :
x=y+z
x.append(x)
print x
</code></pre>
| -1
|
2016-09-05T00:30:24Z
| 39,322,693
|
<p>You can also approach this functionally using itertools.product:</p>
<pre><code>from itertools import product
lst = [y + z for y, z in product([0, 8], [0, 1, 2, 3])]
print(lst)
</code></pre>
<p>will output <code>[0, 1, 2, 3, 8, 9, 10, 11]</code>.</p>
| 0
|
2016-09-05T00:47:32Z
|
[
"python"
] |
How to put Python loop output in a list
| 39,322,625
|
<p>As a beginner to Python(SAGE) I want to put the output of this for loop
into a list:</p>
<pre><code>for y in [0,8] :
for z in [0,1,2,3] :
x=y+z
print x
</code></pre>
<p>The output is </p>
<pre><code>0
1
2
3
8
9
10
11
</code></pre>
<p>(vertically). I want a list so I can use it for a later operation:
I want [1,2,3,8,9,10,11].
I found a similar question and I realize that the output is recalculated
each time. Is there a simple way to store them in a list? Following a suggestion for the other answer, I tried "append" like this, but it gives an error message:</p>
<pre><code>x=[]
for y in [0,2*3] :
for z in [0,1,2,3] :
x=y+z
x.append(x)
print x
</code></pre>
| -1
|
2016-09-05T00:30:24Z
| 39,322,696
|
<p>Try:</p>
<pre><code>x = [y+z for y in [0,8] for z in [0,1,2,3]]
</code></pre>
| 0
|
2016-09-05T00:48:38Z
|
[
"python"
] |
How to put Python loop output in a list
| 39,322,625
|
<p>As a beginner to Python(SAGE) I want to put the output of this for loop
into a list:</p>
<pre><code>for y in [0,8] :
for z in [0,1,2,3] :
x=y+z
print x
</code></pre>
<p>The output is </p>
<pre><code>0
1
2
3
8
9
10
11
</code></pre>
<p>(vertically). I want a list so I can use it for a later operation:
I want [1,2,3,8,9,10,11].
I found a similar question and I realize that the output is recalculated
each time. Is there a simple way to store them in a list? Following a suggestion for the other answer, I tried "append" like this, but it gives an error message:</p>
<pre><code>x=[]
for y in [0,2*3] :
for z in [0,1,2,3] :
x=y+z
x.append(x)
print x
</code></pre>
| -1
|
2016-09-05T00:30:24Z
| 39,322,792
|
<p>You can simply use a list comprehension such as this one:</p>
<pre><code>>>> lst = [y+z for y in [0,8] for z in [0,1,2,3]]
>>> lst
[0, 1, 2, 3, 8, 9, 10, 11]
</code></pre>
<p>That's perfectly clear to any Python programmer.</p>
<p>Or you could use <code>range</code>:</p>
<pre><code>>>> lst=[]
>>> for l in (range(i, i+4) for i in [0, 8]):
... lst.extend(l)
>>> lst
[0, 1, 2, 3, 8, 9, 10, 11]
</code></pre>
<p>Or, since some seem to like complicated answers:</p>
<pre><code>>>> import itertools
>>> lst = list(itertools.chain(*[range(i, i+4) for i in [0,8]]))
>>> lst
[0, 1, 2, 3, 8, 9, 10, 11]
</code></pre>
| 0
|
2016-09-05T01:08:58Z
|
[
"python"
] |
How to put Python loop output in a list
| 39,322,625
|
<p>As a beginner to Python(SAGE) I want to put the output of this for loop
into a list:</p>
<pre><code>for y in [0,8] :
for z in [0,1,2,3] :
x=y+z
print x
</code></pre>
<p>The output is </p>
<pre><code>0
1
2
3
8
9
10
11
</code></pre>
<p>(vertically). I want a list so I can use it for a later operation:
I want [1,2,3,8,9,10,11].
I found a similar question and I realize that the output is recalculated
each time. Is there a simple way to store them in a list? Following a suggestion for the other answer, I tried "append" like this, but it gives an error message:</p>
<pre><code>x=[]
for y in [0,2*3] :
for z in [0,1,2,3] :
x=y+z
x.append(x)
print x
</code></pre>
| -1
|
2016-09-05T00:30:24Z
| 39,323,039
|
<p>You have a lots of ways! First, as a raw code, you can do this:</p>
<pre><code>lst=[]
for y in [0,8] :
for z in [0,1,2,3] :
x=y+z
lst.append(x)
print lst
</code></pre>
<p>You can try <code>list comprehension</code>:</p>
<pre><code>lst = [y+z for y in [0,8] for z in [0,1,2,3]]
print lst
</code></pre>
<p>You can also use <code>itertool chain</code>:</p>
<pre><code>import itertools
lst = list(itertools.chain(*[range(i, i+4) for i in [0,8]]))
print lst
</code></pre>
<p>Another way is <code>itertool products</code>:</p>
<pre><code>import itertools
lst = [y+z for y,z in list(itertools.product([0,8], [0,1,2,3]))]
print lst
</code></pre>
<p>In all cases, <code>output</code> is : <code>[0, 1, 2, 3, 8, 9, 10, 11]</code></p>
| 0
|
2016-09-05T02:00:42Z
|
[
"python"
] |
Python: How to use Value and Array in Multiprocessing pool
| 39,322,677
|
<p>For <code>multiprocessing</code> with <code>Process</code>, I can use <code>Value, Array</code> by setting <code>args</code> param. </p>
<p>With <code>multiprocessing</code> with <code>Pool</code>, how can I use <code>Value, Array.</code> There is nothing in the docs on how to do this. </p>
<pre><code>from multiprocessing import Process, Value, Array
def f(n, a):
n.value = 3.1415927
for i in range(len(a)):
a[i] = -a[i]
if __name__ == '__main__':
num = Value('d', 0.0)
arr = Array('i', range(10))
p = Process(target=f, args=(num, arr))
p.start()
p.join()
print(num.value)
print(arr[:])
</code></pre>
<p>I am trying to use <code>Value, Array</code> within the code snippet below. </p>
<pre><code>import multiprocessing
def do_calc(data):
# access num or
# work to update arr
newdata =data * 2
return newdata
def start_process():
print 'Starting', multiprocessing.current_process().name
if __name__ == '__main__':
num = Value('d', 0.0)
arr = Array('i', range(10))
inputs = list(range(10))
print 'Input :', inputs
pool_size = multiprocessing.cpu_count() * 2
pool = multiprocessing.Pool(processes=pool_size,initializer=start_process, )
pool_outputs = pool.map(do_calc, inputs)
pool.close() # no more tasks
pool.join() # wrap up current tasks
print 'Pool :', pool_outputs
</code></pre>
| 1
|
2016-09-05T00:43:49Z
| 39,322,905
|
<p>I never knew "the reason" for this, but <code>multiprocessing</code> (<code>mp</code>) uses different pickler/unpickler mechanisms for functions passed to most <code>Pool</code> methods. It's a consequence that objects created by things like <code>mp.Value</code>, <code>mp.Array</code>, <code>mp.Lock</code>, ..., can't be passed as arguments to such methods, although they <em>can</em> be passed as arguments to <code>mp.Process</code> <em>and</em> to the optional <code>initializer</code> function of <code>mp.Pool()</code>. Because of the latter, this works:</p>
<pre><code>import multiprocessing as mp
def init(aa, vv):
global a, v
a = aa
v = vv
def worker(i):
a[i] = v.value * i
if __name__ == "__main__":
N = 10
a = mp.Array('i', [0]*N)
v = mp.Value('i', 3)
p = mp.Pool(initializer=init, initargs=(a, v))
p.map(worker, range(N))
print(a[:])
</code></pre>
<p>and that prints</p>
<pre><code>[0, 3, 6, 9, 12, 15, 18, 21, 24, 27]
</code></pre>
<p>That's the only way I know of to get this to work across platforms.</p>
<p>On Linux-y platforms (where <code>mp</code> creates new processes via <code>fork()</code>), you can instead create your <code>mp.Array</code> and <code>mp.Value</code> (etc) objects as module globals any time <em>before</em> you do <code>mp.Pool()</code>. Processes created by <code>fork()</code> inherit whatever is in the module global address space at the time <code>mp.Pool()</code> executes.</p>
<p>But that doesn't work at all on platforms (read "Windows") that don't support <code>fork()</code>.</p>
| 1
|
2016-09-05T01:32:17Z
|
[
"python",
"arrays",
"multiprocessing",
"pool"
] |
Return true if a binary number either contains all zero or all ones on a single flip.(Python)
| 39,322,700
|
<p>I got a program where any binary number is considered and with 1 flip of either 0 or 1, if we get all 0s or all 1s, then it returns true else it will return false. </p>
<p>For e.g. 110 on 1 flip of element 0 returns 111 and it is printed as true.
111 is a binary number which on one flip, is printed as false.
Any possible solution of how to solve it?</p>
<p>Looking forward to the best possible solutions. Appreciate if the solution is written using Python.</p>
<p>This is what i had actually done.</p>
<pre><code>def binary(num, length = 4):
return format(num, '#0{}b'.format(length + 2)).replace('0b', '')
n = binary(125)
n.count('0')
n.count('1')
if (n.count('0') == 1) or (n.count('1') == 1):
return true
</code></pre>
<p>Actually I had no idea of how to flip it. </p>
| -2
|
2016-09-05T00:49:23Z
| 39,322,724
|
<p>You can loop over the values from 0 to log(x) where x is your output and xor with 2<sup>x</sup> which is 100000... Then you just check, whether what you got is 0 or 2<sup>x+1</sup>-1. It should work fine.</p>
<pre><code>def g(x):
for i in range(int(log(x)/log(2))):
if x ^ 2 ** i == 0 or x ^ 2 ** i == 2 ** int(log(x)/log(2) + 1) - 1:
return True
return False
</code></pre>
<p>Another solution is to sort the binary interpretation of the number and check, whether these is only one 1 or only one 0. The lambda function written below does exactly that. Since <code>bin()</code> returns binary <code>0b</code> followed by the binary interpretation of the number I get rid of it and then, remove all <code>0</code> to check whether there only one <code>1</code>, the second part checks the opposite.</p>
<pre><code>f = lambda x: len(str(bin(x))[2:].replace('0','')) == 1 or len(str(bin(x))[2:].replace('1','')) == 1
</code></pre>
<p>If x is the binary interpretation of the number, you should use this:</p>
<pre><code>f = lambda x: len(x.replace('0','')) == 1 or len(x.replace('1','')) == 1
</code></pre>
| 0
|
2016-09-05T00:54:40Z
|
[
"python",
"python-3.x",
"math",
"binary"
] |
Return true if a binary number either contains all zero or all ones on a single flip.(Python)
| 39,322,700
|
<p>I got a program where any binary number is considered and with 1 flip of either 0 or 1, if we get all 0s or all 1s, then it returns true else it will return false. </p>
<p>For e.g. 110 on 1 flip of element 0 returns 111 and it is printed as true.
111 is a binary number which on one flip, is printed as false.
Any possible solution of how to solve it?</p>
<p>Looking forward to the best possible solutions. Appreciate if the solution is written using Python.</p>
<p>This is what i had actually done.</p>
<pre><code>def binary(num, length = 4):
return format(num, '#0{}b'.format(length + 2)).replace('0b', '')
n = binary(125)
n.count('0')
n.count('1')
if (n.count('0') == 1) or (n.count('1') == 1):
return true
</code></pre>
<p>Actually I had no idea of how to flip it. </p>
| -2
|
2016-09-05T00:49:23Z
| 39,322,739
|
<p>One possible solution:</p>
<p>Get first digit to check against all the others, convert to stirng, because integer is not iterable</p>
<pre><code>first = str(number)[0]
</code></pre>
<p>Loop over all of them, return True if we go through the loop, false if we find a digit that doesn't match</p>
<pre><code>for digit in str(number):
if digit == first:
continue
else:
return False
return True
</code></pre>
| 0
|
2016-09-05T00:58:07Z
|
[
"python",
"python-3.x",
"math",
"binary"
] |
Return true if a binary number either contains all zero or all ones on a single flip.(Python)
| 39,322,700
|
<p>I got a program where any binary number is considered and with 1 flip of either 0 or 1, if we get all 0s or all 1s, then it returns true else it will return false. </p>
<p>For e.g. 110 on 1 flip of element 0 returns 111 and it is printed as true.
111 is a binary number which on one flip, is printed as false.
Any possible solution of how to solve it?</p>
<p>Looking forward to the best possible solutions. Appreciate if the solution is written using Python.</p>
<p>This is what i had actually done.</p>
<pre><code>def binary(num, length = 4):
return format(num, '#0{}b'.format(length + 2)).replace('0b', '')
n = binary(125)
n.count('0')
n.count('1')
if (n.count('0') == 1) or (n.count('1') == 1):
return true
</code></pre>
<p>Actually I had no idea of how to flip it. </p>
| -2
|
2016-09-05T00:49:23Z
| 39,322,884
|
<p>Assume that the flip can apply to any bit of the number, you can just count the occurrence of 1 or 0. If either result returns 1, then the answer is true, otherwise the answer is false:</p>
<pre><code>def one_flip(i):
# i should be integer, so convert it to string using bin() and get the result excluding the '0b'
s = bin(i)[2:]
return s.count('0') == 1 or s.count('1') == 1
</code></pre>
| 0
|
2016-09-05T01:27:40Z
|
[
"python",
"python-3.x",
"math",
"binary"
] |
Return true if a binary number either contains all zero or all ones on a single flip.(Python)
| 39,322,700
|
<p>I got a program where any binary number is considered and with 1 flip of either 0 or 1, if we get all 0s or all 1s, then it returns true else it will return false. </p>
<p>For e.g. 110 on 1 flip of element 0 returns 111 and it is printed as true.
111 is a binary number which on one flip, is printed as false.
Any possible solution of how to solve it?</p>
<p>Looking forward to the best possible solutions. Appreciate if the solution is written using Python.</p>
<p>This is what i had actually done.</p>
<pre><code>def binary(num, length = 4):
return format(num, '#0{}b'.format(length + 2)).replace('0b', '')
n = binary(125)
n.count('0')
n.count('1')
if (n.count('0') == 1) or (n.count('1') == 1):
return true
</code></pre>
<p>Actually I had no idea of how to flip it. </p>
| -2
|
2016-09-05T00:49:23Z
| 39,322,891
|
<p>So you need to determine whether binary representation of given number contains only one "one" or only one "zero"? There is bit trick to find numbers with single bit set:</p>
<pre><code>if (x == 0)
return false
if (x & (x - 1) == 0
return true
</code></pre>
<p>Explanation: if number looks like <code>b00001000</code>, then decrement gives <code>b00000111</code> and binary AND leads to zero result</p>
<p>For checking single-zero numbers just invert them</p>
<p>if there is no <code>~</code> operator (binary NOT) in Python, you can invert all bits of number with </p>
<pre><code>x_inversion = -(x+1)
</code></pre>
| 2
|
2016-09-05T01:28:46Z
|
[
"python",
"python-3.x",
"math",
"binary"
] |
Return true if a binary number either contains all zero or all ones on a single flip.(Python)
| 39,322,700
|
<p>I got a program where any binary number is considered and with 1 flip of either 0 or 1, if we get all 0s or all 1s, then it returns true else it will return false. </p>
<p>For e.g. 110 on 1 flip of element 0 returns 111 and it is printed as true.
111 is a binary number which on one flip, is printed as false.
Any possible solution of how to solve it?</p>
<p>Looking forward to the best possible solutions. Appreciate if the solution is written using Python.</p>
<p>This is what i had actually done.</p>
<pre><code>def binary(num, length = 4):
return format(num, '#0{}b'.format(length + 2)).replace('0b', '')
n = binary(125)
n.count('0')
n.count('1')
if (n.count('0') == 1) or (n.count('1') == 1):
return true
</code></pre>
<p>Actually I had no idea of how to flip it. </p>
| -2
|
2016-09-05T00:49:23Z
| 39,322,895
|
<p>Just for laughs - with some bitwise manipulations:</p>
<pre><code>>>> def single_flip(n):
... return any(x and not x & (x - 1) for x in [n, n^2**n.bit_length()-1])])
...
>>> single_flip(0b1110111), single_flip(0b1010111), single_flip(0b0001000)
(True, False, True)
</code></pre>
<p>This just tests whether the number or its bitwise complement (not 2's complement) are a factor of 2.</p>
| 0
|
2016-09-05T01:29:49Z
|
[
"python",
"python-3.x",
"math",
"binary"
] |
"AssertionError: Cannot apply DjangoModelPermissions" even when get_queryset is defined in view
| 39,322,708
|
<p>I'm getting the following error <strong>even though my view is overriding <code>get_queryset()</code>.</strong></p>
<pre><code>AssertionError: Cannot apply DjangoModelPermissions on a view that does not set `.queryset` or have a `.get_queryset()` method.
</code></pre>
<p>Here's my view:</p>
<pre><code>class PlayerViewSet(viewsets.ModelViewSet):
serializer_class = PlayerSerializer
def get_queryset(self):
try:
quality = self.kwargs['quality'].lower()
print("Getting Player for %s"%quality)
return Player.objects.filter(qualities__contains=quality)
except:
# todo: send out a 404
print("No Players found for this quality :(")
pass
</code></pre>
<p>My settings.py:</p>
<pre><code>REST_FRAMEWORK = {
# Use Django's standard `django.contrib.auth` permissions,
# or allow read-only access for unauthenticated users.
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
]
}
</code></pre>
<p><strong>Edit - Additional info:</strong> Here's the entry in urls.py:</p>
<pre><code>router = routers.DefaultRouter()
router.register(r'^player-list/(?P<quality>\w+)', players.views.PlayerViewSet, base_name="Player List")
[...]
urlpatterns = [
url(r'^api/', include(router.urls)),
]
</code></pre>
<p>I don't understand what the issue is. Why doesn't DRF see my <code>get_queryset</code> method?</p>
| 2
|
2016-09-05T00:51:02Z
| 39,356,000
|
<p>I've tried running your code on DRF 3.3.2 and could figure out a couple of easy to miss errors that may be leading to the AssertionError you mentioned.</p>
<ol>
<li>Misspelled <code>get_queryset()</code>. Looks fine in your question here, but double check your code to be sure.</li>
<li>In your code in <code>get_queryset</code>, you return <code>None</code> in the case of an exception. I tried forcing an exception in under <code>get_queryset</code>and silencing it the way you've done (returning None at the end). This lead to the exact AssertionError. So make sure your code under <code>get_queryset</code>isn't raising any exceptions. One area where I think an exception could be raised is when the named url group 'quality' isn't passed into <code>self.kwargs</code>.</li>
</ol>
<p>Sidenote: When DRF calls the permission class' <code>has_permission</code> method, it sends the api view as an argument. It then uses the api view to figure out what your queryset is. If you can set up a debugger at 'rest_framework/permissions.py' (<a href="https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/permissions.py#L124" rel="nofollow">here</a>) and pause inside the <code>has_permission</code> method, you can then double check if the <code>queryset</code> variable is correctly picked up, or is set to None. In your case, it is probably coming up as None which is whats triggering the AssertionError, you can then check if the <code>api_view</code> instance passed on to the function as a parameter, actually refers to an instance of <code>PlayerViewSet</code> or not.</p>
| 0
|
2016-09-06T18:55:20Z
|
[
"python",
"django",
"django-rest-framework"
] |
A function that creates functions named after arguments passed in
| 39,322,751
|
<p>Is there a way to make a function that makes other functions to be called later named after the variables passed in? </p>
<p>For the example let's pretend <a href="https://example.com/engine_list" rel="nofollow">https://example.com/engine_list</a> returns this xml file, when I call it in get_search_engine_xml</p>
<pre><code><engines>
<engine address="https://www.google.com/">Google</engine>
<engine address="https://www.bing.com/">Bing</engine>
<engine address="https://duckduckgo.com/">DuckDuckGo</engine>
</engines>
</code></pre>
<p>And here's my code:</p>
<pre><code>import re
import requests
import xml.etree.ElementTree as ET
base_url = 'https://example.com'
def make_safe(s):
s = re.sub(r"[^\w\s]", '', s)
s = re.sub(r"\s+", '_', s)
s = str(s)
return s
# This is what I'm trying to figure out how to do correctly, create a function
# named after the engine returned in get_search_engine_xml(), to be called later
def create_get_engine_function(function_name, address):
def function_name():
r = requests.get(address)
return function_name
def get_search_engine_xml():
url = base_url + '/engine_list'
r = requests.get(url)
engines_list = str(r.content)
engines_root = ET.fromstring(engines_list)
for child in engines_root:
engine_name = child.text.lower()
engine_name = make_safe(engine_name)
engine_address = child.attrib['address']
create_get_engine_function(engine_name, engine_address)
## Runs without error.
get_search_engine_xml()
## But if I try to call one of the functions.
google()
</code></pre>
<p>I get the following error.</p>
<pre><code>Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'google' is not defined
</code></pre>
<p>Defining engine_name and engine_address seems to be working when I log it out. So I'm pretty sure the problem lies in create_get_engine_function, which admittedly I don't know what I'm doing and I was trying to piece together from similar questions. </p>
<p>Can you name a function created by another function with an argument that's passed in? Is there a better way to do this?</p>
| 0
|
2016-09-05T01:00:06Z
| 39,322,786
|
<p>You can assign them to <a href="https://docs.python.org/3/library/functions.html#globals" rel="nofollow">globals()</a></p>
<pre><code>def create_get_engine_function(function_name, address):
def function():
r = requests.get(address)
function.__name__ = function_name
function.__qualname__ = function_name # for Python 3.3+
globals()[function_name] = function
</code></pre>
<p>Although, depending on what you're actually trying to accomplish, a better design would be to store all the engine names/addresses in a dictionary and access them as needed:</p>
<pre><code># You should probably should rename this to 'parse_engines_from_xml'
def get_search_engine_xml():
...
search_engines = {} # maps names to addresses
for child in engines_root:
...
search_engines[engine_name] = engine_address
return search_engines
engines = get_search_engine_xml()
e = requests.get(engines['google'])
<do whatever>
e = requests.get(engines['bing'])
<do whatever>
</code></pre>
| 2
|
2016-09-05T01:07:22Z
|
[
"python",
"xml",
"automated-tests"
] |
how to groupby in complicated condition in pandas
| 39,322,773
|
<p>I have dataframe like this</p>
<pre><code> A B C
0 1 7 a
1 2 8 b
2 3 9 c
3 4 10 a
4 5 11 b
5 6 12 c
</code></pre>
<p>I would like to get groupby result (key=column C) below;</p>
<pre><code> A B
d 12 36
</code></pre>
<p>"d" means a or b ,</p>
<p>so I would like to groupby only with "a" and "b".</p>
<p>and then put together as "d".</p>
<p>when I sum up with all the key elements then drop, it consume much time....</p>
| 0
|
2016-09-05T01:05:53Z
| 39,322,850
|
<p>One option is to use <code>pandas</code> <code>where</code> to transform the C column so that where it was <code>a</code> or <code>b</code> becomes <code>d</code> and then you can groupby the transformed column and do the normal summary on it, and if rows with <code>c</code> is not desired, you can simply drop it after the summary:</p>
<pre><code>df_sum = df.groupby(df.C.where(~df.C.isin(['a', 'b']), "d")).sum().reset_index()
df_sum
# C A B
#0 c 9 21
#1 d 12 36
df_sum.loc[df_sum.C == "d"]
# C A B
#1 d 12 36
</code></pre>
<p>To see more clearly how the <code>where</code> clause works:</p>
<pre><code>df.C.where(~df.C.isin(['a','b']), 'd')
# 0 d
# 1 d
# 2 c
# 3 d
# 4 d
# 5 c
# Name: C, dtype: object
</code></pre>
<p>It acts like a replace method and replace <code>a</code> and <code>b</code> with <code>d</code> which will be grouped together when passed to <code>groupby</code> function.</p>
| 1
|
2016-09-05T01:21:45Z
|
[
"python",
"pandas"
] |
matrices are not aligned error message
| 39,322,928
|
<p>I have the following dataframe of returns</p>
<pre><code>ret
Out[3]:
Symbol FX OGDC PIB WTI
Date
2010-03-02 0.000443 0.006928 0.000000 0.012375
2010-03-03 -0.000690 -0.007873 0.000171 0.014824
2010-03-04 -0.001354 0.001545 0.000007 -0.008195
2010-03-05 -0.001578 0.008796 -0.000164 0.015955
</code></pre>
<p>And the following weights for each symbol:</p>
<pre><code>df3
Out[4]:
Symbol Weight
0 OGDC 0.182022
1 WTI 0.534814
2 FX 0.131243
3 PIB 0.151921
</code></pre>
<p>I am trying to get a weighted return for each day and tried:</p>
<pre><code>port_ret = ret.dot(df3)
</code></pre>
<p>but I get the following error message:</p>
<pre><code>ValueError: matrices are not aligned
</code></pre>
<p>My objective is to have a weighted return for each date such that, for example 2010-03-02 would be as follows:</p>
<pre><code>weighted_ret = 0.000443*.131243+.006928*.182022+0.000*0.151921+0.012375*.534814 = 0.007937512
</code></pre>
<p>I am not sure why I am getting this error but would be very happy for an alternative solution to the weighted return </p>
| 0
|
2016-09-05T01:36:31Z
| 39,322,943
|
<p>Check the shape of the matrices you're calling the dot product on. The dot product of matrices <code>A.dot(B)</code> can be computed only if second axis of A is the same size as first axis of B.<br>
In your example you have additional column with date, that ruins your computation. You should just get rid of it in your computation. Try running <code>port_ret = ret[:,1:].dot(df3[1:])</code> and check if it produces the result you desire.<br>
For future cases, use <code>numpy.shape()</code> function to debug matrix calculations, it is really helpful tool.</p>
| 0
|
2016-09-05T01:40:08Z
|
[
"python",
"pandas",
"matrix",
"dot",
"np"
] |
matrices are not aligned error message
| 39,322,928
|
<p>I have the following dataframe of returns</p>
<pre><code>ret
Out[3]:
Symbol FX OGDC PIB WTI
Date
2010-03-02 0.000443 0.006928 0.000000 0.012375
2010-03-03 -0.000690 -0.007873 0.000171 0.014824
2010-03-04 -0.001354 0.001545 0.000007 -0.008195
2010-03-05 -0.001578 0.008796 -0.000164 0.015955
</code></pre>
<p>And the following weights for each symbol:</p>
<pre><code>df3
Out[4]:
Symbol Weight
0 OGDC 0.182022
1 WTI 0.534814
2 FX 0.131243
3 PIB 0.151921
</code></pre>
<p>I am trying to get a weighted return for each day and tried:</p>
<pre><code>port_ret = ret.dot(df3)
</code></pre>
<p>but I get the following error message:</p>
<pre><code>ValueError: matrices are not aligned
</code></pre>
<p>My objective is to have a weighted return for each date such that, for example 2010-03-02 would be as follows:</p>
<pre><code>weighted_ret = 0.000443*.131243+.006928*.182022+0.000*0.151921+0.012375*.534814 = 0.007937512
</code></pre>
<p>I am not sure why I am getting this error but would be very happy for an alternative solution to the weighted return </p>
| 0
|
2016-09-05T01:36:31Z
| 39,323,924
|
<p>You have two columns in your weight matrix:</p>
<pre><code>df3.shape
Out[38]: (4, 2)
</code></pre>
<p>Set the index to <code>Symbol</code> on that atrix to get the proper <code>dot</code>:</p>
<pre><code>ret.dot(df3.set_index('Symbol'))
Out[39]:
Weight
Date
2010-03-02 0.007938
2010-03-03 0.006430
2010-03-04 -0.004278
2010-03-05 0.009902
</code></pre>
| 1
|
2016-09-05T04:24:32Z
|
[
"python",
"pandas",
"matrix",
"dot",
"np"
] |
Django's runscript: No (valid) module for script 'filename' found
| 39,322,967
|
<p>I'm trying to run a script from the Django shell using the Django-extension <a href="http://django-extensions.readthedocs.io/en/latest/runscript.html" rel="nofollow">RunScript</a>. I have done this before and but it refuses to recognize my new script:</p>
<pre><code>(env) mint@mint-VirtualBox ~/GP/GP $ python manage.py runscript fill_in_random_variants
No (valid) module for script 'fill_in_random_variants' found
Try running with a higher verbosity level like: -v2 or -v3
</code></pre>
<p>While running any other script works fine:</p>
<pre><code>(env) mint@mint-VirtualBox ~/GP/GP $ python manage.py runscript fill_in_variants
Success! At least, there were no errors.
</code></pre>
<p>I have double checked that the file exists, including renaming it to something else. I have also tried running the command with non-existent script names:</p>
<pre><code>(env) mint@mint-VirtualBox ~/GP/GP $ python manage.py runscript thisfiledoesntexist
No (valid) module for script 'thisfiledoesntexist' found
Try running with a higher verbosity level like: -v2 or -v3
</code></pre>
<p>and the error is the same.</p>
<p>Why can't RunScript find my file?</p>
| 0
|
2016-09-05T01:45:37Z
| 39,322,968
|
<p>RunScript has confusing error messages. It gives the same error for when it can't find a script at all and when there's an import error in the script.</p>
<p>Here's an example script to produce the error:</p>
<pre><code>import nonexistrentpackage
def run():
print("Test")
</code></pre>
<p>The example has the only stated requirement for scripts, namely a <code>run</code> function.</p>
<p>Save this as <code>test_script.py</code> in a scripts folder (such as <code>project root/your app/scripts/test_script.py</code>). Then try to run it:</p>
<pre><code>(env) mint@mint-VirtualBox ~/GP/GP $ python manage.py runscript test_script
No (valid) module for script 'test_script' found
Try running with a higher verbosity level like: -v2 or -v3
</code></pre>
<p>Which is the same error as the file not found one. Now outcomment the import line and try again:</p>
<pre><code>(env) mint@mint-VirtualBox ~/GP/GP $ python manage.py runscript test_script
Test
</code></pre>
<p>As far as I know, the only way to tell the errors apart is to use the verbose (-v2) command line option and then look at the <em>first</em> (scroll up) error returned:</p>
<pre><code>(env) mint@mint-VirtualBox ~/GP/GP $ python manage.py runscript test_script -v2
Check for www.scripts.test_script
Cannot import module 'www.scripts.test_script': No module named 'nonexistrentpackage'.
Check for django.contrib.admin.scripts.test_script
Cannot import module 'django.contrib.admin.scripts.test_script': No module named 'django.contrib.admin.scripts'.
Check for django.contrib.auth.scripts.test_script
Cannot import module 'django.contrib.auth.scripts.test_script': No module named 'django.contrib.auth.scripts'.
Check for django.contrib.contenttypes.scripts.test_script
Cannot import module 'django.contrib.contenttypes.scripts.test_script': No module named 'django.contrib.contenttypes.scripts'.
Check for django.contrib.sessions.scripts.test_script
Cannot import module 'django.contrib.sessions.scripts.test_script': No module named 'django.contrib.sessions.scripts'.
Check for django.contrib.messages.scripts.test_script
Cannot import module 'django.contrib.messages.scripts.test_script': No module named 'django.contrib.messages.scripts'.
Check for django.contrib.staticfiles.scripts.test_script
Cannot import module 'django.contrib.staticfiles.scripts.test_script': No module named 'django.contrib.staticfiles.scripts'.
Check for django_extensions.scripts.test_script
Cannot import module 'django_extensions.scripts.test_script': No module named 'django_extensions.scripts'.
Check for scripts.test_script
Cannot import module 'scripts.test_script': No module named 'scripts'.
No (valid) module for script 'test_script' found
</code></pre>
<p>where we can see the crucial line:</p>
<pre><code>No module named 'nonexistrentpackage'.
</code></pre>
<p>The commonality of the errors seems to be because the extension runs the script using <code>import</code>. It would be more sensible if it first checked for the existence of the file using <a href="https://docs.python.org/3/library/os.path.html" rel="nofollow"><code>os.path.isfile</code></a> and if not found, the threw a more sensible error message.</p>
| 1
|
2016-09-05T01:45:37Z
|
[
"python",
"django"
] |
Convert Pandas groupby group into columns
| 39,323,002
|
<p>I'm trying to group a Pandas dataframe by two separate group types, A_Bucket and B_Bucket, and convert each A_Bucket group into a column. I get the groups as such:</p>
<pre><code>grouped = my_new_df.groupby(['A_Bucket','B_Bucket'])
</code></pre>
<p>I want the A_Bucket group to be in columns and the B_Bucket group to be the indices. 'A' has about 20 values and B has about 20 values, so there are a total of about 400 groups.</p>
<p>When I print grouped and its type I get:</p>
<pre><code>type of grouped2 = <class 'pandas.core.groupby.DataFrameGroupBy'>
A_Bucket B_Bucket
0.100 100.0 5.418450
120.0 18.061367
0.125 80.0 3.100920
100.0 14.137063
120.0 30.744823
140.0 38.669950
160.0 48.303129
180.0 74.576333
200.0 125.119950
0.150 60.0 0.003200
80.0 2.274807
100.0 5.350074
120.0 23.272970
140.0 40.131780
160.0 47.036912
180.0 72.438978
200.0 117.365480
</code></pre>
<p>So A_Bucket group 0.100 has only 2 values, but 0.125 has 7. I want a dataframe like this:</p>
<pre><code> 0.1 0.125 0.15
80 NaN 3.10092 2.274807
100 5.41845 14.137063 5.350074
120 18.0613 30.744823 23.27297
140 NaN 38.66995 40.13178
160 NaN 48.303129 47.036912
180 NaN 74.576333 72.438978
200 NaN 125.11995 NaN
</code></pre>
<p>I saw this question:
<a href="http://stackoverflow.com/questions/35024023/pandas-groupby-result-into-multiple-columns">Pandas groupby result into multiple columns</a></p>
<p>but I don't understand the syntax, and it doesn't arrange the first group into columns like I need. I also want this to work for more than one output column.</p>
<p>How do I do this? </p>
| 0
|
2016-09-05T01:52:21Z
| 39,323,205
|
<p>If I understand you correctly, you are trying to reshape your data frame instead of grouping by summary, in this case you can use <code>set_index()</code> and <code>unstack()</code>:</p>
<pre><code>df.set_index(["A_Bucket", "B_Bucket"]).unstack(level=0)
# Value
# A_Bucket 0.100 0.125 0.150
# B_Bucket
# 60.0 NaN NaN 0.003200
# 80.0 NaN 3.100920 2.274807
# 100.0 5.418450 14.137063 5.350074
# 120.0 18.061367 30.744823 23.272970
# 140.0 NaN 38.669950 40.131780
# 160.0 NaN 48.303129 47.036912
# 180.0 NaN 74.576333 72.438978
# 200.0 NaN 125.119950 117.365480
</code></pre>
<p>If you indeed have done the summary after grouping by, you can still do <code>df.groupby(['A_Bucket', 'B_Bucket']).mean().unstack(level=0)</code></p>
| 2
|
2016-09-05T02:34:44Z
|
[
"python",
"pandas",
"dataframe"
] |
COUNT DISTINCT / nunique within groups
| 39,323,071
|
<p>I want to count the number of distinct tuples within each group:</p>
<pre><code>df = pd.DataFrame({'a': ['A', 'A', 'A', 'A', 'B', 'B', 'B', 'B'],
'b': [1, 2, 1, 2, 1, 2, 1, 2],
'c': [1, 1, 2, 2, 2, 1, 2, 1]})
counts = count_distinct(df, by='a', columns=['b', 'c'])
assert counts == pd.Series([4, 2], index=['A', 'B'])
</code></pre>
<p>In other words, counts should report that for group 'A', there are four distinct tuples and for group 'B', there are two.</p>
<p>I tried using <code>df.groupby('a')['b', 'c'].nunique()</code>, but <code>nunique</code> works only with a single column.</p>
<p>I know I could count distinct tuples by df.groupby(['b', 'c']), but that means I have use a slow <code>apply</code> with a pure python function (the number of groups of column 'a' is large).</p>
<p>I could convert the 'b' and 'c' columns into a single column of tuples, but that would be super slow since it will no longer use vectorized operations.</p>
| 2
|
2016-09-05T02:06:25Z
| 39,323,102
|
<p>I think your logic is equivalent to count the size of data frames grouped by column <code>a</code> after dropping the duplicated values of combined columns <code>a</code>, <code>b</code> and <code>c</code>, since duplicated tuples within each group must also be duplicated records in the data frame assuming your data frame contains only columns <code>a</code>, <code>b</code> and <code>c</code> and vice versa:</p>
<pre><code>df.drop_duplicates().groupby('a').size()
# a
# A 4
# B 2
# dtype: int64
</code></pre>
| 3
|
2016-09-05T02:12:44Z
|
[
"python",
"python-3.x",
"pandas"
] |
tqdm: 'module' object is not callable
| 39,323,182
|
<p>I import tqdm as this:</p>
<pre><code>import tqdm
</code></pre>
<p>I am using tqdm to show progress in my python3 code, but I have the following error:</p>
<pre><code>Traceback (most recent call last):
File "process.py", line 15, in <module>
for dir in tqdm(os.listdir(path), desc = 'dirs'):
TypeError: 'module' object is not callable
</code></pre>
<p>Here is the code:</p>
<pre><code>path = '../dialogs'
dirs = os.listdir(path)
for dir in tqdm(dirs, desc = 'dirs'):
print(dir)
</code></pre>
| 0
|
2016-09-05T02:31:22Z
| 39,333,877
|
<p>The error is telling you are trying to call the module. You can't do this.</p>
<p>To call you just have to do</p>
<pre><code>tqdm.tqdm(dirs, desc = 'dirs')
</code></pre>
<p>to solve your problem. Or simply change your import to</p>
<pre><code>from tqdm import tqdm
</code></pre>
<p>But, the important thing here is to review the documentation for what you are using and ensure you are using it properly.</p>
| 2
|
2016-09-05T15:38:33Z
|
[
"python",
"tqdm"
] |
Spotify - searching for silences in a track
| 39,323,185
|
<p>I have been searching everywhere but haven't found any documentation about the <code>analysis_url</code> <code>audio feature</code> on <code>Spotify API</code>, in order to deepen my understanding on the subject.</p>
<p>As far as I'm concerned, it learns the audio by <code>segments</code>, <code>bars</code>, <code>beats</code>, <code>sample rates</code>, <code>fade ins and outs</code>, <code>keys</code>, <code>timbre</code>, <code>mode</code>, <code>time_signature</code>, <code>tempo</code>etc</p>
<p>what I have so far is:</p>
<pre><code>def analysis_url(track_ids):
names = []
tids = []
for id_ in track_ids:
track_id = sp.track(id_)['uri']
tids.append(track_id)
track_name = sp.track(id_)['name']
names.append(track_name)
features = sp.audio_features(tids)
urls = [x['analysis_url'] for x in features if x]
for url in urls:
analysis = sp._get(url)
</code></pre>
<p>What I would like to do is find <strong>silences</strong> in a track, such as a 'drop' in electronic music.</p>
<p>how can I do that using the <code>analysis_url</code>?</p>
| 1
|
2016-09-05T02:31:46Z
| 39,385,373
|
<p>Analysis comes from a company called EchoNest, which was bought by Spotify some time ago. You can find the documentation for the analysis <a href="http://developer.echonest.com/docs/v4/_static/AnalyzeDocumentation.pdf" rel="nofollow">here</a>.</p>
<p>Segments include a loudness_max value which indicates the relatively loudness of that specific section of music (in db). Normalize those values over the song and look for segments that have a low relative loudness:</p>
<pre><code>def normalize_loudness(filename):
d = json.load(open(filename, 'r'))
x = [_['start'] for _ in d['segments']]
l = [_['loudness_max'] for _ in d['segments']]
min_l = min(l)
max_l = max(l)
norm_l = [(_ - min_l)/(max_l - min_l) for _ in l]
return (x, norm_l)
</code></pre>
<p>Using this on the song "Miss Jackson" by Panic! At The Disco, we can plot the normalized loudness values:</p>
<pre><code>import json
from matplotlib import pyplot as pp
x, norm_l = normalize_loudness('msJackson.json')
pp.plot(x, norm_l, 'o')
pp.show()
exit()
</code></pre>
<p>Yielding:</p>
<p><img src="https://i.imgur.com/KNoa3PL.png" alt="Miss Jackson"></p>
<p>With that you can easily find the low spots in the music:</p>
<pre><code>print([x[i] for i in range(len(x)) if norm_l[i] < .1])
[0.0, 165.86036]
</code></pre>
| 0
|
2016-09-08T07:50:03Z
|
[
"python",
"spotify",
"spotipy"
] |
Plylab / MatPlotLib plot not showing data properly
| 39,323,212
|
<p>I have been following a tutorial to learn about fft and although I have the code verbatum, the plot from my machine does not look how it ought to. I log the data to make sure that I have an approximate sine wav over 5292 samples. However when I run the plot with <code>show()</code> I get the following image: (btw, is there a markdown attr for making these images smaller?)</p>
<p><a href="http://i.stack.imgur.com/kWrO0.png" rel="nofollow"><img src="http://i.stack.imgur.com/kWrO0.png" alt="pyplot"></a></p>
<p>Again, this is generated from the subsequent code:</p>
<pre><code>from pylab import *
from scipy.io import wavfile
sampFreq, snd = wavfile.read('440_sine.wav')
snd = snd / (2.**15)
s1 = snd[:,0]
timeArray = arange(0, 5292, 1)
timeArray = timeArray / sampFreq
timeArray = timeArray * 1000 #scale to milliseconds
plot(timeArray, s1, color='k')
ylabel('Amplitude')
xlabel('Time (ms)')
for i in s1:
print i
show()
</code></pre>
<p>In short, I'm learning about fft and I'm a newcomer to python/matplotlib, so any help is greatly appreciated in advance.</p>
| 1
|
2016-09-05T02:35:50Z
| 39,323,898
|
<p>What is the value of your <code>sampFreq</code>? Your <code>timeArray</code> is an integer list and I am assuming sampFreq is returned an integer as well. If <code>sampFreq</code> is larger than the values in <code>timeArray</code> then all of the resultant values will be 0 because integer division. </p>
<p>You may want to cast <code>sampFreq</code> to a float first before diving through the <code>timeArray</code> list and see if that helps.</p>
<p>As an example of the issue, in python shell try out:</p>
<pre><code>>>> 3/4
</code></pre>
<p>and</p>
<pre><code>>>> 3/4.0
</code></pre>
| 0
|
2016-09-05T04:21:18Z
|
[
"python",
"matplotlib"
] |
python - Removing duplicate rows under conditions in Pandas
| 39,323,225
|
<p>I have a DataFrame like this:</p>
<pre><code> NoDemande NoUsager Sens IdVehiculeUtilise Fait HeurePrevue HeureDebutTrajet
0 42191000823 001208 + 246Véh 1 08:20:04 08:22:26
1 42191000822 001208 + 246Véh 1 08:20:04 08:18:56
2 42191000822 001208 - 246Véh -99 09:05:03 08:56:26
3 42191000823 001208 - 246Véh 1 09:05:03 08:56:26
4 42191000834 001208 + 246Véh 1 16:50:04 16:39:26
5 42191000834 001208 - 246Véh 1 17:45:03 17:25:10
6 42192000761 001208 + 246Véh -1 08:20:04 08:15:07
7 42192000762 001208 + 246Véh 1 08:20:04 08:18:27
8 42192000762 001208 - 246Véh -99 09:05:03 08:58:29
9 42192000761 001208 - 246Véh -11 09:05:03 08:58:29
</code></pre>
<p>I get this data frame from<code>df[df.duplicated(['NoUsager','NoDemande'],keep=False)]</code>which ensure my rows being in pair. I want to drop a pair of rows when <code>NoDemande</code> are continuous numbers (like 42191000822 and 42191000823, 42192000761 and 42192000762) and the column <code>HeurePrevue</code> are the same, which means the records are recorded twice. I have to delete a pair and I'd like to preseve the one with more positive numbers in column <code>Fait</code>(at least one greater than 0)</p>
<p>So my result should look like:</p>
<pre><code> NoDemande NoUsager Sens IdVehiculeUtilise Fait HeurePrevue HeureDebutTrajet
0 42191000823 001208 + 246Véh 1 08:20:04 08:22:26
3 42191000823 001208 - 246Véh 1 09:05:03 08:56:26
4 42191000834 001208 + 246Véh 1 16:50:04 16:39:26
5 42191000834 001208 - 246Véh 1 17:45:03 17:25:10
7 42192000762 001208 + 246Véh 1 08:20:04 08:18:27
8 42192000762 001208 - 246Véh -99 09:05:03 08:58:29
</code></pre>
<p>I know it's something about <code>OR</code> logic but I have no idea how to realize it.</p>
<p>Any help will be appreciated~</p>
| 1
|
2016-09-05T02:37:52Z
| 39,328,823
|
<p>I see here two solutions.
<em>The first is based on the suggestion, that you have always continuous pairs of entries in your dataset</em> - that if any entry has a pair, this pair comes after this entry. Then you should loop over your dataframe with step size = 2:</p>
<pre><code>for i in range(0,x,2):
your action
</code></pre>
<p>And in this loop you can compare your two entries and remove the one that has a negative value.</p>
<p><em>My second proposition is a little bit complex.</em></p>
<p>First you should copy and lag (shift by specific number of rows) all columns. This can be done with following function (applied only on NoDemande, for doing so to every column use a loop):</p>
<pre><code>df.NoDemande = df.NoDemande.shift(-1)
</code></pre>
<p>It will look like:</p>
<pre><code> NoDemande NoDemande_lagged
0 42191000823 42191000822
1 42191000822 42191000822
2 42191000822 42191000823
3 42191000823 42191000834
</code></pre>
<p>Then compare the two values in the same row in NoDemande and NoDemande_lagged columns. If the number from 42191000822 is greater or smaller by 1 than the value in NoDemande, then compare <strong>Fait</strong> and <strong>Fait_lagged</strong> and choose the more positive value, which you should paste in the new column <strong>Fait_selected</strong>. The same you should do with other columns, so that every column will have a lagged copy and a selected copy. Afterwards you should remove your next row, because you have already compared it with the previous one.
At the end you should delete your original and lagged colums and leave only the "_selected".</p>
<p>Sorry for a complex Explanation, hope, that this will help you anyway. If you are familiar with RapidMiner, I can explain how to do this there, it will be easier. And I gave you some ideas for various concepts that can help you to solve your Problem.</p>
| 0
|
2016-09-05T10:39:11Z
|
[
"python",
"pandas",
"dataframe",
"duplicates"
] |
python - Removing duplicate rows under conditions in Pandas
| 39,323,225
|
<p>I have a DataFrame like this:</p>
<pre><code> NoDemande NoUsager Sens IdVehiculeUtilise Fait HeurePrevue HeureDebutTrajet
0 42191000823 001208 + 246Véh 1 08:20:04 08:22:26
1 42191000822 001208 + 246Véh 1 08:20:04 08:18:56
2 42191000822 001208 - 246Véh -99 09:05:03 08:56:26
3 42191000823 001208 - 246Véh 1 09:05:03 08:56:26
4 42191000834 001208 + 246Véh 1 16:50:04 16:39:26
5 42191000834 001208 - 246Véh 1 17:45:03 17:25:10
6 42192000761 001208 + 246Véh -1 08:20:04 08:15:07
7 42192000762 001208 + 246Véh 1 08:20:04 08:18:27
8 42192000762 001208 - 246Véh -99 09:05:03 08:58:29
9 42192000761 001208 - 246Véh -11 09:05:03 08:58:29
</code></pre>
<p>I get this data frame from<code>df[df.duplicated(['NoUsager','NoDemande'],keep=False)]</code>which ensure my rows being in pair. I want to drop a pair of rows when <code>NoDemande</code> are continuous numbers (like 42191000822 and 42191000823, 42192000761 and 42192000762) and the column <code>HeurePrevue</code> are the same, which means the records are recorded twice. I have to delete a pair and I'd like to preseve the one with more positive numbers in column <code>Fait</code>(at least one greater than 0)</p>
<p>So my result should look like:</p>
<pre><code> NoDemande NoUsager Sens IdVehiculeUtilise Fait HeurePrevue HeureDebutTrajet
0 42191000823 001208 + 246Véh 1 08:20:04 08:22:26
3 42191000823 001208 - 246Véh 1 09:05:03 08:56:26
4 42191000834 001208 + 246Véh 1 16:50:04 16:39:26
5 42191000834 001208 - 246Véh 1 17:45:03 17:25:10
7 42192000762 001208 + 246Véh 1 08:20:04 08:18:27
8 42192000762 001208 - 246Véh -99 09:05:03 08:58:29
</code></pre>
<p>I know it's something about <code>OR</code> logic but I have no idea how to realize it.</p>
<p>Any help will be appreciated~</p>
| 1
|
2016-09-05T02:37:52Z
| 39,330,855
|
<p>This is a long-winded solution, there might be shorter ones. <code>frame0</code> is the exact frame you posted above.</p>
<p>First take the data, sort it by <code>NoDemande</code>, split it and recombine it so you have two pairings in the same row. Makes things a lot easier:</p>
<pre><code>frame0.HeurePrevue = pd.to_datetime(frame0.HeurePrevue)
frame0 = frame0.sort_values('NoDemande').reset_index(drop=True)
frameA = frame0.iloc[::2].reset_index(drop=True)
frameB = frame0.iloc[1::2].reset_index(drop=True)
frame1 = pd.concat([frameA,frameB],axis=1,join='inner')
frame1.columns = [u'NoDemande1', u'NoUsager1', u'Sens1', u'IdVehiculeUtilise1', u'Fait1',\
u'HeurePrevue1', u'HeureDebutTrajet1', u'NoDemande2', u'NoUsager2', u'Sens2',\
u'IdVehiculeUtilise2', u'Fait2', u'HeurePrevue2', u'HeureDebutTrajet2']
frame1 = frame1[[u'NoDemande1', u'Fait1',u'HeurePrevue1', u'NoDemande2',u'Fait2',\
u'HeurePrevue2']]
</code></pre>
<p>Next do some comparisons to see if in a given row the row ABOVE that row is a duplicate or not:</p>
<pre><code>frame2 = frame1[['NoDemande1','NoDemande2','HeurePrevue1','HeurePrevue2']].diff()
frame2['lastColumnsPartner'] = (frame2.NoDemande1 == 1) & (frame2.NoDemande2 == 1) &\
(frame2.HeurePrevue1 == pd.Timedelta(0)) &\
(frame2.HeurePrevue2 == pd.Timedelta(0))
frame2 = frame2['lastColumnsPartner'].to_frame()
frame1 = pd.merge(frame1,frame2,left_index=True,right_index=True)
</code></pre>
<p>Now check the values of <code>Fait</code>:</p>
<pre><code>frame1['Fait1Pos'] = 0
frame1['Fait2Pos'] = 0
frame1.ix[frame1.Fait1>0,'Fait1Pos'] = 1
frame1.ix[frame1.Fait2>0,'Fait2Pos'] = 1
frame1['FaitPos'] = frame1.Fait1Pos+frame1.Fait2Pos
frame1['FaitBool'] = (frame1.Fait1 > 0)|(frame1.Fait2 > 0)
</code></pre>
<p>Iterate over all rows and use the boolean <code>lastColumnsPartner</code> to create a new index which identifies duplicate rows:</p>
<pre><code>frame1['newIndex'] = 0
j = -1
for i,row in frame1.iterrows():
if frame1.ix[i,'lastColumnsPartner'] == False:
j+=1
frame1.ix[i,'newIndex'] = j
</code></pre>
<p>Take only rows with at least one positive value in <code>Fait</code> (<code>FaitBool</code>), sort by number of positive values of <code>Fait</code> (<code>FaitPos</code>), drop duplicates (<code>newIndex</code>) to keep only the highest value of <code>Fait</code>, then return <code>NoDemande</code>.</p>
<pre><code>tokeep = frame1[frame1.FaitBool][['NoDemande1','newIndex','FaitPos']]\
.sort_values('FaitPos',ascending=False).drop_duplicates('newIndex')['NoDemande1']
</code></pre>
<p>Finally use boolean indexing on the initial frame to filter everything.</p>
<pre><code>frame0 = frame0[frame0.NoDemande.isin(tokeep)]
</code></pre>
<p>I can't say for sure if it works for all cases, it works for your example. Also there is probably room for improvement.</p>
| 0
|
2016-09-05T12:41:01Z
|
[
"python",
"pandas",
"dataframe",
"duplicates"
] |
python - Removing duplicate rows under conditions in Pandas
| 39,323,225
|
<p>I have a DataFrame like this:</p>
<pre><code> NoDemande NoUsager Sens IdVehiculeUtilise Fait HeurePrevue HeureDebutTrajet
0 42191000823 001208 + 246Véh 1 08:20:04 08:22:26
1 42191000822 001208 + 246Véh 1 08:20:04 08:18:56
2 42191000822 001208 - 246Véh -99 09:05:03 08:56:26
3 42191000823 001208 - 246Véh 1 09:05:03 08:56:26
4 42191000834 001208 + 246Véh 1 16:50:04 16:39:26
5 42191000834 001208 - 246Véh 1 17:45:03 17:25:10
6 42192000761 001208 + 246Véh -1 08:20:04 08:15:07
7 42192000762 001208 + 246Véh 1 08:20:04 08:18:27
8 42192000762 001208 - 246Véh -99 09:05:03 08:58:29
9 42192000761 001208 - 246Véh -11 09:05:03 08:58:29
</code></pre>
<p>I get this data frame from<code>df[df.duplicated(['NoUsager','NoDemande'],keep=False)]</code>which ensure my rows being in pair. I want to drop a pair of rows when <code>NoDemande</code> are continuous numbers (like 42191000822 and 42191000823, 42192000761 and 42192000762) and the column <code>HeurePrevue</code> are the same, which means the records are recorded twice. I have to delete a pair and I'd like to preseve the one with more positive numbers in column <code>Fait</code>(at least one greater than 0)</p>
<p>So my result should look like:</p>
<pre><code> NoDemande NoUsager Sens IdVehiculeUtilise Fait HeurePrevue HeureDebutTrajet
0 42191000823 001208 + 246Véh 1 08:20:04 08:22:26
3 42191000823 001208 - 246Véh 1 09:05:03 08:56:26
4 42191000834 001208 + 246Véh 1 16:50:04 16:39:26
5 42191000834 001208 - 246Véh 1 17:45:03 17:25:10
7 42192000762 001208 + 246Véh 1 08:20:04 08:18:27
8 42192000762 001208 - 246Véh -99 09:05:03 08:58:29
</code></pre>
<p>I know it's something about <code>OR</code> logic but I have no idea how to realize it.</p>
<p>Any help will be appreciated~</p>
| 1
|
2016-09-05T02:37:52Z
| 39,331,422
|
<p>My approach on this problem was to make two columns which contain the conditions for a check (same heure and continuous increasing NoDemande). Then iterate over the dataframe dropping the pairs you do not want based on the Fait columns.</p>
<p>It's a bit of a hacky code but this seems to do the trick:</p>
<pre><code># Recreate DataFrame
df = pd.DataFrame({
'NoDemande': [23, 22, 22, 23, 34, 34, 61, 62, 62, 61],
'HeurePrevue': [84, 84, 93, 93, 64, 73, 84, 84, 93, 93],
'Fait': [1, 1, -99, 1, 1, 1, -1, 1, -99, -11]
}, columns=['NoDemande', 'Fait', 'HeurePrevue'])
# Make columns which contain conditions for inspection
df['sameHeure'] = df.HeurePrevue.iloc[1:] == df.HeurePrevue.iloc[:-1]
df['cont'] = df.NoDemande.diff()
# Cycle over rows
for prev_row, row in zip(df.iloc[:-1].itertuples(), df.iloc[1:].itertuples()):
if row.sameHeure and (row.cont == 1): # If rows are continuous and have the same Heure delete a pair
pair_1 = df.loc[df.NoDemande == row.NoDemande]
pair_2 = df.loc[df.NoDemande == prev_row.NoDemande]
if sum(pair_1.Fait > 0) < sum(pair_2.Fait > 0): # Find which pair to delete
df.drop(pair_1.index, inplace=True)
else:
df.drop(pair_2.index, inplace=True)
df.drop(['cont', 'sameHeure'], 1, inplace=True) # Throw away the added columns
</code></pre>
<p>result:</p>
<pre><code>print(df)
NoDemande Fait HeurePrevue
0 23 1 84
3 23 1 93
4 34 1 64
5 34 1 73
7 62 1 84
8 62 -99 93
</code></pre>
| 1
|
2016-09-05T13:14:11Z
|
[
"python",
"pandas",
"dataframe",
"duplicates"
] |
Django models class attribute and instance property?
| 39,323,233
|
<p>I implement very simple hit-count models in <code>Django</code>.</p>
<p><code>models.py</code></p>
<pre><code>from django.db import models
from model_utils.models import TimeStampedModel
from posts.models import Post
class PostHit(TimeStampedModel):
post = models.ForeignKey(Post, related_name='post_hits')
num_of_hit = models.IntegerField()
class Meta:
verbose_name_plural = "Post hits"
def __str__(self):
return self.post.title
def increase_hit(self):
self.num_of_hit += 1
</code></pre>
<p><code>views.py</code></p>
<pre><code>from django.views.generic.detail import DetailView
from django.core.exceptions import ObjectDoesNotExist
from posts.models import Post, PostHit
from posts.forms import CommentForm
class PostDetailView(DetailView):
model = Post
def get_context_data(self, *args, **kwargs):
context = super().get_context_data(**kwargs)
context['category'] = self.kwargs['category']
context['form'] = CommentForm()
context['tracking_hit_post'] = self.tracking_hit_post()
return context
def tracking_hit_post(self):
post = self.model.objects.get(pk=self.object.id)
post_hit = PostHit.objects.filter(post=post).first()
if post_hit:
post_hit.increase_hit()
else:
post_hit = PostHit.objects.create(
post=post,
num_of_hit=1
)
print(post_hit.num_of_hit)
return post_hit.num_of_hit
</code></pre>
<p>Once <code>PostHit</code> instance created, it calls <code>increase_hit()</code> everytime I visit <code>DetailVie</code>.</p>
<p>But it doesn't increase right way. </p>
<p>First it prints 1. And when I refresh the page, it prints 2. At next refresh, it prints 2 again. It doesn't increase anymore after 2. </p>
<p>What's wrong with my code? Did I misunderstand class attribute and instance property?</p>
| 0
|
2016-09-05T02:38:50Z
| 39,323,262
|
<p>You need to save the model after updating it:</p>
<pre><code>def increase_hit(self):
self.num_of_hit += 1
self.save()
</code></pre>
<p>Otherwise, your changes persist only for the lifetime of the object.</p>
| 2
|
2016-09-05T02:43:12Z
|
[
"python",
"django"
] |
How does this python yield function work?
| 39,323,239
|
<pre class="lang-py prettyprint-override"><code>def func():
output = 0
while True:
new = yield output
output = new
genr = func()
print(next(genr))
print(next(genr))
print(next(genr))
</code></pre>
<p>output:</p>
<blockquote>
<p>0<br>
None<br>
None </p>
</blockquote>
<p>What i thought is:</p>
<ol>
<li><code>genr=func()</code> return a generator, but does not actually run it.</li>
<li>First <code>print(next(genr))</code> run from the begining of func to <code>yield output</code>, but not yet assign back to <code>new</code>,so output <code>0</code> make sense. </li>
<li>Second <code>print(next(genr))</code> start from assigning <code>output</code> back to <code>new</code>ï¼and next line <code>output = new</code> make both <code>output</code> and <code>new</code> to 0, next execute <code>yield output</code> should return 0, but why it return <code>None</code> actually?</li>
</ol>
| 1
|
2016-09-05T02:39:42Z
| 39,323,300
|
<p>The result of a <a href="https://docs.python.org/3/reference/expressions.html#yieldexpr" rel="nofollow">yield expression</a> is the value sent in by the <a href="https://docs.python.org/3/reference/expressions.html#generator.send" rel="nofollow">generator.send()</a> function, and <code>next(gen)</code> is equivalent to <code>gen.send(None)</code>. So <code>new</code> receives the value <code>None</code> each time you call <code>next()</code>. </p>
<p>If you do this instead:</p>
<pre><code>gen = func()
print(next(gen)) # gets the first value of 'output'
print(next(gen)) # send in None, get None back
print(gen.send(10)) # send in 10, get 10 back
print(gen.send(20)) # send in 20, get 20 back
</code></pre>
<p>you'll get this output:</p>
<pre><code>0
None
10
20
</code></pre>
| 3
|
2016-09-05T02:49:32Z
|
[
"python",
"yield"
] |
How does this python yield function work?
| 39,323,239
|
<pre class="lang-py prettyprint-override"><code>def func():
output = 0
while True:
new = yield output
output = new
genr = func()
print(next(genr))
print(next(genr))
print(next(genr))
</code></pre>
<p>output:</p>
<blockquote>
<p>0<br>
None<br>
None </p>
</blockquote>
<p>What i thought is:</p>
<ol>
<li><code>genr=func()</code> return a generator, but does not actually run it.</li>
<li>First <code>print(next(genr))</code> run from the begining of func to <code>yield output</code>, but not yet assign back to <code>new</code>,so output <code>0</code> make sense. </li>
<li>Second <code>print(next(genr))</code> start from assigning <code>output</code> back to <code>new</code>ï¼and next line <code>output = new</code> make both <code>output</code> and <code>new</code> to 0, next execute <code>yield output</code> should return 0, but why it return <code>None</code> actually?</li>
</ol>
| 1
|
2016-09-05T02:39:42Z
| 39,323,321
|
<p>A <a href="https://docs.python.org/3.5/reference/simple_stmts.html#the-yield-statement"><em>yield</em></a> statement is used like <em>return</em> to return a value but it doesn't destroy the stack frame (the part of a function that knows the current line, local variables, and pending try-statements). This allows the function to be resumed after the yield.</p>
<p>When you call a function containing yield, it returns a <a href="https://docs.python.org/3.5/glossary.html#term-generator">"generator"</a> that allows you to run code up to a yield and then to resume it from where it left off.</p>
<pre><code>>>> def squares(n):
for i in range(n):
yield i ** 2
>>> g = squares(5) # create the generator
>>> g
<generator object squares at 0x106beef10>
>>> next(g) # run until the first yield
0
>>> next(g) # resume after the yield
1
>>> next(g) # resume after the yield
4
>>> next(g) # resume after the yield
9
>>> next(g) # resume after the yield
16
>>> next(g) # looping is terminated with a StopIteration
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
next(g) # looping is terminated with a StopIteration
StopIteration
</code></pre>
<p>Interestingly, a generator can accept values using the <em>send()</em> method. To prime the pump for such a generator the first call should be <em>next()</em>.</p>
<pre><code>>>> def capitalize():
word = 'start'
while word != 'quit':
word = yield word.capitalize()
>>> g = capitalize()
>>> next(g) # run to the first yield
'Start'
>>> g.send('three') # send in a value to be assigned to word
'Three'
>>> g.send('blind') # send in a value to be assigned to word
'Blind'
>>> g.send('mice') # send in a value to be assigned to word
'Mice'
>>> g.send('quit') # send in a control value
Traceback (most recent call last):
File "<pyshell#28>", line 1, in <module>
g.send('quit') # send in a control value
StopIteration
</code></pre>
<p>What you've figured-out in your example is that <code>next(g)</code> is really the same as <code>g.send(None)</code>.</p>
<p>Here's what <a href="https://docs.python.org/3.5/reference/expressions.html#yield-expressions">the docs</a> have to say:</p>
<blockquote>
<p>The value of the yield expression after resuming depends on the method
which resumed the execution. If __next__() is used (typically via
either a for or the <em>next()</em> builtin) then the result is <em>None</em>.
Otherwise, if <em>send()</em> is used, then the result will be the value passed
in to that method</p>
</blockquote>
<p>Here's a session that makes all of that visible:</p>
<pre><code>>>> def show_expression():
for i in range(5):
word = yield 10
print('The word is %r' % word)
>>> g = show_expression()
>>> next(g)
10
>>> g.send('blue')
The word is 'blue'
10
>>> g.send('no')
The word is 'no'
10
>>> g.send('yellow')
The word is 'yellow'
10
>>> next(g)
The word is None
10
>>> g.send('done')
The word is 'done'
Traceback (most recent call last):
File "<pyshell#44>", line 1, in <module>
g.send('done')
StopIteration
</code></pre>
<p>Hope that explains all the mysteries from first principles :-)</p>
| 7
|
2016-09-05T02:53:46Z
|
[
"python",
"yield"
] |
Selenium Python cannot select Element on ConnectWise Login Page
| 39,323,279
|
<p>Hi I am trying to select the Company Box on the Connectwise login page to automate a login.</p>
<p>However I have trouble even selecting the Company Field.</p>
<p><a href="http://i.stack.imgur.com/Z5en9.png" rel="nofollow"><img src="http://i.stack.imgur.com/Z5en9.png" alt="enter image description here"></a></p>
<p>The <strong>Element</strong> that needs selecting:</p>
<pre><code><input class="loginTextBox loginTextBox-watermark" type="text" autocomplete="off" autocorrect="off" autocapitalize="off"/>
</code></pre>
<p><strong>What I have tried:</strong></p>
<p>Tried <strong>XPATH</strong>: </p>
<pre><code>company_field = driver.find_element_by_xpath("/x:html/x:body/x:div[6]/x:div/x:table/x:tbody/x:tr[1]/x:td/x:table/x:tbody/x:tr[2]/x:td/x:table/x:tbody/x:tr[1]/x:td/x:table/x:tbody/x:tr/x:td[2]/x:table/x:tbody/x:tr[1]/x:td/x:input")
</code></pre>
<p>Stack Trace:</p>
<blockquote>
<p>selenium.common.exceptions.InvalidSelectorException: Message: invalid selector: Unable to locate an element with the xpath expression /x:html/x:body/x:div[6]/x:div/x:table/x:tbody/x:tr<a href="http://i.stack.imgur.com/Z5en9.png" rel="nofollow">1</a>/x:td/x:table/x:tbody/x:tr[2]/x:td/x:table/x:tbody/x:tr<a href="http://i.stack.imgur.com/Z5en9.png" rel="nofollow">1</a>/x:td/x:table/x:tbody/x:tr/x:td[2]/x:table/x:tbody/x:tr<a href="http://i.stack.imgur.com/Z5en9.png" rel="nofollow">1</a>/x:td/x:input because of the following error:</p>
</blockquote>
<p>Tried <strong>Class Selection</strong>: </p>
<pre><code>company_field = driver.find_element_by_class_name("loginTextBox loginTextBox-watermark")
</code></pre>
<p>Stack Trace:</p>
<blockquote>
<p>selenium.common.exceptions.InvalidSelectorException: Message: invalid selector: Compound class names not permitted</p>
</blockquote>
<p>Tried <strong>CSS</strong>:</p>
<pre><code>driver.find_element_by_css_selector(".loginTextBox loginTextBox-watermark[type='text']").click()
</code></pre>
<p>Stack Trace:</p>
<blockquote>
<p>selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":".loginTextBox loginTextBox-watermark[type='text']"}</p>
</blockquote>
<p><strong>HTML Source of Page:</strong></p>
<pre><code><document>
<html>
<head>
<body style="background-color: #F2F2F2; margin: 0px; padding: 0px;" ondragover="window.event.returnValue=false;">
<iframe id="__gwt_historyFrame" style="position:absolute;width:0;height:0;border:0" tabindex="-1" src="javascript:''"/>
<script src="common/scripts/cw.js?v=201561" type="text/javascript"/>
<script src="common/scripts/cw.io.js?v=201561" type="text/javascript"/>
<script language="javascript" type="text/javascript"> function checkSsl() { if (document.location.protocol != "https:" && document.location.host.indexOf("localhost") == -1 && document.location.href.indexOf("dotnet") == -1) { cw.io.jsonCall("login/IsSslRequired.rails", { 'onsuccess': function (data) { if (data.Data == true) { var url = "https://" + document.location.host + document.location.pathname + document.location.search + document.location.hash; document.location.href = url; } } }); } } cw.ui.createInitialLoadingNode(); checkSsl(); document.writeln("<script type='text/javascript' language='javascript' src='com.connectwise.psa/com.connectwise.psa.nocache.js'></scr" + "ipt>"); function dragover(e) { return false; } </script>
<div id="cw-loading" class="cw-loading">
<script src="com.connectwise.psa/com.connectwise.psa.nocache.js" language="javascript" type="text/javascript"/>
<iframe id="com.connectwise.psa" src="javascript:""" style="position: absolute; width: 0px; height: 0px; border: medium none; left: -1000px; top: -1000px;" tabindex="-1"/>
<div style="display: none;" aria-hidden="true"/>
<div style="position: absolute; z-index: -32767; top: -20cm; width: 10cm; height: 10cm; visibility: hidden;" aria-hidden="true"/>
<div style="position: absolute; left: 0px; top: 0px; right: 0px; bottom: 0px;">
<div class="GHN3134DCB" style="position: absolute; left: 0px; top: 0px; display: block; width: 1366px; height: 659px;"/>
<div class="GHN3134DJB" style="left: 435px; top: 163px; border-width: 0px; z-index: 555555555; position: absolute; overflow: visible; background-color: transparent;">
<div class="popupContent">
<table cellspacing="0" cellpadding="0" style="">
<tbody>
<tr>
<td align="left" style="vertical-align: top;">
<table class="GHN3134DK5I" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<tr>
<td align="left" style="vertical-align: top;">
<table class="GHN3134DJ5I" cellspacing="0" cellpadding="0" style="display: block;">
<tbody>
<tr>
<td align="left" style="vertical-align: top;">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td align="left" style="vertical-align: top;">
<td align="left" style="vertical-align: top;">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td align="left" style="vertical-align: top;">
<input class="loginTextBox loginTextBox-watermark loginTextBox-hightlight" type="text" autocomplete="off" autocorrect="off" autocapitalize="off"/>
</td>
</tr>
<tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
<tr>
<tr>
<tr>
<tr>
<tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
<tr>
</tbody>
</table>
</div>
</div>
</body>
</html>
</document>
</code></pre>
<p>Would appreciate any help?</p>
<p>Thanks for your time.</p>
| 1
|
2016-09-05T02:46:47Z
| 39,323,564
|
<blockquote>
<p>selenium.common.exceptions.InvalidSelectorException: Message: invalid selector: Unable to locate an element with the xpath expression /x:html/x:body/x:div[6]/x:div/x:table/x:tbody/x:tr1/x:td/x:table/x:tbody/x:tr[2]/x:td/x:table/x:tbody/x:tr1/x:td/x:table/x:tbody/x:tr/x:td[2]/x:table/x:tbody/x:tr1/x:td/x:input</p>
</blockquote>
<p>This error occurred because provided <code>xpath</code> syntactically incorrect.</p>
<blockquote>
<p>selenium.common.exceptions.InvalidSelectorException: Message: invalid selector: Compound class names not permitted</p>
</blockquote>
<p>This error occurred because selenium doesn't support compound class to locate an element.</p>
<blockquote>
<p>selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":".loginTextBox loginTextBox-watermark[type='text']"}</p>
</blockquote>
<p>This error occurred because you are locating incorrect element. According to locator it would be try to locate <code><loginTextBox-watermark></code> element which attribute <code>type</code> has value <code>text</code> and should be descendant of an element which has class attribute value <code>loginTextBox</code> which is incorrect.</p>
<p>So basically your all provided locators are syntactically or logically incorrect, you should try using correct <code>css_selector</code> locator as below :-</p>
<pre><code>driver.find_element_by_css_selector("input.loginTextBox.loginTextBox-watermark.loginTextBox-hightlight[type='text']")
</code></pre>
<p>Or if <code><table></code> class name <code>GHN3134DJ5I</code> is unique and fixed, you can try also as :-</p>
<pre><code>driver.find_element_by_css_selector("table.GHN3134DJ5I input.loginTextBox.loginTextBox-watermark.loginTextBox-hightlight[type='text']")
</code></pre>
<p><strong>Css Selector reference</strong> : to <a href="http://www.w3schools.com/cssref/css_selectors.asp" rel="nofollow">learn more about <code>css_selector</code> follow this reference</a></p>
<p><strong>Xpath reference</strong> : : to <a href="http://www.w3schools.com/xsl/xpath_syntax.asp" rel="nofollow">learn more about <code>xpath</code> follow this reference</a></p>
| 1
|
2016-09-05T03:32:58Z
|
[
"python",
"html",
"selenium"
] |
Can I find subject from Spacy Dependency tree using NLTK in python?
| 39,323,325
|
<p>I want to find the <strong>subject</strong> from a sentence using <code>Spacy</code>. The code below is working fine and giving a <strong>dependency tree</strong>.</p>
<pre><code>import spacy
from nltk import Tree
en_nlp = spacy.load('en')
doc = en_nlp("The quick brown fox jumps over the lazy dog.")
def to_nltk_tree(node):
if node.n_lefts + node.n_rights > 0:
return Tree(node.orth_, [to_nltk_tree(child) for child in node.children])
else:
return node.orth_
[to_nltk_tree(sent.root).pretty_print() for sent in doc.sents]
</code></pre>
<p><a href="http://i.stack.imgur.com/OhAFy.png" rel="nofollow"><img src="http://i.stack.imgur.com/OhAFy.png" alt="enter image description here"></a></p>
<p>From this dependency tree code, Can I find the <strong>subject</strong> of this sentence?</p>
| 0
|
2016-09-05T02:54:03Z
| 39,334,628
|
<p>I'm not sure whether you want to write code using the nltk parse tree (see <a href="http://stackoverflow.com/questions/28618400/how-to-identify-the-subject-of-a-sentence">How to identify the subject of a sentence?</a> ). But, spacy also generates this with the 'nsubj' label of the word.dep_ property. </p>
<pre><code>import spacy
from nltk import Tree
en_nlp = spacy.load('en')
doc = en_nlp("The quick brown fox jumps over the lazy dog.")
sentence = next(doc.sents)
for word in sentence:
... print "%s:%s" % (word,word.dep_)
...
The:det
quick:amod
brown:amod
fox:nsubj
jumps:ROOT
over:prep
the:det
lazy:amod
dog:pobj
</code></pre>
<p>Reminder that there could more complicated situations where there is more than one.</p>
<pre><code>>>> doc2 = en_nlp(u'When we study hard, we usually do well.')
>>> sentence2 = next(doc2.sents)
>>> for word in sentence2:
... print "%s:%s" %(word,word.dep_)
...
When:advmod
we:nsubj
study:advcl
hard:advmod
,:punct
we:nsubj
usually:advmod
do:ROOT
well:advmod
.:punct
</code></pre>
| 1
|
2016-09-05T16:33:44Z
|
[
"python",
"nlp",
"spacy"
] |
Turn on 2 LEDs, then blink one forever on button press
| 39,323,330
|
<p>I need help. I need my Raspberry Pi to turn on a Yellow LED and a Red LED. Then, when the Yellow button is pressed, I need the Yellow LED to start blinking forever, and for the Red LED to remain on.</p>
<p>Here is the code I have but it only partially works. It turns the Red LED on but the Yellow LED is off. (I thought that by setting GPIO.output(17, GPIO.HIGH) that that would turn the Yellow LED on, as it does for the Red LED, but it doesnât.)</p>
<p>Pressing the Yellow button starts the Yellow LED blinking forever, which is correct behavior but I need both LEDs to be on and then the Yellow to start blinking forever on the button press.</p>
<p>What am I doing wrong? Thanks!</p>
<pre><code>import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings (False)
GPIO.setup(24, GPIO.IN, pull_up_down = GPIO.PUD_DOWN) #Yellow button
GPIO.setup(17, GPIO.OUT) #Yellow LED
GPIO.setup(27, GPIO.OUT) #Red LED
GPIO.output(17, GPIO.HIGH) #Turn Yellow LED On
GPIO.output(27, GPIO.HIGH) #Turn Red LED On
blinking = False
while True:
if GPIO.input(24):
blinking = True
if blinking:
GPIO.output(17, GPIO.HIGH)
time.sleep(.2)
GPIO.output(17, GPIO.LOW)
time.sleep(.2)
time.sleep(.1)
</code></pre>
| 0
|
2016-09-05T02:54:49Z
| 39,324,240
|
<p>This should do the trick</p>
<pre><code>import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings (False)
GPIO.setup(24, GPIO.IN, pull_up_down = GPIO.PUD_DOWN) #Yellow button
GPIO.setup(17, GPIO.OUT) #Yellow LED
GPIO.setup(27, GPIO.OUT) #Red LED
GPIO.output(17, GPIO.HIGH) #Turn Yellow LED On
GPIO.output(27, GPIO.HIGH) #Turn Red LED On
blinking = False
while True:
if GPIO.input( 24 ):
blinking = True
while blinking:
GPIO.output(17, GPIO.HIGH)
time.sleep(.2)
GPIO.output(17, GPIO.LOW)
time.sleep(.2)
time.sleep(.1)
</code></pre>
| 0
|
2016-09-05T05:08:21Z
|
[
"python",
"button",
"raspberry-pi",
"gpio",
"led"
] |
Replacing unknown characters in a string Python 2.7
| 39,323,331
|
<p>How can I define characters(in a LIST or a STRING), and have any other characters replaced with.. lets say a '?'</p>
<p>Example:</p>
<pre><code>strinput = "abcdefg#~"
legal = '.,/?~abcdefg' #legal characters
while i not in legal:
#Turn i into '?'
print output
</code></pre>
| -1
|
2016-09-05T02:54:49Z
| 39,323,411
|
<p>If this is a large file, read in chunks, and apply <code>re.sub(..)</code> as below. <code>^</code> within a class (square brackets) stands for negation (similar to saying "anything other than")</p>
<pre><code>>>> import re
>>> char = '.,/?~abcdefg'
>>> re.sub(r'[^' + char +']', '?', "test.,/?~abcdefgh")
'?e??.,/?~abcdefg?'
</code></pre>
| 1
|
2016-09-05T03:08:36Z
|
[
"python",
"python-2.7"
] |
Replacing unknown characters in a string Python 2.7
| 39,323,331
|
<p>How can I define characters(in a LIST or a STRING), and have any other characters replaced with.. lets say a '?'</p>
<p>Example:</p>
<pre><code>strinput = "abcdefg#~"
legal = '.,/?~abcdefg' #legal characters
while i not in legal:
#Turn i into '?'
print output
</code></pre>
| -1
|
2016-09-05T02:54:49Z
| 39,323,575
|
<p>Put the legal characters in a set then use <a href="https://docs.python.org/3/reference/expressions.html?highlight=membership#membership-test-operations" rel="nofollow"><code>in</code></a> to test each character of the string. Construct the new string using the <a href="https://docs.python.org/3/library/stdtypes.html#str.join" rel="nofollow"><code>str.join()</code></a> method and a <a href="https://docs.python.org/3/reference/expressions.html#conditional-expressions" rel="nofollow">conditional expression</a>.</p>
<pre><code>>>> s = "test.,/?~abcdefgh"
>>> legal = set('.,/?~abcdefg')
>>> s = ''.join(char if char in legal else '?' for char in s)
>>> s
'?e??.,/?~abcdefg?'
>>>
</code></pre>
| 4
|
2016-09-05T03:35:09Z
|
[
"python",
"python-2.7"
] |
Stopping iterations in python
| 39,323,465
|
<p>I'm relatively new to coding, and I made this program to repeat mouse strokes when I am on a certain webpage so that the process can be automated. </p>
<pre><code>import pyautogui, time
inp = raw_input("Number input?")
iterations = raw_input("Iterations?")
def move(x, y):
pyautogui.moveTo(x, y)
for i in range(int(iterations)):
move(540,515)
pyautogui.click()
move(690,760)
pyautogui.click()
pyautogui.typewrite(inp)
move(1200,790)
pyautogui.click()
move(1200,340)
pyautogui.click()
</code></pre>
<p>If I inputted too many iterations or I need to control my mouse again before the iterations are complete, is there a way to stop the loop/iterations? I tried to use CTRL+BREAK, but it didn't stop the loop. I also tried to add KeyboardInterrupt by using CTRL+C, but I couldn't figure out how to do it for my script.</p>
| 0
|
2016-09-05T03:17:16Z
| 39,323,953
|
<p>For ctrl + C to work, the active window must be the one with the terminal running python.</p>
<p>I guess that it may be tricky when you have your program clicking everywhere...</p>
<p>Now to make an answer worth your while, I introduce you to web browsing with python : <a href="http://selenium-python.readthedocs.io/getting-started.html#simple-usage" rel="nofollow">http://selenium-python.readthedocs.io/getting-started.html#simple-usage</a></p>
<p>This way your program can run in background and you can kill it whenever you want.</p>
| 0
|
2016-09-05T04:29:17Z
|
[
"python",
"loops",
"break"
] |
Try Except block not working with datetime object?
| 39,323,466
|
<p>I have a DataFrame with some datetime data in one column and whatever else in other columns. However, some of the data is messed up, e.g.:</p>
<pre><code>11/11/2014 22:28 15.1
11/11/2014 22:29 16.1
11/11/2014 22:30 15.2
bollocks 10000
11/11/2014 22:32 15.4
:00
11/11/2014 22:34 15.3
</code></pre>
<p>I would like to get rid of the lines that are messed up. For now, I decided to just replace them with NaN values (but dropping them would also help, only it didn't work in the cycle so it's not an issue, in the next step I can just use <code>dropna()</code>). I'm doing this using <code>try()</code>, but the exception doesn't work. My code looks like this:</p>
<pre><code>for line in df.ix[:,"DATETIME"]:
try:
line = datetime.datetime.strptime(line,"%d/%m/%Y %H:%M")
except ValueError:
line = 'NaN'
except TypeError:
line = 'NaN'
</code></pre>
<p>But in the end, I still get the <code>ValueError: time data '156004E00F455AA' does not match format '%d/%m/%Y %H:%M'</code> and the faulty lines are not replaced with <code>NaN</code>. What is wrong here?
(I also tried putting the errors on one line like this: <code>except (ValueError, TypeError):</code> and it didn't work either...)</p>
| 0
|
2016-09-05T03:17:32Z
| 39,323,626
|
<p>This doesn't strictly answer your query, but if you are sure that all the valid datetime strings will be of the format: <code>"%d/%m/%Y %H:%M"</code>, you can do:</p>
<pre><code>In [34]: df
Out[34]:
DATETIME VALUES
0 11/11/2014 22:28 15.1
1 11/11/2014 22:29 16.1
2 11/11/2014 22:30 15.2
3 bollocks 10000.0
4 11/11/2014 22:32 15.4
5 :00 NaN
6 11/11/2014 22:34 15.3
In [35]: df = df.replace(r'^(?!\d{2}/\d{2}/\d{4} \d{2}:\d{2}).*', np.nan, regex=True)
In [36]: df
Out[36]:
DATETIME VALUES
0 11/11/2014 22:28 15.1
1 11/11/2014 22:29 16.1
2 11/11/2014 22:30 15.2
3 NaN 10000.0
4 11/11/2014 22:32 15.4
5 NaN NaN
6 11/11/2014 22:34 15.3
In [37]: df['DATETIME'].apply(lambda x: pd.to_datetime(x, format="%d/%m/%Y %H:%M"))
Out[37]:
0 2014-11-11 22:28:00
1 2014-11-11 22:29:00
2 2014-11-11 22:30:00
3 NaT
4 2014-11-11 22:32:00
5 NaT
6 2014-11-11 22:34:00
Name: DATETIME, dtype: datetime64[ns]
</code></pre>
| 0
|
2016-09-05T03:42:18Z
|
[
"python",
"datetime",
"pandas"
] |
Try Except block not working with datetime object?
| 39,323,466
|
<p>I have a DataFrame with some datetime data in one column and whatever else in other columns. However, some of the data is messed up, e.g.:</p>
<pre><code>11/11/2014 22:28 15.1
11/11/2014 22:29 16.1
11/11/2014 22:30 15.2
bollocks 10000
11/11/2014 22:32 15.4
:00
11/11/2014 22:34 15.3
</code></pre>
<p>I would like to get rid of the lines that are messed up. For now, I decided to just replace them with NaN values (but dropping them would also help, only it didn't work in the cycle so it's not an issue, in the next step I can just use <code>dropna()</code>). I'm doing this using <code>try()</code>, but the exception doesn't work. My code looks like this:</p>
<pre><code>for line in df.ix[:,"DATETIME"]:
try:
line = datetime.datetime.strptime(line,"%d/%m/%Y %H:%M")
except ValueError:
line = 'NaN'
except TypeError:
line = 'NaN'
</code></pre>
<p>But in the end, I still get the <code>ValueError: time data '156004E00F455AA' does not match format '%d/%m/%Y %H:%M'</code> and the faulty lines are not replaced with <code>NaN</code>. What is wrong here?
(I also tried putting the errors on one line like this: <code>except (ValueError, TypeError):</code> and it didn't work either...)</p>
| 0
|
2016-09-05T03:17:32Z
| 39,323,837
|
<p><a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow"><code>pd.to_datetime</code></a> can set to <code>NaT</code> ill-formed data while converting the column to datetime. </p>
<pre><code>pd.to_datetime(df['DATETIME'], format = '%d/%m/%Y %H:%M', errors='coerce')
DATETIME
0 11/11/2014 22:28
1 11/11/2014 22:29
2 11/11/2014 22:30
3 NaT
4 11/11/2014 22:32
5 NaT
6 11/11/2014 22:34
</code></pre>
| 1
|
2016-09-05T04:13:53Z
|
[
"python",
"datetime",
"pandas"
] |
How to take multiple sets of inputs separated by space and carriage return in Python 3?
| 39,323,505
|
<p>So we are allowing a user to enter the number sets they want to enter. Each set of input will contain two integers separated by space. Then, the carriage return denotes the next set of inputs. For example,</p>
<pre><code>Enter number of sets: 3
1 3
2 4
5 6
</code></pre>
<p>Next we input these in variables a,b, perform same operations, display 3 results:</p>
<pre><code>4
3
1
</code></pre>
<p>It should first take all inputs <em>and then</em> show all respective outputs.
We have the logic of processing 1 set of input, but how do we loop it so that we can accept input in this format?</p>
<pre><code>sets = int(input("Enter number of sets: "))
inputs = []
for n in range(sets):
inputs[n] = int(input().strip())
</code></pre>
<p>This crashes with list out of range error. We were thinking of creating a list of lists to hold the pair of values. Any easier solutions?</p>
<p>EDIT: What I'm looking for is a way to solve this problem. It doesn't have to be done via lists specifically. It is not a generic list out of range problem. I do understand what is going wrong, I just need another way to do it.</p>
| -1
|
2016-09-05T03:23:48Z
| 39,323,574
|
<p>The <code>input()</code> is returning a string like <code>"1 3"</code>. Parse that string with something like, <code>a, b = map(int, input().split())</code>. Save the output by using <em>list.append()</em>.</p>
<pre><code>from pprint import pprint
inputs = []
results = []
sets = int(input("Enter number of sets: "))
for n in range(sets):
s = input()
a, b = map(int, s.split())
result = a + b
inputs.append([a, b])
results.append(result)
pprint(inputs)
pprint(results)
</code></pre>
<p>A sample session looks like this:</p>
<pre><code>Enter number of sets: 3
1 3
2 4
5 6
[[1, 3], [2, 4], [5, 6]]
[4, 6, 11]
</code></pre>
<p>The learning points are:</p>
<ul>
<li>Use <a href="https://docs.python.org/3.5/library/stdtypes.html#str.split" rel="nofollow">str.split()</a> to convert a string like <code>"1 3"</code> into a list like <code>['1', '3']</code></li>
<li>Use <a href="https://docs.python.org/3.5/library/functions.html#map" rel="nofollow"><em>map()</em></a> with <a href="https://docs.python.org/3.5/library/functions.html#int" rel="nofollow"><em>int()</em></a> to convert <code>['1', '3']</code> to <code>[1, 3]</code></li>
<li>Use <a href="https://docs.python.org/3.5/tutorial/controlflow.html#unpacking-argument-lists" rel="nofollow">variable unpacking</a> to extract the two values</li>
<li>Use <a href="https://docs.python.org/3.5/library/stdtypes.html#mutable-sequence-types" rel="nofollow"><em>append()</em></a> to grow the <em>inputs</em> and <em>results</em> lists</li>
</ul>
| 4
|
2016-09-05T03:35:04Z
|
[
"python",
"list",
"user-input",
"python-3.4"
] |
How can I create a dictionary from a list of k:v tuples returned from a SQL query?
| 39,323,623
|
<p>My SQL (sqlite3) query is along the lines of this:</p>
<pre><code>SELECT id, name FROM mytable;
</code></pre>
<p>This returns a ton of rows. I would like to create a dictionary from these results, where I can lookup the name given an id.</p>
<p>Other answers I've found seem to create dictionaries based on SQL results, but they use the column label as the key -- I have no interest in that.</p>
<p>Example table:</p>
<pre><code>id | name
------+--------
foo | bar
baz | foobar
</code></pre>
<p>Desired dict:</p>
<pre><code>{
'foo': 'bar',
'baz': 'foobar'
}
</code></pre>
| 2
|
2016-09-05T03:40:54Z
| 39,323,691
|
<p>You can loop over the rows (the <a href="https://docs.python.org/3/library/sqlite3.html#module-sqlite3" rel="nofollow">result cursor is iterable</a>), <a href="https://docs.python.org/3/tutorial/datastructures.html#tuples-and-sequences" rel="nofollow">unpack</a> the key and value, then assemble the result using a <a href="https://docs.python.org/3/tutorial/datastructures.html#dictionaries" rel="nofollow">dict comprehension</a>:</p>
<pre><code>desired_dict = {k:v for k, v in c.execute('SELECT id, name FROM MyTable')}
</code></pre>
<p>I like using dict comprehensions because I can do additional processing to the results before adding to the dictionary (for example changing case, converting to decimal or datetime, etc).</p>
<p>That said, if you want to go directly to the dict, <em>ozgur</em> has the shorter, faster way which is to call <a href="https://docs.python.org/3/library/functions.html#func-dict" rel="nofollow"><em>dict()</em></a> directly:</p>
<pre><code>desired_dict = dict(c.execute('SELECT id, name FROM MyTable'))
</code></pre>
<p>Here's an actual sample session demonstrating the process start to finish:</p>
<pre><code>>>> import sqlite3
>>> c = sqlite3.connect('tmp.db')
>>> c.execute('CREATE TABLE MyTable (id text, name text)')
<sqlite3.Cursor object at 0x106227f80>
>>> c.execute("INSERT INTO MyTable VALUES ('abc', 'Alpha')")
<sqlite3.Cursor object at 0x106283810>
>>> c.execute("INSERT INTO MyTable VALUES ('def', 'Beta')")
<sqlite3.Cursor object at 0x106227f80>
>>> c.execute("INSERT INTO MyTable VALUES ('ghi', 'Gamma')")
<sqlite3.Cursor object at 0x106283810>
>>> c.commit()
>>> c.close()
>>>
>>> c = sqlite3.connect('tmp.db')
>>> {k:v for k, v in c.execute('SELECT id, name FROM MyTable')}
{'ghi': 'Gamma', 'def': 'Beta', 'abc': 'Alpha'}
</code></pre>
| 3
|
2016-09-05T03:52:51Z
|
[
"python",
"sql",
"dictionary",
"sqlite3"
] |
How can I create a dictionary from a list of k:v tuples returned from a SQL query?
| 39,323,623
|
<p>My SQL (sqlite3) query is along the lines of this:</p>
<pre><code>SELECT id, name FROM mytable;
</code></pre>
<p>This returns a ton of rows. I would like to create a dictionary from these results, where I can lookup the name given an id.</p>
<p>Other answers I've found seem to create dictionaries based on SQL results, but they use the column label as the key -- I have no interest in that.</p>
<p>Example table:</p>
<pre><code>id | name
------+--------
foo | bar
baz | foobar
</code></pre>
<p>Desired dict:</p>
<pre><code>{
'foo': 'bar',
'baz': 'foobar'
}
</code></pre>
| 2
|
2016-09-05T03:40:54Z
| 39,323,709
|
<p>The result returned from cursor is a list of 2-elements tuples so you can just convert that to a dictionary as the first item of each tuple is a unique value:</p>
<pre><code>result = dict(cursor.execute("SELECT id, name FROM mytable"))
</code></pre>
| 2
|
2016-09-05T03:55:18Z
|
[
"python",
"sql",
"dictionary",
"sqlite3"
] |
How can I create a dictionary from a list of k:v tuples returned from a SQL query?
| 39,323,623
|
<p>My SQL (sqlite3) query is along the lines of this:</p>
<pre><code>SELECT id, name FROM mytable;
</code></pre>
<p>This returns a ton of rows. I would like to create a dictionary from these results, where I can lookup the name given an id.</p>
<p>Other answers I've found seem to create dictionaries based on SQL results, but they use the column label as the key -- I have no interest in that.</p>
<p>Example table:</p>
<pre><code>id | name
------+--------
foo | bar
baz | foobar
</code></pre>
<p>Desired dict:</p>
<pre><code>{
'foo': 'bar',
'baz': 'foobar'
}
</code></pre>
| 2
|
2016-09-05T03:40:54Z
| 39,323,710
|
<p>Suppose you get your sql query result in Python, something like</p>
<p><code>db_conn = sqlite3.connect('text.db')
cur = db_conn.cursor()
cur.execute('''select id, name from mytable''')</code></p>
<p>Then you can get all the query results in the return of <code>cur.fetchall()</code>.
The result will be a list of tuples, each tuple will be like (<em>id</em>,<em>name</em>).</p>
<p>Knowing this, then it is a piece of cake to transform it into an dictionary,just:</p>
<p><code>mydict = {}
for item in cur.fetchall():
mydict[item[0]] = item[1]
</code></p>
| 0
|
2016-09-05T03:55:19Z
|
[
"python",
"sql",
"dictionary",
"sqlite3"
] |
Extracting text within tag with BeautifulSoup
| 39,323,666
|
<pre><code> <div>
<p class="tabbed" style="margin-top:2px;"><span class="tab"><strong>LANGUAGES</strong></span>Cantonese</p>
<p class="tabbed" style="margin-top:2px;"><span class="tab"></span>English</p>
<p class="tabbed" style="margin-top:2px;"><span class="tab"></span>Putonghua</p>
<p class="tabbed"><span class="tab"><strong>GENDER</strong></span>Male</p>
</div>
</code></pre>
<p>I would like to extract the "Male" in the 5th line but I don't know how to do it. Can anyone help?
I tried " gen = soup.find('span', class_='tab').string" but it doesn't work. </p>
| 0
|
2016-09-05T03:49:17Z
| 39,323,759
|
<p>You can use the <a href="https://www.google.co.in/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&uact=8&ved=0ahUKEwja4Ii7q_fOAhVGN48KHR_QDZsQygQIHzAA&url=https%3A%2F%2Fwww.crummy.com%2Fsoftware%2FBeautifulSoup%2Fdocumentation.html%23The%2520basic%2520find%2520method%3A%2520findAll(name%2C%2520attrs%2C%2520recursive%2C%2520text%2C%2520limit%2C%2520**kwargs)&usg=AFQjCNFvmAXY4S9WJwdCGla7HED-zGam4A&sig2=-fvqI2tGt02bZk6ckYAqaA&bvm=bv.131783435,d.c2I" rel="nofollow">.findAll()</a> method:</p>
<pre><code>In [37]: from bs4 import BeautifulSoup
In [38]: soup = BeautifulSoup("""<div>
...: <p class="tabbed" style="margin-top:2px;"><span class="tab"><strong>LANGUAGES</strong></span>Cantonese</p>
...: <p class="tabbed" style="margin-top:2px;"><span class="tab"></span>English</p>
...: <p class="tabbed" style="margin-top:2px;"><span class="tab"></span>Putonghua</p>
...: <p class="tabbed"><span class="tab"><strong>GENDER</strong></span>Male</p>
...: </div>""", "html")
In [39]: soup.find(lambda tag: tag.text.startswith('GENDER')).text[6:]
Out[39]: u'Male'
</code></pre>
| 0
|
2016-09-05T04:00:29Z
|
[
"python",
"html",
"text",
"tags",
"beautifulsoup"
] |
Extracting text within tag with BeautifulSoup
| 39,323,666
|
<pre><code> <div>
<p class="tabbed" style="margin-top:2px;"><span class="tab"><strong>LANGUAGES</strong></span>Cantonese</p>
<p class="tabbed" style="margin-top:2px;"><span class="tab"></span>English</p>
<p class="tabbed" style="margin-top:2px;"><span class="tab"></span>Putonghua</p>
<p class="tabbed"><span class="tab"><strong>GENDER</strong></span>Male</p>
</div>
</code></pre>
<p>I would like to extract the "Male" in the 5th line but I don't know how to do it. Can anyone help?
I tried " gen = soup.find('span', class_='tab').string" but it doesn't work. </p>
| 0
|
2016-09-05T03:49:17Z
| 39,328,973
|
<p>You don't need to search every tag, you can find the span where the <code>text="GENDER"</code> and get the text from the parent <code>p</code> setting <em>resursive=False</em> to only get the parent text:</p>
<pre><code>In [4]: from bs4 import BeautifulSoup
In [5]: h = """<div>
...: <p class="tabbed" style="margin-top:2px;"><span class="tab"><strong>LANGUAGES</strong></span>Cantonese</p>
...: <p class="tabbed" style="margin-top:2px;"><span class="tab"></span>English</p>
...: <p class="tabbed" style="margin-top:2px;"><span class="tab"></span>Putonghua</p>
...: <p class="tabbed"><span class="tab"><strong>GENDER</strong></span>Male</p>
...: </div>"""
In [6]: soup = BeautifulSoup(h,"html.parser")
In [7]: soup.find("span","tab", text="GENDER").parent.find(text=True,recursive=False)
Out[7]: u'Male'
</code></pre>
<p>Or just using the span without the class name:</p>
<pre><code>In [8]: soup.find("span",text="GENDER").parent.find(text=True,recursive=False)
Out[8]: u'Male'
</code></pre>
| 0
|
2016-09-05T10:48:24Z
|
[
"python",
"html",
"text",
"tags",
"beautifulsoup"
] |
Extracting text within tag with BeautifulSoup
| 39,323,666
|
<pre><code> <div>
<p class="tabbed" style="margin-top:2px;"><span class="tab"><strong>LANGUAGES</strong></span>Cantonese</p>
<p class="tabbed" style="margin-top:2px;"><span class="tab"></span>English</p>
<p class="tabbed" style="margin-top:2px;"><span class="tab"></span>Putonghua</p>
<p class="tabbed"><span class="tab"><strong>GENDER</strong></span>Male</p>
</div>
</code></pre>
<p>I would like to extract the "Male" in the 5th line but I don't know how to do it. Can anyone help?
I tried " gen = soup.find('span', class_='tab').string" but it doesn't work. </p>
| 0
|
2016-09-05T03:49:17Z
| 39,331,893
|
<p>Here's a simpler way for you to understand: You can get your desired output by parsing the "p" tags. </p>
<pre><code>from bs4 import BeautifulSoup
doc = """
<div>
<p class="tabbed" style="margin-top:2px;"><span class="tab"><strong>LANGUAGES</strong></span>Cantonese</p>
<p class="tabbed" style="margin-top:2px;"><span class="tab"></span>English</p>
<p class="tabbed" style="margin-top:2px;"><span class="tab"></span>Putonghua</p>
<p class="tabbed"><span class="tab"><strong>GENDER</strong></span>Male</p>
</div>
"""
soup = BeautifulSoup(doc, "lxml")
ptags = soup.find_all("p", attrs={'class':'tabbed'})
for ptag in ptags:
print ptag.contents[1].string.strip()
</code></pre>
<p>This will give you the output of every "p"tag as follows</p>
<pre><code>Cantonese
English
Putonghua
Male
</code></pre>
<p>Now if you just want the value of the 4th ptag you could replace the above "for loop" with this one line. Assume you are sure you always want the value of 4th ptag, do the folowing</p>
<pre><code>print ptags[3].contents[1].string.strip()
</code></pre>
<p>will give output:</p>
<pre><code>Male
</code></pre>
<hr>
<p>Explanation:</p>
<pre><code>ptags = soup.find_all("p", attrs={'class':'tabbed'})
</code></pre>
<p>This returns a ResultSet - basically a list of ptags. Each ptag in your case has two elements the span tag and string.</p>
<pre><code>print ptags
[<p class="tabbed" style="margin-top:2px;"><span class="tab"><strong>LANGUAGES</strong></span>Cantonese</p>,
<p class="tabbed" style="margin-top:2px;"><span class="tab"></span>English</p>,
<p class="tabbed" style="margin-top:2px;"><span class="tab"></span>Putonghua</p>,
<p class="tabbed"><span class="tab"><strong>GENDER</strong></span>Male</p>]
</code></pre>
<p>Now for every ptag if your print its contents "ptag.contents" it returns a list of elements in the tag
eg:</p>
<pre><code>for ptag in ptags:
print ptag.contents
</code></pre>
<p>will give:</p>
<pre><code>[<span class="tab"><strong>LANGUAGES</strong></span>, u'Cantonese']
[<span class="tab"></span>, u'English']
[<span class="tab"></span>, u'Putonghua']
[<span class="tab"><strong>GENDER</strong></span>, u'Male']
</code></pre>
<p>Now you want the 2nd element in the list, so just get the 2nd element</p>
<pre><code>for ptag in ptags:
print ptag.contents[1].string.strip()
</code></pre>
<p>output:</p>
<pre><code>Cantonese
English
Putonghua
Male
</code></pre>
<p>To print just the 4th one of the ptags</p>
<pre><code>print ptags[3].contents[1].string.strip()
</code></pre>
<p>output:</p>
<pre><code>Male
</code></pre>
| 0
|
2016-09-05T13:39:43Z
|
[
"python",
"html",
"text",
"tags",
"beautifulsoup"
] |
Zeppelin and BigQuery
| 39,323,667
|
<p>I'm looking for a visualisation and analytical notebook engine for <code>BigQuery</code> and am interested in <code>Apache</code>/<code>Zeppelin</code>.</p>
<p>We have internal capability in <code>Python</code> and <code>R</code> and want to use this with our <code>BigQuery</code> back end.</p>
<p>All the installation scenarios I've seen so far ( eg: <a href="https://cloud.google.com/blog/big-data/2016/09/analyzing-bigquery-datasets-using-bigquery-interpreter-for-apache-zeppelin" rel="nofollow">https://cloud.google.com/blog/big-data/2016/09/analyzing-bigquery-datasets-using-bigquery-interpreter-for-apache-zeppelin</a>) seem to require the installation of a fairly hefty <code>Scala</code>/<code>Spark</code> cluster which I don't see the need for (and which would cost a lot)</p>
<p>Is it possible to install <code>Zeppelin</code> without the cluster in <code>Google Cloud</code>?</p>
| 0
|
2016-09-05T03:49:45Z
| 39,324,306
|
<p>Starting with 0.6.1 there is a <a href="https://zeppelin.apache.org/docs/0.6.1/interpreter/bigquery.html" rel="nofollow">Native BigQuery Interpreter for Apache Zeppelin</a> available.<br>
It allows you to process and analyze datasets stored in Google BigQuery by directly running SQL against it from within an Apache Zeppelin notebook.<br>
So you do not need anymore query BigQuery using Apache Spark as it was only way before</p>
| 1
|
2016-09-05T05:17:06Z
|
[
"python",
"google-bigquery",
"apache-zeppelin"
] |
How do you make a list of lists in python3?
| 39,323,671
|
<p>So, currently I've created 2 empty <code>list</code>, with length 128 and 64, added numbers into them (just to test it out) and now I'm trying to insert the <code>DirectoryEntries</code> <code>list</code> into the <code>AvailableBlocks</code> <code>list</code>. But when I print the new list out, it just prints <code>None</code>. Is there a way to do this while keeping <code>DirectoryEntries</code> a <code>list</code>?</p>
<pre><code>AvailableBlocks = list() * 128
DirectoryEntries = list() * 64
AvailableBlocks.append(1)
AvailableBlocks.append(2)
print(AvailableBlocks)
DirectoryEntries.append(123)
DirectoryEntries.append(456)
print(DirectoryEntries)
print(AvailableBlocks.insert(0, DirectoryEntries))
</code></pre>
| 2
|
2016-09-05T03:50:18Z
| 39,323,750
|
<p>The insert does not return a value.
Try</p>
<pre><code>AvailableBlocks.insert(0, DirectoryEntries)
print(AvailableBlocks)
</code></pre>
<p>and it should work</p>
| 4
|
2016-09-05T03:59:05Z
|
[
"python",
"list",
"insert",
"python-3.5"
] |
Updating Jinja2 Variables every X seconds - Python Flask
| 39,323,779
|
<p>I am trying to update variables inside of my index.html file. I am going to be running a thread with a loop in python but I want a way to update my jinja2 table listed below to update every x seconds just like if you were using php and ajax.</p>
<p>Here is my Jinja2 Code: </p>
<pre><code><table border=1 id="allTable" class="display">
<tbody id="eliteTable">
<tr><td colspan=9 class=queueheader>Elite (Current SLA: {{ eliteSLA | safe}}%)</td></tr>
<tr><th>Skill</th><th>SLA</th><th>Calls Waiting</th><th>Hold Time</th><th>Staffed</th><th>Avail</th><th>ACW</th><th>Aux</th><th>ACD Calls</th></tr>
{% for row in eliteList %}
{% if row[2]|int > 30 %}
<tr class=longwait>
{% elif row[2]|int > 0 %}
<tr class=waiting>
{% else %}
<tr>
{% endif %}
{% for i in row %}
<td> {{ i | safe }} </td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
</code></pre>
| -1
|
2016-09-05T04:03:33Z
| 39,323,881
|
<p>You'll need some javascript in there.</p>
<p>Either ajax requests, or websockets, though ajax might be simpler.</p>
<p>Simply use javascript <code>setInterval()</code> with an ajax request.</p>
<p>I'd recommend using a library, maybe jquery as it is very simple.</p>
<pre><code>$.get( "/auto_refresh", function( data ) {
alert( "Data Loaded: " + data );
});
</code></pre>
<p>Note that jinja2 is just for the templating, meaning that at some point the jinja templates get translated into html/css.
So you can play with ajax like you did when you were using PHP.</p>
| 1
|
2016-09-05T04:18:45Z
|
[
"python",
"html",
"flask",
"jinja2"
] |
Updating Jinja2 Variables every X seconds - Python Flask
| 39,323,779
|
<p>I am trying to update variables inside of my index.html file. I am going to be running a thread with a loop in python but I want a way to update my jinja2 table listed below to update every x seconds just like if you were using php and ajax.</p>
<p>Here is my Jinja2 Code: </p>
<pre><code><table border=1 id="allTable" class="display">
<tbody id="eliteTable">
<tr><td colspan=9 class=queueheader>Elite (Current SLA: {{ eliteSLA | safe}}%)</td></tr>
<tr><th>Skill</th><th>SLA</th><th>Calls Waiting</th><th>Hold Time</th><th>Staffed</th><th>Avail</th><th>ACW</th><th>Aux</th><th>ACD Calls</th></tr>
{% for row in eliteList %}
{% if row[2]|int > 30 %}
<tr class=longwait>
{% elif row[2]|int > 0 %}
<tr class=waiting>
{% else %}
<tr>
{% endif %}
{% for i in row %}
<td> {{ i | safe }} </td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
</code></pre>
| -1
|
2016-09-05T04:03:33Z
| 39,353,382
|
<p>Jinja variables are generated at template render-time. There's no way to programmatically update them without using javascript of some sort.</p>
<p>From <a href="http://jinja.pocoo.org/docs/dev/templates/" rel="nofollow">the docs</a> (emphasis mine):</p>
<blockquote>
<p>A [Jinja] template contains variables and/or expressions, <strong>which get replaced with values when a template is rendered</strong>; and tags, which control the logic of the template. The template syntax is heavily inspired by Django and Python.</p>
</blockquote>
| 0
|
2016-09-06T16:06:24Z
|
[
"python",
"html",
"flask",
"jinja2"
] |
Limits on Complex Sparse Linear Algebra in Python
| 39,323,796
|
<p>I am prototyping numerical algorithms for linear programming and matrix manipulation with very large (100,000 x 100,000) very sparse (0.01% fill) complex (a+b*i) matrices with symmetric structure and asymmetric values. I have been happily using MATLAB for seven years, but have been receiving suggestions to switch to Python since it is open source.</p>
<p>I understand that there are many different Python numeric packages available, but does Python have any limits for handling these types of matrices and solving linear optimization problems in real time at high speed? Does Python have a sparse complex matrix solver comparable in speed to MATLAB's backslash A\b operator? (I have written Gaussian and LU codes, but A\B is always at least 5 times faster than anything else that I have tried and scales linearly with matrix size.)</p>
| 0
|
2016-09-05T04:06:14Z
| 39,326,243
|
<p>Probably your sparse solvers were slower than <code>A\b</code> at least in part due to the interpreter overhead of MATLAB scripts. Internally MATLAB uses UMFPACK's multifrontal solver for <code>LU()</code> function and <code>A\b</code> operator (see <a href="http://faculty.cse.tamu.edu/davis/suitesparse.html" rel="nofollow">UMFPACK manual</a>).</p>
<p>You should try <a href="http://docs.scipy.org/doc/scipy/reference/sparse.html" rel="nofollow"><code>scipy.sparse</code></a> package with <a href="http://docs.scipy.org/doc/scipy/reference/sparse.linalg.html" rel="nofollow"><code>scipy.sparse.linalg</code></a> for the assortment of solvers available. In particular, <code>spsolve()</code> function has an option to call UMFPACK routine instead of the builtin SuperLU solver.</p>
<blockquote>
<p>... solving linear optimization problems in real time at high speed?</p>
</blockquote>
<p>Since you have time constraints you might want to consider iterative solvers instead of direct ones.</p>
<p>You can get an idea of the performance of SuperLU implementation in spsolve and iterative solvers available in SciPy from <a href="http://stackoverflow.com/a/18258362/1328439">another post</a> on this site.</p>
| 0
|
2016-09-05T08:06:01Z
|
[
"python",
"matlab",
"matrix",
"linear-programming"
] |
Selenium can't open Firefox 48.0.1
| 39,323,817
|
<p>I am starting to learn how to become a better test driven developer when creating web applications in Django. I am trying to use Selenium to open a browser, but I am getting an error.</p>
<pre><code>selenium.common.exceptions.WebDriverException: Message: Can't load the profile. Profile Dir: /var/folders/xn/bvyw0fm97j1_flsyggj0xn9r0000gp/T/tmptoxt890d If you specified a log_file in the FirefoxBinary constructor, check it for details.
</code></pre>
<p>I read that by "Installing the FF extension "Disable Add-on Compatibility Checks" skips this and everything is fine." <a href="http://stackoverflow.com/questions/35868135/selenium-common-exceptions-webdriverexception-message-cant-load-the-profile">selenium.common.exceptions.WebDriverException: Message: Can't load the profile</a>. I did this, but It is still not working. I used Python2.7 and Python3.5 with Selenium version 2.53.6. </p>
<p>Python file</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
import unittest
caps = DesiredCapabilities.FIREFOX
caps["marionette"] = True
class NewVisitorTest(unittest.TestCase):
def setUp(self):
self.browser = webdriver.Firefox(capabilities=caps)
def tearDown(self):
self.browser.quit()
def test_can_start_a_list_and_retrieve_it_later(self):
self.browser.get('http://localhost:8000')
self.assertIn('To-Do', self.browser.title)
if __name__ == '__main__':
unittest.main(warnings='ignore')
</code></pre>
<p>Stack Trace</p>
<pre><code>Creating test database for alias 'default'...
EException ignored in: <bound method Service.__del__ of <selenium.webdriver.firefox.service.Service object at 0x103f652b0>>
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/selenium/webdriver/common/service.py", line 151, in __del__
self.stop()
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/selenium/webdriver/common/service.py", line 123, in stop
if self.process is None:
AttributeError: 'Service' object has no attribute 'process'
======================================================================
ERROR: test_can_start_a_list_and_retrieve_it_later (functional_tests.NewVisitorTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/timothybaney/Treehouse/TDD/superlists/functional_tests.py", line 13, in setUp
self.browser = webdriver.Firefox(capabilities=caps)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/selenium/webdriver/firefox/webdriver.py", line 82, in __init__
self.service.start()
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/selenium/webdriver/common/service.py", line 62, in start
stdout=self.log_file, stderr=self.log_file)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/subprocess.py", line 947, in __init__
restore_signals, start_new_session)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/subprocess.py", line 1551, in _execute_child
raise child_exception_type(errno_num, err_msg)
NotADirectoryError: [Errno 20] Not a directory
----------------------------------------------------------------------
Ran 1 test in 0.012s
FAILED (errors=1)
Destroying test database for alias 'default'...
</code></pre>
| 2
|
2016-09-05T04:10:00Z
| 39,324,230
|
<p>That error is because you are using FF 48. For FF>=47 FirefoxDriver stop working. You must use the new <a href="https://developer.mozilla.org/en-US/docs/Mozilla/QA/Marionette/WebDriver" rel="nofollow">MarionetteDriver</a> </p>
<p>Set up this:</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
caps = DesiredCapabilities.FIREFOX
caps["marionette"] = True
browser = webdriver.Firefox(capabilities=caps)
browser.get('http://localhost:8000')
assert 'Django' in browser.title
</code></pre>
| 1
|
2016-09-05T05:06:38Z
|
[
"python",
"selenium",
"firefox"
] |
How to delete files using the syntax '*' with python3?
| 39,323,893
|
<p>There are some files that named like percentxxxx.csv,percentyyyy.csv in the dir.I want to delete the files with the name begins with percent.</p>
<p>I find the <code>os.remove</code> function maybe can help me,bu I don't konw how to solve the problem.</p>
<p>Are there any other functions can delete files using the syntax percent*.csv ?</p>
<p>The following is my method:</p>
<pre><code>system_dir=os.getcwd()
for fname in os.listdir(system_dir):
# print(fname)
if fname.startswith('report'):
os.remove(os.path.join(system_dir, fname))
</code></pre>
<p><strong>I mainly want to know whether there are more easier methed ,for example using * syntax in the method.</strong> </p>
| 0
|
2016-09-05T04:20:34Z
| 39,323,904
|
<p>Use <a href="https://docs.python.org/3.1/library/glob.html#module-glob" rel="nofollow">glob</a>:</p>
<pre><code>import os
import glob
for csv in glob.glob("percent*.csv"):
os.remove(csv)
</code></pre>
| 3
|
2016-09-05T04:22:11Z
|
[
"python",
"python-3.x",
"delete-file"
] |
How to build a dictionary of string lengths using a for loop?
| 39,323,937
|
<p>I am pretty new to python, but I know the basic commands. I am trying to create a for loop which, when given a list of sentences, adds a key for the length of each sentence. The value of each key would be the frequency of that sentence length in the list, so that the format would look something like this:</p>
<pre><code>dictionary = {length1:frequency, length2:frequency, etc.}
</code></pre>
<p>I can't seem to find any previously answered questions that deal with this specifically - creating keys using basic functions, then changing the key's value by the frequency of that result. Here is the code I have:</p>
<pre><code>dictionary = {}
for i in sentences:
dictionary[len(i.split())] += 1
</code></pre>
<p>When I try to run the code, I get this message:</p>
<pre><code>Traceback (most recent call last):
File "<pyshell#11>", line 2, in <module>
dictionary[len(i.split())] += 1
KeyError: 27
</code></pre>
<p>Any help fixing my code and an explanation of where I went wrong would be so appreciated!</p>
| 4
|
2016-09-05T04:26:33Z
| 39,324,021
|
<p>I think this will solve your problem, in Python 3:</p>
<pre><code>sentences ='Hi my name is xyz'
words = sentences.split()
dictionary ={}
for i in words:
if len(i) in dictionary:
dictionary[len(i)]+=1
else:
dictionary[len(i)] = 1
print(dictionary)
</code></pre>
<p>Output:</p>
<pre><code>{2: 3, 3: 1, 4: 1}
</code></pre>
<p>In dictionary, first you have to assign some value to key then only you can use that value for further calculations Or else there is alternative use <code>defaultdict</code> to assign default value to each key.</p>
<p>Hope this helps.</p>
| 2
|
2016-09-05T04:39:04Z
|
[
"python",
"string",
"list",
"dictionary",
"sentence"
] |
Getting error message when trying to break out of a while loop in Python
| 39,324,043
|
<p>I'm trying to write code that includes the following:</p>
<p>1) Uses a conditional test in the while statement to stop the loop.</p>
<p>2) Uses an active variable to control how long the loop runs.</p>
<p>3) Use a break statement to exit the loop when the user enters a 'quit' value.</p>
<p><strong>Here is my code:</strong></p>
<pre><code>prompt = "What is your age?"
prompt += "\nEnter 'quit' to exit: "
while True:
age = input(prompt)
age = int(age)
if age == 'quit':
break
elif age < 3:
print("Your ticket is free.")
elif 3 <= age <=12:
print("Your ticket is $10.")
elif 12 < age:
print("Your ticket is $15.")
else:
print("Please enter a valid age.")
</code></pre>
<p>I believe I've answered part 1 and 2 correctly but whenever I enter 'quit' or any other word to test for part 3, I get an error message that states: "ValueError: invalid literal for int() with base 10: 'quit'"</p>
<p>Does anyone have any suggestions of what I may be doing wrong in my code? Thank you for your time.</p>
| 2
|
2016-09-05T04:41:43Z
| 39,324,070
|
<p>You convert age to an integer with <code>int()</code> so it will never equal <code>'quit'</code>. Do the <code>quit</code> check first, then convert to integer:</p>
<pre><code>age = input(prompt)
if age == 'quit':
break;
age = int(age)
...
</code></pre>
<p>This now checks if it's equal to a string literal <em>first</em>, so that in the case it is, it breaks correctly. If not, then continue on as usual.</p>
| 1
|
2016-09-05T04:45:33Z
|
[
"python"
] |
Getting error message when trying to break out of a while loop in Python
| 39,324,043
|
<p>I'm trying to write code that includes the following:</p>
<p>1) Uses a conditional test in the while statement to stop the loop.</p>
<p>2) Uses an active variable to control how long the loop runs.</p>
<p>3) Use a break statement to exit the loop when the user enters a 'quit' value.</p>
<p><strong>Here is my code:</strong></p>
<pre><code>prompt = "What is your age?"
prompt += "\nEnter 'quit' to exit: "
while True:
age = input(prompt)
age = int(age)
if age == 'quit':
break
elif age < 3:
print("Your ticket is free.")
elif 3 <= age <=12:
print("Your ticket is $10.")
elif 12 < age:
print("Your ticket is $15.")
else:
print("Please enter a valid age.")
</code></pre>
<p>I believe I've answered part 1 and 2 correctly but whenever I enter 'quit' or any other word to test for part 3, I get an error message that states: "ValueError: invalid literal for int() with base 10: 'quit'"</p>
<p>Does anyone have any suggestions of what I may be doing wrong in my code? Thank you for your time.</p>
| 2
|
2016-09-05T04:41:43Z
| 39,324,074
|
<p>You are converting the user's input to a number before checking if that input is actually a number. Go from this:</p>
<pre><code>age = input(prompt)
age = int(age)
if age == 'quit':
break
elif age < 3:
print("Your ticket is free.")
</code></pre>
<p>To this:</p>
<pre><code>age = input(prompt)
if age == 'quit':
break
age = int(age)
if age < 3:
print("Your ticket is free.")
</code></pre>
<p>This will check for a request to exit before assuming that the user entered a number.</p>
| 5
|
2016-09-05T04:46:03Z
|
[
"python"
] |
Getting error message when trying to break out of a while loop in Python
| 39,324,043
|
<p>I'm trying to write code that includes the following:</p>
<p>1) Uses a conditional test in the while statement to stop the loop.</p>
<p>2) Uses an active variable to control how long the loop runs.</p>
<p>3) Use a break statement to exit the loop when the user enters a 'quit' value.</p>
<p><strong>Here is my code:</strong></p>
<pre><code>prompt = "What is your age?"
prompt += "\nEnter 'quit' to exit: "
while True:
age = input(prompt)
age = int(age)
if age == 'quit':
break
elif age < 3:
print("Your ticket is free.")
elif 3 <= age <=12:
print("Your ticket is $10.")
elif 12 < age:
print("Your ticket is $15.")
else:
print("Please enter a valid age.")
</code></pre>
<p>I believe I've answered part 1 and 2 correctly but whenever I enter 'quit' or any other word to test for part 3, I get an error message that states: "ValueError: invalid literal for int() with base 10: 'quit'"</p>
<p>Does anyone have any suggestions of what I may be doing wrong in my code? Thank you for your time.</p>
| 2
|
2016-09-05T04:41:43Z
| 39,324,083
|
<p>You are casting the string "quit" to integer, and python tells you it's wrong.</p>
<p>This will work :</p>
<pre><code>prompt = "What is your age?"
prompt += "\nEnter 'quit' to exit: "
while True:
age = input(prompt)
if age == 'quit':
break
age = int(age)
if age < 3:
print("Your ticket is free.")
elif 3 <= age <=12:
print("Your ticket is $10.")
elif 12 < age:
print("Your ticket is $15.")
else:
print("Please enter a valid age.")
</code></pre>
| 1
|
2016-09-05T04:47:13Z
|
[
"python"
] |
Getting error message when trying to break out of a while loop in Python
| 39,324,043
|
<p>I'm trying to write code that includes the following:</p>
<p>1) Uses a conditional test in the while statement to stop the loop.</p>
<p>2) Uses an active variable to control how long the loop runs.</p>
<p>3) Use a break statement to exit the loop when the user enters a 'quit' value.</p>
<p><strong>Here is my code:</strong></p>
<pre><code>prompt = "What is your age?"
prompt += "\nEnter 'quit' to exit: "
while True:
age = input(prompt)
age = int(age)
if age == 'quit':
break
elif age < 3:
print("Your ticket is free.")
elif 3 <= age <=12:
print("Your ticket is $10.")
elif 12 < age:
print("Your ticket is $15.")
else:
print("Please enter a valid age.")
</code></pre>
<p>I believe I've answered part 1 and 2 correctly but whenever I enter 'quit' or any other word to test for part 3, I get an error message that states: "ValueError: invalid literal for int() with base 10: 'quit'"</p>
<p>Does anyone have any suggestions of what I may be doing wrong in my code? Thank you for your time.</p>
| 2
|
2016-09-05T04:41:43Z
| 39,324,128
|
<p>Just for the sake of showing something different, you can actually make use of a <code>try/except</code> here for catching a <code>ValueError</code> and in your exception block, you can check for <code>quit</code> and <code>break</code> accordingly. Furthermore, you can slightly simplify your input prompt to save a couple of lines. </p>
<p>You can also force the casing of <code>quit</code> to lowercase so that you allow it to be written in any casing and just force it to a single case and check for <code>quit</code> (if someone happens to write QuIt or QUIT it will still work).</p>
<pre><code>while True:
age = input("What is your age?\nEnter 'quit' to exit: ")
try:
age = int(age)
if age < 3:
print("Your ticket is free.")
elif 3 <= age <=12:
print("Your ticket is $10.")
elif 12 < age:
print("Your ticket is $15.")
else:
print("Please enter a valid age.")
except ValueError:
if age.lower() == 'quit':
break
</code></pre>
| 1
|
2016-09-05T04:53:39Z
|
[
"python"
] |
Getting error message when trying to break out of a while loop in Python
| 39,324,043
|
<p>I'm trying to write code that includes the following:</p>
<p>1) Uses a conditional test in the while statement to stop the loop.</p>
<p>2) Uses an active variable to control how long the loop runs.</p>
<p>3) Use a break statement to exit the loop when the user enters a 'quit' value.</p>
<p><strong>Here is my code:</strong></p>
<pre><code>prompt = "What is your age?"
prompt += "\nEnter 'quit' to exit: "
while True:
age = input(prompt)
age = int(age)
if age == 'quit':
break
elif age < 3:
print("Your ticket is free.")
elif 3 <= age <=12:
print("Your ticket is $10.")
elif 12 < age:
print("Your ticket is $15.")
else:
print("Please enter a valid age.")
</code></pre>
<p>I believe I've answered part 1 and 2 correctly but whenever I enter 'quit' or any other word to test for part 3, I get an error message that states: "ValueError: invalid literal for int() with base 10: 'quit'"</p>
<p>Does anyone have any suggestions of what I may be doing wrong in my code? Thank you for your time.</p>
| 2
|
2016-09-05T04:41:43Z
| 39,326,538
|
<p>As proposed in a comment above you should use raw_input() instead of input in order to handle the user input as a string so that you can check for the 'quit' string. If the user input is not equal to 'quit' then you can try to manage the input string as integer numbers. In case the user passes an invalid string (e.g. something like 'hgkjhfdjghd') you can handle it as an exception.</p>
<p>Find below a piece of code that demonstrates what I described above:</p>
<pre><code>prompt = "What is your age?"
prompt += "\nEnter 'quit' to exit: "
while True:
age = raw_input(prompt)
if age == 'quit':
break
try:
age = int(age)
if age < 3:
print("Your ticket is free.")
elif 3 <= age <=12:
print("Your ticket is $10.")
elif 12 < age:
print("Your ticket is $15.")
except Exception as e:
print 'ERROR:', e
print("Please enter a valid age.")
</code></pre>
| 0
|
2016-09-05T08:28:03Z
|
[
"python"
] |
Stream a non-seekable file-like object to multiple sinks
| 39,324,151
|
<p>I have a non-seekable file-like object. In particular it is a file of indeterminate size coming from an HTTP request.</p>
<pre><code>import requests
fileobj = requests.get(url, stream=True)
</code></pre>
<p>I am streaming this file to a call to an Amazon AWS SDK function which is writing the contents to Amazon S3. This is working fine.</p>
<pre><code>import boto3
s3 = boto3.resource('s3')
s3.bucket('my-bucket').upload_fileobj(fileobj, 'target-file-name')
</code></pre>
<p>However, at the same time as streaming it to S3 I want to also stream the data to another process. This other process may not need the entire stream and might stop listening at some point; this is fine and should not affect the stream to S3.</p>
<p>It's important I don't use too much memory, since some of these files could be enormous. I don't want to write anything to disk for the same reason.</p>
<p>I don't mind if either sink is slowed down due to the other being slow, as long as S3 eventually gets the entire file, and the data goes to both sinks (rather, to each one which still wants it).</p>
<p>What's the best way to go about this in Python (3)? I know I can't just pass the same file object to both sinks, such as</p>
<pre><code>s3.bucket('my-bucket').upload_fileobj(fileobj, 'target-file-name')
# At the same time somehow as
process = subprocess.Popen(['myapp'], stdin=fileobj)
</code></pre>
<p>I think I could write a wrapper for the file-like object which passes any data read not only to the caller (which would be the S3 sink) but also to the other process. Something like</p>
<pre><code>class MyFilewrapper(object):
def __init__(self, fileobj):
self._fileobj = fileobj
self._process = subprocess.Popen(['myapp'], stdin=popen.PIPE)
def read(self, size=-1):
data = self._fileobj.read(size)
self._process.stdin.write(data)
return data
filewrapper = MyFilewrapper(fileobj)
s3.bucket('my-bucket').upload_fileobj(filewrapper, 'target-file-name')
</code></pre>
<p>But is there a better way to do it? Perhaps something like</p>
<pre><code>streams = StreamDuplicator(fileobj, streams=2)
s3.bucket('my-bucket').upload_fileobj(streams[0], 'target-file-name')
# At the same time somehow as
process = subprocess.Popen(['myapp'], stdin=streams[1])
</code></pre>
| 4
|
2016-09-05T04:56:42Z
| 39,333,962
|
<p>The discomfort regarding your <code>MyFilewrapper</code> solution arises, because the IO loop inside <code>upload_fileobj</code> is now in control of feeding the data to a subprocess that is strictly speaking unrelated to the upload.</p>
<p>A "proper" solution would involve an upload API that provides a file-like object for <strong>writing</strong> the upload stream with an outside loop. That would allow you to feed the data to both target streams "cleanly".</p>
<p>The following example shows the basic concept. The fictional <code>startupload</code> method provides the file-like object for uploading. Of cource you would need to add proper error handling etc.</p>
<pre><code>fileobj = requests.get(url, stream=True)
upload_fd = s3.bucket('my-bucket').startupload('target-file-name')
other_fd = ... # Popen or whatever
buf = memoryview(bytearray(4046))
while True:
r = fileobj.read_into(buf)
if r == 0:
break
read_slice = buf[:r]
upload_fd.write(read_slice)
other_fd.write(read_slice)
</code></pre>
| 1
|
2016-09-05T15:45:00Z
|
[
"python",
"python-3.x",
"stream"
] |
Stream a non-seekable file-like object to multiple sinks
| 39,324,151
|
<p>I have a non-seekable file-like object. In particular it is a file of indeterminate size coming from an HTTP request.</p>
<pre><code>import requests
fileobj = requests.get(url, stream=True)
</code></pre>
<p>I am streaming this file to a call to an Amazon AWS SDK function which is writing the contents to Amazon S3. This is working fine.</p>
<pre><code>import boto3
s3 = boto3.resource('s3')
s3.bucket('my-bucket').upload_fileobj(fileobj, 'target-file-name')
</code></pre>
<p>However, at the same time as streaming it to S3 I want to also stream the data to another process. This other process may not need the entire stream and might stop listening at some point; this is fine and should not affect the stream to S3.</p>
<p>It's important I don't use too much memory, since some of these files could be enormous. I don't want to write anything to disk for the same reason.</p>
<p>I don't mind if either sink is slowed down due to the other being slow, as long as S3 eventually gets the entire file, and the data goes to both sinks (rather, to each one which still wants it).</p>
<p>What's the best way to go about this in Python (3)? I know I can't just pass the same file object to both sinks, such as</p>
<pre><code>s3.bucket('my-bucket').upload_fileobj(fileobj, 'target-file-name')
# At the same time somehow as
process = subprocess.Popen(['myapp'], stdin=fileobj)
</code></pre>
<p>I think I could write a wrapper for the file-like object which passes any data read not only to the caller (which would be the S3 sink) but also to the other process. Something like</p>
<pre><code>class MyFilewrapper(object):
def __init__(self, fileobj):
self._fileobj = fileobj
self._process = subprocess.Popen(['myapp'], stdin=popen.PIPE)
def read(self, size=-1):
data = self._fileobj.read(size)
self._process.stdin.write(data)
return data
filewrapper = MyFilewrapper(fileobj)
s3.bucket('my-bucket').upload_fileobj(filewrapper, 'target-file-name')
</code></pre>
<p>But is there a better way to do it? Perhaps something like</p>
<pre><code>streams = StreamDuplicator(fileobj, streams=2)
s3.bucket('my-bucket').upload_fileobj(streams[0], 'target-file-name')
# At the same time somehow as
process = subprocess.Popen(['myapp'], stdin=streams[1])
</code></pre>
| 4
|
2016-09-05T04:56:42Z
| 39,334,595
|
<p>Here is an implementation of <code>StreamDuplicator</code> with requested functionality and use model. I verified that it handles correctly the case when one of the sinks stops consuming the respective stream half-way.</p>
<p><strong>Usage</strong>:</p>
<pre><code>./streamduplicator.py <sink1_command> <sink2_command> ...
</code></pre>
<p><strong>Example</strong>:</p>
<pre><code>$ seq 100000 | ./streamduplicator.py "sed -n '/0000/ {s/^/sed: /;p}'" "grep 1234"
</code></pre>
<p><strong>Output</strong>:</p>
<pre><code>sed: 10000
1234
11234
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
21234
sed: 20000
31234
sed: 30000
41234
sed: 40000
51234
sed: 50000
61234
sed: 60000
71234
sed: 70000
81234
sed: 80000
91234
sed: 90000
sed: 100000
</code></pre>
<p><strong>streamduplicator.py</strong>:</p>
<pre><code>#!/usr/bin/env python3
import sys
import os
from subprocess import Popen
from threading import Thread
from time import sleep
import shlex
import fcntl
WRITE_TIMEOUT=0.1
def write_or_timeout(stream, data, timeout):
data_to_write = data[:]
time_to_sleep = 1e-6
time_remaining = 1.0 * timeout
while time_to_sleep != 0:
try:
stream.write(data_to_write)
return True
except BlockingIOError as ex:
data_to_write = data_to_write[ex.characters_written:]
if ex.characters_written == 0:
time_to_sleep *= 2
else:
time_to_sleep = 1e-6
time_remaining = timeout
time_to_sleep = min(time_remaining, time_to_sleep)
sleep(time_to_sleep)
time_remaining -= time_to_sleep
return False
class StreamDuplicator(object):
def __init__(self, stream, n, timeout=WRITE_TIMEOUT):
self.stream = stream
self.write_timeout = timeout
self.pipereadstreams = []
self.pipewritestreams = []
for i in range(n):
(r, w) = os.pipe()
readStream = open(r, 'rb')
self.pipereadstreams.append(readStream)
old_flags = fcntl.fcntl(w, fcntl.F_GETFL);
fcntl.fcntl(w, fcntl.F_SETFL, old_flags|os.O_NONBLOCK)
self.pipewritestreams.append(os.fdopen(w, 'wb'))
Thread(target=self).start()
def __call__(self):
while True:
data = self.stream.read(1024*16)
if len(data) == 0:
break
surviving_pipes = []
for p in self.pipewritestreams:
if write_or_timeout(p, data, self.write_timeout) == True:
surviving_pipes.append(p)
self.pipewritestreams = surviving_pipes
def __getitem__(self, i):
return self.pipereadstreams[i]
if __name__ == '__main__':
n = len(sys.argv)
streams = StreamDuplicator(sys.stdin.buffer, n-1, 3)
for (i,cmd) in zip(range(n-1), sys.argv[1:]):
Popen(shlex.split(cmd), stdin=streams[i])
</code></pre>
<p>Implementation limitations:</p>
<ul>
<li><p>usage of <code>fcntl</code> to set a pipe writing file descriptor to non-blocking mode probably makes it unusable under Windows.</p></li>
<li><p>a closed/unsubscribed sink is detected through a write timeout.</p></li>
</ul>
| 1
|
2016-09-05T16:31:17Z
|
[
"python",
"python-3.x",
"stream"
] |
How do I build a cx_oracle app using pyinstaller to use multiple Oracle client versions?
| 39,324,217
|
<p>I am building an application in Python using cx_Oracle (v5) and Pyinstaller to package up and distribute the application. When I built and packaged the application, I had the Oracle 12c client installed. However, when I deployed it to a machine with the 11g client installed, it seems not to work. I get the message "Unable to acquire Oracle environment handle". I assume this is as the result of the application being packaged with Pyinstaller while my ORACLE_HOME was pointed to a 12c client. I know that the cx_Oracle I have was built against both 11g and 12 libraries. So, I'm wondering how I deploy an application using Pyinstaller so it can run with either 11 or 12c client libraries installed?</p>
<p>By the way, I am building this on Linux (debian/Mint 17.2), and deploying to Linux (CentOS 7).</p>
| 0
|
2016-09-05T05:04:42Z
| 39,349,805
|
<p>The error "Unable to acquire Oracle environment handle" means there is something wrong with your Oracle configuration. Check to see what libclntsh.so file you are using. The simplest way to do that is by using the ldd command on the cx_Oracle module that PyInstaller has bundled with the executable. Then check to see if there is a conflict due to setting the environment variable ORACLE_HOME to a different client!</p>
<p>If PyInstaller picked up the libclntsh.so file during its packaging you will need to tell it to stop doing that. There must be an Oracle client (either full client or the much simpler instant client) on the target machine, not just the one file (libclntsh.so).</p>
<p>You can also verify that your configuration is ok by using the cx_Oracle.so module on the target machine to establish a connection -- independently of your application. If that doesn't work or you don't have a Python installation there for some reason, you can also use SQL*Plus to verify that your configuration is ok as well.</p>
| 1
|
2016-09-06T13:07:33Z
|
[
"python",
"oracle",
"pyinstaller",
"cx-oracle"
] |
Fast hash for 2 coordinates where order doesn't matter?
| 39,324,220
|
<p>Is there a formula that is a one way hash for 2 coordinates (a, b) and (c, d) to one integer where a, b, c, and d are positive? Order <strong>doesn't</strong> matter here, so the formula should give the same results when given <code>(a, b), (c, d)</code> and <code>(c, d), (a, b)</code>. The order of the actual numbers in each coordinate point matter (<code>(a, b)</code> is not the same as <code>(b, a)</code>). Speed is the key here, the formula should be fast and have O(1) complexity. </p>
<p>Note - what I'm doing right now is sorting the two coordinates using Python's building in sort, and then using them as keys in Python's built-in dictionary (so, built-in hashing). I need a faster way of doing this so that I can hash the two coordinates to an integer myself.</p>
| 3
|
2016-09-05T05:04:59Z
| 39,325,840
|
<p>You can use the <a href="https://docs.python.org/3/library/functions.html#hash" rel="nofollow">hash()</a> of a <a href="https://docs.python.org/3/library/functions.html#func-frozenset" rel="nofollow">frozenset</a> for this.</p>
<pre><code>>>> hash(frozenset([(10, 20), (11, 22)]))
1735850283064117985
>>> hash(frozenset([(11, 22), (10, 20)]))
1735850283064117985
</code></pre>
<p>Frozensets were specifically designed for this kind of use case (i.e. frozensets are intrinsically unordered collections that are immutable and hashable).</p>
<p>Hope this answer takes your right to what you needed :-)</p>
| 1
|
2016-09-05T07:40:38Z
|
[
"python",
"hash",
"hashmap",
"key",
"hashcode"
] |
Python scipy / Fortran : float64, real, double?
| 39,324,311
|
<p>I am writing a front-end in Python for a Fortran library. The Python modules are supposed to work on both 32-bit and 64-bit machines; for windows, linux and mac. </p>
<p>I would like to get some clarity on the byte widths of some of the data types:</p>
<p>[1] Say a variable in the Fortran function is declared as "real". Is this always 8-byte wide for both 32-bit and 64-bit machines? </p>
<p>[2] What is the difference between scipy.float64 and scipy.double? Are they identical for all machines?</p>
<p>Reliable answers from experts on this topic would help very much. </p>
| 1
|
2016-09-05T05:17:42Z
| 39,324,882
|
<pre><code>In [241]: np.double
Out[241]: numpy.float64
In [246]: x=np.float64(34)
In [247]: x
Out[247]: 34.0
In [248]: x.nbytes
Out[248]: 8
</code></pre>
<p><a href="http://docs.scipy.org/doc/numpy/reference/c-api.config.html" rel="nofollow">http://docs.scipy.org/doc/numpy/reference/c-api.config.html</a>
Docs for system configuration constants</p>
<p><a href="http://docs.scipy.org/doc/numpy/user/misc.html#interfacing-to-fortran" rel="nofollow">http://docs.scipy.org/doc/numpy/user/misc.html#interfacing-to-fortran</a></p>
<p><a href="http://docs.scipy.org/doc/numpy-dev/f2py/" rel="nofollow">http://docs.scipy.org/doc/numpy-dev/f2py/</a></p>
| 1
|
2016-09-05T06:24:15Z
|
[
"python",
"numpy",
"scipy",
"data-type-conversion"
] |
Accept YAML input from website user
| 39,324,356
|
<p>I haven't written this in the code yet but I want to parse YAML from my website users. The YAML should just be string key/values and lists of strings.</p>
<p>They input YAML into a textbox, send it to the server, then the python will parse the YAML, put it in the database and it will later be queryable.</p>
<p>Is there anything I need to do to be able to safely do the above?</p>
| 2
|
2016-09-05T05:24:05Z
| 39,324,450
|
<p>The main thing to observe is to parse the yaml with either <code>safe_load</code> ( <a href="https://pypi.python.org/pypi/ruamel.yaml/" rel="nofollow">ruamel.yaml</a> (supporting YAML 1.2), <a href="http://pyyaml.org/" rel="nofollow">PyYAML</a> (YAML 1.1)) or <code>round_trip_load</code> (ruamel.yaml, this will allow you to extract comments in the YAML file if necessary). </p>
<p>The normal <code>load</code> could be used to execute programs by the Python interpreter, unless you pre-process the YAML to remove any tags.</p>
<hr>
<p><sub>Disclaimer: I am the author of ruamel.yaml</sub></p>
| 2
|
2016-09-05T05:35:49Z
|
[
"python",
"security",
"yaml"
] |
Best way to create Django instances while manipulating/hiding fields from caller?
| 39,324,472
|
<p>Suppose I have the following Django class:</p>
<pre><code>from django.db import models
class Person(models.Model):
name = models.CharField(max_length=254)
year_of_birth = models.IntegerField()
</code></pre>
<p>I can create an instance of the model by doing the following:</p>
<pre><code>p = Person.object.create(name="Mahmoud", year_of_birth=1985)
</code></pre>
<p>However, I don't want the calling function outside the <code>Person</code> class to know the internal details of the class. And I also don't want them to have to calculate their year of birth. I just want them to enter their age (21), and I want to write a method that takes care of the rest for them automatically. </p>
<p>This is a common need I have throughout my Django application. Is there a preferred pattern to solve this problem? Currently, I'm doing it by creating the following static method in the <code>Person</code> class:</p>
<pre><code>import datetime
@staticmethod
def create(name, age):
return Person.objects.create(name=name, year_of_birth=datetime.datetime.now().year-age)
</code></pre>
<p>And then I call it like this: <code>p = Person.create(name="Mahmoud", age=21)</code></p>
<p>But I'm not sure this is the best way to go. Is this the proper/pythonic way to handle this situation?</p>
| 0
|
2016-09-05T05:37:39Z
| 39,325,495
|
<p>Maybe you can add a Person manager to your Person model class like this:</p>
<pre><code>objects = PersonManager()
</code></pre>
<p>Then define a method inside PersonManager() that creates a person:</p>
<pre><code>class PersonManager(models.Manager):
def create_person(name, age):
return self.create(name=name, year_of_birth=datetime.datetime.now().year-age)
</code></pre>
<p>And you'd use it like this:</p>
<pre><code>person = Person.objects.create_person("Dude", 23)
</code></pre>
| 1
|
2016-09-05T07:14:35Z
|
[
"python",
"django",
"django-models"
] |
Understanding Tensorflow LSTM Input shape
| 39,324,520
|
<p>I have a dataset X which consists <strong>N = 4000 samples</strong>, each sample consists of <strong>d = 2 features</strong> (continuous values) spanning back <strong>t = 10 time steps</strong>. I also have the corresponding 'labels' of each sample which are also continuous values, at time step 11. </p>
<p>At the moment my dataset is in the shape X: [4000,20], Y: [4000].</p>
<p>I want to train an LSTM using TensorFlow to predict the value of Y (regression), given the 10 previous inputs of d features, but I am having a tough time implementing this in TensorFlow.</p>
<p>The main problem I have at the moment is understanding how TensorFlow is expecting the input to be formatted. I have seen various examples such as <a href="http://mourafiq.com/2016/05/15/predicting-sequences-using-rnn-in-tensorflow.html" rel="nofollow">this</a>, but these examples deal with one big string of continuous time series data. My data is different samples, each an independent time series.</p>
<p>Thank you.</p>
| 3
|
2016-09-05T05:43:29Z
| 39,325,925
|
<p>The <a href="https://www.tensorflow.org/versions/r0.10/api_docs/python/nn.html#dynamic_rnn" rel="nofollow">documentation of <code>tf.nn.dynamic_rnn</code></a> states:</p>
<blockquote>
<p><code>inputs</code>: The RNN inputs. If <code>time_major == False</code> (default), this must be a Tensor of shape: <code>[batch_size, max_time, ...]</code>, or a nested tuple of such elements.</p>
</blockquote>
<p>In your case, this means that the input should have a shape of <code>[batch_size, 10, 2]</code>. Instead of training on all 4000 sequences at once, you'd use only <code>batch_size</code> many of them in each training iteration. Something like the following should work (added reshape for clarity):</p>
<pre><code>batch_size = 32
# batch_size sequences of length 10 with 2 values for each timestep
input = get_batch(X, batch_size).reshape([batch_size, 10, 2])
# Create LSTM cell with state size 256. Could also use GRUCell, ...
# Note: state_is_tuple=False is deprecated;
# the option might be completely removed in the future
cell = tf.nn.rnn_cell.LSTMCell(256, state_is_tuple=True)
outputs, state = tf.nn.dynamic_rnn(cell,
input,
sequence_length=[10]*batch_size,
dtype=tf.float32)
</code></pre>
<p>From the <a href="https://www.tensorflow.org/versions/r0.10/api_docs/python/nn.html#dynamic_rnn" rel="nofollow">documentation</a>, <code>outputs</code> will be of shape <code>[batch_size, 10, 256]</code>, i.e. one 256-output for each timestep. <code>state</code> will be a <a href="https://github.com/tensorflow/tensorflow/blob/r0.10/tensorflow/python/ops/rnn_cell.py#L238" rel="nofollow">tuple</a> of shapes <code>[batch_size, 256]</code>. You could predict your final value, one for each sequence, from that:</p>
<pre><code>predictions = tf.contrib.layers.fully_connected(state.h,
num_outputs=1,
activation_fn=None)
loss = get_loss(get_batch(Y).reshape([batch_size, 1]), predictions)
</code></pre>
<p>The number 256 in the shapes of <code>outputs</code> and <code>state</code> is determined by <code>cell.output_size</code> resp. <code>cell.state_size</code>. When creating the <code>LSTMCell</code> like above, these are the same. Also see the <a href="https://www.tensorflow.org/versions/r0.10/api_docs/python/rnn_cell.html#LSTMCell" rel="nofollow">LSTMCell documentation</a>.</p>
| 0
|
2016-09-05T07:46:02Z
|
[
"python",
"tensorflow",
"regression",
"lstm"
] |
Why am I getting the error: "Error: Render_to_response not defined"; Django
| 39,324,619
|
<p>I'm learning Django, and I found a very basic example online on how to display tables using templates. I followed the code exactly, but for some reason I get the error:</p>
<pre><code>Error: Render_to_response not defined
</code></pre>
<p>Here is my views.py:</p>
<pre><code>from django.shortcuts import render
def display(request):
return render_to_response('template.tmpl', {'obj':models.Book.objects.all()})
</code></pre>
<p>Here is my urls.py:</p>
<pre><code>from django.conf.urls import url
from . import views
urlpatterns = [
# /table/
url(r'^$', views.display, name='display'),
]
</code></pre>
<p>Here is my template.tmpl:</p>
<pre><code><table>
<tr>
<th>author</th>
<th>title</th>
<th>publication year</th>
</tr>
{% for b in obj %}
<tr>
<td>{{ b.author }}</td>
<td>{{ b.title }}</td>
<td>{{ b.publication_year }}</td>
</tr>
{% endfor %}
</table>
</code></pre>
<p>Here is my models.py:</p>
<pre><code>from django.db import models
class Book(models.Model):
author = models.CharField(max_length = 20)
title = models.CharField(max_length = 40)
publication_year = models.IntegerField()
</code></pre>
<p>I've looked online for some help with this error, but all the problems seem to be much more complicated than the one I'm facing. Is there something I'm missing?</p>
| 3
|
2016-09-05T05:54:39Z
| 39,324,692
|
<p>You are importing <code>render</code> but using <code>render_to_response</code></p>
<p>Replace <code>render_to_response</code></p>
<pre><code>from django.shortcuts import render
def display(request):
return render(request, 'template.tmpl', {'obj':models.Book.objects.all()})
</code></pre>
| 4
|
2016-09-05T06:03:25Z
|
[
"python",
"django"
] |
get Font Size in Python with Tesseract and Pyocr
| 39,324,626
|
<p>Is it possible to get font size from an image using <code>pyocr</code> or <code>Tesseract</code>?
Below is my code.</p>
<pre><code>tools = pyocr.get_available_tools()
tool = tools[0]
txt = tool.image_to_string(
Imagee.open(io.BytesIO(req_image)),
lang=lang,
builder=pyocr.builders.TextBuilder()
)
</code></pre>
<p>Here i get text from image using function <code>image_to_string</code> . And now, my question is, if i can get <code>font-size</code>(number) too of my text.</p>
| 0
|
2016-09-05T05:55:11Z
| 39,400,521
|
<p>Using <a href="https://github.com/sirfz/tesserocr" rel="nofollow">tesserocr</a>, you can get a <code>ResultIterator</code> after calling <code>Recognize</code> on your image, for which you can call the <code>WordFontAttributes</code> method to get the information you need. Read the method's documentation for more info.</p>
<pre><code>import io
import tesserocr
from PIL import Image
with tesserocr.PyTessBaseAPI() as api:
image = Image.open(io.BytesIO(req_image))
api.SetImage(image)
api.Recognize() # required to get result from the next line
iterator = api.GetIterator()
print iterator.WordFontAttributes()
</code></pre>
<p>Example output:</p>
<pre><code>{'bold': False,
'font_id': 283,
'font_name': u'Times_New_Roman',
'italic': False,
'monospace': False,
'pointsize': 9,
'serif': True,
'smallcaps': False,
'underlined': False}
</code></pre>
| 0
|
2016-09-08T21:30:55Z
|
[
"python",
"tesseract",
"font-size",
"python-tesseract"
] |
Rename response fields django rest framework serializer
| 39,324,691
|
<p>I'm calling a simple get API using djangorestframework. My Model is </p>
<pre><code>class Category(models.Model):
category_id = models.AutoField(primary_key=True)
category_name = models.CharField("Category Name", max_length = 30)
category_created_date = models.DateField(auto_now = True, auto_now_add=False)
category_updated_date = models.DateField(auto_now = True, auto_now_add=False)
def __str__(self):
return self.category_name
</code></pre>
<p>serializer.py</p>
<pre><code>class CategorySerializer(serializers.ModelSerializer) :
class Meta:
model = Category
fields = ['category_id', 'category_name']
def category_list(request):
if request.method == 'GET':
categories = Category.objects.all()
serializer = CategorySerializer(categories, many=True)
return Response(serializer.data)
</code></pre>
<p>It's working fine when i hit request on the URL and returning following response.</p>
<pre><code>[
{
"category_id": 1,
"category_name": "ABC"
}
]
</code></pre>
<p>i want to change the response field names as it's for my DB only and don't want to disclose in response. If i change the name in serializer class than it's giving no field match error.</p>
<p>Also i want to customise other params like above response in response object with message and status like below.</p>
<pre><code>{
status : 200,
message : "Category List",
response : [
{
"id": 1,
"name": "ABC"
}
]
}
</code></pre>
<p>Need a proper guide and flow. Experts help.</p>
| 2
|
2016-09-05T06:03:18Z
| 39,324,779
|
<p>You can override to_representation function in serializer.Check the following code you can update <code>data</code> dictionary as you want.</p>
<pre><code>class CategorySerializer(serializers.ModelSerializer) :
class Meta:
model = Category
fields = ['category_id', 'category_name']
def to_representation(self, instance):
data = super(CategorySerializer, self).to_representation(instance)
result_data={"status" : 200,"message" : "Category List"}
result_data["response"]=data
return result_data
</code></pre>
| 0
|
2016-09-05T06:13:05Z
|
[
"python",
"django",
"django-rest-framework",
"jsonserializer"
] |
Rename response fields django rest framework serializer
| 39,324,691
|
<p>I'm calling a simple get API using djangorestframework. My Model is </p>
<pre><code>class Category(models.Model):
category_id = models.AutoField(primary_key=True)
category_name = models.CharField("Category Name", max_length = 30)
category_created_date = models.DateField(auto_now = True, auto_now_add=False)
category_updated_date = models.DateField(auto_now = True, auto_now_add=False)
def __str__(self):
return self.category_name
</code></pre>
<p>serializer.py</p>
<pre><code>class CategorySerializer(serializers.ModelSerializer) :
class Meta:
model = Category
fields = ['category_id', 'category_name']
def category_list(request):
if request.method == 'GET':
categories = Category.objects.all()
serializer = CategorySerializer(categories, many=True)
return Response(serializer.data)
</code></pre>
<p>It's working fine when i hit request on the URL and returning following response.</p>
<pre><code>[
{
"category_id": 1,
"category_name": "ABC"
}
]
</code></pre>
<p>i want to change the response field names as it's for my DB only and don't want to disclose in response. If i change the name in serializer class than it's giving no field match error.</p>
<p>Also i want to customise other params like above response in response object with message and status like below.</p>
<pre><code>{
status : 200,
message : "Category List",
response : [
{
"id": 1,
"name": "ABC"
}
]
}
</code></pre>
<p>Need a proper guide and flow. Experts help.</p>
| 2
|
2016-09-05T06:03:18Z
| 39,324,788
|
<p>You can just wrap it up in <code>json</code>. This is the way you render the way you want:</p>
<pre><code>from django.http import HttpResponse
import json
def category_list(request):
if request.method == 'GET':
categories = Category.objects.all()
serializer = CategorySerializer(categories, many=True)
response = {'code: 200, 'message': 'Category List', 'response': serializer.data}
return HttpResponse(json.dumps(response), mimetype='application/json')
</code></pre>
<p>This is the way you can rename your fields:</p>
<pre><code>class CategorySerializer(serializers.ModelSerializer):
name = serializers.CharField(source='category_name')
class Meta:
model = Category
fields = ['category_id', 'name']
</code></pre>
<p>This is the <a href="http://www.django-rest-framework.org/api-guide/serializers/#specifying-fields-explicitly" rel="nofollow">docs</a> for serializing with different names.</p>
| 1
|
2016-09-05T06:13:50Z
|
[
"python",
"django",
"django-rest-framework",
"jsonserializer"
] |
Rename response fields django rest framework serializer
| 39,324,691
|
<p>I'm calling a simple get API using djangorestframework. My Model is </p>
<pre><code>class Category(models.Model):
category_id = models.AutoField(primary_key=True)
category_name = models.CharField("Category Name", max_length = 30)
category_created_date = models.DateField(auto_now = True, auto_now_add=False)
category_updated_date = models.DateField(auto_now = True, auto_now_add=False)
def __str__(self):
return self.category_name
</code></pre>
<p>serializer.py</p>
<pre><code>class CategorySerializer(serializers.ModelSerializer) :
class Meta:
model = Category
fields = ['category_id', 'category_name']
def category_list(request):
if request.method == 'GET':
categories = Category.objects.all()
serializer = CategorySerializer(categories, many=True)
return Response(serializer.data)
</code></pre>
<p>It's working fine when i hit request on the URL and returning following response.</p>
<pre><code>[
{
"category_id": 1,
"category_name": "ABC"
}
]
</code></pre>
<p>i want to change the response field names as it's for my DB only and don't want to disclose in response. If i change the name in serializer class than it's giving no field match error.</p>
<p>Also i want to customise other params like above response in response object with message and status like below.</p>
<pre><code>{
status : 200,
message : "Category List",
response : [
{
"id": 1,
"name": "ABC"
}
]
}
</code></pre>
<p>Need a proper guide and flow. Experts help.</p>
| 2
|
2016-09-05T06:03:18Z
| 39,325,147
|
<p><strong>First</strong> of all using <code>category_</code> in field names is redundant. Because you are already assigning this fields to <code>Category</code> model, and by doing this you are creating "namespace" for this fields.</p>
<pre><code>class Category(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField("Category Name", max_length = 30)
created_date = models.DateField(auto_now = True, auto_now_add=False)
updated_date = models.DateField(auto_now = True, auto_now_add=False)
def __str__(self):
return self.name
</code></pre>
<p><strong>Second</strong> In django <code>id</code> AutoField is created automatically why would you need set it explicitly?</p>
<p><strong>And answering your question</strong> There is <a href="http://www.django-rest-framework.org/api-guide/fields/#source" rel="nofollow"><code>source</code></a> parameter in serializer fields.</p>
<pre><code>class CategorySerializer(serializers.ModelSerializer):
renamed_id = serializers.IntegerField(source='category_id')
renamed_name = serializers.CharField(source='category_name')
class Meta:
model = Category
fields = ['renamed_id', 'renamed_name']
</code></pre>
<p>And than you can change your response manually</p>
<pre><code>from rest_framework import status
def category_list(request):
if request.method == 'GET':
categories = Category.objects.all()
serializer = CategorySerializer(categories, many=True)
response = {
'status': status.HTTP_200_OK,
'message' : "Category List",
'response' : serializer.data
}
return Response(response)
</code></pre>
| 4
|
2016-09-05T06:46:17Z
|
[
"python",
"django",
"django-rest-framework",
"jsonserializer"
] |
How to run python production on customer environment
| 39,324,787
|
<p>I have some python application that should run on customer site. I compile my <code>py</code> files to <code>pyc</code> (python byte code).</p>
<p>What is the standard way to run the app on the customer environment? The options I see are:</p>
<ul>
<li>As part of my installer, install some python distribution, i.e Anaconda.</li>
<li>Require the customer to have python installed in their environment.</li>
<li>Bring python libraries and executable along with my code and run it directly from my installation dir.</li>
<li>Convert the scripts to exe using some py-to-exe tool.</li>
</ul>
<p>Application usage: The app is used as a tool to calculate statistics for my main product. The customer won't run it explicitly. It won't have any GUI.</p>
<p>Customer environment will be x64 Windows machine. No other restrictions.</p>
<p>Any recommendations or comments? I couldn't find such discussions on the web.</p>
| 9
|
2016-09-05T06:13:36Z
| 39,352,901
|
<p>Given your requirements, the last two options seem most viable:</p>
<blockquote>
<ul>
<li>Bring python libraries and executable along with my code and run it directly from my installation dir.</li>
<li>Convert the scripts to exe using some py-to-exe tool.</li>
</ul>
</blockquote>
<p>You can either <a href="http://docs.python-guide.org/en/latest/shipping/packaging/" rel="nofollow">package</a> your code, or <a href="http://docs.python-guide.org/en/latest/shipping/freezing/#freezing-your-code-ref" rel="nofollow">freeze</a> your code and create an executable for the target OS.</p>
<p>Given your requirements, I'd suggest the latter. You can go through the <a href="https://packaging.python.org" rel="nofollow">Python Packaging Guide</a> for more details regarding packaging.</p>
| 2
|
2016-09-06T15:38:14Z
|
[
"python",
"python-3.x",
"production",
"pyc",
"python-install"
] |
Error importing modules in thumbor
| 39,324,822
|
<p>I have installed thumbor using pip on windows when I try to run the thumbor server I get an error like:</p>
<pre><code>2016-09-05 11:45:10 thumbor:WARNING Module thumbor.filters.brightness could not
be imported.
2016-09-05 11:45:10 thumbor:WARNING Module thumbor.filters.colorize could not be
imported.
2016-09-05 11:45:10 thumbor:WARNING Module thumbor.filters.contrast could not be
imported.
2016-09-05 11:45:10 thumbor:WARNING Module thumbor.filters.rgb could not be impo
rted.
2016-09-05 11:45:10 thumbor:WARNING Module thumbor.filters.round_corner could no
t be imported.
2016-09-05 11:45:10 thumbor:WARNING Module thumbor.filters.noise could not be im
ported.
2016-09-05 11:45:10 thumbor:WARNING Module thumbor.filters.watermark could not b
e imported.
2016-09-05 11:45:10 thumbor:WARNING Module thumbor.filters.equalize could not be
imported.
2016-09-05 11:45:10 thumbor:WARNING Module thumbor.filters.fill could not be imp
orted.
2016-09-05 11:45:10 thumbor:WARNING Module thumbor.filters.sharpen could not be
imported.
2016-09-05 11:45:10 thumbor:WARNING Module thumbor.filters.frame could not be im
ported.
2016-09-05 11:45:10 thumbor:WARNING Module thumbor.filters.convolution could not
be imported.
2016-09-05 11:45:10 thumbor:WARNING Module thumbor.filters.blur could not be imp
orted.
2016-09-05 11:45:10 thumbor:WARNING Module thumbor.filters.saturation could not
be imported.
2016-09-05 11:45:10 thumbor:WARNING Module thumbor.filters.curve could not be im
ported.
2016-09-05 11:45:10 thumbor:WARNING Error importing bounding_box filter, trimmin
g won't work
</code></pre>
<p>I need immediate help on the matter.
I will be exteremely thankful for the solutions</p>
| 0
|
2016-09-05T06:17:33Z
| 39,325,411
|
<p>Seems this issue has already been reported on github <a href="https://github.com/thumbor/thumbor/issues/256" rel="nofollow">issue-256</a>. Try referring to that.</p>
| 0
|
2016-09-05T07:08:19Z
|
[
"python",
"thumbor"
] |
Tensorflow - Using batching to make predictions
| 39,324,856
|
<p>I'm attempting to make predictions using a trained convolutional neural network, slightly modified from the example in the example expert tensorflow tutorial. I have followed the instructions at <a href="https://www.tensorflow.org/versions/master/how_tos/reading_data/index.html" rel="nofollow">https://www.tensorflow.org/versions/master/how_tos/reading_data/index.html</a> to read data from a CSV file. </p>
<p>I have trained the model and evaluated its accuracy. I then saved the model and loaded it into a new python script for making predictions. Can I still use the batching method detailed in the link above or should I use <code>feed_dict</code> instead? Most tutorials I've seen online use the latter. </p>
<p>My code is shown below, I have essentially duplicated the code for reading from my training data, which was stored as lines within a single .csv file. Conv_nn is simply a class that contains the convolutional neural network detailed in the expert MNIST tutorial. Most of the content is probably not very useful except for the part where I run the graph. </p>
<p><strong>I suspect I have badly mixed up training and prediction - I'm not sure if the test images are being fed to the prediction operation correctly or if it is valid to use the same batch operations for both datasets.</strong> </p>
<pre><code>filename_queue = tf.train.string_input_producer(["data/test.csv"],num_epochs=None)
reader = tf.TextLineReader()
key, value = reader.read(filename_queue)
# Defaults force key value and label to int, all others to float.
record_defaults = [[1]]+[[46]]+[[1.0] for i in range(436)]
# Reads in a single row from the CSV and outputs a list of scalars.
csv_list = tf.decode_csv(value, record_defaults=record_defaults)
# Packs the different columns into separate feature tensors.
location = tf.pack(csv_list[2:4])
bbox = tf.pack(csv_list[5:8])
pix_feats = tf.pack(csv_list[9:])
onehot = tf.one_hot(csv_list[1], depth=98)
keep_prob = 0.5
# Creates batches of images and labels.
image_batch, label_batch = tf.train.shuffle_batch(
[pix_feats, onehot],
batch_size=50,num_threads=4,capacity=50000,min_after_dequeue=10000)
# Creates a graph of variables and operation nodes.
nn = Conv_nn(x=image_batch,keep_prob=keep_prob,pixels=33*13,outputs=98)
# Launch the default graph.
with tf.Session() as sess:
sess.run(tf.initialize_all_variables())
saver.restore(sess, 'model1.ckpt')
print("Model restored.")
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(sess=sess,coord=coord)
prediction=tf.argmax(nn.y_conv,1)
pred = sess.run([prediction])
coord.request_stop()
coord.join(threads)
</code></pre>
| 0
|
2016-09-05T06:21:40Z
| 39,359,162
|
<p>Does using tensorflow serving to make predictions work for you?</p>
| 0
|
2016-09-06T23:23:56Z
|
[
"python",
"machine-learning",
"tensorflow"
] |
Python Requests - Dynamically Pass HTTP Verb
| 39,324,970
|
<p>Is there a way to pass an HTTP verb (PATCH/POST) to a function and dynamically use that verb for Python requests?</p>
<p>For example, I want this function to take a 'verb' variable which is only called internally and will either = post/patch.</p>
<pre><code>def dnsChange(self, zID, verb):
for record in config.NEW_DNS:
### LINE BELOW IS ALL THAT MATTERS TO THIS QUESTION
json = requests.verb(headers=self.auth, url=self.API + '/zones/' + str(zID) + '/dns_records', data={"type":record[0], "name":record[1], "content":record[2]})
key = record[0] + "record with host " + record[1]
result = json.loads(json.text)
self.apiSuccess(result,key,value)
</code></pre>
<p>I realize I cannot requests.'verb' as I have above, it's meant to illustrate the question. Is there a way to do this or something similar? I'd like to avoid an:</p>
<pre><code>if verb == 'post':
json = requests.post(headers=self.auth, url=self.API + '/zones/' + str(zID) + '/dns_records', data={"type":record[0], "name":record[1], "content":record[2]}
else:
json = requests.patch(headers=self.auth, url=self.API + '/zones/' + str(zID) + '/dns_records', data={"type":record[0], "name":record[1], "content":record[2]}
</code></pre>
<p>Thanks guys!</p>
| 1
|
2016-09-05T06:32:07Z
| 39,325,096
|
<p>You can always rely on <code>getattr</code> with a default value. Maybe like</p>
<pre><code>action = getattr(requests, verb, None)
if action:
action(headers=self.auth, url=self.API + '/zones/' + str(zID) + '/dns_records', data={"type":record[0], "name":record[1], "content":record[2]})
else:
# handle invalid action
</code></pre>
<p>For the default value it can be a proper action, or just leave it out and an exception will be raised; it's up to you how you want to handle it. I left it as <code>None</code> so you can deal with alternative case in the <code>else</code> section.</p>
| 2
|
2016-09-05T06:42:17Z
|
[
"python",
"http",
"request",
"httpverbs"
] |
Python Requests - Dynamically Pass HTTP Verb
| 39,324,970
|
<p>Is there a way to pass an HTTP verb (PATCH/POST) to a function and dynamically use that verb for Python requests?</p>
<p>For example, I want this function to take a 'verb' variable which is only called internally and will either = post/patch.</p>
<pre><code>def dnsChange(self, zID, verb):
for record in config.NEW_DNS:
### LINE BELOW IS ALL THAT MATTERS TO THIS QUESTION
json = requests.verb(headers=self.auth, url=self.API + '/zones/' + str(zID) + '/dns_records', data={"type":record[0], "name":record[1], "content":record[2]})
key = record[0] + "record with host " + record[1]
result = json.loads(json.text)
self.apiSuccess(result,key,value)
</code></pre>
<p>I realize I cannot requests.'verb' as I have above, it's meant to illustrate the question. Is there a way to do this or something similar? I'd like to avoid an:</p>
<pre><code>if verb == 'post':
json = requests.post(headers=self.auth, url=self.API + '/zones/' + str(zID) + '/dns_records', data={"type":record[0], "name":record[1], "content":record[2]}
else:
json = requests.patch(headers=self.auth, url=self.API + '/zones/' + str(zID) + '/dns_records', data={"type":record[0], "name":record[1], "content":record[2]}
</code></pre>
<p>Thanks guys!</p>
| 1
|
2016-09-05T06:32:07Z
| 39,327,014
|
<p>Just use the <code>request()</code> method. First argument is the HTTP verb that you want to use. <code>get()</code>, <code>post()</code>, etc. are just aliases to <code>request('GET')</code>, <code>request('POST')</code>: <a href="https://requests.readthedocs.io/en/master/api/#requests.request" rel="nofollow">https://requests.readthedocs.io/en/master/api/#requests.request</a></p>
<pre><code>verb = 'POST'
json = requests.request(verb, headers=self.auth, url=self.API + '/zones/' + str(zID) + '/dns_records', data={"type":record[0], "name":record[1], "content":record[2]})
</code></pre>
| 2
|
2016-09-05T08:56:36Z
|
[
"python",
"http",
"request",
"httpverbs"
] |
How to download japanese history stock prices automatically from google finance in python
| 39,325,060
|
<p>I use python to analyze Japanese stock prices. I want to get Japanese historical stock prices to get from google finance. I also refer to googlefinance0.7 ( <a href="https://pypi.python.org/pypi/googlefinance" rel="nofollow">https://pypi.python.org/pypi/googlefinance</a> ) and pandas, but they are not support Japanese stock prices. So how to download japanese history stock prices automatically from google finance? Or are there references to program code in python?</p>
| 2
|
2016-09-05T06:39:53Z
| 39,325,455
|
<p><a href="https://www.quandl.com/data/TSE" rel="nofollow">Quandl</a> has all the historical data sets you need.
<br>
It's designed for easy usage with Python so for <a href="https://www.quandl.com/data/TSE/TOPIX-Tokyo-Stock-Exchange-TOPIX-Index" rel="nofollow">Tokyo Stock Exchange TOPIX Index</a> :</p>
<pre><code>import quandl
mydata = quandl.get("TSE/TOPIX")
</code></pre>
| 1
|
2016-09-05T07:12:01Z
|
[
"python",
"finance",
"stock"
] |
Changing userPassword in OpenLDAP using ldap3 library
| 39,325,089
|
<p>I can't seem to change a users password using the ldap3 python module against an OpenLDAP server. A similar question has been asked <a href="http://stackoverflow.com/questions/37847042/changing-active-directory-user-password-in-python-3-x">before</a> but that's specific to Active Directory.</p>
<p>What I've tried:</p>
<pre><code>from ldap3.extend.standard.modifyPassword import ModifyPassword
from ldap3.utils.hashed import hashed
password = hashed(HASHED_SALTED_SHA, password)
# or..
password = '{SASL}theuser@domain.com'
modify = ModifyPassword(
connection, user.entry_get_dn(), new_password=password)
resp = modify.send()
print(modify.result)
{'referrals': None, 'result': 0, 'description': 'success', 'type': 'extendedResp', 'message': '', 'responseName': None, 'new_password': None, 'dn': '', 'responseValue': None}
</code></pre>
<p>The description says success, but the password isn't actually changed.</p>
<p>I've also tried to send a modify replace message:</p>
<pre><code>def modify_user_password(self, user, password):
dn = user.entry_get_dn()
hashed_password = hashed(HASHED_SALTED_SHA, 'MyStupidPassword')
changes = {
'userPassword': [(MODIFY_REPLACE, [hashed_password])]
}
logger.debug('dn: ' + dn)
logger.debug('changes: ' + str(changes))
success = self.engage_conn.modify(dn, changes=changes)
if success:
logger.debug('Changed password for: %s', dn)
print(self.engage_conn.result)
else:
logger.warn('Unable to change password for %s', dn)
logger.debug(str(self.engage_conn.result))
raise ValueError('stop')
</code></pre>
<p>The connection is <strong>not</strong> an SSL connection. The answer to the AD question requires that the connection be over SSL. Is this also a requirement for OpenLDAP?</p>
<p>Edit:</p>
<p>After changing the <code>dn</code> to <code>user.entry_get_dn()</code> the code seemed to work about 90% of the time. After running these tests again today it appears that it now works consistently. I'm going to chalk this up to not viewing fresh data in my directory browser.</p>
| 2
|
2016-09-05T06:41:54Z
| 39,338,891
|
<p>Changing the password seems to work as described in the docs and shown in the edit of my question above. For future reference, this code seems to work:</p>
<pre><code>from ldap3 import (
HASHED_SALTED_SHA, MODIFY_REPLACE
)
from ldap3.utils.hashed import hashed
def modify_user_password(self, user, password):
dn = user.entry_get_dn()
hashed_password = hashed(HASHED_SALTED_SHA, password)
changes = {
'userPassword': [(MODIFY_REPLACE, [hashed_password])]
}
success = self.connection.modify(dn, changes=changes)
if not success:
print('Unable to change password for %s' % dn)
print(self.connection.result)
raise ValueError('Unable to change password')
</code></pre>
<p>To clarify a few things:</p>
<ol>
<li>This is connecting to an OpenLDAP server (with multiple databases)</li>
<li>There is <strong>NO</strong> SSL here. We plan on implementing SSL but this works without it.</li>
</ol>
| 1
|
2016-09-05T23:54:57Z
|
[
"python",
"python-3.x",
"openldap",
"ldap3"
] |
How to train TensorFlow network using a generator to produce inputs?
| 39,325,275
|
<p>The TensorFlow <a href="https://www.tensorflow.org/versions/r0.10/how_tos/reading_data/index.html" rel="nofollow">docs</a> describe a bunch of ways to read data using TFRecordReader, TextLineReader, QueueRunner etc and queues.</p>
<p>What I would like to do is much, much simpler: I have a python generator function that produces an infinite sequence of training data as (X, y) tuples (both are numpy arrays, and the first dimension is the batch size). I just want to train a network using that data as inputs. </p>
<p>Is there a simple self-contained example of training a TensorFlow network using a generator which produces the data? (along the lines of the MNIST or CIFAR examples)</p>
| 3
|
2016-09-05T06:57:38Z
| 39,331,675
|
<p>Suppose you have a function that generates data: </p>
<pre><code> def generator(data):
...
yield (X, y)
</code></pre>
<p>Now you need some function that describes your network architecture. It could be any network that processes X and has to predict y as output. </p>
<p>Suppose your function receives X and y as inputs, computes prediction for y from X in some way and returns loss function (e.g. cross-entropy or MSE in the case of regression) between y and predicted y:</p>
<pre><code> def NN(X, y):
#computation of prediction for y using X
return loss(y, y_pred)
</code></pre>
<p>To make your model work, you need to define placeholders for both X and y and then run a session:</p>
<pre><code> X = tf.placeholder(tf.float32, shape = [batch_size, X_dim])
y = tf.placeholder(tf.float32, shape = [batch_size, y_dim])
</code></pre>
<p>Placeholders are something like "free variables" which you need to specify when running the session by feed_dict:</p>
<pre><code> sess = tf.Session()
sess.run(init)
batch_gen = generator(data)
batch = batch_gen.next()
#note here batch is a tuple with X for first components and y for second
sess.run([optm, loss, ...], feed_dict = {X: batch[0], y: batch[1]})
#optm here stands for optimizer you have defined and loss for loss function (return value of NN function)
</code></pre>
<p>Here I demonstrated how to run a session for one batch, but you of course could use for loop to train over multiple batches. </p>
<p>Suppose you would find it useful. However, bear in mind this is not full working implementation but rather a pseudocode as you specified almost none details.</p>
| 3
|
2016-09-05T13:27:49Z
|
[
"python",
"tensorflow"
] |
pyinstaller 3.2 with django 1.10.1
| 39,325,296
|
<p>System: windows 7 64 bit, python 3.5, anaconda 3 (64 bit) , django 1.10.1 </p>
<p>I'm trying to compile my django project in 2 ways:</p>
<p>First:</p>
<pre><code>[Anaconda3] c:\compilation\Gui>pyinstaller --name=gui --exclude-module=PyQt4 --exclude-module=matplotlib --clean --win-private-assemblies manage.py
</code></pre>
<p>Second according to <a href="http://stackoverflow.com/questions/34479049/pyinstaller-django-with-custom-admin-commands">this soloution</a>:</p>
<pre><code>[Anaconda3] c:\compilation\Gui>pyinstaller --name=gui --exclude-module=PyQt4 --exclude-module=matplotlib --clean --win-private-assemblies --runtime-hook=pyi_rth_django.py manage.py
</code></pre>
<p>When I try to run the output: </p>
<pre><code>c:\compilation\Gui\dist\gui>gui.exe runserver
</code></pre>
<p>I get (for the 2 versions I get the same output):</p>
<pre><code>c:\compilation\Gui\dist\gui>gui.exe runserver
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x00000000044E9D90>
Traceback (most recent call last):
File "site-packages\django\utils\autoreload.py", line 226, in wrapper
File "site-packages\django\core\management\commands\runserver.py", line 113, in inner_run
File "site-packages\django\utils\autoreload.py", line 249, in raise_last_exception
File "site-packages\django\utils\six.py", line 685, in reraise
File "site-packages\django\utils\autoreload.py", line 226, in wrapper
File "site-packages\django\__init__.py", line 27, in setup
File "site-packages\django\apps\registry.py", line 85, in populate
File "site-packages\django\apps\config.py", line 116, in create
File "importlib\__init__.py", line 126, in import_module
File "<frozen importlib._bootstrap>", line 986, in _gcd_import
File "<frozen importlib._bootstrap>", line 969, in _find_and_load
File "<frozen importlib._bootstrap>", line 956, in _find_and_load_unlocked
ImportError: No module named 'django.contrib.admin.apps'
</code></pre>
<p>Please advice.</p>
| 0
|
2016-09-05T06:59:21Z
| 39,333,547
|
<p>What is your files layout? According to these <code>pyinstaller</code> docs <a href="https://github.com/pyinstaller/pyinstaller/wiki/Recipe-Executable-From-Django" rel="nofollow">https://github.com/pyinstaller/pyinstaller/wiki/Recipe-Executable-From-Django</a> there could be two solutions.</p>
<ol>
<li><p>run your command from parent directory, i.e. instead of</p>
<pre><code>c:\compilation\Gui>pyinstaller --name=gui manage.py
</code></pre>
<p>do</p>
<pre><code>c:\compilation>pyinstaller --name=gui Gui\manage.py
</code></pre></li>
<li><p>try to add <code>import django.contrib.admin.apps</code> to your <code>manage.py</code> and make sure it exists</p></li>
<li><p><a href="https://github.com/pyinstaller/pyinstaller/wiki/Recipe-Executable-From-Django#what-if-it-does-not-work" rel="nofollow">report bug</a></p></li>
</ol>
| 0
|
2016-09-05T15:16:28Z
|
[
"python",
"django",
"pyinstaller"
] |
Numba: Manual looping faster than a += c * b with numpy arrays?
| 39,325,352
|
<p>I would like to do a 'daxpy' (add to a vector the scalar multiple of a second vector and assign the result to the first) with <code>numpy</code> using <code>numba</code>. Doing the following test, I noticed that writing the loop myself was much faster than doing <code>a += c * b</code>.</p>
<p>I was not expecting this. What is the reason for this behavior?</p>
<pre><code>import numpy as np
from numba import jit
x = np.random.random(int(1e6))
o = np.random.random(int(1e6))
c = 3.4
@jit(nopython=True)
def test1(a, b, c):
a += c * b
return a
@jit(nopython=True)
def test2(a, b, c):
for i in range(len(a)):
a[i] += c * b[i]
return a
%timeit -n100 -r10 test1(x, o, c)
>>> 100 loops, best of 10: 2.48 ms per loop
%timeit -n100 -r10 test2(x, o, c)
>>> 100 loops, best of 10: 1.2 ms per loop
</code></pre>
| 5
|
2016-09-05T07:03:30Z
| 39,352,473
|
<p>One thing to keep in mind is 'manual looping' in <code>numba</code> is very fast, essentially the same as the c-loop used by numpy operations.</p>
<p>In the first example there are two operations, a temporary array (<code>c * b</code>) is allocated / calculated, then that temporary array is added to <code>a</code>. In the second example, both calculations are happening in the same loop with no intermediate result.</p>
<p>In theory, <code>numba</code> could fuse loops and optimize #1 to do the same as #2, but it doesn't seem to be doing it. If you just want to optimize numpy ops, <code>numexpr</code> may also be worth a look as it was designed for exactly that - though probably won't do any better than the explicit fused loop.</p>
<pre><code>In [17]: import numexpr as ne
In [18]: %timeit -r10 test2(x, o, c)
1000 loops, best of 10: 1.36 ms per loop
In [19]: %timeit ne.evaluate('x + o * c', out=x)
1000 loops, best of 3: 1.43 ms per loop
</code></pre>
| 2
|
2016-09-06T15:13:48Z
|
[
"python",
"numba"
] |
Installation for pyzmq for Windows fails with error C2143, C4142
| 39,325,522
|
<p>I have a windows 7 machine with python 2.7 and I am trying to install <code>pyzmq</code> following <a href="http://zeromq.org/docs:windows-installations" rel="nofollow">these</a> steps. I built <code>libzmq</code> got the binaries and copied them from <code>libzmq\bin\Win32\Debug\v140\dynamic\</code> to <code>libzmq\lib\</code> so the next step will work(compiler will have access to /lib and /includes from the same parent folder). But, on this step: </p>
<blockquote>
<p>$ python setup.py configure --zmq=../libzmq</p>
</blockquote>
<p>I installed <code>pyzmq</code> and <code>libzmq</code> on the same parent folder, as in the installation description related to <code>pyzmq</code>, <code>libzmq</code> is here: <code>../libzmq</code></p>
<p>But when I need to configure the <code>pyzmq</code>, I get this error:
<a href="http://i.stack.imgur.com/ulF87.png" rel="nofollow"><img src="http://i.stack.imgur.com/ulF87.png" alt="enter image description here"></a></p>
<p>I have VS Community 2015 installed and everything seems fine.</p>
| 0
|
2016-09-05T07:16:46Z
| 39,352,652
|
<p>ZMQ usually provides <code>sln</code> files that will build from Microsoft Visual Studio. You will have to dig around a little to find it. You are better off trying to get that to work then going directly from the <code>python setup.py</code> that you are currently attempting. Note that you also need <code>libsodium</code> to be built and installed. Thankfully, they also provide Microsoft <code>sln</code> files.</p>
<p>In any case, you are probably better using one of the Python wheels like those from Christoph <a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/" rel="nofollow">http://www.lfd.uci.edu/~gohlke/pythonlibs/</a></p>
<p>Just do</p>
<p><code>pip install <wheel file></code></p>
<p>and you should be good.</p>
<p>Good luck!</p>
| 0
|
2016-09-06T15:22:32Z
|
[
"python",
"windows",
"pyzmq"
] |
how to return item load in scrapy loop
| 39,325,674
|
<p>The code is as below , every time it returns only the first loop ,the last 9 loops disapeared .So what should I do to get all the loops ?</p>
<p>I have tried to add a "m = []" and m.append(l) ,but got a error "ERROR: Spider must return Request, BaseItem, dict or None, got 'ItemLoader'"</p>
<p>link is <a href="http://ajax.lianjia.com/ajax/housesell/area/district?ids=23008619&limit_offset=0&limit_count=100&sort=&&city_id=110000" rel="nofollow">http://ajax.lianjia.com/ajax/housesell/area/district?ids=23008619&limit_offset=0&limit_count=100&sort=&&city_id=110000</a></p>
<pre><code>def parse(self, response):
jsonresponse = json.loads(response.body_as_unicode())
for i in range(0,len(jsonresponse['data']['list'])):
l = ItemLoader(item = ItjuziItem(),response=response)
house_code = jsonresponse['data']['list'][i]['house_code']
price_total = jsonresponse['data']['list'][i]['price_total']
ctime = jsonresponse['data']['list'][i]['ctime']
title = jsonresponse['data']['list'][i]['title']
frame_hall_num = jsonresponse['data']['list'][i]['frame_hall_num']
tags = jsonresponse['data']['list'][i]['tags']
house_area = jsonresponse['data']['list'][i]['house_area']
community_id = jsonresponse['data']['list'][i]['community_id']
community_name = jsonresponse['data']['list'][i]['community_name']
is_two_five = jsonresponse['data']['list'][i]['is_two_five']
frame_bedroom_num = jsonresponse['data']['list'][i]['frame_bedroom_num']
l.add_value('house_code',house_code)
l.add_value('price_total',price_total)
l.add_value('ctime',ctime)
l.add_value('title',title)
l.add_value('frame_hall_num',frame_hall_num)
l.add_value('tags',tags)
l.add_value('house_area',house_area)
l.add_value('community_id',community_id)
l.add_value('community_name',community_name)
l.add_value('is_two_five',is_two_five)
l.add_value('frame_bedroom_num',frame_bedroom_num)
print l
return l.load_item()
</code></pre>
| 0
|
2016-09-05T07:27:39Z
| 39,325,882
|
<p>The error: </p>
<blockquote>
<p>ERROR: Spider must return Request, BaseItem, dict or None, got
'ItemLoader'</p>
</blockquote>
<p>is slightly misleading since you can also return a generator! What is happening here is that return breaks the loop and the whole function. You can turn this function into a generator to avoid this.</p>
<p>Simply just replace <code>return</code> with <code>yield</code> in your last line.</p>
<pre><code>return l.load_item()
</code></pre>
<p>to:</p>
<pre><code>yield l.load_item()
</code></pre>
| 2
|
2016-09-05T07:43:16Z
|
[
"python",
"json",
"ajax",
"scrapy",
"web-crawler"
] |
Mongoengine: dynamic Fields with EmbededDocuments as values
| 39,325,746
|
<p>I have been using MapField till now as:</p>
<pre><code>class Game(EmbeddedDocument):
iscomplete = BooleanField()
score = IntField()
#other not dynamic fields
class Progress(Document):
user = ReferenceField(User, dbref=True)
games = MapField(EmbeddedDocumentField(Game))
created_at = DateTimeField()
updated_on = DateTimeField()
</code></pre>
<p>I need to convert games to a ReferenceField.</p>
<p>I want to create Document with dynamic fields/keys but embeddedDocument as the values, so that I can have a document like:</p>
<pre><code>{
"game1": {
"iscomplete": true,
"score": 23,
},
"game2": {
"iscomplete": false,
"score": 10,
}
}
</code></pre>
<p>Is t here anyway I can achieve it?</p>
| 0
|
2016-09-05T07:33:40Z
| 39,355,893
|
<p>You can achive that using <a href="http://docs.mongoengine.org/guide/defining-documents.html#dynamic-document-schemas" rel="nofollow">dynamic document in mongengine</a>:</p>
<blockquote>
<p>DynamicDocument documents work in the same way as Document but any
data / attributes set to them will also be saved</p>
</blockquote>
<p>So, you remove the games field, and add later your dynamic field games as, game1, game2, etc fields, they will be saved.</p>
<pre><code>class Game(EmbeddedDocument):
iscomplete = fields.BooleanField()
score = fields.IntField()
class Progress(DynamicDocument):
user = ReferenceField(User, dbref=True)
created_at = DateTimeField()
updated_on = DateTimeField()
p = Progress()
p.game1 = Game(iscomplete=True, score=10)
p.game2 = Game(iscomplete=False, score=5)
p.save()
</code></pre>
| 1
|
2016-09-06T18:46:34Z
|
[
"python",
"mongodb",
"mongoengine",
"embedded-documents"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.