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 |
|---|---|---|---|---|---|---|---|---|---|
Why can't Python request lib replicate this Ajax call? | 38,986,403 | <p><strong>Short version:</strong>
This Python request doesn't work. The Javascript version does. Why? </p>
<pre><code>import json
import requests
url = 'https://inputtools.google.com/request?itc=ja-t-i0-handwrit&app=demopage'
data = '{"app_version":0.4,"api_level":"537.36","device":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36","input_type":0,"options":"enable_pre_space","requests":[{"writing_guide":{"writing_area_width":200,"writing_area_height":200},"pre_context":"","max_num_results":1,"max_completions":0,"ink":[[[100,100],[20,180],[0,1]],[[20,180],[100,100],[2,3]]]}]}'
headers = {'content-type': 'application/json'}
r = requests.post(url, json=data, headers=headers)
print r.json()
</code></pre>
<p><strong>Longer version:</strong>
I have this Javascript that successfully makes an Ajax call. I print the response to the console and can see an array of suggested characters from the input I send.</p>
<p><a href="https://jsbin.com/wufesifasa/1/edit?js,console,output" rel="nofollow">https://jsbin.com/wufesifasa/1/edit?js,console,output</a></p>
<pre><code>var text = {
'app_version' : 0.4,
'api_level' : '537.36',
'device' : window.navigator.userAgent,
'input_type' : 0, // ?
'options' : 'enable_pre_space', // ?
'requests' : [ {
'writing_guide' : {
'writing_area_width' : 200, // canvas width
'writing_area_height' : 200, // canvas height
},
'pre_context' : '', // confirmed preceding chars
'max_num_results' : 1,
'max_completions' : 0,
'ink' : []
} ]
};
// written coordinates to be sent
text.requests[0].ink = [
[[100,100],[20,180],[0,1]],
[[20,180],[100,100],[2,3]],
];
console.log(JSON.stringify(text))
$.ajax({
url : 'https://inputtools.google.com/request?itc=ja-t-i0-handwrit&app=demopage',
method : 'POST',
contentType : 'application/json',
data : JSON.stringify(text),
dataType : 'json',
}).done(function(json) {
console.log(json);
});
</code></pre>
<p>Output:</p>
<blockquote>
<p>["SUCCESS", [["fb02254b519a9da2", ["+", "å", "t", "T", "ã", "f", "å",
"å¹²", "1", "å"], [], [object Object] { is_html_escaped: false }]]]</p>
</blockquote>
<p>Now I'm trying to replicate that in Python. I've tried using the above code and many variations of it, but every time I receive the response 'FAILED_TO_PARSE_REQUEST_BODY'. What's different between the Ajax and Python calls that makes my request fail? </p>
<p>This question is similar to <a href="http://stackoverflow.com/questions/35326206/simulating-ajax-request-with-python-using-the-requests-lib">this</a> and <a href="http://stackoverflow.com/questions/22183899/simulating-ajax-request-with-python-using-requests-lib">this</a>, but they deal with using the same key multiple times and incorrect data encoding, which I do not think applies in this case. </p>
| 0 | 2016-08-17T00:28:00Z | 39,010,456 | <p>The line <code>json=data</code> should have been <code>data=data</code>. The json attribute accepts a dictionary, which that <code>data</code> string is not. Here is what working code looks like:</p>
<pre><code>import json
import requests
url = 'https://inputtools.google.com/request?itc=ja-t-i0-handwrit&app=demopage'
data = '{"app_version":0.4,"api_level":"537.36","device":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36","input_type":0,"options":"enable_pre_space","requests":[{"writing_guide":{"writing_area_width":200,"writing_area_height":200},"pre_context":"","max_num_results":1,"max_completions":0,"ink":[[[100,100],[20,180],[0,1]],[[20,180],[100,100],[2,3]]]}]}'
headers = {'content-type': 'application/json'}
r = requests.post(url, json=data, headers=headers)
print r.json()
</code></pre>
| 0 | 2016-08-18T05:18:21Z | [
"python",
"ajax",
"request"
] |
Pandas: resample time group names after a dataframe groupby | 38,986,427 | <p>My dataframe looks like</p>
<pre><code>Time, Id A B C
2016-06-15 08:09:26.212962 115516 3 3.238 7.790000
2016-06-15 08:10:13.863304 115517 3 0.000 8.930000
2016-06-15 08:11:02.236033 115518 3 0.000 9.090000
2016-06-15 08:11:52.085754 115519 3 0.000 9.420000
</code></pre>
<p>If I apply a groupby like </p>
<pre><code>grouped = df.groupby(pd.TimeGrouper("5Min"), as_index=False)
</code></pre>
<p>I get group names and groups like:</p>
<pre><code>2016-06-15 08:05:00
2016-06-15 08:09:26.212962
2016-06-15 08:10:00
2016-06-15 08:10:13.863304
2016-06-15 08:11:02.236033
2016-06-15 08:11:52.085754
2016-06-15 08:25:00
2016-06-15 08:25:41.827770
</code></pre>
<p>So my question is how can I resample the group names formed above and fill non existent groups with None to get something like: </p>
<pre><code>2016-06-15 08:05:00
2016-06-15 08:09:26.212962
2016-06-15 08:10:00
2016-06-15 08:10:13.863304
2016-06-15 08:11:02.236033
2016-06-15 08:11:52.085754
2016-06-15 08:15:00
2016-06-15 08:20:00
2016-06-15 08:25:00
2016-06-15 08:25:41.827770
</code></pre>
<p>Can this be formed as a Dataframe as well?</p>
<p>Regards</p>
| 1 | 2016-08-17T00:31:13Z | 38,986,732 | <p>Simplest way is to form them into another DataFrame. Use <code>pd.concat</code></p>
<pre><code>frames, names = [], []
grouped = df.groupby(pd.TimeGrouper("5Min"), as_index=False)
for name, group in grouped:
names.extend([name])
frames.extend([group])
pd.concat(frames, keys=names)
</code></pre>
| 0 | 2016-08-17T01:16:02Z | [
"python",
"pandas",
"dataframe",
"time-series"
] |
Pandas: resample time group names after a dataframe groupby | 38,986,427 | <p>My dataframe looks like</p>
<pre><code>Time, Id A B C
2016-06-15 08:09:26.212962 115516 3 3.238 7.790000
2016-06-15 08:10:13.863304 115517 3 0.000 8.930000
2016-06-15 08:11:02.236033 115518 3 0.000 9.090000
2016-06-15 08:11:52.085754 115519 3 0.000 9.420000
</code></pre>
<p>If I apply a groupby like </p>
<pre><code>grouped = df.groupby(pd.TimeGrouper("5Min"), as_index=False)
</code></pre>
<p>I get group names and groups like:</p>
<pre><code>2016-06-15 08:05:00
2016-06-15 08:09:26.212962
2016-06-15 08:10:00
2016-06-15 08:10:13.863304
2016-06-15 08:11:02.236033
2016-06-15 08:11:52.085754
2016-06-15 08:25:00
2016-06-15 08:25:41.827770
</code></pre>
<p>So my question is how can I resample the group names formed above and fill non existent groups with None to get something like: </p>
<pre><code>2016-06-15 08:05:00
2016-06-15 08:09:26.212962
2016-06-15 08:10:00
2016-06-15 08:10:13.863304
2016-06-15 08:11:02.236033
2016-06-15 08:11:52.085754
2016-06-15 08:15:00
2016-06-15 08:20:00
2016-06-15 08:25:00
2016-06-15 08:25:41.827770
</code></pre>
<p>Can this be formed as a Dataframe as well?</p>
<p>Regards</p>
| 1 | 2016-08-17T00:31:13Z | 38,989,448 | <p>This is the best I could come up with for now.</p>
<pre><code>df.set_index('Time').groupby(pd.TimeGrouper('5T')) \
.apply(lambda df: df.reset_index()).unstack() \
.resample('5T').last().stack(dropna=False)
</code></pre>
| 0 | 2016-08-17T06:25:13Z | [
"python",
"pandas",
"dataframe",
"time-series"
] |
Django logout function is not working | 38,986,470 | <p>I'm using the Django login and logout functions, the login function works, but the logout is not working.</p>
<p>In my HTML file, I have:</p>
<pre><code><a href="{% url 'django.contrib.auth.views.logout' %}">logout</a>
<a href="{% url 'django.contrib.auth.views.login' %}">login</a>
</code></pre>
<p>in my urls.py file I have:</p>
<pre><code>url(r'^$', 'django.contrib.auth.views.login', {
'template_name': 'blog/login.html'
}),
url(r'^$', 'django.contrib.auth.views.logout', {
'template_name': 'blog/logout.html'
}),
</code></pre>
<p>When I login, it works perfectly fine, and I can display the logged in person's name. But when I logout, I'm still logged in because the logged in user's name is still displayed in the banner area.</p>
<p>in my HTML file I have:</p>
<pre><code>{% if user.is_authenticated %}
{{ user }}
{% endif %}
</code></pre>
<p>If the logout function worked, the user name shouldn't be displayed. So I'm assuming it is not working.</p>
<p>What seems to be the issue, any help/direction would be appreciated.</p>
<p>Thanks in advance,</p>
| 0 | 2016-08-17T00:37:17Z | 38,987,984 | <p>Try this:</p>
<pre><code>{% if request.user.is_authenticated %}
Hello {{ request.user.username }}.
{% else %}
Hello Guest
{% endif %}
</code></pre>
| 1 | 2016-08-17T04:10:01Z | [
"python",
"django"
] |
Django logout function is not working | 38,986,470 | <p>I'm using the Django login and logout functions, the login function works, but the logout is not working.</p>
<p>In my HTML file, I have:</p>
<pre><code><a href="{% url 'django.contrib.auth.views.logout' %}">logout</a>
<a href="{% url 'django.contrib.auth.views.login' %}">login</a>
</code></pre>
<p>in my urls.py file I have:</p>
<pre><code>url(r'^$', 'django.contrib.auth.views.login', {
'template_name': 'blog/login.html'
}),
url(r'^$', 'django.contrib.auth.views.logout', {
'template_name': 'blog/logout.html'
}),
</code></pre>
<p>When I login, it works perfectly fine, and I can display the logged in person's name. But when I logout, I'm still logged in because the logged in user's name is still displayed in the banner area.</p>
<p>in my HTML file I have:</p>
<pre><code>{% if user.is_authenticated %}
{{ user }}
{% endif %}
</code></pre>
<p>If the logout function worked, the user name shouldn't be displayed. So I'm assuming it is not working.</p>
<p>What seems to be the issue, any help/direction would be appreciated.</p>
<p>Thanks in advance,</p>
| 0 | 2016-08-17T00:37:17Z | 38,988,037 | <p>There are a couple of issues here. </p>
<p>Firstly, you have exactly the same URL pattern (<code>'^$'</code>) for both login and logout views. This means that the second (logout) pattern will never actually be used because the first one always matches. When you try to log out, the first view that matches is the login view, hence you can never log out. </p>
<p>Change it to:</p>
<pre><code>from django.contrib.auth import views as auth_views
url(r'^login/$', auth_views.login, {
'template_name': 'blog/login.html'
}, name='login'),
url(r'^logout/$', auth_views.logout, {
'template_name': 'blog/logout.html'
}, name='logout'),
</code></pre>
<p>(See the <a href="https://docs.djangoproject.com/en/stable/topics/auth/default/#module-django.contrib.auth.views" rel="nofollow">documentation on using the authentication views</a>.)</p>
<p>Then in your template, you need to refer to the URLs using their names (which I have added above):</p>
<pre><code><a href="{% url 'logout' %}">logout</a>
<a href="{% url 'login' %}">login</a>
</code></pre>
<p>Your current approach (of passing a dotted path to a URL function) has been <a href="https://docs.djangoproject.com/en/1.9/releases/1.8/#passing-a-string-as-view-to-url" rel="nofollow">deprecated since Django 1.8</a> and was removed in Django 1.10, so you should stop using it.</p>
| 2 | 2016-08-17T04:16:29Z | [
"python",
"django"
] |
Program not terminating when score limit is reached? | 38,986,525 | <p>I'm working on a simple text-based trivia game as my first python project, and my program won't terminate once the score limit is reached.</p>
<pre><code>def game(quest_list):
points = 0
score_limit = 20
x, y = info()
time.sleep(2)
if y >= 18 and y < 100:
time.sleep(1)
while points < score_limit:
random.choice(quest_list)(points)
time.sleep(2)
print("Current score:", points, "points")
print("You beat the game!")
quit()
...
</code></pre>
| 1 | 2016-08-17T00:45:21Z | 38,986,607 | <p>It looks like the <code>points</code> variable is not increased. Something like this might work in your inner loop:</p>
<pre><code> while points < score_limit:
points = random.choice(quest_list)(points)
time.sleep(2)
print("Current score:", points, "points")
</code></pre>
<p>I'm assuming that <code>quest_list</code> is a list of functions, and you're passing the <code>points</code> value as an argument? To make this example work, you'll also want to return the points from the function returned by the <code>quest_list</code> that's called. A perhaps cleaner way to build this would be to return only the points generated by the quest. Then you could do something like:</p>
<pre><code> quest = random.choice(quest_list)
points += quest()
</code></pre>
<p>Unless <code>points</code> is a mutable data structure, it won't change the value. You can read more about that in <a href="http://stackoverflow.com/questions/15148496/python-passing-an-integer-by-reference">this StackOverflow question</a>. </p>
| 2 | 2016-08-17T00:58:13Z | [
"python"
] |
Sunrise and Sunset time in Python | 38,986,527 | <p>I'm currently working on a IoT project using NanoPi M1 and it's expected to notify the users when the amount of light received is not adequate during the day time. I've done the part related to light. Hence, I need to find an effective way to retrieve sunrise and sunset time in python, since the whole script is written in python. I know there are several libraries out there for other languages, I wonder what is the most convenient way to do this in python.</p>
<p>It will seem pretty much like this, I suppose:</p>
<pre><code>if(sunrise<T<sunset) and (light<threshold):
notifyUser()
</code></pre>
<p>I'd appreciate any help here, have a good one.</p>
| 2 | 2016-08-17T00:45:38Z | 38,986,561 | <p>Check out <a href="https://pypi.python.org/pypi/astral/1.2" rel="nofollow">astral</a>. Here's a slightly modified <a href="http://pythonhosted.org/astral/#example" rel="nofollow">example from their docs</a>:</p>
<pre><code>>>> from astral import Astral
>>> city_name = 'London'
>>> a = Astral()
>>> a.solar_depression = 'civil'
>>> city = a[city_name]
>>> sun = city.sun(date=datetime.date(2009, 4, 22), local=True)
>>> if (sun['sunrise'] < T < sun['sunset']) and (light < threshold):
>>> notifyUser()
</code></pre>
<p>If you use something like this example, please remember to change the <code>city_name</code> and date provided to <code>city.sun</code>.</p>
| 3 | 2016-08-17T00:50:39Z | [
"python",
"datetime",
"time",
"raspberry-pi"
] |
Making python code more efficient | 38,986,567 | <p>I have the code</p>
<pre><code>num = 1
num2 = 1
num3 = 1
list = []
list2 = []
list3 = []
def numCheck1 (num):
while num<1001:
if (num%3==0):
if (num%5==0):
print num
list.append(num)
num+=1
numCheck1(num)
break
else:
print "error 1"
else:
print "error 2"
num+=1
numCheck1(num)
total=sum(list)
print list
print total
def numCheck2 (num2):
while num2<1001:
if (num2%5==0):
print num2
list2.append(num2)
num2+=1
numCheck1(num2)
break
else:
print "error"
numCheck2(num2)
def numCheck3 (num3):
while num3<1001:
if (num3%3==0):
print num3
list3.append(num3)
num3+=1
numCheck1(num3)
break
else:
print "error"
numCheck3(num3)
total2 = sum(list2)
total3 = sum(list3)
overall = (total2 + total3) - total
print list2
print list3
print total2
print total3
print overall
</code></pre>
<p>As a basic summary of my code, I have 3 functions, and corresponding lists and variables for each of them. The first function checks for all multiples of 3 and 5 below and equal to 1000. The second checks for all multiples of 5 below and equal to 1000. The third checks for all multiples of 3 below and equal to 1000. The numbers that are multiples are added to the corresponding list, while the corresponding variable is incremented to allow the function to check all numbers. At the end, the program calculates 4 totals: the total of each of the lists, and a special total, which adds together the second two totals and subtracts the first to prevent overcounting. This is just the overarching structure of the program.</p>
<p>This program is supposed to solve <a href="https://projecteuler.net/problem=1" rel="nofollow">this problem</a> (not homework, just fun). The code is working (as far as I know; the first function definitely works) but it keeps crashing the compiler (I am using an online compiler, <a href="https://repl.it/" rel="nofollow">repl</a>. I am wondering if there are any ways to make this code more efficient.</p>
<p>Thanks!</p>
| 0 | 2016-08-17T00:51:21Z | 38,986,596 | <p><code>numCheck1</code>: Since <em>all</em> multiples of 3 and 5 are <em>also</em> multiples of 15, you can simply print out each item in <code>range(0, 1001, 15)</code> (counts by 15)</p>
<p><code>numCheck2</code>: <code>range(0, 1001, 5)</code> (counts by 5) should already be all multiples of 5 less than or equal to 1000.</p>
<p><code>numCheck3</code>: <code>range(0, 1001, 3)</code> (counts by 3) is the same thing as above, simply with multiples of 3.</p>
| 1 | 2016-08-17T00:57:07Z | [
"python",
"performance"
] |
Making python code more efficient | 38,986,567 | <p>I have the code</p>
<pre><code>num = 1
num2 = 1
num3 = 1
list = []
list2 = []
list3 = []
def numCheck1 (num):
while num<1001:
if (num%3==0):
if (num%5==0):
print num
list.append(num)
num+=1
numCheck1(num)
break
else:
print "error 1"
else:
print "error 2"
num+=1
numCheck1(num)
total=sum(list)
print list
print total
def numCheck2 (num2):
while num2<1001:
if (num2%5==0):
print num2
list2.append(num2)
num2+=1
numCheck1(num2)
break
else:
print "error"
numCheck2(num2)
def numCheck3 (num3):
while num3<1001:
if (num3%3==0):
print num3
list3.append(num3)
num3+=1
numCheck1(num3)
break
else:
print "error"
numCheck3(num3)
total2 = sum(list2)
total3 = sum(list3)
overall = (total2 + total3) - total
print list2
print list3
print total2
print total3
print overall
</code></pre>
<p>As a basic summary of my code, I have 3 functions, and corresponding lists and variables for each of them. The first function checks for all multiples of 3 and 5 below and equal to 1000. The second checks for all multiples of 5 below and equal to 1000. The third checks for all multiples of 3 below and equal to 1000. The numbers that are multiples are added to the corresponding list, while the corresponding variable is incremented to allow the function to check all numbers. At the end, the program calculates 4 totals: the total of each of the lists, and a special total, which adds together the second two totals and subtracts the first to prevent overcounting. This is just the overarching structure of the program.</p>
<p>This program is supposed to solve <a href="https://projecteuler.net/problem=1" rel="nofollow">this problem</a> (not homework, just fun). The code is working (as far as I know; the first function definitely works) but it keeps crashing the compiler (I am using an online compiler, <a href="https://repl.it/" rel="nofollow">repl</a>. I am wondering if there are any ways to make this code more efficient.</p>
<p>Thanks!</p>
| 0 | 2016-08-17T00:51:21Z | 38,986,717 | <p>I've re-written your code, with comments in-line. You could improve things even more over this, but I think seeing where you could improve this code will be helpful for you.</p>
<pre><code># If you use this, it should be the first line
# in your code. If you're using Python2, you *should*
# use this, because it will make switching to Python3
# that much easier.
from __future__ import print_function
# No need for these global variables
#num = 1
#num2 = 1
#num3 = 1
#list = []
#list2 = []
#list3 = []
#
# Functions should be snake_cased, not camelCase
# also, the blank space between the function name
# and the paren is inconsistent with typical
# Python code.
def num_check_one(start):
# We'll put the return list in here. Also
# calling it `list = []` would have shadowed
# a builtin function. Let's give it a better name:
multiples = []
# If you're iterating over known values in Python
# use a for loop over a range instead.
for num in range(start, 1001):
# No need to nest your ifs.
# Parenthesis are usually just extra noise,
# But you might find it a little clearer with
# them to clarify the grouping
#if (num % 3 == 0) and (num % 5 == 0):
# This could also be written as
# if (not num % 3) and (not num % 5):
# Or, using De Morgan's law:
# if not (num % 3 or num % 5):
if num % 3 == 0 and num % 5 == 0:
print(num)
multiples.append(num)
# Uh, no need to recursively call
# your function here.
#numCheck1(num)
#break
# And finally, you don't need any of these
# else:
# print "error 1"
# else:
# print "error 2"
# num+=1
return multiples
# You can use the keyword in your function call
# which makes it clear what the value is for
multiples = num_check_one(start=1)
total=sum(multiples)
print('Multiples:', multiples)
print('Total:', total)
# Again, fixed casing/spacing, and gave the
# parameter a meaningful name
def num_check_two(start):
multiples = []
# Again, for loop
for num in range(start, 10001):
# 0 is Falsey, so we can
# just treat it as a bool value
if not num % 5:
print(num)
multiples.append(num)
# Got rid of the recursive call again
# You were never incrementing `num2` here,
# which is why your code got into an infinite
# loop. Also why you should use `for` loops by
# default
num_check_two(1)
</code></pre>
| 2 | 2016-08-17T01:13:36Z | [
"python",
"performance"
] |
How to transform user input string into correct object type | 38,986,720 | <p>I am using Python (2.7) along with Natural Language Toolkit (3.2.1) and WordNet. I am <em>very</em> new to programming.</p>
<p>I am trying to write a program which asks the user for a word, then prints synonym sets for that word, then asks the user which synonym set it wants to see the lemmas for.</p>
<p>The problem is that <code>raw_input</code> only accepts strings, so when I try to use the method <code>.lemma_names()</code> on the user input, I get the error <code>AttributeError: 'str' object has no attribute 'lemma_names'</code>.</p>
<p>Here is the code:</p>
<pre><code>from nltk.corpus import wordnet as wn
w1 = raw_input ("What is the word? ")
#This prints the synsets for w1, thus showing them what format to use in the next question.
for synset in wn.synsets(w1):
print synset
#This asks the user to choose the synset of w1 that interests them.
synset1 = raw_input ("Which sense are you looking for? [Use same format as above]")
#This prints the lemmas from the synset of interest.
for x in synset1.lemma_names():
print x
</code></pre>
<p>My question is, how do I transform the user's input from a string to a synset type which I can use the <code>.lemma_names()</code> method on?</p>
<p>I apologize if this question is so basic as to be off-topic. If so, let me know.</p>
| 3 | 2016-08-17T01:14:09Z | 38,988,026 | <p>Try this:</p>
<pre><code>from nltk.corpus import wordnet as wn
w1 = raw_input ("What is the word? ")
synset_dict = dict()
for synset in wn.synsets(w1):
name = synset.name()
synset_dict[name] = synset
print name
synset1 = raw_input ("Which sense are you looking for? [Use same format as above] ")
if synset1 in synset_dict:
synset = synset_dict[synset1]
for lemma in synset.lemma_names():
print lemma
</code></pre>
| 0 | 2016-08-17T04:15:20Z | [
"python",
"nltk",
"wordnet"
] |
"Counting digits" on numbers input by user (Python 2.x) | 38,986,721 | <p>Please bear with my novice question as I just started learning Python (2.x).
I'm trying to run a script where user could enter any number (e.g. ints or float) and the expected output would be the total digit numbers of that input number.</p>
<p>However, I've encountered the following problems and wondered if you could kindly help guide me through solving them. Many thanks!! :)</p>
<p>(problems)</p>
<ol>
<li><p>In the printout message, the n value was always 0; whereas I wished to print out the original input number by the user.</p></li>
<li><p>I wished it would also process the float number. For now, a 'ValueError' was returned and the script was halted whenever a float number was entered.</p></li>
<li><p>If user enters any string or blank character, the script should ignore the input and repeat all over again asking for the user input until the number with correct format (i.e. either integer or float number) was entered.</p></li>
</ol>
<p> </p>
<pre><code>def num_digits(n):
count = 0
while n:
count = count + 1
n = n/10
print 'The total digits for this number, ', n, ', are: ', count
return count
user_input = abs(int(raw_input('Enter a number:\n')))
num_digits(user_input)
</code></pre>
| 2 | 2016-08-17T01:14:42Z | 38,986,804 | <p><code>n</code> is always going to be zero because you have this line:</p>
<pre><code>while n:
</code></pre>
<p>It can never exit that loop without becoming a False-y value. If you want to keep the original value, either operate on a copy, or store the original value:</p>
<pre><code>def num_digits(n):
original = n
... # the rest of your code
</code></pre>
<p>For floats, you need to convert your input to a float instead, i.e.</p>
<pre><code>user_input = abs(float(raw_input('Enter a number:\n')))
</code></pre>
<p>And finally, if you want to require a number you could do something like this:</p>
<pre><code>invalid_input = True
while invalid_input:
user_input = raw_input('Enter a number:\n')
try:
number = abs(float(user_input))
except ValueError:
print('***ERROR*** Please enter a number.')
else:
num_digits(number)
</code></pre>
<p>Of course, you could make your life even easier, and change the else to this:</p>
<pre><code> else:
print(len(user_input.split('.')[0]))
</code></pre>
<p>(The <code>split('.')[0]</code> is for handling floating point numbers)</p>
<p><strong>Update</strong>:</p>
<p>It appears that you wanted the <em>actual</em> length of the floating point digit rather than to use the exact algorithm you're using. In which case, forget the <code>.split</code> part, <code>print(len(user_input))</code> should do what you want.</p>
| 0 | 2016-08-17T01:27:36Z | [
"python",
"python-2.7"
] |
"Counting digits" on numbers input by user (Python 2.x) | 38,986,721 | <p>Please bear with my novice question as I just started learning Python (2.x).
I'm trying to run a script where user could enter any number (e.g. ints or float) and the expected output would be the total digit numbers of that input number.</p>
<p>However, I've encountered the following problems and wondered if you could kindly help guide me through solving them. Many thanks!! :)</p>
<p>(problems)</p>
<ol>
<li><p>In the printout message, the n value was always 0; whereas I wished to print out the original input number by the user.</p></li>
<li><p>I wished it would also process the float number. For now, a 'ValueError' was returned and the script was halted whenever a float number was entered.</p></li>
<li><p>If user enters any string or blank character, the script should ignore the input and repeat all over again asking for the user input until the number with correct format (i.e. either integer or float number) was entered.</p></li>
</ol>
<p> </p>
<pre><code>def num_digits(n):
count = 0
while n:
count = count + 1
n = n/10
print 'The total digits for this number, ', n, ', are: ', count
return count
user_input = abs(int(raw_input('Enter a number:\n')))
num_digits(user_input)
</code></pre>
| 2 | 2016-08-17T01:14:42Z | 38,986,830 | <p>Since you also want to be able to count the digits of floats, simply doing <code>n/10</code> isn't enough. With float values, your loop will end up being infinite, since it will be doing float division instead of int division. (Ex. <code>16.3 / 10 = 1.63</code> --> <code>1.63 / 10 = .163</code> etc -- it will never reach <code>0</code>)</p>
<p>To avoid this problem, I recommend treating the number as a string and counting the number of characters in the string which are digits.</p>
<pre><code>def num_digits(n):
count = 0
curr = n # remaining string you're currently evaluating
while (curr != ''):
digit = curr[len(curr)-1] # get final char
curr = curr[:len(curr)-1] # trim last char off the string
if (not digit.isdigit()):
# ignore things like decimal points or negative signs
continue
count += 1
return count
while True:
value = raw_input('Enter a number:\n') # keep it in string form
try:
convert = float(value) # if it's a valid float, then it's also a valid int
break
except:
print "not a number. enter a valid number"
nd = num_digits(value)
print('{} has {} digits'.format(value, nd))
</code></pre>
<p>Sample output:</p>
<pre><code># float number, ignores negative sign and decimal point
$ python script.py
Enter a number:
-16.3
-16.3 has 3 digits
# asks for input until it has a valid number
$ python script.py
Enter a number:
foo
not a number. enter a valid number
Enter a number:
blah3
not a number. enter a valid number
Enter a number:
89
89 has 2 digits
</code></pre>
| 0 | 2016-08-17T01:32:24Z | [
"python",
"python-2.7"
] |
"Counting digits" on numbers input by user (Python 2.x) | 38,986,721 | <p>Please bear with my novice question as I just started learning Python (2.x).
I'm trying to run a script where user could enter any number (e.g. ints or float) and the expected output would be the total digit numbers of that input number.</p>
<p>However, I've encountered the following problems and wondered if you could kindly help guide me through solving them. Many thanks!! :)</p>
<p>(problems)</p>
<ol>
<li><p>In the printout message, the n value was always 0; whereas I wished to print out the original input number by the user.</p></li>
<li><p>I wished it would also process the float number. For now, a 'ValueError' was returned and the script was halted whenever a float number was entered.</p></li>
<li><p>If user enters any string or blank character, the script should ignore the input and repeat all over again asking for the user input until the number with correct format (i.e. either integer or float number) was entered.</p></li>
</ol>
<p> </p>
<pre><code>def num_digits(n):
count = 0
while n:
count = count + 1
n = n/10
print 'The total digits for this number, ', n, ', are: ', count
return count
user_input = abs(int(raw_input('Enter a number:\n')))
num_digits(user_input)
</code></pre>
| 2 | 2016-08-17T01:14:42Z | 38,986,970 | <p>Another answers have already explaine your bug. Anyway, here's a couple of other options for you to take a look & understand:</p>
<pre><code>def num_digits1(n):
return len(str(n).replace(".", "").replace("-", ""))
def num_digits2(n):
return sum(c.isdigit() for c in str(n))
for v in [-1.0, 0, 00, 000, 1.0, 1e2, 1e-2]:
print v, num_digits1(v), num_digits2(v)
</code></pre>
| 1 | 2016-08-17T01:53:12Z | [
"python",
"python-2.7"
] |
"Counting digits" on numbers input by user (Python 2.x) | 38,986,721 | <p>Please bear with my novice question as I just started learning Python (2.x).
I'm trying to run a script where user could enter any number (e.g. ints or float) and the expected output would be the total digit numbers of that input number.</p>
<p>However, I've encountered the following problems and wondered if you could kindly help guide me through solving them. Many thanks!! :)</p>
<p>(problems)</p>
<ol>
<li><p>In the printout message, the n value was always 0; whereas I wished to print out the original input number by the user.</p></li>
<li><p>I wished it would also process the float number. For now, a 'ValueError' was returned and the script was halted whenever a float number was entered.</p></li>
<li><p>If user enters any string or blank character, the script should ignore the input and repeat all over again asking for the user input until the number with correct format (i.e. either integer or float number) was entered.</p></li>
</ol>
<p> </p>
<pre><code>def num_digits(n):
count = 0
while n:
count = count + 1
n = n/10
print 'The total digits for this number, ', n, ', are: ', count
return count
user_input = abs(int(raw_input('Enter a number:\n')))
num_digits(user_input)
</code></pre>
| 2 | 2016-08-17T01:14:42Z | 38,987,002 | <p>This should do everything you asked. Feel free to comment any questions</p>
<pre><code>def num_digits():
while True:
n = raw_input('Enter a number:\n')
try:
float(n)
if '.' and '-' in n:
print len(n) - 2
elif '.' in n or '-' in n:
print len(n) - 1
else:
print len(n)
break
except:
print 'Invalid Input\n'
continue
num_digits()
</code></pre>
| 0 | 2016-08-17T01:58:57Z | [
"python",
"python-2.7"
] |
Understanding inheritance with python classes | 38,986,722 | <p>so I am trying to understand how to build child classes in python.</p>
<p>So ive created a perent and a child class but I just cant understand how to get them to work</p>
<p>so this is my current code</p>
<pre><code>from abc import ABCMeta, abstractmethod
class Persion(object):
__metaclass__ = ABCMeta # sets the metaclass to a abstract base class . that means we never call this class directley insted its used for child classes to inhearrit
def __init__(self, name, gender):
self.name = name
self.gender = gender
def talk(self):
print("hi my name is " + self.name + " and I am a " + self.gender + ".")
@abstractmethod
def PersionType(self):
"""Returns a string of the childs type"""
pass
class Player(Persion):
def __int__(self,speed):
self.name = name
self.gender = gender
self.speed = speed
self.posX = 0
self.posY = 0
def moveXY(self, X, Y):
self.posX = X
self.posY = Y
def PersionType(self):
return 'Player'
player=Persion("Ben","m")
hero = Player(player,30)
hero.moveXY(20,20)
print("you are now at ", hero.posX, "," , hero.posY)
print("your speed is ", hero.speed)
print("your gender is ", hero.gender)
hero.talk()
</code></pre>
<p>so the end result is I want these functions to work.
but something has gone rong in buildign the inhertance thats what I want to find out.</p>
<pre><code>hero.moveXY(20,20)
print("you are now at ", hero.posX, "," , hero.posY)
print("your speed is ", hero.speed)
print("your gender is ", hero.gender)
hero.talk()
</code></pre>
<p>im getting errors sutch as </p>
<pre><code> line 36, in <module>
print("your speed is ", hero.speed)
AttributeError: 'Player' object has no attribute 'speed'
</code></pre>
<p>I am making this to help me understand how inheratince works in python. </p>
| 1 | 2016-08-17T01:14:43Z | 38,986,788 | <p>There are <strong>three main problems</strong> with your code:</p>
<ol>
<li><p>Change <code>__int__</code> to <code>__init__</code>. Your instance isn't getting initialized, which is why you get the <code>no attribute 'speed'</code> error.</p></li>
<li><p>Your subclass (the class that's inheriting, which in this case is <code>Player</code>) should have an <code>__init__</code> method that takes all the arguments you want associated with it. You can pass the ones used by the superclass (<code>Persion</code>) to the superclass's <code>__init__</code>. That means probably changing the <code>__init__</code> method to:</p>
<pre><code>class Player(Persion):
def __init__(self, name, gender, speed):
super(Player, self).__init__(name, gender)
self.speed = speed
self.posX = 0
self.posY = 0
</code></pre></li>
<li><p>Now, when creating the instances, you need only create an instance of the subclass. It will inherit the methods from the superclass:</p>
<pre><code>hero = Player('Ben', 'm', 30)
</code></pre></li>
</ol>
<p>With these changes, these lines:</p>
<pre><code>print("you are now at ", hero.posX, "," , hero.posY)
print("your speed is ", hero.speed)
print("your gender is ", hero.gender)
hero.talk()
</code></pre>
<p>Now produce this output:</p>
<pre><code>you are now at 20 , 20
your speed is 30
your gender is m
hi my name is Ben and I am a m.
</code></pre>
<p><strong>Additional small notes</strong>:</p>
<ul>
<li>You probably want the class to be named <code>Person</code> instead of <code>Persion</code>.</li>
<li>The <code>@abstractmethod</code> method should not be needed.</li>
</ul>
| 2 | 2016-08-17T01:24:33Z | [
"python",
"class"
] |
Why won't my kv BoxLayout centre horizontally? | 38,986,793 | <p>This is my test.kv file:</p>
<pre><code>BoxLayout:
BoxLayout:
orientation: 'vertical'
size_hint: None, None
height: '160sp'
width: '380sp'
pos_hint: {'center_x': .5, 'center_y': .5}
BoxLayout:
Label:
text: 'UserName'
TextInput:
id: user_name
text: ''
BoxLayout:
Label:
text: 'Password'
TextInput:
id: password
password: True
text: ''
BoxLayout:
Label:
text: 'Domain'
TextInput:
id: domain
text: 'howefarmingco.local'
Button:
text: 'Login'
size_hints: None, 1
width: .6
pos_hint: {'center_x': .5}
on_press: app.do_login()
</code></pre>
<p>The idea is to have the login fields appear centred both vertically and horizontally. The vertical works as I expect it to, but the fields and button all display on the left edge of the window instead of the middle.</p>
<p>Am I missing something very basic here or just going about it in entirely the wrong way?</p>
| 0 | 2016-08-17T01:25:42Z | 38,986,842 | <p>Ahh, silly Mike. I just re-read the docs for the 100th time and it was staring me right in the face.</p>
<p>pos_hint is not used by all layouts!</p>
<p>From FloatLayout docs: FloatLayout honors the pos_hint and the size_hint properties of its children.</p>
<p>Changed my test.kv file so outer BoxLayout is now a FloatLayout and everything works as expected.</p>
| 1 | 2016-08-17T01:33:31Z | [
"python",
"kivy"
] |
When import Theano, I got exception: "dot.exe" not found in path | 38,986,821 | <p>I am running python on Anaconda. I downloaded the Theano from "<a href="https://github.com/Theano/Theano.git" rel="nofollow">https://github.com/Theano/Theano.git</a>" and installed it by running </p>
<pre><code>cd Theano
python setup.py develop
</code></pre>
<p>However, when I tried to import the theano on Ipython notebook. I got the ""dot.exe" not found in path." exception. Have no clue what is going on...</p>
<pre><code>import numpy as np
import time
import theano
Exception Traceback (most recent call last)
<ipython-input-1-432f5c01387b> in <module>()
1 import numpy as np
2 import time
----> 3 import theano
c:\users\t-ninma\documents\studymaterials\theano\theano\__init__.py in <module>()
79 from theano.misc.safe_asarray import _asarray
80
---> 81 from theano.printing import pprint, pp
82
83 from theano.scan_module import scan, map, reduce, foldl, foldr, clone
c:\users\t-ninma\documents\studymaterials\theano\theano\printing.py in <module>()
42 pydot_imported_msg = "pydot can't find graphviz"
43 else:
---> 44 pd.Dot.create(pd.Dot())
45 pydot_imported = True
46 except ImportError:
C:\Users\t-ninma\AppData\Local\Continuum\Anaconda2\lib\site-packages\pydot.pyc in create(self, prog, format)
1874 raise Exception(
1875 '"{prog}" not found in path.'.format(
-> 1876 prog=prog))
1877 else:
1878 raise
Exception: "dot.exe" not found in path.
</code></pre>
| 0 | 2016-08-17T01:30:51Z | 38,987,596 | <p>Seems like you are running anaconda in windows. When installing <code>Theano</code> in a windows machines sometimes there are some issues.</p>
<p><a href="http://rosinality.ncity.net/doku.php?id=python:installing_theano" rel="nofollow">Here</a> you can see a good way to install theano in windows machines. If you have installed any <strong>mingw</strong> compiler or <strong>msys</strong> before, remove then before following this method.</p>
<p>Hope this method will work..!</p>
| 0 | 2016-08-17T03:21:52Z | [
"python",
"theano"
] |
Convert js function to python functions does't work | 38,986,824 | <p>I have found an algorithm written in js (That I don't know how to code with) then I tried to convert it to python after a conversation with some friends who know js<br />
<strong>Javascript</strong></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function crack(code) {
var N = '';
var M = '';
for(var i = 0; i < code.length; i++) {
if(i%2 == 0) {
N += code[i];
} else {
M = code[i] + M;
}
}
var key = N + M;
key = window.atob(key);
key = key.substring(2);
return key;
}</code></pre>
</div>
</div>
</p>
<p><strong>Python</strong></p>
<pre><code>import base64
def crack(code):
N = ''
M = ''
i = 0
for letter in code:
i =code.find(letter)
if i%2 == 0:
N += code[i]
else:
M =code[i] + M
key = N + M
key = base64.b64decode(key)
key = key[2:]
print key
</code></pre>
<p>As you can see it's the same code but the problem here that not give the same result !! <br />
The string here to try on is:<br /></p>
<blockquote>
<p>N=m=NAobdtHRRHwaOuiU8mvcZhWddH5bZhz1MWzLapyR5nibbhG19ynccl3RBXvediCV5mjcbh2d0HubZhW1cWvLM4j8ACxONwi8</p>
</blockquote>
<p>After searching for a while about window.atob found this method decodes a string of data which has been encoded by the btoa() method.<br />
Then searched about btoa found this method uses the "A-Z", "a-z", "0-9", "+", "/" and "=" characters to encode the string.<br />
Now what to do to get the same result with python ??</p>
| 0 | 2016-08-17T01:31:28Z | 38,986,857 | <p>No. It's not the same code.</p>
<pre><code>for(var i = 0; i < code.length; i++) {
if(i%2 == 0) {
</code></pre>
<p>is NOT the same as</p>
<pre><code>for letter in code:
i =code.find(letter)
if i%2 == 0:
</code></pre>
<p>What happens if all letters in the code is the same?</p>
<p>I didn't look further than this.</p>
<p>I recommend doing a "literal" translation first, and THEN attempting a "Pythonic" modification to the code.</p>
| 2 | 2016-08-17T01:36:01Z | [
"javascript",
"python",
"algorithm",
"base64",
"swap"
] |
Convert js function to python functions does't work | 38,986,824 | <p>I have found an algorithm written in js (That I don't know how to code with) then I tried to convert it to python after a conversation with some friends who know js<br />
<strong>Javascript</strong></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function crack(code) {
var N = '';
var M = '';
for(var i = 0; i < code.length; i++) {
if(i%2 == 0) {
N += code[i];
} else {
M = code[i] + M;
}
}
var key = N + M;
key = window.atob(key);
key = key.substring(2);
return key;
}</code></pre>
</div>
</div>
</p>
<p><strong>Python</strong></p>
<pre><code>import base64
def crack(code):
N = ''
M = ''
i = 0
for letter in code:
i =code.find(letter)
if i%2 == 0:
N += code[i]
else:
M =code[i] + M
key = N + M
key = base64.b64decode(key)
key = key[2:]
print key
</code></pre>
<p>As you can see it's the same code but the problem here that not give the same result !! <br />
The string here to try on is:<br /></p>
<blockquote>
<p>N=m=NAobdtHRRHwaOuiU8mvcZhWddH5bZhz1MWzLapyR5nibbhG19ynccl3RBXvediCV5mjcbh2d0HubZhW1cWvLM4j8ACxONwi8</p>
</blockquote>
<p>After searching for a while about window.atob found this method decodes a string of data which has been encoded by the btoa() method.<br />
Then searched about btoa found this method uses the "A-Z", "a-z", "0-9", "+", "/" and "=" characters to encode the string.<br />
Now what to do to get the same result with python ??</p>
| 0 | 2016-08-17T01:31:28Z | 38,986,944 | <p>You are searching for the first occurrence of letter in the code, in the line <code>i =code.find(letter)</code>. As you want the index, I recommend using <a href="https://docs.python.org/2/library/functions.html#enumerate" rel="nofollow">enumerate</a></p>
<p>Result:</p>
<pre class="lang-py prettyprint-override"><code>import base64
def crack(code):
N = ''
M = ''
i = 0
for i, letter in enumerate(code):
if i%2 == 0:
N += code[i]
else:
M =code[i] + M
key = N + M
key = base64.b64decode(key)
key = key[2:]
print key
</code></pre>
<p>Seems correct:</p>
<pre class="lang-py prettyprint-override"><code>>>> crack('N=m=NAobdtHRRHwaOuiU8mvcZhWddH5bZhz1MWzLapyR5nibbhG19ynccl3RBXvediCV5mjcbh2d0HubZhW1cWvLM4j8ACxONwi8')
http://egyg33k.blogspot.com.eg/2016/08/8-malwarebytes-anti-malware.html
</code></pre>
| 0 | 2016-08-17T01:49:02Z | [
"javascript",
"python",
"algorithm",
"base64",
"swap"
] |
__init__ : Inheriting __init__ parameter (dict) to another class's __init__ method? | 38,986,838 | <p>I am confused even after checking many questions asked in SO. I have 2 different class (2 different script) & I want to inherit super class's <code>__init__</code> method's parameters.</p>
<p>script1.py</p>
<pre><code>class MainClass():
def __init__(self,params):
self.one=params['ONE']
self.two=params['TWO']
self.three=params['THREE']
self.four=params['FOUR']
self.five=params['FIVE']
def a():
#---------
#somecode
#Initializing other class's object to access it's method.
s=SubClass() #HERE I WANT TO PASS 'PARAMS' (WHICH IS A DICTIONARY)
s.method1(....)
</code></pre>
<p>script2.py</p>
<pre><code>class SubClass(SuperClass):
def __init__(self,params):
#Here I want all the parameters inside the 'param' in super class.
#(one,two,three...., etc).
#By checking some SO questions, I changed class SubClass() -->
#class Subclass(SuperClass) & below line:
MainClass.__init__(self,params) #But technically I don't have anything
#in param in subclass.
def method1():
#some code...
</code></pre>
<p>Since sub class's param doesn't have anything, It gives me an error:</p>
<pre class="lang-none prettyprint-override"><code>self.one=params['ONE']
TypeError: 'int' object has no attribute '__getitem__'
</code></pre>
<p>I am not getting:</p>
<ol>
<li><p>How can I access all the parameters of super class to sub class in a simplest way? I don't want to pass individual arguments (like self.one, self.two..) to the sub class.</p></li>
<li><p>If I am calling third class inside <code>SubClass</code> -> <code>method1</code> --> Call 3rd class same as passing 'params'. Is it possible?</p></li>
</ol>
| 0 | 2016-08-17T01:33:17Z | 38,987,560 | <p>Is this what you need?</p>
<p><strong>script1.py</strong></p>
<pre><code>class MainClass():
def __init__(self,params):
# Save params for use by a
self.params = params
self.one=params['ONE']
self.two=params['TWO']
...
self.five=params['FIVE']
def a():
s=SubClass(self.params)
s.method1(...)
</code></pre>
<p><strong>script2.py</strong></p>
<pre><code>class SubClass(SuperClass):
def __init__(self,params):
MainClass.__init__(self,params)
def method1():
#some code...
</code></pre>
| 0 | 2016-08-17T03:18:43Z | [
"python",
"python-2.7",
"class",
"oop",
"inheritance"
] |
__init__ : Inheriting __init__ parameter (dict) to another class's __init__ method? | 38,986,838 | <p>I am confused even after checking many questions asked in SO. I have 2 different class (2 different script) & I want to inherit super class's <code>__init__</code> method's parameters.</p>
<p>script1.py</p>
<pre><code>class MainClass():
def __init__(self,params):
self.one=params['ONE']
self.two=params['TWO']
self.three=params['THREE']
self.four=params['FOUR']
self.five=params['FIVE']
def a():
#---------
#somecode
#Initializing other class's object to access it's method.
s=SubClass() #HERE I WANT TO PASS 'PARAMS' (WHICH IS A DICTIONARY)
s.method1(....)
</code></pre>
<p>script2.py</p>
<pre><code>class SubClass(SuperClass):
def __init__(self,params):
#Here I want all the parameters inside the 'param' in super class.
#(one,two,three...., etc).
#By checking some SO questions, I changed class SubClass() -->
#class Subclass(SuperClass) & below line:
MainClass.__init__(self,params) #But technically I don't have anything
#in param in subclass.
def method1():
#some code...
</code></pre>
<p>Since sub class's param doesn't have anything, It gives me an error:</p>
<pre class="lang-none prettyprint-override"><code>self.one=params['ONE']
TypeError: 'int' object has no attribute '__getitem__'
</code></pre>
<p>I am not getting:</p>
<ol>
<li><p>How can I access all the parameters of super class to sub class in a simplest way? I don't want to pass individual arguments (like self.one, self.two..) to the sub class.</p></li>
<li><p>If I am calling third class inside <code>SubClass</code> -> <code>method1</code> --> Call 3rd class same as passing 'params'. Is it possible?</p></li>
</ol>
| 0 | 2016-08-17T01:33:17Z | 38,987,585 | <p>You can pass any and all the non-keyword arguments from the subclass's <code>__init__()</code>to the superclass's like this:</p>
<pre><code>class SubClass(SuperClass):
def __init__(self, *params):
MainClass.__init__(self, *params)
...
</code></pre>
<p>This same idea will work for other methods, too.</p>
| 0 | 2016-08-17T03:20:43Z | [
"python",
"python-2.7",
"class",
"oop",
"inheritance"
] |
string substitution using regex | 38,986,841 | <p>I have this string in python </p>
<pre><code>a = "haha"
result = "hh"
</code></pre>
<p>What i would like to achieve is using regex to replace all occurrences of "aha" to "h" and all "oho" to "h" and all "ehe" to "h"</p>
<p>"h" is just an example. Basically, i would like to retain the centre character. In other words, if its 'eae' i would like it to be changed to 'a'</p>
<p>My regex would be this </p>
<pre><code>"aha|oho|ehe"
</code></pre>
<p>I thought of doing this</p>
<pre><code>import re
reg = re.compile('aha|oho|ehe')
</code></pre>
<p>However, i am stuck on how to achieve this kind of substitution without using loops to iterate through all the possible combinations?</p>
| 0 | 2016-08-17T01:33:30Z | 38,986,903 | <p>What about <code>re.sub(r'[aeo]h[aeo]','h',a)</code> ?</p>
| 1 | 2016-08-17T01:42:53Z | [
"python",
"regex"
] |
string substitution using regex | 38,986,841 | <p>I have this string in python </p>
<pre><code>a = "haha"
result = "hh"
</code></pre>
<p>What i would like to achieve is using regex to replace all occurrences of "aha" to "h" and all "oho" to "h" and all "ehe" to "h"</p>
<p>"h" is just an example. Basically, i would like to retain the centre character. In other words, if its 'eae' i would like it to be changed to 'a'</p>
<p>My regex would be this </p>
<pre><code>"aha|oho|ehe"
</code></pre>
<p>I thought of doing this</p>
<pre><code>import re
reg = re.compile('aha|oho|ehe')
</code></pre>
<p>However, i am stuck on how to achieve this kind of substitution without using loops to iterate through all the possible combinations?</p>
| 0 | 2016-08-17T01:33:30Z | 38,986,904 | <p>You can use <a href="https://docs.python.org/2/library/re.html#re.sub" rel="nofollow"><code>re.sub</code></a>:</p>
<pre><code>import re
print re.sub('aha|oho|ehe', 'h', 'haha') # hh
print re.sub('aha|oho|ehe', 'h', 'hoho') # hh
print re.sub('aha|oho|ehe', 'h', 'hehe') # hh
print re.sub('aha|oho|ehe', 'h', 'hehehahoho') # hhhahh
</code></pre>
| 2 | 2016-08-17T01:43:00Z | [
"python",
"regex"
] |
Doing a "qrsh" inside python script | 38,987,091 | <p>I want to do a "qrsh" which is a grid command which returns a terminal from pool of machines, its behavior is very similar to "rsh", I am trying to run it from inside a python script and came up with following :</p>
<pre><code>os.execl("/remote/sge1/default/bin/lx-amd64/qrsh", "-P test")
</code></pre>
<p>Is it possible to achieve this ? My expectation of output is this :</p>
<pre><code>./script.py
(does qrsh and returns terminal) machine>
</code></pre>
| 0 | 2016-08-17T02:12:31Z | 38,988,822 | <p>The syntax of <code>os.execl</code> is slightly tricky. You are apparently looking for</p>
<pre><code> os.execl("/remote/sge1/default/bin/lx-amd64/qrsh", "qrsh", "-P", "test")
</code></pre>
<p>However, if you want to actually retain control of the subprocess, the <code>execl</code> is wrong - it will <em>replace</em> your Python process with the <code>qrsh</code> process. Overall, <a href="https://docs.python.org/2/library/subprocess.html#subprocess.call" rel="nofollow"><code>subprocess.call</code></a> is both easier to use and more versatile. (In fact, unless you are implementing a replacement for <code>subprocess.call</code> you should probably stay away from the low-level <code>os.exec*</code> primitives.)</p>
<pre><code>subprocess.call(['qrsh', '-P', 'test'])
# Look, your Python program is still executing after qrsh finishes!
</code></pre>
<p>(I am assuming you have <code>/remote/sge1/default/bin/lx-amd64</code> in your <code>PATH</code> already; if you don't, you need to supply an explicit path to <code>qrsh</code> just like in your <code>execl</code> call.)</p>
<p>A common beginner mistake is to expect Python (or some other unspecified part of the OS) to parse commands from strings. Both <code>execl</code> and <code>subprocess</code> require you to split the command into a list of strings. At the command line, your shell takes care of this (so "qrsh -P test" gets parsed into <code>['qrsh', '-P', 'test']</code> and then passed to <code>execvp</code> in this form).</p>
<p><sup>The <code>subprocess</code> module allows you to use <code>shell=True</code> to explicitly invoke a shell for this purpose, but you're better off ignoring that, at least until you have a better understanding of the topic; and once you do, you won't want to.</sup></p>
<p>On Unix, the value of "argument 0" is a curiosity which you probably don't need to worry about. For example, a login shell gets called as <code>execvp("/bin/sh", "-sh", ...)</code> whereas a non-login shell gets invoked as <code>execvp("/bin/sh", "sh", ....)</code>. Most places, argument zero will be identical to the path the actual binary.</p>
| 1 | 2016-08-17T05:38:36Z | [
"python",
"subprocess"
] |
Better Database Design for a Hierarchical Structure? | 38,987,124 | <p>I've created a bilingual dictionary app<sup>1</sup>, and it's currently very simple, but we're going to be starting to develop the entries more fully and I'm trying to figure out the best database structure for it. Previous dictionary projects I've worked on have used xml (since dictionary entries are largely hierarchical), but I need to do it using a database.<sup>2</sup></p>
<p>This is what a typical, medium-complexity entry would look like (simplified a bit):
<hr />
<b>dar</b><br>
<em>/dÄr/</em></p>
<ul>
<li>noun
<ol>
<li>house, dwelling, abode<br>
<em>ar-rÄjl dkhul ad-dÄr</em>, "The man entered the house."</li>
<li>home<br>
<em>rjaÆ·na lid-dÄr</em>, "We returned home."</li>
</ol></li>
<li>verb
<ol>
<li>to turn<br>
<em>dūr li-yamīn</em>, "Turn right."</li>
<li>to turn around/about</li>
</ol></li>
</ul>
<hr />
<p>As you can see, one word can have multiple parts of speech, so "part of speech" can't simply be an attribute of Entry, it has to be related to the senses. Each pos can have multiple senses (numbered), and of course each sense could have multiple near-synonymous translations. Senses may also have example sentences (possibly more than one), but not always. Thinking of how the entry parts relate to each other, I came up with the following structure, using five tables: </p>
<pre><code>Entry
-id
-headword
-pronunciation
-...
PartOfSpeech
-id
-entry (ForeignKey)
-pos
Sense
-id
-sense_number
-part_of_speech (ForeignKey)
-...
Translation
-id
-tr
-sense (ForeignKey)
-...
Example
-id
-ex
-ex_tr
-sense (ForeignKey)
-...
</code></pre>
<p>Or, in other words:</p>
<pre><code> _ Translation
Entry -- PartOfSpeech -- Sense --|
- Example
</code></pre>
<p>This seems simple and makes sense to me, but I'm wondering if it will be too complicated in the execution. For instance, to display a selection of entries, I would need to write several nested <code>for</code> loops (<code>for e in entries â for p in pos â for s in senses â for tr in translations</code>) â and all with reverse lookups! </p>
<p>And I don't think I could even edit a whole entry in the Django admin (unless it lets you somehow do an Inline of an Inline of an Inline). I'm going to build an editor interface anyway, but it's nice to be able to check things on the admin site when you want to.</p>
<p>Is there a better way to do this? I feel like there must be something clever that I'm missing.</p>
<p>Thanks,
Karen</p>
<p><hr/>
<sup>1</sup> If you're curious: <a href="http://tunisiandictionary.org" rel="nofollow">tunisiandictionary.org</a>. In its simple, current form it only has two tables (Entry, Sense), with the translations just comma-delineated in a single field. Which is bad.<br>
<sup>2</sup> For two reasons: 1) because it's a web app I've written with Python/Django, and 2) because I hate xml.</p>
| 2 | 2016-08-17T02:18:09Z | 39,005,920 | <p>Why not use the python <a href="https://docs.python.org/2/library/stdtypes.html#dictionary-view-objects" rel="nofollow">dictionary</a> data structure (or json/bson) along with <a href="https://www.mongodb.com" rel="nofollow">mongodb</a>? </p>
<p>In python, it is much more convenient than <code>xml</code>.</p>
<p>For example you can simply have a list of python dict objects to represent the entire dictionary. Each element can be a structured as follows:</p>
<pre><code>[{
"_id": "1",
"word": "étudier",
'definitions': {
[(
"v",
"to study",
"j'étudie français",
"I study french"
), ...
]
}
}, ...]
</code></pre>
<p>where definitions is a list of tuples (first element is part of speech, second element is the definition, third element is an example in the first language, forth element is the translation of that example).</p>
<p>You can then easily index it within <a href="https://www.mongodb.com/json-and-bson" rel="nofollow">mongodb</a> database.</p>
<p>This is a very simple structure and you don't need to deal with a over-complicated database with foreign keys. Using mongodb, retrieving definitions for a word is as easy as </p>
<p><code>record = db.collection.find({'word':'étudier')</code>.</p>
| -1 | 2016-08-17T20:41:20Z | [
"python",
"django",
"data-structures",
"nlp"
] |
Better Database Design for a Hierarchical Structure? | 38,987,124 | <p>I've created a bilingual dictionary app<sup>1</sup>, and it's currently very simple, but we're going to be starting to develop the entries more fully and I'm trying to figure out the best database structure for it. Previous dictionary projects I've worked on have used xml (since dictionary entries are largely hierarchical), but I need to do it using a database.<sup>2</sup></p>
<p>This is what a typical, medium-complexity entry would look like (simplified a bit):
<hr />
<b>dar</b><br>
<em>/dÄr/</em></p>
<ul>
<li>noun
<ol>
<li>house, dwelling, abode<br>
<em>ar-rÄjl dkhul ad-dÄr</em>, "The man entered the house."</li>
<li>home<br>
<em>rjaÆ·na lid-dÄr</em>, "We returned home."</li>
</ol></li>
<li>verb
<ol>
<li>to turn<br>
<em>dūr li-yamīn</em>, "Turn right."</li>
<li>to turn around/about</li>
</ol></li>
</ul>
<hr />
<p>As you can see, one word can have multiple parts of speech, so "part of speech" can't simply be an attribute of Entry, it has to be related to the senses. Each pos can have multiple senses (numbered), and of course each sense could have multiple near-synonymous translations. Senses may also have example sentences (possibly more than one), but not always. Thinking of how the entry parts relate to each other, I came up with the following structure, using five tables: </p>
<pre><code>Entry
-id
-headword
-pronunciation
-...
PartOfSpeech
-id
-entry (ForeignKey)
-pos
Sense
-id
-sense_number
-part_of_speech (ForeignKey)
-...
Translation
-id
-tr
-sense (ForeignKey)
-...
Example
-id
-ex
-ex_tr
-sense (ForeignKey)
-...
</code></pre>
<p>Or, in other words:</p>
<pre><code> _ Translation
Entry -- PartOfSpeech -- Sense --|
- Example
</code></pre>
<p>This seems simple and makes sense to me, but I'm wondering if it will be too complicated in the execution. For instance, to display a selection of entries, I would need to write several nested <code>for</code> loops (<code>for e in entries â for p in pos â for s in senses â for tr in translations</code>) â and all with reverse lookups! </p>
<p>And I don't think I could even edit a whole entry in the Django admin (unless it lets you somehow do an Inline of an Inline of an Inline). I'm going to build an editor interface anyway, but it's nice to be able to check things on the admin site when you want to.</p>
<p>Is there a better way to do this? I feel like there must be something clever that I'm missing.</p>
<p>Thanks,
Karen</p>
<p><hr/>
<sup>1</sup> If you're curious: <a href="http://tunisiandictionary.org" rel="nofollow">tunisiandictionary.org</a>. In its simple, current form it only has two tables (Entry, Sense), with the translations just comma-delineated in a single field. Which is bad.<br>
<sup>2</sup> For two reasons: 1) because it's a web app I've written with Python/Django, and 2) because I hate xml.</p>
| 2 | 2016-08-17T02:18:09Z | 39,821,465 | <p>You can emulate saving dictionaries in sql databases as well. Someone wrote this awesome helper already:</p>
<p><a href="https://djangosnippets.org/snippets/2451/" rel="nofollow">Django Dictionary Model</a></p>
<p>I use it in my project as well.</p>
| 0 | 2016-10-02T20:37:46Z | [
"python",
"django",
"data-structures",
"nlp"
] |
How to extract the grammar productions rules given bracketed parses? | 38,987,138 | <p>I have a sample sentence. "Open the door." that I parsed a sentence to get the bracketed parse output as below.</p>
<blockquote>
<p>(S (VP (VB open) (NP (DT the) (NN door))) (. .))</p>
</blockquote>
<p>I need to extract the CFG grammar rules that produce the parsed output.
I can manually write them out as such:</p>
<pre><code>grammar = CFG.fromstring("""
S -> VP NP
NP -> Det N
VP -> V
Det ->'the '
N -> 'door'
V -> 'Open'
""")
</code></pre>
<p>But it's time consuming, how do I produce the grammar rules given the bracketed parsed automatically?</p>
| 2 | 2016-08-17T02:20:09Z | 39,049,856 | <p>You can use <strong>Tree.productions()</strong> method to get CFG rules from Tree.</p>
<p><strong>Example:</strong></p>
<pre><code>from nltk import Tree
t = Tree.fromstring("(S (VP (VB open) (NP (DT the) (NN door))) (. .))")
print t.productions()
</code></pre>
<p><strong>Output:</strong></p>
<pre><code>[S -> VP ., VP -> VB NP, VB -> 'open', NP -> DT NN, DT -> 'the',
NN -> 'door', . -> '.']
</code></pre>
<p>For more information check - <a href="http://www.nltk.org/api/nltk.html#nltk.tree.Tree.productions" rel="nofollow">NLTK Tree Productions</a></p>
| 2 | 2016-08-20T02:20:01Z | [
"python",
"parsing",
"nlp",
"nltk",
"context-free-grammar"
] |
How to extract the grammar productions rules given bracketed parses? | 38,987,138 | <p>I have a sample sentence. "Open the door." that I parsed a sentence to get the bracketed parse output as below.</p>
<blockquote>
<p>(S (VP (VB open) (NP (DT the) (NN door))) (. .))</p>
</blockquote>
<p>I need to extract the CFG grammar rules that produce the parsed output.
I can manually write them out as such:</p>
<pre><code>grammar = CFG.fromstring("""
S -> VP NP
NP -> Det N
VP -> V
Det ->'the '
N -> 'door'
V -> 'Open'
""")
</code></pre>
<p>But it's time consuming, how do I produce the grammar rules given the bracketed parsed automatically?</p>
| 2 | 2016-08-17T02:20:09Z | 39,051,849 | <p>If you're looking to create the rules from a bracketed parsed, you can use <a href="http://www.nltk.org/api/nltk.html#nltk.tree.Tree.productions" rel="nofollow"><code>Tree.productions()</code></a></p>
<pre><code>>>> from nltk import Tree
>>> t = Tree.fromstring("(S (NP (D the) (N dog)) (VP (V chased) (NP (D the) (N cat))))")
>>> t.productions()
[S -> NP VP, NP -> D N, D -> 'the', N -> 'dog', VP -> V NP, V -> 'chased', NP -> D N, D -> 'the', N -> 'cat']
</code></pre>
<p>The <code>Tree.productions()</code> will return a list of <a href="https://github.com/nltk/nltk/blob/develop/nltk/grammar.py#L236" rel="nofollow"><code>nltk.grammar.Productions</code></a> objects:</p>
<pre><code>>>> type(t.productions()[0])
<class 'nltk.grammar.Production'>
</code></pre>
<p>To get the rules into a string form, use the <code>Production.unicode_repr</code>:</p>
<pre><code>>>> t.productions()[0].unicode_repr()
u'S -> NP VP'
</code></pre>
<p>To the get the string representation of the grammar learnt from bracketed parse:</p>
<pre><code>>>> from nltk import Tree
>>> t = Tree.fromstring("(S (NP (D the) (N dog)) (VP (V chased) (NP (D the) (N cat))))")
>>> grammar_from_parse = "\n".join([rule.unicode_repr() for rule in t.productions()])
>>> print grammar_from_parse
S -> NP VP
NP -> D N
D -> 'the'
N -> 'dog'
VP -> V NP
V -> 'chased'
NP -> D N
D -> 'the'
N -> 'cat'
</code></pre>
| 2 | 2016-08-20T07:55:31Z | [
"python",
"parsing",
"nlp",
"nltk",
"context-free-grammar"
] |
This works BUT WHY? | 38,987,146 | <p>I'm learing Python on codecademy and came across this solution for a function that's meant to remove duplicates from a list of numbers:</p>
<pre><code>x = [1, 1, 2, 2]
def remove_duplicates(x):
p = []
for i in x:
if i != i:
p.append(i)
return i
</code></pre>
<p>I ran this in pycharm with some print statements and just got an empty list. I'm only curious because when I do this in my head, it makes no sense, but codecademy accepts this as an answer. Is it just a fluke? Or is this on a level I don't understand yet?</p>
| 4 | 2016-08-17T02:21:32Z | 38,987,201 | <p>You are correct: it doesn't make any sense. First, it creates a list called <code>p</code> that gets each item that is not equal to itself. The only object that I know of that is not equal to itself is NaN, but you don't have any of those, so <code>p</code> is just an empty list. Defining <code>p</code> is useless, however, because it isn't even returned. What is returned is <code>i</code>, which is assigned to each item in the last, so it is the last item in the list by the end of the function. In short, that function is equivalent to this:</p>
<pre><code>def remove_duplicates(x):
return x[-1]
</code></pre>
<p>I haven't heard what the function is supposed to return, but perhaps it is supposed to return the number of non-duplicate items. If it is, it "works" just because the last item in the list happens to be the number of non-duplicate items.</p>
| 4 | 2016-08-17T02:29:01Z | [
"python"
] |
This works BUT WHY? | 38,987,146 | <p>I'm learing Python on codecademy and came across this solution for a function that's meant to remove duplicates from a list of numbers:</p>
<pre><code>x = [1, 1, 2, 2]
def remove_duplicates(x):
p = []
for i in x:
if i != i:
p.append(i)
return i
</code></pre>
<p>I ran this in pycharm with some print statements and just got an empty list. I'm only curious because when I do this in my head, it makes no sense, but codecademy accepts this as an answer. Is it just a fluke? Or is this on a level I don't understand yet?</p>
| 4 | 2016-08-17T02:21:32Z | 38,987,221 | <p>Take a look to this snippet to see the pythonic way to remove duplicated (good_result) and also to understand why your code doesn't make any sense:</p>
<pre><code>x = [1, 1, 2, 2]
def remove_duplicates(x):
p = []
for i in x:
if i != i:
p.append(i)
return i
good_result = list(set(x))
print good_result
print remove_duplicates(x)
</code></pre>
<p>As you can see, your function is not returning the filtered list without duplicate values, it's just returning the last element of the list (index=-1). So codeacademy shouldn't accept that snippet as a valid answer to the question <code>how to remove duplicateds from a list</code> for sure.</p>
<p>Now, if we assume what codeacademy was really asking is for <code>the number of unique values from a list</code>, then is a casuality your broken code gives the right answer, which is the same as <code>len(good_result)</code>. It worked just by luck just to say, it doesn't mean your code is correct :)</p>
| 2 | 2016-08-17T02:31:49Z | [
"python"
] |
This works BUT WHY? | 38,987,146 | <p>I'm learing Python on codecademy and came across this solution for a function that's meant to remove duplicates from a list of numbers:</p>
<pre><code>x = [1, 1, 2, 2]
def remove_duplicates(x):
p = []
for i in x:
if i != i:
p.append(i)
return i
</code></pre>
<p>I ran this in pycharm with some print statements and just got an empty list. I'm only curious because when I do this in my head, it makes no sense, but codecademy accepts this as an answer. Is it just a fluke? Or is this on a level I don't understand yet?</p>
| 4 | 2016-08-17T02:21:32Z | 38,987,448 | <p>your code just returns the last element of the number, that is same as </p>
<pre><code>return x[-1]
</code></pre>
<p>It doesn't return a list.
I think you need to check the question that they may be asking like, </p>
<p>a)function to return one of the duplicating element in a list. </p>
<p>b)function to return the no of duplicating elements in a list.</p>
<p>for the above two questions your answer is 2, by luck the answer is correct. </p>
| 0 | 2016-08-17T03:03:34Z | [
"python"
] |
How to get the number of columns in a postgresql table and store it to variable in python? | 38,987,151 | <p>What command would I use to get the number of columns in a postgresql table in python and store it to a variable called rowCount?</p>
| -1 | 2016-08-17T02:22:01Z | 38,987,541 | <p>I don't know about Python, but you can get the number of columns in a table with the following:</p>
<pre><code>select count (*) as column_count
from information_schema.columns
where
table_schema = :YOUR_SCHEMA and
table_name = :YOUR_TABLE
</code></pre>
<p>Insert whatever wrapper code you normally use for Python around this (with bind variable assignments, of course), and I think you will have your answer.</p>
| 0 | 2016-08-17T03:16:00Z | [
"python",
"postgresql"
] |
"Element is not clickable at point (x,y)". Invisible element covers the button | 38,987,154 | <p>Iâm stuck trying to get Selenium with Chrome Webdriver to click a buttom, but there is an element <code><div class="modal-overlay" style="display: block;"></div></code> that covers the entire page and is invisble, that is blocking my clicks. How can I work around this?</p>
<p>I tried using this:</p>
<pre><code>element = driver.find_element_by_xpath("//input[@type='submit']")
driver.execute_script("arguments[0].click();", element)
</code></pre>
<p>but it didnât work. What can I do in this situation?
EDIT:
I used luke_aus answer and got this from the page: (third last image) </p>
<p><a href="http://imgur.com/a/MlmpK" rel="nofollow">http://imgur.com/a/MlmpK</a></p>
| 1 | 2016-08-17T02:22:41Z | 38,987,275 | <p>Just use <code>execute_script</code> to submit the form</p>
<pre><code>driver.execute_script("document.getElementById('myForm').submit()");
</code></pre>
| 1 | 2016-08-17T02:39:54Z | [
"javascript",
"python",
"selenium"
] |
"Element is not clickable at point (x,y)". Invisible element covers the button | 38,987,154 | <p>Iâm stuck trying to get Selenium with Chrome Webdriver to click a buttom, but there is an element <code><div class="modal-overlay" style="display: block;"></div></code> that covers the entire page and is invisble, that is blocking my clicks. How can I work around this?</p>
<p>I tried using this:</p>
<pre><code>element = driver.find_element_by_xpath("//input[@type='submit']")
driver.execute_script("arguments[0].click();", element)
</code></pre>
<p>but it didnât work. What can I do in this situation?
EDIT:
I used luke_aus answer and got this from the page: (third last image) </p>
<p><a href="http://imgur.com/a/MlmpK" rel="nofollow">http://imgur.com/a/MlmpK</a></p>
| 1 | 2016-08-17T02:22:41Z | 38,987,927 | <p>In your case you need to make overlay element invisible forcefully before going to click on submit button as below :-</p>
<pre><code>#first make overlay element invisible
overlay = driver.find_element_by_css_selector("div.modal-overlay")
driver.execute_script("arguments[0].style.display = 'none'", overlay)
#now find submit button and click
driver.find_element_by_id("DeleteSurveyOââK").click()
</code></pre>
<p><strong>Edited1</strong> :- If still it throws exception that submit button is invisible, you should try using <code>WebDriverWait</code> to wait until submit button visible after overlay element invisible as below :</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
#first make overlay element invisible
overlay = driver.find_element_by_css_selector("div.modal-overlay")
driver.execute_script("arguments[0].style.display = 'none'", overlay)
#now find submit button and click
button = WebDriverWait(driver, 10).until(
EC.visibility_of_element_located((By.ID, "DeleteSurveyOââK")))
button.click()
</code></pre>
<p><strong>Edited2</strong> :- If unfortunately submit button is not getting visible try to submit form instead of clicking submit button as below :-</p>
<pre><code>#first make overlay element invisible
overlay = driver.find_element_by_css_selector("div.modal-overlay")
driver.execute_script("arguments[0].style.display = 'none'", overlay)
#now submit the form
driver.find_elementââ_by_id("ModelSurveyFoâârm").submit()
</code></pre>
| 1 | 2016-08-17T04:03:06Z | [
"javascript",
"python",
"selenium"
] |
AWS lambda function ConnectionError when configured with VPC | 38,987,195 | <p><em>I have an AWS lambda function to trigger daily importer jobs</em></p>
<p>I am using a "A starter AWS Lambda function." for this and the lambda_handler is quite simple.
This is a pseudo code of what I am doing:</p>
<pre><code>try:
cron_job = CloudCron()
status = redis_get_importer_status(db_key, key)
if status != 'running':
cron_job.login()
redis_set_importer_status(db_key, key, 'running')
cron_job.start_importer()
except Exception:
exc_traceback = traceback.print_exc()
print(exc_traceback)
</code></pre>
<p>This function is triggered by a CloudWatch Event every 15 minutes.</p>
<p>The lambda function failed to run the lambda_handler and complained about not having an execution policy for the VPC. To resolve this issue, I attached AWSLambdaVPCAccessExecutionRole Policy for this role. While this ran my lamda_handler, there were other issues. The python requests module threw a ConnectionError when trying to login to the site.
I increased the timeout to 5 minutes and memory to 1GB and still seeing this issue.</p>
<p><strong>ConnectionError: HTTPSConnectionPool(host='test.site.com.au', port=443): Max retries exceeded with url: /auth/login (Caused by NewConnectionError(': Failed to establish a new connection: [Errno 110] Connection timed out',))</strong></p>
<p>I ran the same lambda_handler within my VPC and seems to be working seamlessly. </p>
<p><strong>I finally removed the redis set status and get status in my lambda function and the VPC configuration in the lamba and ran the lamda_handler again and this seems to work without any issues.</strong></p>
<p>I need the VPC configuration to set and get keys from the redis server. </p>
<p>Any help is appreciated!</p>
<p>Cheers!</p>
| 0 | 2016-08-17T02:27:55Z | 38,997,446 | <p>Once you place the Lambda function inside your VPC it can only access resources inside the VPC. It can't connect to <code>test.site.com.au</code> because that resolves to a public IP address outside your VPC. You have a few options to get around this issue:</p>
<ul>
<li>Add a NAT Gateway to your VPC. This will provide Internet access to your Lambda function.</li>
<li>If the site you are trying to access is running on a server inside your VPC, then use the private IP address instead of the DNS name. Alternatively, setup a Route53 private hosted zone in your VPC that resolves that DNS name to the private IP address.</li>
</ul>
| 0 | 2016-08-17T13:02:51Z | [
"python",
"aws-lambda",
"amazon-vpc"
] |
Alternative to using deepcopy for nested dictionaries? | 38,987,212 | <p>I have a nested dict like this, but much larger:</p>
<pre><code>d = {'a': {'b': 'c'}, 'd': {'e': {'f':2}}}
</code></pre>
<p>I've written a function which takes a dictionary and a path of keys as input and returns the value associated with that path.</p>
<pre><code>>>> p = 'd/e'
>>> get_from_path(d, p)
>>> {'f':2}
</code></pre>
<p>Once I get the nested dictionary, I will need to modify it, however, d can not be modified. Do I need to use deepcopy, or is there a more efficient solution that doesn't require constantly making copies of the dictionary? </p>
| 1 | 2016-08-17T02:30:28Z | 38,987,280 | <p>Depending on your use case, one approach to avoid making changes to an existing dictionary is to wrap it in a <a href="https://docs.python.org/3/library/collections.html#chainmap-objects" rel="nofollow"><code>collections.ChainMap</code></a>:</p>
<pre><code>>>> import collections
>>> # here's a dictionary we want to avoid dirty'ing
>>> d = {i: i for in in range(10)}
>>> # wrap into a chain map and make changes there
>>> c = collections.ChainMap({}, d)
</code></pre>
<p>Now we can add new keys and values to <code>c</code> without corresponding changes happening in <code>d</code></p>
<pre><code>>>> c[0] = -100
>>> print(c[0], d[0])
-100 0
</code></pre>
<p>Whether this solution is appropriate depends on your use case ... in particular the ChainMap will:</p>
<ul>
<li><p>not behave like a regular map when it comes to some things, like deleting keys:</p>
<pre><code>>>> del c[0]
>>> print(c[0])
0
</code></pre></li>
<li><p>still allow you to modify values in place</p>
<pre><code>>>> d = dict(a=[])
>>> collections.ChainMap({}, d)["a"].append(1)
</code></pre>
<p>will alter the list in <code>d</code></p></li>
</ul>
<p>However, if you are merely wishing to take your embedded dictionary and pop some new keys and values on it, then <code>ChainMap</code> may be appropriate.</p>
| 1 | 2016-08-17T02:40:50Z | [
"python",
"dictionary"
] |
how to scrape facebook event and render them in web site | 38,987,260 | <p>I would like to list the facebook events in a particular region on a web site.
What's your advice on how to make it with python or other language.</p>
| -3 | 2016-08-17T02:37:29Z | 38,987,625 | <p><a href="https://www.crummy.com/software/BeautifulSoup/" rel="nofollow">Beautiful Soup</a> is the standard screen scraping utility for Python. You could also look into using the Python <code>requests</code> library together with the <a href="https://developers.facebook.com/docs/graph-api" rel="nofollow">Facebook API</a> to get your information directly.</p>
| 0 | 2016-08-17T03:26:42Z | [
"python",
"facebook",
"events",
"screen-scraping"
] |
Python requests - how to set default retries object for created sessions? | 38,987,263 | <p>I'd like to force all requests to retry on some 5xx HTTP status codes. What I would do is:</p>
<pre><code>retry = requests.packages.urllib3.util.retry.Retry(
total=20,
backoff_factor=0.1,
status_forcelist=[500, 502, 503, 504],
method_whitelist=frozenset(['GET', 'POST']))
for adapter in session.adapters.values():
adapter.max_retries = retry
</code></pre>
<p>But I need to do it for existing code with a lot of different sessions in different modules/packages. Some of them use <code>s = Session(); s.get()</code>, others use <code>requests.get()</code>. So, I'd like to force them all to use this <code>Retry</code> instance.</p>
<p>Is it possible to do it on <code>requests</code> package level (by initializing, setting up, simple monkey patching <code>requests</code> package)? </p>
<pre><code>import requests
# Initialize/setup/patch requests package.
???
# Following should retry on server errors:
requests.Session().get('http://httpstat.us/500')
requests.post('http://httpstat.us/500', data={})
</code></pre>
<p>I tried to set <code>requests.adapters.DEFAULT_RETRIES</code> to <code>retry</code> object. But this is not how it works...</p>
| 1 | 2016-08-17T02:38:15Z | 39,050,757 | <pre><code>import requests
import logging
logging.basicConfig(level='DEBUG')
def forceretry(max_retries):
""" Decorator for `requests.adapters.HTTPAdapter.__init__`. """
def decorate(func):
def wrapper(self, *args, **kwargs):
func(self, *args, **kwargs)
self.max_retries = max_retries
return wrapper
return decorate
max_retries = requests.packages.urllib3.util.retry.Retry(
total=20,
backoff_factor=0.1,
status_forcelist=[500, 502, 503, 504],
method_whitelist=frozenset(['GET', 'POST']))
func = requests.adapters.HTTPAdapter.__init__
requests.adapters.HTTPAdapter.__init__ = forceretry(max_retries)(func)
requests.post('http://httpstat.us/500', data={})
</code></pre>
<p>It forces <code>Retry</code> object for every Session (doesn't set default one). But it worked for me.</p>
| 0 | 2016-08-20T05:24:44Z | [
"python",
"python-requests"
] |
Python requests - how to set default retries object for created sessions? | 38,987,263 | <p>I'd like to force all requests to retry on some 5xx HTTP status codes. What I would do is:</p>
<pre><code>retry = requests.packages.urllib3.util.retry.Retry(
total=20,
backoff_factor=0.1,
status_forcelist=[500, 502, 503, 504],
method_whitelist=frozenset(['GET', 'POST']))
for adapter in session.adapters.values():
adapter.max_retries = retry
</code></pre>
<p>But I need to do it for existing code with a lot of different sessions in different modules/packages. Some of them use <code>s = Session(); s.get()</code>, others use <code>requests.get()</code>. So, I'd like to force them all to use this <code>Retry</code> instance.</p>
<p>Is it possible to do it on <code>requests</code> package level (by initializing, setting up, simple monkey patching <code>requests</code> package)? </p>
<pre><code>import requests
# Initialize/setup/patch requests package.
???
# Following should retry on server errors:
requests.Session().get('http://httpstat.us/500')
requests.post('http://httpstat.us/500', data={})
</code></pre>
<p>I tried to set <code>requests.adapters.DEFAULT_RETRIES</code> to <code>retry</code> object. But this is not how it works...</p>
| 1 | 2016-08-17T02:38:15Z | 39,052,802 | <p>I would use <a href="https://en.wikipedia.org/wiki/Exponential_backoff" rel="nofollow">exponential backoff</a> algorithm.</p>
<p>Here is a nice package that provides a decorator for you: <a href="https://pypi.python.org/pypi/backoff/1.3.1" rel="nofollow">backoff</a>. Can be used with <code>requests</code>.</p>
<p>Code sample from package documentation:</p>
<pre><code>@backoff.on_exception(backoff.expo,
requests.exceptions.RequestException,
max_tries=8)
def get_url(url):
return requests.get(url)
</code></pre>
| 0 | 2016-08-20T09:59:12Z | [
"python",
"python-requests"
] |
IDLE's subprocess didn't make connection. Either IDLE can't start a subprocess or personal firewall software is blocking the connection | 38,987,289 | <p>I started programing a game on a Mac. Then, I brought the same EXACT code to another Mac. </p>
<p>I got many, many different errors with Pygame saying it wasn't installed, EVEN THOUGH IT WAS! </p>
<p>Anyway, I fixed those errors, then I went to go run the module and the window appeared then it crashed and gave me this message: </p>
<blockquote>
<p>IDLE's subprocess didn't make connection. Either IDLE can't start a
subprocess or personal firewall software is blocking the connection</p>
</blockquote>
<p>I never got this message before. However, it continues to crash. I have killed idle using the Activity Monitor. There weren't any files in the directory. I have deleted all of the Python files that I have created.</p>
<p>Trashed every <code>.pyc</code> file. The Mac I am using is on El Captain; Python is at 2.7.12. Like I said, the code has not changed AT ALL from the first computer.</p>
<p>However, games that are pre-installed with IDLE work perfectly. I have moved the program to the same folders as the games. I copied the content from my program to another file, still nothing.</p>
<p>All help is appreciated, thank you :)</p>
| 0 | 2016-08-17T02:41:31Z | 39,058,369 | <p>The most likely reason that your getting this error, is because you're
not the administrator of the computer and you're trying to run a script from your local disk. There are a few things that you could do to solve this.</p>
<h2>1. Move the .py file:</h2>
<p>Before jumping to the method below, simply try moving your python file to a different location on your drive. Then try running the script with the python IDLE. If Your script still won't run, or you must have the script on your local drive, see the second method below</p>
<h2>2. Run the script from the command prompt\terminal:</h2>
<p>To run the script from your command prompt\terminal, first find the path to your python executable. In my case mine is:</p>
<blockquote>
<p>C:\Users[insert user name here]\AppData\Local\Programs\Python\Python35\python.exe</p>
</blockquote>
<p>Copy and paste the entire path this into your command prompt\terminal window. Next, find the path to your python file. For an example, the path to my script is:</p>
<blockquote>
<p>C:\test.py</p>
</blockquote>
<p><strong>It is important to note that your path to your python executable cannot contain spaces.</strong></p>
<p>Next copy and paste the path tot your python file into your command prompt\terminal window. When finished, the command your made should like something like this:</p>
<blockquote>
<p>C:\Users[insert user name here]\AppData\Local\Programs\Python\Python35\python.exe C:\test.py</p>
</blockquote>
<p>Next press enter, and watch your python script run.</p>
| 0 | 2016-08-20T20:17:58Z | [
"python",
"osx",
"pygame",
"osx-elcapitan"
] |
PIP install for scipy fails spectacularly on Ubuntu 14.04 | 38,987,322 | <p>I'm trying to install the scipy package on Ubuntu 14.04.4 LTS, only because gensim needs it, using pip (before anyone chimes in on switching to any of the twelve other python package managers: No). I have installed all the prereq packages:</p>
<ul>
<li>python 2.7</li>
<li>libblas3</li>
<li>liblapack3</li>
<li>gcc</li>
<li>gfortran</li>
<li>python-dev</li>
<li>libc6</li>
<li>libatlas-base</li>
<li>libatlas-dev</li>
<li>python-build-essential</li>
</ul>
<p>When I run pip install gensim, I get about ten full minutes of compiler warnings followed by several <code>virtual memory exhausted: Cannot allocate memory</code> errors. One of the compiler warnings that keeps coming up is:</p>
<pre><code>/home/ubuntu/www/cool-project/venv/local/lib/python2.7/site-packages/numpy/core/include/numpy/npy_1_7_deprecated_api.h:15:2: warning: #warning "Using deprecated NumPy API, disable it by " "#defining NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION" [-Wcpp]
#warning "Using deprecated NumPy API, disable it by " \
^
</code></pre>
<p>This is despite already having numpy installed:</p>
<pre><code>(venv)ubuntu@box:~/www/cool-project$ pip install numpy --upgrade
Requirement already up-to-date: numpy in ./venv/lib/python2.7/site-packages
Cleaning up...
</code></pre>
<p>Lastly, the final error message:</p>
<pre><code>error: Command "c++ -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -fPIC -D__STDC_FORMAT_MACROS=1 -Iscipy/sparse/sparsetools -I/home/ubuntu/www/cool-project/venv/local/lib/python2.7/site-packages/numpy/core/include -I/usr/include/python2.7 -c scipy/sparse/sparsetools/bsr.cxx -o build/temp.linux-x86_64-2.7/scipy/sparse/sparsetools/bsr.o" failed with exit status 1
</code></pre>
<p>Any ideas why this is happening?</p>
| 1 | 2016-08-17T02:46:11Z | 39,024,932 | <p>It turns out that what was needed was for pip itself to be upgraded to the latest version: <code>pip install --upgrade pip</code>. After that was done, scipy installed without a problem.</p>
| 0 | 2016-08-18T18:15:39Z | [
"python",
"python-2.7",
"ubuntu",
"numpy",
"scipy"
] |
Format attribute of Java and Python in C | 38,987,327 | <p>In Python, we could use the format attribute this way: </p>
<pre><code>"Today is {}/{}/{}".format(self.day, self.month, self.year)
</code></pre>
<p>In Java, we could do the same: </p>
<pre><code>MessageFormat.format("Today is {0}/{1}/{2}", this.day, this.month, this.year);
</code></pre>
<p>Is there an equivalent format attribute in C? Apart from the %d and %s things which are also present in Python along with the format attribute. The later has an advantage as it doesnt require specifying the type of the variable whether a number or a string or whatnot. </p>
| 1 | 2016-08-17T02:46:52Z | 38,987,383 | <p>It can't be done in C. Not cleanly, at least.</p>
<p>Both Java and Python have <em>strong typing</em>. This means that objects have an intrinsic type that cannot change, and this type is known during the execution of the program. You can transform any object to a string appropriately, because their types are known and they implement the <code>toString()</code>/ <code>__str__()</code> method.</p>
<p>C, in contrast, has <em>weak typing</em>. Types in C are more of an <em>interpretation</em> of the data at a memory address. You can cast anything to anything else. The <code>sprintf()</code> function has no way of knowing what's what.</p>
<p>There are ways of building strings with a generic syntax in C++, if you're interested.</p>
| 2 | 2016-08-17T02:56:19Z | [
"java",
"python",
"c"
] |
Is it possible to make a list comprehension from the following function? | 38,987,378 | <p>There is a function that returns a sum of integers from list x that are greater than integer y. If there is none of the numbers greater than y the function returns 0.</p>
<pre><code>def sum_greater(x, y):
result = 0
for i in range(len(x)):
if x[i] > y:
result = result + x[i]
return result
</code></pre>
<p>My question: is it possible (and if it is than how) to make a list comprehension from this function? </p>
| 0 | 2016-08-17T02:56:08Z | 38,987,398 | <p>You can use the <code>sum()</code> function with a generator expression:</p>
<pre><code>sum(i for i in x if i > y)
</code></pre>
| 3 | 2016-08-17T02:58:09Z | [
"python",
"list-comprehension"
] |
Is it possible to make a list comprehension from the following function? | 38,987,378 | <p>There is a function that returns a sum of integers from list x that are greater than integer y. If there is none of the numbers greater than y the function returns 0.</p>
<pre><code>def sum_greater(x, y):
result = 0
for i in range(len(x)):
if x[i] > y:
result = result + x[i]
return result
</code></pre>
<p>My question: is it possible (and if it is than how) to make a list comprehension from this function? </p>
| 0 | 2016-08-17T02:56:08Z | 38,987,405 | <p>Since 0 is the natural result of the sum of nothing, that doesn't need any special handling. You can send a <a href="https://www.python.org/dev/peps/pep-0289/" rel="nofollow">generator expression</a> to the built-in <code>sum</code>:</p>
<pre><code>def sum_greater(x, y):
return sum(i for i in x if i>y)
</code></pre>
| 3 | 2016-08-17T02:59:16Z | [
"python",
"list-comprehension"
] |
if statement inside an if statement | 38,987,390 | <p>this is kinda my homework and I'm stuck on making the code becoming a follow up question, like this code here, I've tried inserting an if statement after that but it gave me an unexpected incent error.</p>
<p>Here are my codes so far:</p>
<pre><code>Choice = input("Hello! Do you want to buy or sell snakes? Please enter (b) or (s) :")
if Choice == "b":
buySnake = input ("What snake do you want to buy? We are selling python, kingsnake, rattlesnake, deathadder, cobra, mamba, viper and gartersnake. Please choose one : ")
if buySnake == "python":
return (to be added)
elif Choice == "s":
sellFsnakes(snakeList,name,amount)
else:
print("Please try again.")
buyWsnakes(snakeList,name,amount)
</code></pre>
| 1 | 2016-08-17T02:57:02Z | 38,987,403 | <p>You have an extra indent. Just remove the extra level of indentation:</p>
<pre><code>Choice = input("Hello! Do you want to buy or sell snakes? Please enter (b) or (s) :")
if Choice == "b":
buySnake = input ("What snake do you want to buy? We are selling python, kingsnake, rattlesnake, deathadder, cobra, mamba, viper and gartersnake. Please choose one : ")
if buySnake == "python":
return (to be added)
elif Choice == "s":
sellFsnakes(snakeList,name,amount)
else:
print("Please try again.")
buyWsnakes(snakeList,name,amount)
</code></pre>
| 4 | 2016-08-17T02:58:57Z | [
"python"
] |
if statement inside an if statement | 38,987,390 | <p>this is kinda my homework and I'm stuck on making the code becoming a follow up question, like this code here, I've tried inserting an if statement after that but it gave me an unexpected incent error.</p>
<p>Here are my codes so far:</p>
<pre><code>Choice = input("Hello! Do you want to buy or sell snakes? Please enter (b) or (s) :")
if Choice == "b":
buySnake = input ("What snake do you want to buy? We are selling python, kingsnake, rattlesnake, deathadder, cobra, mamba, viper and gartersnake. Please choose one : ")
if buySnake == "python":
return (to be added)
elif Choice == "s":
sellFsnakes(snakeList,name,amount)
else:
print("Please try again.")
buyWsnakes(snakeList,name,amount)
</code></pre>
| 1 | 2016-08-17T02:57:02Z | 38,987,429 | <p>Indentation is the way to create code blocks in Python. Your error says exactly what you did wrong.</p>
<pre><code>if condition:
# executes if condition is met
if internalCondition:
# executes if both condition and internalCondition is met
elif otherCondition:
# executes if first statement didn't and otherCondition is met
else:
# executes if nothing else executed
</code></pre>
<p>You indented <code>if internalCondition:</code> with excess whitespaces.</p>
| 0 | 2016-08-17T03:01:15Z | [
"python"
] |
Kmeans is not producing an elbow | 38,987,400 | <p>I have a data frame of about 300,000 unique product names and I am trying to use k means to cluster similar names together. I used sklearn's tfidfvectorizer to vectorize the names and convert to a tf-idf matrix.</p>
<p>Next I ran k means on the tf-idf matrix with number of clusters ranging from 5 to 25. Then I plotted the inertia for each # of clusters. </p>
<p>Based on the plot am I approaching the problem wrong? What are some takeaways from this if there is no distinct elbow?</p>
<p><a href="http://i.stack.imgur.com/xyQOy.png" rel="nofollow"><img src="http://i.stack.imgur.com/xyQOy.png" alt="enter image description here"></a></p>
| 0 | 2016-08-17T02:58:17Z | 39,806,928 | <p>Most likely because k-means w=th TF-IDF doesn't work well on such short text such as product names.</p>
<p>Not seeing an elbow is an indication that the results aren't good.</p>
| 0 | 2016-10-01T13:02:14Z | [
"python",
"scikit-learn",
"cluster-computing",
"k-means"
] |
Why can't use "r+" mode to create a new file in Python with open() | 38,987,408 | <p>In the docs of open() build in function of python,the meaning of "+" is as follows:</p>
<blockquote>
<p>open a disk file for updating(reading and writing)</p>
</blockquote>
<p>but when i use the open() build-in to create a new file with python 3.5 in win7,i got the "FileNotFoundError".</p>
<pre><code>tmp_fileï¼open(str(temp_path),'r+')
</code></pre>
<p>as the explanation of open() in doc,should't it create a new empty file if the file specifiled is not existï¼when use the "r+" mode?</p>
| 0 | 2016-08-17T02:59:23Z | 38,987,518 | <p><code>r+</code> mode will open an <strong>existing</strong> file for write, but will not create the file if it doesn't exists.</p>
<p>You should open the file with <code>w</code> if you want to create a new file.</p>
| 0 | 2016-08-17T03:12:35Z | [
"python",
"python-3.x"
] |
Why can't use "r+" mode to create a new file in Python with open() | 38,987,408 | <p>In the docs of open() build in function of python,the meaning of "+" is as follows:</p>
<blockquote>
<p>open a disk file for updating(reading and writing)</p>
</blockquote>
<p>but when i use the open() build-in to create a new file with python 3.5 in win7,i got the "FileNotFoundError".</p>
<pre><code>tmp_fileï¼open(str(temp_path),'r+')
</code></pre>
<p>as the explanation of open() in doc,should't it create a new empty file if the file specifiled is not existï¼when use the "r+" mode?</p>
| 0 | 2016-08-17T02:59:23Z | 38,987,526 | <p>You should use :<br />
file = open(str(temp_path), 'w+')</p>
| 0 | 2016-08-17T03:13:35Z | [
"python",
"python-3.x"
] |
urlopen for loop with beautifulsoup | 38,987,427 | <p>New user here. I'm <em>starting</em> to get the hang of Python syntax but keep getting thrown off by for loops. I understand each scenario I've reach on SO thus far (and my previous examples), but can't seem to come up with one for my current scenario.</p>
<p>I am playing around with BeautifulSoup to extract features from app stores as an exercise.</p>
<p>I created a list of both GooglePlay and iTunes urls to play around with.</p>
<pre><code> list = {"https://play.google.com/store/apps/details?id=com.tov.google.ben10Xenodromeplus&hl=en",
"https://play.google.com/store/apps/details?id=com.doraemon.doraemonRepairShopSeasons&hl=en",
"https://play.google.com/store/apps/details?id=com.KnowledgeAdventure.SchoolOfDragons&hl=en",
"https://play.google.com/store/apps/details?id=com.turner.stevenrpg&hl=en",
"https://play.google.com/store/apps/details?id=com.indigokids.mimdoctor&hl=en",
"https://play.google.com/store/apps/details?id=com.rovio.gold&hl=en",
"https://itunes.apple.com/us/app/angry-birds/id343200656?mt=8",
"https://itunes.apple.com/us/app/doodle-jump/id307727765?mt=8",
"https://itunes.apple.com/us/app/tiny-wings/id417817520?mt=8",
"https://itunes.apple.com/us/app/flick-home-run-!/id454086751?mt=8",
"https://itunes.apple.com/us/app/bike-race-pro/id510461370?mt=8"}
</code></pre>
<p>To test out beautifulsoup (bs in my code), I used one app for each store:</p>
<pre><code>gptest = bs(urllib.urlopen("https://play.google.com/store/apps/details?id=com.rovio.gold&hl=en"))
ios = bs(urllib.urlopen("https://itunes.apple.com/us/app/doodle-jump/id307727765?mt=8"))
</code></pre>
<p>I found an app's category on iTunes using:</p>
<pre><code>print ios.find(itemprop="applicationCategory").get_text()
</code></pre>
<p>...and on Google Play:</p>
<pre><code>print gptest.find(itemprop="genre").get_text()
</code></pre>
<p>With this newfound confidence, I wanted to try to iterate through my entire list and output these values, but then I realized I suck at for loops...</p>
<p>Here's my attempt:</p>
<pre><code>def opensite():
for item in list:
bs(urllib.urlopen())
for item in list:
try:
if "itunes.apple.com" in row:
print "Category:", opensite.find(itemprop="applicationCategory").get_text()
else if "play.google.com" in row:
print "Category", opensite.find(itemprop="genre").get_text()
except:
pass
</code></pre>
<p>Note: Ideally I'd be passing a csv (called "sample" with one column "URL") so I believe my loop would start with</p>
<pre><code>for row in sample.URL:
</code></pre>
<p>but I figured it was more helpful to show you a list rather than deal with a data frame.</p>
<p>Thanks in advance!</p>
| -1 | 2016-08-17T03:00:56Z | 38,988,164 | <pre><code>from __future__ import print_function #
try: #
from urllib import urlopen # Support Python 2 and 3
except ImportError: #
from urllib.request import urlopen #
from bs4 import BeautifulSoup as bs
for line in open('urls.dat'): # Read urls from file line by line
doc = bs(urlopen(line.strip()), 'html5lib') # Strip \n from url, open it and parse
if 'apple.com' in line:
prop = 'applicationCategory'
elif 'google.com' in line:
prop = 'genre'
else:
continue
print(doc.find(itemprop=prop).get_text())
</code></pre>
| 1 | 2016-08-17T04:33:04Z | [
"python",
"for-loop",
"beautifulsoup",
"urlopen"
] |
urlopen for loop with beautifulsoup | 38,987,427 | <p>New user here. I'm <em>starting</em> to get the hang of Python syntax but keep getting thrown off by for loops. I understand each scenario I've reach on SO thus far (and my previous examples), but can't seem to come up with one for my current scenario.</p>
<p>I am playing around with BeautifulSoup to extract features from app stores as an exercise.</p>
<p>I created a list of both GooglePlay and iTunes urls to play around with.</p>
<pre><code> list = {"https://play.google.com/store/apps/details?id=com.tov.google.ben10Xenodromeplus&hl=en",
"https://play.google.com/store/apps/details?id=com.doraemon.doraemonRepairShopSeasons&hl=en",
"https://play.google.com/store/apps/details?id=com.KnowledgeAdventure.SchoolOfDragons&hl=en",
"https://play.google.com/store/apps/details?id=com.turner.stevenrpg&hl=en",
"https://play.google.com/store/apps/details?id=com.indigokids.mimdoctor&hl=en",
"https://play.google.com/store/apps/details?id=com.rovio.gold&hl=en",
"https://itunes.apple.com/us/app/angry-birds/id343200656?mt=8",
"https://itunes.apple.com/us/app/doodle-jump/id307727765?mt=8",
"https://itunes.apple.com/us/app/tiny-wings/id417817520?mt=8",
"https://itunes.apple.com/us/app/flick-home-run-!/id454086751?mt=8",
"https://itunes.apple.com/us/app/bike-race-pro/id510461370?mt=8"}
</code></pre>
<p>To test out beautifulsoup (bs in my code), I used one app for each store:</p>
<pre><code>gptest = bs(urllib.urlopen("https://play.google.com/store/apps/details?id=com.rovio.gold&hl=en"))
ios = bs(urllib.urlopen("https://itunes.apple.com/us/app/doodle-jump/id307727765?mt=8"))
</code></pre>
<p>I found an app's category on iTunes using:</p>
<pre><code>print ios.find(itemprop="applicationCategory").get_text()
</code></pre>
<p>...and on Google Play:</p>
<pre><code>print gptest.find(itemprop="genre").get_text()
</code></pre>
<p>With this newfound confidence, I wanted to try to iterate through my entire list and output these values, but then I realized I suck at for loops...</p>
<p>Here's my attempt:</p>
<pre><code>def opensite():
for item in list:
bs(urllib.urlopen())
for item in list:
try:
if "itunes.apple.com" in row:
print "Category:", opensite.find(itemprop="applicationCategory").get_text()
else if "play.google.com" in row:
print "Category", opensite.find(itemprop="genre").get_text()
except:
pass
</code></pre>
<p>Note: Ideally I'd be passing a csv (called "sample" with one column "URL") so I believe my loop would start with</p>
<pre><code>for row in sample.URL:
</code></pre>
<p>but I figured it was more helpful to show you a list rather than deal with a data frame.</p>
<p>Thanks in advance!</p>
| -1 | 2016-08-17T03:00:56Z | 38,988,694 | <p>Try this for reading urls from list:</p>
<pre><code>from bs4 import BeautifulSoup as bs
import urllib2
import requests
list = {"https://play.google.com/store/apps/details?id=com.tov.google.ben10Xenodromeplus&hl=en",
"https://play.google.com/store/apps/details?id=com.doraemon.doraemonRepairShopSeasons&hl=en",
"https://play.google.com/store/apps/details?id=com.KnowledgeAdventure.SchoolOfDragons&hl=en",
"https://play.google.com/store/apps/details?id=com.turner.stevenrpg&hl=en",
"https://play.google.com/store/apps/details?id=com.indigokids.mimdoctor&hl=en",
"https://play.google.com/store/apps/details?id=com.rovio.gold&hl=en",
"https://itunes.apple.com/us/app/angry-birds/id343200656?mt=8",
"https://itunes.apple.com/us/app/doodle-jump/id307727765?mt=8",
"https://itunes.apple.com/us/app/tiny-wings/id417817520?mt=8",
"https://itunes.apple.com/us/app/flick-home-run-!/id454086751?mt=8",
"https://itunes.apple.com/us/app/bike-race-pro/id510461370?mt=8"}
def opensite():
for item in list:
bs(urllib2.urlopen(item),"html.parser")
source = requests.get(item)
text_new = source.text
soup = bs(text_new, "html.parser")
try:
if "itunes.apple.com" in item:
print item,"Category:",soup.find('span',{'itemprop':'applicationCategory'}).text
elif "play.google.com" in item:
print item,"Category:", soup.find('span',{'itemprop':'genre'}).text
except:
pass
opensite()
</code></pre>
<p>It will print like </p>
<pre><code>https://itunes.apple.com/us/app/doodle-jump/id307727765?mt=8 Category: Games
https://play.google.com/store/apps/details?id=com.KnowledgeAdventure.SchoolOfDragons&hl=en Category: Role Playing
https://play.google.com/store/apps/details?id=com.tov.google.ben10Xenodromeplus&hl=en Category: Role Playing
https://itunes.apple.com/us/app/tiny-wings/id417817520?mt=8 Category: Games
https://play.google.com/store/apps/details?id=com.doraemon.doraemonRepairShopSeasons&hl=en Category: Role Playing
https://itunes.apple.com/us/app/angry-birds/id343200656?mt=8 Category: Games
https://play.google.com/store/apps/details?id=com.indigokids.mimdoctor&hl=en Category: Role Playing
https://itunes.apple.com/us/app/bike-race-pro/id510461370?mt=8 Category: Games
https://play.google.com/store/apps/details?id=com.rovio.gold&hl=en Category: Role Playing
https://play.google.com/store/apps/details?id=com.turner.stevenrpg&hl=en Category: Role Playing
https://itunes.apple.com/us/app/flick-home-run-!/id454086751?mt=8 Category: Games
</code></pre>
| 1 | 2016-08-17T05:26:16Z | [
"python",
"for-loop",
"beautifulsoup",
"urlopen"
] |
Django: Change status and color in a bootstrap button | 38,987,443 | <p>I am trying to change the status (from Authenticate to Authenticated) and color (from default to success) on a bootstrap button whenever my Soundcloud API has authenticated its user and is redirected back to my website.</p>
<p>Here is my Soundcloud class in <code>views.py</code>:</p>
<pre><code>class SoundcloudAccountView(PodcastRequiredMixin, View):
form_class = SoundcloudAccountForm
template_name = 'pod_funnel/forms_soundcloud_account.html'
def get(self, request, *args, **kwargs):
# We check if we have a Soundcloud config for this users podcast, if not
# redirect directly to Oauth 2, otherwise show form
soundcloud_config_id = self.podcast.soundcloud_account_id
if soundcloud_config_id is None:
soundcloud_config = SoundcloudConfig(client=self.client)
soundcloud_config.save()
self.podcast.soundcloud_account = soundcloud_config
self.podcast.save()
else:
soundcloud_config = self.podcast.soundcloud_account
if not soundcloud_config.is_authenticated():
client_id = settings.PODFUNNEL_SOUNDCLOUD_APP_CLIENT_ID
client_secret = settings.PODFUNNEL_SOUNDCLOUD_APP_CLIENT_SECRET
redirect_uri = settings.PODFUNNEL_SOUNDCLOUD_APP_AUTH_CALLBACK
api = SoundcloudAPI(soundcloud_config, request, client_id, client_secret, redirect_uri)
request_url_response = api.get_authentication_url()
if request_url_response.success and request_url_response.redirect_url:
return HttpResponseRedirect(request_url_response.redirect_url)
initial_values = {'name': soundcloud_config.screen_name}
form = self.form_class(initial=initial_values)
return render(request, self.template_name, {'form': form})
# if we get a post request on this view, it means the user wants to reauthenticate or delete.
# Delete current soundcloud config and call get for reauthenticate otherwise back to accounts.
def post(self, request, *args, **kwargs):
soundcloud_config_id = self.podcast.soundcloud_account_id
if soundcloud_config_id is not None:
SoundcloudConfig.objects.filter(id=soundcloud_config_id).delete()
isDelete = request.POST.get('action', None) == 'Delete'
if isDelete:
return HttpResponseRedirect(reverse('podfunnel:accounts'))
return self.get(request, args, kwargs)
class SoundcloudAuthenticationView(LoginRequiredMixin, RedirectView):
pattern_name = 'podfunnel:soundcloudaccount'
def get(self, request, *args, **kwargs):
soundcloud_config_id = self.request.session.get('soundcloud_config_id')
self.request.session.delete('soundcloud_config_id')
soundcloud_config = get_object_or_404(SoundcloudConfig, id=soundcloud_config_id)
# Now we need to exchange the tokens
client_id = settings.PODFUNNEL_SOUNDCLOUD_APP_CLIENT_ID
client_secret = settings.PODFUNNEL_SOUNDCLOUD_APP_CLIENT_SECRET
redirect_uri = settings.PODFUNNEL_SOUNDCLOUD_APP_AUTH_CALLBACK
api = SoundcloudAPI(soundcloud_config, request, client_id, client_secret, redirect_uri)
exchangeTokenResponse = api.get_tokens_for_authentication_callback(self.request)
# If succesfull update 'soundcloud_config' info
# Otherwise we redirect without saving.
if exchangeTokenResponse.success:
soundcloud_config.access_token = exchangeTokenResponse.access_token
response = api.me() # Get name
if response.success:
soundcloud_config.screen_name = response.resource.get('username')
soundcloud_config.save()
return super(SoundcloudAuthenticationView, self).get(request, *args, **kwargs)
</code></pre>
<p>And here is the code in the template where I want the button to change its color and status whenever the user is redirected successfully from Soundcloud:</p>
<pre><code><div class="col-md-4 text-center">
<br>
<a class="btn btn-warning box-shadow--6dp" href="{% url 'podfunnel:soundcloudaccount' %}" role="button">Authenticate</a>
<br>
</div>
</code></pre>
<p>Any suggestion on how I can implement this? Could I do this without implementing <code>jQuery</code>?</p>
<p>Would appreciate any suggestion</p>
| 0 | 2016-08-17T03:02:29Z | 38,987,769 | <p>You can render bootstrap status to your template, like</p>
<pre><code>return render(request, self.template_name, {'status': 'btn btn-success'})
return render(request, self.template_name, {'status': 'btn btn-danger'})
</code></pre>
<p>then use it in the template, like</p>
<pre><code><input type="button" class={{status}} value="" />
</code></pre>
| 0 | 2016-08-17T03:42:47Z | [
"python",
"django",
"twitter-bootstrap"
] |
How to detect ending location (x,y,z) of certain sequence in 3D domain | 38,987,464 | <p>I have protein 3D creo-EM scan, such that it contains a chain which bends and twists around itself - and has in 3-dimension space 2 chain endings (like continuous rope). I need to detect (x,y,z) location within given cube space of two or possibly multiplier of 2 endings. Cube space of scan is presented by densities in each voxel (in range 0 till 1) provided by scanning EM microscope, such that "existing matter" gives values closer to 1, and "no matter" gives density values closer to 0. I need a method to detect protein "rope" edges (possible "rope ending" definition is lack of continuation in certain tangled direction. Intuitively, I think there could be at least 2 methods: 1) Certain method in graph theory (I can't specify precisely - if you know one - please name or describe it. 2) Derivatives from analytic algebra - but again I can't specify specific attitude - so please name or explain one. Please specify computation complexity of suggested method. My project is implemented in Python. Please help. Thanks in advance.</p>
| 2 | 2016-08-17T03:05:29Z | 38,987,964 | <p>One approach would be to choose a threshold density, convert all voxels below this threshold to 0 and all above it to 1, and then look for <strong>the pair of 1-voxels whose shortest path is longest</strong> among all pairs of 1-voxels. These two voxels should be near the ends of the longest "rope", regardless of the exact shape that rope takes.</p>
<p>You can define a graph where there is a vertex for each 1-voxel and an edge between each 1-voxel and its 6 (or possibly 14) neighbours. You can then compute the lengths of the shortest paths between some given vertex u and every other vertex in O(|V|) time and space using breadth first search (we don't need Dijkstra or Floyd-Warshall here since every edge has weight 1). Repeating this for each possible start vertex u gives an O(|V|^2)-time algorithm. As you do this, keep track of the furthest pair so far.</p>
<p>If your voxel space has w*h*d cells, there could be w*h*d vertices in the graph (if every single voxel is a 1-voxel), so this could take O(w^2*h^2*d^2) time in the worst case, which is probably quite a lot. Luckily there are many ways to speed this up if you can afford a slightly imprecise answer:</p>
<ul>
<li>Only compute shortest paths from start vertices that are at the boundary -- i.e. those vertices that have fewer than 6 (or 14) neighbours. (I believe this won't sacrifice an optimal solution.)</li>
<li>Alternatively, first "skeletonise" the graph by repeatedly getting rid of all such boundary vertices whose removal will not disconnect the graph.</li>
<li>A good order for choosing starting vertices is to first choose any vertex, and then always choose a vertex that was found to be at maximum possible distance from the last one (and which has not yet been tried, of course). This should get you a very good approximation to the longest shortest path after just 3 iterations: the furthest vertex from the start vertex will be near one of the two rope ends, and the furthest vertex from <em>that</em> vertex will be near the other end!</li>
</ul>
<p>Note: If there is no full-voxel gap between distant points on the rope that are near each other due to bending, then the shortest paths will "short-circuit" through these false connections and possibly reduce the accuracy. You might be able to ameliorate this by increasing the threshold. OTOH, if the threshold is too high then the rope can become disconnected. I expect you want to choose the highest threshold that results in only 1 connected component.</p>
| 1 | 2016-08-17T04:07:38Z | [
"python",
"algorithm",
"graph",
"analytics",
"d3dimage"
] |
How to detect ending location (x,y,z) of certain sequence in 3D domain | 38,987,464 | <p>I have protein 3D creo-EM scan, such that it contains a chain which bends and twists around itself - and has in 3-dimension space 2 chain endings (like continuous rope). I need to detect (x,y,z) location within given cube space of two or possibly multiplier of 2 endings. Cube space of scan is presented by densities in each voxel (in range 0 till 1) provided by scanning EM microscope, such that "existing matter" gives values closer to 1, and "no matter" gives density values closer to 0. I need a method to detect protein "rope" edges (possible "rope ending" definition is lack of continuation in certain tangled direction. Intuitively, I think there could be at least 2 methods: 1) Certain method in graph theory (I can't specify precisely - if you know one - please name or describe it. 2) Derivatives from analytic algebra - but again I can't specify specific attitude - so please name or explain one. Please specify computation complexity of suggested method. My project is implemented in Python. Please help. Thanks in advance.</p>
| 2 | 2016-08-17T03:05:29Z | 38,993,951 | <p>If you want to enumerate each continuous path (thereby obtaining the ends of each path) in your 3D scan you could, for each position, apply a basic depth-first-search, for example:</p>
<pre><code>//applied at some voxel
dfs(...)
for each surrounding voxel
dfs(...)
</code></pre>
<p>Or in detail:</p>
<pre><code>class coordinate{
x
y
z
visited
}
initialize pathList
initialize coords
add all coordinates which contain "matter" to coords
dfs(coordinate,path)
coordinate.visited = TRUE
isEnd = TRUE
FOR each coordinate
//check each of the 26 possible locations (total 26 conditionals)
IF coordinate.get(x-1,y-1,z+1) IN coords AND
NOT coordinate.get(x-1,y-1,z+1).visited THEN
isEnd = FALSE
path += coordinate.get(x-1,y-1,z+1)
dfs(coordinate.get(x-1,y-1,z+1),path)
...
IF coordinate.get(x+1,y+1,z-1) IN coords AND
NOT coordinate.get(x+1,y+1,z-1).visited THEN
isEnd = FALSE
path += coordinate.get(x+1,y+1,z-1)
dfs(coordinate.get(x+1,y+1,z-1),path)
IF isEnd THEN
add path to pathList
remove coordinate from coords
WHILE coords isn't empty
dfs(coords.get(0),"")
</code></pre>
<p>The general procedure (dfs) is well-documented on dozens of other sites but if you want to test it here's some crude java (I'm not too familiar with python) that mirrors what's above:</p>
<pre class="lang-java prettyprint-override"><code>public class C {
ArrayList<Coordinate> coords = new ArrayList<>();
ArrayList<String> paths = new ArrayList<>();
static class Coordinate {
int x, y, z;
boolean visited;
Coordinate(int x,int y,int z){
this.x = x;
this.y = y;
this.z = z;
visited = false;
}
public String toString() {
return "("+x+","+y+","+z+")";
}
}
void dfs(Coordinate c,String path) {
c.visited=true;
path+=c.toString();
boolean isEnd = true;
//apply dfs to 26 possible neighbors
for(int x = c.x-1; x <= c.x+1; x++) {
for (int y = c.y-1; y <= c.y+1; y++) {
for (int z = c.z+1; z >= c.z-1; z--) {
Coordinate coord = getCoordinate(x,y,z);
//if coord exists and it's not been visited
if(coord!=null && !coord.visited && !coord.equals(c)) {
isEnd = false;
dfs(coord, path);
}
}
}
}
if(isEnd) paths.add(path);
coords.remove(c);
}
Coordinate getCoordinate(int x,int y,int z){
for(Coordinate b: coords){
if(x==b.x && y==b.y && z==b.z) return b;
}
return null;
}
void search(){
//while there are points in 3d space extend a path from one
while(!coords.isEmpty()){
dfs(coords.get(0),"");
}
}
public static void main(String[] args) {
C coord = new C();
//for each place where there exists matter
//create a coordinate object and add to coords
// for example:
coord.coords.add(new Coordinate(0,0,0));
coord.coords.add(new Coordinate(-1,1,1));
coord.coords.add(new Coordinate(1,1,1));
coord.coords.add(new Coordinate(-1,2,2));
coord.coords.add(new Coordinate(-1,0,2));
coord.coords.add(new Coordinate(1,2,2));
coord.coords.add(new Coordinate(1,0,2));
coord.search();
//print out each path on separate line,
//the path endings can easily be obtained from this
for(String s:coord.paths) System.out.println(s);
}
}
</code></pre>
| 0 | 2016-08-17T10:22:03Z | [
"python",
"algorithm",
"graph",
"analytics",
"d3dimage"
] |
eval() and run() in tensorflow | 38,987,466 | <p>I'm referring to <strong>Deep MNIST for Experts tutorial</strong> given by the tensorflow. I have a problem in <a href="https://www.tensorflow.org/versions/r0.10/tutorials/mnist/pros/index.html#train-and-evaluate-the-model" rel="nofollow">Train and Evaluate</a> part of that tutorial. There they have given a sample code as follows.</p>
<pre><code>cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y_conv),reduction_indices=[1]))
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
correct_prediction = tf.equal(tf.argmax(y_conv,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
sess.run(tf.initialize_all_variables())
for i in range(20000):
batch = mnist.train.next_batch(50)
if i%100 == 0:
train_accuracy = accuracy.eval(feed_dict={x:batch[0], y_: batch[1], keep_prob: 1.0})
print("step %d, training accuracy %g"%(i, train_accuracy))
train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})
print("test accuracy %g"%accuracy.eval(feed_dict={x: mnist.test.images,
y_: mnist.test.labels, keep_prob: 1.0}))
</code></pre>
<p>So in these code segment they have used <code>accuracy.eval()</code> at one time. And other time <code>train_step.run()</code>. As I know of both of them are tensor variables.</p>
<p>And in some cases, I have seen like</p>
<pre><code>sess.run(variable, feed_dict)
</code></pre>
<p>So my question is what are the differences between these 3 implementations. And how can I know what to use when..?</p>
<p>Thank You!!</p>
| 1 | 2016-08-17T03:05:52Z | 38,990,824 | <p>If you have only one default session, they are basically the same.</p>
<p>From <a href="https://www.tensorflow.org/versions/r0.10/api_docs/python/framework.html#Operation" rel="nofollow">https://www.tensorflow.org/versions/r0.10/api_docs/python/framework.html#Operation</a>:</p>
<blockquote>
<p>op.run() is a shortcut for calling tf.get_default_session().run(op)</p>
</blockquote>
<p>From <a href="https://www.tensorflow.org/versions/r0.10/api_docs/python/framework.html#Tensor" rel="nofollow">https://www.tensorflow.org/versions/r0.10/api_docs/python/framework.html#Tensor</a>:</p>
<blockquote>
<p>t.eval() is a shortcut for calling tf.get_default_session().run(t)</p>
</blockquote>
<p>Why these differences between Tensor and Operation? From <a href="https://www.tensorflow.org/versions/r0.10/api_docs/python/framework.html#Tensor" rel="nofollow">https://www.tensorflow.org/versions/r0.10/api_docs/python/framework.html#Tensor</a>:</p>
<blockquote>
<p>Note: the Tensor class will be replaced by Output in the future. Currently these two are aliases for each other.</p>
</blockquote>
| 2 | 2016-08-17T07:43:16Z | [
"python",
"python-2.7",
"tensorflow"
] |
using ansible pam_limits module to change max user processes, but failed | 38,987,582 | <p>I deployed ansible 2.1.1.0 with python 2.7.12 on Redhat 6.5. And I tried below script to modify max user processes, it runs with no failed msg but did not have effects on max user processes.</p>
<p>I know I can try other ways by editing /etc/security/limit.d/90-nproc.conf using either copy module or shell module, but since ansible offers pam_limits module, i guess this may be more graceful.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>- name: set ulimit nproc use_max
pam_limits: domain=* limit_item=nproc limit_type=- value=unlimited use_max=yes</code></pre>
</div>
</div>
</p>
| 0 | 2016-08-17T03:20:34Z | 38,989,254 | <p>Ansible <a href="http://docs.ansible.com/ansible/pam_limits_module.html#synopsis" rel="nofollow"><code>pam_limits</code></a> module uses <code>/etc/security/limits.conf</code> by default.</p>
<p>You need to add a <code>dest</code> parameter to specify path to a different file.</p>
| 1 | 2016-08-17T06:12:10Z | [
"python",
"ansible",
"ansible-playbook",
"ansible-2.x"
] |
How to return 1 out of 2 values depending on input values from a function | 38,987,628 | <p>Hi basically I would like to return 1 value if input is negative and another if input is positive. But not return both at the same time. The values returned would be used for the curve_fit function from scipy to determine my unknow parameters (a & b). </p>
<p>I tried using a if loop inside the function but it gives the following error:</p>
<p><code>ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
</code></p>
<p>Here is my code:</p>
<pre><code>#Input fitting data
PAP_Applied_H = [-5,5,10]
PAP_Eb_fit = [30.7,31.3,31.6]
#Function Fitting
def f2(x,a,b):
if x<0:
y=a*((1+(x/b))**2)
else:
y=a*((1-(x/b))**2)
return y
params2,extras2 = curve_fit(f2,PAP_Applied_H,PAP_Eb_fit,p0=(1,15))
#Linear Fitting
linefit2 = py.polyfit(PAP_Applied_H,PAP_Eb_fit,1)
l2 = py.poly1d(linefit2)
x_new2 = list(range(-50000,1000,1))
x_line2 = list(range(-3000,3000,1))
y_func2 = f2(x_new2,params2[0],params2[1])
y_line2 = l2(x_line2)
</code></pre>
<p>So how should i change the function 'f2' such that it returns the value I want? Any help would be appreciated. Thanks in advance.</p>
| 1 | 2016-08-17T03:26:59Z | 38,988,706 | <p>How about: </p>
<p>def f(x, a, b): return a * (1 - 2*abs(x)/b + (x/b)**2) </p>
<p>I know, it's a workaround and doesn't solve the general cae.</p>
| 0 | 2016-08-17T05:28:10Z | [
"python",
"function",
"python-3.x",
"jupyter-notebook"
] |
How to return 1 out of 2 values depending on input values from a function | 38,987,628 | <p>Hi basically I would like to return 1 value if input is negative and another if input is positive. But not return both at the same time. The values returned would be used for the curve_fit function from scipy to determine my unknow parameters (a & b). </p>
<p>I tried using a if loop inside the function but it gives the following error:</p>
<p><code>ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
</code></p>
<p>Here is my code:</p>
<pre><code>#Input fitting data
PAP_Applied_H = [-5,5,10]
PAP_Eb_fit = [30.7,31.3,31.6]
#Function Fitting
def f2(x,a,b):
if x<0:
y=a*((1+(x/b))**2)
else:
y=a*((1-(x/b))**2)
return y
params2,extras2 = curve_fit(f2,PAP_Applied_H,PAP_Eb_fit,p0=(1,15))
#Linear Fitting
linefit2 = py.polyfit(PAP_Applied_H,PAP_Eb_fit,1)
l2 = py.poly1d(linefit2)
x_new2 = list(range(-50000,1000,1))
x_line2 = list(range(-3000,3000,1))
y_func2 = f2(x_new2,params2[0],params2[1])
y_line2 = l2(x_line2)
</code></pre>
<p>So how should i change the function 'f2' such that it returns the value I want? Any help would be appreciated. Thanks in advance.</p>
| 1 | 2016-08-17T03:26:59Z | 38,989,033 | <p>Your input <code>x</code> is a list. You cannot check for positive or negative value for whole list. You have to check each element one by one.
Try this:</p>
<pre><code>def f2(x,a,b):
y=[]
for i in range(len(x)):
if x[i]<0:
y.append(a*((1+(x[i]/b))**2))
else:
y.append(a*((1-(x[i]/b))**2))
return y
</code></pre>
<p>Here the return value <code>y</code> is also a list of values.</p>
| 0 | 2016-08-17T05:56:24Z | [
"python",
"function",
"python-3.x",
"jupyter-notebook"
] |
python:I want to read the csv file which contains chinese,I used the 'reload(sys)' but it can't work | 38,987,658 | <p>I use Python 3.5 and PyCharm.</p>
<p>My code:</p>
<pre><code>import importlib,sys
importlib.reload (sys)
sys.setdefaultencoding("utf-8")
</code></pre>
<p>The error:</p>
<pre class="lang-none prettyprint-override"><code> sys.setdefaultencoding("utf-8")
AttributeError: module 'sys' has no attribute 'setdefaultencoding'
</code></pre>
| 0 | 2016-08-17T03:29:56Z | 38,987,874 | <p>Use of sys.setdefaultencoding("utf-8") is strictly discouraged.</p>
<p>In Python 3, the default encoding has been switched from ascii to utf-8. First check what encoding is set from python prompt using the following commands.</p>
<pre><code>$ python
>>> import sys
>>> sys.stdout.encoding
'UTF-8'
</code></pre>
<p>You can explicitly set the encoding to UTF-8 using the following ways:</p>
<p><strong>Option 1: Add encoding line in top of file name</strong></p>
<p>Add the below line after *.py file.</p>
<pre><code>#-*- coding: utf-8 -*-
</code></pre>
<p><strong>Option 2 : Through PYTHONIOENCODING export variable</strong></p>
<pre><code>export PYTHONIOENCODING=UTF-8
$ python test.py
</code></pre>
<p><strong>Option 3 : Using encode function</strong></p>
<pre><code>#!/usr/bin/env python
#-*- coding: utf-8 -*-
text = u'ãªãªã³ããã¯'
print text.encode("utf-8")
print text
</code></pre>
| 1 | 2016-08-17T03:57:31Z | [
"python"
] |
How to import the module which using argparse | 38,987,831 | <p>I got the module call foo.py, use argparse to handle variables, requires some variables, -a and a element</p>
<pre><code>python foo.py -a element
</code></pre>
<p>This works well, now I get a list of elements, I try to use foo.py to run all of them.So I create a script like this:</p>
<pre><code>import foo
for i in range(len(element)):
# how to run foo and pass -a here?
</code></pre>
<p>another option will be use execfile()</p>
<pre><code>execfile("foo.py") #should I set the -a as some global variable here?
</code></pre>
<p>I follow here <a href="https://stackoverflow.com/questions/5262702/argparse-module-how-to-add-option-without-any-argument">argparse module How to add option without any argument?</a>, I don't quite understand how to do this.</p>
<h2>EDIT</h2>
<p>Follow <a href="https://stackoverflow.com/questions/28440441/importing-a-python-script-from-another-script-and-running-it-with-arguments">importing a python script from another script and running it with arguments</a>, Now I can run the script well, But any better solution than add a list to sys.args? Or I have to add the element first, after the main() finish, than delete it from sys.args and over and over again.</p>
| 0 | 2016-08-17T03:51:06Z | 38,989,617 | <p>Thanks to @Karin,This works great.</p>
<pre><code>import sys
sys.argv += ['-a','-H MYHOSTNAME' .... other options]
from pyrseas import dbtoyaml
dbtoyaml.main()
</code></pre>
<p>And this also work.</p>
<pre><code>proc = subprocess.Popen(['python', 'foo.py', '-a', 'bala'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
</code></pre>
| 0 | 2016-08-17T06:35:12Z | [
"python"
] |
Attempting to plot images with annotations in matplotlib, but the overlap makes them unreadable | 38,987,840 | <p>I'm writing a script to classify images based on their features: Histogram, color balance, keypoint count, etc. And although the function that I wrote to display the charts works fine:</p>
<pre><code>fig,axes = plt.subplots(2,3,figsize=(15,7))
axes[0, 0].scatter((zip(*xy_a))[0], (zip(*xy_a))[1])
for i, txt in enumerate(xy_na): axes[0, 0].annotate(txt, ((zip(*xy_a))[0][i],(zip(*xy_a))[1][i]))
axes[0, 0].set_title("xy_a")
axes[0, 0].set_xlabel('Histogram')
axes[0, 0].set_ylabel('Average Pixel')
axes[1, 0].scatter(*zip(*xy_b))
for i, txt in enumerate(xy_na): axes[1, 0].annotate(txt, ((zip(*xy_b))[0][i],(zip(*xy_b))[1][i]))
axes[1, 0].set_title("xy_b")
axes[1, 0].set_xlabel('Average Pixel')
axes[1, 0].set_ylabel('Keypoint Number')
axes[0, 1].scatter(*zip(*xy_c))
for i, txt in enumerate(xy_na): axes[0, 1].annotate(txt, ((zip(*xy_c))[0][i],(zip(*xy_c))[1][i]))
axes[0, 1].set_title("xy_c")
axes[0, 1].set_xlabel('Keypoint Number')
axes[0, 1].set_ylabel('Histogram')
axes[1, 1].scatter(*zip(*xy_d))
for i, txt in enumerate(xy_na): axes[1, 1].annotate(txt, ((zip(*xy_d))[0][i],(zip(*xy_d))[1][i]))
axes[1, 1].set_title("xy_d")
axes[1, 1].set_xlabel('Dimentional Mean')
axes[1, 1].set_ylabel('Histogram')
axes[0, 2].scatter(*zip(*xy_e))
for i, txt in enumerate(xy_na): axes[0, 2].annotate(txt, ((zip(*xy_e))[0][i],(zip(*xy_f))[1][i]))
axes[0, 2].set_title("xy_e")
axes[0, 2].set_xlabel('Average Pixel')
axes[0, 2].set_ylabel('Dimentional Mean')
axes[1, 2].scatter(*zip(*xy_f))
for i, txt in enumerate(xy_na): axes[1, 2].annotate(txt, ((zip(*xy_f))[0][i],(zip(*xy_f))[1][i]))
axes[1, 2].set_title("xy_f")
axes[1, 2].set_xlabel('Keypoint Number')
axes[1, 2].set_ylabel('Dimentional Mean')
fig.tight_layout()
fig.suptitle("Folder: {}".format ((str(folder_path)).split("/")[-1]))
plt.show()
</code></pre>
<p>The chart that it generates is less than readable:</p>
<p><a href="http://i.stack.imgur.com/4Ofn6.png" rel="nofollow"><img src="http://i.stack.imgur.com/4Ofn6.png" alt="enter image description here"></a></p>
<p>That folder has 13 images in it: 11 facial shots and 2 group pictures. Now, it's not <em>entirely unreadable</em>, but what happens when I run it on a folder with 100 images?</p>
<p>There are other answers on overlapping annotations, but none of them are applicable to my one-liner annotation scheme. If anyone could find a solution to my problem, that would be great.</p>
| 0 | 2016-08-17T03:52:53Z | 38,994,535 | <p>I would suggest that, instead of showing all annotations at all time, just show the annotation when you click on a data point. The same data point could also be highlighted in the other subplots.</p>
<p>See <a href="http://scipy-cookbook.readthedocs.io/items/Matplotlib_Interactive_Plotting.html" rel="nofollow">this cookbook recipe</a> for an example on how to achieve this</p>
| 1 | 2016-08-17T10:48:47Z | [
"python",
"matplotlib",
"graph",
"charts",
"annotations"
] |
Django and weasyprint, merge pdf | 38,987,854 | <p>It's possible to merge multiple pdf in django with weasyprint?</p>
<p>I have something like this:</p>
<pre><code>def verpdf(request, pk):
odet = get_object_or_404(Note, pk = pk)
template = get_template('pdfnot.html')
template1 = get_template('pdfnot2.html')
p1 = template.render({'odet': odet}).encode(encoding="ISO-8859-1")
p2 = template1.render({'note':odet}).encode(encoding="ISO-8859-1")
pdf1 = HTML(string=p1).render()
pdf2 = HTML(string=p2).render()
all_pages = [po for po in pdf1.pages for doc in pdf2.pages]
pdf_file = pdf1.copy(all_pages).write_pdf()
http_response = HttpResponse(pdf_file, content_type='application/pdf')
http_response['Content-Disposition'] = 'filename="report.pdf"'
return http_response
</code></pre>
<p>But i'm not able to join the two files, always output only the first template, it's possible to merge the two documents into one pdf? Can you help me? Thanks.</p>
| 0 | 2016-08-17T03:54:17Z | 38,988,594 | <p>Took me a while, but i solved it, was my fault for not understand the documentation lol, here is the code if anyone have the same problem:</p>
<pre><code>def verpdf(request, pk):
odet = get_object_or_404(Note, pk = pk)
template = get_template('pdfnot.html')
template1 = get_template('pdfnot2.html')
p1 = template.render({'odet': odet}).encode(encoding="ISO-8859-1")
p2 = template1.render({'note':odet}).encode(encoding="ISO-8859-1")
pdf1 = HTML(string=p1)
pdf2 = HTML(string=p2)
pdf11 = pdf1.render()
pdf12 = pdf2.render()
#val = [p for p in doc.pages for doc in pdf11, pdf12] # error, doc used before assignment, fixed with next code
val = []
for doc in pdf11, pdf12:
for p in doc.pages:
val.append(p)
pdf_file = pdf11.copy(val).write_pdf() #use metadata of pdf11
http_response = HttpResponse(pdf_file, content_type='application/pdf')
http_response['Content-Disposition'] = 'filename="report.pdf"'
return http_response
</code></pre>
<p>And with this an pdf output with two pages.</p>
| 0 | 2016-08-17T05:17:54Z | [
"python",
"django",
"pdf",
"weasyprint"
] |
Django add GenericForeignKey search fields | 38,987,895 | <p>Django 1.8.4 add GenericForeignKey search fields does not work.</p>
<p>I've created several Product models like:</p>
<pre><code>class Product1(models.Model):
...
orders = GenericRelation(Order)
class Product2(models.Model):
...
orders = GenericRelation(Order)
</code></pre>
<p>And in Order model:</p>
<pre><code>class Order(models.Model):
content_type = models.ForeignKey(
ContentType,
blank=True,
null=True
)
object_id = models.PositiveIntegerField(
blank=True,
null=True
)
product = generic.GenericForeignKey('content_type','object_id')
</code></pre>
<p>This all works Fine,</p>
<p>But when I want to search Produt name in OrderAdmin, I added prodct__name search fields like this:</p>
<pre><code>class OrderAdmin(admin.ModelAdmin):
...
search_fields = [
'product__name',
]
</code></pre>
<p>This Does Not Work!</p>
<p>Django raise that:</p>
<pre><code>Field 'product' does not generate an automatic reverse relation and therefore cannot be used for reverse querying.
If it is a GenericForeignKey, consider adding a GenericRelation.
</code></pre>
<p>Don't understand How Django 1.8 GenericForeignKey works, GenericRelations Already exist in Products models, but still doesn't work.</p>
| 1 | 2016-08-17T03:59:58Z | 39,016,729 | <p>By override the default <code>get_search_results</code> method, the following code Generally works, but still got a little problem. </p>
<pre><code>def get_search_results(self, request, queryset, search_term):
"""Override to Include searching `product__name` which is a
GenericForeignKey Field of all product types.
Returns a tuple containing a queryset to implement the search,
and a boolean indicating if the results may contain duplicates.
"""
products = [v for k, v in pro_models.PRODUCT_DICT.iteritems()]
generic_queryset = queryset
product_list = list()
for bit in search_term.split():
for product in products:
product_queryset = product.objects.filter(
Q(name__icontains=bit))
product_list += list(product_queryset)
generic_query = [Q(**{
'content_type': ContentType.objects.get_for_model(product),
'object_id': product.id
}) for product in product_list]
if generic_query:
generic_queryset = generic_queryset.filter(
reduce(operator.or_, generic_query))
else:
generic_queryset = generic_queryset.none()
default_queryset, use_distinct = \
super(OrderAdmin, self).get_search_results(
request,
queryset,
search_term
)
return default_queryset | generic_queryset, use_distinct
</code></pre>
| 0 | 2016-08-18T11:13:05Z | [
"python",
"django"
] |
Python Non-recursive Permutation | 38,987,928 | <p>Does anyone understand the following iterative algorithm for producing all permutations of a list of numbers?</p>
<p>I do not understand the logic within the <code>while len(stack)</code> loop. Can someone please explain how it works?</p>
<pre><code># Non-Recursion
@param nums: A list of Integers.
@return: A list of permutations.
def permute(self, nums):
if nums is None:
return []
nums = sorted(nums)
permutation = []
stack = [-1]
permutations = []
while len(stack):
index = stack.pop()
index += 1
while index < len(nums):
if nums[index] not in permutation:
break
index += 1
else:
if len(permutation):
permutation.pop()
continue
stack.append(index)
stack.append(-1)
permutation.append(nums[index])
if len(permutation) == len(nums):
permutations.append(list(permutation))
return permutations
</code></pre>
<p>I'm just trying to understand the code above.</p>
| 0 | 2016-08-17T04:03:08Z | 38,988,162 | <p>As mentioned in the comments section to your question, debugging may provide a helpful way to understand what the code does. However, let me provide a high-level perspective of what your code does.</p>
<p>First of all, although there are no recursive calls to the function permute, the code your provided is effectively recursive, as all it does is keeping its own stack, instead of using the one provided by the memory manager of your OS. Specifically, the variable stack is keeping the 'recursive data', so to speak, that is passed from one recursive call to another. You could, and perhaps should, consider each iteration of the outer while loop in the <em>permute</em> function as a recursive call. If you do so, you will see that the outer while loop helps 'recursively' traverse each permutation of <em>nums</em> in a depth-first manner.</p>
<p>Noticing this, it's fairly easy to figure out what each 'recursive call' does. Basically, the variable <em>permutation</em> keeps the current permutation of <em>nums</em> which is being formed as while loop progresses. Variable <em>permutations</em> store all the permutations of <em>nums</em> that are found. As you may observe, <em>permutations</em> are updated only when <em>len(permutation)</em> is equal to <em>len(nums)</em> which can be considered as the base case of the recurrence relation that is being implemented using a custom stack. Finally, the inner while loop basically picks which element of <em>nums</em> to add to the current permutation(i.e. stored in variable <em>permutation</em>) being formed.</p>
<p>So that is about it, really. You can figure out what is exactly being done on the lines relevant to the maintenance of <em>stack</em> using a debugger, as suggested. As a final note, let me repeat that I, personally, would not consider this implementation to be non-recursive. It just so happens that, instead of using the abstraction provided by the OS, this recursive solution keeps its own stack. To provide a better understanding of how a proper non-recursive solution would be, you may observe the difference in recursive and iterative solutions to the problem of finding n<sup>th</sup> Fibonacci number provided below. As you can see, the non-recursive solution keeps no stack, and instead of dividing the problem into smaller instances of it(recursion) it builds up the solution from smaller solutions. (dynamic programming)</p>
<pre><code>def recursive_fib(n):
if n == 0:
return 0
return recursive_fib(n-1) - recursive_fib(n-2)
def iterative_fib(n):
f_0 = 0
f_1 = 1
for i in range(3, n):
f_2 = f_1 + f_0
f_0 = f_1
f_1 = f_2
return f_1
</code></pre>
| 2 | 2016-08-17T04:32:46Z | [
"python",
"algorithm",
"permutation"
] |
Python Non-recursive Permutation | 38,987,928 | <p>Does anyone understand the following iterative algorithm for producing all permutations of a list of numbers?</p>
<p>I do not understand the logic within the <code>while len(stack)</code> loop. Can someone please explain how it works?</p>
<pre><code># Non-Recursion
@param nums: A list of Integers.
@return: A list of permutations.
def permute(self, nums):
if nums is None:
return []
nums = sorted(nums)
permutation = []
stack = [-1]
permutations = []
while len(stack):
index = stack.pop()
index += 1
while index < len(nums):
if nums[index] not in permutation:
break
index += 1
else:
if len(permutation):
permutation.pop()
continue
stack.append(index)
stack.append(-1)
permutation.append(nums[index])
if len(permutation) == len(nums):
permutations.append(list(permutation))
return permutations
</code></pre>
<p>I'm just trying to understand the code above.</p>
| 0 | 2016-08-17T04:03:08Z | 38,990,643 | <p>The answer from @ilim is correct and should be the accepted answer but I just wanted to add another point that wouldn't fit as a comment. Whilst I imagine you are studying this algorithm as an exercise it should be pointed out that a better way to proceed, depending on the size of the list, may be to user <code>itertools</code>'s <code>permutations()</code> function:</p>
<pre><code>print [x for x in itertools.permutations([1, 2, 3])]
</code></pre>
<p>Testing on my machine with a list of 11 items (39m permutations) took 1.7secs with <code>itertools.permutations(x)</code> but took 76secs using the custom solution above. Note however that with 12 items (479m permutations) the <code>itertools</code> solution blows up with a memory error. If you need to generate permutations of such size efficiently you may be better dropping to native code.</p>
| 0 | 2016-08-17T07:32:45Z | [
"python",
"algorithm",
"permutation"
] |
Deployed django app to heroku missing CSS / static files | 38,987,993 | <p>Preface this by saying I have now read multiple posts on this question (including <a href="http://stackoverflow.com/questions/28961177/heroku-static-files-not-loading-django?rq=1">here</a>, <a href="http://stackoverflow.com/questions/34121663/static-files-not-found-deploying-django-on-heroku?rq=1">here</a>, and <a href="http://stackoverflow.com/questions/10825443/django-heroku-static-dir?rq=1">here</a>). What I understand is that the <code>static url</code> in <code>settings.py</code> needs a modification for heroku to run these static files. What I need, explained like I am a child, is what tweak to make to these <code>static url</code> when the static directory is nested within the app -- as this was a best practice imparted in a recent tutorial (if this is not the ideal practice I would appreciate being corrected). </p>
<p><strong>Question 1:</strong> Should the <code>media</code> files be kept in a directory within the app or at the project level?</p>
<p><strong>Question 2:</strong> If the media files are kept within a directory inside the app, like my directory below, then how am I supposed to modify the <code>url</code> in <code>settings.py</code> to load the static files once pushed to heroku?</p>
<p>My project structure is the following:</p>
<pre><code>gvlabs
__init__.py
__init__.pyc
settings.py
settings.pyc
urls.py
urls.pyc
wsgi.py
wsgi.pyc
manage.py
Procfile
requirements.txt
runtime.txt
welcome
__init__.py
__init__.pyc
admin.py
admin.pyc
apps.py
hello.py
migrations
models.py
models.pyc
static
css
fonts
images
js
templates
welcome
base.html
comingsoon.html
contact_us.html
index.html
post_list.html
tests.py
urls.py
urls.pyc
views.py
views.pyc
</code></pre>
<p><strong>settings.py</strong></p>
<pre><code># Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
PROJECT_DIR = os.path.join(PROJECT_ROOT,'../welcome')
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/
#STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_ROOT= os.path.join(PROJECT_DIR,'static')
STATIC_URL = '/welcome/static/'
# Extra places for collectstatic to find static files.
STATICFILES_DIRS = ()
# Simplified static file serving.
# https://warehouse.python.org/project/whitenoise/
STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'
</code></pre>
| 0 | 2016-08-17T04:10:53Z | 38,993,312 | <ol>
<li><p>The main problem with your configuration is the <code>STATIC_ROOT</code> setting. You should change this to something like <code>os.path.join(BASE_DIR, 'static_root')</code>.</p>
<p><code>STATIC_ROOT</code> should point to an empty directory (it doesn't need to exist, Django will create it if necessary) where Django can collect your static files together and do any necessary processing on them before it serves them. It is <strong>not</strong> the directory where you store your static files.</p></li>
<li><p>Regardless of where you put your static files, you shouldn't need to change the <code>STATIC_URL</code> setting. Just leave it as <code>/static/</code>. The main reason for needing to change this is when you're serving static files via a CDN, when it would be set to something like <code>https://my-cdn.example.com/static/</code></p></li>
<li><p>I would keep static files in a directory at the project level. Sometimes, when creating a reusable app it makes sense to bundle everything together by storing its static files in a directory within the app. But most projects I've worked on have kept the main set of static files at the project level.</p></li>
<li><p>It doesn't really matter where you put your static files as long as you tell Django where to find them. You do this by adding the path to the directory to the <code>STATICFILES_DIRS</code> setting like so:</p>
<pre><code>STATICFILES_DIRS = [
os.path.join(PROJECT_DIR, 'static'),
]
</code></pre>
<p>(Technically, if your static files are in an app directory Django should be able to find them automatically, but let's keep things simple and explicit.)</p></li>
<li><p>As a side note: be careful not to use the term "media" here as that has a specific meaning in Django terminology where it refers to <a href="https://docs.djangoproject.com/en/1.10/howto/static-files/#serving-files-uploaded-by-a-user-during-development" rel="nofollow">user-uploaded</a> files like profile images rather than files that belong with your codebase like CSS and JavaScript files.</p></li>
</ol>
| 1 | 2016-08-17T09:52:30Z | [
"python",
"django",
"heroku"
] |
Access Host redis database from docker conatiner | 38,987,997 | <p>I am trying to connect to host redis database through my docker conatiner.</p>
<p>In my dockerfile , I have redis as a requirement, which gets installed [pip install redis] and image is build using that docker file.
After than I instantiate the conatiner using following command</p>
<pre><code>sudo docker run -p 6543:6543 your_image_name
</code></pre>
<p>my app.py is following</p>
<pre><code>from wsgiref.simple_server import make_server
from pyramid.config import Configurator
from pyramid.response import Response
import redis
def hello(request):
ds_id = '4000'
r_server = redis.Redis(unix_socket_path='/tmp/redis.sock')
result = r_server.set('foo','11')
return Response(result)
</code></pre>
<p>Problem is when Redis is installed in the beginning redis.sock file is not generated and thus creating error when I try to connect.</p>
<p>Dockerfile:</p>
<pre><code>FROM centos:latest
MAINTAINER Ramana Rao <treerao@gmail.com>
# load base packages w/ yum
RUN yum install -y git gcc libffi-devel openssl-devel python-devel postgresql-devel libxml2-devel libxslt-devel
COPY ./requirements.txt .
RUN curl https://bootstrap.pypa.io/get-pip.py >get-pip.py && \
python get-pip.py && \
rm get-pip.py &&\
pip install -r requirements.txt
EXPOSE 6543
WORKDIR /app
COPY app /app
ENTRYPOINT [ "python" ]
CMD [ "app.py" ]
</code></pre>
<p>requirements</p>
<pre><code>pyramid
cornice
pyramid_chameleon
pyramid_beaker
pyramid_redis_sessions
pyRFC3339
oauthlib==0.7.2
oauth2client==1.5.2
pycrypto
PyOpenSSL
pymongo
SQLAlchemy
psycopg2
lxml
gspread
jira
waitress
paste
PasteDeploy
redis
</code></pre>
<p>Is there any other way to connect to host redis data. </p>
| 0 | 2016-08-17T04:11:45Z | 38,988,477 | <ol>
<li><p>If you have a redis instance running on the host machine and just want the container to connect to that redis instance, then you just need to mount the socket file inside the container. For example, if the location of the socket file on the host machine is <code>/var/run/redis/redis.sock</code> and you want the location of the socket file inside the container to be <code>/tmp/redis.sock</code>, then launch the container like this:</p>
<pre><code>sudo docker run \
-p 6543:6543 \
-v /var/run/redis/redis.sock:/tmp/redis.sock \
your_image_name app.py
</code></pre></li>
<li><p>If you want to setup redis inside the container <em>and</em> run the python app, follow this:</p>
<p>Create a file <code>start.sh</code> with the contents:</p>
<pre><code>#!/bin/bash
/usr/bin/redis-server >/dev/null 2>&1 &
/usr/bin/python $1
</code></pre>
<p>Make the following modification to the file <code>app.py</code>:</p>
<pre><code>r_server = redis.StrictRedis(host='localhost', port=6379, db=0)
</code></pre>
<p>Make the following modifications to your Dockerfile:</p>
<p>Add the package <code>epel-release</code></p>
<pre><code>RUN yum install -y git gcc libffi-devel openssl-devel python-devel postgresql-devel libxml2-devel libxslt-devel
</code></pre>
<p>epel-release</p>
<p>Install redis</p>
<pre><code>RUN yum install -y redis
</code></pre>
<p>Copy the script created above to <code>/app</code> directory:</p>
<pre><code>COPY start.sh /app
RUN chmod +x /app/start.sh
</code></pre>
<p>Change entry point to start.sh</p>
<pre><code>ENTRYPOINT [ "/app/start.sh" ]
</code></pre></li>
</ol>
| 0 | 2016-08-17T05:05:57Z | [
"python",
"database",
"docker",
"redis"
] |
Access Host redis database from docker conatiner | 38,987,997 | <p>I am trying to connect to host redis database through my docker conatiner.</p>
<p>In my dockerfile , I have redis as a requirement, which gets installed [pip install redis] and image is build using that docker file.
After than I instantiate the conatiner using following command</p>
<pre><code>sudo docker run -p 6543:6543 your_image_name
</code></pre>
<p>my app.py is following</p>
<pre><code>from wsgiref.simple_server import make_server
from pyramid.config import Configurator
from pyramid.response import Response
import redis
def hello(request):
ds_id = '4000'
r_server = redis.Redis(unix_socket_path='/tmp/redis.sock')
result = r_server.set('foo','11')
return Response(result)
</code></pre>
<p>Problem is when Redis is installed in the beginning redis.sock file is not generated and thus creating error when I try to connect.</p>
<p>Dockerfile:</p>
<pre><code>FROM centos:latest
MAINTAINER Ramana Rao <treerao@gmail.com>
# load base packages w/ yum
RUN yum install -y git gcc libffi-devel openssl-devel python-devel postgresql-devel libxml2-devel libxslt-devel
COPY ./requirements.txt .
RUN curl https://bootstrap.pypa.io/get-pip.py >get-pip.py && \
python get-pip.py && \
rm get-pip.py &&\
pip install -r requirements.txt
EXPOSE 6543
WORKDIR /app
COPY app /app
ENTRYPOINT [ "python" ]
CMD [ "app.py" ]
</code></pre>
<p>requirements</p>
<pre><code>pyramid
cornice
pyramid_chameleon
pyramid_beaker
pyramid_redis_sessions
pyRFC3339
oauthlib==0.7.2
oauth2client==1.5.2
pycrypto
PyOpenSSL
pymongo
SQLAlchemy
psycopg2
lxml
gspread
jira
waitress
paste
PasteDeploy
redis
</code></pre>
<p>Is there any other way to connect to host redis data. </p>
| 0 | 2016-08-17T04:11:45Z | 38,989,493 | <p>You need to access the hosts localhost loopback device, so what you do is <a href="https://gist.github.com/EugenMayer/3019516e5a3b3a01b6eac88190327e7c#file-gistfile1-txt" rel="nofollow">https://gist.github.com/EugenMayer/3019516e5a3b3a01b6eac88190327e7c#file-gistfile1-txt</a></p>
<p>You create this file at</p>
<ul>
<li><code>/Library/LaunchDaemons/docker.loopback.alias.plist</code></li>
<li><code>sudo chown root:staff /Library/LaunchDaemons/docker.loopback.alias.plist</code></li>
</ul>
<p>you OSX. Then you restart your mac, after that, you can access the host loopback device using the ip <code>10.254.254.254</code> <strong>from inside of the container</strong>, so from the container you can now configure redist to connect to <code>10.254.254.254:6543</code> - which will then use your osx-host redis</p>
<p>Theory:
You need to create this loopback alias, since you cannot use <code>localhost</code> in the container, since this would pick up the loopback device of the <strong>container itself - his own loopback device</strong> - not the loopback device of your host</p>
| 0 | 2016-08-17T06:27:41Z | [
"python",
"database",
"docker",
"redis"
] |
Odoo payslip with leave in salary rule python code | 38,988,205 | <p>I have to calculate the basic pay with if condition.if the employee does not have unpaid leave means Unpaid is not there under Worked days and input under payslip then unpaid leave should be o(Zero).
I have tried the below code but its given error.</p>
<pre><code>day=contract.wage/30
if not worked_days.Unpaid.number_of_days in payslip:
result=day*(30-0)
else:
result=day*(30-worked_days.Unpaid.number_of_days)
</code></pre>
| 0 | 2016-08-17T04:38:18Z | 38,988,407 | <p>The in command in python is used to check for membership.
E.g. : <code>3 in [1, 2, 3]</code> results in True.
I am not exactly sure what is the purpose of payslip in your code but from what I understand you may try this:</p>
<pre><code>day=contract.wage/30
if Not(worked_days.Unpaid.number_of_days):
result=day*(30-0)
else:
result=day*(30-worked_days.Unpaid.number_of_days)
</code></pre>
<p>Edit after comments :</p>
<pre><code>day=contract.wage/30
if worked_days.Unpaid and worked_days.Unpaid.number_of_days or False:
result=day*(30-0)
else:
result=day*(30-worked_days.Unpaid.number_of_days)
</code></pre>
| 1 | 2016-08-17T04:59:04Z | [
"python",
"openerp",
"odoo-8"
] |
Urllib HTTP Error 403 | 38,988,249 | <p>I've searched through the forums to try and figure out why the following code was not working:</p>
<pre><code>import nltk, re, pprint
from urllib import request
url = "http://www.gutenberg.org/files/2554/2554.txt"
response = request.urlopen(url)
raw = response.read().decode('utf8')
print(raw[:75])
</code></pre>
<p>But have thus far been unsuccessful in resolving things. Here are some similar solutions I tried to implement to no avail:
<a href="http://stackoverflow.com/questions/22877619/python3-urllib-error-httperror-http-error-403-forbidden">Forum 1,</a>
<a href="http://stackoverflow.com/questions/16627227/http-error-403-in-python-3-web-scraping">Forum 2</a></p>
<p>The error I get is:</p>
<pre><code> File "C:\Python33\lib\urllib\request.py", line 163, in urlopen
return opener.open(url, data, timeout)
File "C:\Python33\lib\urllib\request.py", line 472, in open
response = meth(req, response)
File "C:\Python33\lib\urllib\request.py", line 582, in http_response
'http', request, response, code, msg, hdrs)
File "C:\Python33\lib\urllib\request.py", line 510, in error
return self._call_chain(*args)
File "C:\Python33\lib\urllib\request.py", line 444, in _call_chain
result = func(*args)
File "C:\Python33\lib\urllib\request.py", line 590, in http_error_default
raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 403: Forbidden
</code></pre>
<p>Any help would be greatly appreciated</p>
| 0 | 2016-08-17T04:43:20Z | 38,988,344 | <p>This code works:</p>
<p><em>Python 2</em></p>
<pre><code>from urllib import urlopen
url = "http://www.gutenberg.org/files/2554/2554.txt"
response = urlopen(url)
if response.code == 200:
raw = response.read().decode('utf-8')
print raw[:75]
else:
print 'Error', response.code
response.close()
</code></pre>
<p>Response:</p>
<blockquote>
<p>The Project Gutenberg EBook of Crime and Punishment, by Fyodor Dostoevsky</p>
</blockquote>
<p><em>Python 3</em></p>
<pre><code>from urllib import request
url = "http://www.gutenberg.org/files/2554/2554.txt"
try:
response = request.urlopen(url)
raw = response.read().decode('utf-8')
print(raw[:75])
except Exception as ex:
print('Error:', ex)
</code></pre>
<p>If you get HTTP code 403, it mean that you forbidden from access this url.</p>
| 3 | 2016-08-17T04:54:19Z | [
"python",
"urllib",
"http-error",
"urlopen"
] |
Django Rest Framework (DRF) How to set pagination class depending on query_params? | 38,988,272 | <p>I'm trying to use different sets of pagination classes on a viewset depending on query_params.</p>
<pre><code>class BlockViewSet(viewsets.ModelViewSet):
pagination_class = defaultPaginationClass
def get_queryset(self):
queryset = Block.objects.all()
user = self.request.query_params.get('user', None)
if user is no None:
queryset = queryset.filter(user=user)
return queryset
</code></pre>
<p>so if the get request is made to <code>/block/</code>, I want to use defaultPagination class while if the request is made to <code>/block/?user=1</code>, I want to use customPagination class.</p>
| 0 | 2016-08-17T04:45:39Z | 38,989,390 | <p>Try to redefine <code>paginator</code> property and if there is user query param, assign your custom pagination class to <code>self._paginator</code></p>
<pre><code>@property
def paginator(self):
"""
The paginator instance associated with the view, or `None`.
"""
if not hasattr(self, '_paginator'):
if self.pagination_class is None:
self._paginator = None
else:
user = self.request.query_params.get('user', None)
if user is not None:
self._paginator = customPaginationClass()
else:
self._paginator = self.pagination_class()
return self._paginator
</code></pre>
<p>Final</p>
<pre><code>class BlockViewSet(viewsets.ModelViewSet):
pagination_class = defaultPaginationClass
@property
def paginator(self):
"""
The paginator instance associated with the view, or `None`.
"""
if not hasattr(self, '_paginator'):
if self.pagination_class is None:
self._paginator = None
else:
user = self.request.query_params.get('user', None)
if user is not None:
self._paginator = customPaginationClass()
else:
self._paginator = self.pagination_class()
return self._paginator
def get_queryset(self):
queryset = Block.objects.all()
user = self.request.query_params.get('user', None)
if user is no None:
queryset = queryset.filter(user=user)
return queryset
</code></pre>
| 0 | 2016-08-17T06:21:12Z | [
"python",
"django",
"pagination",
"django-rest-framework"
] |
Still getting 404 page not found on Django using correct route files and settings | 38,988,331 | <p>I'm going through the polls Django tutorial and have searched for answers to this. So far:</p>
<ol>
<li><p>I made sure I'm using the right directories. The main urls.py is in mysite/mysite/, the polls urls.py is in mysite/polls/urls.py.</p></li>
<li><p>Tried adding 'polls' to INSTALLED_APPS in the settings.py of mysite/mysite.</p></li>
<li><p>Am making sure that I am requesting 127.0.0.1:8000/polls and not 127.0.0.1:8000</p></li>
<li><p>I am using Python 3.4 and Django 1.9, same as the tutorial.</p></li>
</ol>
<p>I am still receiving this message:</p>
<pre><code>Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/polls
Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:
^polls/
^admin/
The current URL, polls, didn't match any of these.
</code></pre>
<p><strong>mysite/mysite/urls.py</strong></p>
<pre><code>from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^polls/', include('polls.urls')),
url(r'^admin/', admin.site.urls),
]
</code></pre>
<p><strong>mysite/polls/urls.py</strong></p>
<pre><code>from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^%', views.index, name='index'),
]
</code></pre>
<p><strong>mysite/polls/views.py</strong></p>
<pre><code>from django.shortcuts import render
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello, world")
</code></pre>
| 0 | 2016-08-17T04:52:24Z | 38,988,444 | <p>In your <code>polls/urls.py</code>
change <code>url(r'^%', views.index, name='index')</code> to <code>url(r'^$', views.index, name='index')</code>. </p>
<p>Also in your urls.py, you have route for <code>127.0.0.1:8000/polls/</code> and you request for <code>127.0.0.1:8000/polls</code> . Notice the trailing slash.</p>
<p>So you should request to <code>127.0.0.1:8000/polls/</code> . </p>
<p>Add <code>APPEND_SLASH = True</code> in your <code>settings.py</code> file so that it would redirect <code>127.0.0.1:8000/polls</code> to <code>127.0.0.1:8000/polls/</code> .</p>
| 0 | 2016-08-17T05:01:59Z | [
"python",
"django"
] |
Still getting 404 page not found on Django using correct route files and settings | 38,988,331 | <p>I'm going through the polls Django tutorial and have searched for answers to this. So far:</p>
<ol>
<li><p>I made sure I'm using the right directories. The main urls.py is in mysite/mysite/, the polls urls.py is in mysite/polls/urls.py.</p></li>
<li><p>Tried adding 'polls' to INSTALLED_APPS in the settings.py of mysite/mysite.</p></li>
<li><p>Am making sure that I am requesting 127.0.0.1:8000/polls and not 127.0.0.1:8000</p></li>
<li><p>I am using Python 3.4 and Django 1.9, same as the tutorial.</p></li>
</ol>
<p>I am still receiving this message:</p>
<pre><code>Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/polls
Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:
^polls/
^admin/
The current URL, polls, didn't match any of these.
</code></pre>
<p><strong>mysite/mysite/urls.py</strong></p>
<pre><code>from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^polls/', include('polls.urls')),
url(r'^admin/', admin.site.urls),
]
</code></pre>
<p><strong>mysite/polls/urls.py</strong></p>
<pre><code>from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^%', views.index, name='index'),
]
</code></pre>
<p><strong>mysite/polls/views.py</strong></p>
<pre><code>from django.shortcuts import render
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello, world")
</code></pre>
| 0 | 2016-08-17T04:52:24Z | 38,988,448 | <p>So i tried your Index view with your urls.py.
It works, the only thing different is in your "Request URL, you must request for - 127.0.0.1:8000/polls/%</p>
<p>changing your urls to </p>
<p>url('^/%', index) - polls URLs.py
url('^polls', include('polls.urls')) - project URLs</p>
<p>This will work.</p>
| 0 | 2016-08-17T05:02:41Z | [
"python",
"django"
] |
Python advanced slicing | 38,988,560 | <p>I am a little confused with Python's advanced slicing. I basically had a dictionary and with help from SO, I made it into an array. </p>
<pre><code> array1 =
([[[36, 16],
[48, 24],
[12, 4],
[12, 4]],
[[48, 24],
[64, 36],
[16, 6],
[16, 6]],
[[12, 4],
[16, 6],
[ 4, 1],
[ 4, 1]],
[[12, 4],
[16, 6],
[ 4, 1],
[ 4, 1]]])
</code></pre>
<p>To practice using matrix solver, the array was turned into a square matrix (4 x 4) using:</p>
<pre><code> array_matrix_sized = array[:, :, 0]
</code></pre>
<p>I read that this means [number of indices, rows, columns]. I am a little clueless as to why [:,:,0] returns a 4 x 4 matrix. To try to help, I made an array that has a length 100, and I have been trying to turn it into a 10 x 10 matrix in a similar manner with no success. What throws me off is the number of rows is ":" and the number of columns is "0", if I read this concept correctly. For a 4 x 4 matrix, why isn't it array[:, 4, 4]? I am also assuming the : is because I am interested in all the values. </p>
<p>Thank you in advance for any help/advice. I do apologize if this is a simple question, but I really could use the clarification on how this works.</p>
<p>Still not quite understanding.
If I have </p>
<pre><code> array2 = array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38,
39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64,
65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77,
78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90,
91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103,
104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116,
117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129,
130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142,
143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155,
156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168,
169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181,
182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194,
195, 196, 197, 198, 199])
</code></pre>
<p>To get it into a 10 X 10 matrix, I tried using array2[:,:,0] and get the error IndexError: too many indices for array. Isn't this similar to my first example?</p>
| 0 | 2016-08-17T05:13:50Z | 38,988,696 | <blockquote>
<p>I read that this means [number of indices, rows, columns]. [...] What throws me off is the number of rows is ":" and the number of columns is "0", if I read this concept correctly.</p>
</blockquote>
<p>No. It means [which parts I want on dimension 1, which parts I want on dimension 2, which parts I want on dimension 3]. The indices are not how many rows/columns you want, they are <em>which</em> ones you want. And, as you said <code>:</code> means "all" in this context.</p>
<blockquote>
<p>For a 4 x 4 matrix, why isn't it array[:, 4, 4]?</p>
</blockquote>
<p>You don't specify the shape of the result. The shape of the result depends on the shape of the original array. Since your array is 4x4x2, getting one element on the last dimension gives you 4x4. If the array was 8x7x2, then <code>[:, :, 0]</code> would give you an 8x7 result.</p>
<p>So <code>[:, :, 0]</code> means "give me everything on the first two dimensions, but only the first item on the last dimension. This amounts to getting the first element of each "row" (or the first "column" as it appears in the display) which is why you get the result you get:</p>
<pre><code>>>> array1[:, :, 0]
array([[36, 48, 12, 12],
[48, 64, 16, 16],
[12, 16, 4, 4],
[12, 16, 4, 4]])
</code></pre>
<p>Likewise, doing <code>[0, :, :]</code> gives you the first "chunk":</p>
<pre><code>>>> array1[0, :, :]
array([[36, 16],
[48, 24],
[12, 4],
[12, 4]])
</code></pre>
<p>And doing <code>[:, 0, :]</code> gives you the first row of each chunk:</p>
<pre><code>>>> x[:, 0, :]
array([[36, 16],
[48, 24],
[12, 4],
[12, 4]])
</code></pre>
| 4 | 2016-08-17T05:26:27Z | [
"python",
"arrays",
"numpy",
"matrix"
] |
Python advanced slicing | 38,988,560 | <p>I am a little confused with Python's advanced slicing. I basically had a dictionary and with help from SO, I made it into an array. </p>
<pre><code> array1 =
([[[36, 16],
[48, 24],
[12, 4],
[12, 4]],
[[48, 24],
[64, 36],
[16, 6],
[16, 6]],
[[12, 4],
[16, 6],
[ 4, 1],
[ 4, 1]],
[[12, 4],
[16, 6],
[ 4, 1],
[ 4, 1]]])
</code></pre>
<p>To practice using matrix solver, the array was turned into a square matrix (4 x 4) using:</p>
<pre><code> array_matrix_sized = array[:, :, 0]
</code></pre>
<p>I read that this means [number of indices, rows, columns]. I am a little clueless as to why [:,:,0] returns a 4 x 4 matrix. To try to help, I made an array that has a length 100, and I have been trying to turn it into a 10 x 10 matrix in a similar manner with no success. What throws me off is the number of rows is ":" and the number of columns is "0", if I read this concept correctly. For a 4 x 4 matrix, why isn't it array[:, 4, 4]? I am also assuming the : is because I am interested in all the values. </p>
<p>Thank you in advance for any help/advice. I do apologize if this is a simple question, but I really could use the clarification on how this works.</p>
<p>Still not quite understanding.
If I have </p>
<pre><code> array2 = array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38,
39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64,
65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77,
78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90,
91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103,
104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116,
117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129,
130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142,
143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155,
156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168,
169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181,
182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194,
195, 196, 197, 198, 199])
</code></pre>
<p>To get it into a 10 X 10 matrix, I tried using array2[:,:,0] and get the error IndexError: too many indices for array. Isn't this similar to my first example?</p>
| 0 | 2016-08-17T05:13:50Z | 38,988,981 | <p>I just wanted to add a clarifying example:</p>
<pre><code>>>> np.arange(4*4*2).reshape(4,4,2)
array([[[ 0, 1],
[ 2, 3],
[ 4, 5],
[ 6, 7]],
[[ 8, 9],
[10, 11],
[12, 13],
[14, 15]],
[[16, 17],
[18, 19],
[20, 21],
[22, 23]],
[[24, 25],
[26, 27],
[28, 29],
[30, 31]]])
</code></pre>
<p>Since we are in three dimensions, we can still maintain a spatial metaphor. Imagine these 4X2 slices were all stacked up against each other, in front of you, in order (like if they were books). That is, we take the first one and prop it up like a book, the second one behind it and so forth. We choose the first chunk from the first dimension, and it merely gives us back the first "book":</p>
<pre><code>>>> a[0,:,:]
array([[0, 1],
[2, 3],
[4, 5],
[6, 7]])
</code></pre>
<p>Now look at the difference between that and the first chunk of the second dimension:</p>
<pre><code>>>> a[:,0,:]
array([[ 0, 1],
[ 8, 9],
[16, 17],
[24, 25]])
</code></pre>
<p>This is like slicing off the top. Imagine shaving off the top. It just so happens that with the array you posted, these are the same!</p>
<p>Now finally, the first chunk of the third dimension: </p>
<pre><code>>>> a[:,:,0]
array([[ 0, 2, 4, 6],
[ 8, 10, 12, 14],
[16, 18, 20, 22],
[24, 26, 28, 30]])
</code></pre>
<p>This is like slicing what you have in front of you in half - imagine a karate-chop.</p>
<p>Here's a (very crude) image (drawn on my laptop...sorry).
<a href="http://i.stack.imgur.com/E29zE.png" rel="nofollow"><img src="http://i.stack.imgur.com/E29zE.png" alt="enter image description here"></a></p>
| 2 | 2016-08-17T05:52:04Z | [
"python",
"arrays",
"numpy",
"matrix"
] |
how to read the nested list in csv file using pandas like a list | 38,988,909 | <p>I have scraped the data from a site "itjuzi.com",and store nested list in csv file, and read it with pandas .But now the how to read the unicode string or nested list like a list ? and encoding ?</p>
<p><a href="http://i.stack.imgur.com/gTx44.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/gTx44.jpg" alt="enter image description here"></a></p>
<p>the code is "pd.read_csv('/root/code/company_info.csv',encoding='utf-8')"</p>
<p>sample of source data</p>
<p>"[[u'\u5b5f\u51e1\u5b87', u'\u521b\u59cb\u4eba', u'\u963f\u72fc\u5de5\u4f5c\u5ba4\u521b\u59cb\u4eba\u517cCEO', u'<a href="http://www.itjuzi.com/person/29395" rel="nofollow">http://www.itjuzi.com/person/29395</a>']]</p>
<p>all source data</p>
<p><a href="http://7rf31y.com1.z0.glb.clouddn.com/company_info.csv" rel="nofollow">http://7rf31y.com1.z0.glb.clouddn.com/company_info.csv</a></p>
| -3 | 2016-08-17T05:45:47Z | 39,016,774 | <p>The unicode data is there, it's just not rendered:</p>
<pre><code>$ print(u'[\u9e64\u5e74\u5802\u4e2d\u533b\u9662]')
[鹤年å ä¸å»é¢]
</code></pre>
<p>Regarding your list of lists you need to adjust your spider code. By default scrapy ItemLoaders and even Selector's <code>eextract()</code> method returns a list of values, even if there is only one value in it.</p>
<p>To resolve that just make sure the values are not lists:</p>
<pre><code>from scrapy.loader.processors import TakeFirst
from scrapy.loader import ItemLoader
def parse(self, response):
# you can use .extract_first() function
item = dict()
item['name'] = response.xpath('//div').extract_first()
yield item
# or you can use itemloader
class MyItemLoader(scrapy.loaders.ItemLoader):
name_out = TakeFirst()
loader = MyItemLoader(selector=response)
loader.add_xpath('name', '//div')
yield loader.load_item()
</code></pre>
| -1 | 2016-08-18T11:14:45Z | [
"python",
"csv",
"pandas",
"scrapy",
"nested-lists"
] |
django unit test for exceptions | 38,988,968 | <p>i am working in a django project and writing services to facilitate apis.in the services , i have class and class methods like this,</p>
<pre><code>class ProductService(object):
def delete_product(self, product_id, deleting_user):
try:
product = Product.objects.get(pk=product_id)
except Product.DoesNotExist:
raise ObjectDoesNotExist(_('no product found for this id {}'.format(product_id)))
try:
deleting_user = Customer.objects.get(owner=deleting_user)
except Customer.DoesNotExist:
raise ValidationError(_('No owner found for this deleting user'))
</code></pre>
<p>i have write following unit test for this method,</p>
<pre><code>def setUp(self):
self.product_service = ProductService()
self.wrong_id = 0
self.right_id = 1
self.right_user = _user
self.wrong_user = wrong_user
def test_raise_does_not_exist_error_for_wrong_product_id(self):
with self.assertRaises(ObjectDoesNotExist) as e:
self.product_service.delete_product(
self.product_id=self.wrong_id,
user=self.right_user
)
self.assertEqual(e.exception.message, 'no product found for this id {}'.format(wrong_id))
def test_raise_validtaion_error_for_wrong_deleting_user(self):
with self.assertRaises(ObjectDoesNotExist) as e:
self.product_service.delete_product(
self.product_id=self.right_id,
user=self.wrong_user
)
self.assertEqual(e.exception.message, 'No owner found for this deleting user')
</code></pre>
<p>so far so good, all the tests are OK! </p>
<p>but,say i have lots of test cases like this .that is, testing the 'errors' and if in future i have to change the error messages, then i have to change the test cases also, which could be a MESS, but on the other hand i also need to test the <code>errors</code> appropiately.</p>
<p>question is, how can i test the exceptions for different scenario?because the way i am testing, though it is ok for now,but for the future,it could be a mess,so i need some suggestions from you guys to handle this situation in an efficient way . </p>
| 0 | 2016-08-17T05:50:35Z | 38,989,108 | <p>We are using Enum for this case:</p>
<pre><code>class ProductErrors(Enum):
not_found = "Product {} not found"
doesnt_exist = "Product {} doesn't exist"
</code></pre>
<p>This will allow you to use this enum in your tests and check it like that:</p>
<pre><code>def test_raise_does_not_exist_error_for_wrong_product_id(self):
with self.assertRaises(ObjectDoesNotExist) as e:
self.product_service.delete_product(
self.product_id=self.wrong_id,
user=self.right_user
)
self.assertEqual(e.exception.message, ProductErrors.not_found.value.format(wrong_id))
</code></pre>
| 0 | 2016-08-17T06:02:06Z | [
"python",
"django",
"unit-testing"
] |
django unit test for exceptions | 38,988,968 | <p>i am working in a django project and writing services to facilitate apis.in the services , i have class and class methods like this,</p>
<pre><code>class ProductService(object):
def delete_product(self, product_id, deleting_user):
try:
product = Product.objects.get(pk=product_id)
except Product.DoesNotExist:
raise ObjectDoesNotExist(_('no product found for this id {}'.format(product_id)))
try:
deleting_user = Customer.objects.get(owner=deleting_user)
except Customer.DoesNotExist:
raise ValidationError(_('No owner found for this deleting user'))
</code></pre>
<p>i have write following unit test for this method,</p>
<pre><code>def setUp(self):
self.product_service = ProductService()
self.wrong_id = 0
self.right_id = 1
self.right_user = _user
self.wrong_user = wrong_user
def test_raise_does_not_exist_error_for_wrong_product_id(self):
with self.assertRaises(ObjectDoesNotExist) as e:
self.product_service.delete_product(
self.product_id=self.wrong_id,
user=self.right_user
)
self.assertEqual(e.exception.message, 'no product found for this id {}'.format(wrong_id))
def test_raise_validtaion_error_for_wrong_deleting_user(self):
with self.assertRaises(ObjectDoesNotExist) as e:
self.product_service.delete_product(
self.product_id=self.right_id,
user=self.wrong_user
)
self.assertEqual(e.exception.message, 'No owner found for this deleting user')
</code></pre>
<p>so far so good, all the tests are OK! </p>
<p>but,say i have lots of test cases like this .that is, testing the 'errors' and if in future i have to change the error messages, then i have to change the test cases also, which could be a MESS, but on the other hand i also need to test the <code>errors</code> appropiately.</p>
<p>question is, how can i test the exceptions for different scenario?because the way i am testing, though it is ok for now,but for the future,it could be a mess,so i need some suggestions from you guys to handle this situation in an efficient way . </p>
| 0 | 2016-08-17T05:50:35Z | 38,989,257 | <p>If I understand correctly, you are worried about the lot of repetitive code, which would make it hard to maintain the tests should anything change (e.g.: the method's signature accepting a new parameter, etc.).</p>
<p>Introducing a helper method might help (be careful not to create too many helper methods that use each other, as then the test code would become hard to follow), e.g.:</p>
<pre><code>def test_raise_validtaion_error_for_wrong_deleting_user(self):
self.assert_delete_product_raises_error(
exception_cls=ObjectDoesNotExist,
error_message='No owner found for this deleting user',
product_id=self.right_id,
user=self.wrong_user
)
def assert_delete_product_raises_error(self, exception_cls, error_message, **delete_product_kwargs):
with self.assertRaises(exception_cls) as raised:
self.product_service.delete_product(**delete_product_kwargs)
self.assertEqual(error_message, raised.exception.message)
</code></pre>
<p>This way should something change for the underlying method (e.g.: a new, required argument, that is not relevant for these tests, it can be added as a default in the helper method, and the actual tests would stay stable. </p>
<p>But as said above, avoid having too many helper methods and default values - if there are a lot of them, consider refactoring the test class into multiple test classes.</p>
| 0 | 2016-08-17T06:12:24Z | [
"python",
"django",
"unit-testing"
] |
django unit test for exceptions | 38,988,968 | <p>i am working in a django project and writing services to facilitate apis.in the services , i have class and class methods like this,</p>
<pre><code>class ProductService(object):
def delete_product(self, product_id, deleting_user):
try:
product = Product.objects.get(pk=product_id)
except Product.DoesNotExist:
raise ObjectDoesNotExist(_('no product found for this id {}'.format(product_id)))
try:
deleting_user = Customer.objects.get(owner=deleting_user)
except Customer.DoesNotExist:
raise ValidationError(_('No owner found for this deleting user'))
</code></pre>
<p>i have write following unit test for this method,</p>
<pre><code>def setUp(self):
self.product_service = ProductService()
self.wrong_id = 0
self.right_id = 1
self.right_user = _user
self.wrong_user = wrong_user
def test_raise_does_not_exist_error_for_wrong_product_id(self):
with self.assertRaises(ObjectDoesNotExist) as e:
self.product_service.delete_product(
self.product_id=self.wrong_id,
user=self.right_user
)
self.assertEqual(e.exception.message, 'no product found for this id {}'.format(wrong_id))
def test_raise_validtaion_error_for_wrong_deleting_user(self):
with self.assertRaises(ObjectDoesNotExist) as e:
self.product_service.delete_product(
self.product_id=self.right_id,
user=self.wrong_user
)
self.assertEqual(e.exception.message, 'No owner found for this deleting user')
</code></pre>
<p>so far so good, all the tests are OK! </p>
<p>but,say i have lots of test cases like this .that is, testing the 'errors' and if in future i have to change the error messages, then i have to change the test cases also, which could be a MESS, but on the other hand i also need to test the <code>errors</code> appropiately.</p>
<p>question is, how can i test the exceptions for different scenario?because the way i am testing, though it is ok for now,but for the future,it could be a mess,so i need some suggestions from you guys to handle this situation in an efficient way . </p>
| 0 | 2016-08-17T05:50:35Z | 38,989,718 | <p>Now that I understand the original question that the goal is to allow changing the error text without having the tests break, I suggest to use <a href="https://docs.djangoproject.com/en/1.10/topics/i18n/translation/" rel="nofollow">translations</a>. Instead of the full English text of the error, just use keys/codenames. I.e.: instead of <code>_('No owner found for this deleting user'))</code> use <code>_('product_delete_error_no_owner_found')</code> and translate the actual texts outside in the PO files. </p>
<p>Granted, this can lead to other problems (need to make sure that all your translation strings are actually translated, the dynamic content (variables) are not missed out during translation, and that all translation files are correctly deployed), but it would make the tests stable in the way the question desires it</p>
| 0 | 2016-08-17T06:40:25Z | [
"python",
"django",
"unit-testing"
] |
Get array row and column number according to values in python | 38,988,974 | <p>For example I have a <code>5*5 np.array</code> like this:</p>
<pre><code>a=[[1,2,3,4,5],
[6,7,8,9,10],
[11,12,13,14,15],
[16,17,18,19,20],
[21,22,23,24,25]]
</code></pre>
<p>if I want to get the range of row and column where <code>number<=15</code>, how can I do this?</p>
<p>On the contrary, if I know the range of row and column, like <code>i</code> in <code>xrange(1,4)</code> and <code>j</code> in <code>xrange(1,4)</code>, how can I get the number like:</p>
<pre><code>[[7,8,9],
[12,13,14],
[17,18,19]]
</code></pre>
| 1 | 2016-08-17T05:51:10Z | 38,989,212 | <p>To get the range based on a condition, you can either apply the condition directly, or use <a href="https://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.where.html" rel="nofollow"><code>np.where</code></a> :</p>
<pre><code>>>> a
array([[ 1, 2, 3, 4, 5],
[ 6, 7, 8, 9, 10],
[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20],
[21, 22, 23, 24, 25]])
>>> a < 15
array([[ True, True, True, True, True],
[ True, True, True, True, True],
[ True, True, True, True, False],
[False, False, False, False, False],
[False, False, False, False, False]], dtype=bool)
>>> np.where(a < 15)
(array([0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2]),
array([0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3]))
</code></pre>
<p>In the latter case, the return value is a tuple of the matching indices.</p>
<p>To achieve the opposite operation, you can simply slice your array :</p>
<pre><code>>>> ar[1:4, 1:4]
array([[ 7, 8, 9],
[12, 13, 14],
[17, 18, 19]])
</code></pre>
| 0 | 2016-08-17T06:09:19Z | [
"python",
"arrays",
"numpy"
] |
Copy / paste JetBrains PyCharm behavior | 38,988,979 | <p>I'm new to PyCharm and cannot understand it's <strong>copy/paste</strong> behavior -
If i copy <code>code('foobar')</code> and insert it <strong>inside</strong> code i've got</p>
<pre><code>code-code-codefoobarcode-code
</code></pre>
<p>and it's right as for me, but if i paste <strong>'foobar'</strong> at the end of line i've got</p>
<pre><code>foobar code-code-code-code
</code></pre>
<p>e.g. it appears at begining of line. Is it a bug or a feature?) Can I change editor's behaviour?</p>
<p>I'm using PyCharm 145.597.11</p>
| -1 | 2016-08-17T05:51:45Z | 38,992,262 | <p>The behavior I was confused of difference between "paste simple" and "paste".
I've found keymap editor and edited shortcuts. Thanks.</p>
| 1 | 2016-08-17T09:02:04Z | [
"python",
"pycharm",
"jetbrains"
] |
Index error: String out of range, but it shouldn't be going out of range? | 38,989,032 | <p>Alright so I am making an encoder/decoder and currently I'm testing to see if my idea will work, but I keep getting the error telling me my string index is out of range when it shouldn't be going out of range in the first place.</p>
<pre><code>message = "abc"
#Should come out as 212223
translated = ' '
n = 1
while n >= 0:
t = message[n]
if t == 'a':
translated = translated + '21'
elif t == 'b':
translated = translated + '22'
elif t == 'c':
translated = translated + '23'
while n <= len(message):
n = n + 1
print(translated)
</code></pre>
<p>It makes perfect sense to me so I had a hard time searching for appropriate help that solves for what I am doing, so can I have some help? A link, a solution, what I'm doing wrong and how to fix it? Thanks</p>
| 0 | 2016-08-17T05:56:04Z | 38,989,115 | <pre><code>n = 0
while n >= 0:
</code></pre>
<p>You have an infinite loop as you keep on incrementing <code>n</code>.
At some point <code>message[n]</code> will get out of range.</p>
<p>You should move the <code>while n <= len(message):</code> to be your main loop instead of your current one.</p>
<p>A better way will be to iterate directly over <code>message</code> with a <code>for</code> loop:</p>
<pre><code>for t in message:
if t == 'a':
translated = translated + '21'
elif t == 'b':
translated = translated + '22'
elif t == 'c':
translated = translated + '23'
</code></pre>
| 3 | 2016-08-17T06:02:30Z | [
"python",
"python-3.x",
"encryption"
] |
Index error: String out of range, but it shouldn't be going out of range? | 38,989,032 | <p>Alright so I am making an encoder/decoder and currently I'm testing to see if my idea will work, but I keep getting the error telling me my string index is out of range when it shouldn't be going out of range in the first place.</p>
<pre><code>message = "abc"
#Should come out as 212223
translated = ' '
n = 1
while n >= 0:
t = message[n]
if t == 'a':
translated = translated + '21'
elif t == 'b':
translated = translated + '22'
elif t == 'c':
translated = translated + '23'
while n <= len(message):
n = n + 1
print(translated)
</code></pre>
<p>It makes perfect sense to me so I had a hard time searching for appropriate help that solves for what I am doing, so can I have some help? A link, a solution, what I'm doing wrong and how to fix it? Thanks</p>
| 0 | 2016-08-17T05:56:04Z | 38,989,129 | <p>Here:</p>
<pre><code>while n <= len(message):
n = n + 1
</code></pre>
<p>Should need changing to:</p>
<pre><code>while n < len(message):
n = n + 1
</code></pre>
<p>The last index of a string will be <code>len(message) - 1</code>, as indexing starts at 0.
I would just set n to len(message) - 1 instantly instead however.</p>
| 0 | 2016-08-17T06:03:23Z | [
"python",
"python-3.x",
"encryption"
] |
Index error: String out of range, but it shouldn't be going out of range? | 38,989,032 | <p>Alright so I am making an encoder/decoder and currently I'm testing to see if my idea will work, but I keep getting the error telling me my string index is out of range when it shouldn't be going out of range in the first place.</p>
<pre><code>message = "abc"
#Should come out as 212223
translated = ' '
n = 1
while n >= 0:
t = message[n]
if t == 'a':
translated = translated + '21'
elif t == 'b':
translated = translated + '22'
elif t == 'c':
translated = translated + '23'
while n <= len(message):
n = n + 1
print(translated)
</code></pre>
<p>It makes perfect sense to me so I had a hard time searching for appropriate help that solves for what I am doing, so can I have some help? A link, a solution, what I'm doing wrong and how to fix it? Thanks</p>
| 0 | 2016-08-17T05:56:04Z | 38,989,154 | <p>Because at last loop you are using t = message[3]..It is the cause of your error. If you message variable contain "abc" then you can access only t = message[0], t = message[1], t = message[2]. So try this</p>
<pre><code>message = "abc"
#Should come out as 212223
translated = ' '
n = 1
while n >= 0:
t = message[n-1]
if t == 'a':
translated = translated + '21'
elif t == 'b':
translated = translated + '22'
elif t == 'c':
translated = translated + '23'
while n <= len(message):
n = n + 1
print(translated)
</code></pre>
| 0 | 2016-08-17T06:04:28Z | [
"python",
"python-3.x",
"encryption"
] |
Python Avro writer.append doesn't work when a json string is passed as a variable. | 38,989,070 | <p>Avro Schema file: user.avsc</p>
<pre><code>{"namespace": "example.avro",
"type": "record",
"name": "User",
"fields": [
{"name": "TransportProtocol", "type": "string"}
]
}
</code></pre>
<p>Pasting my code snippet that works:-</p>
<pre><code>import json
from avro import schema, datafile, io
import avro.schema
from avro.datafile import DataFileReader, DataFileWriter
from avro.io import DatumReader, DatumWriter
schema = avro.schema.parse(open("user.avsc").read())
writer = DataFileWriter(open("users.avro", "w"), DatumWriter(), schema)
writer.append({"TransportProtocol": "udp"})
writer.close()
</code></pre>
<p>Pasting my code snippet that doesn't work:-</p>
<pre><code>dummy_json = '{"TransportProtocol": "udp"}'
schema = avro.schema.parse(open("user.avsc").read())
writer = DataFileWriter(open("users.avro", "w"), DatumWriter(), schema)
writer.append(dummy_json)
writer.close()
</code></pre>
<p>When I pass the json string as it is in the append function, it words and I get the desired avro output. But if I initialize the json string to a variable and then try to pass that variable in the append function, it doesn't work and throws an error:-</p>
<pre><code>avro.io.AvroTypeException: The datum {"TransportProtocol": "udp"} is not an example of the schema {
</code></pre>
<p>Any help?Thanks</p>
| 0 | 2016-08-17T05:59:29Z | 38,995,511 | <p>I think that might be due to the fact that in your first example you actually pass a dictionary <code>{"TransportProtocol": "udp"}</code>, not a string. But in the second one, you pass a string <code>'{"TransportProtocol": "udp"}'</code>. </p>
<p>Check this out (<a href="http://avro.apache.org/docs/1.7.6/gettingstartedpython.html" rel="nofollow">http://avro.apache.org/docs/1.7.6/gettingstartedpython.html</a>): </p>
<blockquote>
<p>We use DataFileWriter.append to add items to our data file. Avro
records are represented as Python dicts.</p>
</blockquote>
<p>So basically, you can't pass string as a parameter.</p>
| 1 | 2016-08-17T11:34:56Z | [
"python",
"avro",
"writer"
] |
How to Replace' \ ' with' / ' | 38,989,121 | <pre><code>a="D:/R_SVN/hostworkspace/middleware/projects/module/com.ofss.fc.module.ac/src/com/ofss/fc/app\ac\service\writeoffrecovery\ext\WriteoffRecoveryApplicationServiceExtExecutor.java"
b=a.replace('\','/')
print b
</code></pre>
<p>Error: </p>
<pre><code> b=a.replace('\','/')
</code></pre>
<p>SyntaxError: <code>EOL while scanning string literal</code></p>
| 2 | 2016-08-17T06:02:43Z | 38,989,149 | <p>You have to escape the backslash, because it is a special character:</p>
<pre><code> b=a.replace('\\','/')
</code></pre>
| 2 | 2016-08-17T06:04:17Z | [
"python"
] |
How to Replace' \ ' with' / ' | 38,989,121 | <pre><code>a="D:/R_SVN/hostworkspace/middleware/projects/module/com.ofss.fc.module.ac/src/com/ofss/fc/app\ac\service\writeoffrecovery\ext\WriteoffRecoveryApplicationServiceExtExecutor.java"
b=a.replace('\','/')
print b
</code></pre>
<p>Error: </p>
<pre><code> b=a.replace('\','/')
</code></pre>
<p>SyntaxError: <code>EOL while scanning string literal</code></p>
| 2 | 2016-08-17T06:02:43Z | 38,989,328 | <p>As "Backslash notation" is used for "<strong>Escape character</strong>", you have to add <code>\\</code> instead of <code>\</code></p>
<pre><code>a.replace('\\','/')
</code></pre>
| 2 | 2016-08-17T06:16:57Z | [
"python"
] |
How to Replace' \ ' with' / ' | 38,989,121 | <pre><code>a="D:/R_SVN/hostworkspace/middleware/projects/module/com.ofss.fc.module.ac/src/com/ofss/fc/app\ac\service\writeoffrecovery\ext\WriteoffRecoveryApplicationServiceExtExecutor.java"
b=a.replace('\','/')
print b
</code></pre>
<p>Error: </p>
<pre><code> b=a.replace('\','/')
</code></pre>
<p>SyntaxError: <code>EOL while scanning string literal</code></p>
| 2 | 2016-08-17T06:02:43Z | 38,990,087 | <p>In strings <code>\</code> is escape character e.g if there are two \ like <code>\\</code> then first one is escape character.</p>
<p>in <code>b=a.replace('\','/')</code> '\' is read as escape character. so you can replace it with <code>\\</code>. In this case first \ will be escaped and second one will perform operation on string <code>a</code>.</p>
<p><strong>code</strong>:</p>
<pre><code>>>> a="D:/R_SVN/hostworkspace/middleware/projects/module/com.ofss.fc.module.ac/src/com/ofss/fc/app\ac\service\writeoffrecovery\ext\WriteoffRecoveryApplicationServiceExtExecutor.java"
>>> b=a.replace('\\','/')
>>> print b
D:/R_SVN/hostworkspace/middleware/projects/module/com.ofss.fc.module.ac/src/com/ofss/fc/appc/service/writeoffrecovery/ext/WriteoffRecoveryApplicationServiceExtExecutor.java
</code></pre>
| 1 | 2016-08-17T07:01:43Z | [
"python"
] |
How to use a python function from another module | 38,989,150 | <p>I trying to import a module and use a function from that module in my current python file.</p>
<p>I run the nosetests on the parser_tests.py file but it fails with "name 'parse_subject' not defined"</p>
<p>e.g its not finding the parse_subject function which is clearly defined in the parsrer.py file</p>
<p>This is the parsrer file:</p>
<pre><code>def peek(word_list):
if word_list:
word = word_list[0]
return word[0]
else:
return None
#Confirms that the expected word is the right type,
</code></pre>
<p>def match(word_list, expecting):
if word_list:
word = word_list.pop(0)</p>
<pre><code> if word[0] == expecting:
return word
else:
return None
else:
return None
</code></pre>
<p>def skip(word_list, word_type):
while peek(word_list) == word_type:
match(word_list, word_type)</p>
<p>def parse_verb(word_list):
skip(word_list, 'stop')</p>
<pre><code>if peek(word_list) == 'verb':
return match(word_list, 'verb')
else:
raise ParserError("Expected a verb next.")
</code></pre>
<p>def parse_object(word_list):
skip(word_list, 'stop')
next_word = peek(word_list)</p>
<pre><code>if next_word == 'noun':
return match(word_list, 'noun')
elif next_word == 'direction':
return match(word_list, 'direction')
else:
raise ParserError("Expected a noun or direction next.")
</code></pre>
<p>def parse_subject(word_list):
skip(word_list, 'stop')
next_word = peek(word_list)</p>
<pre><code>if next_word == 'noun':
return match(word_list, 'noun')
elif next_word == 'verb':
return ('noun', 'player')
else:
raise ParserError("Expected a verb next.")
</code></pre>
<p>def parse_sentence(word_list):
subj = parse_subject(word_list)
verb = parse_verb(word_list)
obj = parse_object(word_list)</p>
<pre><code>return Sentence(subj, verb, obj)
</code></pre>
<p>This is my tests file</p>
<pre><code>from nose.tools import *
</code></pre>
<p>from nose.tools import assert_equals
import sys
sys.path.append("h:/projects/projectx48/ex48")</p>
<p>import parsrer</p>
<p>def test_subject():
word_list = [('noun', 'bear'), ('verb', 'eat'), ('stop', 'the'), ('noun', 'honey')]
assert_equals(parse_subject(word_list), ('noun','bear'))</p>
| 1 | 2016-08-17T06:04:23Z | 38,989,228 | <h1>Import Module</h1>
<p>You can either import the whole module or you can specifically import that specific function using <strong>from an example keyword</strong>.</p>
<p>For example:</p>
<pre><code>from parser_tests import parse_subject
# and then you can invoke the function.
parse_subject()
</code></pre>
| 0 | 2016-08-17T06:10:40Z | [
"python",
"import",
"module"
] |
How to use a python function from another module | 38,989,150 | <p>I trying to import a module and use a function from that module in my current python file.</p>
<p>I run the nosetests on the parser_tests.py file but it fails with "name 'parse_subject' not defined"</p>
<p>e.g its not finding the parse_subject function which is clearly defined in the parsrer.py file</p>
<p>This is the parsrer file:</p>
<pre><code>def peek(word_list):
if word_list:
word = word_list[0]
return word[0]
else:
return None
#Confirms that the expected word is the right type,
</code></pre>
<p>def match(word_list, expecting):
if word_list:
word = word_list.pop(0)</p>
<pre><code> if word[0] == expecting:
return word
else:
return None
else:
return None
</code></pre>
<p>def skip(word_list, word_type):
while peek(word_list) == word_type:
match(word_list, word_type)</p>
<p>def parse_verb(word_list):
skip(word_list, 'stop')</p>
<pre><code>if peek(word_list) == 'verb':
return match(word_list, 'verb')
else:
raise ParserError("Expected a verb next.")
</code></pre>
<p>def parse_object(word_list):
skip(word_list, 'stop')
next_word = peek(word_list)</p>
<pre><code>if next_word == 'noun':
return match(word_list, 'noun')
elif next_word == 'direction':
return match(word_list, 'direction')
else:
raise ParserError("Expected a noun or direction next.")
</code></pre>
<p>def parse_subject(word_list):
skip(word_list, 'stop')
next_word = peek(word_list)</p>
<pre><code>if next_word == 'noun':
return match(word_list, 'noun')
elif next_word == 'verb':
return ('noun', 'player')
else:
raise ParserError("Expected a verb next.")
</code></pre>
<p>def parse_sentence(word_list):
subj = parse_subject(word_list)
verb = parse_verb(word_list)
obj = parse_object(word_list)</p>
<pre><code>return Sentence(subj, verb, obj)
</code></pre>
<p>This is my tests file</p>
<pre><code>from nose.tools import *
</code></pre>
<p>from nose.tools import assert_equals
import sys
sys.path.append("h:/projects/projectx48/ex48")</p>
<p>import parsrer</p>
<p>def test_subject():
word_list = [('noun', 'bear'), ('verb', 'eat'), ('stop', 'the'), ('noun', 'honey')]
assert_equals(parse_subject(word_list), ('noun','bear'))</p>
| 1 | 2016-08-17T06:04:23Z | 38,989,452 | <p>It is difficult to know exactly how to diagnose your issue without seeing your code, but here's my best guess as to what might help.</p>
<p>First, <a href="https://docs.python.org/2/library/parser.html" rel="nofollow"><code>parser</code></a> is already a builtin module in Python, so you should consider a different name for your <strong>parser.py</strong> file.</p>
<p>Second, you should make sure that the path to the directory in which your <strong>parser.py</strong> file resides can be found in <code>sys.path</code>. You can check this yourself by running this snippet from your <strong>current Python file</strong>:</p>
<pre><code>import sys
for line in sys.path:
print line
</code></pre>
<p>If the directory in which <code>parser.py</code> is found is <em>not</em> included in your <code>path</code>, you can append that path to <code>sys.path</code>, like this:</p>
<pre><code>import sys
sys.path.append("/path/to/your/module")
</code></pre>
<p>Finally, you should make sure that you are importing your function properly in your <strong>current Python file</strong>, like this:</p>
<pre><code>from parser import parser_subject
</code></pre>
| 0 | 2016-08-17T06:25:29Z | [
"python",
"import",
"module"
] |
How to use a python function from another module | 38,989,150 | <p>I trying to import a module and use a function from that module in my current python file.</p>
<p>I run the nosetests on the parser_tests.py file but it fails with "name 'parse_subject' not defined"</p>
<p>e.g its not finding the parse_subject function which is clearly defined in the parsrer.py file</p>
<p>This is the parsrer file:</p>
<pre><code>def peek(word_list):
if word_list:
word = word_list[0]
return word[0]
else:
return None
#Confirms that the expected word is the right type,
</code></pre>
<p>def match(word_list, expecting):
if word_list:
word = word_list.pop(0)</p>
<pre><code> if word[0] == expecting:
return word
else:
return None
else:
return None
</code></pre>
<p>def skip(word_list, word_type):
while peek(word_list) == word_type:
match(word_list, word_type)</p>
<p>def parse_verb(word_list):
skip(word_list, 'stop')</p>
<pre><code>if peek(word_list) == 'verb':
return match(word_list, 'verb')
else:
raise ParserError("Expected a verb next.")
</code></pre>
<p>def parse_object(word_list):
skip(word_list, 'stop')
next_word = peek(word_list)</p>
<pre><code>if next_word == 'noun':
return match(word_list, 'noun')
elif next_word == 'direction':
return match(word_list, 'direction')
else:
raise ParserError("Expected a noun or direction next.")
</code></pre>
<p>def parse_subject(word_list):
skip(word_list, 'stop')
next_word = peek(word_list)</p>
<pre><code>if next_word == 'noun':
return match(word_list, 'noun')
elif next_word == 'verb':
return ('noun', 'player')
else:
raise ParserError("Expected a verb next.")
</code></pre>
<p>def parse_sentence(word_list):
subj = parse_subject(word_list)
verb = parse_verb(word_list)
obj = parse_object(word_list)</p>
<pre><code>return Sentence(subj, verb, obj)
</code></pre>
<p>This is my tests file</p>
<pre><code>from nose.tools import *
</code></pre>
<p>from nose.tools import assert_equals
import sys
sys.path.append("h:/projects/projectx48/ex48")</p>
<p>import parsrer</p>
<p>def test_subject():
word_list = [('noun', 'bear'), ('verb', 'eat'), ('stop', 'the'), ('noun', 'honey')]
assert_equals(parse_subject(word_list), ('noun','bear'))</p>
| 1 | 2016-08-17T06:04:23Z | 38,989,510 | <p>Could it be that there is already a built in function called parser. I am calling one of my locally created parser.py file that I put together instead. </p>
| 0 | 2016-08-17T06:28:45Z | [
"python",
"import",
"module"
] |
Can XSLT be improved further? | 38,989,162 | <p>I have 2 XSLs:</p>
<p><strong>GET ID</strong></p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.1"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:oval="http://oval.mitre.org/XMLSchema/oval-common-5"
xmlns:oval-res="http://oval.mitre.org/XMLSchema/oval-results-5"
xmlns:oval-def="http://oval.mitre.org/XMLSchema/oval-definitions-5"
xmlns:ind-def="http://oval.mitre.org/XMLSchema/oval-definitions-5#independent"
xmlns:unix-def="http://oval.mitre.org/XMLSchema/oval-definitions-5#unix"
xmlns:linux-def="http://oval.mitre.org/XMLSchema/oval-definitions-5#linux"
exclude-result-prefixes="oval oval-def oval-res ind-def unix-def linux-def">
<xsl:output method="text" encoding="utf-8" />
<xsl:template match="/">
<xsl:apply-templates/>
</xsl:template>
<xsl:template match="oval-def:definition">
<xsl:value-of select='@id'/>
<xsl:text>&#xa;</xsl:text>
</xsl:template>
<!-- include to stop leakage from builtin templates -->
<xsl:template match='node()' mode='engine-results'/>
<xsl:template match="text()"/>
</code></pre>
<p><strong>GET TITLE and RESULT</strong></p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.1"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:oval="http://oval.mitre.org/XMLSchema/oval-common-5"
xmlns:oval-res="http://oval.mitre.org/XMLSchema/oval-results-5"
xmlns:oval-def="http://oval.mitre.org/XMLSchema/oval-definitions-5"
xmlns:ind-def="http://oval.mitre.org/XMLSchema/oval-definitions-5#independent"
xmlns:unix-def="http://oval.mitre.org/XMLSchema/oval-definitions-5#unix"
xmlns:linux-def="http://oval.mitre.org/XMLSchema/oval-definitions-5#linux"
exclude-result-prefixes="oval oval-def oval-res ind-def unix-def linux-def">
<xsl:output method="text" encoding="utf-8" />
<xsl:template match="/">
<xsl:apply-templates/>
</xsl:template>
<xsl:template match="oval-def:definition">
<xsl:if test="@id=$defid">
<xsl:value-of select='oval-def:metadata/oval-def:title'/>
<xsl:text>&#xa;</xsl:text>
</xsl:if>
</xsl:template>
<xsl:template match="oval-res:system/oval-res:definitions/oval-res:definition">
<xsl:if test="@definition_id=$defid">
<xsl:value-of select='@result'/>
</xsl:if>
</xsl:template>
<!-- include to stop leakage from builtin templates -->
<xsl:template match='node()' mode='engine-results'/>
<xsl:template match="text()"/>
</xsl:stylesheet>
</code></pre>
<p><strong>Some stats</strong>
The source XML file is approximately 50 MB.
The number of IDs in the source file is 2962.
I am using xsltproc on Linux.</p>
<p>I am using a python program to get the all the IDs from the source XML first. Then, for each ID, collecting title and status from the source XML. This transformation is taking approximately 2 hours on a 4 CPU box with 8 GB of RAM. </p>
<p>My question is, is there something that I could do to improve XSLT further to reduce transformation time?</p>
<p><strong>Sample Source file</strong></p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<oval_results xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:oval="http://oval.mitre.org/XMLSchema/oval-common-5" xmlns="http://oval.mitre.org/XMLSchema/oval-results-5" xsi:schemaLocation="http://oval.mitre.org/XMLSchema/oval-results-5 oval-results-schema.xsd http://oval.mitre.org/XMLSchema/oval-common-5 oval-common-schema.xsd">
<generator>
<oval:product_name>cpe:/a:open-scap:oscap</oval:product_name>
<oval:product_version>1.2.5</oval:product_version>
<oval:schema_version>5.10</oval:schema_version>
<oval:timestamp>2016-08-17T11:43:37</oval:timestamp>
</generator>
<directives>
<definition_true reported="true" content="full"/>
<definition_false reported="true" content="full"/>
<definition_unknown reported="true" content="full"/>
<definition_error reported="true" content="full"/>
<definition_not_evaluated reported="true" content="full"/>
<definition_not_applicable reported="true" content="full"/>
</directives>
<oval_definitions xmlns:oval="http://oval.mitre.org/XMLSchema/oval-common-5" xmlns:unix-def="http://oval.mitre.org/XMLSchema/oval-definitions-5#unix" xmlns:ind-def="http://oval.mitre.org/XMLSchema/oval-definitions-5#independent" xmlns:lin-def="http://oval.mitre.org/XMLSchema/oval-definitions-5#linux" xmlns="http://oval.mitre.org/XMLSchema/oval-definitions-5" xsi:schemaLocation="http://oval.mitre.org/XMLSchema/oval-definitions-5#unix unix-definitions-schema.xsd http://oval.mitre.org/XMLSchema/oval-definitions-5#independent independent-definitions-schema.xsd http://oval.mitre.org/XMLSchema/oval-definitions-5#linux linux-definitions-schema.xsd http://oval.mitre.org/XMLSchema/oval-definitions-5 oval-definitions-schema.xsd http://oval.mitre.org/XMLSchema/oval-common-5 oval-common-schema.xsd">
<generator>
<oval:product_name>Enhanced SCAP Content Editor (eSCAPe)</oval:product_name>
<oval:product_version>1.2.2</oval:product_version>
<oval:schema_version>5.10</oval:schema_version>
<oval:timestamp>2015-09-20T02:13:56</oval:timestamp>
</generator>
<definitions>
<definition id="oval:com.vmware.test.linux:def:3" version="1" class="compliance">
<metadata>
<title>Rule 3 - /etc/passwd file is group-owned by root</title>
<affected family="unix">
<platform>cpe:/o:sles11:linux</platform>
</affected>
<description>This rule verifies that /etc/passwd file is group-owned by root.</description>
</metadata>
<criteria comment="None">
<criterion test_ref="oval:com.vmware.test.linux:tst:3" comment="This rule verifies that /etc/passwd file is group-owned by root."/>
</criteria>
</definition>
<definition id="oval:com.vmware.test.linux:def:2" version="1" class="compliance">
<metadata>
<title>Rule 2 - /etc/passwd file is owned by root</title>
<affected family="unix">
<platform>cpe:/o:sles11:linux</platform>
</affected>
<description>This rule verifies that /etc/passwd file is owned by root.</description>
</metadata>
<criteria comment="None">
<criterion test_ref="oval:com.vmware.test.linux:tst:2" comment="This rule verifies that /etc/passwd file is owned by root."/>
</criteria>
</definition>
<definition id="oval:com.vmware.test.linux:def:1" version="1" class="compliance">
<metadata>
<title>Rule 1 - /etc/passwd file has permissions of 644 or more restrictive</title>
<affected family="unix">
<platform>cpe:/o:sles11:linux</platform>
</affected>
<description>This rule verifies that /etc/passwd file has permissions of 644 or more restrictive.</description>
</metadata>
<criteria comment="None">
<criterion test_ref="oval:com.vmware.test.linux:tst:1" comment="This rule verifies that /etc/passwd file has permissions of 644 or more restrictive."/>
</criteria>
</definition>
</definitions>
<tests>
<unix-def:file_test id="oval:com.vmware.test.linux:tst:3" version="1" check="all" comment="Default comment, please change">
<unix-def:object object_ref="oval:com.vmware.test.linux:obj:1"/>
<unix-def:state state_ref="oval:com.vmware.test.linux:ste:3"/>
</unix-def:file_test>
<unix-def:file_test id="oval:com.vmware.test.linux:tst:2" version="1" check="all" comment="This rule verifies that /etc/passwd file is owned by root.">
<unix-def:object object_ref="oval:com.vmware.test.linux:obj:1"/>
<unix-def:state state_ref="oval:com.vmware.test.linux:ste:2"/>
</unix-def:file_test>
<unix-def:file_test id="oval:com.vmware.test.linux:tst:1" version="1" check="all" comment="This rule verifies that /etc/passwd file has permissions of 644 or more restrictive.">
<unix-def:object object_ref="oval:com.vmware.test.linux:obj:1"/>
<unix-def:state state_ref="oval:com.vmware.test.linux:ste:1"/>
</unix-def:file_test>
</tests>
<objects>
<unix-def:file_object id="oval:com.vmware.test.linux:obj:1" version="1" comment="/etc/passwd file">
<unix-def:filepath>/etc/passwd</unix-def:filepath>
</unix-def:file_object>
</objects>
<states>
<unix-def:file_state id="oval:com.vmware.test.linux:ste:3" version="1" comment="This rule verifies that /etc/passwd file is group-owned by root.">
<unix-def:group_id datatype="int">0</unix-def:group_id>
</unix-def:file_state>
<unix-def:file_state id="oval:com.vmware.test.linux:ste:2" version="1" comment="This rule verifies that /etc/passwd file is owned by root.">
<unix-def:user_id datatype="int">0</unix-def:user_id>
</unix-def:file_state>
<unix-def:file_state id="oval:com.vmware.test.linux:ste:1" version="1" comment="This rule verifies that /etc/passwd file has permissions of 644 or more restrictive.">
<unix-def:uexec datatype="boolean">false</unix-def:uexec>
<unix-def:gwrite datatype="boolean">false</unix-def:gwrite>
<unix-def:gexec datatype="boolean">false</unix-def:gexec>
<unix-def:owrite datatype="boolean">false</unix-def:owrite>
<unix-def:oexec datatype="boolean">false</unix-def:oexec>
</unix-def:file_state>
</states>
</oval_definitions>
<results>
<system>
<definitions>
<definition definition_id="oval:com.vmware.test.linux:def:3" result="true" version="1">
<criteria operator="AND" result="true">
<criterion test_ref="oval:com.vmware.test.linux:tst:3" version="1" result="true"/>
</criteria>
</definition>
<definition definition_id="oval:com.vmware.test.linux:def:2" result="true" version="1">
<criteria operator="AND" result="true">
<criterion test_ref="oval:com.vmware.test.linux:tst:2" version="1" result="true"/>
</criteria>
</definition>
<definition definition_id="oval:com.vmware.test.linux:def:1" result="true" version="1">
<criteria operator="AND" result="true">
<criterion test_ref="oval:com.vmware.test.linux:tst:1" version="1" result="true"/>
</criteria>
</definition>
</definitions>
<tests>
<test test_id="oval:com.vmware.test.linux:tst:1" version="1" check="all" result="true">
<tested_item item_id="1312221" result="true"/>
</test>
<test test_id="oval:com.vmware.test.linux:tst:2" version="1" check="all" result="true">
<tested_item item_id="1312221" result="true"/>
</test>
<test test_id="oval:com.vmware.test.linux:tst:3" version="1" check="all" result="true">
<tested_item item_id="1312221" result="true"/>
</test>
</tests>
<oval_system_characteristics xmlns:oval="http://oval.mitre.org/XMLSchema/oval-common-5" xmlns:unix-sys="http://oval.mitre.org/XMLSchema/oval-system-characteristics-5#unix" xmlns:ind-sys="http://oval.mitre.org/XMLSchema/oval-system-characteristics-5#independent" xmlns:lin-sys="http://oval.mitre.org/XMLSchema/oval-system-characteristics-5#linux" xmlns="http://oval.mitre.org/XMLSchema/oval-system-characteristics-5" xsi:schemaLocation="http://oval.mitre.org/XMLSchema/oval-system-characteristics-5 oval-system-characteristics-schema.xsd http://oval.mitre.org/XMLSchema/oval-system-characteristics-5#independent independent-system-characteristics-schema.xsd http://oval.mitre.org/XMLSchema/oval-system-characteristics-5#unix unix-system-characteristics-schema.xsd http://oval.mitre.org/XMLSchema/oval-system-characteristics-5#linux linux-system-characteristics-schema.xsd http://oval.mitre.org/XMLSchema/oval-common-5 oval-common-schema.xsd">
<generator>
<oval:product_name>cpe:/a:open-scap:oscap</oval:product_name>
<oval:schema_version>5.10</oval:schema_version>
<oval:timestamp>2016-08-17T11:43:36</oval:timestamp>
</generator>
<system_info>
<os_name>Linux</os_name>
<os_version>#1 SMP Thu Mar 26 10:55:49 UTC 2015 (0e3c7c8)</os_version>
<architecture>x86_64</architecture>
<primary_host_name>vROPS_6-1</primary_host_name>
<interfaces>
<interface>
<interface_name>lo</interface_name>
<ip_address>127.0.0.1</ip_address>
<mac_address>00:00:00:00:00:00</mac_address>
</interface>
<interface>
<interface_name>lo</interface_name>
<ip_address>127.0.0.2</ip_address>
<mac_address>00:00:00:00:00:00</mac_address>
</interface>
<interface>
<interface_name>eth0</interface_name>
<ip_address>10.112.56.130</ip_address>
<mac_address>00:50:56:93:61:59</mac_address>
</interface>
<interface>
<interface_name>lo</interface_name>
<ip_address>::1</ip_address>
<mac_address>00:00:00:00:00:00</mac_address>
</interface>
<interface>
<interface_name>eth0</interface_name>
<ip_address>fe80::250:56ff:fe93:6159</ip_address>
<mac_address>00:50:56:93:61:59</mac_address>
</interface>
<interface>
<interface_name>sit0</interface_name>
<ip_address>::10.112.56.130</ip_address>
<mac_address>00:00:00:00:00:00</mac_address>
</interface>
<interface>
<interface_name>sit0</interface_name>
<ip_address>::127.0.0.2</ip_address>
<mac_address>00:00:00:00:00:00</mac_address>
</interface>
<interface>
<interface_name>sit0</interface_name>
<ip_address>::127.0.0.1</ip_address>
<mac_address>00:00:00:00:00:00</mac_address>
</interface>
</interfaces>
</system_info>
<collected_objects>
<object id="oval:com.vmware.test.linux:obj:1" version="1" flag="complete">
<reference item_ref="1312221"/>
</object>
</collected_objects>
<system_data>
<unix-sys:file_item id="1312221" status="exists">
<unix-sys:filepath>/etc/passwd</unix-sys:filepath>
<unix-sys:path>/etc</unix-sys:path>
<unix-sys:filename>passwd</unix-sys:filename>
<unix-sys:type>regular</unix-sys:type>
<unix-sys:group_id datatype="int">0</unix-sys:group_id>
<unix-sys:user_id datatype="int">0</unix-sys:user_id>
<unix-sys:a_time datatype="int">1471360413</unix-sys:a_time>
<unix-sys:c_time datatype="int">1471360395</unix-sys:c_time>
<unix-sys:m_time datatype="int">1463992525</unix-sys:m_time>
<unix-sys:size datatype="int">1254</unix-sys:size>
<unix-sys:suid datatype="boolean">false</unix-sys:suid>
<unix-sys:sgid datatype="boolean">false</unix-sys:sgid>
<unix-sys:sticky datatype="boolean">false</unix-sys:sticky>
<unix-sys:uread datatype="boolean">true</unix-sys:uread>
<unix-sys:uwrite datatype="boolean">true</unix-sys:uwrite>
<unix-sys:uexec datatype="boolean">false</unix-sys:uexec>
<unix-sys:gread datatype="boolean">true</unix-sys:gread>
<unix-sys:gwrite datatype="boolean">false</unix-sys:gwrite>
<unix-sys:gexec datatype="boolean">false</unix-sys:gexec>
<unix-sys:oread datatype="boolean">true</unix-sys:oread>
<unix-sys:owrite datatype="boolean">false</unix-sys:owrite>
<unix-sys:oexec datatype="boolean">false</unix-sys:oexec>
<unix-sys:has_extended_acl datatype="boolean">false</unix-sys:has_extended_acl>
</unix-sys:file_item>
</system_data>
</oval_system_characteristics>
</system>
</results>
</oval_results>
</code></pre>
<p><strong>Output of Python program</strong></p>
<pre><code>[
{
"Status": "true",
"Title": "Rule 3 - /etc/passwd file is group-owned by root",
"RuleID": "oval:com.vmware.test.linux:def:3"
},
{
"Status": "true",
"Title": "Rule 2 - /etc/passwd file is owned by root",
"RuleID": "oval:com.vmware.test.linux:def:2"
},
{
"Status": "true",
"Title": "Rule 1 - /etc/passwd file has permissions of 644 or more restrictive",
"RuleID": "oval:com.vmware.test.linux:def:1"
}
]
</code></pre>
| 0 | 2016-08-17T06:05:05Z | 38,990,027 | <p>Would something like this work for you?</p>
<p><strong>XSLT 1.0</strong></p>
<pre><code><xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:oval-res="http://oval.mitre.org/XMLSchema/oval-results-5"
xmlns:oval-def="http://oval.mitre.org/XMLSchema/oval-definitions-5"
exclude-result-prefixes="oval-def oval-res">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:key name="result" match="oval-res:definition" use="@definition_id" />
<xsl:template match="/oval-res:oval_results">
<output>
<xsl:for-each select="oval-def:oval_definitions/oval-def:definitions/oval-def:definition">
<def>
<RuleID>
<xsl:value-of select="@id" />
</RuleID>
<Title>
<xsl:value-of select="oval-def:metadata/oval-def:title"/>
</Title>
<Status>
<xsl:value-of select="key('result', @id)/@result"/>
</Status>
</def>
</xsl:for-each>
</output>
</xsl:template>
</xsl:stylesheet>
</code></pre>
<p>For ease of testing, I have made this return an XML result. Applied to your input example, the result will be:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<output>
<def>
<RuleID>oval:com.vmware.test.linux:def:3</RuleID>
<Title>Rule 3 - /etc/passwd file is group-owned by root</Title>
<Status>true</Status>
</def>
<def>
<RuleID>oval:com.vmware.test.linux:def:2</RuleID>
<Title>Rule 2 - /etc/passwd file is owned by root</Title>
<Status>true</Status>
</def>
<def>
<RuleID>oval:com.vmware.test.linux:def:1</RuleID>
<Title>Rule 1 - /etc/passwd file has permissions of 644 or more restrictive</Title>
<Status>true</Status>
</def>
</output>
</code></pre>
| 1 | 2016-08-17T06:58:07Z | [
"python",
"xml",
"xslt"
] |
Pandas plot, combine two plots | 38,989,178 | <p>Currently I have 3 plots that I am plotting in the 2x2 subplots. It looks like this:</p>
<pre><code>fig, axes = plt.subplots(nrows=2, ncols=2)
df1.plot('type_of_plot', ax=axes[0, 0]);
df2.plot('type_of_plot', ax=axes[0, 1]);
df3.plot('type_of_plot', ax=axes[1, 0]);
</code></pre>
<p>The 4-th subplot is empty, and I would like the 3-rd one to occupy the whole last row.</p>
<p>I tried various combinations of axes for the third subplot. Like <code>axes[1]</code>, <code>axes[1:]</code>, <code>axes[1,:]</code>. But everything results in the error.</p>
<p>So how can I achieve what I want?</p>
| 4 | 2016-08-17T06:06:16Z | 38,989,558 | <p>You can do this : </p>
<pre><code>import matplotlib.pyplot as plt
fig=plt.figure()
a=fig.add_axes((0.05,0.05,0.4,0.4)) # number here are coordinate (left,bottom,width,height)
b=fig.add_axes((0.05,0.5,0.4,0.4))
c=fig.add_axes((0.5,0.05,0.4,0.85))
df1.plot('type_of_plot', ax=a);
df2.plot('type_of_plot', ax=b);
df3.plot('type_of_plot', ax=c);
plt.show()
</code></pre>
<p>see also the <a href="http://matplotlib.org/api/figure_api.html#matplotlib.figure.Figure.add_axes" rel="nofollow">documentation of add_axes</a></p>
<p>The <code>rect</code> coordinate I gave you are not very readable, but you can easily adjust it.</p>
<p>EDIT: Here is what I got : <a href="http://i.stack.imgur.com/jASrf.png" rel="nofollow"><img src="http://i.stack.imgur.com/jASrf.png" alt="enter image description here"></a></p>
| 2 | 2016-08-17T06:31:45Z | [
"python",
"pandas",
"matplotlib"
] |
Export SVM model to PMML using Python | 38,989,272 | <p>I am applying SVM algorithm using Scikit-Learn to predict whether a Customer will opt for a Home Loan or not. I want the model to be exported into PMML format. The features and labels in the dataset are shown below:<br><br>
<strong>Features</strong> <br>1. Frequency of visits <br>2. Response to offers<br>3. Usage of online banking facility<br>4. Number of savings account<br>5. Number of checking account<br>6. Number of checks written<br>7. Number of EFTs done<br>
8. Property acquired<br>
9. Other Loans Behaviour<br>
10. Income<br></p>
<p><strong>Label</strong><br>
Is House Loan <br><br></p>
<p>The model is generated properly, but it can't be exported into PMML. The code is pasted below:<br><br><strong>Code:</strong><br></p>
<pre><code>from sklearn.decomposition import PCA
from sklearn2pmml.decoration import ContinuousDomain
import pandas
import sklearn_pandas
from sklearn.svm import SVC
home_loan = pandas.read_csv('home-loan-dataset.csv')
home_loan = home_loan.drop(['CustID'], axis=1)
home_loan_df = pandas.concat((pandas.DataFrame(home_loan[:], columns = ['Frequencyofvisits','Responsetooffers','UsageofOnlineBankingFacility','Numberofsavingsaccount','Numberofcheckingaccount','Numberofcheckswritten','NumberofEFTsdone','PropertyAcquired','OtherLoansBehaviour','Income']), pandas.DataFrame(home_loan['IsHouseLoan'], columns = ["IsHouseLoan"])), axis = 1)
home_loan_mapper = sklearn_pandas.DataFrameMapper([
(['Frequencyofvisits','Responsetooffers','UsageofOnlineBankingFacility','Numberofsavingsaccount','Numberofcheckingaccount','Numberofcheckswritten','NumberofEFTsdone','PropertyAcquired','OtherLoansBehaviour','Income'], [ContinuousDomain(), PCA(n_components = 3)]),
("IsHouseLoan", None)
])
home_loan = home_loan_df
home_loan_X = home_loan[['Frequencyofvisits','Responsetooffers','UsageofOnlineBankingFacility','Numberofsavingsaccount','Numberofcheckingaccount','Numberofcheckswritten','NumberofEFTsdone','PropertyAcquired','OtherLoansBehaviour','Income']]
home_loan_y = home_loan[['IsHouseLoan']]
# Classify using SVM
home_loan_classifier = SVC()
home_loan_classifier.fit(home_loan_X, home_loan_y.values.ravel())
SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0,
decision_function_shape=None, degree=3, gamma='auto', kernel='rbf',
max_iter=-1, probability=False, random_state=None, shrinking=True,
tol=0.001, verbose=False)
#
# Conversion to PMML
#
from sklearn2pmml import sklearn2pmml
sklearn2pmml(home_loan_classifier, home_loan_mapper, "SVMHomeLoan.pmml", with_repr = True)
</code></pre>
<p><br>The following error is displayed while converting to PMML:<br><br><strong>Error:</strong><br></p>
<pre><code>C:\Python27\python.exe C:/Users/Admin/PycharmProjects/ML-Programs/Bank-Customer-Segmentation/svm-pmml.py
Aug 17, 2016 11:35:01 AM org.jpmml.sklearn.Main run
INFO: Parsing DataFrameMapper PKL..
Aug 17, 2016 11:35:01 AM org.jpmml.sklearn.Main run
INFO: Parsed DataFrameMapper PKL in 30 ms.
Aug 17, 2016 11:35:01 AM org.jpmml.sklearn.Main run
INFO: Converting DataFrameMapper..
Aug 17, 2016 11:35:01 AM org.jpmml.sklearn.Main run
SEVERE: Failed to convert DataFrameMapper
java.lang.IllegalArgumentException: The value of the sklearn2pmml.decoration.ContinuousDomain.data_min_ attribute (null) is not a supported array type
at org.jpmml.sklearn.ClassDictUtil.getArray(ClassDictUtil.java:51)
at sklearn2pmml.decoration.ContinuousDomain.getDataMin(ContinuousDomain.java:111)
at sklearn2pmml.decoration.ContinuousDomain.encodeFeatures(ContinuousDomain.java:50)
at sklearn_pandas.DataFrameMapper.encodeFeatures(DataFrameMapper.java:70)
at org.jpmml.sklearn.Main.run(Main.java:146)
at org.jpmml.sklearn.Main.main(Main.java:107)
Exception in thread "main" java.lang.IllegalArgumentException: The value of the sklearn2pmml.decoration.ContinuousDomain.data_min_ attribute (null) is not a supported array type
at org.jpmml.sklearn.ClassDictUtil.getArray(ClassDictUtil.java:51)
at sklearn2pmml.decoration.ContinuousDomain.getDataMin(ContinuousDomain.java:111)
at sklearn2pmml.decoration.ContinuousDomain.encodeFeatures(ContinuousDomain.java:50)
at sklearn_pandas.DataFrameMapper.encodeFeatures(DataFrameMapper.java:70)
at org.jpmml.sklearn.Main.run(Main.java:146)
at org.jpmml.sklearn.Main.main(Main.java:107)
Traceback (most recent call last):
File "C:/Users/Admin/PycharmProjects/ML-Programs/Bank-Customer-Segmentation/svm-pmml.py", line 52, in <module>
sklearn2pmml(home_loan_classifier, home_loan_mapper, "SVMHomeLoan.pmml", with_repr = True)
File "C:\Python27\lib\site-packages\sklearn2pmml\__init__.py", line 56, in sklearn2pmml
subprocess.check_call(cmd)
File "C:\Python27\lib\subprocess.py", line 540, in check_call
raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError: Command '['java', '-cp', 'C:\\Python27\\lib\\site-packages\\sklearn2pmml\\resources\\guava-19.0.jar;C:\\Python27\\lib\\site-packages\\sklearn2pmml\\resources\\istack-commons-runtime-2.21.jar;C:\\Python27\\lib\\site-packages\\sklearn2pmml\\resources\\jaxb-core-2.2.11.jar;C:\\Python27\\lib\\site-packages\\sklearn2pmml\\resources\\jaxb-runtime-2.2.11.jar;C:\\Python27\\lib\\site-packages\\sklearn2pmml\\resources\\jcommander-1.48.jar;C:\\Python27\\lib\\site-packages\\sklearn2pmml\\resources\\jpmml-converter-1.0.7.jar;C:\\Python27\\lib\\site-packages\\sklearn2pmml\\resources\\jpmml-sklearn-1.0-SNAPSHOT.jar;C:\\Python27\\lib\\site-packages\\sklearn2pmml\\resources\\jpmml-xgboost-1.0.5.jar;C:\\Python27\\lib\\site-packages\\sklearn2pmml\\resources\\pmml-agent-1.2.16.jar;C:\\Python27\\lib\\site-packages\\sklearn2pmml\\resources\\pmml-model-1.2.16.jar;C:\\Python27\\lib\\site-packages\\sklearn2pmml\\resources\\pmml-model-metro-1.2.16.jar;C:\\Python27\\lib\\site-packages\\sklearn2pmml\\resources\\pmml-schema-1.2.16.jar;C:\\Python27\\lib\\site-packages\\sklearn2pmml\\resources\\pyrolite-4.12.jar;C:\\Python27\\lib\\site-packages\\sklearn2pmml\\resources\\serpent-1.12.jar;C:\\Python27\\lib\\site-packages\\sklearn2pmml\\resources\\slf4j-api-1.7.21.jar;C:\\Python27\\lib\\site-packages\\sklearn2pmml\\resources\\slf4j-jdk14-1.7.21.jar', 'org.jpmml.sklearn.Main', '--pkl-estimator-input', 'c:\\users\\Admin\\appdata\\local\\temp\\tmplgmrjq.pkl', '--repr-estimator', "SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0,\n decision_function_shape=None, degree=3, gamma='auto', kernel='rbf',\n max_iter=-1, probability=False, random_state=None, shrinking=True,\n tol=0.001, verbose=False)", '--pkl-mapper-input', 'c:\\users\\Admin\\appdata\\local\\temp\\tmpobahse.pkl', '--repr-mapper', "DataFrameMapper(features=[(['Frequencyofvisits', 'Responsetooffers', 'UsageofOnlineBankingFacility', 'Numberofsavingsaccount', 'Numberofcheckingaccount', 'Numberofcheckswritten', 'NumberofEFTsdone', 'PropertyAcquired', 'OtherLoansBehavior', 'Income100000'], TransformerPipeline(steps=[('continuousdomain', ContinuousDomain(invalid_value_treatment='return_invalid')), ('pca', PCA(copy=True, n_components=3, whiten=False))])), ('IsHouseLoan', None)],\n sparse=False)", '--pmml-output', 'SVMHomeLoan.pmml']' returned non-zero exit status 1
</code></pre>
<p><br>
<strong>What could be the reason ?</strong></p>
| 0 | 2016-08-17T06:13:43Z | 38,989,758 | <p>Obviously, one of your data columns does not meet the expectations of the <code>sklearn2pmml.decoration.ContinuousDomain</code> transformation. It's impossible to say which column, and what is the exact nature of the problem (eg. categorical operational type instead of continuous, wrong numeric data type, <strong>column contains NA values</strong>, etc.) without seeing your data.</p>
<p>You have two options here:</p>
<ol>
<li>Identify the misbehaving column, and fix the data issue so that the <code>ContinuousDomain</code> transformation works OK.</li>
<li>Exclude the <code>ContinuousDomain</code> from the list transformations list.</li>
</ol>
<p>At the moment you're using data pre-processing logic that has been directly copied from sklearn2pmml README.md file. Please re-work it to match you data - it's unlikely that the <code>[ContinuousDomain(), PCA(n_components = 3)]</code> transformation is the right solution for your use case.</p>
<p>Also, this issue is rather specific to the <a href="https://github.com/jpmml/sklearn2pmml" rel="nofollow">sklearn2pmml</a> package. You're likely to get better/faster replies if you opened an issue in sklearn2pmml issue tracker.</p>
| 1 | 2016-08-17T06:42:18Z | [
"python",
"scikit-learn",
"svm",
"pmml"
] |
Padding in Panel and static text wrap in wxpython | 38,989,282 | <p>I would like to have a layout something like this</p>
<p><a href="http://i.stack.imgur.com/NLjCQ.png" rel="nofollow"><img src="http://i.stack.imgur.com/NLjCQ.png" alt="enter image description here"></a></p>
<p>There is a Main Panel just inside the frame with blank padding in the left and right which another Sub Panel located in the middle. A Static Text element located at the top of Sub Panel and it should wrap properly when changing the window size.</p>
<p>My code snippet listed as following</p>
<pre><code>import wx
class MyPanel(wx.Panel):
def __init__(self, parent):
super(MyPanel, self).__init__(parent)
self.hsizer = wx.BoxSizer()
self.hsizer.AddStretchSpacer()
self.panel = wx.Panel(self)
self.panel.SetSize((350, -1))
self.vsizer = wx.BoxSizer(wx.VERTICAL)
label = (
"This is a long scentence that I want it wrapped properly, "
"but it doesn't seem to work at work. "
"I prefer if you guys can give any sugeestions or help. "
"For Long Long Long Long Long scentence."
)
style = wx.ALIGN_LEFT
self.static_text = wx.StaticText(self, label=label, style=style)
self.vsizer.Add(self.static_text, flag=wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border=5)
self.static_text.Wrap(self.panel.Size[0])
self.static_text.SetAutoLayout(True)
self.panel.SetSizer(self.vsizer)
self.hsizer.Add(self.panel, flag=wx.ALIGN_CENTER)
self.hsizer.AddStretchSpacer()
self.SetSizer(self.hsizer)
self.Layout()
print self.Size
print self.panel.Size
if __name__ == '__main__':
app = wx.App()
frame = wx.Frame(None)
sizer = wx.BoxSizer()
sizer.Add(MyPanel(frame), flag=wx.EXPAND)
frame.SetSizer(sizer)
frame.Show()
app.MainLoop()
</code></pre>
<p>Currently, not only the Sub Panel is not located in the middle, but also the text in static text doesn't wrap properly when changing the window size. Any suggestions to make it work?</p>
| 0 | 2016-08-17T06:14:04Z | 39,005,419 | <p>It is often helpful to set some background colours while trying to implement a layout with sizers, that way it's easy to visualize where the boundaries are, and how they behave while resizing things. Another helpful tool is the <a href="https://wiki.wxpython.org/Widget%20Inspection%20Tool" rel="nofollow">Widget Inspection Tool</a>. For example:</p>
<pre class="lang-py prettyprint-override"><code>import wx
class MyPanel(wx.Panel):
def __init__(self, parent):
super(MyPanel, self).__init__(parent)
self.SetBackgroundColour('pink')
self.hsizer = wx.BoxSizer()
self.hsizer.AddStretchSpacer()
self.panel = wx.Panel(self)
self.panel.SetSize((350, -1))
self.panel.SetBackgroundColour('green')
self.vsizer = wx.BoxSizer(wx.VERTICAL)
label = (
"This is a long scentence that I want it wrapped properly, "
"but it doesn't seem to work at work. "
"I prefer if you guys can give any sugeestions or help. "
"For Long Long Long Long Long scentence."
)
style = wx.ALIGN_LEFT
self.static_text = wx.StaticText(self, label=label, style=style)
self.static_text.SetBackgroundColour('yellow')
self.vsizer.Add(self.static_text, flag=wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border=5)
self.static_text.Wrap(self.panel.Size[0])
self.static_text.SetAutoLayout(True)
self.panel.SetSizer(self.vsizer)
self.hsizer.Add(self.panel, flag=wx.ALIGN_CENTER)
self.hsizer.AddStretchSpacer()
self.SetSizer(self.hsizer)
if __name__ == '__main__':
app = wx.App()
frame = wx.Frame(None)
frame.SetBackgroundColour('sky blue')
sizer = wx.BoxSizer()
sizer.Add(MyPanel(frame), flag=wx.EXPAND)
frame.SetSizer(sizer)
frame.Show()
import wx.lib.inspection
wx.lib.inspection.InspectionTool().Show()
app.MainLoop()
</code></pre>
<p>After running that we can see that things don't really match your sketch of the layout, that things like the text don't change size or position when the frame is resized, and that the MyPanel (the pink one) is also not resizing to fill the frame. Also, it appears from the code that you intend the text to be the child of the green panel (self.panel) but looking at the colours at runtime it obviously is not. Looking again at the code we see that it is being created with self as the parent instead of self.panel.</p>
<p>So after a few more tweaks to address those issues, we end up with this code:</p>
<pre class="lang-py prettyprint-override"><code>import wx
class MyPanel(wx.Panel):
def __init__(self, parent):
super(MyPanel, self).__init__(parent)
self.SetBackgroundColour('pink')
self.hsizer = wx.BoxSizer()
self.hsizer.AddStretchSpacer()
self.panel = wx.Panel(self)
self.panel.SetSize((350, -1))
self.panel.SetBackgroundColour('green')
self.vsizer = wx.BoxSizer(wx.VERTICAL)
label = (
"This is a long scentence that I want it wrapped properly, "
"but it doesn't seem to work at work. "
"I prefer if you guys can give any sugeestions or help. "
"For Long Long Long Long Long scentence."
)
style = wx.ALIGN_LEFT
self.static_text = wx.StaticText(self.panel, label=label, style=style)
self.static_text.SetBackgroundColour('yellow')
self.vsizer.Add(self.static_text,
flag=wx.EXPAND | wx.ALL | wx.ALIGN_TOP, border=5)
self.static_text.Wrap(self.panel.Size[0])
self.panel.SetSizer(self.vsizer)
self.hsizer.Add(self.panel, 1, flag=wx.EXPAND)
self.hsizer.AddStretchSpacer()
self.SetSizer(self.hsizer)
if __name__ == '__main__':
app = wx.App()
frame = wx.Frame(None)
frame.SetBackgroundColour('sky blue')
sizer = wx.BoxSizer()
sizer.Add(MyPanel(frame), 1, flag=wx.EXPAND)
frame.SetSizer(sizer)
frame.Show()
import wx.lib.inspection
wx.lib.inspection.InspectionTool().Show()
app.MainLoop()
</code></pre>
<p>Finally, if you want the text to be rewrapped when the size gets narrower than 350 then you'll need to do something like catch EVT_SIZE events and call Wrap again with a different size when needed.</p>
| 2 | 2016-08-17T20:09:34Z | [
"python",
"user-interface",
"layout",
"wxpython",
"wx"
] |
How many times a number appears in succession without a break or change in number python/numpy | 38,989,309 | <p>I need to find the max consecutive number of times a number has appeared. Specifically 1 or 0 . To clarify. </p>
<pre><code>a = [1,0,0,0,1,1,1,1,0,1]
</code></pre>
<p>What I want python to do is count how many times 1 and 0 appeared in succession. </p>
<p>So for 1 the max it appeared in succession is 4 and for 0 the max succession is 3. </p>
<p>what I tried so far</p>
<pre><code>from collections import Counter
import numpy
l = [1, 0, 0, 0, 0, 1, 1]
x = sum(1 for i in l if i % [1])
print
</code></pre>
<p>x</p>
| 1 | 2016-08-17T06:15:59Z | 38,989,521 | <p>You can use <code>groupby</code></p>
<pre><code>from itertools import groupby
max_of_1 = max([i for i in [[key,len(list(group))] for key, group in groupby(a)] if i[0]])[1]
max_of_0 = max([i for i in [[key,len(list(group))] for key, group in groupby(a)] if not i[0]])[1]
</code></pre>
<p><strong>Result</strong></p>
<pre><code>In [1]: max_of_1
Out[1]: 4
In [2]: max_of_0
Out[3]: 3
</code></pre>
| 1 | 2016-08-17T06:30:09Z | [
"python",
"numpy"
] |
I want my board to be printed as a rhombus. So every previous line should have a smaller indentation than the next. How can I do that? | 38,989,403 | <pre><code>global counter
global winner
def initBoard():
global x
global y
x = int(input("Give x size for the board "))
while x < 1 or x > 20:
x = int(input("Please give a valid input (between 1 and 20) "))
y = int(input("Give y size for the board "))
while y < 1 or y > 20:
y = int(input("Please give a valid input (between 1 and 20) "))
i = 0
j = 0
global board
board = [[0 for i in range(x)] for j in range(y)]
def showBoard():
i = 0
j = 0
for i in range(1,1 + y):
for j in range(1,1 + x):
if j % x == 0:
print("[", board [i-1] [j-1], "]", "\n")
else:
print("[", board [i-1] [j-1], "]", end="")
def setPiece():
return 0
def play():
initBoard()
showBoard()
play()
</code></pre>
<p>My code so far. Haven't completed the setPiece function so don't stress about that. Function initBoard asks for user dimensions and initialises the board and the function showBoard is supposed to print the board. It does print it but I don't know how to print it like described on the title</p>
| -1 | 2016-08-17T06:22:10Z | 38,990,768 | <p>I believe this is what you are looking for:</p>
<pre><code>global counter
global winner
def initBoard():
global x
global y
x = int(input("Give x size for the board "))
while x < 1 or x > 20:
x = int(input("Please give a valid input (between 1 and 20) "))
y = int(input("Give y size for the board "))
while y < 1 or y > 20:
y = int(input("Please give a valid input (between 1 and 20) "))
global board
board = [[0 for i in range(x)] for j in range(y)]
def showBoard():
for i in range(1, 1 + y):
for j in range(1, 1 + x):
if j % x == 0:
print("[", board[i-1][j-1], "]", "\n")
print(" " * i*3, end="") # write a space depending on the row without line break
else:
print("[", board[i-1][j-1], "]", end="")
def setPiece():
return 0
def play():
initBoard()
showBoard()
play()
</code></pre>
<p>I used <code>end=""</code> to prevent the line break after the print statement that sets a number of spaces depending on which line you are in. By changing the factor <code>i*3</code> to something else, you can adjust the slope. Ah, and I fixed the formatting. Be sure to read the <a href="https://www.python.org/dev/peps/pep-0008/" rel="nofollow">PEP 8 style guide for Python</a> to achieve readable and consistent code formatting.</p>
| 0 | 2016-08-17T07:40:27Z | [
"python"
] |
Import error flask application | 38,989,454 | <p>I got this error running the application with this command
'python manage.py runserver'</p>
<p>the error</p>
<pre><code>C:\Users\Kamran\Envs\thermos\lib\site-packages\flask_sqlalchemy\__init__.py:800: UserWarning: SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and will be disabled by default in the future. Set it to True to suppress this warning.
warnings.warn('SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and will be disabled by default in the future. Set it to True to suppress this warning.')
Traceback (most recent call last):
File "manage.py", line 1, in <module>
from thermos import app, db
File "E:\Kamran\My Work\Website\Python Flask Tutorial\thermos\thermos\__init__.py", line 13, in <module>
import models
File "E:\Kamran\My Work\Website\Python Flask Tutorial\thermos\thermos\models.py", line 3, in <module>
from thermos import db
ImportError: cannot import name db
</code></pre>
<p>and I have managed my files like this</p>
<p><a href="http://i.stack.imgur.com/U4oyE.png" rel="nofollow"><img src="http://i.stack.imgur.com/U4oyE.png" alt="enter image description here"></a>
<a href="http://i.stack.imgur.com/Ikjbe.png" rel="nofollow"><img src="http://i.stack.imgur.com/Ikjbe.png" alt="enter image description here"></a></p>
<hr>
<p>manage.py</p>
<pre><code>from thermos import app, db
from thermos.models import User
from flask.ext.script import Manager, prompt_bool
manager = Manager(app)
@manager.command
def initdb():
db.create_all()
db.session.add(User(username='Cameron', email='cameron@google.com'))
db.session.add(User(username='Mahshid', email='mahshid@python.org'))
db.session.commit()
print 'Initialized the database'
@manager.command
def dropdb():
if prompt_bool(
'Are you sure you want to lose all your data'):
db.drop_all()
print 'Dropped the database'
if __name__ == '__main__':
manager.run()
</code></pre>
<p><strong>init</strong>.py</p>
<pre><code>import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
basedir = os.path.abspath(os.path.dirname(__file__))
app = Flask(__name__)
app.config['SECRET_KEY'] = 'K\xa5r\x94\xc2"\x06\x14\'\xc1\xe4\xa6\r\x9f\x16\xf9z4hIR\x14g\x1c'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'thermos.db')
app.config['DEBUG'] = True
db = SQLAlchemy(app)
import models
import views
</code></pre>
<p>models.py</p>
<pre><code>from datetime import datetime
from sqlalchemy import desc
from thermos import db
class Bookmark(db.Model):
id = db.Column(db.Integer, primary_key=True)
url = db.Column(db.Text, nullable=False)
date = db.Column(db.DateTime, default=datetime.utcnow)
description = db.Column(db.String(300))
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
@staticmethod
def newest(num):
return Bookmark.query.order_by(desc(Bookmark.date)).limit(num)
def __repr__(self):
return '<Bookmark "{}": "{}">'.format(self.description, self.url)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True)
email = db.Column(db.String(120), unique=True)
bookmarks = db.relationship('Bookmark', backref='user', lazy='dynamic')
def __rep__(self):
return '<User %r>' % self.username
</code></pre>
<p>views.py</p>
<pre><code>from flask import render_template, redirect, url_for, flash
from thermos import app, db
from forms import BookmarkForm
from models import User, Bookmark
def logged_in_user():
return models.User.query.filter_by(username='Cameron').first()
@app.route('/')
@app.route('/index')
def index():
return render_template('index.html', new_bookmarks=models.Bookmark.newest(5))
@app.route('/add', methods = ['GET', 'POST'])
def add():
form = BookmarkForm()
if form.validate_on_submit():
url = form.url.data
description = form.description.data
bm = models.Bookmark(user=logged_in_user(), url=url, description=description)
db.session.add(bm)
db.session.commit()
flash('stored "{}"'.format(description))
return redirect(url_for('index'))
return render_template('add.html', form=form)
@app.errorhandler(404)
def page_not_found(e):
return render_template('404.html'), 404
@app.errorhandler(500)
def page_not_found(e):
return render_template('500.html'), 500
if __name__=='__main__':
app.run(debug=True)
</code></pre>
| -2 | 2016-08-17T06:25:33Z | 38,993,541 | <p>It is not the Cirular Import problem, Its bad addressing the modules</p>
<p>In the views.py</p>
<pre><code>from flask import render_template, redirect, url_for, flash
from thermos import models, app, db
from forms import BookmarkForm
from models import User, Bookmark
</code></pre>
| 0 | 2016-08-17T10:02:54Z | [
"python",
"flask",
"import"
] |
Why I can't instantiate a instance in the same module? | 38,989,481 | <p>Suppose my module is <code>myclass.py</code>, and here is the code:</p>
<pre><code>#!/usr/bin/env python
# coding=utf-8
class A(object):
b = B()
def __init__(self):
pass
class B(object):
pass
</code></pre>
<p>and import it</p>
<pre><code>In [1]: import myclass
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-1-e891426834ac> in <module>()
----> 1 import myclass
/home/python/myclass.py in <module>()
2 # coding=utf-8
3
----> 4 class A(object):
5 b = B()
6 def __init__(self):
/home/python/myclass.py in A()
3
4 class A(object):
----> 5 b = B()
6 def __init__(self):
7 pass
NameError: name 'B' is not defined
</code></pre>
<p>I know that if I define the class B above the class A, it is ok, there is no error. But, I don't want do that, are there any other methods to solve this. And I know that in C, there is function declaration.Thank you!</p>
| 2 | 2016-08-17T06:27:00Z | 38,989,614 | <p>The class definition is a statement. When statement <code>AA</code> is executed, The statement of <code>BB</code> is not executed yet. Therefore, There is no class <code>B</code> yet and you get <code>NameError: name 'B' is not defined</code></p>
<pre><code>class A(object):
b = B() # <== AA
def __init__(self):
pass
class B(object): # <== BB
pass
</code></pre>
<p>To fix it: </p>
<hr>
<p>You can change the order of classes:</p>
<pre><code>class B(object):
pass
class A(object):
b = B()
def __init__(self):
pass
</code></pre>
<hr>
<p>You can move the statement which use the class <code>B</code> to <code>classmethod</code> and call it after the the defintion of class <code>B</code>:</p>
<pre><code>class A(object):
@classmethod
def init(cls):
cls.b = B()
def __init__(self):
pass
class B(object):
pass
A.init()
</code></pre>
| 8 | 2016-08-17T06:34:52Z | [
"python"
] |
Why I can't instantiate a instance in the same module? | 38,989,481 | <p>Suppose my module is <code>myclass.py</code>, and here is the code:</p>
<pre><code>#!/usr/bin/env python
# coding=utf-8
class A(object):
b = B()
def __init__(self):
pass
class B(object):
pass
</code></pre>
<p>and import it</p>
<pre><code>In [1]: import myclass
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-1-e891426834ac> in <module>()
----> 1 import myclass
/home/python/myclass.py in <module>()
2 # coding=utf-8
3
----> 4 class A(object):
5 b = B()
6 def __init__(self):
/home/python/myclass.py in A()
3
4 class A(object):
----> 5 b = B()
6 def __init__(self):
7 pass
NameError: name 'B' is not defined
</code></pre>
<p>I know that if I define the class B above the class A, it is ok, there is no error. But, I don't want do that, are there any other methods to solve this. And I know that in C, there is function declaration.Thank you!</p>
| 2 | 2016-08-17T06:27:00Z | 38,989,669 | <p>It should work if you do it like so:</p>
<pre><code>class A(object):
def __init__(self):
self.b = B()
class B(object):
pass
</code></pre>
<p><strong>EDIT:</strong> You can do it like this if you want to write all the definitions of the class after you have written class A.</p>
<pre><code>class B:
pass
class A(object):
b = B()
def __init__(self):
pass
class B(object):
def __init__(self):
pass
</code></pre>
<p><strong>EDIT 2:</strong> Ignore the above solution, it doesn't work.</p>
| 0 | 2016-08-17T06:38:10Z | [
"python"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.