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 |
|---|---|---|---|---|---|---|---|---|---|
django views - hyperlinks with thumbnails | 39,027,560 | <p>I'm brand new to django front-end web development. </p>
<p>I have an <code>index.html</code> in my templates folder which has two thumbnails for sign up or login, and clicking on them directs you to <code>signup.html</code> and <code>login.html</code>. I have included the respective urls for those in <code>urls.py</code>. I'm stuck as to how I can edit my <code>views.py</code> so that I can record which option the user takes in order to perform the directing. I've used hyperlinks and thumbnails in my HTML code.</p>
<p>Currently my <code>views.py</code> looks like this:</p>
<pre><code> from django.shortcuts import render
from .models import Customer
# Create your views here.
def index(request):
return render(request, 'newuser/index.html', {})
def login(request):
return render(request, 'newuser/login.html', {})
def signup(request):
return render(request, 'newuser/signup.html', {})`
</code></pre>
<p>And <code>urls.py</code>:</p>
<pre><code>from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name = 'index'),
url(r'^login$', views.login, name = 'login'),
url(r'^signup$', views.signup, name = 'signup'),
]
</code></pre>
<p>And finally, this is my <code>index.html</code>:</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title> Zucumber </title>
<link rel = "stylesheet" href = "//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<link rel = "stylesheet" href = "//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/bootstrap-theme.min.css">
<link href="https://fonts.googleapis.com/css?family=PT+Sans" rel="stylesheet">
<link rel = "stylesheet" href = "{% static 'css/newuser.css' %}">
</head>
<body>
<div class = "page-header">
<h1> Welcome to My Site </h1>
</div>
<style>
.container {
margin-left: 300px;
margin-right: 300px;
}
</style>
<div class = "container">
<div class="row">
<div class="col-xs-6 col-md-3">
<a href="signup" class="thumbnail">
<img src="/static/img/signup.jpg" alt = "Sign Up as New User">
</a>
<h3> Sign Up </h3>
</div>
<div class="col-xs-6 col-md-3">
<a href="login" class="thumbnail">
<img src="/static/img/login.jpg" alt = "Log In as Existing User">
</a>
<h3> Log In </h3>
</div>
</div>
</div>
</body>
</html>
</code></pre>
| 0 | 2016-08-18T21:09:28Z | 39,030,935 | <p>I'm not sure if i follow what you are asking exactly, but if its just the directing the user in the urls then you should use the url template tag with something like this</p>
<pre><code><a href="{% url 'signup' %}" class="thumbnail">
<img src="/static/img/signup.jpg" alt = "Sign Up as New User">
</a>
<a href="{% url 'login' %}" class="thumbnail">
<img src="/static/img/login.jpg" alt = "Log In as Existing User">
</a>
</code></pre>
<p>because you named the urls in urls.py you can reference them by name in the url template tag and it will figure out the full url.</p>
<p>for example as you named this one login</p>
<pre><code>url(r'^login$', views.login, name = 'login'),
</code></pre>
<p>using the following</p>
<pre><code><a href="{% url 'login' %}" class="thumbnail">click here</a>
</code></pre>
<p>will cause it to render with the url <a href="http://yoursite.com/login" rel="nofollow">http://yoursite.com/login</a> </p>
<p>if you are actually looking to record the clicks the user makes that is slightly more involved and you probably want to setup some model to persist the data and then catch the clicks in the views somehow</p>
| 1 | 2016-08-19T04:06:23Z | [
"python",
"html",
"django",
"twitter-bootstrap"
] |
django views - hyperlinks with thumbnails | 39,027,560 | <p>I'm brand new to django front-end web development. </p>
<p>I have an <code>index.html</code> in my templates folder which has two thumbnails for sign up or login, and clicking on them directs you to <code>signup.html</code> and <code>login.html</code>. I have included the respective urls for those in <code>urls.py</code>. I'm stuck as to how I can edit my <code>views.py</code> so that I can record which option the user takes in order to perform the directing. I've used hyperlinks and thumbnails in my HTML code.</p>
<p>Currently my <code>views.py</code> looks like this:</p>
<pre><code> from django.shortcuts import render
from .models import Customer
# Create your views here.
def index(request):
return render(request, 'newuser/index.html', {})
def login(request):
return render(request, 'newuser/login.html', {})
def signup(request):
return render(request, 'newuser/signup.html', {})`
</code></pre>
<p>And <code>urls.py</code>:</p>
<pre><code>from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name = 'index'),
url(r'^login$', views.login, name = 'login'),
url(r'^signup$', views.signup, name = 'signup'),
]
</code></pre>
<p>And finally, this is my <code>index.html</code>:</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title> Zucumber </title>
<link rel = "stylesheet" href = "//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<link rel = "stylesheet" href = "//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/bootstrap-theme.min.css">
<link href="https://fonts.googleapis.com/css?family=PT+Sans" rel="stylesheet">
<link rel = "stylesheet" href = "{% static 'css/newuser.css' %}">
</head>
<body>
<div class = "page-header">
<h1> Welcome to My Site </h1>
</div>
<style>
.container {
margin-left: 300px;
margin-right: 300px;
}
</style>
<div class = "container">
<div class="row">
<div class="col-xs-6 col-md-3">
<a href="signup" class="thumbnail">
<img src="/static/img/signup.jpg" alt = "Sign Up as New User">
</a>
<h3> Sign Up </h3>
</div>
<div class="col-xs-6 col-md-3">
<a href="login" class="thumbnail">
<img src="/static/img/login.jpg" alt = "Log In as Existing User">
</a>
<h3> Log In </h3>
</div>
</div>
</div>
</body>
</html>
</code></pre>
| 0 | 2016-08-18T21:09:28Z | 39,033,493 | <p>Please avoid hard-coding urls in Django. You can use the power of reverse url matching here. Since you already have name assigned to your urls, you can have <code>container</code> in your <code>index.html</code> like this:</p>
<pre><code><div class = "container">
<div class="row">
<div class="col-xs-6 col-md-3">
<a href="{% url 'signup' %}" class="thumbnail">
<img src="/static/img/signup.jpg" alt = "Sign Up as New User">
</a>
<h3> Sign Up </h3>
</div>
<div class="col-xs-6 col-md-3">
<a href="{% url 'login' %}" class="thumbnail">
<img src="/static/img/login.jpg" alt = "Log In as Existing User">
</a>
<h3> Log In </h3>
</div>
</div>
</div>
</code></pre>
<p>This would help in redirecting to corresponding urls using your <code>urls.py</code>.</p>
<p>Next, you need to create a <code>forms</code> to be displayed on <code>signup</code> and <code>login</code> page. Since you've imported <code>Customer</code> from models, I'm assuming that you want to create <code>signup</code> and <code>login</code> for them.</p>
<p>So you can put in your <code>forms.py</code>:</p>
<pre><code>from django.contrib.auth.forms import AuthenticationForm, UserCreationForm
from django import forms
from .models import Customer
class LoginForm(AuthenticationForm):
username = forms.CharField(label="Username", max_length=30,
widget=forms.TextInput(attrs={'class': 'form-control', 'name': 'username'}))
password = forms.CharField(label="Password", max_length=30,
widget=forms.PasswordInput(attrs={'class': 'form-control', 'name': 'password'}))
class SignUpForm(UserCreationForm):
class Meta:
model = Customer
</code></pre>
<p>In <code>SignUpForm</code> you can also specify the fields you want from the user while registering by providing <code>fields</code> as a list of attributes of <code>Customer</code> model.</p>
<p>In your <code>login.html</code> you can provide a space for your <code>LoginForm</code> to render like:</p>
<pre><code><form action="{% url 'login' %}" method="POST">
{% csrf_token %}
{% for field in form %}
<b>{{ field.label }}</b>:
{{ field }}<br>
{{ field.errors }}
{% endfor %}
<input type="submit" value="Sumbit">
</form>
</code></pre>
<p>Similarly your <code>signup.html</code> would also provide form like this:</p>
<pre><code><form action="{% url 'signup' %}" method="POST">
{% csrf_token %}
{% for field in form %}
<b>{{ field.label }}</b>:
{{ field }}<br>
{{ field.errors }}<br>
{% endfor %}
<input type="submit" value="Sumbit">
</form>
</code></pre>
<p>Finally edit your <code>login</code> and <code>signup</code> views to store the data like this:</p>
<pre><code>from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from django.contrib.auth import authenticate, login, logout
from .forms import LoginForm, SignUpForm
def login(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
return HttpResponse("Logged in", status=200)
else:
form = LoginForm(request.POST)
context = {'form': form}
return render(request, 'login.html', context=context, status=401)
if request.method == 'GET':
form = LoginForm(None)
context = {'form': form}
return render(request, 'login.html', context=context)
def signup(request):
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
form.save()
else:
context = {'form': form}
return render(request, 'signup.html', context=context)
return HttpResponse("Registered Successfully", status=200)
if request.method == 'GET':
form = SignUpForm(None)
context = {'form': form}
return render(request, 'signup.html', context=context)
</code></pre>
<p>Note here that I've used login and logout functionality of <code>django.contrib.auth</code>. This may not be what you want for your application. But the idea is pretty much similar.
I hope this helps.</p>
| 0 | 2016-08-19T07:33:56Z | [
"python",
"html",
"django",
"twitter-bootstrap"
] |
Some element.tail attributes are empty although they shouldn't | 39,027,618 | <p>I am trying to parse rather <a href="https://mcepl.fedorapeople.org/tmp/Mat-old.xml" rel="nofollow">large XML file</a> (with one biblical book) using xml.etree.ElementTree from python 3.4 (for compatibility with Windows I would prefer to stay with the standard library modules), and the relevant methods are here.</p>
<pre><code>class BibleTree:
def __init__(self, file_name: str) -> None:
self.root = ET.parse(file_name).getroot()
@staticmethod
def _list_to_clean_text(str_in: str) -> str:
out = re.sub(r'[\s\n]+', ' ', str_in, flags=re.DOTALL)
return out.strip()
@staticmethod
def _clean_text(intext: Optional[str]) -> str:
return intext if intext is not None else ''
def __iter__(self) -> Tuple[int, int, str]:
collected = None
cur_chap = 0
cur_verse = 0
for child in self.root:
if child.tag in ['kap', 'vers']:
if collected and collected.strip():
yield cur_chap, cur_verse, self._list_to_clean_text(collected)
if child.tag == 'kap':
cur_chap = int(child.attrib['n'])
elif child.tag == 'vers':
cur_verse = int(child.attrib['n'])
collected = self._clean_text(child.tail)
else:
if collected is not None:
collected += self._clean_text(child.text)
collected += self._clean_text(child.tail)
</code></pre>
<p>The problem is that in some situations (e.g., the element <code><odkazo/></code> on line 54) the <code>tail</code> attribute of the variable <code>child</code> is None, although it should be IMHO a text.</p>
<p>Any ideas, what I do wrong, please?</p>
| 0 | 2016-08-18T21:13:12Z | 39,057,700 | <p>This is PEBKAC ... I have assumed that there are no milestoned elements inside of other elements. So, I need to rewrite whole function as a recursive one. Oh well.</p>
| 0 | 2016-08-20T18:59:12Z | [
"python",
"xml",
"elementtree"
] |
Scrapy - How to avoid Pagination Blackhole? | 39,027,680 | <p>I was recently working on a website spider and noticed it was requesting an infinite number of pages because a site hadn't coded their pagination to ever stop.</p>
<p>So while they only had a few pages of content, it still would generate a next link and a url ...?page=400, ...?page=401, etc.</p>
<p>The content didn't change, just the URL. Is there a way to make Scrapy stop following pagination when content stops changing? Or something I could code up custom.</p>
| 0 | 2016-08-18T21:18:52Z | 39,034,235 | <p>If the content doesn't change you can compare the content of the current page with the previous page and if it's the same, break the crawl.</p>
<p>for example:</p>
<pre><code>def parse(self, response):
product_urls = response.xpath("//a/@href").extract()
# check last page
if response.meta.get('prev_urls') == product_urls:
logging.info('reached the last page at: {}'.format(response.url))
return # reached the last page
# crawl products
for url in product_urls:
yield Request(url, self.parse_product)
# create next page url
next_page = response.meta.get('page', 0) + 1
next_url = re.sub('page=\d+', 'page={}'.format(next_page), response.url)
# now for the next page carry some data in meta
yield Request(next_url,
meta={'prev_urls': product_urls,
'page': next_page}
</code></pre>
| 1 | 2016-08-19T08:16:19Z | [
"python",
"pagination",
"scrapy",
"web-crawler"
] |
Same code inserts data into one database but not into another | 39,027,681 | <p>I am facing a strange problem right now. I am using pypyodbc to insert data into a test database hosted by AWS. This database that I created was by hand and did not imitate all relations and whatnot between tables. All I did was create a table with the same columns and the same datatypes as the original (let's call it master) database. When I run my code and insert the data it works in the test environment. Then I change it over to the master database and the code runs all the way through but no data is actually inputted. Is there any chance that there are security protocols in place which prevent me from inputting data in through the Python script rather than through a normal SQL query? Is there something I am missing?</p>
| 0 | 2016-08-18T21:18:54Z | 39,027,828 | <p>It sounds like it's not pointing to the correct database. Have you made sure the connection information changes to point to the correct DB? So the server name is correct, the login credentials are good, etc.?</p>
| 2 | 2016-08-18T21:31:54Z | [
"python",
"sql-server",
"pypyodbc"
] |
pyqt with native python thread qpixmap and parent error | 39,027,837 | <p>I'm using python native thread with pyqt default thread. When I want show qmessagebox in native thread, my program is crashed.
Here is my code:</p>
<pre><code>.........
self.serverSoc.listen(5)
self.status="Server listening on %s:%s" % serveraddr
self.serverStatus = 1
thread.start_new_thread(self.listenClients, ())
def listenClients(self):
while 1:
clientsoc, clientaddr = self.serverSoc.accept()
print("Client connected from %s:%s" % clientaddr)
data = clientsoc.recv(self.buffsize)
if data.startswith('%sendchatrequest%'):
try:
requestuser = data.rsplit(':', 1)[1]
msg = "%s wanted to chat with you. Do you accept this?" %requestuser
reply = QtGui.QMessageBox.question(self, 'Chat Request',
msg, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
</code></pre>
<p>and I got this error:</p>
<pre><code>QObject::setParent: Cannot set parent, new parent is in a different thread
QPixmap: It is not safe to use pixmaps outside the GUI thread
QPixmap: It is not safe to use pixmaps outside the GUI thread
QPixmap: It is not safe to use pixmaps outside the GUI thread
QPixmap: It is not safe to use pixmaps outside the GUI thread
QPixmap: It is not safe to use pixmaps outside the GUI thread
QPixmap: It is not safe to use pixmaps outside the GUI thread
QPixmap: It is not safe to use pixmaps outside the GUI thread
X Error: BadImplementation (server does not implement operation) 17
Major opcode: 20 (X_GetProperty)
Resource id: 0x0
[xcb] Unknown request in queue while dequeuing
[xcb] Most likely this is a multi-threaded client and XInitThreads has not been called
[xcb] Aborting, sorry about that.
python2.7: ../../src/xcb_io.c:179: dequeue_pending_request: Assertion `!xcb_xlib_unknown_req_in_deq' failed.
</code></pre>
<p>how can I fix it? Thank you so much</p>
| 0 | 2016-08-18T21:32:19Z | 39,043,812 | <p>Qt requires that all GUI operations are done in the main thread.</p>
<p>Why not use a <a href="http://doc.qt.io/qt-5/qtcpsocket.html" rel="nofollow">QTcpSocket</a> instead which nicely integrates into Qt's mainloop instead of requiring a thread?</p>
| 0 | 2016-08-19T16:28:04Z | [
"python",
"multithreading",
"pyqt"
] |
Python: change "\" to "\\" | 39,028,037 | <p>I have an entry field that allows the user to enter their own directory/path structure when saving a file, if the user just copies their directory from windows explorer you can get text like "c:\directory\file.ext" how can I take text entered like that and replace it with the necessary "\" for the os module to use?</p>
| 0 | 2016-08-18T21:50:07Z | 39,028,200 | <p>maybe <code>os.path.normpath()</code> would be helpful to you - and the documentation <a href="https://docs.python.org/2/library/os.path.html" rel="nofollow">here</a></p>
| 0 | 2016-08-18T22:04:15Z | [
"python",
"replace"
] |
Python: change "\" to "\\" | 39,028,037 | <p>I have an entry field that allows the user to enter their own directory/path structure when saving a file, if the user just copies their directory from windows explorer you can get text like "c:\directory\file.ext" how can I take text entered like that and replace it with the necessary "\" for the os module to use?</p>
| 0 | 2016-08-18T21:50:07Z | 39,028,549 | <p>Use a raw string to get the backslashes</p>
<pre><code>>>> path = r"c:\test\123"
>>> path
'c:\\test\\123'
>>> print path
c:\test\123
</code></pre>
| 0 | 2016-08-18T22:36:44Z | [
"python",
"replace"
] |
How do I ask all of the questions in the list without repeating the lines of code? | 39,028,103 | <pre><code>question = ["1 â Which seven-a-side ball game is played in a swimming pool?",
"2 - When was the Olympics last held in London?",
"3 - What is the world record time of the men's 100m sprint?",
"4 - The latest Bond song was sung by whom?",
"5 - Who won the Euro 2016 Final?",
"6 - Who is the mascot of Pokemon?",
"7 - How many stars are on the U.S flag?",
"8 - If 1 = 5, 2 = 10, 3 = 15 and 4 = 20, what does 5 =?",
"9 - In a right angled triangle one side is 3 and another side is 4, what is the length of the hypotenuse?",
"10 - What is the 7th decimal place of pi?"]
multi1 = ["A: Marco Polo","A: 1944","A:9.58seconds","A: Charlie Puth","A: Portugal","A: Mew","A: 49","A: 25","A: 2","A: 4"]
multi2 = ["B: Polo","B: 2004","B: 9.68seconds","B: Sam Smith","B: Wales","B: Mewtwo","B: 52","B: 4","B: 5","B: 1"]
multi3 = ["C: Water Polo","C: 2008","C: 9.54seconds","C: Adele","C: France","C: Pikachu","C: 51","C: 5","C: 3.5","C: 9"]
multi4 = ["D: Polo Marco","D: 2012","D: 9.60seconds","D: Daniel Craig","D: Germany","D: Togepi","D: 50","D: 1","D: 6","D: 6"]
correctAnswer = ['C','D','A','B','A','C','D','D','B','D']
valueWon = ['£0','£100','£2500','£500','£1000','£2500','£5000','£10000','£100000','£1000000']
x = input(question[0] + ' ' +multi1[0]+ ' ' +multi2[0]+ ' ' +multi3[0]+ ' ' +multi4[0])
if x == ("A","B","C"):
print("I'm sorry that was incorrect,",correctAnswer[0],"was the correct answer, you won,",valueWon[0])
else:
y = input("Congratulations, you won" +" " +valueWon[1]+" " +"would you like to continue, yes or no?")
if y == ("No","no"):
exit
</code></pre>
<p>I'm making a 'who wants to be a millionaire' game and I want to ask all of the questions in the list without repeating all of the code that I have used above as it will be too lengthy and I know that there is an easier way. Thanks</p>
| 0 | 2016-08-18T21:54:49Z | 39,028,250 | <p>I am assuming that this is what you want. I see a lot of improvisations that can be made to the code. But still, I am presenting my answers here, for starters.</p>
<pre><code>question = ["1 â Which seven-a-side ball game is played in a swimming pool?","2 - When was the Olympics last held in London?",
"3 - What is the world record time of the men's 100m sprint?",
"4 - The latest Bond song was sung by whom?",
"5 - Who won the Euro 2016 Final?",
"6 - Who is the mascot of Pokemon?",
"7 - How many stars are on the U.S flag?",
"8 - If 1 = 5, 2 = 10, 3 = 15 and 4 = 20, what does 5 =?",
"9 - In a right angled triangle one side is 3 and another side is 4,what is the length of the hypotenuse?",
"10 - What is the 7th decimal place of pi?"]
multi1 = ["A: Marco Polo","A: 1944","A:9.58seconds","A: Charlie Puth","A:Portugal","A: Mew","A: 49","A: 25","A: 2","A: 4"]
multi2 = ["B: Polo","B: 2004","B: 9.68seconds","B: Sam Smith","B: Wales","B: Mewtwo","B: 52","B: 4","B: 5","B: 1"]
multi3 = ["C: Water Polo","C: 2008","C: 9.54seconds","C: Adele","C: France","C: Pikachu","C: 51","C: 5","C: 3.5","C: 9"]
multi4 = ["D: Polo Marco","D: 2012","D: 9.60seconds","D: Daniel Craig","D: Germany","D: Togepi","D: 50","D: 1","D: 6","D: 6"]
correctAnswer = ['C','D','A','B','A','C','D','D','B','D']
valueWon = ['£0','£100','£2500','£500','£1000','£2500','£5000','£10000','£100000','£1000000']
for i,j in enumerate(question):
x = input(j + '\n ' +multi1[i]+ '\n ' +multi2[i]+ '\n ' +multi3[i]+ '\n ' +multi4[i]+'\n')
if x == ("A","B","C"):
print("I'm sorry that was incorrect,",correctAnswer[i],"was the correct answer, you won,",valueWon[i])
else:
y = input("Congratulations, you won" +" " +valueWon[i]+" " +"would you like to continue, yes or no?")
if y == ("No","no"):
break
</code></pre>
<p>I hope this helps.</p>
<p>Thanks!</p>
| 0 | 2016-08-18T22:09:27Z | [
"python",
"python-3.x"
] |
How do I ask all of the questions in the list without repeating the lines of code? | 39,028,103 | <pre><code>question = ["1 â Which seven-a-side ball game is played in a swimming pool?",
"2 - When was the Olympics last held in London?",
"3 - What is the world record time of the men's 100m sprint?",
"4 - The latest Bond song was sung by whom?",
"5 - Who won the Euro 2016 Final?",
"6 - Who is the mascot of Pokemon?",
"7 - How many stars are on the U.S flag?",
"8 - If 1 = 5, 2 = 10, 3 = 15 and 4 = 20, what does 5 =?",
"9 - In a right angled triangle one side is 3 and another side is 4, what is the length of the hypotenuse?",
"10 - What is the 7th decimal place of pi?"]
multi1 = ["A: Marco Polo","A: 1944","A:9.58seconds","A: Charlie Puth","A: Portugal","A: Mew","A: 49","A: 25","A: 2","A: 4"]
multi2 = ["B: Polo","B: 2004","B: 9.68seconds","B: Sam Smith","B: Wales","B: Mewtwo","B: 52","B: 4","B: 5","B: 1"]
multi3 = ["C: Water Polo","C: 2008","C: 9.54seconds","C: Adele","C: France","C: Pikachu","C: 51","C: 5","C: 3.5","C: 9"]
multi4 = ["D: Polo Marco","D: 2012","D: 9.60seconds","D: Daniel Craig","D: Germany","D: Togepi","D: 50","D: 1","D: 6","D: 6"]
correctAnswer = ['C','D','A','B','A','C','D','D','B','D']
valueWon = ['£0','£100','£2500','£500','£1000','£2500','£5000','£10000','£100000','£1000000']
x = input(question[0] + ' ' +multi1[0]+ ' ' +multi2[0]+ ' ' +multi3[0]+ ' ' +multi4[0])
if x == ("A","B","C"):
print("I'm sorry that was incorrect,",correctAnswer[0],"was the correct answer, you won,",valueWon[0])
else:
y = input("Congratulations, you won" +" " +valueWon[1]+" " +"would you like to continue, yes or no?")
if y == ("No","no"):
exit
</code></pre>
<p>I'm making a 'who wants to be a millionaire' game and I want to ask all of the questions in the list without repeating all of the code that I have used above as it will be too lengthy and I know that there is an easier way. Thanks</p>
| 0 | 2016-08-18T21:54:49Z | 39,028,252 | <p>One way would be to turn your questions into individual Class objects. </p>
<pre><code>class Question():
def __init__(self, id, question, answers, correct_answer):
self.id = id
self.question = question
self.answers = answers
self.correct_answer = correct_answer
question_one = Question(
1,
"Which seven-a-side ball game is played in a swimming pool?",
{"1":"Marco Polo", "2":"Water Polo", "3":"Polo", "4":"Polo Marco"},
"Water Polo"
)
question_list = [question_one]
for _ in question_list:
print("Question number {0}: {1}".format(_.id, _.question))
answer = input("{0}\n".format(_.answers))
if _.answers[answer] == _.correct_answer:
print("You're correct!")
</code></pre>
<p>The resulting output would be:</p>
<pre><code>>>>Which seven-a-side ball game is played in a swimming pool?
>>>{'2': 'Water Polo', '1': 'Marco Polo', '3': 'Polo', '4': 'Polo Marco'}
>>>2
>>>You're correct!
</code></pre>
<p>And so on and so forth. Please note that if you're in Python 2.7, you'll need to remove the quotations from the numbers in the <code>answers</code> dict.</p>
| 2 | 2016-08-18T22:09:29Z | [
"python",
"python-3.x"
] |
How do I ask all of the questions in the list without repeating the lines of code? | 39,028,103 | <pre><code>question = ["1 â Which seven-a-side ball game is played in a swimming pool?",
"2 - When was the Olympics last held in London?",
"3 - What is the world record time of the men's 100m sprint?",
"4 - The latest Bond song was sung by whom?",
"5 - Who won the Euro 2016 Final?",
"6 - Who is the mascot of Pokemon?",
"7 - How many stars are on the U.S flag?",
"8 - If 1 = 5, 2 = 10, 3 = 15 and 4 = 20, what does 5 =?",
"9 - In a right angled triangle one side is 3 and another side is 4, what is the length of the hypotenuse?",
"10 - What is the 7th decimal place of pi?"]
multi1 = ["A: Marco Polo","A: 1944","A:9.58seconds","A: Charlie Puth","A: Portugal","A: Mew","A: 49","A: 25","A: 2","A: 4"]
multi2 = ["B: Polo","B: 2004","B: 9.68seconds","B: Sam Smith","B: Wales","B: Mewtwo","B: 52","B: 4","B: 5","B: 1"]
multi3 = ["C: Water Polo","C: 2008","C: 9.54seconds","C: Adele","C: France","C: Pikachu","C: 51","C: 5","C: 3.5","C: 9"]
multi4 = ["D: Polo Marco","D: 2012","D: 9.60seconds","D: Daniel Craig","D: Germany","D: Togepi","D: 50","D: 1","D: 6","D: 6"]
correctAnswer = ['C','D','A','B','A','C','D','D','B','D']
valueWon = ['£0','£100','£2500','£500','£1000','£2500','£5000','£10000','£100000','£1000000']
x = input(question[0] + ' ' +multi1[0]+ ' ' +multi2[0]+ ' ' +multi3[0]+ ' ' +multi4[0])
if x == ("A","B","C"):
print("I'm sorry that was incorrect,",correctAnswer[0],"was the correct answer, you won,",valueWon[0])
else:
y = input("Congratulations, you won" +" " +valueWon[1]+" " +"would you like to continue, yes or no?")
if y == ("No","no"):
exit
</code></pre>
<p>I'm making a 'who wants to be a millionaire' game and I want to ask all of the questions in the list without repeating all of the code that I have used above as it will be too lengthy and I know that there is an easier way. Thanks</p>
| 0 | 2016-08-18T21:54:49Z | 39,028,315 | <p>To answer your question simply: you could iterate over each question in the list of questions with a foreach loop.</p>
<pre><code>for q in question:
#do something with q, the for loop will do this for every q in your list 'question'
</code></pre>
<p>The problem with this is you don't have access to the corresponding multiple choice answers, the correct answer, or the value won easily. That is, if the loop is iterating and you're on the 2nd question, how does the for loop know to present the 2nd multiple choice answers, the 2nd correct answer, etc? </p>
<p>You could do:</p>
<pre><code>for q in question:
#set idx equal to the index number of the current question,
#so if you're on question 3, it'll be index 2, and you can use
#idx to grab the corresponding multiple choice answers/correct answer/etc
idx = question.index(q)
#have the user input an answer
x = input(q + ' ' + multi1[idx] + ... + multi4[idx])
if (x != correctAnswer[idx]):
print("I'm sorry that was incorrect,",correctAnswer[idx],"was the correct answer")
else:
y = input("Congratulations, you won" +" " +valueWon[idx]+" " +"would you like to continue, yes or no?")
if y == ("No","no"):
break
</code></pre>
<p>but <code>enumerate</code> already does this for you:</p>
<pre><code>for i, q in enumerate(question):
#have the user input an answer
x = input(q + ' ' + multi1[i] + ... + multi4[i])
if (x != correctAnswer[i]):
print("I'm sorry that was incorrect,",correctAnswer[i],"was the correct answer")
else:
y = input("Congratulations, you won" +" " +valueWon[i]+" " +"would you like to continue, yes or no?")
if y == ("No","no"):
break
</code></pre>
<p>You could (and probably should) create a class for this that way all of your data is coupled together instead of spread out over several objects. Then you would just have to iterate over the list of objects and use those in the same way. </p>
| 0 | 2016-08-18T22:14:39Z | [
"python",
"python-3.x"
] |
How to get the original name of a function after it is wrapped by function decorator? | 39,028,124 | <h1>The Code</h1>
<pre><code>def blahblah(func):
def wrapper(*args):
pass # blah blah blah....
return wrapper
@blahblah
def func1(arg1):
pass # blah blah blah
@blahblah
def func2(arg1):
pass # blah blah blah
functions = [func1, func2]
for func in functions:
print(func.__name__, func(0))
</code></pre>
<p>What I want is to get the original name of this code, like "func1" and "func2". But the code written before just gives me "wrapper" and "wrapper". Is there any way around? 'd better without changing the wrapping code.</p>
<h1>The Output</h1>
<pre><code> wrapper None
wrapper None
</code></pre>
<h1>Ideal Output</h1>
<pre><code> func1 None
func2 None
</code></pre>
| 2 | 2016-08-18T21:57:23Z | 39,028,167 | <p>You can use the <code>functools.wraps</code> helper function as follows which'll preserve the original name and doc string of the wrapped function, eg:</p>
<pre><code>from functools import wraps
def blahblah(func):
@wraps(func)
def wrapper(*args):
pass # blah blah blah....
return wrapper
@blahblah
def func1(arg1):
pass # blah blah blah
print(func1.__name__)
# func1
</code></pre>
<p>As <a href="http://stackoverflow.com/users/418413/kojiro">kojiro</a> points out in comments, while this preserves the name and doc strings, there are things to be aware of - <a href="https://hynek.me/articles/decorators/" rel="nofollow">https://hynek.me/articles/decorators/</a></p>
| 5 | 2016-08-18T22:01:28Z | [
"python"
] |
How do you use index with words from nltk.corpus? | 39,028,160 | <p>If I were to want to get the 1252nd word from words.words() how would I do it? Of course I could do something like this, but it's so ugly I can barely look at it. </p>
<pre><code>random_word = 1252
counter = 0
for i in words.words():
if counter == random_word:
print(i)
counter += 1
</code></pre>
<p>Is there another way?</p>
| 0 | 2016-08-18T22:01:00Z | 39,028,230 | <p>words.words() from NLTK should be a list. With lists you can just do indexing.</p>
<p>So if you'd like to get the 1252nd word in the list (assuming you're counting pythonically, so 1st position starts at 0), just do <code>words.words()[1251]</code></p>
<p>If you need to access many words from that list at one time (e.g. pull out items at index 1, 20, 500), I would suggest using Python's <code>itemgetter</code></p>
<p>If you wanted to get the index of a certain word in that words.words() list, just do <code>words.words().index('word_you_want_index_for')</code></p>
<p>thanks @Padraic Cunningham for the reminder on python-indexing</p>
| 1 | 2016-08-18T22:07:16Z | [
"python",
"nltk"
] |
How do I hide pandas to_datetime NaT in when I write to CSV? | 39,028,197 | <p>I am a little bit perplexed as to why NaT are showing up in my CSV...usually they show up as "". Here is my date formatting:</p>
<pre><code>df['submitted_on'] = pd.to_datetime(df['submitted_on'], errors='coerce').dt.to_period('d')
df['resolved_on'] = pd.to_datetime(df['resolved_on'], errors='coerce').dt.to_period('d')
df['closed_on'] = pd.to_datetime(df['closed_on'], errors='coerce').dt.to_period('d')
df['duplicate_on'] = pd.to_datetime(df['duplicate_on'], errors='coerce').dt.to_period('d')
df['junked_on'] = pd.to_datetime(df['junked_on'], errors='coerce').dt.to_period('d')
df['unproducible_on'] = pd.to_datetime(df['unproducible_on'], errors='coerce').dt.to_period('d')
df['verified_on'] = pd.to_datetime(df['verified_on'], errors='coerce').dt.to_period('d')
</code></pre>
<p>When I df.head() this is my result. Good, fine, all is dandy.</p>
<pre><code> identifier status submitted_on resolved_on closed_on duplicate_on junked_on \
0 xx1 D 2004-07-28 NaT NaT 2004-08-26 NaT
1 xx2 N 2010-03-02 NaT NaT NaT NaT
2 xx3 U 2005-10-26 NaT NaT NaT NaT
3 xx4 V 2006-06-30 2006-09-15 NaT NaT NaT
4 xx5 R 2012-09-21 2013-06-06 NaT NaT NaT
unproducible_on verified_on
0 NaT NaT
1 NaT NaT
2 2005-11-01 NaT
3 NaT 2006-11-20
4 NaT NaT
</code></pre>
<p>But I write to CSV and the NaT shows up:</p>
<pre><code>"identifier","status","submitted_on","resolved_on","closed_on","duplicate_on","junked_on","unproducible_on","verified_on"
"xx1","D","2004-07-28","NaT","NaT","2004-08-26","NaT","NaT","NaT"
"xx2","N","2010-03-02","NaT","NaT","NaT","NaT","NaT","NaT"
"xx3","U","2005-10-26","NaT","NaT","NaT","NaT","2005-11-01","NaT"
"xx4","V","2006-06-30","2006-09-15","NaT","NaT","NaT","NaT","2006-11-20"
"xx5","R","2012-09-21","2013-06-06","NaT","NaT","NaT","NaT","NaT"
"xx6","D","2009-11-25","NaT","NaT","2010-02-26","NaT","NaT","NaT"
"xx7","D","2003-08-29","NaT","NaT","2003-08-29","NaT","NaT","NaT"
"xx8","R","2003-06-06","2003-06-24","NaT","NaT","NaT","NaT","NaT"
"xx9","R","2004-11-05","2004-11-15","NaT","NaT","NaT","NaT","NaT"
"xx10","R","2008-02-21","2008-09-25","NaT","NaT","NaT","NaT","NaT"
"xx11","R","2007-03-08","2007-03-21","NaT","NaT","NaT","NaT","NaT"
"xx12","R","2011-08-22","2012-06-21","NaT","NaT","NaT","NaT","NaT"
"xx13","J","2003-07-07","NaT","NaT","NaT","2003-07-10","NaT","NaT"
"xx14","A","2008-09-24","NaT","NaT","NaT","NaT","NaT","NaT"
</code></pre>
<p>So, I did what I thought would fix the problem. <code>df.fillna('', inplace=True)</code> and nada. I then tried <code>df.replace(pd.NaT, '')</code> with no results, followed by <code>na_rep=''</code> when I wrote to CSV which also did not result in desired output. What am I supposed to be using to prevent NaT from being transcribed into CSV?</p>
<p>Sample data:</p>
<pre><code>"identifier","status","submitted_on","resolved_on","closed_on","duplicate_on","junked_on","unproducible_on","verified_on"
"xx1","D","2004-07-28 07:00:00.0","null","null","2004-08-26 07:00:00.0","null","null","null"
"xx2","N","2010-03-02 03:00:16.0","null","null","null","null","null","null"
"xx3","U","2005-10-26 14:20:20.0","null","null","null","null","2005-11-01 13:02:22.0","null"
"xx4","V","2006-06-30 07:00:00.0","2006-09-15 07:00:00.0","null","null","null","null","2006-11-20 08:00:00.0"
"xx5","R","2012-09-21 06:30:58.0","2013-06-06 09:35:25.0","null","null","null","null","null"
"xx6","D","2009-11-25 02:16:03.0","null","null","2010-02-26 12:28:22.0","null","null","null"
"xx7","D","2003-08-29 07:00:00.0","null","null","2003-08-29 07:00:00.0","null","null","null"
"xx8","R","2003-06-06 12:00:00.0","2003-06-24 12:00:00.0","null","null","null","null","null"
"xx9","R","2004-11-05 08:00:00.0","2004-11-15 08:00:00.0","null","null","null","null","null"
"xx10","R","2008-02-21 05:13:39.0","2008-09-25 17:20:57.0","null","null","null","null","null"
"xx11","R","2007-03-08 17:47:44.0","2007-03-21 23:47:57.0","null","null","null","null","null"
"xx12","R","2011-08-22 19:50:25.0","2012-06-21 05:52:12.0","null","null","null","null","null"
"xx13","J","2003-07-07 12:00:00.0","null","null","null","2003-07-10 12:00:00.0","null","null"
"xx14","A","2008-09-24 11:36:34.0","null","null","null","null","null","null"
</code></pre>
| 2 | 2016-08-18T22:04:00Z | 39,028,412 | <p>Your problem lies in that you are converting to <code>periods</code>. The <code>NaT</code> you see is actually a <code>period</code> object.</p>
<p>One way around this is to convert to strings instead.</p>
<p>Use</p>
<pre><code>.dt.strftime('%Y-%m-%d')
</code></pre>
<p>Instead of </p>
<pre><code>.dt.to_period('d')
</code></pre>
<p>Then the <code>NaT</code>s you see will be strings and can be replaced like</p>
<pre><code>.dt.strftime('%Y-%m-%d').replace('NaT', '')
</code></pre>
<hr>
<pre><code>df = pd.DataFrame(dict(date=pd.to_datetime(['2015-01-01', pd.NaT])))
df
</code></pre>
<p><a href="http://i.stack.imgur.com/BOcYr.png" rel="nofollow"><img src="http://i.stack.imgur.com/BOcYr.png" alt="enter image description here"></a></p>
<pre><code>df.date.dt.strftime('%Y-%m-%d')
0 2015-01-01
1 NaT
Name: date, dtype: object
</code></pre>
<hr>
<pre><code>df.date.dt.strftime('%Y-%m-%d').replace('NaT', '')
0 2015-01-01
1
Name: date, dtype: object
</code></pre>
| 3 | 2016-08-18T22:23:31Z | [
"python",
"date",
"pandas"
] |
Using unittest to test argparse - exit errors | 39,028,204 | <p>Going off of <a href="http://stackoverflow.com/questions/5943249">Greg Haskin's answer in this question</a>, I tried to make a unittest to check that argparse is giving the appropriate error when I pass it some args that are not present in the <code>choices</code>. However, <code>unittest</code> generates a false positive using the <code>try/except</code> statement below.</p>
<p>In addition, when I make a test using just a <code>with assertRaises</code> statement, <code>argparse</code> forces the system exit and the program does not execute any more tests.</p>
<p>I would like to be able to have a test for this, but maybe it's redundant given that <code>argparse</code> exits upon error?</p>
<pre><code>#!/usr/bin/env python3
import argparse
import unittest
class sweep_test_case(unittest.TestCase):
"""Tests that the merParse class works correctly"""
def setUp(self):
self.parser=argparse.ArgumentParser()
self.parser.add_argument(
"-c", "--color",
type=str,
choices=["yellow", "blue"],
required=True)
def test_required_unknown_TE(self):
"""Try to perform sweep on something that isn't an option.
Should return an attribute error if it fails.
This test incorrectly shows that the test passed, even though that must
not be true."""
args = ["--color", "NADA"]
try:
self.assertRaises(argparse.ArgumentError, self.parser.parse_args(args))
except SystemExit:
print("should give a false positive pass")
def test_required_unknown(self):
"""Try to perform sweep on something that isn't an option.
Should return an attribute error if it fails.
This test incorrectly shows that the test passed, even though that must
not be true."""
args = ["--color", "NADA"]
with self.assertRaises(argparse.ArgumentError):
self.parser.parse_args(args)
if __name__ == '__main__':
unittest.main()
</code></pre>
<p>Errors:</p>
<pre><code>Usage: temp.py [-h] -c {yellow,blue}
temp.py: error: argument -c/--color: invalid choice: 'NADA' (choose from 'yellow', 'blue')
E
usage: temp.py [-h] -c {yellow,blue}
temp.py: error: argument -c/--color: invalid choice: 'NADA' (choose from 'yellow', 'blue')
should give a false positive pass
.
======================================================================
ERROR: test_required_unknown (__main__.sweep_test_case)
Try to perform sweep on something that isn't an option.
----------------------------------------------------------------------
Traceback (most recent call last): #(I deleted some lines)
File "/Users/darrin/anaconda/lib/python3.5/argparse.py", line 2310, in _check_value
raise ArgumentError(action, msg % args)
argparse.ArgumentError: argument -c/--color: invalid choice: 'NADA' (choose from 'yellow', 'blue')
During handling of the above exception, another exception occurred:
Traceback (most recent call last): #(I deleted some lines)
File "/anaconda/lib/python3.5/argparse.py", line 2372, in exit
_sys.exit(status)
SystemExit: 2
</code></pre>
| 1 | 2016-08-18T22:04:31Z | 39,028,444 | <p>If you look in the error log, you can see that a <code>argparse.ArgumentError</code> is raised and not an <code>AttributeError</code>. your code should look like this:</p>
<pre><code>#!/usr/bin/env python3
import argparse
import unittest
from argparse import ArgumentError
class sweep_test_case(unittest.TestCase):
"""Tests that the merParse class works correctly"""
def setUp(self):
self.parser=argparse.ArgumentParser()
self.parser.add_argument(
"-c", "--color",
type=str,
choices=["yellow", "blue"],
required=True)
def test_required_unknown_TE(self):
"""Try to perform sweep on something that isn't an option.
Should return an attribute error if it fails.
This test incorrectly shows that the test passed, even though that must
not be true."""
args = ["--color", "NADA"]
try:
self.assertRaises(ArgumentError, self.parser.parse_args(args))
except SystemExit:
print("should give a false positive pass")
def test_required_unknown(self):
"""Try to perform sweep on something that isn't an option.
Should return an attribute error if it fails.
This test incorrectly shows that the test passed, even though that must
not be true."""
args = ["--color", "NADA"]
with self.assertRaises(ArgumentError):
self.parser.parse_args(args)
if __name__ == '__main__':
unittest.main()
</code></pre>
| 1 | 2016-08-18T22:26:33Z | [
"python",
"unit-testing",
"python-3.x",
"argparse",
"python-unittest"
] |
Using unittest to test argparse - exit errors | 39,028,204 | <p>Going off of <a href="http://stackoverflow.com/questions/5943249">Greg Haskin's answer in this question</a>, I tried to make a unittest to check that argparse is giving the appropriate error when I pass it some args that are not present in the <code>choices</code>. However, <code>unittest</code> generates a false positive using the <code>try/except</code> statement below.</p>
<p>In addition, when I make a test using just a <code>with assertRaises</code> statement, <code>argparse</code> forces the system exit and the program does not execute any more tests.</p>
<p>I would like to be able to have a test for this, but maybe it's redundant given that <code>argparse</code> exits upon error?</p>
<pre><code>#!/usr/bin/env python3
import argparse
import unittest
class sweep_test_case(unittest.TestCase):
"""Tests that the merParse class works correctly"""
def setUp(self):
self.parser=argparse.ArgumentParser()
self.parser.add_argument(
"-c", "--color",
type=str,
choices=["yellow", "blue"],
required=True)
def test_required_unknown_TE(self):
"""Try to perform sweep on something that isn't an option.
Should return an attribute error if it fails.
This test incorrectly shows that the test passed, even though that must
not be true."""
args = ["--color", "NADA"]
try:
self.assertRaises(argparse.ArgumentError, self.parser.parse_args(args))
except SystemExit:
print("should give a false positive pass")
def test_required_unknown(self):
"""Try to perform sweep on something that isn't an option.
Should return an attribute error if it fails.
This test incorrectly shows that the test passed, even though that must
not be true."""
args = ["--color", "NADA"]
with self.assertRaises(argparse.ArgumentError):
self.parser.parse_args(args)
if __name__ == '__main__':
unittest.main()
</code></pre>
<p>Errors:</p>
<pre><code>Usage: temp.py [-h] -c {yellow,blue}
temp.py: error: argument -c/--color: invalid choice: 'NADA' (choose from 'yellow', 'blue')
E
usage: temp.py [-h] -c {yellow,blue}
temp.py: error: argument -c/--color: invalid choice: 'NADA' (choose from 'yellow', 'blue')
should give a false positive pass
.
======================================================================
ERROR: test_required_unknown (__main__.sweep_test_case)
Try to perform sweep on something that isn't an option.
----------------------------------------------------------------------
Traceback (most recent call last): #(I deleted some lines)
File "/Users/darrin/anaconda/lib/python3.5/argparse.py", line 2310, in _check_value
raise ArgumentError(action, msg % args)
argparse.ArgumentError: argument -c/--color: invalid choice: 'NADA' (choose from 'yellow', 'blue')
During handling of the above exception, another exception occurred:
Traceback (most recent call last): #(I deleted some lines)
File "/anaconda/lib/python3.5/argparse.py", line 2372, in exit
_sys.exit(status)
SystemExit: 2
</code></pre>
| 1 | 2016-08-18T22:04:31Z | 39,029,904 | <p>While the parser may raise an ArgumentError during parsing a specific argument, that is normally trapped, and passed to <code>parser.error</code> and <code>parse.exit</code>. The result is that the usage is printed, along with an error message, and then <code>sys.exit(2)</code>.</p>
<p>So <code>asssertRaises</code> is not a good way of testing for this kind of error in <code>argparse</code>. The unittest file for the module, <code>test/test_argparse.py</code> has an elaborate way of getting around this, the involves subclassing the <code>ArgumentParser</code>, redefining its <code>error</code> method, and redirecting output.</p>
<p><code>parser.parse_known_args</code> (which is called by <code>parse_args</code>) ends with:</p>
<pre><code> try:
namespace, args = self._parse_known_args(args, namespace)
if hasattr(namespace, _UNRECOGNIZED_ARGS_ATTR):
args.extend(getattr(namespace, _UNRECOGNIZED_ARGS_ATTR))
delattr(namespace, _UNRECOGNIZED_ARGS_ATTR)
return namespace, args
except ArgumentError:
err = _sys.exc_info()[1]
self.error(str(err))
</code></pre>
<p>=================</p>
<p>How about this test (I've borrowed several ideas from <code>test_argparse.py</code>:</p>
<pre><code>import argparse
import unittest
class ErrorRaisingArgumentParser(argparse.ArgumentParser):
def error(self, message):
#print(message)
raise ValueError(message) # reraise an error
class sweep_test_case(unittest.TestCase):
"""Tests that the Parse class works correctly"""
def setUp(self):
self.parser=ErrorRaisingArgumentParser()
self.parser.add_argument(
"-c", "--color",
type=str,
choices=["yellow", "blue"],
required=True)
def test_required_unknown(self):
"""Try to perform sweep on something that isn't an option.
Should pass"""
args = ["--color", "NADA"]
with self.assertRaises(ValueError) as cm:
self.parser.parse_args(args)
print('msg:',cm.exception)
self.assertIn('invalid choice', str(cm.exception))
if __name__ == '__main__':
unittest.main()
</code></pre>
<p>with a run:</p>
<pre><code>1931:~/mypy$ python3 stack39028204.py
msg: argument -c/--color: invalid choice: 'NADA' (choose from 'yellow', 'blue')
.
----------------------------------------------------------------------
Ran 1 test in 0.002s
OK
</code></pre>
| 1 | 2016-08-19T01:45:00Z | [
"python",
"unit-testing",
"python-3.x",
"argparse",
"python-unittest"
] |
Using unittest to test argparse - exit errors | 39,028,204 | <p>Going off of <a href="http://stackoverflow.com/questions/5943249">Greg Haskin's answer in this question</a>, I tried to make a unittest to check that argparse is giving the appropriate error when I pass it some args that are not present in the <code>choices</code>. However, <code>unittest</code> generates a false positive using the <code>try/except</code> statement below.</p>
<p>In addition, when I make a test using just a <code>with assertRaises</code> statement, <code>argparse</code> forces the system exit and the program does not execute any more tests.</p>
<p>I would like to be able to have a test for this, but maybe it's redundant given that <code>argparse</code> exits upon error?</p>
<pre><code>#!/usr/bin/env python3
import argparse
import unittest
class sweep_test_case(unittest.TestCase):
"""Tests that the merParse class works correctly"""
def setUp(self):
self.parser=argparse.ArgumentParser()
self.parser.add_argument(
"-c", "--color",
type=str,
choices=["yellow", "blue"],
required=True)
def test_required_unknown_TE(self):
"""Try to perform sweep on something that isn't an option.
Should return an attribute error if it fails.
This test incorrectly shows that the test passed, even though that must
not be true."""
args = ["--color", "NADA"]
try:
self.assertRaises(argparse.ArgumentError, self.parser.parse_args(args))
except SystemExit:
print("should give a false positive pass")
def test_required_unknown(self):
"""Try to perform sweep on something that isn't an option.
Should return an attribute error if it fails.
This test incorrectly shows that the test passed, even though that must
not be true."""
args = ["--color", "NADA"]
with self.assertRaises(argparse.ArgumentError):
self.parser.parse_args(args)
if __name__ == '__main__':
unittest.main()
</code></pre>
<p>Errors:</p>
<pre><code>Usage: temp.py [-h] -c {yellow,blue}
temp.py: error: argument -c/--color: invalid choice: 'NADA' (choose from 'yellow', 'blue')
E
usage: temp.py [-h] -c {yellow,blue}
temp.py: error: argument -c/--color: invalid choice: 'NADA' (choose from 'yellow', 'blue')
should give a false positive pass
.
======================================================================
ERROR: test_required_unknown (__main__.sweep_test_case)
Try to perform sweep on something that isn't an option.
----------------------------------------------------------------------
Traceback (most recent call last): #(I deleted some lines)
File "/Users/darrin/anaconda/lib/python3.5/argparse.py", line 2310, in _check_value
raise ArgumentError(action, msg % args)
argparse.ArgumentError: argument -c/--color: invalid choice: 'NADA' (choose from 'yellow', 'blue')
During handling of the above exception, another exception occurred:
Traceback (most recent call last): #(I deleted some lines)
File "/anaconda/lib/python3.5/argparse.py", line 2372, in exit
_sys.exit(status)
SystemExit: 2
</code></pre>
| 1 | 2016-08-18T22:04:31Z | 39,029,963 | <p>If you look into the source code of argparse, in <code>argparse.py</code>, around line 1732 (my python version is 3.5.1), there is a method of <code>ArgumentParser</code> called <code>parse_known_args</code>. The code is:</p>
<pre><code># parse the arguments and exit if there are any errors
try:
namespace, args = self._parse_known_args(args, namespace)
if hasattr(namespace, _UNRECOGNIZED_ARGS_ATTR):
args.extend(getattr(namespace, _UNRECOGNIZED_ARGS_ATTR))
delattr(namespace, _UNRECOGNIZED_ARGS_ATTR)
return namespace, args
except ArgumentError:
err = _sys.exc_info()[1]
self.error(str(err))
</code></pre>
<p>So, the <code>ArgumentError</code> will be swallowed by <code>argparse</code>, and exit with an error code. If you want to test this anyway, the only way I could think out is mocking <code>sys.exc_info</code>.</p>
| 0 | 2016-08-19T01:52:57Z | [
"python",
"unit-testing",
"python-3.x",
"argparse",
"python-unittest"
] |
Send scheduled emails with pyramid_mailer and apscheduler | 39,028,210 | <p>I've tried getting this to work but there must be a better way, any input is welcome.</p>
<p>I'm trying to send scheduled emails in my python pyramid app using pyramid_mailer (settings stored in .ini file), and apscheduler to set the schedule.</p>
<p>I also use the SQLAlchemyJobStore so jobs can be restarted if the app restarts.</p>
<pre><code>jobstores = {
'default': SQLAlchemyJobStore(url='mysql://localhost/lgmim')
}
scheduler = BackgroundScheduler(jobstores=jobstores)
@view_config(route_name='start_email_schedule')
def start_email_schedule(request):
# add the job and start the scheduler
scheduler.add_job(send_scheduled_email, 'interval', [request], weeks=1)
scheduler.start()
return HTTPOk()
def send_scheduled_email(request):
# compile message and recipients
# send mail
send_mail(request, subject, recipients, message)
def send_mail(request, subject, recipients, body):
mailer = request.registry['mailer']
message = Message(subject=subject,
recipients=recipients,
body=body)
mailer.send_immediately(message, fail_silently=False)
</code></pre>
<p>This is as far as I've gotten, now I'm getting an error, presumably because it can't pickle the request.</p>
<pre><code>PicklingError: Can't pickle <type 'function'>: attribute lookup __builtin__.function failed
</code></pre>
<p>Using <code>pyramid.threadlocal.get_current_registry().settings</code> to get the mailer works the first time, but thereafter I get an error. I'm advised not to use it in any case.</p>
<p>What else can I do?</p>
| 2 | 2016-08-18T22:05:10Z | 39,071,976 | <p>Generally, you cannot pickle <code>request</code> object as it contains references to things like open sockets and other liveful objects. </p>
<p>Some useful patterns here are that</p>
<ul>
<li><p>You pregenerate email id in the database and then pass id (int, UUID) over scheduler</p></li>
<li><p>You generate template context (JSON dict) and then pass that over the scheduler and render the template inside a worker</p></li>
<li><p>You do all database fetching and related inside a scheduler and don't pass any arguments</p></li>
</ul>
<p>Specifically, the problem how to generate a faux <code>request</code> object inside a scheduler can be solved like this:</p>
<pre><code>from pyramid import scripting
from pyramid.paster import bootstrap
def make_standalone_request():
bootstrap_env = bootstrap("your-pyramid-config.ini")
app = bootstrap_env["app"]
pyramid_env = scripting.prepare(registry=bootstrap_env["registry"])
request = pyramid_env["request"]
# Note that request.url will be always dummy,
# so if your email refers to site URL, you need to
# resolve request.route_url() calls before calling the scheduler
# or read the URLs from settings
return request
</code></pre>
<p><a href="https://websauna.org/narrative/misc/task.html" rel="nofollow">Some more inspiration can be found here (disclaimer: I am the author).</a></p>
| 2 | 2016-08-22T05:34:38Z | [
"python",
"pyramid",
"mailer",
"apscheduler"
] |
Tensorflow execution in a virtual machine with no GPUs | 39,028,218 | <p>I had a question regarding tensorflow that is, somewhat critical to what task I'm trying to accomplish.</p>
<p>My scenario is as follows,
1. I have a tensorflow script that has been set-up, trained and tested. It is working well.</p>
<ol start="2">
<li><p>The training and testing was done on a devBox with 2 Titan X cards. </p>
<ol start="3">
<li>We need to now port this system to a live-pilot testing stage and are required to deploy it on a virtual-machine with Ubuntu 14.04 running atop of it.</li>
</ol></li>
</ol>
<p>Here lies the problem - A vm will not have access to underlying GPUs and must validate the incoming data in CPU only mode. My question,</p>
<ol>
<li>Will the absence of GPUs hinder the validation process of my ML system? Does tensorflow, by default use GPUs for CNN computation and will the absence of a GPU affect the execution?</li>
<li>How do I run my script in CPU only mode?</li>
<li>Will setting CUDA_VISIBLE_DEVICES to none help with the validation in a CPU-only mode after the system has been trained on GPU boxes?</li>
</ol>
<p>I'm sorry if this comes across as a noob question but I am new to TF and any advice would be much appreciated. Please let me know if you need any further information about my scenario.</p>
| 0 | 2016-08-18T22:05:50Z | 39,028,775 | <p>Testing with <code>CUDA_VISIBLE_DEVICES</code> set to empty string will make sure that you don't have anything that depends on GPU being present, and theoretically it should be enough. In practice, there are some bugs in GPU codepath which can get triggered when there are no GPUs (like <a href="https://github.com/tensorflow/tensorflow/issues/2940#issuecomment-238952433" rel="nofollow">this one</a>), so you want to make sure your GPU software environment (CUDA version) is the same.</p>
<p>Alternatively, you could compile TensorFlow without GPU support (<code>bazel build -c opt tensorflow</code>), this way you don't have to worry about matching CUDA environments or setting <code>CUDA_VISIBLE_DEVICES</code></p>
| 0 | 2016-08-18T23:03:52Z | [
"python",
"machine-learning",
"tensorflow",
"conv-neural-network"
] |
Pandas DataFrame: Compute values based on column min/max | 39,028,237 | <p>I have an NxN DataFrame with values I need to scale to a range of values that signify importance, where 0 is irrelevant and 3 is very important.</p>
<p>The formula I'm using to scale of course depends on the min and max values in each column, which are different for each column: Col A's range could be 1-12 while Col B's range could be 1M to 45M.</p>
<p>Here's the formula I'm using.</p>
<p><code>min_importance + ((max_importance - min_importance) / (max_spec_value - min_spec_value)) * (spec_value - min_spec_value)</code></p>
<p>How do I create a new DataFrame or dictionary with scaled values for each column, while retaining the index, which is needed later for identification?</p>
<p>I tried creating a function with the above formula, and using apply() to call the function for each row, but I can't pass column min/max to the function, so that doesn't work.</p>
<p>DataFrame sample ("Body: retail price" and "Body: sensor resolution" are columns):</p>
<pre> Body: retail price Body: sensor resolution
Body name
Nikon D500 2000.00 20668416
Nikon D7000 1200.00 16084992
Sony Alpha 7R II 3199.00 42177408
Canon EOS 5D Mark III 3499.00 22118400
Canon 7D Mark II 1799.00 19961856
iPhone 6 (front) 699.00 1000000
iPhone 6 (rear) 699.00 7990272
Fujifilm X-T1 1299.95 15980544
Fujifilm X-T2 1599.00 24000000</pre>
| 0 | 2016-08-18T22:07:58Z | 39,042,038 | <p>min-max normalization can be done with:</p>
<pre><code>(df - df.min()) / (df.max() - df.min())
Out:
Body: retail price Body: sensor resolution
Body name
Nikon D500 0.464643 0.477651
Nikon D7000 0.178929 0.366341
Sony Alpha 7R II 0.892857 1.000000
Canon EOS 5D Mark III 1.000000 0.512864
Canon 7D Mark II 0.392857 0.460492
iPhone 6 (front) 0.000000 0.000000
iPhone 6 (rear) 0.000000 0.169760
Fujifilm X-T1 0.214625 0.363805
Fujifilm X-T2 0.321429 0.558559
</code></pre>
<p>You don't need apply. <code>df.min()</code> will return a series and when doing <code>df - df.min()</code> pandas will subtract corresponding column's minimum value from each value. This is called broadcasting which makes the task easier.</p>
<p>If you have different importance levels for each column, best thing to do would be to store it in a dataframe:</p>
<pre><code>importances = pd.DataFrame({'max_imp': [1, 3], 'min_imp': [0, 0]}, index= df.columns)
importances
Out:
max_imp min_imp
Body: retail price 1 0
Body: sensor resolution 3 0
</code></pre>
<p>Now with the same principle, you can adjust your formula:</p>
<pre><code>importances['min_imp'] + ((importances['max_imp'] - importances['min_imp']) / (df.max() - df.min())) * (df - df.min())
Out:
Body: retail price Body: sensor resolution
Body name
Nikon D500 0.464643 1.432952
Nikon D7000 0.178929 1.099024
Sony Alpha 7R II 0.892857 3.000000
Canon EOS 5D Mark III 1.000000 1.538591
Canon 7D Mark II 0.392857 1.381475
iPhone 6 (front) 0.000000 0.000000
iPhone 6 (rear) 0.000000 0.509280
Fujifilm X-T1 0.214625 1.091415
Fujifilm X-T2 0.321429 1.675676
</code></pre>
<p>Note that the index of <code>importances</code> and the columns of the actual dataframe should match. In this example, the first column's range is converted to [0-1] and the second column's range to [0-3].</p>
| 0 | 2016-08-19T14:52:20Z | [
"python",
"dataframe"
] |
Why does del (x) with parentheses around the variable name work? | 39,028,249 | <p>Why does this piece of code work the way it does?</p>
<pre><code>x = 3
print(dir()) #output indicates that x is defined in the global scope
del (x)
print(dir()) #output indicates that x is not defined in the global scope
</code></pre>
<p>My understanding is that <code>del</code> is a keyword in Python, and what follows <code>del</code> should be a name. <code>(name)</code> is not a name. Why does the example seem to show that <code>del (name)</code> works the same as <code>del name</code>?</p>
| 0 | 2016-08-18T22:09:21Z | 39,028,426 | <p>The definition of the <a href="https://docs.python.org/3/reference/simple_stmts.html#the-del-statement" rel="nofollow"><code>del</code> statemant</a> is:</p>
<blockquote>
<p>del_stmt ::= "del" target_list</p>
</blockquote>
<p>and from the definition of <a href="https://docs.python.org/3/reference/simple_stmts.html#grammar-token-target_list" rel="nofollow"><code>target_list</code></a>:</p>
<blockquote>
<p>target_list ::= target ("," target)* [","] <br>
target ::= identifier
| "(" target_list ")" | "[" [target_list] "]"
| ... </p>
</blockquote>
<p>you can see that parentheses around the list of targets are allowed.</p>
<p>For example, if you define <code>x,y = 1,2</code> all of those are allowed and has the same affect:</p>
<pre><code>del x,y,
del (x,y)
del (x),[y]
del [x,(y)]
del ([x], (y))
</code></pre>
| 2 | 2016-08-18T22:25:00Z | [
"python"
] |
python: convert pywintyptes.datetime to datetime.datetime | 39,028,290 | <p>I am using pywin32 to read/write to an Excel file. I have some dates in Excel, stored in format yyyy-mm-dd hh:mm:ss. I would like to import those into Python as datetime.datetime objects. Here is the line of code I started with:</p>
<pre><code>prior_datetime = datetime.strptime(excel_ws.Cells(2, 4).Value, '%Y-%m-%d %H:%M:%S')
</code></pre>
<p>That didn't work. I got the error: </p>
<pre><code>strptime() argument 1 must be str, not pywintypes.datetime
</code></pre>
<p>I tried casting it to a string, like so:</p>
<pre><code>prior_datetime = datetime.strptime(str(excel_ws.Cells(2, 4).Value), '%Y-%m-%d %H:%M:%S')
</code></pre>
<p>That didn't work either. I got the error:</p>
<pre><code>ValueError: unconverted data remains: +00:00
</code></pre>
<p>So then I tried something a little different:</p>
<pre><code>prior_datetime = datetime.fromtimestamp(int(excel_ws.Cells(2, 4).Value))
</code></pre>
<p>Still no luck. Error:</p>
<pre><code>TypeError: a float is required.
</code></pre>
<p>Casting to a float didn't help. Nor integer. (Hey, I was desperate at this point.) </p>
<p>I might be looking in the wrong plce, but I'm having a terrible time finding any good documentation on pywin32 in general or pywintypes or pywintypes.datetime in particular.</p>
<p>Any help?</p>
| 1 | 2016-08-18T22:12:51Z | 39,028,464 | <p>So the problem is the <code>+00:00</code> timezone offset. <a href="https://stackoverflow.com/questions/20194496/iso-to-datetime-object-z-is-a-bad-directive">Looking into this there's not an out of the box solution for Python</a></p>
<pre><code>datetime.datetime.strptime("2016-04-01 17:29:25+00:00", '%Y-%m-%d %H:%M:%S %z')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/_strptime.py", line 324, in _strptime
(bad_directive, format))
ValueError: 'z' is a bad directive in format '%Y-%m-%d %H:%M:%S %z'
</code></pre>
<p>One band-aid solution is to strip the timezone but that feels pretty gross.</p>
<pre><code>datetime.datetime.strptime("2016-04-01 17:29:25+00:00".rstrip("+00:00"), '%Y-%m-%d %H:%M:%S')
datetime.datetime(2016, 4, 1, 17, 29, 25)
</code></pre>
<p>Looking around it looks like (if you can use a third party library) <code>dateutil</code> solves this issue and is nicer to use then <code>datetime.strptime</code>.</p>
<h1>On Commandline</h1>
<pre><code>pip install python-dateutil
</code></pre>
<h1>code</h1>
<pre><code>>>> import dateutil.parser
>>> dateutil.parser.parse("2016-04-01 17:29:25+00:00")
datetime.datetime(2016, 4, 1, 17, 29, 25, tzinfo=tzutc())
</code></pre>
| 1 | 2016-08-18T22:28:38Z | [
"python",
"excel",
"pywin32"
] |
Mismatch in feature_names in xgboost sklearn during multi-class text classification | 39,028,385 | <p>I am trying to perform a multiclass text classification using xgboost in python (sklearn edition), but at times it errors out telling me that there is a mismatch in feature names. The odd thing is that at times it does work (perhaps 1 out of 4 times), but the uncertainty is making it difficult for me to rely on this solution for now, even though it is showing encouraging results without even doing any real pre-processing.</p>
<p>I have provided some illustrative sample data in the code that would be similar to what I'd be using. The code I currently have is as follows:</p>
<p><strong>Updated code that reflects maxymoo's suggestion</strong></p>
<pre><code>import xgboost as xgb
import numpy as np
from sklearn.cross_validation import KFold, train_test_split
from sklearn.metrics import accuracy_score
from sklearn.feature_extraction.text import CountVectorizer
rng = np.random.RandomState(31337)
y = np.array([0, 1, 2, 1, 0, 3, 1, 2, 3, 0])
X = np.array(['milk honey bear bear honey tigger',
'tom jerry cartoon mouse cat cat WB',
'peppa pig mommy daddy george peppa pig pig',
'cartoon jerry tom silly',
'bear honey hundred year woods',
'ben holly elves fairies gaston fairy fairies castle king',
'tom and jerry mouse WB',
'peppa pig daddy pig rebecca rabit',
'elves ben holly little kingdom king big people',
'pot pot pot pot jar winnie pooh disney tigger bear'])
xgb_model = make_pipeline(CountVectorizer(), xgb.XGBClassifier())
kf = KFold(y.shape[0], n_folds=2, shuffle=True, random_state=rng)
for train_index, test_index in kf:
xgb_model.fit(X[train_index],y[train_index])
predictions = xgb_model.predict(X[test_index])
actuals = y[test_index]
accuracy = accuracy_score(actuals, predictions)
print accuracy
</code></pre>
<p>The error I tend to get is as follows:</p>
<pre><code>Traceback (most recent call last):
File "main.py", line 95, in <module>
predictions = xgb_model.predict(X[test_index])
File "//anaconda/lib/python2.7/site-packages/xgboost-0.6-py2.7.egg/xgboost/sklearn.py", line 465, in predict
ntree_limit=ntree_limit)
File "//anaconda/lib/python2.7/site-packages/xgboost-0.6-py2.7.egg/xgboost/core.py", line 939, in predict
self._validate_features(data)
File "//anaconda/lib/python2.7/site-packages/xgboost-0.6-py2.7.egg/xgboost/core.py", line 1179, in _validate_features
data.feature_names))
ValueError: feature_names mismatch: ['f0', 'f1', 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'f9', 'f10', 'f11', 'f12', 'f13', 'f14', 'f15', 'f16', 'f17', 'f18', 'f19', 'f20', 'f21', 'f22', 'f23', 'f24', 'f25', 'f26'] ['f0', 'f1', 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'f9', 'f10', 'f11', 'f12', 'f13', 'f14', 'f15', 'f16', 'f17', 'f18', 'f19', 'f20', 'f21', 'f22', 'f23', 'f24']
expected f26, f25 in input data
</code></pre>
<p>Any pointers would be really appreciated!</p>
| 1 | 2016-08-18T22:21:33Z | 39,030,902 | <p>You need to make sure that you are only scoring the model with features that it has been trained on. The usual way to do this is to use a <code>Pipeline</code> to package the vectoriser and the model together. That way they will both be trained at the same time, and if a new feature is encountered in the test data, the vectoriser will just ignore it (also note that you don't need to recreate the model at each stage of the cross-validation, you just initialise it once and then refit it at each fold):</p>
<pre><code>from sklearn.pipeline import make_pipeline
xgb_model = make_pipeline(CountVectoriser(), xgb.XGBClassifier())
for train_index, test_index in kf:
xgb_model.fit(X[train_index],y[train_index])
predictions = xgb_model.predict(X[test_index])
actuals = y[test_index]
accuracy = accuracy_score(actuals, predictions)
print accuracy
</code></pre>
| 0 | 2016-08-19T04:00:43Z | [
"python",
"machine-learning",
"scikit-learn",
"text-classification",
"xgboost"
] |
Difference between UDP server and UDP client: sock.bind((host, port)) is on the client or server side? | 39,028,505 | <p>The UDP server:</p>
<pre><code># -*- coding: utf-8 -*-
#!/usr/bin/python3
#server UDP
from socket import *
def main():
# Cria host e port number
host = ""
port = 5000
# Cria socket #UDP
server = socket(AF_INET, SOCK_DGRAM)
# Indica que o servidor foi iniciado
print("Servidor iniciado")
# Bloco infinito do servidor
while True:
# Recebe a data e o endereço da conexão
print("server.recvfrom(1024)",server.recvfrom(1024))
data, endereço = server.recvfrom(1024)
# Imprime as informações da conexão
print("Menssagem recebida de", str(endereço))
print("Recebemos do cliente:", str(data))
# Vamos mandar de volta a menssagem em eco
resposta = "Eco=>" + str(data)
server.sendto(data, endereço)
# Fechamos o servidor
server.close()
if __name__ == '__main__':
main()
</code></pre>
<p>The UDP client:</p>
<pre><code># -*- coding: utf-8 -*-
#!/usr/bin/python3
#client UDP
from socket import *
def main():
# Cria host e port number
host = "localhost"
port = 5000
# O servidor será um par endereço e port
server = (host, port)
# Criamos o socket
sock = socket(AF_INET, SOCK_DGRAM)
sock.bind((host, port))
# Vamos mandar mensagem enquanto a mensagem for diferente de sair (s)
msg = input("-> ")
while msg != 's':
# Mandamos a mensagem através da conexão
sock.sendto(msg.encode(), server)
# Recebemos uma resposta do servidor
data, endereco = sock.recvfrom(1024)
# Imprimimos a mensagem recebida
print("Recebida ->", str(data))
# Podemos mandar mais mensagens
msg = input("-> ")
# Fechamos a conexão
sock.close()
if __name__ == '__main__':
main()
</code></pre>
<p>The codes are working but I am not sure what is the server or the client: Difference between UDP server and UDP client: sock.bind((host, port)) is on the client or server side?</p>
| 1 | 2016-08-18T22:32:37Z | 39,065,914 | <p>As @VPfB answered, see: <a href="http://stackoverflow.com/questions/6189831/whats-the-purpose-of-using-sendto-recvfrom-instead-of-connect-send-recv-with-ud">What's the purpose of using sendto/recvfrom instead of connect/send/recv with UDP sockets?</a></p>
<p>The model server/client :</p>
<p>client is the part that iniciate the communication and server is the receiver one.</p>
<p>Client:</p>
<pre><code># -*- coding: utf-8 -*-
#!/usr/bin/python3
from socket import *
def main():
# Cria host e port number
host = "localhost"
port = 5000
# O servidor será um par endereço e port
server = (host, port)
# Criamos o socket
sock = socket(AF_INET, SOCK_DGRAM)
##sock.bind((host, port)) #server side
# Vamos mandar mensagem enquanto a mensagem for diferente de sair (s)
msg = input("-> ")
while msg != 's':
# Mandamos a mensagem através da conexão
sock.sendto(msg.encode(), server) #encode para enviar no formato de bytes
# Recebemos uma respota do servidor
data, endereco = sock.recvfrom(1024)
# Imprimimos a mensagem recebida
print("Recebida ->", str(data))
# Podemos mandar mais mensagens
msg = input("-> ")
# Fechamos a conexão
sock.close()
if __name__ == '__main__':
main()
</code></pre>
<p>Server:</p>
<pre><code># -*- coding: utf-8 -*-
#!/usr/bin/python3
from socket import *
def main():
# Cria host e port number
host = ""
port = 5000
# Cria socket #UDP
server = socket(AF_INET, SOCK_DGRAM)
server.bind((host, port))
# Indica que o servidor foi iniciado
print("Servidor iniciado")
# Bloco infinito do servidor
while True:
# Recebe a data e o endereço da conexão
print("server.recvfrom(1024)",server.recvfrom(1024))
data, endereço = server.recvfrom(1024)
# Imprime as informações da conexão
print("Menssagem recebida de", str(endereço))
print("Recebemos do cliente:", str(data))
# Vamos mandar de volta a menssagem em eco
resposta = "Eco=>" + str(data)
server.sendto(data, endereço)
# Fechamos o servidor
server.close()
if __name__ == '__main__':
main()
</code></pre>
| 1 | 2016-08-21T15:34:06Z | [
"python",
"python-3.x"
] |
2to3 - how to keep newline characters from input file? | 39,028,517 | <p>I'm attempting to run <code>2to3</code> on Windows machine where *.py files has Unix-style end-line characters. Running <code>2to3</code> modifies newline characters in output file.</p>
<p>MCVE:</p>
<p><strong>print2.py content before</strong></p>
<pre><code>print "Hello, world!"\n
</code></pre>
<p>Executed command:</p>
<pre><code>2to3 print2.py -w -n
</code></pre>
<p><strong>print2.py content after</strong></p>
<pre><code>print("Hello, world!")\r\n
</code></pre>
<p><strong>Expected content:</strong></p>
<pre><code>print("Hello, world!")\n
</code></pre>
<p>Is it possible to keep old newline characters when <code>2to3</code> conversion is performed?</p>
| 2 | 2016-08-18T22:33:59Z | 39,028,615 | <p>On Windows, the system line separator is <code>\r\n</code>, as we can see in <code>os.py</code>:</p>
<pre><code>if 'posix' in _names:
...
linesep = '\n'
...
elif 'nt' in _names:
...
linesep = '\r\n'
...
</code></pre>
<p>This line separator is used in <code>lib2to3.refactor</code>:</p>
<pre><code>def _to_system_newlines(input):
if os.linesep != "\n":
return input.replace(u"\n", os.linesep)
else:
return input
</code></pre>
<p>So to preserve line separators with the 2to3 script, it should be enough to replace line <code>return input.replace(u"\n", os.linesep)</code> by <code>return input</code> in the above function.</p>
| 0 | 2016-08-18T22:46:20Z | [
"python",
"python-3.x",
"python-2.x",
"2to3"
] |
2to3 - how to keep newline characters from input file? | 39,028,517 | <p>I'm attempting to run <code>2to3</code> on Windows machine where *.py files has Unix-style end-line characters. Running <code>2to3</code> modifies newline characters in output file.</p>
<p>MCVE:</p>
<p><strong>print2.py content before</strong></p>
<pre><code>print "Hello, world!"\n
</code></pre>
<p>Executed command:</p>
<pre><code>2to3 print2.py -w -n
</code></pre>
<p><strong>print2.py content after</strong></p>
<pre><code>print("Hello, world!")\r\n
</code></pre>
<p><strong>Expected content:</strong></p>
<pre><code>print("Hello, world!")\n
</code></pre>
<p>Is it possible to keep old newline characters when <code>2to3</code> conversion is performed?</p>
| 2 | 2016-08-18T22:33:59Z | 39,094,236 | <p>Since there seems to be no standard way to change this behavior in command line usage, I've prepared very simple Python script, which runs code and patches unwanted behavior.</p>
<p>Here's an example for <code>python modernize</code>, but any 2to3-based tool will do just fine.</p>
<pre><code># to access function to patch
import lib2to3.refactor
# actual main
import libmodernize.main
# convert str to list of args, not mandatory
import shlex
# patch problematic function, as suggested by @mfripp
lib2to3.refactor._to_system_newlines = lambda input: input
args = shlex.split("-w -n src") # prepare args
libmodernize.main.main(args) # pass args to main, equivalent of running cmdline tool
</code></pre>
| 1 | 2016-08-23T06:53:59Z | [
"python",
"python-3.x",
"python-2.x",
"2to3"
] |
How to use multiple nodes in a cluster to process huge data - python | 39,028,535 | <p>I have a 15 node cluster which I am planning to use for processing data in the range of 90 million rows(Hive table) / per day. The data is present in one of the nodes as a hive table and I am using something like the following command,</p>
<pre><code>with hive.connect(host = 'hostname of that node', port= 10000, authMechanism='LDAP', user='username', password='pass') as conn:
with conn.cursor() as cur:
cur.execute('select * from tablename')
do_not_touch_this_data = pd.DataFrame(cur.fetch())
</code></pre>
<p>The problem here is the query is running for more than 8 hours to load all the data into python. This is because the package takes all the data and loads it into the memory of this particular node. Even after loading, I am not able to run even basic commands like count / EDA. It is taking a lot of time for each command. This is because 128 GB RAM of this particular node in the 15 node cluster is overloaded. </p>
<p>I want to make use of other nodes memory as well in order to read / process / do EDA with the data. Can anybody suggest a way to use these nodes in python, so that, the commands would run much faster and I would be able to use all the nodes? I am a beginner to distributed computing and I am guessing there should be a way to make use of all the nodes. Also whether reading all the data into python memory is a good practice?</p>
<p>Thanks for the help</p>
| 0 | 2016-08-18T22:35:42Z | 39,174,021 | <p>Distributed systems is a large and complex topic that's best left to experts. You're using Pyhon, Pandas, and Hive. You should just switch to Spark, which has its own <code>DataFrame</code> abstraction similar to Pandas and supports reading from Hive tables but will handle distributing the data across your servers for you. You should be able to easily translate any operations you're doing in Pandas directly to Spark.</p>
| 1 | 2016-08-26T20:12:32Z | [
"python",
"python-2.7",
"hadoop",
"hive",
"distributed-computing"
] |
Python Scrabble challenge find valid words | 39,028,548 | <p>I'm trying to complete a python project that basically takes an input and goes through a list of valid scrabble words and determines which of those words can be made given the input.</p>
<p>The first part was somewhat easy, but the part that actually matters is giving me issues.</p>
<p>Here's what I have so far:</p>
<pre><code>import argparse
import sys
"""
Step 1: Get input from the user
"""
parser = argparse.ArgumentParser()
parser.add_argument("rack", type=str, help = "letters on the rack (no spaces)")
args = parser.parse_args()
rack = args.rack
rack = rack.upper()
rack = sorted(rack)
"""
Step 2: Open the sowpods.txt file, read the contents and turn it into a list
"""
def file_len(fname):
with open(fname) as f:
for i, l in enumerate(f):
pass
return i + 1
scores = {"a": 1, "c": 3, "b": 3, "e": 1, "d": 2, "g": 2,
"f": 4, "i": 1, "h": 4, "k": 5, "j": 8, "m": 3,
"l": 1, "o": 1, "n": 1, "q": 10, "p": 3, "s": 1,
"r": 1, "u": 1, "t": 1, "w": 4, "v": 4, "y": 4,
"x": 8, "z": 10}
file = "sowpods.txt"
length = file_len(file)
file = open("sowpods.txt", 'r')
file_list = list(file)
for i in range(length):
value = file_list[i]
value = value.rstrip('\n')
file_list[i] = value
"""
Step 3: Find valid words
"""
#for x in range(len(file_list)):
for x in range(82980,83000):
tmp = rack
test = file_list[x]
pos = []
if len(test) > len(tmp):
break
else:
for y in range(len(test)):
letter = test[y]
if letter in tmp[y:(len(tmp))]:
pos.append(letter)
print(pos)
</code></pre>
<p>I'm sure it's very messy as I haven't programmed in a while, but I just want to figure out the part where the program checks for validity. Right now, the loop goes through a range where I know there are words that can be made from the rack but I'm stuck. I've looked at <a href="http://stackoverflow.com/questions/5485654/how-can-this-python-scrabble-word-finder-be-made-faster">this</a> post on some help, but to be honest, I'm not really sure what's going on.</p>
<p>I may be going a little over my head here, but I'd still like to figure this out.</p>
| 0 | 2016-08-18T22:36:29Z | 39,028,740 | <p>The easiest way to check if words are valid is to use a <code>collections.Counter</code>. You take the occurrences of each letter in the rack, and the occurrences of each letter for each scrabble word then take the difference. If there's nothing left of the scrabble word after removing the letters from the rack, then you can make the scrabble word.</p>
<p>Example code (use the dictionary provided instead of a system one):</p>
<pre><code>from collections import Counter
with open('/usr/share/dict/words') as fin:
lines = (word.strip().upper() for word in fin)
words = [(word, Counter(word)) for word in lines]
rack = Counter('AEDTUMS')
for scrabble_word, letter_count in words:
# Using length here to limit output for example purposes
if len(scrabble_word) >= 6 and not (letter_count - rack):
print(scrabble_word)
</code></pre>
<p>Will give you:</p>
<pre><code>MEDUSA
AMUSED
SAUTED
</code></pre>
| 1 | 2016-08-18T23:00:04Z | [
"python",
"python-3.x"
] |
Change a parent variable in subclass, then use new value in parent class? | 39,028,550 | <p>I'm just getting to grips with python, and am currently trying to change the value of a Parent class variable using a subclass method. A basic example of my code is below. </p>
<pre><code>from bs4 import BeautifulSoup
import requests
import urllib.request as req
class Parent(object):
url = "http://www.google.com"
r = requests.get(url)
soup = BeautifulSoup(r.content, "lxml")
print(url)
def random_method(self):
print(Parent.soup.find_all())
class Child(Parent):
def set_url(self):
new_url = input("Please enter a URL: ")
request = req.Request(new_url)
response = req.urlopen(request)
Parent.url = new_url
def print_url(self):
print(Parent.url)
</code></pre>
<p>If I run the methods, the outputs are as follows.</p>
<pre><code>run = Child()
run.Parent()
>>> www.google.com
run.set_url()
>>> Please enter a url: www.thisismynewurl.com
run.print_url()
>>> www.thisismynewurl.com
run.random_method()
>>> #Prints output for www.google.com
</code></pre>
<p>Can anyone explain why I can get the new url printing when I run print_url, but if I try and use it in another method, it reverts to the old value?</p>
| 0 | 2016-08-18T22:36:45Z | 39,028,575 | <p>Because when you use <code>Parent.url</code> it uses the static value set inside the class Parent, not the value from the instance of the class.</p>
| 0 | 2016-08-18T22:40:53Z | [
"python"
] |
Change a parent variable in subclass, then use new value in parent class? | 39,028,550 | <p>I'm just getting to grips with python, and am currently trying to change the value of a Parent class variable using a subclass method. A basic example of my code is below. </p>
<pre><code>from bs4 import BeautifulSoup
import requests
import urllib.request as req
class Parent(object):
url = "http://www.google.com"
r = requests.get(url)
soup = BeautifulSoup(r.content, "lxml")
print(url)
def random_method(self):
print(Parent.soup.find_all())
class Child(Parent):
def set_url(self):
new_url = input("Please enter a URL: ")
request = req.Request(new_url)
response = req.urlopen(request)
Parent.url = new_url
def print_url(self):
print(Parent.url)
</code></pre>
<p>If I run the methods, the outputs are as follows.</p>
<pre><code>run = Child()
run.Parent()
>>> www.google.com
run.set_url()
>>> Please enter a url: www.thisismynewurl.com
run.print_url()
>>> www.thisismynewurl.com
run.random_method()
>>> #Prints output for www.google.com
</code></pre>
<p>Can anyone explain why I can get the new url printing when I run print_url, but if I try and use it in another method, it reverts to the old value?</p>
| 0 | 2016-08-18T22:36:45Z | 39,028,583 | <pre><code>class Parent(object):
url = "http://www.google.com"
r = requests.get(url)
soup = BeautifulSoup(r.content, "lxml")
print(url)
</code></pre>
<p>The code to assign the <code>soup</code> is run once, at time of class <em>definition</em>. </p>
<p>Therefore no changes to <code>Parent.url</code> will be reflected in calls to the <code>random_method</code>, because the soup is already collected. </p>
| 0 | 2016-08-18T22:42:08Z | [
"python"
] |
TypeError: __init__() got an unexpected keyword argument 'columns' | 39,028,568 | <p>I am trying to create a plugin in wxpython and running into below error,can any one help understand why I am running into this error and how to fix this?</p>
<pre><code>import wx
from wx.lib.agw import ultimatelistctrl as ULC
class TestFrame(wx.App):
def __init__(self):
wx.App.__init__(self)
APPNAME = 'plugin'
self.frame = wx.Frame(None, -1, size=wx.Size(600,700), title=APPNAME, style=wx.DEFAULT_FRAME_STYLE)
splitter = wx.SplitterWindow(self.frame, -1)
splitter.SetMinimumPaneSize(180)
panel1 = wx.Panel(splitter, size=wx.Size(-1, 300))
commands_panel = wx.Panel(panel1, -1)
package_panel = wx.Panel(commands_panel, -1)
self.view_listctrl = ULC.UltimateListCtrl(package_panel, id=-1,columns=2,selectionType=1)
package_vbox.Add(self.view_listctrl, 2, wx.EXPAND | wx.ALL, 5)
#view_listctrl = ULC.UltimateListCtrl(package_panel, id=-1)
itemCount = int('2')
for x in range(0,itemCount):
view_listctrl.SetItemKind(x, 2 , 1)
if __name__ == "__main__":
app = wx.App(False)
frame = TestFrame()
app.MainLoop()
</code></pre>
<p>Error:-</p>
<pre><code>Traceback (most recent call last):
File "listctr.py", line 26, in <module>
frame = TestFrame()
File "listctr.py", line 15, in __init__
self.view_listctrl = ULC.UltimateListCtrl(package_panel, id=-1,columns=2,selectionType=1)
TypeError: __init__() got an unexpected keyword argument 'columns'
</code></pre>
| -1 | 2016-08-18T22:40:12Z | 39,028,591 | <p>If you look at <a href="https://wxpython.org/Phoenix/docs/html/wx.lib.agw.ultimatelistctrl.UltimateListCtrl.html#wx.lib.agw.ultimatelistctrl.UltimateListCtrl.__init__" rel="nofollow">the documentation for the class's <code>__init__</code></a>, you can see that it has no <a href="https://docs.python.org/2/tutorial/controlflow.html#keyword-arguments" rel="nofollow">keyword argument</a> <code>columns</code>, and yet you're trying to pass one:</p>
<pre><code>self.view_listctrl = ULC.UltimateListCtrl(package_panel, id=-1,columns=2,selectionType=1)
</code></pre>
<p>It's basically exactly what the error message is telling you.</p>
| 1 | 2016-08-18T22:44:05Z | [
"python",
"wxpython"
] |
Find string greater than (x) in length | 39,028,590 | <p>How can I search through a variable and look for a word/string that is greater than 20 in length?</p>
<pre><code>var = '''this is my example and I want
no find the following
string jakjajsiwjsjwijaksjdfjaiwjalskdjfiajwlajfklajsdfwi
from this variable'''
</code></pre>
<p>Thanks</p>
| 0 | 2016-08-18T22:44:03Z | 39,028,673 | <p>Iterate through a list of the words using <code>split</code> and check the <code>len</code> of each word.</p>
<pre><code>for x in var.split():
if len(x) > 20:
print(x)
</code></pre>
<p>Or of course you can use a <a href="https://docs.python.org/3.4/tutorial/datastructures.html#list-comprehensions" rel="nofollow">list comprehension</a>.</p>
<pre><code>long_words = [x for x in var.split() if len(x) > 20]
print(long_words)
</code></pre>
| 2 | 2016-08-18T22:52:55Z | [
"python"
] |
Find string greater than (x) in length | 39,028,590 | <p>How can I search through a variable and look for a word/string that is greater than 20 in length?</p>
<pre><code>var = '''this is my example and I want
no find the following
string jakjajsiwjsjwijaksjdfjaiwjalskdjfiajwlajfklajsdfwi
from this variable'''
</code></pre>
<p>Thanks</p>
| 0 | 2016-08-18T22:44:03Z | 39,028,695 | <p>Using a list comprehension:</p>
<pre><code>print [x for x in var.split() if len(x) > 20]
</code></pre>
| 4 | 2016-08-18T22:55:22Z | [
"python"
] |
Find string greater than (x) in length | 39,028,590 | <p>How can I search through a variable and look for a word/string that is greater than 20 in length?</p>
<pre><code>var = '''this is my example and I want
no find the following
string jakjajsiwjsjwijaksjdfjaiwjalskdjfiajwlajfklajsdfwi
from this variable'''
</code></pre>
<p>Thanks</p>
| 0 | 2016-08-18T22:44:03Z | 39,028,711 | <pre><code>var_split = var.split(' ')
long_word = ''
for word in var_split:
if len(word) > 20:
long_word = word
</code></pre>
| 0 | 2016-08-18T22:56:31Z | [
"python"
] |
Unable to set psycopg2 autocommit after shp2pgsql import | 39,028,663 | <p>I am loading a shapefile into a postGIS database using shp2pgsql, piped via psql, wrapped in a python subprocess like this:</p>
<pre><code>command = "shp2pgsql -s 4269 -a -D -W LATIN1 file.shp table | psql -h host -d db -U user"
p=subprocess.Popen(command, shell=True)
p.communicate()
</code></pre>
<p>This works perfectly, with the following output:</p>
<pre><code>Loading objects...
Shapefile type: Polygon
Postgis type: MULTIPOLYGON[2]
SET
SET
BEGIN
COMMIT
</code></pre>
<p>There is no <code>END</code> statement, but to the best of my knowledge <code>END</code> and <code>COMMIT</code> are equivalent.</p>
<p>I then want to set <code>con.autocommit = True</code> for a psycopg2 connection to the same database. I get the following error:</p>
<pre><code>psycopg2.ProgrammingError: autocommit cannot be used inside a transaction
</code></pre>
<p>Why does psycopg2 report that a transaction is still in progress? Is there a different way I should be closing the psql transaction?</p>
<p>If I don't run the shp2pgsql subprocess command, <code>con.autocommit</code> executes successfully. Does shp2pgsql by default leave a transaction open somewhere? (<a href="http://www.bostongis.com/pgsql2shp_shp2pgsql_quickguide.bqg" rel="nofollow">http://www.bostongis.com/pgsql2shp_shp2pgsql_quickguide.bqg</a> doesn't suggest this)</p>
<p>No relevant entries exist in <code>pg_locks</code> to suggest a stalled/idle transaction. I do not use the psycopg2 connection object in the shp2pgsql function. And, if I recreate a new connection object</p>
<pre><code>con = psycopg2.connect(host=db_host, user=db_user, password=db_pass, database=db_name)
</code></pre>
<p>after the shp2pgsql function, <code>con.autocommit=True</code> works fine.</p>
<p>Edit: I of course can simply create the psycopg2 connection object after all shp2pgsql imports have finished, but this is not ideal in my code, and I'd rather understand what's happening.</p>
<p>Edit2: setting <code>con.autocommit=True</code> immediately after opening the psycopg2 connection, as opposed to later, bypasses this error.</p>
<p>Edit3: adding MWE</p>
<pre><code>import psycopg2
import os
import subprocess
from glob import glob
def vacuum(con, table=""):
autocommit_orig = con.autocommit
con.autocommit = True
with con.cursor() as cur:
cur.execute("VACUUM ANALYZE {};".format(table))
con.autocommit = autocommit_orig
def read_shapefile(path, tablename, srid="4269"):
command = "shp2pgsql -s {} -a -D -W LATIN1 {} {} | psql -h {} -d {} -U {}".format(srid, path, tablename, host, dbname, user)
p=subprocess.Popen(command, shell=True)
p.communicate()
def load_data(con, datapath):
dir = os.path.join(datapath,dataname)
shapefiles = glob(os.path.join(dir,"*.shp"))
for shapefile in shapefiles:
read_shapefile(shapefile, tablename)
if __name__ == "__main__":
con = psycopg2.connect(host=db_host, user=db_user, password=db_pass, database=db_name)
load_data(con, datapath)
vacuum(con, tablename)
</code></pre>
| 1 | 2016-08-18T22:51:56Z | 39,043,073 | <p>I can't see where this is happening, but according to <a href="http://initd.org/psycopg/docs/faq.html" rel="nofollow">this</a>, <a href="https://news.ycombinator.com/item?id=4269241" rel="nofollow">this</a>, and <a href="https://dba.stackexchange.com/questions/75395/are-transactions-in-postgresql-via-psycopg2-per-cursor-or-per-connection">this</a>, a transaction is begun the first time a command is sent to the database.</p>
<p>Transactions are per-connection, so <code>psql</code> shouldn't be tripping you up.</p>
<p>Following <a href="http://initd.org/psycopg/docs/faq.html" rel="nofollow">this advice</a>, my suggestion is that you stick a <code>con.rollback()</code> just before <code>con.autocommit=True</code> in your code. This will end the implicit transaction that's somehow got started. If you still have all the data you expect, than something's issued a <code>SELECT</code> command or similar read-only directive.</p>
<p>If you move the <code>con.rollback()</code> backwards from <code>con.autocommit=True</code> it will allow you to isolate where the transaction has begun without restructuring your code.</p>
<p>It is a guess, but perhaps when <code>psql</code> changes the database state psycopg2 begins a transaction at that time? I haven't found docs to support this hypothesis.</p>
| 0 | 2016-08-19T15:44:25Z | [
"python",
"postgresql",
"psycopg2",
"psql"
] |
How can I have Python read variables from a browser? | 39,028,675 | <p>On a school project, I am trying to code an AI to a simple game.
The problem is that the game is a javascript code running in a browser, while the AI is to be coded with Python.</p>
<p>I have isolated the useful real-time variables (like position, speed...) in the .js file, and I was able to output them in the browser debug console.</p>
<p>How could I have Python access those variables, in real time?</p>
<p>Edit: To make myself more clear, I am trying to beat Chromium's T-Rex Runner. Here is my modified version, showing useful informations in the console: <a href="https://github.com/17maxd/t-rex-runner/" rel="nofollow">https://github.com/17maxd/t-rex-runner/</a> .</p>
| 0 | 2016-08-18T22:53:20Z | 39,028,821 | <p>Two solutions come through my mind:</p>
<ol>
<li>The game's server code may expose API (e.g. REST API) via which your AI could query parameters and execute commands.</li>
<li>Make your AI interact with game just like human would using <a href="http://selenium-python.readthedocs.io/" rel="nofollow">selenium-python</a></li>
</ol>
<p>Using Selenium you can read state at any time by executing JS in browser like this (assuming your page includes jQuery):</p>
<pre class="lang-py prettyprint-override"><code>from selenium import webdriver
driver = webdriver.PhantomJS()
driver.get('http://example.com')
some_value = driver.execute_script('return $("#some_id").val();')
driver.close()
</code></pre>
| 0 | 2016-08-18T23:08:41Z | [
"javascript",
"python",
"browser"
] |
Flask-SQLAlchemy: CircularDependencyError where same row in many-to-one relationship can be in one-to-many relationship with same table | 39,028,722 | <p>I'm using Flask-SQLAlchemy 2.1 with SQLAlchemy 1.0.13, and I have two tables, <code>Address</code> and <code>Customer</code> that have multiple relationships to each other, as follows:</p>
<pre><code>class Address(db.Model):
id = db.Column(db.Integer, primary_key=True)
... # Other rows including first_name, last_name, etc.
customer_id = db.Column(
db.Integer,
db.ForeignKey('customers.id')
)
customer = db.relationship(
'Customer',
foreign_keys=customer_id,
back_populates='addresses'
)
class Customer(db.Model):
id = db.Column(db.Integer, primary_key=True)
billing_address_id = db.Column(db.Integer, db.ForeignKey('addresses.id'))
billing_address = db.relationship(
'Address',
foreign_keys=billing_address_id
)
shipping_address_id = db.Column(
db.Integer,
db.ForeignKey('addresses.id')
)
shipping_address = db.relationship(
'Address',
foreign_keys=shipping_address_id
)
addresses = db.relationship(
'Address',
foreign_keys='Address.customer_id',
back_populates='customer'
)
</code></pre>
<p>There are also two event listeners that automatically add any set <code>billing_address</code> or <code>shipping_address</code> to <code>addresses</code> for <code>Customer</code> instances:</p>
<pre><code>@event.listens_for(Customer.billing_address, 'set')
def add_billing_address_event(target, value, oldvalue, initiator):
"""If a billing address is added to a `Customer`, add it to addresses."""
if value is not None and value not in target.addresses:
target.addresses.append(value)
@event.listens_for(Customer.shipping_address, 'set')
def add_shipping_address_event(target, value, oldvalue, initiator):
"""If a shipping address is added to `Customer`, add to addresses."""
if value is not None and value not in target.addresses:
target.addresses.append(value)
</code></pre>
<p>Attempting to set <code>Customer.billing_address</code> and <code>Customer.shipping_address</code> results in a <code>CircularDependencyError</code> as I would expect:</p>
<pre><code>> c = Customer()
> c.billing_address = Address(first_name='Bill')
> c.shipping_address = Address(first_name='Ship')
> db.session.add(c)
> db.session.flush()
CircularDependencyError: Circular dependency detected. (ProcessState(ManyToOneDP(Customer.shipping_address), <Customer at 0x7f53aa5c9fd0>, delete=False), ProcessState(ManyToOneDP(Address.customer), <Address at 0x7f53aa4e4128>, delete=False), ProcessState(ManyToOneDP(Address.customer), <Address at 0x7f53aa4e4080>, delete=False), SaveUpdateState(<Customer at 0x7f53aa5c9fd0>), ProcessState(ManyToOneDP(Customer.billing_address), <Customer at 0x7f53aa5c9fd0>, delete=False), ProcessState(OneToManyDP(Customer.addresses), <Customer at 0x7f53aa5c9fd0>, delete=False), SaveUpdateState(<Address at 0x7f53aa4e4080>), SaveUpdateState(<Address at 0x7f53aa4e4128>))
</code></pre>
<p>If I comment out the event listeners, this does not cause the <code>CircularDependencyError</code>, which is also what I would expect, as <code>Customer.address</code> is not being accessed. This is not a solution, however, as the circular dependency results from having the same <code>Address</code> instance exist in <code>billing_address</code> or <code>shipping_address</code> and <code>addresses</code>, and I would like to allow <code>addresses</code> to include current billing and shipping addresses.</p>
<p>According to the <a href="http://docs.sqlalchemy.org/en/latest/orm/relationship_persistence.html#rows-that-point-to-themselves-mutually-dependent-rows" rel="nofollow">relevant SQLAlchemy docs</a> this should be fixable by adding <code>post_update=True</code> argument to one side of the relationship, and giving its foreign key a name:</p>
<pre><code>class Address(db.Model):
...
customer_id = db.Column(
db.Integer,
db.ForeignKey('customers.id', name='fk_customer_id')
)
customer = db.relationship(
'Customer',
foreign_keys=customer_id,
back_populates='addresses',
post_update=True
)
</code></pre>
<p>This still raises a <code>CircularDependencyError</code>, however:</p>
<pre><code>CircularDependencyError: Circular dependency detected. (ProcessState(OneToManyDP(Customer.addresses), <Customer at 0x7f620af3ff60>, delete=False), SaveUpdateState(<Address at 0x7f620ae5a080>), SaveUpdateState(<Address at 0x7f620ae5a128>), ProcessState(ManyToOneDP(Customer.billing_address), <Customer at 0x7f620af3ff60>, delete=False), SaveUpdateState(<Customer at 0x7f620af3ff60>), ProcessState(ManyToOneDP(Customer.shipping_address), <Customer at 0x7f620af3ff60>, delete=False))
</code></pre>
<p>I've also tried passing <code>use_alter=True</code> to the <code>customer_id</code> foreign key as mentioned in some related StackOverflow posts:</p>
<pre><code>customer_id = db.Column(
db.Integer,
db.ForeignKey('customers.id', name='fk_customer_id', use_alter=True)
)
</code></pre>
<p>The <code>CircularDependencyError</code> still happens. I have found a solution that seems to work, which I will post below, but I am not confident it is the correct solution.</p>
| 0 | 2016-08-18T22:58:05Z | 39,028,803 | <p>Setting <code>post_update=True</code> on both sides of the relationship appears to solve the problem:</p>
<pre><code>class Address(db.Model):
...
customer_id = db.Column(db.Integer, db.ForeignKey('customers.id'))
customer = db.relationship(
'Customer',
foreign_keys=customer_id,
back_populates='addresses',
post_update=True
)
class Customer(db.Model):
...
addresses = db.relationship(
'Address',
foreign_keys='Address.customer_id',
back_populates='customer',
post_update=True
)
</code></pre>
<p>Now when adding a <code>billing_address</code> and/or a <code>shipping_address</code>, it is automatically added to <code>addresses</code> without issue. Adding a new <code>billing_address</code> or <code>shipping_address</code> behaves as I expect it to as well, leaving the old address in <code>addresses</code> as well as adding the new one.</p>
<p>I am not completely confident in this answer, however, as the SQLAlchemy documentation explicitly mentions that <code>post_update=True</code> should be set for one side of the relationship, not both, so I am wondering if my solution will lead to unexpected behavior.</p>
<p><strong>Edit - Here's the proper solution:</strong></p>
<p>For some reason, setting <code>post_update=True</code> on <code>addresses</code> without also setting it on <code>customer</code> (or vice versa) wasn't working, but setting it on <code>billing_address</code> and <code>shipping_address</code> as suggested by @univerio. Thanks!</p>
<pre><code>class Customer(db.Model):
...
billing_address = db.relationship(
'Address',
foreign_keys=billing_address_id,
post_update=True
)
shipping_address = db.relationship(
'Address',
foreign_keys=shipping_address_id,
post_update=True
)
</code></pre>
| 0 | 2016-08-18T23:06:43Z | [
"python",
"sqlalchemy",
"relationship",
"flask-sqlalchemy",
"circular-dependency"
] |
How to create a lambda for assignment? | 39,028,791 | <p>I just to pass something like:</p>
<pre><code>def ___(x):
x.a=0
return x
</code></pre>
<p>or </p>
<pre><code>def ___(x):
x.a=0
</code></pre>
<p>into a function. How to make it happen?</p>
| -3 | 2016-08-18T23:05:14Z | 39,028,813 | <p>A lambda can only be an expression, and assignment isn't an expression in Python. Fortunately, there is another way to set an attribute in Python: the function <code>setattr()</code>. So you can write:</p>
<pre><code>lambda x: setattr(x, "a", 0)
</code></pre>
<p>This isn't very good Python, though, because it makes the code less clear just so it can be used in a lambda. I'd just use a named function.</p>
| 3 | 2016-08-18T23:07:53Z | [
"python"
] |
How to create a lambda for assignment? | 39,028,791 | <p>I just to pass something like:</p>
<pre><code>def ___(x):
x.a=0
return x
</code></pre>
<p>or </p>
<pre><code>def ___(x):
x.a=0
</code></pre>
<p>into a function. How to make it happen?</p>
| -3 | 2016-08-18T23:05:14Z | 39,028,820 | <pre><code>x.a=0
</code></pre>
<p>The line above is a <em><a href="https://docs.python.org/3/reference/simple_stmts.html#assignment-statements" rel="nofollow">statement</a></em>, and lambda functions can not contain statements (only <em><a href="https://docs.python.org/3/reference/expressions.html" rel="nofollow">expressions</a></em>).</p>
<p>However, you can pass normal functions as arguments to other functions, no problems!<br>
So: just use a <code>def</code>. </p>
| 0 | 2016-08-18T23:08:33Z | [
"python"
] |
JSON Dump of raw SQL query returning empty dictionary | 39,028,870 | <p>I am sending a string through http get request to my views.py and then send back to my javascript but I am not getting my desired data, and instead, I am getting an empty dict. I am on Django 1.8 as well.</p>
<p><strong>views.py:</strong></p>
<pre><code>def getData(request):
some_data = request.GET.get('selectionvalue')
cursor = connection.cursor()
cursor.execute("SELECT SW_ID FROM sw WHERE SWName = %s ", [some_data])
row = cursor.fetchall()
return JsonResponse({"Item" : list(row)})
#return JsonResponse({"Hello" : "world"}) works.
</code></pre>
<p>I've been stuck on this problem for the past couple hours and would love any help. Thank you.</p>
<p><strong>I tried this but still no luck:</strong></p>
<pre><code>def getData(request):
some_data = request.GET.get('selectionvalue')
cursor = connection.cursor()
cursor.execute("SELECT SW_ID FROM sw WHERE SWName = %s ", [some_data])
row = cursor.fetchall()
data = {"Item" : row}
return JsonResponse(data)
</code></pre>
<p><strong>UPDATE:</strong></p>
<p>I have now converted the query dict that i originally had to a string. I am now trying to use that string variable within my query but it is not working. If a different query without the variable it works perfectly. I can't seem to figure this out.</p>
| 0 | 2016-08-18T23:14:29Z | 39,044,821 | <p>Okay after playing around for a bit, I finally fixed it. My problem was that I needed to search for an exact string name in one of the tables and columns in my database but I was retrieving my sent data in views.py as a query dictionary. The thing is that this query dictionary had my single string that I passed in through my request as the key of the dictionary, not the value. So i needed to convert it into a single string variable then use my query. I also needed to not have the ' ' around my %s inside the query.</p>
<p><strong>Views.py:</strong></p>
<pre><code>def getData(request):
some_data = request.GET
for key in some_data:
SWVALUE = key
cursor = connection.cursor()
cursor.execute("SELECT SW_ID FROM sw WHERE SWName = %s ", (SWVALUE))
= %s ", %ItemfromSW)
row = cursor.fetchall()
json_data = json.dumps(list(row))
return HttpResponse(json_data, content_type = "application/json")
</code></pre>
| 0 | 2016-08-19T17:35:54Z | [
"javascript",
"python",
"json",
"django"
] |
JSON Dump of raw SQL query returning empty dictionary | 39,028,870 | <p>I am sending a string through http get request to my views.py and then send back to my javascript but I am not getting my desired data, and instead, I am getting an empty dict. I am on Django 1.8 as well.</p>
<p><strong>views.py:</strong></p>
<pre><code>def getData(request):
some_data = request.GET.get('selectionvalue')
cursor = connection.cursor()
cursor.execute("SELECT SW_ID FROM sw WHERE SWName = %s ", [some_data])
row = cursor.fetchall()
return JsonResponse({"Item" : list(row)})
#return JsonResponse({"Hello" : "world"}) works.
</code></pre>
<p>I've been stuck on this problem for the past couple hours and would love any help. Thank you.</p>
<p><strong>I tried this but still no luck:</strong></p>
<pre><code>def getData(request):
some_data = request.GET.get('selectionvalue')
cursor = connection.cursor()
cursor.execute("SELECT SW_ID FROM sw WHERE SWName = %s ", [some_data])
row = cursor.fetchall()
data = {"Item" : row}
return JsonResponse(data)
</code></pre>
<p><strong>UPDATE:</strong></p>
<p>I have now converted the query dict that i originally had to a string. I am now trying to use that string variable within my query but it is not working. If a different query without the variable it works perfectly. I can't seem to figure this out.</p>
| 0 | 2016-08-18T23:14:29Z | 39,046,203 | <p>Have you tried to print "row" variable? Is there any result?
Because maybe this is not a problem from the query, but the problem is that row data is not json serializable, and so JsonResponse can't render it.</p>
<p>i. e., I believe cursor.fetchall() will deliver your data in the following format: [(1,),(5,),(7,)], because it returns a list of tuples. And when you call list(row), response is the same (as a list of tuples is already a list).</p>
<p>Just to be sure, try this:</p>
<pre><code>def getData(request):
some_data = request.GET.get('selectionvalue')
cursor = connection.cursor()
cursor.execute("SELECT SW_ID FROM sw WHERE SWName = %s ", [some_data])
row = cursor.fetchall()
items = []
for r in row:
items.append(r[0])
return JsonResponse({"Item" : items})
</code></pre>
| 0 | 2016-08-19T19:10:54Z | [
"javascript",
"python",
"json",
"django"
] |
Transforming column dataframe pandas into sequence | 39,028,903 | <p>I have data and convert into dataframe</p>
<pre><code>d = [
(1,70399,0.988375133622),
(1,33919,0.981573492596),
(1,62461,0.981426807114),
(579,1,0.983018778374),
(745,1,0.995580488899),
(834,1,0.980942505189)
]
df = pd.DataFrame(d, columns=['source', 'target', 'weight'])
>>> df
source target weight
0 1 70399 0.988375
1 1 33919 0.981573
2 1 62461 0.981427
3 579 1 0.983019
4 745 1 0.995580
5 834 1 0.980943
</code></pre>
<p>I need transform column source into sequence, I have tried using </p>
<pre><code>df.source = (df.source.diff() != 0).cumsum() - 1
</code></pre>
<p>but I just get :</p>
<pre><code>>>> df
source target weight
0 0 70399 0.988375
1 0 33919 0.981573
2 0 62461 0.981427
3 1 1 0.983019
4 2 1 0.995580
5 3 1 0.980943
</code></pre>
<p>I need transform value column target based value source, ideal result is :</p>
<pre><code>>>> df
source target weight
0 0 70399 0.988375
1 0 33919 0.981573
2 0 62461 0.981427
3 1 0 0.983019
4 2 0 0.995580
5 3 0 0.980943
</code></pre>
<p>value <code>target</code> change match value in source, in <code>source</code>, <code>value</code> 1 change into 0, so i need change <code>value</code> 1 in <code>target</code> into 0 too</p>
<p>How can I do that ? Maybe anyone can help me :)</p>
<p>Thanks :)</p>
| 0 | 2016-08-18T23:17:20Z | 39,029,014 | <p>Something like this?</p>
<pre><code>df['source_code'] = df.source.astype('category').cat.codes
>>> df
source target weight source_code
0 1 70399 0.988375 0
1 1 33919 0.981573 0
2 1 62461 0.981427 0
3 579 1 0.983019 1
4 745 1 0.995580 2
5 834 1 0.980943 3
</code></pre>
| 0 | 2016-08-18T23:30:21Z | [
"python",
"pandas"
] |
Transforming column dataframe pandas into sequence | 39,028,903 | <p>I have data and convert into dataframe</p>
<pre><code>d = [
(1,70399,0.988375133622),
(1,33919,0.981573492596),
(1,62461,0.981426807114),
(579,1,0.983018778374),
(745,1,0.995580488899),
(834,1,0.980942505189)
]
df = pd.DataFrame(d, columns=['source', 'target', 'weight'])
>>> df
source target weight
0 1 70399 0.988375
1 1 33919 0.981573
2 1 62461 0.981427
3 579 1 0.983019
4 745 1 0.995580
5 834 1 0.980943
</code></pre>
<p>I need transform column source into sequence, I have tried using </p>
<pre><code>df.source = (df.source.diff() != 0).cumsum() - 1
</code></pre>
<p>but I just get :</p>
<pre><code>>>> df
source target weight
0 0 70399 0.988375
1 0 33919 0.981573
2 0 62461 0.981427
3 1 1 0.983019
4 2 1 0.995580
5 3 1 0.980943
</code></pre>
<p>I need transform value column target based value source, ideal result is :</p>
<pre><code>>>> df
source target weight
0 0 70399 0.988375
1 0 33919 0.981573
2 0 62461 0.981427
3 1 0 0.983019
4 2 0 0.995580
5 3 0 0.980943
</code></pre>
<p>value <code>target</code> change match value in source, in <code>source</code>, <code>value</code> 1 change into 0, so i need change <code>value</code> 1 in <code>target</code> into 0 too</p>
<p>How can I do that ? Maybe anyone can help me :)</p>
<p>Thanks :)</p>
| 0 | 2016-08-18T23:17:20Z | 39,032,937 | <p>You can use:</p>
<pre><code>#remember original values
source_old = df.source.copy()
df.source = (df.source.diff() != 0).cumsum() - 1
#series for maping
ser = pd.Series(df.source.values, index=source_old).drop_duplicates()
print (ser)
source
1 0
579 1
745 2
834 3
dtype: int32
#map where values exists
df.target = df.target.mask(df.target.isin(ser), df.target.map(ser)).astype(int)
print (df)
source target weight
0 0 70399 0.988375
1 0 33919 0.981573
2 0 62461 0.981427
3 1 0 0.983019
4 2 0 0.995580
5 3 0 0.980943
</code></pre>
| 0 | 2016-08-19T07:02:02Z | [
"python",
"pandas"
] |
What precisely does DEPTH_LIMIT refer to? Is the current depth referencable? | 39,028,908 | <p>Scrapy indicates it has a <a href="http://doc.scrapy.org/en/latest/topics/settings.html#depth-limit" rel="nofollow"><code>DEPTH_LIMIT</code> setting</a>, but doesn't specifically say what it considers 'depth'. In terms of scraping pages, I've seen 'depth' refer to 'depth of the url', or <code>http://somedomain.com/this/is/a/depth/six/url</code>, where the page that is requested by that URL has a depth of 'six', because it's six segments in. <code>http://somedomain.com</code> would be depth zero.</p>
<p>On the other hand, when we consider scraping in terms of trees, depth would more likely refer to how far you are from the starting location. Thus, if I feed it a starting url of <code>http://somedomain.com/start/here</code>, that is depth zero, and any link found on that response would be depth one.</p>
<p>Does Scrapy use one of these definitions? If so which one? If it is the latter one (which seems the more logical), is there any way to get that depth information, either when you're processing the response in the crawler or when you're post-processing it as an item in the pipeline?</p>
| 1 | 2016-08-18T23:17:50Z | 39,029,055 | <p>Scrapy uses a DFS approach for traversal and the current depth can be accessed via the response meta data: <code>response.meta['depth']</code>.</p>
| 1 | 2016-08-18T23:35:09Z | [
"python",
"scrapy",
"scrapy-spider"
] |
WebSockets Client Connections Time Out When Trying to Open a Connection with Tornado Server | 39,028,935 | <p>I have a Tornado server with a WebSocketHandler, and when I connect to the handler on localhost everything works correctly. However, the server is being moved to a new environment and now must run on <code>wss</code> instead of <code>ws</code> protocol. Since moving to the new environment, all client connections to my WebSocketHandler time out without ever opening. <code>telnet</code> connects just fine, however. The issue occurs in all major browsers, afaik.</p>
<p>The firewall has an exception for the port my server is running on, and I've enabled TLS in the Tornado server by sending in my <code>.cer</code> and <code>.key</code> files, but to no avail. I also tried following the advice <a href="http://stackoverflow.com/questions/23775215/can-not-established-websocket-secure-connection-on-firefox" title="Can not established Websocket secure connection on Firefox">here</a> regarding ProxyPass in an Apache server running on the same environment, and connections are still timing out.</p>
<p>Environment: CentOS Linux release 7.2.1511</p>
<p>Relevant Tornado Code:</p>
<pre><code>import tornado.websocket
import tornado.ioloop
import tornado.auth
import tornado.escape
import tornado.concurrent
class WSHandler(tornado.websocket.WebSocketHandler)
def check_origin(self, origin):
return True
def open(self, arg1, arg2):
self.stream.set_nodelay(True)
self.arg2 = arg2
self.write_message("Opened the connection")
class WSApp(tornado.web.Application):
def __init__(self, arg1=None, arg2=None, handlers=None,
default_host='', transforms=None, **settings):
print("Starting WSApp application")
super(WSApp, self).__init__(handlers=handlers,
default_host=default_host,
transforms=transforms,
**settings)
if __name__ == "__main__":
settings = {
"cookie_secret": b'om nom nom' # /s,
"ssl_options": {
"certfile": "path/to/certfile.cer",
"keyfile": "path/to/keyfile.key"
}
application = AMQPWSTunnel(handlers=[
(r"/(resource)/(.+)", AMQPWSHandler)
],
debug=True,
**settings)
application.listen(8930)
try:
tornado.ioloop.IOLoop.current().start()
except KeyboardInterrupt:
application.shutdown()
</code></pre>
<p>ProxyPass Settings</p>
<pre><code>ProxyPass /resource/<resource_name> wss://127.0.0.1:8930/resource/<resource_name>
ProxyPassReverse /resource/<resource_name> wss://127.0.0.1:8930/resource/<resource_name>
</code></pre>
<p>WebSocket Connection</p>
<pre><code>var ws = new Websocket("wss://my-domain:8930/resource/<resource_id>");
</code></pre>
<p>Any help would be appreciated! </p>
| 1 | 2016-08-18T23:20:17Z | 39,041,012 | <p>The issue was with ProxyPass settings and the post used in my <code>wss</code> url.</p>
<p>Tornado Update:</p>
<p>The ssl cert and key files were removed from Tornado configuration.</p>
<p>ProxyPass Update:</p>
<pre><code>ProxyPass /resource/<resource_name> ws://127.0.0.1:8930/resource/<resource_name>
ProxyPassReverse /resource/<resource_name> ws://127.0.0.1:8930/resource/<resource_name>
</code></pre>
<p>The second argument must be a non-ssl protocol (changed from <code>wss://</code> to <code>ws://</code>), though by keeping the cert in place I probably could have used <code>wss</code>. This is a non-issue, though, because Apache catches incoming WebSocket requests to my server.</p>
<p>Client Update:</p>
<p>The client must send requests to Apache, which then tunnels them to the Tornado server. So just remove the port from the url (or add Apache's port number)</p>
<pre><code>var ws = new Websocket("wss://my-domain/resource/<resource_id>");
</code></pre>
<p>Those three changes did the trick! Hopefully this is helpful to anyone else stuck on the same issue.</p>
| 0 | 2016-08-19T14:02:49Z | [
"python",
"ssl",
"websocket",
"tornado",
"proxypass"
] |
Copying nested custom objects: alternatives to deepcopy | 39,028,978 | <p>I'm looking to make a deep copy of a class object that contains a list of class objects, each with their own set of stuff. The objects don't contain anything more exciting than ints and lists (no dicts, no generators waiting to yield, etc). I'm performing the deep copy on between 500-800 objects a loop, and it's really slowing the program down. I realize that this is already inefficient; it currently can't be changed.</p>
<p>Example of how it looks:</p>
<pre><code>import random
import copy
class Base:
def __init__(self, minimum, maximum, length):
self.minimum = minimum
self.maximum = maximum
self.numbers = [random.randint(minimum, maximum) for _ in range(length)]
# etc
class Next:
def __init__(self, minimum, maximum, length, quantity):
self.minimum = minimum
self.maximum = maximum
self.bases = [Base(minimum, maximum, length) for _ in range(quantity)]
# etc
</code></pre>
<p>Because of the actions I'm performing on the objects, I can't shallow copy. I need the contents to be owned by the new variable:</p>
<pre><code>> first = Next(0, 10, 5, 10)
> second = first
> first.bases[0].numbers[1] = 4
> print(first.bases[0].numbers)
> [2, 4, 3, 3, 8]
> print(second.bases[0].numbers)
> [2, 4, 3, 3, 8]
>
> first = Next(0, 10, 5, 10)
> second = copy.deepcopy(first)
> first.bases[0].numbers[1] = 4
> print(first.bases[0].numbers)
> [8, 4, 7, 9, 9]
> print(second.bases[0].numbers)
> [8, 11, 7, 9, 9]
</code></pre>
<p>I've tried a couple of different ways, such as using json to serialize and reload the data, but in my tests it's not been nearly fast enough, because I'm stuck reassigning all of the variables each time. My attempt at pulling off a clever <code>self.__dict__ = dct</code> hasn't worked because of the nested objects.</p>
<p>Any ideas for how to efficiently deep copy multiply-nested Python objects without using copy.deepcopy?</p>
| 0 | 2016-08-18T23:25:19Z | 39,029,350 | <p>One of the first things that <code>copy.deepcopy</code> looks for is if the object defines <a href="https://github.com/tadhgmister/cpython/blob/master/Lib/copy.py#L159" rel="nofollow">it's own <code>__deepcopy__</code> method</a> So instead of having it figure out how to copy object every time just define your own process.</p>
<p>It would require you have a way of defining a <code>Base</code> object without any element of random-ness for the copies to use, but if you can find a more efficient process of copying your objects you should define it as a <code>__deepcopy__</code> method to speed up copying process.</p>
| 2 | 2016-08-19T00:17:18Z | [
"python",
"python-3.x"
] |
Copying nested custom objects: alternatives to deepcopy | 39,028,978 | <p>I'm looking to make a deep copy of a class object that contains a list of class objects, each with their own set of stuff. The objects don't contain anything more exciting than ints and lists (no dicts, no generators waiting to yield, etc). I'm performing the deep copy on between 500-800 objects a loop, and it's really slowing the program down. I realize that this is already inefficient; it currently can't be changed.</p>
<p>Example of how it looks:</p>
<pre><code>import random
import copy
class Base:
def __init__(self, minimum, maximum, length):
self.minimum = minimum
self.maximum = maximum
self.numbers = [random.randint(minimum, maximum) for _ in range(length)]
# etc
class Next:
def __init__(self, minimum, maximum, length, quantity):
self.minimum = minimum
self.maximum = maximum
self.bases = [Base(minimum, maximum, length) for _ in range(quantity)]
# etc
</code></pre>
<p>Because of the actions I'm performing on the objects, I can't shallow copy. I need the contents to be owned by the new variable:</p>
<pre><code>> first = Next(0, 10, 5, 10)
> second = first
> first.bases[0].numbers[1] = 4
> print(first.bases[0].numbers)
> [2, 4, 3, 3, 8]
> print(second.bases[0].numbers)
> [2, 4, 3, 3, 8]
>
> first = Next(0, 10, 5, 10)
> second = copy.deepcopy(first)
> first.bases[0].numbers[1] = 4
> print(first.bases[0].numbers)
> [8, 4, 7, 9, 9]
> print(second.bases[0].numbers)
> [8, 11, 7, 9, 9]
</code></pre>
<p>I've tried a couple of different ways, such as using json to serialize and reload the data, but in my tests it's not been nearly fast enough, because I'm stuck reassigning all of the variables each time. My attempt at pulling off a clever <code>self.__dict__ = dct</code> hasn't worked because of the nested objects.</p>
<p>Any ideas for how to efficiently deep copy multiply-nested Python objects without using copy.deepcopy?</p>
| 0 | 2016-08-18T23:25:19Z | 39,414,002 | <p>Based on cherish's answers <a href="http://stackoverflow.com/questions/24756712/deepcopy-is-extremely-slow/29385667#29385667">here</a>, <code>pickle.loads(pickle.dumps(first))</code> works about twice as fast per call. I had written it off initially because of an unrelated error when testing it, but on retesting it, it performs well within my needs.</p>
| 1 | 2016-09-09T14:32:34Z | [
"python",
"python-3.x"
] |
Reading string as text in an equation | 39,029,068 | <p>I want to be able to execute the following code:</p>
<pre><code>import numpy
z=numpy.zeros(4)
k="z[i-1]"
for i in range(len(b)):
z[i]=k
</code></pre>
<p>Which should return the same output as:</p>
<pre><code>z=numpy.zeros(4)
for i in range(6):
z[i]=z[i-1]
</code></pre>
<p>If I execute the first code block, I get an expected error message:</p>
<pre><code> File "<ipython-input-982-3ba4e617a74a>", line 1, in <module>
z[i]=(k)
ValueError: could not convert string to float: 'z[i-1]'
</code></pre>
<p>How can I pass the text from the string into the loop so that it functions as an equation, as if the characters from the string were typed by hand?</p>
| 0 | 2016-08-18T23:37:27Z | 39,029,137 | <p>Do it as following:</p>
<pre><code>import numpy
z=numpy.zeros(4)
k="z[i-1]"
for i in range(len(b)):
z[i]=eval(k)
</code></pre>
<p>But note eval can be a security problem: <a href="http://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html" rel="nofollow">http://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html</a></p>
| 1 | 2016-08-18T23:46:05Z | [
"python",
"string",
"for-loop",
"text"
] |
Reading string as text in an equation | 39,029,068 | <p>I want to be able to execute the following code:</p>
<pre><code>import numpy
z=numpy.zeros(4)
k="z[i-1]"
for i in range(len(b)):
z[i]=k
</code></pre>
<p>Which should return the same output as:</p>
<pre><code>z=numpy.zeros(4)
for i in range(6):
z[i]=z[i-1]
</code></pre>
<p>If I execute the first code block, I get an expected error message:</p>
<pre><code> File "<ipython-input-982-3ba4e617a74a>", line 1, in <module>
z[i]=(k)
ValueError: could not convert string to float: 'z[i-1]'
</code></pre>
<p>How can I pass the text from the string into the loop so that it functions as an equation, as if the characters from the string were typed by hand?</p>
| 0 | 2016-08-18T23:37:27Z | 39,029,139 | <p>I think you're looking for the <a href="https://docs.python.org/2/library/functions.html#eval" rel="nofollow">builtin <code>eval()</code></a></p>
<p>Consider:</p>
<pre><code>>>> z = numpy.zeros(4)
>>> k = "10 + z[i-1]"
>>> for i in range(1, 4):
... z[i] = eval(k)
...
>>> z
array([ 0., 10., 20., 30.])
</code></pre>
<p>I made the expression a little more complex so you could see interesting output.</p>
| 3 | 2016-08-18T23:46:19Z | [
"python",
"string",
"for-loop",
"text"
] |
Reading string as text in an equation | 39,029,068 | <p>I want to be able to execute the following code:</p>
<pre><code>import numpy
z=numpy.zeros(4)
k="z[i-1]"
for i in range(len(b)):
z[i]=k
</code></pre>
<p>Which should return the same output as:</p>
<pre><code>z=numpy.zeros(4)
for i in range(6):
z[i]=z[i-1]
</code></pre>
<p>If I execute the first code block, I get an expected error message:</p>
<pre><code> File "<ipython-input-982-3ba4e617a74a>", line 1, in <module>
z[i]=(k)
ValueError: could not convert string to float: 'z[i-1]'
</code></pre>
<p>How can I pass the text from the string into the loop so that it functions as an equation, as if the characters from the string were typed by hand?</p>
| 0 | 2016-08-18T23:37:27Z | 39,029,286 | <p>Other then <code>eval</code> which is highly discouraged in production code, You can just as easily define a function that returns a specific item based on the array and index:</p>
<pre><code>def k(arr,idx):
return arr[idx-1]
for i in range(len(b)):
z[i]= k(z,i)
</code></pre>
<p>If this rule needs to be applied in various spots in your code then you can edit the one function to apply that logic in all the places it is needed.</p>
| 1 | 2016-08-19T00:06:50Z | [
"python",
"string",
"for-loop",
"text"
] |
pycparser.plyparser.ParseError on complex struct | 39,029,209 | <p>I'm trying to use <code>pycparser</code> to parse this C code:</p>
<p><a href="https://github.com/nbeaver/mx-trunk/blob/0b80678773582babcd56fe959d5cfbb776cc0004/libMx/d_adsc_two_theta.c" rel="nofollow">https://github.com/nbeaver/mx-trunk/blob/0b80678773582babcd56fe959d5cfbb776cc0004/libMx/d_adsc_two_theta.c</a></p>
<p>A repo with a minimal example and Makefile is here:</p>
<p><a href="https://github.com/nbeaver/pycparser-problem" rel="nofollow">https://github.com/nbeaver/pycparser-problem</a></p>
<p>Using <code>pycparser</code> v2.14 (from pip) and gcc 4.9.2 on Debian Jessie.</p>
<p>Things I have tried:</p>
<ul>
<li>Pass the <code>-nostdinc</code> flag to <code>gcc</code> and including the <code>fake_libc_include</code> folder.</li>
<li>Use <code>-D'__attribute__(x)='</code> to take out GCC extensions</li>
<li>Use fake headers for e.g. <code><sys/param.h></code></li>
<li>Use the <code>-std=c99</code> in case the code is not C99 compatible.</li>
<li>Reproduce the <a href="http://eli.thegreenplace.net/2015/on-parsing-c-type-declarations-and-fake-headers/" rel="nofollow">redis example</a> in case there is something weird with my machine.</li>
</ul>
<p>This is what the traceback looks like:</p>
<pre><code>Traceback (most recent call last):
File "just_parse.py", line 21, in <module>
parse(path)
File "just_parse.py", line 9, in parse
ast = pycparser.parse_file(filename)
File "/home/nathaniel/.local/lib/python2.7/site-packages/pycparser/__init__.py", line 93, in parse_file
return parser.parse(text, filename)
File "/home/nathaniel/.local/lib/python2.7/site-packages/pycparser/c_parser.py", line 146, in parse
debug=debuglevel)
File "/home/nathaniel/.local/lib/python2.7/site-packages/pycparser/ply/yacc.py", line 265, in parse
return self.parseopt_notrack(input,lexer,debug,tracking,tokenfunc)
File "/home/nathaniel/.local/lib/python2.7/site-packages/pycparser/ply/yacc.py", line 1047, in parseopt_notrack
tok = self.errorfunc(errtoken)
File "/home/nathaniel/.local/lib/python2.7/site-packages/pycparser/c_parser.py", line 1680, in p_error
column=self.clex.find_tok_column(p)))
File "/home/nathaniel/.local/lib/python2.7/site-packages/pycparser/plyparser.py", line 55, in _parse_error
raise ParseError("%s: %s" % (coord, msg))
pycparser.plyparser.ParseError: in/d_adsc_two_theta.c:63:82: before: .
</code></pre>
<p>The traceback points to this line:</p>
<p><a href="https://github.com/nbeaver/mx-trunk/blob/0b80678773582babcd56fe959d5cfbb776cc0004/libMx/d_adsc_two_theta.c#L63" rel="nofollow">https://github.com/nbeaver/mx-trunk/blob/0b80678773582babcd56fe959d5cfbb776cc0004/libMx/d_adsc_two_theta.c#L63</a></p>
<p>Which in turn points to this <code>#define</code> macro:</p>
<p><a href="https://github.com/nbeaver/mx-trunk/blob/0b80678773582babcd56fe959d5cfbb776cc0004/libMx/mx_motor.h#L484" rel="nofollow">https://github.com/nbeaver/mx-trunk/blob/0b80678773582babcd56fe959d5cfbb776cc0004/libMx/mx_motor.h#L484</a></p>
| 3 | 2016-08-18T23:55:39Z | 39,496,991 | <p>The cause appears to be the <code>offsetof()</code> function. The minimal working examples are fixed by recent commits, however:</p>
<p><a href="https://github.com/eliben/pycparser/issues/87" rel="nofollow">https://github.com/eliben/pycparser/issues/87</a></p>
| 0 | 2016-09-14T18:09:13Z | [
"python",
"c",
"ply",
"pycparser"
] |
How to detect uncertainty of text in NLTK Python? | 39,029,244 | <p>I am a beginner at NLTK and machine learning with the goal of giving uncertainty ratings to sentences.
For example, a sentence like <code>This is likely caused by a..</code> would receive a certainty score of say 6, where as <code>There is definitely something wrong with me</code> would receive a 10 and <code>I think it could possibly happen</code> would score a 3. </p>
<p>Regardless of the score system, a classification of "certain" and "uncertain" can also suffice my needs.</p>
<p>I did not find any existing works on this. How would I approach this? I do have some untrained text data.</p>
| 1 | 2016-08-19T00:00:16Z | 39,058,248 | <p>As far as I know, existing nlp toolkits do not have such feature. </p>
<p>You have to train your own model and for that you need training data. If you have a dataset that contains uncertainty labels for each sentence, then you can train a text classification model on that.</p>
<p>If you don't have labeled data, there was a <a href="http://www.aclweb.org/anthology/W/W10/W10-3001.pdf" rel="nofollow">CoNLL 2010 Shared task</a> on detecting uncertainty/hedging and the dataset for that should be available.
You can access the CoNLL 2010 dataset and train a simple text classifier on that and use the trained model on your own dataset. Assuming that the nature of your data is not very different than theirs, this should work.</p>
<p>For text classification, you can simply use <a href="http://scikit-learn.org/stable/tutorial/text_analytics/working_with_text_data.html" rel="nofollow">scikit-learn</a> library which is straight forward. </p>
<p>You might also find the following references useful:</p>
<ul>
<li><p>Rubin, Victoria et al. "<a href="http://Rubin,%20Victoria%20L.,%20Elizabeth%20D.%20Liddy,%20and%20Noriko%20Kando.%20%22Certainty%20identification%20in%20texts:%20Categorization%20model%20and%20manual%20tagging%20results.%22%20Computing%20attitude%20and%20affect%20in%20text:%20Theory%20and%20applications.%20Springer%20Netherlands,%202006.%2061-76." rel="nofollow">Certainty identification in texts:
Categorization model and manual tagging results</a>." Computing
attitude and affect in text: Theory and applications. 2006. 61-76.</p></li>
<li><p>Medlock, Ben, and Ted Briscoe. "<a href="http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.379.8338&rep=rep1&type=pdf#page=1030" rel="nofollow">Weakly supervised learning for hedge
classification in scientific literature</a>." ACL. Vol. 2007. 2007.</p></li>
</ul>
| 3 | 2016-08-20T20:05:53Z | [
"python",
"nlp",
"artificial-intelligence",
"nltk"
] |
How to detect uncertainty of text in NLTK Python? | 39,029,244 | <p>I am a beginner at NLTK and machine learning with the goal of giving uncertainty ratings to sentences.
For example, a sentence like <code>This is likely caused by a..</code> would receive a certainty score of say 6, where as <code>There is definitely something wrong with me</code> would receive a 10 and <code>I think it could possibly happen</code> would score a 3. </p>
<p>Regardless of the score system, a classification of "certain" and "uncertain" can also suffice my needs.</p>
<p>I did not find any existing works on this. How would I approach this? I do have some untrained text data.</p>
| 1 | 2016-08-19T00:00:16Z | 39,072,951 | <p>Instead of NLP problem, this is more like a text categorization problem.</p>
<p>You can define pre existing set of tags like:</p>
<pre><code>HIGHEST, HIGH , MEDIUM , LOW , NIL
</code></pre>
<p>You can then use any algorithm e.g Naive Bayes classifier or K nearest neighbours to classify your text in one of these tags, by providing it training data
initially i.e. extract tokens from text which you consider as 'certainity' drivers, and training your classifier.</p>
| 2 | 2016-08-22T06:51:20Z | [
"python",
"nlp",
"artificial-intelligence",
"nltk"
] |
Most efficient way to merge two partially inclusive lists of files and their properties | 39,029,305 | <p>I have a system that runs a custom cli with a variation of the <code>ls</code> or <code>dir</code> command, returning a list of files and folders in your working directory.</p>
<p>The problem is, I can either run the command with a flag that returns the files and their time stamps (date created and last modified), or one that returns the file and their file sizes. There is no way to get both in a single cli command.</p>
<p>A further complication arises when getting the time stamped list, only some of the files are returned (all files ending in certain prefixes are left out). Neither list is in any particular order.</p>
<p>I wish to create a dictionary that contains all the information for each file in one place. What is the cleanest, most efficient, and most pythonic way to do this?</p>
<p><strong>Quick sample of data:</strong></p>
<p><code>dir -time</code> gives a list of 506 elements. Only (but not all) files ending in .ts have timestamps. Some files show in the list but do not have timestamps, some files (such as anything ending in .index) do not show up in the list at all.</p>
<pre><code>ch20prefix_20_182.ts 2014-10-22 16:06:20 - 2014-10-22 16:08:51
ch21prefix_21_40.ts 2014-10-14 16:15:42 - 2014-10-14 16:16:51
modinfo_sdk1.23b24L
bs780_ntplatency
ch10prefix_10_237.ts 2014-10-27 11:05:10 - 2014-10-27 11:07:33
ch10prefix_10_277.ts 2014-10-30 14:03:51 - 2014-10-30 14:04:24
video1_6_1.ts
ch11prefix_11_179.ts 2014-10-22 14:53:50 - 2014-10-22 14:56:00`
</code></pre>
<p><code>dir -size</code> gives a list of 967 elements. All files are present here, all files have a file size.</p>
<pre><code>ch10prefix_10_340.index 159544
ch2prefix_2_705.ts 75958204
<ts220> 0
ch11prefix_11_148.ts 19877616
ch10prefix_10_310.ts 7373924
ch11prefix_11_111.index 17112
ch11prefix_11_278.index 1368
ch2prefix_2_307.ts 6492580
channelConfig.xml.2HD 18144
ch21prefix_21_220.ts 12893604
ch20prefix_20_128.index 1720
</code></pre>
<p>There is some rhyme and reason to the mess that is why some files show up and others don't, why some have timestamps and others don't, but that is largely irrelevant to this question.</p>
<p><strong>My thoughts on how to approach it:</strong></p>
<p>What I want as final output is a dictionary with each key as a file name, and it's value as another dictionary with key/val pairs for Time Created, Time Mod, fileSize. This way one can easily lookup all 3 pieces of information for each file.</p>
<p>The difficult part for me, however, is finding an efficient way of combining the data from each list. The first thing that comes to mind would be to loop through the larger list (file size), and then for each element, check if it is in the smaller list, and if it is (and has a timestamp), add the data. But that is horridly inefficient. Although some files in the larger list I know ahead of time do not have timestamps in the other list, I cannot say that for all files that don't have a timestamp.</p>
<p>The lists are unsorted, but It occurs to me that if they were sorted by file name, that allow for a much faster way of looking up each file from one list in another, but considering the runtime of sorting the lists, it still might not be worth the effort.</p>
<p>So, what would be the most efficient approach here? I am mostly concerned with run-time and readability, but welcome the inclusion of other factors in how I might approach this problem.</p>
| 0 | 2016-08-19T00:10:08Z | 39,029,471 | <p>Sounds like a good use case for Sqlite.
Python has <a href="https://docs.python.org/2/library/sqlite3.html" rel="nofollow">good support</a> for it. Instead of creating a disk file based DB you could use a pure in-memory based database by passing the right arguments. First I'd create a 2 tables - tblFileNTimeStamp (File name (PK), timestamp) and tblFileNSize (File name (PK), filesize). Use the output of the two commands to populate the database and use a join on the primary keys to pick the results you need.</p>
| 0 | 2016-08-19T00:36:28Z | [
"python",
"performance",
"list",
"dictionary"
] |
Most efficient way to merge two partially inclusive lists of files and their properties | 39,029,305 | <p>I have a system that runs a custom cli with a variation of the <code>ls</code> or <code>dir</code> command, returning a list of files and folders in your working directory.</p>
<p>The problem is, I can either run the command with a flag that returns the files and their time stamps (date created and last modified), or one that returns the file and their file sizes. There is no way to get both in a single cli command.</p>
<p>A further complication arises when getting the time stamped list, only some of the files are returned (all files ending in certain prefixes are left out). Neither list is in any particular order.</p>
<p>I wish to create a dictionary that contains all the information for each file in one place. What is the cleanest, most efficient, and most pythonic way to do this?</p>
<p><strong>Quick sample of data:</strong></p>
<p><code>dir -time</code> gives a list of 506 elements. Only (but not all) files ending in .ts have timestamps. Some files show in the list but do not have timestamps, some files (such as anything ending in .index) do not show up in the list at all.</p>
<pre><code>ch20prefix_20_182.ts 2014-10-22 16:06:20 - 2014-10-22 16:08:51
ch21prefix_21_40.ts 2014-10-14 16:15:42 - 2014-10-14 16:16:51
modinfo_sdk1.23b24L
bs780_ntplatency
ch10prefix_10_237.ts 2014-10-27 11:05:10 - 2014-10-27 11:07:33
ch10prefix_10_277.ts 2014-10-30 14:03:51 - 2014-10-30 14:04:24
video1_6_1.ts
ch11prefix_11_179.ts 2014-10-22 14:53:50 - 2014-10-22 14:56:00`
</code></pre>
<p><code>dir -size</code> gives a list of 967 elements. All files are present here, all files have a file size.</p>
<pre><code>ch10prefix_10_340.index 159544
ch2prefix_2_705.ts 75958204
<ts220> 0
ch11prefix_11_148.ts 19877616
ch10prefix_10_310.ts 7373924
ch11prefix_11_111.index 17112
ch11prefix_11_278.index 1368
ch2prefix_2_307.ts 6492580
channelConfig.xml.2HD 18144
ch21prefix_21_220.ts 12893604
ch20prefix_20_128.index 1720
</code></pre>
<p>There is some rhyme and reason to the mess that is why some files show up and others don't, why some have timestamps and others don't, but that is largely irrelevant to this question.</p>
<p><strong>My thoughts on how to approach it:</strong></p>
<p>What I want as final output is a dictionary with each key as a file name, and it's value as another dictionary with key/val pairs for Time Created, Time Mod, fileSize. This way one can easily lookup all 3 pieces of information for each file.</p>
<p>The difficult part for me, however, is finding an efficient way of combining the data from each list. The first thing that comes to mind would be to loop through the larger list (file size), and then for each element, check if it is in the smaller list, and if it is (and has a timestamp), add the data. But that is horridly inefficient. Although some files in the larger list I know ahead of time do not have timestamps in the other list, I cannot say that for all files that don't have a timestamp.</p>
<p>The lists are unsorted, but It occurs to me that if they were sorted by file name, that allow for a much faster way of looking up each file from one list in another, but considering the runtime of sorting the lists, it still might not be worth the effort.</p>
<p>So, what would be the most efficient approach here? I am mostly concerned with run-time and readability, but welcome the inclusion of other factors in how I might approach this problem.</p>
| 0 | 2016-08-19T00:10:08Z | 39,031,526 | <p>It is hard to tell from your question what your desired result is. If you want all files in both lists even if they only appear in one or the other just make one pass through both files and create a dictionary using <code>collections.defaultdict</code></p>
<pre><code>from collections import defaultdict
d = defaultdict(dict)
with open('fileA.txt') as f:
for line in f:
name, time = line[:24], line[24:]
name, time = name.strip(), time.strip()
time_created, time_modified = time.split(' - ')
d[name]['time_created'] = time_created
d[name]['time_modified'] = time_modified
with open('fileB.txt') as f:
for line in f:
name, size = line[:24], line[24:]
name, size = name.strip(), size.strip()
d[name]['size'] = size
</code></pre>
<hr>
<p>If your final result only includes files that appear in both lists then make one pass over each list constructing separate dictionaries.</p>
<pre><code>dA = defaultdict(dict)
dB = defaultdict(dict)
with open('fileA.txt') as f:
for line in f:
name, time = line[:24], line[24:]
name, time = name.strip(), time.strip()
try:
time_created, time_modified = time.split(' - ')
except ValueError:
time_created, time_modified = '', ''
dA[name]['time_created'] = time_created
dA[name]['time_modified'] = time_modified
with open('fileB.txt') as f:
for line in f:
name, size = line[:24], line[24:]
name, size = name.strip(), size.strip()
dB[name]['size'] = size
</code></pre>
<p>Then make a pass over one of those dictionaries creating a third dictionary with common keys.</p>
<pre><code>d = defaultdict(dict)
for k, v in dA.items():
if k in dB:
d[k] = v
d[k].update(dB[k])
</code></pre>
<hr>
<p>Since this is the only answer (so far) with a solution And @Brian C didn't offer one, this MUST be the most efficient.</p>
| 1 | 2016-08-19T05:11:33Z | [
"python",
"performance",
"list",
"dictionary"
] |
How can I use urllib.request.urlretrieve with python 2.7 | 39,029,356 | <p>I am trying to get images dowloaded from image-net.org so that I can create a haar cascade classifier. I am following this tutorial <a href="https://www.youtube.com/watch?v=z_6fPS5tDNU&list=PLQVvvaa0QuDdttJXlLtAJxJetJcqmqlQq&index=18" rel="nofollow">https://www.youtube.com/watch?v=z_6fPS5tDNU&list=PLQVvvaa0QuDdttJXlLtAJxJetJcqmqlQq&index=18</a> but I am using python 2.7 instead of python 3. So in the tutorial he has the line:</p>
<pre><code>urllib.request.urlretrieve(img, pathToImage)
</code></pre>
<p>Instead of <code>import urllib.request</code> I did this <code>import urllib2</code> So I tried this but it isn't vaild</p>
<pre><code>urllib2.urlretrieve(i, "Negatives/"+str(num)+".jpg")
</code></pre>
<p>Thank you in Advance!</p>
| 0 | 2016-08-19T00:18:36Z | 39,029,399 | <p>You just need to import urllib without '2'</p>
<pre><code>import urllib
urllib.urlretrieve(i, "Negatives/"+str(num)+".jpg")
</code></pre>
| 2 | 2016-08-19T00:25:51Z | [
"python",
"python-2.7",
"urllib2",
"urllib"
] |
How can I use urllib.request.urlretrieve with python 2.7 | 39,029,356 | <p>I am trying to get images dowloaded from image-net.org so that I can create a haar cascade classifier. I am following this tutorial <a href="https://www.youtube.com/watch?v=z_6fPS5tDNU&list=PLQVvvaa0QuDdttJXlLtAJxJetJcqmqlQq&index=18" rel="nofollow">https://www.youtube.com/watch?v=z_6fPS5tDNU&list=PLQVvvaa0QuDdttJXlLtAJxJetJcqmqlQq&index=18</a> but I am using python 2.7 instead of python 3. So in the tutorial he has the line:</p>
<pre><code>urllib.request.urlretrieve(img, pathToImage)
</code></pre>
<p>Instead of <code>import urllib.request</code> I did this <code>import urllib2</code> So I tried this but it isn't vaild</p>
<pre><code>urllib2.urlretrieve(i, "Negatives/"+str(num)+".jpg")
</code></pre>
<p>Thank you in Advance!</p>
| 0 | 2016-08-19T00:18:36Z | 39,029,538 | <p>on this <a href="http://stackoverflow.com/questions/17449904/python-urllib-urlretrieve-behind-proxy">Python urllib urlretrieve behind proxy</a></p>
<pre><code>import urllib2
download = opener.urlretrieve(URL, "Negatives/"+str(num)+".jpg")
</code></pre>
<p>the code can be transformed to</p>
<pre><code>import urllib2
with open("Negatives/"+str(num)+".jpg",'wb') as f:
f.write(urllib2.urlopen(URL).read())
f.close()
</code></pre>
| 0 | 2016-08-19T00:46:54Z | [
"python",
"python-2.7",
"urllib2",
"urllib"
] |
Scraping next page XHR request | 39,029,382 | <p>I want to scrape the second page of this user <a href="https://www.tripadvisor.com/members/1happykat" rel="nofollow">reviews</a>. </p>
<p>However the next button executes a XHR request, and while I can see it using Chrome developer tools, I cannot replicate it. </p>
| 0 | 2016-08-19T00:23:14Z | 39,030,263 | <p>It's not so easy task. First of all you should install this
<a href="https://chrome.google.com/webstore/detail/request-maker/kajfghlhfkcocafkcjlajldicbikpgnp" rel="nofollow">extension</a>.
It helps you to test own requests based on captured data, i.e. catch and simulate requests with captured data.</p>
<p>As I see they send a token in this XHR request, so you need to get it in from html page body(stores in source code, js variable "taSecureToken" ).</p>
<p>Next you need to do four steps:</p>
<ol>
<li>Catch POST request with plugin</li>
<li>Change token to saved before</li>
<li>Set <code>limit</code> and <code>offset</code> variables in POST request data</li>
<li>Generate request with resulted body</li>
</ol>
<p>Note: on this request server returns json data(not the html with next page) containing info about loaded objects on next page.</p>
| 0 | 2016-08-19T02:33:11Z | [
"python",
"ajax",
"scrape"
] |
Call imported function in python using string | 39,029,428 | <p>I have a list of the names of imported functions, which I can call as follows:</p>
<pre><code>from myfile import function1
from myfile import function2
function1()
function2()
</code></pre>
<p>How would I call the functions from a list of names? For example:</p>
<pre><code>fns = ['function1', 'function2']
for fn in fns:
fn()
</code></pre>
<p>How would I do the above properly?</p>
| 2 | 2016-08-19T00:29:33Z | 39,029,447 | <p>You can access to function objects from <code>globals()</code> namespace, but note that this is not a general approach, since first of all your imported objects should be callable (have <code>__call__</code> attribute) and they should be present in global name space.:</p>
<pre><code>for fn in fns:
try:
globals()[fn]()
except KeyError:
raise Exception("The name {} is not in global namespace".format(fn))
</code></pre>
<p>Example:</p>
<pre><code>>>> from itertools import combinations, permutations
>>>
>>> l = ['combinations', 'permutations']
>>> for i in l:
... print(list(globals()[i]([1, 2, 3], 2)))
...
[(1, 2), (1, 3), (2, 3)]
[(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]
</code></pre>
| 2 | 2016-08-19T00:32:40Z | [
"python"
] |
Call imported function in python using string | 39,029,428 | <p>I have a list of the names of imported functions, which I can call as follows:</p>
<pre><code>from myfile import function1
from myfile import function2
function1()
function2()
</code></pre>
<p>How would I call the functions from a list of names? For example:</p>
<pre><code>fns = ['function1', 'function2']
for fn in fns:
fn()
</code></pre>
<p>How would I do the above properly?</p>
| 2 | 2016-08-19T00:29:33Z | 39,029,462 | <p>don't use a list of strings, just store the functions in the list:</p>
<pre><code>fns = [function1, function2]
for fn in fns:
fn()
</code></pre>
| 4 | 2016-08-19T00:35:35Z | [
"python"
] |
BeautifulSoup: findAll doesn't find the tags | 39,029,430 | <p>I'm sorry about the many questions I post, but I have no idea what to do about this bug: when testing this <a href="http://www.wired.com/2016/08/cape-watch-99/" rel="nofollow">page</a>, with simple <code>p</code>s</p>
<pre><code>ab=soup.find("article", {"itemprop":"articleBody"})
p=ab.findAll("p")
print(len(p)) #gives 1
</code></pre>
<p>There are many <code>p</code> tags, but I get only the first.
I tried to copy-paste the whole <code><article itemprop="articleBody"></code> html text into a string and passed it to a new <code>BeautifulSoup</code> object. Searching that object for <code>p</code> gave all the desired tags (14). </p>
<p>Why the usual approach doesn't work? Are the <code>p</code> tags loaded dynamically here (but the html code looks pretty normal)?</p>
| 1 | 2016-08-19T00:29:47Z | 39,030,583 | <p>Your code is giving only one p because when your are parsing soup and trying to see what it has parsed,it is getting only one paragraph
see below code</p>
<pre><code>ab = soup.find("article", {"itemprop": "articleBody"})
print ab
</code></pre>
<p>the output is </p>
<pre><code><article class="content link-underline relative body-copy" data-js="content" itemprop="articleBody">
<p>Not every update about a superhero movie is worthy of great attention. Take, for example, <a href="http://www.slashfilm.com/aquaman-setting/">the revelation</a> that not all of <em>Aquaman</em> will take place underwater</p></article>
</code></pre>
<p>since you are finding item under article tag and soup close the search when it find the closing article tag, and therefore its returning 1 as len of p which is correct as per your current code</p>
| 1 | 2016-08-19T03:17:58Z | [
"python",
"web-scraping",
"beautifulsoup"
] |
BeautifulSoup: findAll doesn't find the tags | 39,029,430 | <p>I'm sorry about the many questions I post, but I have no idea what to do about this bug: when testing this <a href="http://www.wired.com/2016/08/cape-watch-99/" rel="nofollow">page</a>, with simple <code>p</code>s</p>
<pre><code>ab=soup.find("article", {"itemprop":"articleBody"})
p=ab.findAll("p")
print(len(p)) #gives 1
</code></pre>
<p>There are many <code>p</code> tags, but I get only the first.
I tried to copy-paste the whole <code><article itemprop="articleBody"></code> html text into a string and passed it to a new <code>BeautifulSoup</code> object. Searching that object for <code>p</code> gave all the desired tags (14). </p>
<p>Why the usual approach doesn't work? Are the <code>p</code> tags loaded dynamically here (but the html code looks pretty normal)?</p>
| 1 | 2016-08-19T00:29:47Z | 39,036,620 | <p>The issue is the parser:</p>
<pre><code>In [21]: req = requests.get("http://www.wired.com/2016/08/cape-watch-99/")
In [22]: soup = BeautifulSoup(req.content, "lxml")
In [23]: len(soup.select("article[itemprop=articleBody] p"))
Out[23]: 26
In [24]: soup = BeautifulSoup(req.content, "html.parser")
In [25]: len(soup.select("article[itemprop=articleBody] p"))
Out[25]: 1
In [26]: soup = BeautifulSoup(req.content, "html5lib")
In [27]: len(soup.select("article[itemprop=articleBody] p"))
Out[27]: 26
</code></pre>
<p>You can see <em>html5lib</em> and <em>lxml</em> get all the p tags but the standard <em>html.parser</em> does not handle the broken html as well. Running the article html through <a href="https://validator.w3.org/" rel="nofollow">validator.w3</a> you get a lot of output, in particular:</p>
<p><a href="http://i.stack.imgur.com/XxYXo.png" rel="nofollow"><img src="http://i.stack.imgur.com/XxYXo.png" alt="enter image description here"></a></p>
| 1 | 2016-08-19T10:23:04Z | [
"python",
"web-scraping",
"beautifulsoup"
] |
(Python) How can I turn a csv file with thousands of 10 digit numbers into decimal? (10dig -> 3dig+7decimal) | 39,029,468 | <p>I am working with large data of GPS coordinates. These coordinates are coming in as 10 digit numbers (<code>1234567890</code>) from a csv file.</p>
<p>I have two 25,000 columns of 10 digit numbers for both Latitude and Longitude.</p>
<p>How can I turn <code>1234567890</code> into <code>123.4567890</code>?</p>
<p>I've looked at different ways to manipulate and extract strings, but am confused on how to make Python add a value a certain amount of spaces forward.</p>
<p>Thanks,</p>
| 0 | 2016-08-19T00:36:18Z | 39,029,533 | <p>So if your content is string and you need to divide by <code>10**7</code>, you could simply do this:</p>
<pre><code>def to_float(s):
return float(s)/10**7
</code></pre>
<p>then do <code>df.apply(to_float)</code></p>
| 0 | 2016-08-19T00:44:49Z | [
"python",
"pandas",
"numpy"
] |
(Python) How can I turn a csv file with thousands of 10 digit numbers into decimal? (10dig -> 3dig+7decimal) | 39,029,468 | <p>I am working with large data of GPS coordinates. These coordinates are coming in as 10 digit numbers (<code>1234567890</code>) from a csv file.</p>
<p>I have two 25,000 columns of 10 digit numbers for both Latitude and Longitude.</p>
<p>How can I turn <code>1234567890</code> into <code>123.4567890</code>?</p>
<p>I've looked at different ways to manipulate and extract strings, but am confused on how to make Python add a value a certain amount of spaces forward.</p>
<p>Thanks,</p>
| 0 | 2016-08-19T00:36:18Z | 39,042,720 | <p>If you want to convert the csv file itself (instead of the in-memory data read from the csv file), you could use the regular expression library.</p>
<pre><code>import re
with open('input.csv') as input_file, open('output.csv', 'w') as output_file:
for line in input_file:
line = re.sub(r'(\d{3})(\d{7})', r'\1.\2', line)
output_file.write(line)
</code></pre>
| 0 | 2016-08-19T15:25:15Z | [
"python",
"pandas",
"numpy"
] |
Pandas Python - Finding Time Series Not Covered | 39,029,480 | <p>Hoping someone can help me out with this one because I don't even know where to start.</p>
<p>Given a data frame that contains a series of start and end times, such as:</p>
<pre><code>Order Start Time End Time
1 2016-08-18 09:30:00.000 2016-08-18 09:30:05.000
1 2016-08-18 09:30:00.005 2016-08-18 09:30:25.001
1 2016-08-18 09:30:30.001 2016-08-18 09:30:56.002
1 2016-08-18 09:30:40.003 2016-08-18 09:31:05.003
1 2016-08-18 11:30:45.000 2016-08-18 13:31:05.000
</code></pre>
<p>For each order id, I am looking to find a list of time periods that are not covered by any of the ranges between the earliest start time and latest end time </p>
<p>So in the example above, I would be looking for </p>
<pre><code>2016-08-18 09:30:05.000 to 2016-08-18 09:30:00.005 (the time lag between the first and second rows)
2016-08-18 09:30:25.001 to 2016-08-18 09:30:30.001 (the time lag between the second and third rows)
</code></pre>
<p>and</p>
<pre><code>2016-08-18 09:31:05.003 to 2016-08-18 11:30:45.000 (the time period between 4 and 5)
</code></pre>
<p>There is overlap between the 3 and 4 rows, so they wouldn't count</p>
<p><strong>A few things to consider (additional color):</strong></p>
<p>Each record indicates an outstanding order placed at (for example) one of the stock exchanges. Therefore, I can have orders open at Nasdaq and NYSE at the same time. I also can have a short duration order at Nasdaq and a long one at NYSE starting at the same time.</p>
<p>That would look as following:</p>
<pre><code>Order Start Time End Time
1 2016-08-18 09:30:00.000 2016-08-18 09:30:05.000 (NYSE)
1 2016-08-18 09:30:00.001 2016-08-18 09:30:00.002 (NASDAQ)
</code></pre>
<p>I am trying to figure out when we are doing nothing at all, and I have no live orders on any exchanges. </p>
<p>I have zero idea where to even start on this..any ideas would be appreciated</p>
| 1 | 2016-08-19T00:37:10Z | 39,040,021 | <h3>Setup</h3>
<pre><code>from StringIO import StringIO
import pandas as pd
text = """Order Start Time End Time
1 2016-08-18 09:30:00.000 2016-08-18 09:30:05.000
1 2016-08-18 09:30:00.005 2016-08-18 09:30:25.001
1 2016-08-18 09:30:30.001 2016-08-18 09:30:56.002
1 2016-08-18 09:30:40.003 2016-08-18 09:31:05.003
1 2016-08-18 11:30:45.000 2016-08-18 13:31:05.000
2 2016-08-18 09:30:00.000 2016-08-18 09:30:05.000
2 2016-08-18 09:30:00.005 2016-08-18 09:30:25.001
2 2016-08-18 09:30:30.001 2016-08-18 09:30:56.002
2 2016-08-18 09:30:40.003 2016-08-18 09:31:05.003
2 2016-08-18 11:30:45.000 2016-08-18 13:31:05.000"""
df = pd.read_csv(StringIO(text), sep='\s{2,}', engine='python', parse_dates=[1, 2])
</code></pre>
<h3>Solution</h3>
<pre><code>def find_gaps(df, start_text='Start Time', end_text='End Time'):
# rearrange stuff to get all times and a tracker
# in single columns.
cols = [start_text, end_text]
df = df.reset_index()
df1 = df[cols].stack().reset_index(-1)
df1.columns = ['edge', 'time']
df1['edge'] = df1['edge'].eq(start_text).mul(2).sub(1)
# sort by ascending time, then descending edge
# (starts before ends if equal time)
# this will ensure we avoid zero length gaps.
df1 = df1.sort_values(['time', 'edge'], ascending=[True, False])
# we identify gaps when we've reached a number
# of ends equal to number of starts.
# we'll track that with cumsum, when cumsum is
# zero, we've found a gap
# last position should always be zero and is not a gap.
# So I remove it.
track = df1['edge'].cumsum().iloc[:-1]
gap_starts = track.index[track == 0]
gaps = df.ix[gap_starts]
gaps[start_text] = gaps[end_text]
gaps[end_text] = df.shift(-1).ix[gap_starts, start_text]
return gaps
df.set_index('Order').groupby(level=0).apply(find_gaps)
</code></pre>
<p><a href="http://i.stack.imgur.com/9Gyyl.png" rel="nofollow"><img src="http://i.stack.imgur.com/9Gyyl.png" alt="enter image description here"></a></p>
| 1 | 2016-08-19T13:14:27Z | [
"python",
"pandas",
"time-series"
] |
Subtrees of Phylogenetic Trees in BioPython | 39,029,517 | <p>I have a phylogenetic tree in newick format. I want to pull out a subtree based on the labels of the terminal nodes (so based on a list of species). A copy of the tree I am using can be found here: <a href="http://hgdownload.soe.ucsc.edu/goldenPath/dm6/multiz27way/dm6.27way.nh" rel="nofollow">http://hgdownload.soe.ucsc.edu/goldenPath/dm6/multiz27way/dm6.27way.nh</a></p>
<p>Currently I have read in the tree using BioPython like so:</p>
<pre><code>from Bio import Phylo
#read in Phylogenetic Tree
tree = Phylo.read('dm6.27way.nh', 'newick')
#list of species of interest
species_list = ['dm6', 'droSim1', 'droSec1', 'droYak3', 'droEre2', 'droBia2', 'droSuz1', 'droAna3', 'droBip2', 'droEug2', 'droEle2', 'droKik2', 'droTak2', 'droRho2', 'droFic2']
</code></pre>
<p>How would I pull out the subtree of only the species in species_list?</p>
| 1 | 2016-08-19T00:41:47Z | 39,029,641 | <p>Ok yeah, assuming you want the smallest tree that has all the species in your species list you want the root node of this tree to be the most recent common ancestor (MRCA) of all the species in the list which is thankfully already implemented in Phylo:</p>
<pre><code>from Bio import Phylo
#read in Phylogenetic Tree
tree = Phylo.read('dm6.27way.nh', 'newick')
#list of species of interest
species_list = ['dm6',
'droSim1',
'droSec1',
'droYak3',
'droEre2',
'droBia2',
'droSuz1',
'droAna3',
'droBip2',
'droEug2',
'droEle2',
'droKik2',
'droTak2',
'droRho2',
'droFic2']
common_ancestor = tree.common_ancestor(species_list)
Phylo.draw_ascii(common_ancestor)
</code></pre>
<p>output:</p>
<pre><code>Clade
___ dm6
___|
| | , droSim1
| |_|
__________| | droSec1
| |
| | _____ droYak3
,| |_|
|| |____ droEre2
||
|| _______ droBia2
||_____|
| |_____ droSuz1
|
__| _______ droAna3
| |_________________________________|
| | |________ droBip2
| |
| |___________________ droEug2
|
|_____________ droEle2
,|
||______________________________ droKik2
__||
| ||______________ droTak2
___________________| |
| |____________ droRho2
|
|_______________ droFic2
</code></pre>
| 3 | 2016-08-19T01:01:41Z | [
"python",
"tree",
"bioinformatics",
"biopython"
] |
Subtrees of Phylogenetic Trees in BioPython | 39,029,517 | <p>I have a phylogenetic tree in newick format. I want to pull out a subtree based on the labels of the terminal nodes (so based on a list of species). A copy of the tree I am using can be found here: <a href="http://hgdownload.soe.ucsc.edu/goldenPath/dm6/multiz27way/dm6.27way.nh" rel="nofollow">http://hgdownload.soe.ucsc.edu/goldenPath/dm6/multiz27way/dm6.27way.nh</a></p>
<p>Currently I have read in the tree using BioPython like so:</p>
<pre><code>from Bio import Phylo
#read in Phylogenetic Tree
tree = Phylo.read('dm6.27way.nh', 'newick')
#list of species of interest
species_list = ['dm6', 'droSim1', 'droSec1', 'droYak3', 'droEre2', 'droBia2', 'droSuz1', 'droAna3', 'droBip2', 'droEug2', 'droEle2', 'droKik2', 'droTak2', 'droRho2', 'droFic2']
</code></pre>
<p>How would I pull out the subtree of only the species in species_list?</p>
| 1 | 2016-08-19T00:41:47Z | 39,029,850 | <p>Instead of using BioPython, use <code>ete3</code>.</p>
<pre><code>from ete3 import Tree
t = Tree('dm6.27way.nh')
t.prune(species_list, preserve_branch_length=True)
t.write()
</code></pre>
<p>From the documentation,</p>
<p>From version 2.2, this function includes also the preserve_branch_length flag, which allows to remove nodes from a tree while keeping original distances among remaining nodes.</p>
| 0 | 2016-08-19T01:35:57Z | [
"python",
"tree",
"bioinformatics",
"biopython"
] |
NameError: name 'name' is not defined | 39,029,555 | <p>Currently working through Python Crash course and this example is giving me trouble</p>
<pre><code>class Restaurant():
def __init__(self, restaurant_name, cuisine_type):
""" initializing name and cuisine attributes"""
self.restaurant_name = name
self.cuisine_type = c_type
def greeting(self):
"""simulate greetting with restaurant info..."""
print(self.name.title() + " is a " + self.c_type.title()
+ " type of restaurant.")
def open_or_nah(self):
""" wheteher or not the restaurant is open in this case they will be always"""
print(self.name.title() + " is open af")
china_king = Restaurant('china king', 'chinese')
china_king.greeting
china_king.open_or_nah
</code></pre>
<p>the console keeps giving me the error</p>
<pre><code>Traceback (most recent call last):
File "python", line 16, in <module>
File "python", line 4, in __init__
NameError: name 'name' is not defined
</code></pre>
<p>I've searched around for the reason as to what is causing this but i can't figure it out. What's wrong?</p>
| -3 | 2016-08-19T00:49:43Z | 39,029,565 | <p>Looks like a small mistake, just modify it in your <code>__init__</code></p>
<pre><code>self.name = restaurant_name
</code></pre>
| 2 | 2016-08-19T00:52:01Z | [
"python",
"class"
] |
NameError: name 'name' is not defined | 39,029,555 | <p>Currently working through Python Crash course and this example is giving me trouble</p>
<pre><code>class Restaurant():
def __init__(self, restaurant_name, cuisine_type):
""" initializing name and cuisine attributes"""
self.restaurant_name = name
self.cuisine_type = c_type
def greeting(self):
"""simulate greetting with restaurant info..."""
print(self.name.title() + " is a " + self.c_type.title()
+ " type of restaurant.")
def open_or_nah(self):
""" wheteher or not the restaurant is open in this case they will be always"""
print(self.name.title() + " is open af")
china_king = Restaurant('china king', 'chinese')
china_king.greeting
china_king.open_or_nah
</code></pre>
<p>the console keeps giving me the error</p>
<pre><code>Traceback (most recent call last):
File "python", line 16, in <module>
File "python", line 4, in __init__
NameError: name 'name' is not defined
</code></pre>
<p>I've searched around for the reason as to what is causing this but i can't figure it out. What's wrong?</p>
| -3 | 2016-08-19T00:49:43Z | 39,029,592 | <pre><code>class Restaurant():
def __init__(self, restaurant_name, cuisine_type):
""" initializing name and cuisine attributes"""
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
</code></pre>
<p>name is not part of your class init. It should be <code>restaurant_name</code> which you are receiving as part of initialization.</p>
<p>or change it to below</p>
<pre><code>def __init__(self, name, c_type):
</code></pre>
| 0 | 2016-08-19T00:54:51Z | [
"python",
"class"
] |
NameError: name 'name' is not defined | 39,029,555 | <p>Currently working through Python Crash course and this example is giving me trouble</p>
<pre><code>class Restaurant():
def __init__(self, restaurant_name, cuisine_type):
""" initializing name and cuisine attributes"""
self.restaurant_name = name
self.cuisine_type = c_type
def greeting(self):
"""simulate greetting with restaurant info..."""
print(self.name.title() + " is a " + self.c_type.title()
+ " type of restaurant.")
def open_or_nah(self):
""" wheteher or not the restaurant is open in this case they will be always"""
print(self.name.title() + " is open af")
china_king = Restaurant('china king', 'chinese')
china_king.greeting
china_king.open_or_nah
</code></pre>
<p>the console keeps giving me the error</p>
<pre><code>Traceback (most recent call last):
File "python", line 16, in <module>
File "python", line 4, in __init__
NameError: name 'name' is not defined
</code></pre>
<p>I've searched around for the reason as to what is causing this but i can't figure it out. What's wrong?</p>
| -3 | 2016-08-19T00:49:43Z | 39,029,598 | <p>Your problem is in your <code>__init__</code> method in your <code>Restaurant</code> class.</p>
<pre><code>class Restaurant():
def __init__(self, restaurant_name, cuisine_type):
""" initializing name and cuisine attributes"""
self.restaurant_name = name
self.cuisine_type = c_type
</code></pre>
<p>Here, you can see that every time you create a new instance of class type <code>Restaurant</code>, you have to pass in two arguments for the parameters, <code>restaurant_name</code> and <code>cuisine_type</code>.</p>
<p>The <code>__init__</code> function can only see things that are passed into it, so when you tell it to look for <code>name</code> it is getting "confused". </p>
<p>Your <code>__init__</code> method is thinking: "<code>name</code>? What is <code>name</code>? I only know <code>restaurant_name</code> and <code>cuisine_type</code>, so I'm going to have to throw an error."</p>
<p>Your code should look like this:</p>
<pre><code>class Restaurant():
def __init__(self, restaurant_name, cuisine_type):
""" initializing name and cuisine attributes"""
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
</code></pre>
| 1 | 2016-08-19T00:55:59Z | [
"python",
"class"
] |
NameError: name 'name' is not defined | 39,029,555 | <p>Currently working through Python Crash course and this example is giving me trouble</p>
<pre><code>class Restaurant():
def __init__(self, restaurant_name, cuisine_type):
""" initializing name and cuisine attributes"""
self.restaurant_name = name
self.cuisine_type = c_type
def greeting(self):
"""simulate greetting with restaurant info..."""
print(self.name.title() + " is a " + self.c_type.title()
+ " type of restaurant.")
def open_or_nah(self):
""" wheteher or not the restaurant is open in this case they will be always"""
print(self.name.title() + " is open af")
china_king = Restaurant('china king', 'chinese')
china_king.greeting
china_king.open_or_nah
</code></pre>
<p>the console keeps giving me the error</p>
<pre><code>Traceback (most recent call last):
File "python", line 16, in <module>
File "python", line 4, in __init__
NameError: name 'name' is not defined
</code></pre>
<p>I've searched around for the reason as to what is causing this but i can't figure it out. What's wrong?</p>
| -3 | 2016-08-19T00:49:43Z | 39,029,608 | <p>Just a small mistake, from mixing variable names. Change your <code>__init__</code> function to</p>
<pre><code>def __init__(self, name, cuisine_type):
""" initializing name and cuisine attributes"""
self.name = name
self.cuisine_type = c_type
</code></pre>
| 1 | 2016-08-19T00:57:07Z | [
"python",
"class"
] |
Saving List of Tuples in XML | 39,029,570 | <p>I have a list of lists as such:</p>
<pre><code>[[value A, Value B, Value C], [value D, value E, Value F]]
</code></pre>
<p>I've got XML structure as follows:</p>
<pre><code><root>
<data>
</data>
</root>
</code></pre>
<p>I'm trying to understand the best way to write the list into XML. </p>
<p>I understand how to parse the XML, how to get the data, as well as how to write the data to the XML, using etree in my particular case. What I'm struggling with is a conceptual best-practice for storing this data-type in XML.</p>
<p>I apologize for the vauge-nature of this question, but I'm struggling with fundamentals here.</p>
<p>I have tried saving the entire list as a string, which saves fineâbut it's messy to deal with later on.</p>
<p><strong>UPDATED:</strong></p>
<p>using @mkHun 's general approach, with @Jon Clements attribute concept, the following works for my purposes:</p>
<pre><code>from lxml import etree
var = [["value A", "Value B", "Value C"], ["value D", "value E", "Value F"]]
for j in var:
root = etree.Element('root')
member = etree.SubElement(root, "member")
member.attrib['att1'] = j[0]
member.attrib['att2'] = j[1]
member.attrib['att3'] = j[2]
root.append(member)
out = etree.tostring(root, pretty_print=True)
print(out)
</code></pre>
<p>This approach, lessening the iterative depth to consolidate each list into a single <code>SubElement</code>, creates an XML structure similar to the following:</p>
<pre><code><root>
<member att1="Value A" att2="Value B" att3="Value C"/"
<member att1="Value D" att2="Value E" att3="Value F"/"
</root>
</code></pre>
<p>I am uncertain that this is the best, or most-efficient manner in which to store this data still, but for now it is the best method which I have tried. </p>
<p>Thanks</p>
| 1 | 2016-08-19T00:52:29Z | 39,029,649 | <p>use <code>lxml</code></p>
<pre><code>from lxml import etree
var = [["value A", "Value B", "Value C"], ["value D", "value E", "Value F"]]
for j in var:
root = etree.Element('root')
for m in j:
data = etree.Element('data')
data.text = m
root.append(data)
out = etree.tostring(root, pretty_print=True)
print out
</code></pre>
| 1 | 2016-08-19T01:03:34Z | [
"python",
"xml",
"list",
"nested-lists"
] |
Finding nested dynamically generated elements with Selenium | 39,029,575 | <p>I'm working with Selenium and the Chrome Driver, But I haven't been able to find an element by ID. However, this element is visible in the web inspector of the browser. I think this is because the element is dynamically generated (all the time I see the same URL in the Browser Url Bar, but content changes dynamically.</p>
<p>The way to solve it is to properly undersand driver waits. The first page is the login page which I can get past by succesfully:</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
delay = 5
username = driver.find_element_by_name('Username')
password = driver.find_element_by_name('Password')
username.send_keys('my_username')
password.send_keys('my_password')
login = driver.find_element_by_id('login_button')
login.click()
</code></pre>
<p>After this step I can succesfully find the element called say, button_a, after I click on this, the page generates a new button say, button_b, for which I use a wait for presence command.</p>
<pre><code>button_a = driver.find_element_by_id('button_a')
button_a.click()
WebDriverWait(driver, delay).until(
EC.presence_of_element_located(
driver.find_element_by_id('button_b')))
</code></pre>
<p>However this throws the classic exception:</p>
<pre><code>selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"id","selector":"button_b"}
</code></pre>
<p>It seems that the driver is keeping a reference to the old DOM and doesn't keep track of new elements added to the DOM, the page is not reloaded after the click on button_a but I just get the classic Spin Wheel where the client is dynamically generating new content. At this point I can clearly see that the button_b id exists by right clicking on the browser and then inspect.</p>
<p>Is this possible to solve with Selenium?</p>
<p>Excuse me I'm just a total noob in web browser automation.</p>
| 0 | 2016-08-19T00:53:01Z | 39,031,925 | <p>Actually you are going wrong, you are going to find element then use wait for WebElement. You should try using By locator instead as below :-</p>
<pre><code>button_a = driver.find_element_by_id('button_a')
button_a.click()
button_b = WebDriverWait(driver, delay).until(EC.presence_of_element_located((By.ID, 'button_b')))
</code></pre>
| 0 | 2016-08-19T05:49:45Z | [
"python",
"selenium",
"selenium-webdriver",
"selenium-chromedriver"
] |
Finding nested dynamically generated elements with Selenium | 39,029,575 | <p>I'm working with Selenium and the Chrome Driver, But I haven't been able to find an element by ID. However, this element is visible in the web inspector of the browser. I think this is because the element is dynamically generated (all the time I see the same URL in the Browser Url Bar, but content changes dynamically.</p>
<p>The way to solve it is to properly undersand driver waits. The first page is the login page which I can get past by succesfully:</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
delay = 5
username = driver.find_element_by_name('Username')
password = driver.find_element_by_name('Password')
username.send_keys('my_username')
password.send_keys('my_password')
login = driver.find_element_by_id('login_button')
login.click()
</code></pre>
<p>After this step I can succesfully find the element called say, button_a, after I click on this, the page generates a new button say, button_b, for which I use a wait for presence command.</p>
<pre><code>button_a = driver.find_element_by_id('button_a')
button_a.click()
WebDriverWait(driver, delay).until(
EC.presence_of_element_located(
driver.find_element_by_id('button_b')))
</code></pre>
<p>However this throws the classic exception:</p>
<pre><code>selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"id","selector":"button_b"}
</code></pre>
<p>It seems that the driver is keeping a reference to the old DOM and doesn't keep track of new elements added to the DOM, the page is not reloaded after the click on button_a but I just get the classic Spin Wheel where the client is dynamically generating new content. At this point I can clearly see that the button_b id exists by right clicking on the browser and then inspect.</p>
<p>Is this possible to solve with Selenium?</p>
<p>Excuse me I'm just a total noob in web browser automation.</p>
| 0 | 2016-08-19T00:53:01Z | 39,032,568 | <blockquote>
<p>It seems that the driver is keeping a reference to the old DOM and
doesn't keep track of new elements added to the DOM, the page is not
reloaded after the click on button_a but I just get the classic Spin
Wheel where the client is dynamically generating new content.
Actually Selenium detects any changes made to the DOM made by page reload, AJAX calls, Javascript execution, etc.
So, to put this to test, if you have let's say your <code>button_a</code> and try the following:</p>
</blockquote>
<pre><code>buttonA = driver.find_element_by_id("button_a")
//Ajax call here
buttonA.click()
</code></pre>
<p>you will get a <code>StaleElementReferenceException</code> error(element is no longer attached to DOM) meaning that any bindings made by Selenium to that element are lost.</p>
<p>Now, to overcome the issue that you have, using your example, you could go with:</p>
<pre><code>//get the first element, button_a and click it
//going by your example this means you have only one element containing `button`
//in the `id`
driver.find_element_by_xpath(".//*[contains(@id,'button')]").click()
//now, as you say, you will have 2 elements containing `button` in the `id`
//so get all the elements and click on the last one
buttonB = driver.find_elements_by_xpath(".//*[contains(@id,'button')]")
buttonB[len(buttonB)-1].click()
</code></pre>
<p>As a note, I apologize for any syntax errors if any, as I'm not a pythonist. </p>
| 0 | 2016-08-19T06:38:21Z | [
"python",
"selenium",
"selenium-webdriver",
"selenium-chromedriver"
] |
While loop not properly breaking, script hangs | 39,029,596 | <p>The problem is that it is not detecting a draw and just hangs if noone wins. I understand that it isn't a good practice to paste the whole script here and ask for help but I'm all out of ideas. I got this TicTacToe script off of github and am trying to implement random moves between two AI players (both making only random moves). </p>
<pre><code> import random
import time
class Tic(object):
winning_combos = (
[0, 1, 2], [3, 4, 5], [6, 7, 8],
[0, 3, 6], [1, 4, 7], [2, 5, 8],
[0, 4, 8], [2, 4, 6])
winners = ('X-win', 'Draw', 'O-win')
def __init__(self, squares=[]):
if len(squares) == 0:
self.squares = [" " for i in range(9)]
else:
self.squares = squares
def show(self):
for element in [self.squares[i:i + 3] for i in range(0, len(self.squares), 3)]:
print(element)
def available_moves(self):
"""what spots are left empty?"""
return [k for k, v in enumerate(self.squares) if v is " "]
def available_combos(self, player):
"""what combos are available?"""
return self.available_moves() + self.get_squares(player)
def complete(self):
"""is the game over?"""
if " " not in [v for v in self.squares]:
return True
if self.winner() != " ":
return True
return False
def X_won(self):
return self.winner() == 'X'
def O_won(self):
return self.winner() == 'O'
def tied(self):
return self.complete() is True and self.winner() is " "
def winner(self):
for player in ('X', 'O'):
positions = self.get_squares(player)
for combo in self.winning_combos:
win = True
for pos in combo:
if pos not in positions:
win = False
if win:
return player
return " "
def get_squares(self, player):
"""squares that belong to a player"""
return [k for k, v in enumerate(self.squares) if v == player]
def make_move(self, position, player):
"""place on square on the board"""
self.squares[position] = player
def determine(board, player):
a = -2
choices = []
if len(board.available_moves()) == 9:
return 4
for move in board.available_moves():
board.make_move(move, player)
board.make_move(move, " ")
if val > a:
a = val
choices = [move]
elif val == a:
choices.append(move)
return random.choice(choices)
def get_enemy(player):
if player == 'O':
return 'X'
return 'O'
board = Tic()
count = 0
player = 'X'
while not board.complete():
if board.complete():
break
while count == 0:
player_move = int(random.randint(1, 9))
if player_move not in board.available_moves():
continue
board.make_move(player_move, player)
player = get_enemy(player)
count += 1
while count == 1:
computer_move = int(random.randint(1, 9))
if computer_move not in board.available_moves():
continue
board.make_move(computer_move, player)
count -= 1
if board.complete():
break
if board.complete():
print("winner is", board.winner())
final_win = "winner is " + board.winner()
log = open("log_for_orig.txt", "a")
log.write(final_win + "\n" + "\n")
</code></pre>
| -3 | 2016-08-19T00:55:42Z | 39,029,667 | <p>Player block</p>
<pre><code> while count == 0:
player_move = int(random.randint(1, 9))
if player_move not in board.available_moves():
continue
</code></pre>
<p>Computer block</p>
<pre><code> while count == 1:
computer_move = int(random.randint(1, 9))
if computer_move not in board.available_moves():
continue
</code></pre>
<p>Problem lies in above two blocks of code. </p>
<p>In the first block, when count is 0, and player_move is not in available moves, then you are skipping by doing continue, so count still remains 0, which will make it enter in same first block and this pattern continues until unless player changes his move. You should basically prompt user to change his move rather than continuing.</p>
<p>Same applies for second block of code as well. As computer is playing, you should deal it in much better way.</p>
| 0 | 2016-08-19T01:06:35Z | [
"python",
"python-2.7"
] |
While loop not properly breaking, script hangs | 39,029,596 | <p>The problem is that it is not detecting a draw and just hangs if noone wins. I understand that it isn't a good practice to paste the whole script here and ask for help but I'm all out of ideas. I got this TicTacToe script off of github and am trying to implement random moves between two AI players (both making only random moves). </p>
<pre><code> import random
import time
class Tic(object):
winning_combos = (
[0, 1, 2], [3, 4, 5], [6, 7, 8],
[0, 3, 6], [1, 4, 7], [2, 5, 8],
[0, 4, 8], [2, 4, 6])
winners = ('X-win', 'Draw', 'O-win')
def __init__(self, squares=[]):
if len(squares) == 0:
self.squares = [" " for i in range(9)]
else:
self.squares = squares
def show(self):
for element in [self.squares[i:i + 3] for i in range(0, len(self.squares), 3)]:
print(element)
def available_moves(self):
"""what spots are left empty?"""
return [k for k, v in enumerate(self.squares) if v is " "]
def available_combos(self, player):
"""what combos are available?"""
return self.available_moves() + self.get_squares(player)
def complete(self):
"""is the game over?"""
if " " not in [v for v in self.squares]:
return True
if self.winner() != " ":
return True
return False
def X_won(self):
return self.winner() == 'X'
def O_won(self):
return self.winner() == 'O'
def tied(self):
return self.complete() is True and self.winner() is " "
def winner(self):
for player in ('X', 'O'):
positions = self.get_squares(player)
for combo in self.winning_combos:
win = True
for pos in combo:
if pos not in positions:
win = False
if win:
return player
return " "
def get_squares(self, player):
"""squares that belong to a player"""
return [k for k, v in enumerate(self.squares) if v == player]
def make_move(self, position, player):
"""place on square on the board"""
self.squares[position] = player
def determine(board, player):
a = -2
choices = []
if len(board.available_moves()) == 9:
return 4
for move in board.available_moves():
board.make_move(move, player)
board.make_move(move, " ")
if val > a:
a = val
choices = [move]
elif val == a:
choices.append(move)
return random.choice(choices)
def get_enemy(player):
if player == 'O':
return 'X'
return 'O'
board = Tic()
count = 0
player = 'X'
while not board.complete():
if board.complete():
break
while count == 0:
player_move = int(random.randint(1, 9))
if player_move not in board.available_moves():
continue
board.make_move(player_move, player)
player = get_enemy(player)
count += 1
while count == 1:
computer_move = int(random.randint(1, 9))
if computer_move not in board.available_moves():
continue
board.make_move(computer_move, player)
count -= 1
if board.complete():
break
if board.complete():
print("winner is", board.winner())
final_win = "winner is " + board.winner()
log = open("log_for_orig.txt", "a")
log.write(final_win + "\n" + "\n")
</code></pre>
| -3 | 2016-08-19T00:55:42Z | 39,029,970 | <p>This is a very poor way to select an available move:</p>
<pre><code>while count == 0:
player_move = int(random.randint(1, 9))
if player_move not in board.available_moves():
continue
</code></pre>
<p>It will work OK when there are lots of available moves. But when there are very few available moves, it may take a long time for <code>random.randint()</code> to pick one of them, so your program may seem to hang.</p>
<p>The <code>random</code> module provides a function for selecting an element from a list directly.</p>
<pre><code>if count == 0:
player_move = random.choice(board.available_moves())
</code></pre>
<p>See <a href="http://stackoverflow.com/questions/306400/how-do-i-randomly-select-an-item-from-a-list-using-python">How do I randomly select an item from a list using Python?</a></p>
| 1 | 2016-08-19T01:53:28Z | [
"python",
"python-2.7"
] |
Reading a pre-formatted binary file in Python | 39,029,615 | <p>So, I created a simple binary file using MATLAB that has the following structure:</p>
<pre><code>file.test
--------
[record_type] = 1 % 'int', 4 bytes, record_type = 1 means a string is read next
[string_length] = len(str) % 'int', 4 bytes, tells us how many bytes to read
[string] = '...' % 'char', the number of bytes in string length
[record_type] = 2 % 'int', 4 bytes, record_type = 2 means a vector will be read
[rows] = size(vector,1) % 'int', 4 bytes
[columns] = size(vector,2) % 'int', 4 bytes
[vector] = (vector) % 'double'
</code></pre>
<p>I can read this file back in MATLAB with the following code (this is just the read portions of the code, I do have error checking and other things):</p>
<pre><code>fid=fopen('file.test','rb')
record_names={}
record_data=[]
while ~feof(fid)
[record_name_type,count]=fread(fid,1,'int');
if count == 0 % reached eof
break;
end
record_name_length=fread(fid,1,'int');
record_names{end+1}=char(fread(fid,record_name_length,'char')');
% read vector
record_type=fread(fid,1,'int');
rows=fread(fid,1,'int');
cols=fread(fid,1,'int');
record_data{end+1}=fread(fid,[rows,cols],'double');
end
</code></pre>
<p>So, I had to translate this same function into Python 2.7. Unfortunately, it's proving to be very difficult. I can't just call <code>fread</code> anymore and tell it how many elements or bytes I want to read. I have tried the following code with <code>structs</code>:</p>
<pre><code>def read_file(filename):
# checking to see if file exists / other checks happen
fid=open(filename,'rb')
record_data=[]
record_names=[]
result=read_record(fid)
while result:
record_names.append(result['record_name'])
record_names.append(result['data'])
result=read_record(fid)
fid.close()
return (record_names, record_data)
def read_record(fid):
try:
# read name
record_name_type = struct.unpack('i',fid.read(struct.calcsize('i')))[0]
record_name_len = struct.unpack('i',fid.read(struct.calcsize('i')))[0]
record_name = struct.unpack('s',fid.read(record_name_len))[0]
# read vector
record_type = struct.unpack('i',fid.read(struct.calcsize('i')))[0]
rows = struct.unpack('i',fid.read(struct.calcsize('i')))[0]
cols = struct.unpack('i',fid.read(struct.calcsize('i')))[0]
record_data = numpy.array(struct.unpack('%dd' % rows,fid.read(rows*struct.calcsize('d'))),dtype=float)
# store into result and return
result=OrderedDict()
result['record_name']=record_name
result['data']=record_data
except struct.error as e:
print e
result=None
return result
</code></pre>
<p>Now when running my method in python, I get the following error:</p>
<p><code>unpack requires a string argument of length 1</code> which is coming from the <code>except strcut.error as e</code> portion. I had a feeling I was reading the vector incorrectly but I don't know how I'm reading the string incorrectly.</p>
<p>Does anyone know of an easier way to read this binary file? Or is there some tutorial I could follow to help me understand how to properly use structs in Python? I'm really new to it and especially this area in Python.</p>
| 0 | 2016-08-19T00:57:39Z | 39,029,729 | <p>You can use <a href="https://construct.readthedocs.io/en/latest/" rel="nofollow">Construct</a>:</p>
<pre><code>from construct import *
MyData = Struct(
"MyData",
SBInt32("record_type"),
Switch("value", lambda ctx: ctx.record_type,
{
1: Embed(Struct(
'string_data',
SBInt32("string_length"), Bytes("string", lambda ctx: ctx.string_length))),
2: Embed(Struct(
'vector_data',
SBInt32("rows"), SBInt32("columns"),
Array(lambda ctx: ctx.rows * ctx.columns, LFloat64("vector"))))
}
)
)
s = MyData.build(Container(record_type=1, string_length=4, string='abcd'))
print(repr(s))
print(MyData.parse(s))
s = MyData.build(Container(record_type=2, rows=2, columns=3, vector=[1, 2, 3, 4, 5, 6]))
print(repr(s))
print(MyData.parse(s))
</code></pre>
<p>The output:</p>
<pre><code>'\x00\x00\x00\x01\x00\x00\x00\x04abcd'
Container:
record_type = 1
string_length = 4
string = 'abcd'
'\x00\x00\x00\x02\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\x00@\x00\x00\x00\x00\x00\x00\x08@\x00\x00\x00\x00\x00\x00\x10@\x00\x00\x00\x00\x00\x00\x14@\x00\x00\x00\x00\x00\x00\x18@'
Container:
record_type = 2
rows = 2
columns = 3
vector = [
1.0
2.0
3.0
4.0
5.0
6.0
]
</code></pre>
| 0 | 2016-08-19T01:18:03Z | [
"python",
"matlab",
"file",
"numpy",
"binary"
] |
Printing color to the python command line | 39,029,635 | <p>I was working away on a project in python, and I was wondering how to pront with color. I know of colorama, and termcolor, but they are not working.
When I run this code in my python interpreter (PyCharm: <a href="https://www.jetbrains.com/pycharm/" rel="nofollow">https://www.jetbrains.com/pycharm/</a>) the colors work fine, but in the command line, the following:</p>
<pre><code>import colorama
print(colorama.Fore.GREEN + 'Green text')
</code></pre>
<p>Outputs as:</p>
<pre><code>[32mGreenText
</code></pre>
<p>Between the '[', and the begining of the line, their is a strange character. I know it is not ASCII, and probabaly not Unicode, so I took a screenshot of it.
<a href="http://i.stack.imgur.com/I7cIc.png" rel="nofollow">enter image description here</a>
-I do not know if that worked, this is my first post-</p>
<p>Thanks in advance
HELP ME!!!!!!!!</p>
| -1 | 2016-08-19T01:00:36Z | 39,029,679 | <p>Call <code>colorama.init()</code> before <code>print()</code>:</p>
<pre><code>import colorama
colorama.init(autoreset=True)
print(colorama.Fore.GREEN + 'Green text')
</code></pre>
| 0 | 2016-08-19T01:08:23Z | [
"python",
"printing",
"colors",
"command-line-interface"
] |
pandas dataframe look ahead value | 39,029,709 | <p>What's the best way to do this with pandas dataframe? I want to loop through a dataframe, and compute the difference between the current value and the next value which is different than the current value.
For example:
[13, 13, 13, 14, 13, 12]
will create a new column with this
[-1, -1, -1, 1, 1]</p>
| 0 | 2016-08-19T01:13:33Z | 39,030,005 | <p>How about use <code>diff</code> to calculate the difference and then back fill 0 with the next non zero value:</p>
<pre><code>import pandas as pd
import numpy as np
df = pd.DataFrame({"S": [13, 13, 13, 14, 13, 12]})
df.S.diff(-1).replace(0, np.nan).bfill() # replace zero with nan and apply back fill.
# 0 -1
# 1 -1
# 2 -1
# 3 1
# 4 1
# 5 NaN
# Name: S, dtype: float64
</code></pre>
| 1 | 2016-08-19T01:57:45Z | [
"python",
"pandas",
"dataframe"
] |
Sprite duplicating itself..? | 39,029,712 | <p>While doing some test in python, one of the sprites in a Player class randomly started duplicating itself.. I can't figure it out.. (I realize it's probally something really simple)</p>
<p>Here's the code:</p>
<pre><code>import pygame
from pygame.locals import *
import time
pygame.font.init()
myfont = pygame.font.SysFont("mirc", 25)
screen = pygame.display.set_mode((720, 480))
clock = pygame.time.Clock()
health = 10
keys = {"w":False, "a":False, "s":False, "d":False, " ":False}
class Thing:
def __init__(self, picture):
self.texture = pygame.image.load(picture).convert()
self.position = [360, 240]
def draw(self, screen):
screen.blit(self.texture, tuple([int(e) for e in self.position]))
def move(self, direction, distance):
if direction == "UP":
self.position[1] -= distance
elif direction == "DOWN":
self.position[1] += distance
elif direction == "RIGHT":
self.position[0] += distance
elif direction == "LEFT":
self.position[0] -= distance
class Enemy:
def __init__(self, picture):
self.texture = pygame.image.load(picture).convert()
self.position = [15, 110]
def draw(self, screen):
screen.blit(self.texture, tuple([int(e) for e in self.position]))
def move(self, distance):
if player.direction == "UP":
self.position[1] -= distance
elif player.direction == "DOWN":
self.position[0] -= distance
elif player.direction == "RIGHT":
self.position[1] += distance
elif player.direction == "LEFT":
self.position[1] += distance
done = False
black = (0, 0, 0)
player = Thing("2.png")
enemy = Enemy("1.png")
while not done:
clock.tick(60)
for event in pygame.event.get():
if event.type == QUIT:
done = True
if event.type == KEYDOWN:
if event.key == K_w:
keys["w"] = True
if event.key == K_a:
keys["a"] = True
if event.key == K_s:
keys["s"] = True
if event.key == K_d:
keys["d"] = True
if event.key == K_SPACE:
keys[" "] = True
if event.type == KEYUP:
if event.key == K_w:
keys["w"] = False
if event.key == K_a:
keys["a"] = False
if event.key == K_s:
keys["s"] = False
if event.key == K_d:
keys["d"] = False
if event.key == K_SPACE:
keys[" "] = False
#Consistent movement
if keys["w"]:
player.move("UP", 2)
if keys["a"]:
player.move("LEFT", 2)
if keys["s"]:
player.move("DOWN", 2)
if keys["d"]:
player.move("RIGHT", 2)
#if keys[" "]:
#Shoot..
#Walls - Player
if player.position[1] <= -2:
player.position[1] += 2
if player.position[1] >= 433:
player.position[1] -= 2
if player.position[0] <= -2:
player.position[0] += 2
if player.position[0] >= 690:
player.position[0] -= 2
#Walls - Enemy
if enemy.position[1] <= -2:
enemy.position[1] += 2
if enemy.position[1] >= 433:
enemy.position[1] -= 2
if enemy.position[0] <= -2:
enemy.position[0] += 2
if enemy.position[0] >= 690:
enemy.position[0] -= 2
#Text
label = myfont.render("Health: " + str(health), 50, (255, 255, 255))
screen.blit(label, (5, 5))
player.draw(screen)
pygame.display.flip()
pygame.quit()
</code></pre>
| -1 | 2016-08-19T01:14:05Z | 39,029,774 | <p>Turns out my original answer was close - your problem is that you're simply drawing the image - you never fill the screen even though you've declared <code>black = (0, 0, 0)</code>. You need to put <code>screen.fill(black)</code> before you start drawing everything else.</p>
<hr>
<p>For the record, here is what a <strong>Minimal</strong>, Complete, and Verifiable example looks like:</p>
<pre><code>import pygame
from pygame.locals import *
import time
pygame.font.init()
myfont = pygame.font.SysFont("mirc", 25)
screen = pygame.display.set_mode((720, 480))
clock = pygame.time.Clock()
class Thing:
def __init__(self, picture):
self.texture = pygame.image.load(picture).convert()
self.position = [360, 240]
def draw(self, screen):
screen.blit(self.texture, self.position)
done = False
black = (0, 0, 0)
player = Thing(os.path.expanduser("~/Downloads/disapproval.png"))
x_direction = 1
y_direction = 0
while not done:
clock.tick(60)
for event in pygame.event.get():
if event.type == QUIT:
done = True
if player.position[0] < 400:
x_direction = 1
y_direction = 0
elif player.position[0] >= 400 and player.position[1] > 100:
x_direction = 0
y_direction = -1
else:
x_direction = 0
y_direction = 0
player.position[0] += x_direction
player.position[1] += y_direction
# Uncomment this line, and you'll fix your problem
#screen.fill(black)
player.draw(screen)
pygame.display.flip()
pygame.quit()
</code></pre>
<p><strong>disapproval.png</strong><br>
<a href="http://i.stack.imgur.com/HMeSR.png" rel="nofollow"><img src="http://i.stack.imgur.com/HMeSR.png" alt="disapproval"></a></p>
| 0 | 2016-08-19T01:25:27Z | [
"python",
"pygame"
] |
Python + kivy: How to display multi language in one label (Unicode)? | 39,029,719 | <p>Using the following code I want to display letters from some languages into <strong>one label</strong>. </p>
<p>These languages are: <strong>English, German, Japanese, Chinese, Russian, French, Spanish, Arabic.</strong> </p>
<p>I tried with some Windows system fonts, but none of them could display <strong>ALL</strong> letters correctly. </p>
<p>I would like to know if there is any font to support all of the languages above?</p>
<p>Or how can I do it in kivy? (to have all of them in one label.)</p>
<p>Here is the code:</p>
<pre><code># -*- coding: utf-8 -*-
from kivy.app import App
#kivy.require("1.8.0")
from kivy.uix.label import Label
from kivy.uix.widget import Widget
from kivy.lang import Builder
import kivy.resources
#kivy.resources.resource_add_path(r'/home/kivy/android/android-sdk-linux/platforms/android-18/data/fonts')
kivy.resources.resource_add_path('C:\Windows\Fonts')
import os.path
Builder.load_string('''
<Label>:
font_name: 'AdobeGothicStd-Bold.otf'
<Widgets>:
Label:
text: "ABC ÃäÃüà ã«ã»ãã 䏿 ÑÑÌÑÑкий ÑзÑÌк ÃéÃèÃêÃë EspañolØ§ÙØ¹ÙØ±ÙØ¨ÙÙÙÙØ©â âfrançais"
size: root.width, 75
pos: root.x, root.top - 150
font_size: 50
height: 75
''')
class Widgets(Widget):
def build(self):
return Widgets()
class MyApp(App):
def build(self):
return Widgets()
if __name__ == "__main__":
MyApp().run()
</code></pre>
<p>Thanks!</p>
| 0 | 2016-08-19T01:15:26Z | 39,034,644 | <p>For many technical and social reasons you won't find a single font of good quality that covers all the locales you want to target.</p>
<p>Good software achieves what you intend to do by composing different fonts (and the labels need to be annotated with the target locale, codepoint is not enough, Japanese and Chinese codepoints overlap but should not be rendered the same way).</p>
<p>Lots of python software is not internationalization-ready and still assumes selecting a specific font or font file is good enough. Yes it is but only in an ascii world.</p>
<p>To learn about font composition, look up fontconfig and harfbuzz-ng. </p>
| 1 | 2016-08-19T08:39:35Z | [
"python",
"unicode",
"character-encoding",
"kivy"
] |
Flask CORS and Flask Limiter | 39,029,767 | <p>I am using flask cors, flask limiter and AngularJS for my web-app.. Everything is working fine but what I want is too return a 429 too many request message on the front-end but I can't seem to do that because the OPTIONS methods blocks everything once it returns a 429</p>
<p>My AngularJS error response code: </p>
<pre><code>function(response){
var res_data = (response.data && response.data.data) ? response.data.data : null;
var res_status = response.status;
FlashService.Error(response[keys.issue_fields], true);
if (res_status == 513 && res_data && res_data[keys.issue_fields][0] == keys.email) {
vm.error = "Your email is not recognized. Please try again.";
} else if (res_status == 513 && res_data && res_data[keys.issue_fields][0] == keys.password){
vm.error = "Your email and password combination was incorrect. Please try again.";
} else if (res_status == 513 && res_data && res_data[keys.issue_fields][0] == keys.suspension){
vm.error = "Your account is inactive.";
}else if (res_status == 429) {
vm.error = "You have attempted a numerous login failed attempt.. Please try again later.";
}else if (res_status == -1) {
vm.error = "Server Error. Please try again later.";
}else {
vm.error = "Your email and password combination was incorrect. Please try again.";
}
vm.dataLoading = false;
});
</code></pre>
<p>This is my flask code:</p>
<pre><code>@user_manager.route('/login/dp', methods=['POST'])
#make sure limit_key is changed if modify limit since it is hard coded
@limiter.limit("5/15minute")
def login_dp():
if key.email() in request.form and key.password() in request.form:
user_id = CBDPUserDatabase().login(request.form[key.email()], request.form[key.password()])
if user_id > 0:
limit_key = 'LIMITER/%s/%s/10/15/minute' % (get_ipaddr(), request.endpoint)
if limit_key in limiter._storage.storage: del limiter._storage.storage[limit_key]
if limit_key in limiter._storage.expirations: del limiter._storage.expirations[limit_key]
user_profile = CBDPUserDatabase().fetch_user_profile(user_id)
token = create_dp_token(user_id, user_profile[key.dealership()][key.id()])
if user_profile is not None:
return ResponsePacket.success(data={key.profile(): user_profile, key.token(): token})
else:
# Couldn't retrieve the user's profile
return ResponsePacket.data_exception(data={key.issue_fields(): [key.profile()]})
elif user_id == -2:
# Email address not found in user database
return ResponsePacket.data_exception(data={key.issue_fields(): [key.email()]})
elif user_id == -3:
# Password given does not match
return ResponsePacket.data_exception(data={key.issue_fields(): [key.password()]})
elif user_id == -4:
return ResponsePacket.data_exception(data={key.issue_fields(): [key.suspension()]})
else:
return ResponsePacket.request_exception()
</code></pre>
<p>This is my CORS setup:</p>
<pre><code>cors = CORS(application, resources={r"*": {"origins": "*"}})
</code></pre>
<p>Here is my flask logs:</p>
<pre><code>127.0.0.1 - - [19/Aug/2016 08:10:02] "OPTIONS /user/login/dp HTTP/1.1" 200 -
127.0.0.1 - - [19/Aug/2016 08:10:04] "POST /user/login/dp HTTP/1.1" 513 -
127.0.0.1 - - [19/Aug/2016 08:10:06] "POST /user/login/dp HTTP/1.1" 513 -
127.0.0.1 - - [19/Aug/2016 08:10:07] "POST /user/login/dp HTTP/1.1" 513 -
127.0.0.1 - - [19/Aug/2016 08:10:08] "OPTIONS /user/login/dp HTTP/1.1" 200 -
127.0.0.1 - - [19/Aug/2016 08:10:08] "POST /user/login/dp HTTP/1.1" 429 -
127.0.0.1 - - [19/Aug/2016 08:10:10] "POST /user/login/dp HTTP/1.1" 429 -
127.0.0.1 - - [19/Aug/2016 08:10:13] "OPTIONS /user/login/dp HTTP/1.1" 429 -
127.0.0.1 - - [19/Aug/2016 08:10:22] "OPTIONS /user/login/dp HTTP/1.1" 429 -
127.0.0.1 - - [19/Aug/2016 08:10:24] "OPTIONS /user/login/dp HTTP/1.1" 429 -
127.0.0.1 - - [19/Aug/2016 08:10:24] "OPTIONS /user/login/dp HTTP/1.1" 429 -
127.0.0.1 - - [19/Aug/2016 08:10:26] "OPTIONS /user/login/dp HTTP/1.1" 429 -
</code></pre>
<p>Here is my web console</p>
<p><a href="http://i.stack.imgur.com/AEr1m.png" rel="nofollow"><img src="http://i.stack.imgur.com/AEr1m.png" alt="enter image description here"></a></p>
| 0 | 2016-08-19T01:24:48Z | 39,030,577 | <p>I got it now! Just put a methods parameter</p>
<pre><code>@limiter.limit("20/15minute", methods=['POST'])
</code></pre>
| 0 | 2016-08-19T03:17:02Z | [
"python",
"angularjs",
"flask",
"flask-cors"
] |
Does "%" divide the length of the word? If so, why does only 'why' come up? | 39,029,785 | <p>I hope to turn this into an app to remind myself to think every once in a while. I would like to ask 'why'/'why not' every time I put an input in. I wanna make the determinant factor whether or not the length of the <code>notoriginal</code>/<code>alsonotoriginal</code> is even or odd. </p>
<pre><code>print ('Have you thought today?')
original = input('Yes or No:')
if len(original) > 2:
notoriginal = input('When?:')
elif len(original) < 3:
alsonotoriginal = input('Why?:')
while len(notoriginal) % 2 == 0:
input('Why not?:')
while len(notoriginal) % 2 > 0:
input('Why?:')
while len(alsonotoriginal) % 2 == 0:
input('Why not?:')
while len(alsonotoriginal) % 2 > 0:
input('Why?:')
</code></pre>
<p>You guys are the best! Thanks!</p>
<p>Edit: Thank you for all your help. I realize this was a pretty simple thing that I messed up. I'd also like to point out that I've since changed the original/notoriginal to better variable names such as second, third, and fourth. I fixed the problem I had, I took your suggestions. What I was confused/forgot about was that you could simply rename variables later in the code and the whole variable would change. What I had was this:</p>
<pre><code>print ('Have you thought today?')
first = input('Yes or No:')
if len(*first*) > 2:
**second** = input('When?:')
elif len(*second*) < 3:
**third** = input('Why?:')
if len(third) % 2 == 0:
fourth = input('Why not?:')
else:
fifth = input('Why?:')
while len(fourth) % 2 == 0:
fifth = input('Why?')
while len(fourth) % 2 > 0:
sixth = input('Why not?')
</code></pre>
<p>The problem was that I kept renaming variables, when they didn't have to be renamed and in fact caused an error because they were renamed. I was calling on the code to assess two separate variables when I should've been calling the code to check on a single variable that had two separate outcome values, like so:</p>
<pre><code>print ('Have you thought today?')
first = input('Yes or No:')
if len(first) > 2:
second = input('When?:')
elif len(first) < 3:
second = input('Why?:')
if len(second) % 2 == 0:
third = input('Why not?:')
else:
third = input('Why?:')
while len(third) % 2 == 0:
third = input('Why?')
while len(third) % 2 > 0:
third = input('Why not?')
</code></pre>
| -3 | 2016-08-19T01:26:51Z | 39,030,146 | <h2>The % Operand</h2>
<blockquote>
<p>The % (modulo) operator yields the remainder from the division of the
first argument by the second. The numeric arguments are first
converted to a common type. A zero right argument raises the
ZeroDivisionError exception. The arguments may be floating point
numbers, e.g., 3.14%0.7 equals 0.34 (since 3.14 equals 4*0.7 + 0.34.)
The modulo operator always yields a result with the same sign as its
second operand (or zero); the absolute value of the result is strictly
smaller than the absolute value of the second operand</p>
</blockquote>
<p><a href="https://docs.python.org/3/reference/expressions.html#binary-arithmetic-operations" rel="nofollow" title="taken from here">taken from here</a></p>
<p>To divide <code>len('word')</code> you can use the <code>/</code> operand, but by using the <code>% 2</code> operation you are able to determine if a number is even or not by analyzing the result, if it returns 0, it is even, if it does not, it is odd, like so:</p>
<pre><code>number = input('Type a number: ')
if number % 2 == 0:
print('Even')
else:
print('Odd')
</code></pre>
<hr>
<h2>Why the 'why' input keeps coming up</h2>
<p>The reason your code loops and seems to get stuck on the 'why?' question is because you are using <code>while len(notoriginal) % 2 > 0</code> and <code>while len(alsonotoriginal) % 2 > 0</code>, since the <code>notoriginal</code> and the <code>alsonotoriginal</code> values don't change after the input, you get what is called a 'infinite loop', the same <code>while</code> loop will run forever. To fix this, instead of using <code>while</code>, you could use a <code>if</code> and <code>elif</code> statement, but doing so will require you to fix your code logic, since it's quite flawed at the moment.</p>
<hr>
<h2>Also...</h2>
<p>Don't ever call your variables these generic names, it just makes for very confusing debugging later on.</p>
| 2 | 2016-08-19T02:16:07Z | [
"python",
"loops",
"division"
] |
PIP doesn't seem to be installing correctly | 39,029,810 | <p>I have updated my path for python 3.5.2 to its installation folder and installed pip manually through the get-pip.py file.</p>
<p>PIP is saying "Requirement already up-to-date: pip in c:\users\MyName\appdata\local\programs\python\python35-32\lib\site-packages"</p>
<p>When typing pip into CMD, it is saying that it is not recognized. Any alternatives?</p>
| 0 | 2016-08-19T01:30:30Z | 39,029,839 | <p>Pip is not in your Path. The path variable is a place that holds directories for all your commands. Including commands like python. Right now it searches in all the directories listed in the Path variable, and when not found it will output a command not recognized error.</p>
<p>Windows: </p>
<p><a href="http://www.howtogeek.com/118594/how-to-edit-your-system-path-for-easy-command-line-access/" rel="nofollow">http://www.howtogeek.com/118594/how-to-edit-your-system-path-for-easy-command-line-access/</a></p>
<p>Mac OSX/Linux:</p>
<p><a href="https://coolestguidesontheplanet.com/add-shell-path-osx/" rel="nofollow">https://coolestguidesontheplanet.com/add-shell-path-osx/</a></p>
| 0 | 2016-08-19T01:34:16Z | [
"python",
"pip",
"python-3.5"
] |
PIP doesn't seem to be installing correctly | 39,029,810 | <p>I have updated my path for python 3.5.2 to its installation folder and installed pip manually through the get-pip.py file.</p>
<p>PIP is saying "Requirement already up-to-date: pip in c:\users\MyName\appdata\local\programs\python\python35-32\lib\site-packages"</p>
<p>When typing pip into CMD, it is saying that it is not recognized. Any alternatives?</p>
| 0 | 2016-08-19T01:30:30Z | 39,029,852 | <p>You need adding pip.exe directory (C:\Pythonxxx\Scripts) to PATH Environment Variable in Windows.</p>
| 1 | 2016-08-19T01:36:03Z | [
"python",
"pip",
"python-3.5"
] |
Python - using re.compile with re.split | 39,029,811 | <p>I am trying to extract specific data from a text file. Each line of the file has strings separated by tabs. I would like to separate each word and keep it as whole word. Is it possible to combine re.split and re.compile.findall to do this? </p>
<p>An example is shown below. </p>
<p>Original line in file: </p>
<pre><code>Name Charlie Blue Bird ******Grade:5****** ****** ****** ******
</code></pre>
<p>Line separated by tabs: </p>
<pre><code>['Name', 'Charlie Blue Bird', '******Grade:5******', '******', '******']
</code></pre>
<p>Line that I would like to have: </p>
<pre><code>['Name', 'Charlie', 'Blue', 'Bird', 'Grade:5']
</code></pre>
<p>Any help is greatly appreciated. </p>
<p>(Yes, the stars are meant to be there as well). </p>
| -2 | 2016-08-19T01:30:39Z | 39,029,871 | <p>Just use a single <code>findall</code> and search for the characters you're interested in.</p>
<pre><code>>>> import re
>>> s = 'Name Charlie Blue Bird ******Grade:5****** ****** ****** ****** '
>>> re.findall(r'[A-Za-z0-9:]+', s)
['Name', 'Charlie', 'Blue', 'Bird', 'Grade:5']
</code></pre>
| 0 | 2016-08-19T01:39:18Z | [
"python",
"regex"
] |
setting GDB breakpoint for C++ class member function written using template | 39,029,908 | <p>I'm trying to set a breakpoint at a C++ class member function which is defined using template. I've looked for the solution in stackoverflow but couldn't find the same problem. Below is a sample code showing the function definition(from py-faster-rcnn caffe code, Dtype is defined as float outside).</p>
<pre><code>template <typename Dtype>
void SoftmaxWithLossLayer<Dtype>::Forward_gpu(
const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) {
softmax_layer_->Forward(softmax_bottom_vec_, softmax_top_vec_);
const Dtype* prob_data = prob_.gpu_data();
const Dtype* label = bottom[1]->gpu_data();
</code></pre>
<p>Yesterday, I successfully set the breakpoint using</p>
<pre><code>br SoftmaxWithLossLayer<float>::Forward_gpu( const vector<Blob<float>*>& , const vector<Blob<float>*>& )
</code></pre>
<p>But this morning, it doesn't work! What can be the problem? If I use <code>br filename:linenuber</code>, it works.<br>
(BTW, I'm using DDD attached to a process running python including C++ library wrapped by boost but I hope this is irrelevant.)</p>
| 2 | 2016-08-19T01:45:49Z | 39,175,405 | <p>I have never tried this but have you considered using nm to determine how it is defined within the shared library? You might be able to use that information to help ddd/gdb consistently find the template method.</p>
| 0 | 2016-08-26T22:23:09Z | [
"python",
"c++",
"templates",
"gdb",
"breakpoints"
] |
How to best extract sub dictionaries by value in this object? | 39,029,939 | <p>I am dealing with a database in which someone created a PHP ArrayObject that had virtually no checks in place before being created. </p>
<p>I am able to extract this as a dictionary of dictionaries using the
python phpserialize library's unserialize module, so that it looks like this:</p>
<pre><code>{0: '{"0": {"0": "use_of_color", "1": "3"}, "1": {"0": "plant_variety", "1": "2"}, "2": {"0": "design", "1": "2"}, "3": {"0": "maintenance", "1": "2"}, "4": {"0": "environmental_stewardship", "1": "3"}}',
1: '{"0": {"0": "use_of_color", "1": "3"}, "1": {"0": "plant_variety", "1": "2"}, "2": {"0": "design", "1": "3"}, "3": {"0": "maintenance", "1": "4"}, "4": {"0": "environmental_stewardship", "1": "2"}}',
2: '{"0": {"0": "color", "1": 3}, "1": {"0": "plant_variety", "1": 3}, "2": {"0": "design", "1": 4}, "3": {"0": "maintenance", "1": 4}, "4": {"0": "environmental_stewardship", "1": 4}}',
3: '{"0": {"0": "location", "1": "4"}, "1": {"0": "sizing", "1": "4"}, "2": {"0": "design", "1": "3"}, "3": {"0": "maintenance", "1": "3"}, "4": {"0": "visual_appeal", "1": "4"}}',
4: '{"0": {"0": "visual_impact", "1": "3"}, "1": {"0": "plant_variety_and_health", "1": "4"}, "2": {"0": "design", "1": "3"}, "3": {"0": "maintenance", "1": 0}, "4": {"0": "environmental_stewardship", "1": "2"}}',
5: '{"0": {"0": "location", "1": "3"}, "1": {"0": "sizing", "1": "3"}, "2": {"0": "design", "1": "3"}, "3": {"0": "maintenance", "1": "3"}, "4": {"0": "visual_appeal", "1": "3"}}',
...
56: '{"0": {"0": "visual_impact", "1": "2"}, "1": {"0": "plant_variety_and_health", "1": "3"}, "2": {"0": "design", "1": "1"}, "3": {"0": "maintenance", "1": "2"}, "4": {"0": "environmental_stewardship", "1": "1"}}',
57: '{"0": {"0": "color", "1": 3}, "1": {"0": "plant_variety", "1": 2}, "2": {"0": "design", "1": 1}, "3": {"0": "maintenance", "1": 2}, "4": {"0": "environmental_stewardship", "1": 2}}',
58: '{"0": {"0": "visual_impact", "1": "4"}, "1": {"0": "plant_variety_and_health", "1": "3"}, "2": {"0": "design", "1": "4"}, "3": {"0": "maintenance", "1": "3"}, "4": {"0": "environmental_stewardship", "1": "4"}}',
59: '{"0": {"0": "visual_impact", "1": "3"}, "1": {"0": "plant_variety_and_health", "1": "3"}, "2": {"0": "design", "1": "3"}, "3": {"0": "maintenance", "1": "3"}, "4": {"0": "environmental_stewardship", "1": "4"}}',
60: '{"0": {"0": "use_of_color", "1": "3"}, "1": {"0": "plant_variety", "1": "4"}, "2": {"0": "design", "1": "3"}, "3": {"0": "maintenance", "1": "2"}, "4": {"0": "environmental_stewardship", "1": "3"}}',
61: '{"0": {"0": "use_of_color", "1": "3"}, "1": {"0": "plant_variety", "1": "4"}, "2": {"0": "design", "1": "3"}, "3": {"0": "maintenance", "1": "2"}, "4": {"0": "environmental_stewardship", "1": "3"}}',
62: '{"0": {"0": "visual_impact", "1": "2"}, "1": {"0": "plant_variety_and_health", "1": "2"}, "2": {"0": "design", "1": "2"}, "3": {"0": "maintenance", "1": "1"}, "4": {"0": "environmental_stewardship", "1": "1"}}',
63: '{"0": {"0": "visual_impact", "1": "4"}, "1": {"0": "plant_variety_and_health", "1": "3"}, "2": {"0": "design", "1": "3"}, "3": {"0": "maintenance", "1": "4"}, "4": {"0": "environmental_stewardship", "1": "4"}}',
64: '{"0": {"0": "visual_impact", "1": "4"}, "1": {"0": "plant_variety_and_health", "1": "3"}, "2": {"0": "design", "1": "3"}, "3": {"0": "maintenance", "1": "4"}, "4": {"0": "environmental_stewardship", "1": "4"}}',
65: '{"0": {"0": "visual_impact", "1": "3"}, "1": {"0": "plant_variety_and_health", "1": "3"}, "2": {"0": "design", "1": "3"}, "3": {"0": "maintenance", "1": "2"}, "4": {"0": "environmental_stewardship", "1": "3"}}'}
</code></pre>
<p>The problem is that I need a way to extract the sub dictionaries that have a the same values (e.g., all those with "visual_impact" or "color", etc.). However, since these sub dictionaries are not paired with the same key throughout the object, this seems not possible.</p>
<p>I am thinking that maybe reassigning the key names to align with the values would be doable.</p>
<p>So, for example</p>
<pre><code>dict = {"0": {"0": "color", "1": 3}, "1": {"0": "plant_variety", "1": 3}, "2": {"0": "design", "1": 4}, "3": {"0": "maintenance", "1": 4}, "4": {"0": "environmental_stewardship", "1": 4}}
</code></pre>
<p>Would instead become</p>
<pre><code>dict = {"0": {"0": "color", "1": 3}, "4": {"0": "plant_variety", "1": 3}, "1": {"0": "design", "1": 4}, "3": {"0": "maintenance", "1": 4}, "2": {"0": "environmental_stewardship", "1": 4}}
</code></pre>
<p>Thus, for <code>dict["0"]</code> I want to always have "color" in the sub dictionary/value, <code>dict["1"]</code> would always have "design", etc. So, for my example dict above, <code>dict["0"]</code> would give <code>{"0": "color", "1": 3}</code>, <code>dict["1"]</code> would give <code>{"0": "design", "1": 4}</code>, etc.</p>
<p>Thus, I am trying to reassign the keys based on what is in the value/sub dictionary. Key "0" always has "color" in the sub dictionary/value, key "1" always has "design", etc. for the whole dictionary of dictionaries listed above.</p>
<p>I found this <a href="http://stackoverflow.com/questions/4406501/change-the-name-of-a-key-in-dictionary">change-the-name-of-a-key-in-dictionary</a>, but this object is confusing in terms of how to do this, since this is dependent on the value/sub dictionary's content.</p>
<p>I know that I have to deal with making sure that values, such as, 'use_of_color' is changed to 'color', etc. are uniformly named before doing this, but that should not be a problem. I just need a way to ensure that I am always extracting the sub dictionary with the value of 'color' by the same key, and the only way I can see of doing this is by reassigning the keys.</p>
<p>If there is a better way to deal with this, I am open to suggestions.</p>
| 0 | 2016-08-19T01:49:52Z | 39,030,122 | <p>I'm assuming you want a grouping of the sub-dictionaries by the value of their key '0', i.e. by 'location', 'environmental_stewardship', etc. But actually, you don't have subdictionaries at all, you have strings that are dictionary literals. If your dictionary were named <code>horrible_mess</code>, you could use this quick hack:</p>
<pre><code>>>> from ast import literal_eval
>>> still_messy = {k:literal_eval(v) for k,v in horrible_mess.items()}
</code></pre>
<p>Then, it's probably easiest to simply do the following:</p>
<pre><code>>>> from collections import defaultdict
>>> grouped = defaultdict(list)
>>> for sub in still_messy.values():
... for d in sub.values():
... grouped[d['0']].append(d)
...
>>> grouped['visual_appeal']
[{'1': '4', '0': 'visual_appeal'}, {'1': '3', '0': 'visual_appeal'}]
>>> grouped['environmental_stewardship']
[{'1': '3', '0': 'environmental_stewardship'}, {'1': '2', '0': 'environmental_stewardship'}, {'1': 4, '0': 'environmental_stewardship'}, {'1': '2', '0': 'environmental_stewardship'}, {'1': '3', '0': 'environmental_stewardship'}, {'1': '4', '0': 'environmental_stewardship'}, {'1': '1', '0': 'environmental_stewardship'}, {'1': 2, '0': 'environmental_stewardship'}, {'1': '4', '0': 'environmental_stewardship'}, {'1': '4', '0': 'environmental_stewardship'}, {'1': '3', '0': 'environmental_stewardship'}, {'1': '3', '0': 'environmental_stewardship'}, {'1': '1', '0': 'environmental_stewardship'}, {'1': '4', '0': 'environmental_stewardship'}]
>>>
</code></pre>
| 2 | 2016-08-19T02:13:36Z | [
"python",
"dictionary",
"serialization",
"key-value",
"arrayobject"
] |
How to best extract sub dictionaries by value in this object? | 39,029,939 | <p>I am dealing with a database in which someone created a PHP ArrayObject that had virtually no checks in place before being created. </p>
<p>I am able to extract this as a dictionary of dictionaries using the
python phpserialize library's unserialize module, so that it looks like this:</p>
<pre><code>{0: '{"0": {"0": "use_of_color", "1": "3"}, "1": {"0": "plant_variety", "1": "2"}, "2": {"0": "design", "1": "2"}, "3": {"0": "maintenance", "1": "2"}, "4": {"0": "environmental_stewardship", "1": "3"}}',
1: '{"0": {"0": "use_of_color", "1": "3"}, "1": {"0": "plant_variety", "1": "2"}, "2": {"0": "design", "1": "3"}, "3": {"0": "maintenance", "1": "4"}, "4": {"0": "environmental_stewardship", "1": "2"}}',
2: '{"0": {"0": "color", "1": 3}, "1": {"0": "plant_variety", "1": 3}, "2": {"0": "design", "1": 4}, "3": {"0": "maintenance", "1": 4}, "4": {"0": "environmental_stewardship", "1": 4}}',
3: '{"0": {"0": "location", "1": "4"}, "1": {"0": "sizing", "1": "4"}, "2": {"0": "design", "1": "3"}, "3": {"0": "maintenance", "1": "3"}, "4": {"0": "visual_appeal", "1": "4"}}',
4: '{"0": {"0": "visual_impact", "1": "3"}, "1": {"0": "plant_variety_and_health", "1": "4"}, "2": {"0": "design", "1": "3"}, "3": {"0": "maintenance", "1": 0}, "4": {"0": "environmental_stewardship", "1": "2"}}',
5: '{"0": {"0": "location", "1": "3"}, "1": {"0": "sizing", "1": "3"}, "2": {"0": "design", "1": "3"}, "3": {"0": "maintenance", "1": "3"}, "4": {"0": "visual_appeal", "1": "3"}}',
...
56: '{"0": {"0": "visual_impact", "1": "2"}, "1": {"0": "plant_variety_and_health", "1": "3"}, "2": {"0": "design", "1": "1"}, "3": {"0": "maintenance", "1": "2"}, "4": {"0": "environmental_stewardship", "1": "1"}}',
57: '{"0": {"0": "color", "1": 3}, "1": {"0": "plant_variety", "1": 2}, "2": {"0": "design", "1": 1}, "3": {"0": "maintenance", "1": 2}, "4": {"0": "environmental_stewardship", "1": 2}}',
58: '{"0": {"0": "visual_impact", "1": "4"}, "1": {"0": "plant_variety_and_health", "1": "3"}, "2": {"0": "design", "1": "4"}, "3": {"0": "maintenance", "1": "3"}, "4": {"0": "environmental_stewardship", "1": "4"}}',
59: '{"0": {"0": "visual_impact", "1": "3"}, "1": {"0": "plant_variety_and_health", "1": "3"}, "2": {"0": "design", "1": "3"}, "3": {"0": "maintenance", "1": "3"}, "4": {"0": "environmental_stewardship", "1": "4"}}',
60: '{"0": {"0": "use_of_color", "1": "3"}, "1": {"0": "plant_variety", "1": "4"}, "2": {"0": "design", "1": "3"}, "3": {"0": "maintenance", "1": "2"}, "4": {"0": "environmental_stewardship", "1": "3"}}',
61: '{"0": {"0": "use_of_color", "1": "3"}, "1": {"0": "plant_variety", "1": "4"}, "2": {"0": "design", "1": "3"}, "3": {"0": "maintenance", "1": "2"}, "4": {"0": "environmental_stewardship", "1": "3"}}',
62: '{"0": {"0": "visual_impact", "1": "2"}, "1": {"0": "plant_variety_and_health", "1": "2"}, "2": {"0": "design", "1": "2"}, "3": {"0": "maintenance", "1": "1"}, "4": {"0": "environmental_stewardship", "1": "1"}}',
63: '{"0": {"0": "visual_impact", "1": "4"}, "1": {"0": "plant_variety_and_health", "1": "3"}, "2": {"0": "design", "1": "3"}, "3": {"0": "maintenance", "1": "4"}, "4": {"0": "environmental_stewardship", "1": "4"}}',
64: '{"0": {"0": "visual_impact", "1": "4"}, "1": {"0": "plant_variety_and_health", "1": "3"}, "2": {"0": "design", "1": "3"}, "3": {"0": "maintenance", "1": "4"}, "4": {"0": "environmental_stewardship", "1": "4"}}',
65: '{"0": {"0": "visual_impact", "1": "3"}, "1": {"0": "plant_variety_and_health", "1": "3"}, "2": {"0": "design", "1": "3"}, "3": {"0": "maintenance", "1": "2"}, "4": {"0": "environmental_stewardship", "1": "3"}}'}
</code></pre>
<p>The problem is that I need a way to extract the sub dictionaries that have a the same values (e.g., all those with "visual_impact" or "color", etc.). However, since these sub dictionaries are not paired with the same key throughout the object, this seems not possible.</p>
<p>I am thinking that maybe reassigning the key names to align with the values would be doable.</p>
<p>So, for example</p>
<pre><code>dict = {"0": {"0": "color", "1": 3}, "1": {"0": "plant_variety", "1": 3}, "2": {"0": "design", "1": 4}, "3": {"0": "maintenance", "1": 4}, "4": {"0": "environmental_stewardship", "1": 4}}
</code></pre>
<p>Would instead become</p>
<pre><code>dict = {"0": {"0": "color", "1": 3}, "4": {"0": "plant_variety", "1": 3}, "1": {"0": "design", "1": 4}, "3": {"0": "maintenance", "1": 4}, "2": {"0": "environmental_stewardship", "1": 4}}
</code></pre>
<p>Thus, for <code>dict["0"]</code> I want to always have "color" in the sub dictionary/value, <code>dict["1"]</code> would always have "design", etc. So, for my example dict above, <code>dict["0"]</code> would give <code>{"0": "color", "1": 3}</code>, <code>dict["1"]</code> would give <code>{"0": "design", "1": 4}</code>, etc.</p>
<p>Thus, I am trying to reassign the keys based on what is in the value/sub dictionary. Key "0" always has "color" in the sub dictionary/value, key "1" always has "design", etc. for the whole dictionary of dictionaries listed above.</p>
<p>I found this <a href="http://stackoverflow.com/questions/4406501/change-the-name-of-a-key-in-dictionary">change-the-name-of-a-key-in-dictionary</a>, but this object is confusing in terms of how to do this, since this is dependent on the value/sub dictionary's content.</p>
<p>I know that I have to deal with making sure that values, such as, 'use_of_color' is changed to 'color', etc. are uniformly named before doing this, but that should not be a problem. I just need a way to ensure that I am always extracting the sub dictionary with the value of 'color' by the same key, and the only way I can see of doing this is by reassigning the keys.</p>
<p>If there is a better way to deal with this, I am open to suggestions.</p>
| 0 | 2016-08-19T01:49:52Z | 39,030,125 | <p>Please let me know if this is the output you expect, if not could you please include expected output in your question? I apologize that the code is ugly, but it basically just loops through all of the sub-dictionaries and only considers values that can't be converted to int (this is a hack) and uses those as keys in a new dictionary.</p>
<p>CODE:</p>
<pre><code>from ast import literal_eval
data = {0: '{"0": {"0": "use_of_color", "1": "3"}, "1": {"0": "plant_variety", "1": "2"}, "2": {"0": "design", "1": "2"}, "3": {"0": "maintenance", "1": "2"}, "4": {"0": "environmental_stewardship", "1": "3"}}',
1: '{"0": {"0": "use_of_color", "1": "3"}, "1": {"0": "plant_variety", "1": "2"}, "2": {"0": "design", "1": "3"}, "3": {"0": "maintenance", "1": "4"}, "4": {"0": "environmental_stewardship", "1": "2"}}',
2: '{"0": {"0": "color", "1": 3}, "1": {"0": "plant_variety", "1": 3}, "2": {"0": "design", "1": 4}, "3": {"0": "maintenance", "1": 4}, "4": {"0": "environmental_stewardship", "1": 4}}',
3: '{"0": {"0": "location", "1": "4"}, "1": {"0": "sizing", "1": "4"}, "2": {"0": "design", "1": "3"}, "3": {"0": "maintenance", "1": "3"}, "4": {"0": "visual_appeal", "1": "4"}}',
4: '{"0": {"0": "visual_impact", "1": "3"}, "1": {"0": "plant_variety_and_health", "1": "4"}, "2": {"0": "design", "1": "3"}, "3": {"0": "maintenance", "1": 0}, "4": {"0": "environmental_stewardship", "1": "2"}}',
5: '{"0": {"0": "location", "1": "3"}, "1": {"0": "sizing", "1": "3"}, "2": {"0": "design", "1": "3"}, "3": {"0": "maintenance", "1": "3"}, "4": {"0": "visual_appeal", "1": "3"}}',
56: '{"0": {"0": "visual_impact", "1": "2"}, "1": {"0": "plant_variety_and_health", "1": "3"}, "2": {"0": "design", "1": "1"}, "3": {"0": "maintenance", "1": "2"}, "4": {"0": "environmental_stewardship", "1": "1"}}',
57: '{"0": {"0": "color", "1": 3}, "1": {"0": "plant_variety", "1": 2}, "2": {"0": "design", "1": 1}, "3": {"0": "maintenance", "1": 2}, "4": {"0": "environmental_stewardship", "1": 2}}',
58: '{"0": {"0": "visual_impact", "1": "4"}, "1": {"0": "plant_variety_and_health", "1": "3"}, "2": {"0": "design", "1": "4"}, "3": {"0": "maintenance", "1": "3"}, "4": {"0": "environmental_stewardship", "1": "4"}}',
59: '{"0": {"0": "visual_impact", "1": "3"}, "1": {"0": "plant_variety_and_health", "1": "3"}, "2": {"0": "design", "1": "3"}, "3": {"0": "maintenance", "1": "3"}, "4": {"0": "environmental_stewardship", "1": "4"}}',
60: '{"0": {"0": "use_of_color", "1": "3"}, "1": {"0": "plant_variety", "1": "4"}, "2": {"0": "design", "1": "3"}, "3": {"0": "maintenance", "1": "2"}, "4": {"0": "environmental_stewardship", "1": "3"}}',
61: '{"0": {"0": "use_of_color", "1": "3"}, "1": {"0": "plant_variety", "1": "4"}, "2": {"0": "design", "1": "3"}, "3": {"0": "maintenance", "1": "2"}, "4": {"0": "environmental_stewardship", "1": "3"}}',
62: '{"0": {"0": "visual_impact", "1": "2"}, "1": {"0": "plant_variety_and_health", "1": "2"}, "2": {"0": "design", "1": "2"}, "3": {"0": "maintenance", "1": "1"}, "4": {"0": "environmental_stewardship", "1": "1"}}',
63: '{"0": {"0": "visual_impact", "1": "4"}, "1": {"0": "plant_variety_and_health", "1": "3"}, "2": {"0": "design", "1": "3"}, "3": {"0": "maintenance", "1": "4"}, "4": {"0": "environmental_stewardship", "1": "4"}}',
64: '{"0": {"0": "visual_impact", "1": "4"}, "1": {"0": "plant_variety_and_health", "1": "3"}, "2": {"0": "design", "1": "3"}, "3": {"0": "maintenance", "1": "4"}, "4": {"0": "environmental_stewardship", "1": "4"}}',
65: '{"0": {"0": "visual_impact", "1": "3"}, "1": {"0": "plant_variety_and_health", "1": "3"}, "2": {"0": "design", "1": "3"}, "3": {"0": "maintenance", "1": "2"}, "4": {"0": "environmental_stewardship", "1": "3"}}'}
sep_by_type = {}
for key1,val1 in data.iteritems():
val1 = literal_eval(val1) #because val1 is a string not a dict
for key2,val2 in val1.iteritems():
for key3,val3 in val2.iteritems():
try:
int(val3)
except:
if val3 not in sep_by_type:
sep_by_type[val3] = [val2]
else:
sep_by_type[val3].append(val2)
for sep_key in sep_by_type:
print sep_key,sep_by_type[sep_key]
print ""
</code></pre>
<p>OUTPUT</p>
<pre><code>sizing [{'1': '4', '0': 'sizing'}, {'1': '3', '0': 'sizing'}]
plant_variety [{'1': '2', '0': 'plant_variety'}, {'1': '2', '0': 'plant_variety'}, {'1': 3, '0': 'plant_variety'}, {'1': 2, '0': 'plant_variety'}, {'1': '4', '0': 'plant_variety'}, {'1': '4', '0': 'plant_variety'}]
maintenance [{'1': '2', '0': 'maintenance'}, {'1': '4', '0': 'maintenance'}, {'1': 4, '0': 'maintenance'}, {'1': '3', '0': 'maintenance'}, {'1': 0, '0': 'maintenance'}, {'1': '3', '0': 'maintenance'}, {'1': '2', '0': 'maintenance'}, {'1': '4', '0': 'maintenance'}, {'1': '2', '0': 'maintenance'}, {'1': 2, '0': 'maintenance'}, {'1': '3', '0': 'maintenance'}, {'1': '3', '0': 'maintenance'}, {'1': '2', '0': 'maintenance'}, {'1': '2', '0': 'maintenance'}, {'1': '1', '0': 'maintenance'}, {'1': '4', '0': 'maintenance'}]
use_of_color [{'1': '3', '0': 'use_of_color'}, {'1': '3', '0': 'use_of_color'}, {'1': '3', '0': 'use_of_color'}, {'1': '3', '0': 'use_of_color'}]
color [{'1': 3, '0': 'color'}, {'1': 3, '0': 'color'}]
plant_variety_and_health [{'1': '4', '0': 'plant_variety_and_health'}, {'1': '3', '0': 'plant_variety_and_health'}, {'1': '3', '0': 'plant_variety_and_health'}, {'1': '3', '0': 'plant_variety_and_health'}, {'1': '3', '0': 'plant_variety_and_health'}, {'1': '3', '0': 'plant_variety_and_health'}, {'1': '2', '0': 'plant_variety_and_health'}, {'1': '3', '0': 'plant_variety_and_health'}]
visual_appeal [{'1': '4', '0': 'visual_appeal'}, {'1': '3', '0': 'visual_appeal'}]
design [{'1': '2', '0': 'design'}, {'1': '3', '0': 'design'}, {'1': 4, '0': 'design'}, {'1': '3', '0': 'design'}, {'1': '3', '0': 'design'}, {'1': '3', '0': 'design'}, {'1': '3', '0': 'design'}, {'1': '3', '0': 'design'}, {'1': '1', '0': 'design'}, {'1': 1, '0': 'design'}, {'1': '4', '0': 'design'}, {'1': '3', '0': 'design'}, {'1': '3', '0': 'design'}, {'1': '3', '0': 'design'}, {'1': '2', '0': 'design'}, {'1': '3', '0': 'design'}]
location [{'1': '4', '0': 'location'}, {'1': '3', '0': 'location'}]
environmental_stewardship [{'1': '3', '0': 'environmental_stewardship'}, {'1': '2', '0': 'environmental_stewardship'}, {'1': 4, '0': 'environmental_stewardship'}, {'1': '2', '0': 'environmental_stewardship'}, {'1': '3', '0': 'environmental_stewardship'}, {'1': '4', '0': 'environmental_stewardship'}, {'1': '1', '0': 'environmental_stewardship'}, {'1': 2, '0': 'environmental_stewardship'}, {'1': '4', '0': 'environmental_stewardship'}, {'1': '4', '0': 'environmental_stewardship'}, {'1': '3', '0': 'environmental_stewardship'}, {'1': '3', '0': 'environmental_stewardship'}, {'1': '1', '0': 'environmental_stewardship'}, {'1': '4', '0': 'environmental_stewardship'}]
visual_impact [{'1': '3', '0': 'visual_impact'}, {'1': '3', '0': 'visual_impact'}, {'1': '4', '0': 'visual_impact'}, {'1': '2', '0': 'visual_impact'}, {'1': '4', '0': 'visual_impact'}, {'1': '3', '0': 'visual_impact'}, {'1': '2', '0': 'visual_impact'}, {'1': '4', '0': 'visual_impact'}]
</code></pre>
<p>UPDATE
I used literal_eval instead of eval which is safer. (thanks juanpa.arrivillaga!)</p>
| 1 | 2016-08-19T02:13:41Z | [
"python",
"dictionary",
"serialization",
"key-value",
"arrayobject"
] |
python 2.7 replacing a raw_input string with a value from a dictionary | 39,030,037 | <p>I am very new to programming (6 weeks, self taught on the net with "codecademy" and "python the hard way"). I decided it was time I started experimenting at writing code without direction and I hit a wall with my second project.</p>
<p>I am trying to make a "secret coder" that takes a raw_input string and replaces every letters in it with the next one in the alphabet. With my very limited knowledge, I figured that a dictionary should be the way to go. With a "little" googling help, I wrote this:</p>
<pre><code>alpha = {"a" : "b", "b" : "c", "c" : "d", "d" : "e", "e" : "f", "f" : "g","g" : "h"
, "h" : "i", "i" : "j", "j" : "k", "k" : "l", "l" : "m","m" : "n", "n" : "o"
, "o" : "p", "p" : "q", "q" : "r", "r" : "s","s" : "t", "t" : "u", "u" : "v"
, "v" : "w", "w" : "x", "x" : "y", "y" : "z", "z" : "a"}
entry = raw_input("Please write a sentence you want to encode: ")
def encode(entry, letters):
for k, v in letters.iteritems():
if k in alpha:
entry = entry.replace(k, v)
return entry
print encode(entry, alpha)
</code></pre>
<p>The problem that I have is that only half the letters in my string are replaced by the correct values from the dictionary. "a" and "b" will both be printed as "c" when "a" should be printed as "b" and "b" should be printed as "c" and so on.</p>
<p><a href="http://i.stack.imgur.com/LFO7b.png" rel="nofollow">illustration</a></p>
<p>Where I get completely lost is that, when I replaced every value in my dictionary with numbers, it worked perfectly.</p>
<p><a href="http://i.stack.imgur.com/Dj9sC.png" rel="nofollow">illustration bis</a></p>
<p>That's the gist of it, I really don't get what is wrong with my code. </p>
<p>Thank you in advance for your help.</p>
<p>PS: This was my very first post on stackoverflow, hopefully I did everything the way I should. </p>
<p>EDIT: Since I cannot give reputation yet, I will just thank you all here for your helpful answers. I can see a bit clearer now where my mistake is and I will take the info provided here to fix my code and work on understanding it properly. Also I can see that there are much more logical and straightforward approches to solving this kind of problem. Functions are still a bit blurry to me but I guess it is normal so early on.</p>
| 2 | 2016-08-19T02:01:54Z | 39,030,103 | <pre><code>def encode(entry, letters):
for k, v in letters.iteritems():
if k in alpha:
entry = entry.replace(k, v)
return entry
print encode(entry, alpha)
</code></pre>
<p>Calling <code>encode(entry, alpha)</code> in your print function, you pass the <code>encode()</code> function the <code>alpha</code> dictionary to be the <code>letters</code> variable in the function. Then, you use the iterator to loop through the <code>letters</code> variable (which is the <code>alpha</code> dictionary). Then your if statement checks to see if that <code>k</code> (which you just got from the <code>letters</code> variable, which is the <code>alpha</code> dictionary) is in the <code>alpha</code> dictionary, which of course it is.</p>
<p>You'll need to do something like this instead:</p>
<pre><code>for k, v in letters.iteritems():
if k in entry:
entry = entry.replace(k, v)
</code></pre>
| 0 | 2016-08-19T02:11:32Z | [
"python",
"python-2.7",
"function",
"dictionary",
"raw-input"
] |
python 2.7 replacing a raw_input string with a value from a dictionary | 39,030,037 | <p>I am very new to programming (6 weeks, self taught on the net with "codecademy" and "python the hard way"). I decided it was time I started experimenting at writing code without direction and I hit a wall with my second project.</p>
<p>I am trying to make a "secret coder" that takes a raw_input string and replaces every letters in it with the next one in the alphabet. With my very limited knowledge, I figured that a dictionary should be the way to go. With a "little" googling help, I wrote this:</p>
<pre><code>alpha = {"a" : "b", "b" : "c", "c" : "d", "d" : "e", "e" : "f", "f" : "g","g" : "h"
, "h" : "i", "i" : "j", "j" : "k", "k" : "l", "l" : "m","m" : "n", "n" : "o"
, "o" : "p", "p" : "q", "q" : "r", "r" : "s","s" : "t", "t" : "u", "u" : "v"
, "v" : "w", "w" : "x", "x" : "y", "y" : "z", "z" : "a"}
entry = raw_input("Please write a sentence you want to encode: ")
def encode(entry, letters):
for k, v in letters.iteritems():
if k in alpha:
entry = entry.replace(k, v)
return entry
print encode(entry, alpha)
</code></pre>
<p>The problem that I have is that only half the letters in my string are replaced by the correct values from the dictionary. "a" and "b" will both be printed as "c" when "a" should be printed as "b" and "b" should be printed as "c" and so on.</p>
<p><a href="http://i.stack.imgur.com/LFO7b.png" rel="nofollow">illustration</a></p>
<p>Where I get completely lost is that, when I replaced every value in my dictionary with numbers, it worked perfectly.</p>
<p><a href="http://i.stack.imgur.com/Dj9sC.png" rel="nofollow">illustration bis</a></p>
<p>That's the gist of it, I really don't get what is wrong with my code. </p>
<p>Thank you in advance for your help.</p>
<p>PS: This was my very first post on stackoverflow, hopefully I did everything the way I should. </p>
<p>EDIT: Since I cannot give reputation yet, I will just thank you all here for your helpful answers. I can see a bit clearer now where my mistake is and I will take the info provided here to fix my code and work on understanding it properly. Also I can see that there are much more logical and straightforward approches to solving this kind of problem. Functions are still a bit blurry to me but I guess it is normal so early on.</p>
| 2 | 2016-08-19T02:01:54Z | 39,030,105 | <p>The problem is that since you're iterating over the dictionary instead of the string you might replace original character many times. For example with given input of <code>'ab'</code> the first replace will result to <code>'bb'</code> and second to <code>'cc'</code> in case that <a href="https://docs.python.org/2/library/stdtypes.html#dict.iteritems" rel="nofollow"><code>iteritems</code></a> returns the keys in order <code>a, b</code>. Note that since dictionary is unordered collection the order of returned items is random.</p>
<p>You could fix the problem by using <a href="https://www.python.org/dev/peps/pep-0289/" rel="nofollow">generator expression</a> to iterate over the source string and <a href="https://docs.python.org/2/library/stdtypes.html#str.join" rel="nofollow"><code>join</code></a> to create the result:</p>
<pre><code>def encode(entry, letters):
return ''.join(letters.get(c, c) for c in entry)
</code></pre>
<p>The above example is calling <a href="https://docs.python.org/2/library/stdtypes.html#dict.get" rel="nofollow"><code>get</code></a> instead of using index operator to handle the cases where <code>alpha</code> doesn't contain a letter in source string. The difference between <code>get</code> and index operator is that <code>get</code> takes second argument that is default value which will be returned in case that key doesn't exist. In the above example the default value is the character itself.</p>
| 2 | 2016-08-19T02:11:37Z | [
"python",
"python-2.7",
"function",
"dictionary",
"raw-input"
] |
python 2.7 replacing a raw_input string with a value from a dictionary | 39,030,037 | <p>I am very new to programming (6 weeks, self taught on the net with "codecademy" and "python the hard way"). I decided it was time I started experimenting at writing code without direction and I hit a wall with my second project.</p>
<p>I am trying to make a "secret coder" that takes a raw_input string and replaces every letters in it with the next one in the alphabet. With my very limited knowledge, I figured that a dictionary should be the way to go. With a "little" googling help, I wrote this:</p>
<pre><code>alpha = {"a" : "b", "b" : "c", "c" : "d", "d" : "e", "e" : "f", "f" : "g","g" : "h"
, "h" : "i", "i" : "j", "j" : "k", "k" : "l", "l" : "m","m" : "n", "n" : "o"
, "o" : "p", "p" : "q", "q" : "r", "r" : "s","s" : "t", "t" : "u", "u" : "v"
, "v" : "w", "w" : "x", "x" : "y", "y" : "z", "z" : "a"}
entry = raw_input("Please write a sentence you want to encode: ")
def encode(entry, letters):
for k, v in letters.iteritems():
if k in alpha:
entry = entry.replace(k, v)
return entry
print encode(entry, alpha)
</code></pre>
<p>The problem that I have is that only half the letters in my string are replaced by the correct values from the dictionary. "a" and "b" will both be printed as "c" when "a" should be printed as "b" and "b" should be printed as "c" and so on.</p>
<p><a href="http://i.stack.imgur.com/LFO7b.png" rel="nofollow">illustration</a></p>
<p>Where I get completely lost is that, when I replaced every value in my dictionary with numbers, it worked perfectly.</p>
<p><a href="http://i.stack.imgur.com/Dj9sC.png" rel="nofollow">illustration bis</a></p>
<p>That's the gist of it, I really don't get what is wrong with my code. </p>
<p>Thank you in advance for your help.</p>
<p>PS: This was my very first post on stackoverflow, hopefully I did everything the way I should. </p>
<p>EDIT: Since I cannot give reputation yet, I will just thank you all here for your helpful answers. I can see a bit clearer now where my mistake is and I will take the info provided here to fix my code and work on understanding it properly. Also I can see that there are much more logical and straightforward approches to solving this kind of problem. Functions are still a bit blurry to me but I guess it is normal so early on.</p>
| 2 | 2016-08-19T02:01:54Z | 39,030,138 | <p>Dictionaries aren't ordered, so you are replacing some letters ('a' -> 'b') and others are getting skipped over.</p>
<p>For your edification what you are doing is called a <code>rot</code> (rotation). The most well-known one is <code>rot13</code>.</p>
<p>Writing things yourself is helpful when you first start out, but there is a pretty cool standard library function called <code>string.maketrans</code> which will do exactly this!</p>
| 0 | 2016-08-19T02:15:00Z | [
"python",
"python-2.7",
"function",
"dictionary",
"raw-input"
] |
python 2.7 replacing a raw_input string with a value from a dictionary | 39,030,037 | <p>I am very new to programming (6 weeks, self taught on the net with "codecademy" and "python the hard way"). I decided it was time I started experimenting at writing code without direction and I hit a wall with my second project.</p>
<p>I am trying to make a "secret coder" that takes a raw_input string and replaces every letters in it with the next one in the alphabet. With my very limited knowledge, I figured that a dictionary should be the way to go. With a "little" googling help, I wrote this:</p>
<pre><code>alpha = {"a" : "b", "b" : "c", "c" : "d", "d" : "e", "e" : "f", "f" : "g","g" : "h"
, "h" : "i", "i" : "j", "j" : "k", "k" : "l", "l" : "m","m" : "n", "n" : "o"
, "o" : "p", "p" : "q", "q" : "r", "r" : "s","s" : "t", "t" : "u", "u" : "v"
, "v" : "w", "w" : "x", "x" : "y", "y" : "z", "z" : "a"}
entry = raw_input("Please write a sentence you want to encode: ")
def encode(entry, letters):
for k, v in letters.iteritems():
if k in alpha:
entry = entry.replace(k, v)
return entry
print encode(entry, alpha)
</code></pre>
<p>The problem that I have is that only half the letters in my string are replaced by the correct values from the dictionary. "a" and "b" will both be printed as "c" when "a" should be printed as "b" and "b" should be printed as "c" and so on.</p>
<p><a href="http://i.stack.imgur.com/LFO7b.png" rel="nofollow">illustration</a></p>
<p>Where I get completely lost is that, when I replaced every value in my dictionary with numbers, it worked perfectly.</p>
<p><a href="http://i.stack.imgur.com/Dj9sC.png" rel="nofollow">illustration bis</a></p>
<p>That's the gist of it, I really don't get what is wrong with my code. </p>
<p>Thank you in advance for your help.</p>
<p>PS: This was my very first post on stackoverflow, hopefully I did everything the way I should. </p>
<p>EDIT: Since I cannot give reputation yet, I will just thank you all here for your helpful answers. I can see a bit clearer now where my mistake is and I will take the info provided here to fix my code and work on understanding it properly. Also I can see that there are much more logical and straightforward approches to solving this kind of problem. Functions are still a bit blurry to me but I guess it is normal so early on.</p>
| 2 | 2016-08-19T02:01:54Z | 39,030,162 | <p>Xetnus is correct you need to loop through entry variable instead of the letters. maybe something like this</p>
<pre><code>def encode(entry, letters):
new_entry = ''
for letter in entry:
if letter in letters:
new_entry += letters[letter]
return new_entry
print encode(entry, alpha)
</code></pre>
| 2 | 2016-08-19T02:17:46Z | [
"python",
"python-2.7",
"function",
"dictionary",
"raw-input"
] |
python 2.7 replacing a raw_input string with a value from a dictionary | 39,030,037 | <p>I am very new to programming (6 weeks, self taught on the net with "codecademy" and "python the hard way"). I decided it was time I started experimenting at writing code without direction and I hit a wall with my second project.</p>
<p>I am trying to make a "secret coder" that takes a raw_input string and replaces every letters in it with the next one in the alphabet. With my very limited knowledge, I figured that a dictionary should be the way to go. With a "little" googling help, I wrote this:</p>
<pre><code>alpha = {"a" : "b", "b" : "c", "c" : "d", "d" : "e", "e" : "f", "f" : "g","g" : "h"
, "h" : "i", "i" : "j", "j" : "k", "k" : "l", "l" : "m","m" : "n", "n" : "o"
, "o" : "p", "p" : "q", "q" : "r", "r" : "s","s" : "t", "t" : "u", "u" : "v"
, "v" : "w", "w" : "x", "x" : "y", "y" : "z", "z" : "a"}
entry = raw_input("Please write a sentence you want to encode: ")
def encode(entry, letters):
for k, v in letters.iteritems():
if k in alpha:
entry = entry.replace(k, v)
return entry
print encode(entry, alpha)
</code></pre>
<p>The problem that I have is that only half the letters in my string are replaced by the correct values from the dictionary. "a" and "b" will both be printed as "c" when "a" should be printed as "b" and "b" should be printed as "c" and so on.</p>
<p><a href="http://i.stack.imgur.com/LFO7b.png" rel="nofollow">illustration</a></p>
<p>Where I get completely lost is that, when I replaced every value in my dictionary with numbers, it worked perfectly.</p>
<p><a href="http://i.stack.imgur.com/Dj9sC.png" rel="nofollow">illustration bis</a></p>
<p>That's the gist of it, I really don't get what is wrong with my code. </p>
<p>Thank you in advance for your help.</p>
<p>PS: This was my very first post on stackoverflow, hopefully I did everything the way I should. </p>
<p>EDIT: Since I cannot give reputation yet, I will just thank you all here for your helpful answers. I can see a bit clearer now where my mistake is and I will take the info provided here to fix my code and work on understanding it properly. Also I can see that there are much more logical and straightforward approches to solving this kind of problem. Functions are still a bit blurry to me but I guess it is normal so early on.</p>
| 2 | 2016-08-19T02:01:54Z | 39,030,167 | <p>Others have pointed out how to do this correctly using a dictionary as lookup. However, you can also use the <code>str.translate</code> method which avoids having to do the look up and rebuilding a string.</p>
<pre><code>import string
trans = string.maketrans(
'abcdefghijklmnopqrstuvwxyz', # from...
'bcdefghijklmnopqrstuvwxyza' # to
)
print raw_input('Please enter something to encode: ').translate(trans)
</code></pre>
| 0 | 2016-08-19T02:18:26Z | [
"python",
"python-2.7",
"function",
"dictionary",
"raw-input"
] |
Capture interactive Python shell output along with input | 39,030,061 | <p>I want to capture the Python shell output along with the input sent to it. For example, in the following use case, help() should also be present in Line 4 of capture.log:</p>
<pre><code>$ echo "help()" | python3 -i > capture.log 2>&1
$ cat capture.log
Python 3.4.2 (default, Oct 8 2014, 10:45:20)
[GCC 4.9.1] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
Welcome to Python 3.4's help utility!
If this is your first time using Python, you should definitely check out
the tutorial on the Internet at http://docs.python.org/3.4/tutorial/.
....
....
</code></pre>
| 4 | 2016-08-19T02:06:49Z | 39,030,729 | <p>Assuming a Unix-like environment, you can capture all <code>tty</code> input and output with the <code>script</code> command:</p>
<pre><code>$ script capture.log
Script started, output file is capture.log
$ python3
# python interactive session here
$ exit
Script done, output file is capture.log
$ cat capture.log
Script started on Thu Aug 18 21:21:55 2016
$ python3
Python 3.5.2 (default, Jul 21 2016, 07:25:19)
[GCC 4.2.1 Compatible Apple LLVM 7.3.0 (clang-703.0.31)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> help()
Welcome to Python 3.5's help utility!
If this is your first time using Python, you should definitely check out
the tutorial on the Internet at http://docs.python.org/3.5/tutorial/.
....
....
>>> ^D
$ exit
Script done on Thu Aug 18 21:22:06 2016
</code></pre>
<p>If, as in the question example, Python is driven completely by <code>stdin</code> pipe and the goal is to capture the pipe input and Python output, you can get close by using the <code>tee</code> command:</p>
<pre><code>$ echo "help()" | tee capture.log | python3 -i >> capture.log 2>&1
$ cat capture.log
help()
Python 3.5.2 (default, Jul 21 2016, 07:25:19)
[GCC 4.2.1 Compatible Apple LLVM 7.3.0 (clang-703.0.31)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>
Welcome to Python 3.5's help utility!
If this is your first time using Python, you should definitely check out
the tutorial on the Internet at http://docs.python.org/3.5/tutorial/.
....
....
</code></pre>
<p>As you can see, the input and output are both captured, but they're not aligned.</p>
| 5 | 2016-08-19T03:37:11Z | [
"python",
"bash",
"shell",
"stdout",
"stdin"
] |
sort out dataframe where index meet certain conditions | 39,030,075 | <p>I have a data frame like this:</p>
<pre><code> name pe outstanding totals totalAssets
code
300533 abc 30.04 2500.00 10000.00 82066.80
300532 def 31.27 2100.00 8400.00 77945.25
603986 NiT 23.40 2500.00 10000.00 89517.36
600187 ITG 0.00 145562.42 145562.42 393065.88
000652 IGE 929.15 146567.31 147557.39 2969607.50
</code></pre>
<p>I want to sort out those rows whose first 3 chars of index isin(['000','300'])</p>
<p>which the result will beï¼</p>
<pre><code> name pe outstanding totals totalAssets
code
300533 abc 30.04 2500.00 10000.00 82066.80
300532 def 31.27 2100.00 8400.00 77945.25
000652 IGE 929.15 146567.31 147557.39 2969607.50
</code></pre>
<p>thanks.</p>
| 1 | 2016-08-19T02:08:13Z | 39,030,175 | <p>You can use <code>str</code> to extract the first 3 characters from index:</p>
<pre><code>df[df.index.str[:3].isin(['300', '000'])]
# name pe outstanding totals totalAssets
# code
#300533 abc 30.04 2500.00 10000.00 82066.80
#300532 def 31.27 2100.00 8400.00 77945.25
#000652 IGE 929.15 146567.31 147557.39 2969607.50
</code></pre>
| 2 | 2016-08-19T02:19:33Z | [
"python",
"pandas"
] |
code from black hat python runs forever? | 39,030,080 | <p>The code in this pastebin link <a href="http://pastebin.com/E98XChyU" rel="nofollow">here</a> is from the Black Hat Python Book, It's a great book but I've been having a lot of problems with the code because I couldn't simply copy and paste the code to my ide which meant hours of rewriting because of errors.</p>
<p>I have finally finished writing the code and hopefully for the last time am experiencing an error. The code in the pastebin link always runs forever. It doesn't return an error, it just indefinitely runs. In the command prompt I type:</p>
<pre><code>bhp.py -t google.com -p 80
</code></pre>
<p>and that runs forever.
Also if I type </p>
<pre><code>echo -ne "GET / HTTP/1.1\r\nHost: www.google.com -p 80" | bhp.py -t www.google.com -p 80
</code></pre>
<p>that returns "[*] Exception! Exiting!"</p>
<p>hopefully that can provide some insight into what the problem is. I am currently on a windows 10 laptop too if that can help. Thanks for helping</p>
<p>EDIT: the author used linux</p>
| 0 | 2016-08-19T02:09:08Z | 39,030,931 | <p>Here are some insights : </p>
<p>First using pastebin you can click 'raw' link to get the code properly : <a href="http://pastebin.com/raw/E98XChyU" rel="nofollow">http://pastebin.com/raw/E98XChyU</a></p>
<p>Didn't test, but it seems correct.</p>
<p>Anyway, your problem is in this function : <code>client_sender(buffer)</code></p>
<p>At the end of this function, replace the <code>except</code> handler by :</p>
<pre><code>except Exception as e:
# catch exceptions more properly, you can still do some "homework"
print("[*] Exception : %s" % e)
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
print(exc_type, fname, exc_tb.tb_lineno)
# teardown the connection
client.close()
</code></pre>
<p>This will give you more information.</p>
| 0 | 2016-08-19T04:05:52Z | [
"python",
"python-2.7",
"hacking"
] |
pandas: Add row from one data frame to another data frame? | 39,030,164 | <p>I have two dataframes with identical column headers.</p>
<p>I am iterating over the rows in df1, splitting one of the columns, and then using those split columns to create multiple rows to add to the other dataframe.</p>
<pre><code>for index, row in df1.iterrows():
curr_awards = row['AWARD'].split(" ")
for award in curr_awards:
new_line = row
new_line['AWARD'] = award.strip()
#insert code here to add new_line to df2
</code></pre>
<p>What is the pandas method for adding a row to another data frame?</p>
| -2 | 2016-08-19T02:18:12Z | 39,030,413 | <p>I figured it out.</p>
<pre><code>for index, row in df1.iterrows():
curr_awards = row['AWARD'].split(" ")
for award in curr_awards:
new_line = row
new_line['AWARD'] = award.strip()
df2.loc[len(df2)] = new_line
</code></pre>
| 0 | 2016-08-19T02:53:30Z | [
"python",
"python-3.x",
"pandas"
] |
How to return a dictionary using field function in Odoo | 39,030,185 | <p>I got an error in my field function.
In my function, I want to return a float value from my variable <code>total</code>. And I already searched it and I found an answer <a href="http://stackoverflow.com/questions/27628039/valueerror-dictionary-update-sequence-element-0-has-length-1-2-is-required">here</a> but still I don't understand the explanation.
Here's my error.</p>
<pre><code>ValueError: dictionary update sequence element #0 has length 1; 2 is required
</code></pre>
<p>Here is my code.</p>
<pre><code>@api.multi
@api.depends('total_eec', 'total_tec')
def _consumption_actual_value(self):
res = {}
total = 0.0
for i in self:
total = i.total_eec + i.total_tec
res[i.id] = total
return res
_columns = {'consumption_actual': fields.function(_consumption_actual_value, string='Consumption (kWh) Actual'), # TEC + EEC}
</code></pre>
<p>Please help.</p>
| 0 | 2016-08-19T02:21:43Z | 39,031,116 | <p>You have mixed up both api, you have declared field with old api and function written in new api. You should try following.</p>
<pre><code>@api.multi
@api.depends('total_eec', 'total_tec')
def _consumption_actual_value(self):
for i in self:
total = i.total_eec + i.total_tec
i.consumption_actual = total or 0.0
consumption_actual = fields.Float(compute=_consumption_actual_value, string='Consumption (kWh) Actual')
</code></pre>
| 1 | 2016-08-19T04:26:15Z | [
"python",
"openerp",
"odoo-8"
] |
Crazy but minor issue in grid-based game | 39,030,278 | <p>This has been really bugging me. I'm creating a game where a hero moves on a grid and part of it involves a collision check. The collision check stops the hero from moving in a direction if something already occupies the grid there.</p>
<p>It works for all directions except down. I can't see why?! It's the same structure for up, down, left and right. They all work, except down. I don't see it, can someone help?</p>
<p>Here is the code:</p>
<pre><code>import random as random
import pygame as pygame
pygame.init()
clock = pygame.time.Clock()
Screen = pygame.display.set_mode([650, 650])
Done = False
MapSize = 25
TileWidth = 20
TileHeight = 20
TileMargin = 4
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
class MapTile(object):
def __init__(self, Name, Column, Row):
self.Name = Name
self.Column = Column
self.Row = Row
class Character(object):
def __init__(self, Name, HP, Column, Row):
self.Name = Name
self.HP = HP
self.Column = Column
self.Row = Row
def Move(self, Direction):
if Direction == "UP":
if self.Row > 0:
if self.CollisionCheck("UP") == False:
self.Row -= 1
if Direction == "LEFT":
if self.Column > 0:
if self.CollisionCheck("LEFT") == False:
self.Column -= 1
if Direction == "RIGHT":
if self.Column < MapSize-1:
if self.CollisionCheck("RIGHT") == False:
self.Column += 1
if Direction == "DOWN":
if self.Row < MapSize-1:
if self.CollisionCheck("DOWN") == False:
self.Row += 1
Map.update()
def CollisionCheck(self, Direction):
if Direction == "UP":
if len(Map.Grid[self.Column][(self.Row)-1]) > 1:
return True
if Direction == "LEFT":
if len(Map.Grid[self.Column-1][(self.Row)]) > 1:
return True
if Direction == "RIGHT":
if len(Map.Grid[self.Column+1][(self.Row)]) > 1:
return True
if Direction == "DOWN":
if len(Map.Grid[self.Column][self.Row+1]) > 1:
return True
else:
return False
def Location(self):
print("Coordinates: " + str(self.Column) + ", " + str(self.Row))
class Map(object):
global MapSize
Grid = []
for Row in range(MapSize): # Creating grid
Grid.append([])
for Column in range(MapSize):
Grid[Row].append([])
for Row in range(MapSize): #Filling grid with grass
for Column in range(MapSize):
TempTile = MapTile("Grass", Column, Row)
Grid[Column][Row].append(TempTile)
for Row in range(MapSize): #Rocks
for Column in range(MapSize):
TempTile = MapTile("Rock", Column, Row)
if Row == 1:
Grid[Column][Row].append(TempTile)
for i in range(10): #Random trees
RandomRow = random.randint(0, MapSize - 1)
RandomColumn = random.randint(0, MapSize - 1)
TempTile = MapTile("Tree", RandomColumn, RandomRow)
Grid[RandomColumn][RandomRow].append(TempTile)
RandomRow = random.randint(0, MapSize - 1)
RandomColumn = random.randint(0, MapSize - 1)
Hero = Character("Hero", 10, RandomColumn, RandomRow)
def update(self):
for Column in range(MapSize):
for Row in range(MapSize):
for i in range(len(Map.Grid[Column][Row])):
if Map.Grid[Column][Row][i].Column != Column:
Map.Grid[Column][Row].remove(Map.Grid[Column][Row][i])
elif Map.Grid[Column][Row][i].Name == "Hero":
Map.Grid[Column][Row].remove(Map.Grid[Column][Row][i])
Map.Grid[int(Map.Hero.Column)][int(Map.Hero.Row)].append(Map.Hero)
Map = Map()
while not Done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
Done = True
elif event.type == pygame.MOUSEBUTTONDOWN:
Pos = pygame.mouse.get_pos()
Column = Pos[0] // (TileWidth + TileMargin)
Row = Pos[1] // (TileHeight + TileMargin)
print(str(Row) + ", " + str(Column))
for i in range(len(Map.Grid[Column][Row])):
print(str(Map.Grid[Column][Row][i].Name))
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
Map.Hero.Move("LEFT")
if event.key == pygame.K_RIGHT:
Map.Hero.Move("RIGHT")
if event.key == pygame.K_UP:
Map.Hero.Move("UP")
if event.key == pygame.K_DOWN:
Map.Hero.Move("DOWN")
Screen.fill(BLACK)
for Row in range(MapSize): # Drawing grid
for Column in range(MapSize):
for i in range(0, len(Map.Grid[Column][Row])):
Color = WHITE
if len(Map.Grid[Column][Row]) == 2:
Color = RED
if Map.Grid[Column][Row][i].Name == "Hero":
Color = GREEN
pygame.draw.rect(Screen, Color, [(TileMargin + TileWidth) * Column + TileMargin,
(TileMargin + TileHeight) * Row + TileMargin,
TileWidth,
TileHeight])
clock.tick(60)
pygame.display.flip()
Map.update()
pygame.quit()
</code></pre>
| -1 | 2016-08-19T02:34:36Z | 39,031,491 | <p>An <code>else</code> block goes with an <code>if</code> and optionally any number of <code>elif</code> blocks. Since you used only <code>if</code> blocks, the <code>else</code> is really with only the <code>Down</code> option. Let's say you hit down. Your <code>if ... == "DOWN":</code> block will be entered. If the inner <code>if</code> block succeeds, your method returns True. If it doesn't, the method moves on. It gets to the <code>else</code> block, but it skips it. Why? Because we know that the <code>if</code> succeeded. The <code>else</code> happens only when the <code>if</code> does not succeed. That means that the <code>else</code> happens only when the user types something other than down, so why the <code>else</code>? When do you want the method to return False? You want it return False only if it hasn't yet returned True. If it has already returned True, it won't get to this point anyway. Therefore, just use <code>return False</code> instead of putting it in an <code>else</code> block.</p>
| 0 | 2016-08-19T05:08:48Z | [
"python",
"python-3.x",
"oop",
"pygame"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.