title
stringlengths 10
172
| question_id
int64 469
40.1M
| question_body
stringlengths 22
48.2k
| question_score
int64 -44
5.52k
| question_date
stringlengths 20
20
| answer_id
int64 497
40.1M
| answer_body
stringlengths 18
33.9k
| answer_score
int64 -38
8.38k
| answer_date
stringlengths 20
20
| tags
sequence |
---|---|---|---|---|---|---|---|---|---|
How to convert a string into a list without including a specific character plus without using replace and split methods? | 39,967,795 | <p>Let's say you have:</p>
<pre><code>x = "1,2,13"
</code></pre>
<p>and you want to achieve:</p>
<pre><code>list = ["1","2","13"]
</code></pre>
<p>Can you do it without the split and replace methods?</p>
<p>What I have tried:</p>
<pre><code>list=[]
for number in x:
if number != ",":
list.append(number)
print(list) # ['1', '2', '1', '3']
</code></pre>
<p>but this works only if its a single digit</p>
| 0 | 2016-10-10T22:36:56Z | 39,967,932 | <p>You could use a regular expression:</p>
<pre><code>>>> import re
>>> re.findall('(\d+)', '123,456')
['123', '456']
</code></pre>
| 2 | 2016-10-10T22:51:52Z | [
"python"
] |
How to make a list in python when the input file has multiple separators? | 39,967,799 | <p>The sample file looks like this:</p>
<pre><code> ['>1\n', 'TCCGGGGGTATC\n', '>2\n', 'TCCGTGGGTATC\n',
'>3\n', 'TCCGTGGGTATC\n', '>4\n', 'TCCGGGGGTATC\n',
'>5\n', 'TCCGTGGGTATC\n', '>6\n', 'TCCGTGGGTATC\n',
'>7\n', 'TCCGTGGGTATC\n', '>8\n', 'TCCGGGGGTATC\n','\n',
'$$$\n', '\n',
'>B1\n', 'ATCGGGGGTATT\n', '>B2\n', 'TT-GTGGGAATC\n',
'>3\n', 'TTCGTGGGAATC\n', '>B4\n', 'TT-GTGGGTATC\n',
'>B5\n', 'TTCGTGGGTATT\n', '>B6\n','TTCGGGGGTATC\n',
'>B7\n', 'TT-GTGGGTATC\n', '>B8\n', 'TTCGGGGGAATC\n',
'>B9\n', 'TTCGGGGGTATC\n','>B10\n', 'TTCGGGGGTATC\n',
'>B42\n', 'TT-GTGGGTATC\n']
</code></pre>
<p>The <code>$$$</code> separates the two sets. I need to use <code>.strip</code> function and remove the <code>\n</code> and all the "headers". </p>
<p>I need to make a list (as below) and replace "-" with Z </p>
<pre><code> [ 'TCCGGGGGTATC','TCCGTGGGTATC','TCCGTGGGTATC', 'TCCGGGGGTATC',
'TCCGTGGGTATC','TCCGTGGGTATC','TCCGTGGGTATC', 'TCCGGGGGTATC',
'ATCGGGGGTATT','TT-GTGGGAATC','TTCGTGGGAATC', 'TT-GTGGGTATC',
'TTCGTGGGTATT','TTCGGGGGTATC','TT-GTGGGTATC', 'TTCGGGGGAATC',
'TTCGGGGGTATC','TTCGGGGGTATC','TT-GTGGGTATC']
</code></pre>
<p>Here is the link to a code (<a href="http://stackoverflow.com/a/39965048/6820344">http://stackoverflow.com/a/39965048/6820344</a>), where a similar question was answered. I tried to modify the code to get the output mentioned above. However, I am unable to have the list without the "$$$". Also, I need a list, not a list of lists. </p>
<pre><code>seq_list = []
for x in lst:
if x.startswith('>'):
seq_list.append([])
continue
x = x.strip()
if x:
seq_list[-1].append(x.replace("-", "Z"))
print(seq_list)
</code></pre>
| 0 | 2016-10-10T22:37:20Z | 39,968,005 | <pre><code>input = ['>1\n', 'TCCGGGGGTATC\n', '>2\n', 'TCCGTGGGTATC\n',
'>3\n', 'TCCGTGGGTATC\n', '>4\n', 'TCCGGGGGTATC\n',
'>5\n', 'TCCGTGGGTATC\n', '>6\n', 'TCCGTGGGTATC\n',
'>7\n', 'TCCGTGGGTATC\n', '>8\n', 'TCCGGGGGTATC\n', '\n',
'$$$\n', '\n',
'>B1\n', 'ATCGGGGGTATT\n', '>B2\n', 'TT-GTGGGAATC\n',
'>3\n', 'TTCGTGGGAATC\n', '>B4\n', 'TT-GTGGGTATC\n',
'>B5\n', 'TTCGTGGGTATT\n', '>B6\n', 'TTCGGGGGTATC\n',
'>B7\n', 'TT-GTGGGTATC\n', '>B8\n', 'TTCGGGGGAATC\n',
'>B9\n', 'TTCGGGGGTATC\n', '>B10\n', 'TTCGGGGGTATC\n',
'>B42\n', 'TT-GTGGGTATC\n']
output = []
for elem in input:
if elem.startswith('>') or \
elem.startswith('$') or \
elem.isspace():
continue
output.append(elem.replace('-', 'Z').strip())
from pprint import pprint
pprint(output, compact=True)
</code></pre>
<p>When the preceding code is run, the following output is the result:</p>
<pre><code>['TCCGGGGGTATC', 'TCCGTGGGTATC', 'TCCGTGGGTATC', 'TCCGGGGGTATC', 'TCCGTGGGTATC',
'TCCGTGGGTATC', 'TCCGTGGGTATC', 'TCCGGGGGTATC', 'ATCGGGGGTATT', 'TTZGTGGGAATC',
'TTCGTGGGAATC', 'TTZGTGGGTATC', 'TTCGTGGGTATT', 'TTCGGGGGTATC', 'TTZGTGGGTATC',
'TTCGGGGGAATC', 'TTCGGGGGTATC', 'TTCGGGGGTATC', 'TTZGTGGGTATC']
</code></pre>
| 1 | 2016-10-10T22:58:57Z | [
"python",
"list",
"append"
] |
How to count number of occurrences of a chracter in a string (list) | 39,967,810 | <p>I'm trying to count the occurrence of each character for any given string input, the occurrences must be output in ascending order( includes numbers and exclamation marks)
I have this for my code so far, i am aware of the Counter function, but it does not output the answer in the format I'd like it to, and I do not know how to format Counter. Instead I'm trying to find away to use the count() to count each character. I've also seen the dictionary function , but I'd be hoping that there is a easier way to do it with count() </p>
<pre><code>from collections import Counter
sentence=input("Enter a sentence b'y: ")
lowercase=sentence.lower()
list1=list(lowercase)
list1.sort()
length=len(list1)
list2=list1.count(list1)
print(list2)
p=Counter(list1)
print(p)
</code></pre>
| 0 | 2016-10-10T22:38:38Z | 39,967,862 | <p>One way to do this would be by removing instances of your sub string and looking at the length...</p>
<pre><code>def nofsub(s,ss):
return((len(s)-len(s.replace(ss,"")))/len(ss))
</code></pre>
<p>alternatively you could use re or regular expressions,</p>
<pre><code>from re import *
def nofsub(s,ss):
return(len(findall(compile(ss), s)))
</code></pre>
<p>finally you could count them manually,</p>
<pre><code>def nofsub(s,ss):
return(len([k for n,k in enumerate(s) if s[n:n+len(ss)]==ss]))
</code></pre>
<p>Test any of the three with...</p>
<pre><code>>>> nofsub("asdfasdfasdfasdfasdf",'asdf')
5
</code></pre>
<p>Now that you can count any given character you can iterate through your string's unique characters and apply a counter for each unique character you find. Then sort and print the result.</p>
<pre><code>def countChars(s):
s = s.lower()
d = {}
for k in set(s):
d[k]=nofsub(s,k)
for key, value in sorted(d.iteritems(), key=lambda (k,v): (v,k)):
print "%s: %s" % (key, value)
</code></pre>
| -1 | 2016-10-10T22:44:47Z | [
"python",
"list",
"count"
] |
How to count number of occurrences of a chracter in a string (list) | 39,967,810 | <p>I'm trying to count the occurrence of each character for any given string input, the occurrences must be output in ascending order( includes numbers and exclamation marks)
I have this for my code so far, i am aware of the Counter function, but it does not output the answer in the format I'd like it to, and I do not know how to format Counter. Instead I'm trying to find away to use the count() to count each character. I've also seen the dictionary function , but I'd be hoping that there is a easier way to do it with count() </p>
<pre><code>from collections import Counter
sentence=input("Enter a sentence b'y: ")
lowercase=sentence.lower()
list1=list(lowercase)
list1.sort()
length=len(list1)
list2=list1.count(list1)
print(list2)
p=Counter(list1)
print(p)
</code></pre>
| 0 | 2016-10-10T22:38:38Z | 39,967,884 | <p>Your best bet is to use <code>Counter</code> (which does work on a string) and then sort on it's output.</p>
<pre><code>from collections import Counter
sentence = input("Enter a sentence b'y: ")
lowercase = sentence.lower()
# Counter will work on strings
p = Counter(lowercase)
count = Counter.items()
# count is now (more or less) equivalent to
# [('a', 1), ('r', 1), ('b', 1), ('o', 2), ('f', 1)]
# And now you can run your sort
sorted_count = sorted(count)
# Which will sort by the letter. If you wanted to
# sort by quantity, tell the sort to use the
# second element of the tuple by setting key:
# sorted_count = sorted(count, key=lambda x:x[1])
for letter, count in sorted_count:
# will cycle through in order of letters.
# format as you wish
print(letter, count)
</code></pre>
| 0 | 2016-10-10T22:46:34Z | [
"python",
"list",
"count"
] |
How to count number of occurrences of a chracter in a string (list) | 39,967,810 | <p>I'm trying to count the occurrence of each character for any given string input, the occurrences must be output in ascending order( includes numbers and exclamation marks)
I have this for my code so far, i am aware of the Counter function, but it does not output the answer in the format I'd like it to, and I do not know how to format Counter. Instead I'm trying to find away to use the count() to count each character. I've also seen the dictionary function , but I'd be hoping that there is a easier way to do it with count() </p>
<pre><code>from collections import Counter
sentence=input("Enter a sentence b'y: ")
lowercase=sentence.lower()
list1=list(lowercase)
list1.sort()
length=len(list1)
list2=list1.count(list1)
print(list2)
p=Counter(list1)
print(p)
</code></pre>
| 0 | 2016-10-10T22:38:38Z | 39,967,905 | <p>If you just want to format the Counter output differently:</p>
<pre><code>for key, value in Counter(list1).items():
print('%s: %s' % (key, value))
</code></pre>
| 0 | 2016-10-10T22:48:36Z | [
"python",
"list",
"count"
] |
How to count number of occurrences of a chracter in a string (list) | 39,967,810 | <p>I'm trying to count the occurrence of each character for any given string input, the occurrences must be output in ascending order( includes numbers and exclamation marks)
I have this for my code so far, i am aware of the Counter function, but it does not output the answer in the format I'd like it to, and I do not know how to format Counter. Instead I'm trying to find away to use the count() to count each character. I've also seen the dictionary function , but I'd be hoping that there is a easier way to do it with count() </p>
<pre><code>from collections import Counter
sentence=input("Enter a sentence b'y: ")
lowercase=sentence.lower()
list1=list(lowercase)
list1.sort()
length=len(list1)
list2=list1.count(list1)
print(list2)
p=Counter(list1)
print(p)
</code></pre>
| 0 | 2016-10-10T22:38:38Z | 39,967,969 | <p>You could use the list function to break the words apart`from collections </p>
<pre><code>from collections import Counter
sentence=raw_input("Enter a sentence b'y: ")
lowercase=sentence.lower()
list1=list(lowercase)
list(list1)
length=len(list1)
list2=list1.count(list1)
print(list2)
p=Counter(list1)
print(p)
</code></pre>
| -3 | 2016-10-10T22:55:52Z | [
"python",
"list",
"count"
] |
How to count number of occurrences of a chracter in a string (list) | 39,967,810 | <p>I'm trying to count the occurrence of each character for any given string input, the occurrences must be output in ascending order( includes numbers and exclamation marks)
I have this for my code so far, i am aware of the Counter function, but it does not output the answer in the format I'd like it to, and I do not know how to format Counter. Instead I'm trying to find away to use the count() to count each character. I've also seen the dictionary function , but I'd be hoping that there is a easier way to do it with count() </p>
<pre><code>from collections import Counter
sentence=input("Enter a sentence b'y: ")
lowercase=sentence.lower()
list1=list(lowercase)
list1.sort()
length=len(list1)
list2=list1.count(list1)
print(list2)
p=Counter(list1)
print(p)
</code></pre>
| 0 | 2016-10-10T22:38:38Z | 39,968,126 | <p>Just call <a href="https://docs.python.org/3/library/collections.html#collections.Counter.most_common" rel="nofollow"><code>.most_common</code></a> and reverse the output with <a href="https://docs.python.org/3/library/functions.html#reversed" rel="nofollow"><em>reversed</em></a> to get the output from least to most common:</p>
<pre><code>from collections import Counter
sentence= "foobar bar"
lowercase = sentence.lower()
for k, count in reversed(Counter(lowercase).most_common()):
print(k,count)
</code></pre>
| 1 | 2016-10-10T23:12:33Z | [
"python",
"list",
"count"
] |
How to count number of occurrences of a chracter in a string (list) | 39,967,810 | <p>I'm trying to count the occurrence of each character for any given string input, the occurrences must be output in ascending order( includes numbers and exclamation marks)
I have this for my code so far, i am aware of the Counter function, but it does not output the answer in the format I'd like it to, and I do not know how to format Counter. Instead I'm trying to find away to use the count() to count each character. I've also seen the dictionary function , but I'd be hoping that there is a easier way to do it with count() </p>
<pre><code>from collections import Counter
sentence=input("Enter a sentence b'y: ")
lowercase=sentence.lower()
list1=list(lowercase)
list1.sort()
length=len(list1)
list2=list1.count(list1)
print(list2)
p=Counter(list1)
print(p)
</code></pre>
| 0 | 2016-10-10T22:38:38Z | 39,968,144 | <p><a href="https://docs.python.org/3/library/collections.html#collections.Counter" rel="nofollow"><code>collections.Counter</code></a> objects provide a <a href="https://docs.python.org/3/library/collections.html#collections.Counter.most_common" rel="nofollow"><code>most_common()</code></a> method that returns a list of tuples in <em>decreasing</em> frequency. So, if you want it in ascending frequency, reverse the list:</p>
<pre><code>from collections import Counter
sentence = input("Enter a sentence: ")
c = Counter(sentence.lower())
result = reversed(c.most_common())
print(list(result))
</code></pre>
<p><em>Demo run</em></p>
<pre>
Enter a sentence: Here are 3 sentences. This is the first one. Here is the second. The end!
[('a', 1), ('!', 1), ('3', 1), ('f', 1), ('d', 2), ('o', 2), ('c', 2), ('.', 3), ('r', 4), ('i', 4), ('n', 5), ('t', 6), ('h', 6), ('s', 7), (' ', 14), ('e', 14)]
</pre>
| 1 | 2016-10-10T23:14:50Z | [
"python",
"list",
"count"
] |
How to count number of occurrences of a chracter in a string (list) | 39,967,810 | <p>I'm trying to count the occurrence of each character for any given string input, the occurrences must be output in ascending order( includes numbers and exclamation marks)
I have this for my code so far, i am aware of the Counter function, but it does not output the answer in the format I'd like it to, and I do not know how to format Counter. Instead I'm trying to find away to use the count() to count each character. I've also seen the dictionary function , but I'd be hoping that there is a easier way to do it with count() </p>
<pre><code>from collections import Counter
sentence=input("Enter a sentence b'y: ")
lowercase=sentence.lower()
list1=list(lowercase)
list1.sort()
length=len(list1)
list2=list1.count(list1)
print(list2)
p=Counter(list1)
print(p)
</code></pre>
| 0 | 2016-10-10T22:38:38Z | 39,968,674 | <p>Another way to avoid using Counter.</p>
<pre><code>sentence = 'abc 11 222 a AAnn zzz?? !'
list1 = list(sentence.lower())
#If you want to remove the spaces.
#list1 = list(sentence.replace(" ", ""))
#Removing duplicate characters from the string
sentence = ''.join(set(list1))
dict = {}
for char in sentence:
dict[char] = list1.count(char)
for item in sorted(dict.items(), key=lambda x: x[1]):
print 'Number of Occurences of %s is %d.' % (item[0], item[1])
</code></pre>
<p>Output:</p>
<pre><code>Number of Occurences of c is 1.
Number of Occurences of b is 1.
Number of Occurences of ! is 1.
Number of Occurences of n is 2.
Number of Occurences of 1 is 2.
Number of Occurences of ? is 2.
Number of Occurences of 2 is 3.
Number of Occurences of z is 3.
Number of Occurences of a is 4.
Number of Occurences of is 6.
</code></pre>
| 0 | 2016-10-11T00:22:20Z | [
"python",
"list",
"count"
] |
django: side menu template visible everywhere | 39,967,812 | <p>I need to create a side menu in my django admin that should appear in all pages. Ideally my template should be a generic navigation.html file containing this code and parsing app_list param (the same that is used into index.html template populating the dashboard):</p>
<pre><code>{% block side_menu %}
{% if app_list %}
{% for app in app_list %}
<ul class="sidebar-menu app-{{ app.app_label }} module">
<li class="treeview">
<a href="#">
<i class="fa fa-dashboard"></i> <span>{{ app.name | truncatechars:"25" }}</span>
<span class="pull-right-container">
<i class="fa fa-angle-left pull-right"></i>
</span>
</a>
{% for model in app.models %}
<ul class="treeview-menu">
{% if model.admin_url %}
<li><a href="{{ model.admin_url }}"><strong>{{ model.name }}</strong></a></li>
{% else %}
<li>{{ model.name }}</li>
{% endif %}
{% if model.add_url %}
<li><a href="{{ model.add_url }}"><i class="fa fa-plus"></i> {% trans 'Add' %}</a></li>
{% else %}
<td>&nbsp;</td>
{% endif %}
{% if model.admin_url %}
<li><a href="{{ model.admin_url }}"><i class="fa fa-pencil-square-o"></i> {% trans 'Change' %}</a></li>
{% else %}
<td>&nbsp;</td>
{% endif %}
</ul>
{% endfor %}
</li>
</ul>
{% endfor %}
{% else %}
<p>{% trans "You don't have permission to edit anything." %}</p>
{% endif %}
{% endblock side_menu %}
</code></pre>
<p>My questions are:</p>
<p>1) how can I include my new navigations.html template in all pages?</p>
<p>2) how can I pass to this template the app_list dictionary?</p>
<p>Thanx in advance</p>
| 0 | 2016-10-10T22:38:45Z | 39,968,002 | <p>1) It looks like <a href="https://docs.djangoproject.com/en/1.10/ref/templates/language/#template-inheritance" rel="nofollow">you're on the right track</a> - you have <code>{% block %}</code>. You just need to have your other files extend that navigation file (you may want to just make it base.html, like the documentation in the link, and have it contain everything all pages should have) and allow those pages to add their own content.</p>
<p>Make it so <code>navigations.html</code> allows a body:</p>
<pre><code><html>
{% block side_menu %}
...
{% endblock side_menu %}
<body>
{% block body %}
{% endblock body %}
</body>
</html>
</code></pre>
<p>Then at the top of every template:</p>
<pre><code>{% extends 'my_app/navigations.html' %}
</code></pre>
<p>with that templates content inside of the <code>{% block body %}</code>.</p>
<p>2) You can <a href="https://docs.djangoproject.com/en/1.10/ref/templates/api/#writing-your-own-context-processors" rel="nofollow">make a template context processor</a> that passes the context to every template. They're very simple, per the documentation:</p>
<blockquote>
<p>Itâs a Python function that takes one argument, an HttpRequest object,
and returns a dictionary that gets added to the template context</p>
</blockquote>
<p>So:</p>
<pre><code>def my_context_processor(request):
apps = App.objects.all()
return {'app_list': apps}
</code></pre>
<p>and in your settings:</p>
<pre><code>TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
# Other context processors....
'my_app.processors.my_context_processor',
],
},
},
]
</code></pre>
<p>Now in every template, you can do <code>{% for app in app_list %}</code> without needing your view to return that context.</p>
| 1 | 2016-10-10T22:58:44Z | [
"python",
"django"
] |
Installing ggplot for python failed with error code 1 | 39,967,873 | <p>I am trying to install ggplot for Python using</p>
<pre><code>pip install ggplot
</code></pre>
<p>but I get an error message saying
<a href="http://i.stack.imgur.com/ZgiKU.png" rel="nofollow"><img src="http://i.stack.imgur.com/ZgiKU.png" alt="enter image description here"></a></p>
<p>I am using Python2.7 on Windows8. I looked at the suggestions and among other things tried the suggestion <a href="http://stackoverflow.com/questions/28142839/pip-install-numpy-python-2-7-fails-with-errorcode-1">here</a></p>
<ol>
<li>pip install wheel to install support for wheel files.</li>
<li>pip install ggplot-0.11.5-py2.py3-none-any.whl to install the wheel. I downloaded the whl file from <a href="https://pypi.python.org/pypi/ggplot" rel="nofollow">here</a>.</li>
</ol>
<p>Upon doing this I got further messages saying:
Failed building wheel for scipy
Failed cleaning build for scipy </p>
<p>In addition I still get the original error message.</p>
<p>Please provide suggestions.</p>
| 0 | 2016-10-10T22:45:35Z | 39,968,223 | <p>After trying all possible things suggested in various forums this is what worked for me:</p>
<ol>
<li>Download numpy-1.11.2+mkl-cp27-cp27m-win_amd64.whl and scipy-0.18.1-cp27-cp27m-win_amd64.whl files from <a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/#scipy" rel="nofollow">http://www.lfd.uci.edu/~gohlke/pythonlibs/#scipy</a> to C:\Python27\Scripts directory.</li>
<li><p>Run the following commands from the DOS command window in windows </p>
<p>pip install numpy-1.11.2+mkl-cp27-cp27m-win_amd64.whl</p>
<p>pip install scipy-0.18.1-cp27-cp27m-win_amd64.whl</p></li>
</ol>
<p>They were both successfully installed.</p>
<ol start="3">
<li><p>Finally</p>
<p>pip install ggplot</p></li>
</ol>
| 0 | 2016-10-10T23:23:55Z | [
"python",
"ggplot2"
] |
python pandas and locate values | 39,967,952 | <p>Let's say I've a DataSerie like this :</p>
<pre><code>df = pandas.DataFrame(numpy.random.randn(4,4),columns=list('ABCD'))
df['test'] = ['A','B','A','C']
</code></pre>
<p>I would like to extract the lines with the 'A' letter and retrieve the values of a Serie, let's say 'C' column. How is it possible to do this whitouh looping into the serie ?
Many thanks.</p>
| 2 | 2016-10-10T22:54:30Z | 39,968,024 | <p>How about</p>
<pre><code>df[df['test'].str.contains('A')]['C']
</code></pre>
| 1 | 2016-10-10T23:01:00Z | [
"python",
"pandas",
"locate"
] |
python pandas and locate values | 39,967,952 | <p>Let's say I've a DataSerie like this :</p>
<pre><code>df = pandas.DataFrame(numpy.random.randn(4,4),columns=list('ABCD'))
df['test'] = ['A','B','A','C']
</code></pre>
<p>I would like to extract the lines with the 'A' letter and retrieve the values of a Serie, let's say 'C' column. How is it possible to do this whitouh looping into the serie ?
Many thanks.</p>
| 2 | 2016-10-10T22:54:30Z | 39,968,053 | <p>Using pandas filtering:</p>
<pre><code>df[df["test"].str.contains("A")]["C"]
</code></pre>
| 0 | 2016-10-10T23:04:09Z | [
"python",
"pandas",
"locate"
] |
python pandas and locate values | 39,967,952 | <p>Let's say I've a DataSerie like this :</p>
<pre><code>df = pandas.DataFrame(numpy.random.randn(4,4),columns=list('ABCD'))
df['test'] = ['A','B','A','C']
</code></pre>
<p>I would like to extract the lines with the 'A' letter and retrieve the values of a Serie, let's say 'C' column. How is it possible to do this whitouh looping into the serie ?
Many thanks.</p>
| 2 | 2016-10-10T22:54:30Z | 39,968,896 | <p>If equal to 'A' is what you need</p>
<pre><code>df.loc[df.test.eq('A'), 'C']
</code></pre>
<p>Otherwise </p>
<pre><code>df.loc[df.test.str.contains('A'), 'C']
</code></pre>
| 0 | 2016-10-11T00:52:29Z | [
"python",
"pandas",
"locate"
] |
Basic python usage, calling a function | 39,968,122 | <p>I am working on leetcode but actually never wrote a file locally before. </p>
<pre><code>class Solution(object):
def singleNumber(self, nums):
for i in range(0,len(nums),2):
if (i != len(nums) - 1) and (nums[i] != nums[i+1]):
print (nums[i])
elif i == len(nums) - 1:
print (nums[i])
def main():
nums=[1,1,2,2,3]
s=Solution()
s.singleNumber(nums)
print('done')
</code></pre>
<p>I am running this script but not seeing any output and don't understand what I'm doing wrong.</p>
| 0 | 2016-10-10T23:12:09Z | 39,968,147 | <p>Move your <strong>main</strong> function outside of the class, and then specifically execute it:</p>
<pre><code>class Solution(object):
def singleNumber(self, nums):
for i in range(0,len(nums),2):
if (i != len(nums) - 1) and (nums[i] != nums[i+1]):
print (nums[i])
elif i == len(nums) - 1:
print (nums[i])
def main():
nums=[1,1,2,2,3]
s=Solution()
s.singleNumber(nums)
print('done')
main()
</code></pre>
<p>Output:</p>
<pre><code>3
done
</code></pre>
<p>Another possibility is to make it a separate function at all: drop the <strong>def main</strong> line, un-indent the four lines of that code, and run it from the top level.</p>
| 2 | 2016-10-10T23:15:36Z | [
"python"
] |
Basic python usage, calling a function | 39,968,122 | <p>I am working on leetcode but actually never wrote a file locally before. </p>
<pre><code>class Solution(object):
def singleNumber(self, nums):
for i in range(0,len(nums),2):
if (i != len(nums) - 1) and (nums[i] != nums[i+1]):
print (nums[i])
elif i == len(nums) - 1:
print (nums[i])
def main():
nums=[1,1,2,2,3]
s=Solution()
s.singleNumber(nums)
print('done')
</code></pre>
<p>I am running this script but not seeing any output and don't understand what I'm doing wrong.</p>
| 0 | 2016-10-10T23:12:09Z | 39,968,231 | <p>Unlike many other programming languages, such as Java, Python does not require the <code>main</code> method to be inside a class. Even more, Python <strong>does not need to have a <code>main</code> method defined</strong>: it runs the whole file as an application. In your original post, Python performs this actions:</p>
<ul>
<li>Define the method <code>singleNumber</code> as the code it holds.</li>
<li>Define the method <code>main</code> as the code it holds.</li>
<li>Save this two methods inside the class <code>Solution</code>.</li>
<li>No more lines to run, therefore ends application.</li>
</ul>
<p>To make the application correct, you must write it as follows:</p>
<pre><code>class Solution(object):
def singleNumber(self, nums):
for i in range(0,len(nums),2):
if (i != len(nums) - 1) and (nums[i] != nums[i+1]):
print (nums[i])
elif i == len(nums) - 1:
print (nums[i])
if __name__=='__main__':
nums=[1,1,2,2,3]
s=Solution()
s.singleNumber(nums)
print('done')
</code></pre>
<p>You may wonder why the line <code>if __name__=='__main__':</code>; every file contains the variable <code>__name__</code> implicitly defined and its value depends if you're running the file directly or it is imported. On the first case, the assignment <code>__name__='__main__'</code> is done, on the second case the <code>__name__</code> variable is assigned the name of the file itself; this gives you an idea whether this file is the main or not.</p>
<p>You may also discard the <code>Solution</code> class and promote the <code>singleNumber</code> method to a module method.</p>
| 2 | 2016-10-10T23:25:08Z | [
"python"
] |
Python method not executed | 39,968,137 | <p>Total noob here. I'm trying to create a python object and execute methods in an instance therein and it seems the code block I want to execute just won't run. The code block in question is run_job which when called just seems to do nothing. What am I doing wrong?</p>
<pre><code>import datetime
import uuid
import paramiko
class scan_job(object):
def __init__(self, protocol, target, user_name, password, command):
self.guid = uuid.uuid1()
self.start_time = datetime.datetime.now()
self.target = target
self.command = command
self.user_name = user_name
self.password = password
self.protocol = protocol
self.result = ""
def run_job(self):
if self.protocol == 'SSH':
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
print "creating connection"
ssh.connect(self.target, self.user_name, self.password)
print "connected"
stdin, stdout, stderr = ssh.exec_command(self.command)
for line in stdout:
print '... ' + line.strip('\n')
self.result += line.strip('\n')
yield ssh
finally:
print "closing connection"
ssh.close()
print "closed"
else:
print "Unknown protocol"
def show_command(self):
print self.command
test = scan_job('SSH', '192.168.14.10', 'myuser', 'mypassword', 'uname -n')
test.show_command()
test.run_job()
</code></pre>
| 0 | 2016-10-10T23:13:57Z | 39,968,183 | <p>Your method contains a yield statement, which makes it a generator. Generators are evaluated lazily. Consider:</p>
<pre><code>>>> def gen():
... yield 10
... yield 3
... yield 42
...
>>> result = gen()
>>> next(result)
10
>>> next(result)
3
>>> next(result)
42
>>>
</code></pre>
<p>This is likely not what you intended to do. </p>
| 0 | 2016-10-10T23:18:45Z | [
"python",
"python-2.7"
] |
Python method not executed | 39,968,137 | <p>Total noob here. I'm trying to create a python object and execute methods in an instance therein and it seems the code block I want to execute just won't run. The code block in question is run_job which when called just seems to do nothing. What am I doing wrong?</p>
<pre><code>import datetime
import uuid
import paramiko
class scan_job(object):
def __init__(self, protocol, target, user_name, password, command):
self.guid = uuid.uuid1()
self.start_time = datetime.datetime.now()
self.target = target
self.command = command
self.user_name = user_name
self.password = password
self.protocol = protocol
self.result = ""
def run_job(self):
if self.protocol == 'SSH':
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
print "creating connection"
ssh.connect(self.target, self.user_name, self.password)
print "connected"
stdin, stdout, stderr = ssh.exec_command(self.command)
for line in stdout:
print '... ' + line.strip('\n')
self.result += line.strip('\n')
yield ssh
finally:
print "closing connection"
ssh.close()
print "closed"
else:
print "Unknown protocol"
def show_command(self):
print self.command
test = scan_job('SSH', '192.168.14.10', 'myuser', 'mypassword', 'uname -n')
test.show_command()
test.run_job()
</code></pre>
| 0 | 2016-10-10T23:13:57Z | 39,969,648 | <blockquote>
<p>Yield is a keyword that is used like return, except the function will
return a generator.</p>
</blockquote>
<p>To read more about generators:<br>
1) <a href="http://stackoverflow.com/questions/1756096/understanding-generators-in-python">Understanding Generators in Python</a><br>
2) <a href="http://stackoverflow.com/questions/231767/what-does-the-yield-keyword-do">What does the "yield" keyword do?</a><br>
3) <a href="https://www.sitepoint.com/quick-tip-understanding-the-yield-keyword-in-python/" rel="nofollow">https://www.sitepoint.com/quick-tip-understanding-the-yield-keyword-in-python/</a></p>
<p>All you need to do is, change:</p>
<pre><code>yield ssh
</code></pre>
<p>To:</p>
<pre><code>return ssh
</code></pre>
<p>So that, run_job will execute like a normal function, until it reaches its end, exception or return statement. However, if you want to run it without changing the yield statement. Here is how you can do it:</p>
<pre><code>x = test.run_job()
x.next()
</code></pre>
| 0 | 2016-10-11T02:30:28Z | [
"python",
"python-2.7"
] |
Django 1.9 form inheritance on UpdateView | 39,968,241 | <p>The problem i have is with a single field that i added. </p>
<p>I have my form:</p>
<pre><code>
class employeesForm(forms.ModelForm):
class Meta:
fields = [
'num_employee',
'id_ignition',
'fullName',
'shortName',
'salary',
'gender',
'rfc',
'imss',
'curp',
'birthday',
'initday',
'id_costCenter',
'id_jobCode',
'id_status',
'nationality',
'picture',
'source',
]
widgets = {
'num_employee': forms.NumberInput(attrs={'class': 'form-control', 'name': 'num_employee'}),
'id_ignition': forms.NumberInput(attrs={'class': 'form-control', 'name': 'id_ignition'}),
'fullName': forms.TextInput(attrs={'class': 'form-control', 'name': 'fullName', 'placeholder': 'Angel Rafael Ortega Vazquez'}),
'shortName': forms.TextInput(attrs={'class': 'form-control', 'name': 'shortName', 'placeholder': 'Rafael Ortega'}),
'salary': forms.NumberInput(attrs={'class': 'form-control', 'name': 'salary', 'placeholder': '5000'}),
'gender': forms.CheckboxInput(attrs={'class': 'form-control', 'name': 'gender'}),
'rfc': forms.TextInput(attrs={'class': 'form-control', 'name': 'rfc', 'id': 'rfc'}),
'imss': forms.TextInput(attrs={'class': 'form-control', 'name': 'imss', 'id': 'imss'}),
'curp': forms.TextInput(attrs={'class': 'form-control', 'name': 'curp'}),
'birthday': forms.DateInput(attrs={'class': 'form-control', 'name': 'birthday'}),
'initday': forms.DateInput(attrs={'class': 'form-control', 'name': 'initday'}),
'id_costCenter': forms.Select(attrs={'class': 'form-control', 'name': 'id_costCenter'}),
'id_jobCode': forms.Select(attrs={'class': 'form-control', 'name': 'id_jobCode'}),
'id_status': forms.Select(attrs={'class': 'form-control', 'name': 'id_status'}),
'nationality': forms.Select(attrs={'class': 'form-control', 'name': 'nationality'}),
'picture': forms.ClearableFileInput(attrs={'class': 'form-control', 'name': 'picture'}),
'source': forms.Select(attrs={'class': 'form-control', 'name': 'source'}),
}
</code></pre>
<p>In my model I have an extra field (antiquity), but Iâm ignoring it here because in my CreateView i populate that field based in other parameters (antiquity = initday).</p>
<p>Everything worked fine until I needed to create an UpdateView with that extra field pre-populated, what I did was to inherit the previews form and adding that extra field:</p>
<pre><code>
class Enhanced_employeesForm(employeesForm):
antiquity = forms.CharField(
widget=forms.DateInput(attrs={'class': 'form-control', 'name': 'antiquity'}))
</code></pre>
<p>It did the thing, the input field is rendered in my template, but while everything is pre-populated with the info based in the id, my antiquity field is empty.</p>
<p>Thatâs the only thing Iâm missing in my configuration, because django even detect when that field is empty on the submit and prevent any update to the database</p>
<p>I tried doing something like:</p>
<pre><code>form.antiquity(instance=Employees.objects.get(pk=self.kwargs['pk']))
</code></pre>
<p>But the error says that 'Enhanced_employeesForm' object has no attribute 'antiquity'.</p>
| 0 | 2016-10-10T23:25:53Z | 39,980,993 | <p>I was doing it wrong, i had to add this code into my enhanced form:</p>
<pre><code>class Enhanced_employeesForm(employeesForm):
class Meta(employeesForm.Meta):
employeesForm.Meta.fields += ['antiquity']
</code></pre>
<p>and that made the thing.</p>
<p>if you need widgets you might noticed that everything is overriden, to prevent that you'll need this:</p>
<pre><code>employeesForm.Meta.widgets['antiquity'] = forms.DateInput(attrs={'class': 'form-control'})
</code></pre>
| 0 | 2016-10-11T15:28:14Z | [
"python",
"inheritance",
"django-forms",
"django-views",
"django-1.9"
] |
Python Selenium Webpage Scraping Selecting Drop Down and entering text in html form | 39,968,269 | <p>I have a problem scraping data from the following site: <a href="https://arcc.sdcounty.ca.gov/Pages/Assessors-Roll-Tax.aspx" rel="nofollow">https://arcc.sdcounty.ca.gov/Pages/Assessors-Roll-Tax.aspx</a>. </p>
<p>I have to do these steps in order:</p>
<ol>
<li><p>Select a drop down option "Street Address'</p></li>
<li><p>Enter a street address into a text field (ie 43 Hadar Dr)</p></li>
<li><p>Click the 'Submit' button. </p></li>
</ol>
<p>After clicking submit, I should be directed to a page that has the APN number for a given address.</p>
<p><strong>The problem:</strong>
I am able to do the above steps. However, when I select a drop down option and input address in the textbox, it fails as the textbox input address for some reason is cleared before clicking 'submit' ONLY when I have selected a drop down option. </p>
<p>I have tried using Selenium's Expected Conditions to trigger the input in the text box after a drop down option has been selected, but did nothing. I am looking for any help on identifying the why there is this problem as well as any advice on solutions. </p>
<p>Thanks.Much appreciated.</p>
<p><strong>My code:</strong></p>
<pre><code> driver = webdriver.Chrome()
driver.get('https://arcc.sdcounty.ca.gov/Pages/Assessors-Roll-Tax.aspx')
#Selects drop down option ('Street Address')
mySelect = Select(driver.find_element_by_id("ctl00_ctl43_g_d30f33ca_a5a7_4f69_bb21_cd4abc25 ea12_ctl00_ddlSearch"))
my=mySelect.select_by_value('0')
wait = WebDriverWait(driver,300)
#Enter address in text box to left of drop down
driver.find_element_by_id("ctl00_ctl43_g_d30f33ca_a5a7_4f69_bb21_cd4abc25ea12_ct l00_txtSearch").send_keys("11493 hadar dr")
#Click 'Submit' button to return API numbers associated with address
driver.find_element_by_id("ctl00_ctl43_g_d30f33ca_a5a7_4f69_bb21_cd4abc25ea12_ctl00_btnSearch").click()
driver.quit()
</code></pre>
| 1 | 2016-10-10T23:28:35Z | 39,968,527 | <p>Not sure if this is your situation. But one thing that jumped out from your question is the text box input... Often, when filling in a website text box, even though the text is clearly visible, the text is not actually read by the text-box method until after the focus (cursor) is clicked or tabbed out and away from the text box. </p>
<p>Tabbing the text cursor out of the text entry box first, before 'clicking submit', will often solve this issue.</p>
| 0 | 2016-10-11T00:01:37Z | [
"python",
"html",
"selenium",
"selenium-webdriver"
] |
Python Selenium Webpage Scraping Selecting Drop Down and entering text in html form | 39,968,269 | <p>I have a problem scraping data from the following site: <a href="https://arcc.sdcounty.ca.gov/Pages/Assessors-Roll-Tax.aspx" rel="nofollow">https://arcc.sdcounty.ca.gov/Pages/Assessors-Roll-Tax.aspx</a>. </p>
<p>I have to do these steps in order:</p>
<ol>
<li><p>Select a drop down option "Street Address'</p></li>
<li><p>Enter a street address into a text field (ie 43 Hadar Dr)</p></li>
<li><p>Click the 'Submit' button. </p></li>
</ol>
<p>After clicking submit, I should be directed to a page that has the APN number for a given address.</p>
<p><strong>The problem:</strong>
I am able to do the above steps. However, when I select a drop down option and input address in the textbox, it fails as the textbox input address for some reason is cleared before clicking 'submit' ONLY when I have selected a drop down option. </p>
<p>I have tried using Selenium's Expected Conditions to trigger the input in the text box after a drop down option has been selected, but did nothing. I am looking for any help on identifying the why there is this problem as well as any advice on solutions. </p>
<p>Thanks.Much appreciated.</p>
<p><strong>My code:</strong></p>
<pre><code> driver = webdriver.Chrome()
driver.get('https://arcc.sdcounty.ca.gov/Pages/Assessors-Roll-Tax.aspx')
#Selects drop down option ('Street Address')
mySelect = Select(driver.find_element_by_id("ctl00_ctl43_g_d30f33ca_a5a7_4f69_bb21_cd4abc25 ea12_ctl00_ddlSearch"))
my=mySelect.select_by_value('0')
wait = WebDriverWait(driver,300)
#Enter address in text box to left of drop down
driver.find_element_by_id("ctl00_ctl43_g_d30f33ca_a5a7_4f69_bb21_cd4abc25ea12_ct l00_txtSearch").send_keys("11493 hadar dr")
#Click 'Submit' button to return API numbers associated with address
driver.find_element_by_id("ctl00_ctl43_g_d30f33ca_a5a7_4f69_bb21_cd4abc25ea12_ctl00_btnSearch").click()
driver.quit()
</code></pre>
| 1 | 2016-10-10T23:28:35Z | 39,969,032 | <p>Just changed a few things in your code to make it work.</p>
<pre><code>mySelect = Select(driver.find_element_by_id("ctl00_ctl43_g_d30f33ca_a5a7_4f69_bb21_cd4abc25 ea12_ctl00_ddlSearch"))
</code></pre>
<p>To find_element_by_name(...):</p>
<pre><code>mySelect = Select(driver.find_element_by_name("ctl00$ctl43$g_d30f33ca_a5a7_4f69_bb21_cd4abc25ea12$ctl00$ddlSearch"))
</code></pre>
<p>And</p>
<pre><code>my=mySelect.select_by_value('0')
</code></pre>
<p>To select_by_visible_text('...'):</p>
<pre><code>my = mySelect.select_by_visible_text("Street Address")
</code></pre>
<p>And</p>
<pre><code>driver.find_element_by_id("ctl00_ctl43_g_d30f33ca_a5a7_4f69_bb21_cd4abc25ea12_ct l00_txtSearch").send_keys("11493 hadar dr")
</code></pre>
<p>To find_element_by_xpath(...), since I usually get better results when finding elements by xpath.</p>
<pre><code>driver.find_element_by_xpath('//*[@id="ctl00_ctl43_g_d30f33ca_a5a7_4f69_bb21_cd4abc25ea12_ctl00_txtSearch"]').send_keys("11493 hadar dr")
</code></pre>
<p>This is how it all looks like:</p>
<pre><code>from selenium.webdriver.support.ui import WebDriverWait
from selenium import webdriver
from selenium.webdriver.support.ui import Select
driver = webdriver.Chrome()
driver.get('https://arcc.sdcounty.ca.gov/Pages/Assessors-Roll-Tax.aspx')
#Selects drop down option ('Street Address')
mySelect = Select(driver.find_element_by_name("ctl00$ctl43$g_d30f33ca_a5a7_4f69_bb21_cd4abc25ea12$ctl00$ddlSearch"))
my = mySelect.select_by_visible_text("Street Address")
wait = WebDriverWait(driver,300)
#Enter address in text box to left of drop down
driver.find_element_by_xpath('//*[@id="ctl00_ctl43_g_d30f33ca_a5a7_4f69_bb21_cd4abc25ea12_ctl00_txtSearch"]').send_keys("11493 hadar dr")
#Click 'Submit' button to return API numbers associated with address
driver.find_element_by_id("ctl00_ctl43_g_d30f33ca_a5a7_4f69_bb21_cd4abc25ea12_ctl00_btnSearch").click()
driver.quit()
</code></pre>
| 1 | 2016-10-11T01:11:43Z | [
"python",
"html",
"selenium",
"selenium-webdriver"
] |
How to use counters and zip functions with a list of lists in Python? | 39,968,360 | <p>I have a list of lists :</p>
<pre><code>results = [['TTTT', 'CCCZ'], ['ATTA', 'CZZC']]
</code></pre>
<p>I create a counter that stores number number of characters in each element in each list, only if the characters are ATGC [NOT Z]</p>
<pre><code>The desired output is [[4,3],[4,2]]
</code></pre>
<p>**</p>
<p>Code:</p>
<pre><code>counters = [Counter(sub_list) for sub_list in results]
nn =[]
d = []
for counter in counters:
atgc_count = sum((val for key, val in counter.items() if key in "ATGC"))
nn.append(atgc_count)
d = [i - 1 for i in nn]
correctionfactor = [float(b) / float(m) for b,m in zip(nn, d)]
print nn
print correctionfactor
"Failed" Output:
[0, 0]
<closed file 'c:/test/zzz.txt', mode 'r' at 0x02B46078>
Desired Output
nn = [[4,3],[4,2]]
correctionfactor = [[1.33, 1.5],[1.33,2]]
</code></pre>
<p>**</p>
<p>And then I calculate frequency of each character (pi), square it and then sum (and then I calculate het = 1 - sum). </p>
<pre><code>The desired output [[1,2],[1,2]] #NOTE: This is NOT the real values of expected output. I just need the real values to be in this format.
</code></pre>
<p>**
Code</p>
<pre><code>list_of_hets = []
for idx, element in enumerate(sample):
count_dict = {}
square_dict = {}
for base in list(element):
if base in count_dict:
count_dict[base] += 1
else:
count_dict[base] = 1
for allele in count_dict:
square_freq = (count_dict[allele] / float(nn[idx]))**2
square_dict[allele] = square_freq
pf = 0.0
for i in square_dict:
pf += square_dict[i] # pf --> pi^2 + pj^2...pn^2
het = 1-pf
list_of_hets.append(het)
print list_of_hets
"Failed" OUTPUT:
[-0.0, -0.0]
</code></pre>
<p>**
I need to multiply every elements in list_of_hets by correction factor</p>
<pre><code>h = [float(n) * float(p) for n,p in zip(correction factor,list_of_hets)
With the values given above:
h = [[1.33, 1.5],[1.33,2]] #correctionfactor multiplied by list_of_hets
</code></pre>
<p>Finally, I need to find the average value of every element in h and store it in a new list.</p>
<pre><code>The desired output should read as [1.33, 1.75].
</code></pre>
<p>I tried following this example (<a href="http://stackoverflow.com/questions/13783315/sum-of-list-of-lists-returns-sum-list">Sum of list of lists; returns sum list</a>). </p>
<pre><code>hs = [mean(i) for i in zip(*h)]
</code></pre>
<p>But I get the following error "TypeError: zip argument #1 must support iteration"</p>
<p>I understand that correcting the code at the first step may solve it. I tried to manually input the "desired outputs" and run the rest of the code, but no luck.</p>
| 0 | 2016-10-10T23:37:28Z | 39,969,273 | <p>The first part can be done like this:</p>
<pre><code>BASES = {'A', 'C', 'G', 'T'}
results = [['TTTT', 'CCCZ'], ['ATTA', 'CZZC']]
counts = [[sum(c in BASES for c in s) for s in pair] for pair in results]
>>> counts
[[4, 3], [4, 2]]
</code></pre>
<p>Once you have the counts, the correction factor can also be calculated with a list comprehension:</p>
<pre><code>correction_factors = [[i/float(i-1) for i in pair] for pair in counts]
>>> correction_factors
[[1.3333333333333333, 1.5], [1.3333333333333333, 2.0]]
</code></pre>
<p>but you do need to be careful of the case where a count is 1 as this will lead to a division by zero error. I'm not sure how you should handle that... would a value of <code>1</code> be appropriate?</p>
<pre><code>correction_factors = [[i/float(i-1) if i-1 else 1 for i in pair] for pair in counts]
</code></pre>
| 1 | 2016-10-11T01:42:08Z | [
"python",
"list",
"error-handling",
"append"
] |
How to use counters and zip functions with a list of lists in Python? | 39,968,360 | <p>I have a list of lists :</p>
<pre><code>results = [['TTTT', 'CCCZ'], ['ATTA', 'CZZC']]
</code></pre>
<p>I create a counter that stores number number of characters in each element in each list, only if the characters are ATGC [NOT Z]</p>
<pre><code>The desired output is [[4,3],[4,2]]
</code></pre>
<p>**</p>
<p>Code:</p>
<pre><code>counters = [Counter(sub_list) for sub_list in results]
nn =[]
d = []
for counter in counters:
atgc_count = sum((val for key, val in counter.items() if key in "ATGC"))
nn.append(atgc_count)
d = [i - 1 for i in nn]
correctionfactor = [float(b) / float(m) for b,m in zip(nn, d)]
print nn
print correctionfactor
"Failed" Output:
[0, 0]
<closed file 'c:/test/zzz.txt', mode 'r' at 0x02B46078>
Desired Output
nn = [[4,3],[4,2]]
correctionfactor = [[1.33, 1.5],[1.33,2]]
</code></pre>
<p>**</p>
<p>And then I calculate frequency of each character (pi), square it and then sum (and then I calculate het = 1 - sum). </p>
<pre><code>The desired output [[1,2],[1,2]] #NOTE: This is NOT the real values of expected output. I just need the real values to be in this format.
</code></pre>
<p>**
Code</p>
<pre><code>list_of_hets = []
for idx, element in enumerate(sample):
count_dict = {}
square_dict = {}
for base in list(element):
if base in count_dict:
count_dict[base] += 1
else:
count_dict[base] = 1
for allele in count_dict:
square_freq = (count_dict[allele] / float(nn[idx]))**2
square_dict[allele] = square_freq
pf = 0.0
for i in square_dict:
pf += square_dict[i] # pf --> pi^2 + pj^2...pn^2
het = 1-pf
list_of_hets.append(het)
print list_of_hets
"Failed" OUTPUT:
[-0.0, -0.0]
</code></pre>
<p>**
I need to multiply every elements in list_of_hets by correction factor</p>
<pre><code>h = [float(n) * float(p) for n,p in zip(correction factor,list_of_hets)
With the values given above:
h = [[1.33, 1.5],[1.33,2]] #correctionfactor multiplied by list_of_hets
</code></pre>
<p>Finally, I need to find the average value of every element in h and store it in a new list.</p>
<pre><code>The desired output should read as [1.33, 1.75].
</code></pre>
<p>I tried following this example (<a href="http://stackoverflow.com/questions/13783315/sum-of-list-of-lists-returns-sum-list">Sum of list of lists; returns sum list</a>). </p>
<pre><code>hs = [mean(i) for i in zip(*h)]
</code></pre>
<p>But I get the following error "TypeError: zip argument #1 must support iteration"</p>
<p>I understand that correcting the code at the first step may solve it. I tried to manually input the "desired outputs" and run the rest of the code, but no luck.</p>
| 0 | 2016-10-10T23:37:28Z | 39,970,108 | <p>First map traverse results.
Second map replace 'Z' and count element.</p>
<pre><code>map(lambda x:map(lambda y:len(y.replace('Z','')),x),l)
</code></pre>
| 0 | 2016-10-11T03:30:11Z | [
"python",
"list",
"error-handling",
"append"
] |
How to convert unicode array to string in Python | 39,968,414 | <p>I am very new with Python and I am trying to print a single object from a unicode array that I retrieved from my server. My array look like this when I print the results:</p>
<pre><code>{u'results': [{u'playerName': u'Sean Plott', u'score': u'12'}]
</code></pre>
<p>I would like to print the result in <code>playerName</code> as a string only. Thanks in advance.</p>
| 0 | 2016-10-10T23:44:22Z | 39,968,456 | <p>You should spend some time looking up dictionaries and lists in python. You currently have a dictionary with a list in it, and a dictionary inside of that list.</p>
<p>Here's the official reference guide on Python data structures:</p>
<p><a href="https://docs.python.org/3/tutorial/datastructures.html" rel="nofollow">https://docs.python.org/3/tutorial/datastructures.html</a></p>
<p>That being said, here's an example:</p>
<pre><code>>>> d = {u'results': [{u'playerName': u'Sean Plott', u'score': u'12'}]}
>>> d["results"]
[{'score': '12', 'playerName': 'Sean Plott'}]
>>> d["results"][0]["playerName"]
'Sean Plott'
</code></pre>
| 3 | 2016-10-10T23:51:04Z | [
"python",
"arrays",
"string",
"unicode"
] |
XLRD/ Entrez: Search through Pubmed and extract the counts | 39,968,425 | <p>I am working on a project that requires me to search through <code>pubmed</code> using inputs from an <code>Excel</code> spreadsheet and print counts of the results. I have been using <code>xlrd</code> and <code>entrez</code> to do this job. Here is what I have tried.</p>
<ol>
<li><p>I need to search through <code>pubmed</code> using the name of the author, his/her medical school, a range of years, and his/her mentor's name, which are all in an <code>Excel</code> spreadsheet. I have used <code>xlrd</code> to turn each column with the required information into lists of strings.</p>
<pre><code>from xlrd import open_workbook
book = xlrd.open_workbook("HEENT.xlsx").sheet_by_index(0)
med_name = []
for row in sheet.col(2):
med_name.append(row)
med_school = []
for row in sheet.col(3):
med_school.append(row)
mentor = []
for row in sheet.col(9):
mentor.append(row)
</code></pre></li>
<li><p>I have managed to print the counts of my specific queries using Entrez.</p>
<pre><code>from Bio import Entrez
Entrez.email = "[email protected]"
handle = Entrez.egquery(term="Jennifer Runch AND ((2012[Date - Publication] : 2017[Date - Publication])) ")
handle_1 = Entrez.egquery(term = "Jennifer Runch AND ((2012[Date - Publication] : 2017[Date - Publication])) AND Leoard P. Byk")
handle_2 = Entrez.egquery(term = "Jennifer Runch AND ((2012[Date - Publication] : 2017[Date - Publication])) AND Southern Illinois University School of Medicine")
record = Entrez.read(handle)
record_1 = Entrez.read(handle_1)
record_2 = Entrez.read(handle_2)
pubmed_count = []
for row in record["eGQueryResult"]:
if row["DbName"] == "pubmed":
pubmed_count.append(row["Count"])
for row in record_1["eGQueryResult"]:
if row["DbName"] == "pubmed":
pubmed_count.append(row["Count"])
for row in record_2["eGQueryResult"]:
if row["DbName"] == "pubmed":
pubmed_count.append(row["Count"])
print(pubmed_count)
>>>['3', '0', '0']
</code></pre>
<p>The problem is that I need to replace the student name ("Jennifer Runch") with the next student name in the list of student names("med_name"), the medical school with the next school, and the current mentor's name with the next mentor's name from the list.</p></li>
</ol>
<p>I think I should write a for loop after declaring my email to <code>pubmed</code>, but I am not sure how to link the two blocks of code together. Does anyone know of an efficient way to connect the two blocks of code or know how to do this with a more efficient way than the one I have tried?
Thank you!</p>
| 1 | 2016-10-10T23:46:09Z | 39,972,453 | <p>You got most of the code in place. It just needed to be modified slightly.</p>
<p>Assuming your table looks like this:</p>
<pre><code>Jennifer Bunch |Southern Illinois University School of Medicine|Leonard P. Rybak
Philipp Robinson|Stanford University School of Medicine |Roger Kornberg
</code></pre>
<p>you could use the following code</p>
<pre><code>import xlrd
from Bio import Entrez
sheet = xlrd.open_workbook("HEENT.xlsx").sheet_by_index(0)
med_name = list()
med_school = list()
mentor = list()
search_terms = list()
for row in range(0, sheet.nrows):
search_terms.append([sheet.cell_value(row, 0), sheet.cell_value(row,1), sheet.cell_value(row, 2)])
pubmed_counts = list()
for search_term in search_terms:
handle = Entrez.egquery(term="{0} AND ((2012[Date - Publication] : 2017[Date - Publication])) ".format(search_term[0]))
handle_1 = Entrez.egquery(term = "{0} AND ((2012[Date - Publication] : 2017[Date - Publication])) AND {1}".format(search_term[0], search_term[2]))
handle_2 = Entrez.egquery(term = "{0} AND ((2012[Date - Publication] : 2017[Date - Publication])) AND {1}".format(search_term[0], search_term[1]))
record = Entrez.read(handle)
record_1 = Entrez.read(handle_1)
record_2 = Entrez.read(handle_2)
pubmed_count = ['', '', '']
for row in record["eGQueryResult"]:
if row["DbName"] == "pubmed":
pubmed_count[0] = row["Count"]
for row in record_1["eGQueryResult"]:
if row["DbName"] == "pubmed":
pubmed_count[1] = row["Count"]
for row in record_2["eGQueryResult"]:
if row["DbName"] == "pubmed":
pubmed_count[2] = row["Count"]
print(pubmed_count)
pubmed_counts.append(pubmed_count)
</code></pre>
<p>Output</p>
<hr>
<pre><code>['3', '0', '0']
['1', '0', '0']
</code></pre>
<p>The required modification is to make the queries variable using <a href="https://docs.python.org/3.6/library/string.html#string.Formatter" rel="nofollow">format</a>.</p>
<p>Some other modifications which are not necessary but might be helpful:</p>
<ul>
<li>loop over the <code>Excel</code> sheet only once</li>
<li>store the <code>pubmed_count</code> in a predefined list because if values come back empty, the size of the output will vary making it hard to guess which value belongs to which query</li>
<li>everything could be even further optimized and prettified, e.g. store the queries in a list and loop over them which would give less code repetition but now it does the job.</li>
</ul>
| 1 | 2016-10-11T07:39:08Z | [
"python",
"xlrd",
"biopython",
"pubmed"
] |
openpyxl: a better way to read a range of numbers to an array | 39,968,466 | <p>I am looking for a better (more readable / less hacked together) way of reading a range of cells using <code>openpyxl</code>. What I have at the moment works, but involves composing the excel cell range (e.g. <code>A1:C3</code>) by assembling bits of the string, which feels a bit rough.</p>
<p>At the moment this is how I read <code>nCols</code> columns and <code>nRows</code> rows starting from a particular cell (minimum working example, assumes that <code>worksheet.xlsx</code> is in working directory, and has the cell references written in cells <code>A1</code> to <code>C3</code> in <code>Sheet1</code>:</p>
<pre><code>from openpyxl import load_workbook
import numpy as np
firstCol = "B"
firstRow = 2
nCols = 2
nRows = 2
lastCol = chr(ord(firstCol) + nCols - 1)
cellRange = firstCol + str(firstRow) + ":" + lastCol + str(firstRow + nRows - 1)
wsName = "Sheet1"
wb = load_workbook(filename="worksheet.xlsx", data_only=True)
data = np.array([[i.value for i in j] for j in wb[wsName][cellRange]])
print(data)
</code></pre>
<p>Returns:</p>
<pre><code>[[u'B2' u'C2']
[u'B3' u'C3']]
</code></pre>
<p>As well as being a bit ugly there are functional limitations with this approach. For example in sheets with more than 26 columns it will fail for columns like <code>AA</code>.</p>
<p>Is there a better/correct way to read <code>nRows</code> and <code>nCols</code> from a given top-left corner using openpyxl?</p>
| 1 | 2016-10-10T23:53:02Z | 39,971,903 | <p>openpyxl provides functions for converting between numerical column indices (1-based index) and Excel's 'AA' style. See the <code>utils</code> module for details.</p>
<p>However, you'll have little need for them in general. You can use the <code>get_squared_range()</code> method of worksheets for programmatic access. And, starting with openpyxl 2.4, you can do the same with the <code>iter_rows()</code> and <code>iter_cols()</code> methods. NB. <code>iter_cols()</code> is not available in read-only mode.</p>
<p>The equivalent MWE using <code>iter_rows()</code> would be:</p>
<pre><code>from openpyxl import load_workbook
import numpy as np
wsName = "Sheet1"
wb = load_workbook(filename="worksheet.xlsx", data_only=True)
ws = wb[wsName]
firstRow = 2
firstCol = 2
nCols = 2
nRows = 2
allCells = np.array([[cell.value for cell in row] for row in ws.iter_rows()])
# allCells is zero-indexed
data = allCells[(firstRow-1):(firstRow-1+nRows),(firstCol-1):(firstCol-1+nCols)]
print(data)
</code></pre>
<p>The equivalent MWE using <code>get_squared_range()</code> would be:</p>
<pre><code>from openpyxl import load_workbook
import numpy as np
wsName = "Sheet1"
wb = load_workbook(filename="worksheet.xlsx", data_only=True)
firstCol = 2
firstRow = 2
nCols = 2
nRows = 2
data = np.array([[i.value for i in j] for j in wb[wsName].get_squared_range(
firstCol, firstRow, firstCol+nCols-1, firstRow+nRows-1)])
print(data)
</code></pre>
<p>Both of which return:</p>
<pre><code>[[u'B2' u'C2']
[u'B3' u'C3']]
</code></pre>
<p>See also <a href="https://openpyxl.readthedocs.io/en/default/pandas.html" rel="nofollow">https://openpyxl.readthedocs.io/en/default/pandas.html</a> for more information on using Pandas and openpyxl together.</p>
| 1 | 2016-10-11T06:57:37Z | [
"python",
"numpy",
"openpyxl"
] |
openpyxl: a better way to read a range of numbers to an array | 39,968,466 | <p>I am looking for a better (more readable / less hacked together) way of reading a range of cells using <code>openpyxl</code>. What I have at the moment works, but involves composing the excel cell range (e.g. <code>A1:C3</code>) by assembling bits of the string, which feels a bit rough.</p>
<p>At the moment this is how I read <code>nCols</code> columns and <code>nRows</code> rows starting from a particular cell (minimum working example, assumes that <code>worksheet.xlsx</code> is in working directory, and has the cell references written in cells <code>A1</code> to <code>C3</code> in <code>Sheet1</code>:</p>
<pre><code>from openpyxl import load_workbook
import numpy as np
firstCol = "B"
firstRow = 2
nCols = 2
nRows = 2
lastCol = chr(ord(firstCol) + nCols - 1)
cellRange = firstCol + str(firstRow) + ":" + lastCol + str(firstRow + nRows - 1)
wsName = "Sheet1"
wb = load_workbook(filename="worksheet.xlsx", data_only=True)
data = np.array([[i.value for i in j] for j in wb[wsName][cellRange]])
print(data)
</code></pre>
<p>Returns:</p>
<pre><code>[[u'B2' u'C2']
[u'B3' u'C3']]
</code></pre>
<p>As well as being a bit ugly there are functional limitations with this approach. For example in sheets with more than 26 columns it will fail for columns like <code>AA</code>.</p>
<p>Is there a better/correct way to read <code>nRows</code> and <code>nCols</code> from a given top-left corner using openpyxl?</p>
| 1 | 2016-10-10T23:53:02Z | 39,972,803 | <p>For completeness (and so I can find it later) the equivalent code using the <code>pandas</code> function <code>read_excel</code> suggested by @Rob in a comment would be:</p>
<pre><code>import pandas
import numpy as np
wsName = "Sheet1"
df = pandas.read_excel(open("worksheet.xlsx", "rb"), sheetname=wsName, header=None)
firstRow = 2
firstCol = 2
nCols = 2
nRows = 2
# Data-frame is zero-indexed
data = np.array(df.ix[(firstRow-1):(firstRow-2+nRows), (firstRow-1):(firstRow-2+nRows)])
print(data)
</code></pre>
<p>Which returns:</p>
<pre><code>[[u'B2' u'C2']
[u'B3' u'C3']]
</code></pre>
| 0 | 2016-10-11T08:01:31Z | [
"python",
"numpy",
"openpyxl"
] |
Comparing a sequence of letters to a list of words in python | 39,968,554 | <p>I have a list of letters which is in a particular order (think of old school texting, so my sequence of buttons here is 4266532)</p>
<pre><code>letters = [['g', 'h', 'i'], ['a', 'b', 'c'], ['m', 'n', 'o'], ['m', 'n', 'o'], ['j', 'k', 'l'], ['d', 'e', 'f']]
</code></pre>
<p>and a list of words</p>
<pre><code>words = ['i', 'am', 'an', 'old', 'man']
</code></pre>
<p>I want to see how many matched sentences there are for this sequence of letters compared to this word list.</p>
<p>For example the sequence of letters could equal 'i am old' or 'i an old' </p>
<p>EDIT: To clarify what I mean by sequence</p>
<p>on old phones that still have buttons instead of touch screen. each button (or number) has letters that are attached to it. For example the number/button '2' has the letters <code>['a','b','c']</code> attached to it. The number/button '3' has the letters <code>['d,'e','f']</code> attached to it. So my <code>letters</code> list above displays what letters could appear on the screen when you push <code>4266532</code></p>
| -1 | 2016-10-11T00:05:07Z | 39,968,779 | <p>Not sure what your full criteria is but since your lists are going to be small you can do something like:</p>
<pre><code>from collections import Counter
from itertools import combinations, chain
letters = [['g', 'h', 'i'], ['a', 'b', 'c'], ['m', 'n', 'o'],['m', 'n', 'o'], ['j', 'k', 'l'], ['d', 'e', 'f']]
allowed = set(chain.from_iterable(letters))
words = ['i', 'am', 'an', 'old', 'man']
for phrase in combinations(words, 3):
phrase_c = Counter(chain.from_iterable(phrase))
if any((v > 1 and k not in "mno") or k not in allowed for k, v in phrase_c.items()):
continue
print(phrase)
</code></pre>
<p>Which would give you:</p>
<pre><code>('i', 'am', 'old')
('i', 'an', 'old')
('i', 'old', 'man')
</code></pre>
<p>If words is always a subset of the letter you can remove the <code>if k not in "mno"</code></p>
<p>if you have to be in order then it is simpler, just make sure each letter from the phrase appears in the subsets and in the correct order:</p>
<pre><code>from collections import Counter
from itertools import combinations, chain
letters = [['g', 'h', 'i'], ['a', 'b', 'c'], ['m', 'n', 'o'], ['m', 'n', 'o'], ['j', 'k', 'l'], ['d', 'e', 'f']]
words = ['i', 'am', 'an', 'old', 'man']
for phrase in combinations(words, 3):
for ind, letter in enumerate(chain.from_iterable(phrase)):
if ind >= len(letters) or letter not in letters[ind]:
break
else:
print(phrase)
</code></pre>
<p>Which would give you:</p>
<pre><code>('i', 'am', 'old')
('i', 'an', 'old')
</code></pre>
<p>If you sort words based on the letter order and filter words that don't contain any letters from the set you can reduce the complexity quite a bit. You can also consider the fact that you can only create at most phrases that have 6 letters i.e <code>4266532</code> </p>
| 1 | 2016-10-11T00:37:23Z | [
"python"
] |
How to tell when enter/return has been pressed in pyQt4 lineEdit | 39,968,562 | <p>I'm having a problem where I can't figure out how to tell if the user hits enter. All of the stackoverflow posts and docs I read all tell me to to add self.textEdit.returnPressed.connect, or something along the lines of that and none of the solutions work. I'm using pyQt 4. Here's the code:</p>
<pre><code># -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'untitled.ui'
#
# Created by: PyQt4 UI code generator 4.11.4
#
# WARNING! All changes made in this file will be lost!
import gi
import signal
gi.require_version('Gtk', '3.0')
import sys
import dbus
import pygtk
import gi
import signal
from PyQt4 import QtCore, QtGui
from PyQt4.QtCore import pyqtSlot
from PyQt4.QtCore import QUrl
from PyQt4.QtWebKit import QWebView
import sip
sip.setapi('QString', 2)
sip.setapi('QVariant', 2)
gi.require_version('Notify', '0.7')
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(679, 600)
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.saveButton = QtGui.QPushButton(self.centralwidget)
self.saveButton.setGeometry(QtCore.QRect(10, 0, 88, 28))
self.saveButton.setObjectName(_fromUtf8("pushButton"))
self.textEdit = QtGui.QTextEdit(self.centralwidget)
self.textEdit.setGeometry(QtCore.QRect(0, 30, 681, 800))
self.textEdit.setObjectName(_fromUtf8("textEdit"))
self.fontButton = QtGui.QPushButton(self.centralwidget)
self.fontButton.setGeometry(QtCore.QRect(400, 0, 88, 28))
self.fontButton.setObjectName(_fromUtf8("fontButton"))
self.fontSize = QtGui.QTextEdit(self.centralwidget)
self.fontSize.setGeometry(QtCore.QRect(200, 0, 88, 28))
self.fontSize.setObjectName(_fromUtf8("fontEdit"))
self.fontSize.returnPressed.connect(self.pushButtonOK.click)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtGui.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 679, 24))
self.menubar.setObjectName(_fromUtf8("menubar"))
self.menuTest = QtGui.QMenu(self.menubar)
self.menuTest.setObjectName(_fromUtf8("menuTest"))
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtGui.QStatusBar(MainWindow)
self.statusbar.setObjectName(_fromUtf8("statusbar"))
MainWindow.setStatusBar(self.statusbar)
self.menubar.addAction(self.menuTest.menuAction())
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
@QtCore.pyqtSlot()
def on_pushButtonOK_clicked(self):
inputNumber = self.lineEditNumber.text()
if inputNumber.isdigit():
info = "You selected `{0}`"
else:
info = "Please select a number, `{0}` isn't valid!"
print(info.format(inputNumber))
#functions
def save(self):
with open('log.txt', 'w') as yourFile:
yourFile.write(str(self.textEdit.toPlainText()))
def saveFont(self):
self.QtGui.QtFont.font.setPointSize(int(self.fontSize))
def commander(self):
save(self)
self.saveButton.clicked.connect(lambda: save(self))
self.fontButton.clicked.connect(lambda: save(self))
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
self.saveButton.setText(_translate("MainWindow", "Save text", None))
self.fontButton.setText(_translate("MainWindow", "Save Font", None))
self.menuTest.setTitle(_translate("MainWindow", "test", None))
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
MainWindow = QtGui.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
</code></pre>
| 0 | 2016-10-11T00:06:09Z | 39,969,154 | <p>You have to mistakes </p>
<ul>
<li><code>returnPressed</code> works with <code>QtLineEdit</code> and you use <code>QtTextEdit</code></li>
<li>you don't have <code>self.pushButtonOK</code> but <code>self.saveButton</code> and <code>self.fontButton</code></li>
</ul>
<p>So you need</p>
<pre><code> self.fontSize = QtGui.QLineEdit(self.centralwidget)
self.fontSize.setGeometry(QtCore.QRect(200, 0, 88, 28))
self.fontSize.setObjectName(_fromUtf8("fontEdit"))
self.fontSize.returnPressed.connect(self.fontButton.click)
</code></pre>
| 1 | 2016-10-11T01:27:44Z | [
"python",
"python-3.x",
"pyqt",
"pyqt4"
] |
Beautiful Soup: get contents of search result tag | 39,968,593 | <p>Trying to get the contents of this type of html snippet using beautiful soup (it is a "tag" object).</p>
<pre><code><span class="font5"> arrives at this calculation from the Torahâs report that the deluge (rains) began on the 17<sup>th</sup> day of the second month </span>
</code></pre>
<p>I've tried:</p>
<pre><code>soup.contents.find_all('span')
soup.find_all('span')
soup.find_all(re.compile("font[0-9]+"))
soup.string
soup.child
</code></pre>
<p>And none of these seem to be working. What can I do?</p>
| 2 | 2016-10-11T00:09:01Z | 39,968,632 | <p><code>soup.find_all('span')</code> does work; returns all <code>span</code> tags.</p>
<p>If you want to get <code>span</code> tag with <code>font<N></code> class, specify the pattern as a keyword argument <code>class_</code>:</p>
<pre><code>soup.find_all('span', class_=re.compile('font[0-9]+'))
</code></pre>
| 2 | 2016-10-11T00:14:56Z | [
"python",
"beautifulsoup"
] |
Beautiful Soup: get contents of search result tag | 39,968,593 | <p>Trying to get the contents of this type of html snippet using beautiful soup (it is a "tag" object).</p>
<pre><code><span class="font5"> arrives at this calculation from the Torahâs report that the deluge (rains) began on the 17<sup>th</sup> day of the second month </span>
</code></pre>
<p>I've tried:</p>
<pre><code>soup.contents.find_all('span')
soup.find_all('span')
soup.find_all(re.compile("font[0-9]+"))
soup.string
soup.child
</code></pre>
<p>And none of these seem to be working. What can I do?</p>
| 2 | 2016-10-11T00:09:01Z | 39,969,119 | <p>If starting with <em>font</em> is unique enough you can use also use a <em>css selector</em> looking for the class starting with font:</p>
<pre><code>soup.select("span[class^=font]")
</code></pre>
| 0 | 2016-10-11T01:21:18Z | [
"python",
"beautifulsoup"
] |
Beautiful Soup: get contents of search result tag | 39,968,593 | <p>Trying to get the contents of this type of html snippet using beautiful soup (it is a "tag" object).</p>
<pre><code><span class="font5"> arrives at this calculation from the Torahâs report that the deluge (rains) began on the 17<sup>th</sup> day of the second month </span>
</code></pre>
<p>I've tried:</p>
<pre><code>soup.contents.find_all('span')
soup.find_all('span')
soup.find_all(re.compile("font[0-9]+"))
soup.string
soup.child
</code></pre>
<p>And none of these seem to be working. What can I do?</p>
| 2 | 2016-10-11T00:09:01Z | 39,980,164 | <pre><code>print ''.join(soup.findAll(text=True))
</code></pre>
<p>(answered <a href="http://stackoverflow.com/questions/2957013/beautifulsoup-just-get-inside-of-a-tag-no-matter-how-many-enclosing-tags-there">here</a>)</p>
| 0 | 2016-10-11T14:52:09Z | [
"python",
"beautifulsoup"
] |
Why can't I reference key in reduce logic? | 39,968,659 | <p>I want to have logic in my <code>combineByKey</code>/<code>reduceByKey</code>/<code>foldByKey</code> that relies on the key currently being operated on. From what I can tell by the method signatures, the only parameters passed to these methods are the values being combined/reduced/folded.</p>
<p>Using a simple example where I just have an RDD which is <code>(int, int)</code> tuples, the result I want is an rdd keyed by <code>tuple[0]</code> where the value is the <code>int</code> closest to the key.</p>
<p>For example:</p>
<pre><code>(1, 8)
(1, 3)
(1, -1)
(2, 4)
(2, 5)
(2, 2)
(3, 2)
(3, 4)
</code></pre>
<p>Should reduce to:</p>
<pre><code>(1, 3)
(2, 2)
(3, 2)
</code></pre>
<p>Note in comparing <code>(1, 3)</code> and <code>(1, -1)</code> I don't care which one is picked since they are both the same distance. Same for the "3" key.</p>
<p>The way I would imagine doing this would be something along the lines of:</p>
<pre><code>rdd.reduceByKey(lambda key, v1, v2: v1 if abs(key - v1) < abs(key - v2) else v2)
</code></pre>
<p>But the <code>reduce</code> function only takes 2 arguments: two values to be combined. It seems like the easiest method would be to reference the key in my reducer in order to achieve my goal; is this possible?</p>
<p>If I try this I get an error:</p>
<pre><code>rdd = sc.parallelize([(1, 8), (1, 3), (1, -1), (2, 4), (2, 5), (2, 2), (3, 2), (3, 4)])
rdd.reduceByKey(lambda key, v1, v2: v1 if abs(key - v1) < abs(key - v2) else v2).collect()
</code></pre>
<blockquote>
<p>TypeError: () takes exactly 3 arguments (2 given)</p>
</blockquote>
<p>I'm not really looking for a solution to this example problem. What I'm wondering is if there is a reason the key is not passed to the <code>reduceByKey</code> function? I assume it is some basic principle of the map-reduce philosophy that I am missing.</p>
<hr>
<p>Note I can solve my example by inserting a map step which maps each value to a tuple consisting of the value and the distance from the key:</p>
<pre><code>rdd = sc.parallelize([(1, 8), (1, 3), (1, -1), (2, 4), (2, 5), (2, 2), (3, 2), (3, 4)])
rdd = rdd.map(lambda tup: (tup[0], tuple([tup[1], abs(tup[0] - tup[1])])))
rdd.reduceByKey(lambda v1, v2: v1 if v1[1] < v2[1] else v2).mapValues(lambda x: x[0]).collectAsMap()
</code></pre>
| 0 | 2016-10-11T00:18:46Z | 39,971,861 | <p>I think there is no strong reason not to pass keys.<br>
however, I feel <code>reduceByKey</code> API was designed for common use case -- compute sum of values for each key. So far I've never needed keys within the value computation. But that's just my opinion.</p>
<p>Also the problem that you solved seems to be simple aggregation problem. <code>min()</code> and <code>groupByKey</code> can find the answer. I know you are not looking for a solution but here is how I'd write.</p>
<pre><code>from pyspark import SparkContext
sc = SparkContext()
rdd = sc.parallelize([(1, 8), (1, 3), (1, -1), (2, 4), (2, 5), (2, 2), (3, 2), (3, 4)])
reduced = rdd.groupByKey().map(lambda (k, v): (k, min(v, key=lambda e:abs(e-k))))
print(reduced.collectAsMap())
</code></pre>
<p>Result</p>
<pre><code>{1: 3, 2: 2, 3: 2}
</code></pre>
| 0 | 2016-10-11T06:54:33Z | [
"python",
"mapreduce",
"pyspark"
] |
Checking if something is true in all iterations of a Python for loop | 39,968,669 | <p>I'm trying to find is a variable is an element of any lists in a list of lists. If it is an element of any of them, then I'm using <code>continue</code> to move onto the next block. If it's not a member of any lists I would like to then create a new list in the list of lists, with the variable as the only entry of that list.</p>
<p>The reason I'm asking is because with either the if statement being satisfied, or with none of the else iterations being satisfied, both situations see the same outcome, a continuation past this block.</p>
<pre><code>for group in groups:
if point in group:
continue
else:
# if point not an element of any group,
create group in groups with variable as only element
</code></pre>
<p>Update:</p>
<p>Would this work? Is there a more succinct way to do it?</p>
<pre><code>for group in groups:
if point in group:
groupCheck = 1
else:
pass
if not groupCheck:
# Create a new list including point
</code></pre>
| 2 | 2016-10-11T00:21:09Z | 39,968,716 | <p>Why not just put the if statement outside of the loop?</p>
<pre><code>found = False
for group in groups:
if point in group:
found = True
break
if not found:
groups.append([point])
</code></pre>
| 1 | 2016-10-11T00:28:40Z | [
"python"
] |
Checking if something is true in all iterations of a Python for loop | 39,968,669 | <p>I'm trying to find is a variable is an element of any lists in a list of lists. If it is an element of any of them, then I'm using <code>continue</code> to move onto the next block. If it's not a member of any lists I would like to then create a new list in the list of lists, with the variable as the only entry of that list.</p>
<p>The reason I'm asking is because with either the if statement being satisfied, or with none of the else iterations being satisfied, both situations see the same outcome, a continuation past this block.</p>
<pre><code>for group in groups:
if point in group:
continue
else:
# if point not an element of any group,
create group in groups with variable as only element
</code></pre>
<p>Update:</p>
<p>Would this work? Is there a more succinct way to do it?</p>
<pre><code>for group in groups:
if point in group:
groupCheck = 1
else:
pass
if not groupCheck:
# Create a new list including point
</code></pre>
| 2 | 2016-10-11T00:21:09Z | 39,968,721 | <p>Reverse your logic, and use the <code>else</code> clause of the <code>for</code> loop to create the new group.</p>
<pre><code>for group in groups:
if point in group:
break
else:
create_new_group(point)
</code></pre>
<p>Or just use <code>any()</code>.</p>
<pre><code>if not any(point in group for group in groups):
create_new_group(point)
</code></pre>
| 4 | 2016-10-11T00:28:58Z | [
"python"
] |
Checking if something is true in all iterations of a Python for loop | 39,968,669 | <p>I'm trying to find is a variable is an element of any lists in a list of lists. If it is an element of any of them, then I'm using <code>continue</code> to move onto the next block. If it's not a member of any lists I would like to then create a new list in the list of lists, with the variable as the only entry of that list.</p>
<p>The reason I'm asking is because with either the if statement being satisfied, or with none of the else iterations being satisfied, both situations see the same outcome, a continuation past this block.</p>
<pre><code>for group in groups:
if point in group:
continue
else:
# if point not an element of any group,
create group in groups with variable as only element
</code></pre>
<p>Update:</p>
<p>Would this work? Is there a more succinct way to do it?</p>
<pre><code>for group in groups:
if point in group:
groupCheck = 1
else:
pass
if not groupCheck:
# Create a new list including point
</code></pre>
| 2 | 2016-10-11T00:21:09Z | 39,968,724 | <p>Make a function.</p>
<pre><code>def check_matches(point, groups):
for group in groups:
if point in group:
return true
return false
if not check_matches(point, groups):
groups.append([point])
</code></pre>
<p>You can leave it this simple, depending on what you are trying to do with this, or build this into a more sophisticated function:</p>
<pre><code>def get_groups(point, groups):
if not check_matches(point, groups):
groups.append([point])
return groups
groups = get_groups(point, groups)
</code></pre>
<p>There are simple list comprehension things you can do here, but given your apparent newness to Python I don't recommend them. It's a sure way to get you confused and to make more mistakes in the future.</p>
| 1 | 2016-10-11T00:29:06Z | [
"python"
] |
Checking if something is true in all iterations of a Python for loop | 39,968,669 | <p>I'm trying to find is a variable is an element of any lists in a list of lists. If it is an element of any of them, then I'm using <code>continue</code> to move onto the next block. If it's not a member of any lists I would like to then create a new list in the list of lists, with the variable as the only entry of that list.</p>
<p>The reason I'm asking is because with either the if statement being satisfied, or with none of the else iterations being satisfied, both situations see the same outcome, a continuation past this block.</p>
<pre><code>for group in groups:
if point in group:
continue
else:
# if point not an element of any group,
create group in groups with variable as only element
</code></pre>
<p>Update:</p>
<p>Would this work? Is there a more succinct way to do it?</p>
<pre><code>for group in groups:
if point in group:
groupCheck = 1
else:
pass
if not groupCheck:
# Create a new list including point
</code></pre>
| 2 | 2016-10-11T00:21:09Z | 39,968,735 | <p>Try using the built-in <code>any()</code> function.</p>
<pre><code>if not any(point in group for group in groups):
groups.append([point])
</code></pre>
| 1 | 2016-10-11T00:30:11Z | [
"python"
] |
Quick numpy array extension | 39,968,711 | <p>I wonder if there is a trick to extending a numpy array with consecutive
numbers in between each original values, up to a user controlled default length. Perhaps there is already a built-in function that turns x into y</p>
<pre><code>x=np.array([4,8,4,10])
y=np.array([4,5,6,7,8,9,10,11,4,5,6,7,10,11,12,13])
</code></pre>
<p>Here the length between each element that I added was three. Speed is of the essence here. I need something like this for my column data to work in creating a sparse
matrix.</p>
<p>Also, if I have an array such as </p>
<pre><code>s=np.array([0,1])
</code></pre>
<p>is there a quick way to extend each element an arbitrary amount of
times, lets say 4 for example:</p>
<pre><code>s=np.array([0,0,0,0,1,1,1,1])
</code></pre>
| 0 | 2016-10-11T00:28:12Z | 39,968,794 | <p>Broadcasted addition is probably the fastest</p>
<pre><code>In [241]: (x[:,None]+np.arange(4)).ravel()
Out[241]: array([ 4, 5, 6, 7, 8, 9, 10, 11, 4, 5, 6, 7, 10, 11, 12, 13])
</code></pre>
<p>It gets trickier if adding different amounts for each sublist. </p>
<p><code>repeat</code> is useful:</p>
<pre><code>In [242]: np.repeat(np.array([0,1]),[3,4])
Out[242]: array([0, 0, 0, 1, 1, 1, 1])
</code></pre>
<p><code>tile</code> is another good tool.</p>
| 1 | 2016-10-11T00:38:44Z | [
"python",
"arrays",
"numpy"
] |
Quick numpy array extension | 39,968,711 | <p>I wonder if there is a trick to extending a numpy array with consecutive
numbers in between each original values, up to a user controlled default length. Perhaps there is already a built-in function that turns x into y</p>
<pre><code>x=np.array([4,8,4,10])
y=np.array([4,5,6,7,8,9,10,11,4,5,6,7,10,11,12,13])
</code></pre>
<p>Here the length between each element that I added was three. Speed is of the essence here. I need something like this for my column data to work in creating a sparse
matrix.</p>
<p>Also, if I have an array such as </p>
<pre><code>s=np.array([0,1])
</code></pre>
<p>is there a quick way to extend each element an arbitrary amount of
times, lets say 4 for example:</p>
<pre><code>s=np.array([0,0,0,0,1,1,1,1])
</code></pre>
| 0 | 2016-10-11T00:28:12Z | 39,968,798 | <p>I don't know a built-in function that does precisely that, but with some creativity you could do:</p>
<pre><code>>>> x=np.array([4,8,4,10])
>>> np.array([x+i for i in range(4)]).T.ravel()
array([ 4, 5, 6, 7, 8, 9, 10, 11, 4, 5, 6, 7, 10, 11, 12, 13])
</code></pre>
<p>For the second half of your question, have a look at <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.repeat.html#numpy.repeat" rel="nofollow"><code>numpy.repeat</code></a> and <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.tile.html#numpy.tile" rel="nofollow"><code>numpy.tile</code></a>.</p>
| 0 | 2016-10-11T00:39:11Z | [
"python",
"arrays",
"numpy"
] |
Quick numpy array extension | 39,968,711 | <p>I wonder if there is a trick to extending a numpy array with consecutive
numbers in between each original values, up to a user controlled default length. Perhaps there is already a built-in function that turns x into y</p>
<pre><code>x=np.array([4,8,4,10])
y=np.array([4,5,6,7,8,9,10,11,4,5,6,7,10,11,12,13])
</code></pre>
<p>Here the length between each element that I added was three. Speed is of the essence here. I need something like this for my column data to work in creating a sparse
matrix.</p>
<p>Also, if I have an array such as </p>
<pre><code>s=np.array([0,1])
</code></pre>
<p>is there a quick way to extend each element an arbitrary amount of
times, lets say 4 for example:</p>
<pre><code>s=np.array([0,0,0,0,1,1,1,1])
</code></pre>
| 0 | 2016-10-11T00:28:12Z | 39,968,805 | <p>This works on lists:</p>
<pre><code>def extend(myList, n):
extensions = [range(x, x + n) for x in myList]
return [item for sublist in extensions for item in sublist] # flatten
</code></pre>
<p>Use as follows:</p>
<pre><code>extend([4, 8, 4, 10], 4)
</code></pre>
| 0 | 2016-10-11T00:39:39Z | [
"python",
"arrays",
"numpy"
] |
Test for presence of specific text in tag with scrapy | 39,968,727 | <p>I'm interested in testing for the presence of specific text (an error message) on pages that I'm scraping. I have the following working statement:</p>
<pre><code> not_found=response.selector.xpath('//*[@id="Error"]/font[contains(text(),"is not found")]')
</code></pre>
<p>I can see that their is a boolean test mentioned in the docs (<a href="https://doc.scrapy.org/en/0.12/topics/selectors.html#scrapy.selector.XPathSelector.__nonzero__" rel="nofollow">https://doc.scrapy.org/en/0.12/topics/selectors.html#scrapy.selector.XPathSelector.<strong>nonzero</strong></a>) but I'm not sure if I can apply it here to do something like (pseudocode):</p>
<pre><code> if __nonzero__(not_found):
</code></pre>
<p>I was having trouble finding it to import so have not been able to test properly. How can I get this working?</p>
| 0 | 2016-10-11T00:29:45Z | 39,968,824 | <p>Python doc: <a href="https://docs.python.org/2/reference/datamodel.html#object.__nonzero__" rel="nofollow"><code>__nonzero__</code></a></p>
<p>It is used automatically when you do <code>bool(not_found)</code><br>
and <code>bool()</code> is use automatically when you do <code>if not_found:</code></p>
<hr>
<p>You don't have to use <code>__nonzero__</code> and you shouldn't use it directly (because you have <code>bool()</code> for this) but if you really have to then it should be <code>not_found.__nonzero__()</code></p>
| 1 | 2016-10-11T00:41:20Z | [
"python",
"scrapy"
] |
"oauth2client.transport : Refreshing due to a 401" what exactly this log mean? | 39,968,806 | <p>I setup a job on google cloud dataflow, and it need more than 7 hours to make it done. My Job ID is 2016-10-10_09_29_48-13166717443134662621. It didn't show any error in pipeline. Just keep logging out "oauth2client.transport : Refreshing due to a 401". Is there any problem of my workers or there is something wrong. If so, how can I solve it?</p>
| 0 | 2016-10-11T00:39:45Z | 39,970,763 | <p>As a general approach, you should try running the pipeline locally, using the <code>DirectPipelineRunner</code> on a small dataset to debug your custom transformations.</p>
<p>Once that passes, you can use the Google Cloud Dataflow UI to investigate the pipeline state. You can particularly look at <code>Elements Added</code> field in the <code>Step</code> tab to see whether your transformations are producing output.</p>
<hr>
<p>In this particular job, there's a step that doesn't seem to be producing output, which normally indicates an issue in the user code.</p>
| 2 | 2016-10-11T05:01:00Z | [
"python",
"google-cloud-dataflow"
] |
Python multiprocessing start more processes than cores | 39,968,808 | <p>Say I start 10 process in a loop using Process() but I only have 8 cores available. How does python handle this?</p>
| 0 | 2016-10-11T00:39:51Z | 39,969,183 | <p>While best practice is to use as many threads as you have virtual cores available, you don't have to stick to that. Using less means you could be under-utilizing your available processor capacity. Using more means you'll be over-utilizing your available processor capacity.</p>
<p>Both these situations mean you'll be doing work at a slower rate than would otherwise be possible. (Though using more threads than you have cores has less of an impact than using fewer threads than your have cores.)</p>
| 1 | 2016-10-11T01:31:18Z | [
"python",
"multiprocessing"
] |
How to write the dictionary key in a batch of text using python? | 39,968,817 | <p>I would be grateful for any help. I have a dictionary which looks like this:</p>
<p>TEST_versions = {'D14 2015' : 'X1', 'D12 2014' : 'X2'}</p>
<p>I want the key from the dictionary to be placed in my text (which I am appending to a file) so I have written:</p>
<pre><code>for v in TEST_versions.keys():
#print(v)
add_code = open('make_all_ascii_files.txt','a')
add_code.write("""
SELECT IF (Version_selector = v).""")
</code></pre>
<p>v is not taking the value of the key, rather the letter v is being appended to the file. How can I write the code so v takes the value 'D14 2015' for example.</p>
| 0 | 2016-10-11T00:40:38Z | 39,968,836 | <p>You need to <a href="https://docs.python.org/2/library/stdtypes.html#str.format" rel="nofollow">format</a> the string with the variable:</p>
<pre><code>for v in TEST_versions.keys():
#print(v)
add_code = open('make_all_ascii_files.txt','a')
add_code.write("""
SELECT IF (Version_selector = {}).""".format(v))
</code></pre>
<p>If you have more than one variable you're formatting you can index them:</p>
<pre><code>for v in TEST_versions:
#print(v)
add_code = open('make_all_ascii_files.txt','a')
add_code.write("""
SELECT IF (Version_selector = {0}; value={1}).""".format(v, TEST_versions[v]))
</code></pre>
<p>Note that the call to <code>.keys()</code> is unnecessary in your example because python iterates over a dictionary's keys by default.</p>
| 0 | 2016-10-11T00:42:55Z | [
"python",
"dictionary"
] |
How to write the dictionary key in a batch of text using python? | 39,968,817 | <p>I would be grateful for any help. I have a dictionary which looks like this:</p>
<p>TEST_versions = {'D14 2015' : 'X1', 'D12 2014' : 'X2'}</p>
<p>I want the key from the dictionary to be placed in my text (which I am appending to a file) so I have written:</p>
<pre><code>for v in TEST_versions.keys():
#print(v)
add_code = open('make_all_ascii_files.txt','a')
add_code.write("""
SELECT IF (Version_selector = v).""")
</code></pre>
<p>v is not taking the value of the key, rather the letter v is being appended to the file. How can I write the code so v takes the value 'D14 2015' for example.</p>
| 0 | 2016-10-11T00:40:38Z | 39,968,905 | <p><em>v</em> is not replaced within string itself.
You can do something like following, for example (using named placeholders)</p>
<pre><code>for k in TEST_versions.keys():
add_code = open('make_all_ascii_files.txt','a')
add_code.write(
"SELECT IF (Version_selector = %(value)s)."
% { 'value': TEST_versions[k] }
)
</code></pre>
<p>or </p>
<pre><code>for k in TEST_versions.keys():
add_code = open('make_all_ascii_files.txt','a')
add_code.write("""SELECT IF (Version_selector = %s).""" % TEST_versions[k] )
</code></pre>
<p>or</p>
<pre><code>for k, v in TEST_versions.items():
add_code = open('make_all_ascii_files.txt','a')
add_code.write("SELECT IF (Version_selector = %s)." % v)
</code></pre>
<p>or some other options for string formatting. Python got lots of options for this</p>
<p>I guess you'd like to review <a href="https://docs.python.org/2/library/string.html#format-string-syntax" rel="nofollow">https://docs.python.org/2/library/string.html#format-string-syntax</a> for details.</p>
| 0 | 2016-10-11T00:53:17Z | [
"python",
"dictionary"
] |
I need to assume for an empty sequence in this code for python | 39,968,888 | <p>The function prints the keyword length, then prints a sorted list of all the dictionary keywords of the required length, which have the highest frequency, followed by the frequency. For example, the following code:</p>
<pre><code> word_frequencies = {"fish":9, "parrot":8, "frog":9, "cat":9, "stork":1, "dog":4, "bat":9, "rat":4}
print_most_frequent(word_frequencies,3)
print_most_frequent(word_frequencies,4)
print_most_frequent(word_frequencies,5)
print_most_frequent(word_frequencies,6)
print_most_frequent(word_frequencies, 7)
</code></pre>
<p>prints outs:</p>
<pre><code> 3 letter keywords: ['bat', 'cat'] 9
4 letter keywords: ['fish', 'frog'] 9
5 letter keywords: ['stork'] 1
6 letter keywords: ['parrot'] 8
7 letter keywords: [] 0
</code></pre>
<p>So far I have this code:</p>
<pre><code>def print_most_frequent(words_dict, word_len):
right_length = {}
for k, v in words_dict.items():
if len(k) == word_len:
right_length[k] = v
max_freq = max(right_length.values())
max_words = {}
for k, v in right_length.items():
if v == max_freq:
max_words[k] = v
print (str(word_len) + " letter keywords: " + str(sorted(max_words.keys())) + " " + str(max_freq))
</code></pre>
<p>and this gives me:</p>
<pre><code> 3 letter keywords: ['bat', 'cat'] 9
4 letter keywords: ['fish', 'frog'] 9
5 letter keywords: ['stork'] 1
6 letter keywords: ['parrot'] 8
</code></pre>
<p>but not the empty sequence. How do I make an addition to my code so that it counts for the empty sequence.</p>
<pre><code> 7 letter keywords: [] 0
</code></pre>
| 1 | 2016-10-11T00:51:08Z | 39,968,961 | <p>Simply add a fallback condition to the <code>max()</code> call so that it never tries to find the largest of an empty iterable:</p>
<pre><code>max_freq = max(right_length.values() or [0])
</code></pre>
<p>If <code>right_length.values()</code> is empty, <code>[0]</code> (which is not empty) will be used instead, and <code>max()</code> doesn't produce an error for that.</p>
| 1 | 2016-10-11T01:00:07Z | [
"python",
"list",
"function"
] |
Python 3 and b'\x92'.decode('latin1') | 39,968,891 | <p>I'm getting results I didn't expect from decoding b'\x92' with the latin1 codec. See the session below:</p>
<pre><code>Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:01:18) [MSC v.1900 32 bit (Intel)] on win32
>>> b'\xa3'.decode('latin1').encode('ascii', 'namereplace')
b'\\N{POUND SIGN}'
>>> b'\x92'.decode('latin1').encode('ascii', 'namereplace')
b'\\x92'
>>> ord(b'\x92'.decode('latin1'))
146
</code></pre>
<p>The result decoding b'\xa3' gave me exactly what I was expecting. But the two results for b'\x92' were not what I expected. I was expecting b'\x92'.decode('latin1') to result in U+2018, but it seems to be returning U+0092.</p>
<p>What am I missing?</p>
| 0 | 2016-10-11T00:51:40Z | 39,968,985 | <p>The error I made was to expect that the character 0x92 decoded to "RIGHT SINGLE QUOTATION MARK" in latin-1, it doesn't. The confusion was caused because it was present in a file that was specified as being in latin1 encoding. It now appears that the file was actually encoded in windows-1252. This is apparently a common source of confusion:</p>
<p><a href="http://www.i18nqa.com/debug/table-iso8859-1-vs-windows-1252.html" rel="nofollow">http://www.i18nqa.com/debug/table-iso8859-1-vs-windows-1252.html</a></p>
<p>If the character is decoded with the correct encoding, then the expected result is obtained.</p>
<pre><code>>>> b'\x92'.decode('windows-1252').encode('ascii', 'namereplace')
b'\\N{RIGHT SINGLE QUOTATION MARK}'
</code></pre>
| 0 | 2016-10-11T01:04:11Z | [
"python",
"python-3.x",
"unicode",
"python-unicode"
] |
Python 3 and b'\x92'.decode('latin1') | 39,968,891 | <p>I'm getting results I didn't expect from decoding b'\x92' with the latin1 codec. See the session below:</p>
<pre><code>Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:01:18) [MSC v.1900 32 bit (Intel)] on win32
>>> b'\xa3'.decode('latin1').encode('ascii', 'namereplace')
b'\\N{POUND SIGN}'
>>> b'\x92'.decode('latin1').encode('ascii', 'namereplace')
b'\\x92'
>>> ord(b'\x92'.decode('latin1'))
146
</code></pre>
<p>The result decoding b'\xa3' gave me exactly what I was expecting. But the two results for b'\x92' were not what I expected. I was expecting b'\x92'.decode('latin1') to result in U+2018, but it seems to be returning U+0092.</p>
<p>What am I missing?</p>
| 0 | 2016-10-11T00:51:40Z | 39,968,989 | <p>I just want to make clear that you're not encoding anything here. </p>
<p><code>xa3</code> has a ordinal value of 163 (0xa3 in hexadecimal). Since that ordinal is not seven bits, it can't be encoded into ascii. Your handler for errors just replaces the Unicode Character into the name of the character. The Unicode Character 163 maps to £.</p>
<p>'\x92' on the other hand, has an ordinal value of 146. According to <a href="https://en.wikipedia.org/wiki/List_of_Unicode_characters#Control_codes" rel="nofollow">this Wikipedia Article</a>, the character isn't printable - it's a privately used control code in the C2 space. This explains why it's name is simply the literal <code>'\\x92'</code>.</p>
<p>As an aside, if you need the name of the character, it's much better to do it like this:</p>
<pre><code>import unicodedata
print unicodedata.name(u'\xa3')
</code></pre>
| 1 | 2016-10-11T01:04:29Z | [
"python",
"python-3.x",
"unicode",
"python-unicode"
] |
Python 3 and b'\x92'.decode('latin1') | 39,968,891 | <p>I'm getting results I didn't expect from decoding b'\x92' with the latin1 codec. See the session below:</p>
<pre><code>Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:01:18) [MSC v.1900 32 bit (Intel)] on win32
>>> b'\xa3'.decode('latin1').encode('ascii', 'namereplace')
b'\\N{POUND SIGN}'
>>> b'\x92'.decode('latin1').encode('ascii', 'namereplace')
b'\\x92'
>>> ord(b'\x92'.decode('latin1'))
146
</code></pre>
<p>The result decoding b'\xa3' gave me exactly what I was expecting. But the two results for b'\x92' were not what I expected. I was expecting b'\x92'.decode('latin1') to result in U+2018, but it seems to be returning U+0092.</p>
<p>What am I missing?</p>
| 0 | 2016-10-11T00:51:40Z | 40,029,793 | <blockquote>
<p>I was expecting b'\x92'.decode('latin1') to result in U+2018</p>
</blockquote>
<p><code>latin1</code> is an alias for <a href="https://en.wikipedia.org/wiki/ISO/IEC_8859-1" rel="nofollow">ISO-8859-1</a>. In that encoding, byte 0x92 maps to character U+0092, an unprintable control character.</p>
<p>The encoding you might have really meant is <code>windows-1252</code>, the Microsoft <a href="https://en.wikipedia.org/wiki/Windows-1252" rel="nofollow">Western code page</a> based on it. In that encoding, 0x92 is U+2019 which is close...</p>
<p>(Further befuddlement arises because for historical reasons web browsers are also confused between the two. When a web page is served as <code>charset=iso-8859-1</code>, web browsers actually use <code>windows-1252</code>.)</p>
| 1 | 2016-10-13T19:53:51Z | [
"python",
"python-3.x",
"unicode",
"python-unicode"
] |
median of five points python | 39,968,904 | <p>My data frame (<code>df</code>) has a list of numbers (total 1773) and I am trying to find a median for five numbers (e.g. the <code>median of 3rd number = median (1st,2nd,3rd,4th,5th)</code>)</p>
<pre><code>num
10
20
15
34
...
...
...
def median(a, b, c,d,e):
I=[a,b,c,d,e]
return I[2]
num_median = [num[0]]
for i in range(1, len(num)):
num_median = median(num[i - 1], num[i-2], num[i],num[i+1],num[i+2])
df['num_median']=num_median
IndexError: index 1773 is out of bounds for axis 0 with size 1773
</code></pre>
<p>Where did it go wrong and Is there any other method to compute the median?</p>
| 0 | 2016-10-11T00:53:10Z | 39,968,928 | <p>An example which will help:</p>
<pre><code>a = [0, 1, 2, 3]
print('Length={}'.format(len(a)))
print(a(4))
</code></pre>
<p>You are trying the same thing. The actual index of an element is one lower than the place it is. Keep in mind your exception shows you <em>exactly</em> where your problem is.</p>
<p>You need to modify:</p>
<pre><code>for i in range(1, len(num) - 2):
num_median = median(num[i - 1], num[i-2], num[i],num[i+1],num[i+2])
</code></pre>
<p>So that your last index check will not be too large. Otherwise, when you are at the end of your array (index = 1773) you will be trying to access an index which doesn't exist (1773 + 2).</p>
| 1 | 2016-10-11T00:56:16Z | [
"python",
"numpy",
"indexing",
"median"
] |
How to pack spheres in python? | 39,968,941 | <p>I am trying to model random closed packing spheres of uniform size in a square using python. <strong>And the spheres should not overlap</strong> but I do not know how to do this</p>
<p>I have so far:
<a href="http://i.stack.imgur.com/fwScD.png" rel="nofollow"><img src="http://i.stack.imgur.com/fwScD.png" alt="enter image description here"></a></p>
<p>Code:</p>
<pre><code>import random, math, pylab
def show_conf(L, sigma, title, fname):
pylab.axes()
for [x, y] in L:
for ix in range(-1, 2):
for iy in range(-1, 2):
cir = pylab.Circle((x + ix, y + iy), radius=sigma, fc='r')
pylab.gca().add_patch(cir)
pylab.axis('scaled')
pylab.xlabel('eixo x')
pylab.ylabel('eixo y')
pylab.title(title)
pylab.axis([0.0, 1.0, 0.0, 1.0])
pylab.savefig(fname)
pylab.close()
L = []
N = 8 ** 2
for i in range(N):
posx = float(random.uniform(0, 1))
posy = float(random.uniform(0, 1))
L.append([posx, posy])
print L
N = 8 ** 2
eta = 0.3
sigma = math.sqrt(eta / (N * math.pi))
Q = 20
ltilde = 5*sigma
N_sqrt = int(math.sqrt(N) + 0.5)
titulo1 = '$N=$'+str(N)+', $\eta =$'+str(eta)
nome1 = 'inicial'+'_N_'+str(N) + '_eta_'+str(eta) + '.png'
show_conf(L, sigma, titulo1, nome1)
</code></pre>
| 1 | 2016-10-11T00:57:40Z | 39,969,076 | <p>This is a very hard problem (and probably <strong>np-hard</strong>). There should be a lot of ressources available.</p>
<p>Before i present some more general approach, check out <a href="https://en.wikipedia.org/wiki/Circle_packing_in_a_square" rel="nofollow">this wikipedia-site</a> for an overview of the currently best known packing-patterns for some N (N circles in a square).</p>
<p>You are lucky that there is an existing circle-packing implementation in python (<strong>heuristic!</strong>) which is heavily based on modern optimization-theory (<a href="https://ocw.mit.edu/courses/sloan-school-of-management/15-097-prediction-machine-learning-and-statistics-spring-2012/projects/MIT15_097S12_proj5.pdf" rel="nofollow">difference of convex-functions</a> + <a href="http://papers.nips.cc/paper/2125-the-concave-convex-procedure-cccp.pdf" rel="nofollow">Concave-convex-procedure</a>).</p>
<ul>
<li>The method used is described <a href="https://stanford.edu/~boyd/papers/dccp.html" rel="nofollow">here</a> (academic paper & link to software; 2016!)</li>
<li>The software package used is <a href="https://github.com/cvxgrp/dccp" rel="nofollow">here</a>
<ul>
<li>There is an example directory with <code>circle_packing.py</code> (which is posted below together with the output)</li>
</ul></li>
<li>The following example also works for circles of different shapes</li>
</ul>
<h3>Example taken from the above software-package (example by Xinyue Shen)</h3>
<pre><code>__author__ = 'Xinyue'
from cvxpy import *
import numpy as np
import matplotlib.pyplot as plt
import dccp
n = 10
r = np.linspace(1,5,n)
c = Variable(n,2)
constr = []
for i in range(n-1):
for j in range(i+1,n):
constr.append(norm(c[i,:]-c[j,:])>=r[i]+r[j])
prob = Problem(Minimize(max_entries(max_entries(abs(c),axis=1)+r)), constr)
#prob = Problem(Minimize(max_entries(normInf(c,axis=1)+r)), constr)
prob.solve(method = 'dccp', ccp_times = 1)
l = max_entries(max_entries(abs(c),axis=1)+r).value*2
pi = np.pi
ratio = pi*sum_entries(square(r)).value/square(l).value
print "ratio =", ratio
print prob.status
# plot
plt.figure(figsize=(5,5))
circ = np.linspace(0,2*pi)
x_border = [-l/2, l/2, l/2, -l/2, -l/2]
y_border = [-l/2, -l/2, l/2, l/2, -l/2]
for i in xrange(n):
plt.plot(c[i,0].value+r[i]*np.cos(circ),c[i,1].value+r[i]*np.sin(circ),'b')
plt.plot(x_border,y_border,'g')
plt.axes().set_aspect('equal')
plt.xlim([-l/2,l/2])
plt.ylim([-l/2,l/2])
plt.show()
</code></pre>
<h3>Output</h3>
<p><a href="http://i.stack.imgur.com/Ryupg.png" rel="nofollow"><img src="http://i.stack.imgur.com/Ryupg.png" alt="enter image description here"></a></p>
<h3>Modification for your task: equal-sized circles</h3>
<p>Just replace:</p>
<pre><code>r = np.linspace(1,5,n)
</code></pre>
<p>With:</p>
<pre><code>r = [1 for i in range(n)]
</code></pre>
<h3>Output</h3>
<p><a href="http://i.stack.imgur.com/x3cBf.png" rel="nofollow"><img src="http://i.stack.imgur.com/x3cBf.png" alt="enter image description here"></a></p>
<h3>Fun example with 64 circles (this will take some time!)</h3>
<p><a href="http://i.stack.imgur.com/Th3zK.png" rel="nofollow"><img src="http://i.stack.imgur.com/Th3zK.png" alt="enter image description here"></a></p>
| 3 | 2016-10-11T01:16:16Z | [
"python",
"optimization",
"mathematical-optimization",
"packing"
] |
R lm versus Python sklearn linear_model | 39,968,999 | <p>When I study Python SKlearn, the first example that I come across is the linear regression.</p>
<p><a href="http://scikit-learn.org/stable/modules/linear_model.html" rel="nofollow">http://scikit-learn.org/stable/modules/linear_model.html</a></p>
<p>Code of its very first example:</p>
<pre><code>from sklearn import linear_model
reg = linear_model.LinearRegression()
reg.fit([[0, 0], [1, 1], [2,2]], [0, 1,2])
reg.fit
reg.coef_
array([ 0.5, 0.5])
</code></pre>
<p>Here I assume <code>[[0, 0], [1, 1], [2,2]]</code> represents a data.frame containing <code>x1 = c(0,1,2)</code> and <code>x2 = c(0,1,2)</code> and <code>y = c(0,1,2)</code> as well.</p>
<p>Immediately, I begin to think that <code>array([ 0.5, 0.5])</code> are the coeffs for <code>x1</code> and <code>x2</code>. </p>
<p>But, are there standard errors for those estimates? What about t tests p values, R2 and other figures?</p>
<p>Then I try to do the same thing in R.</p>
<pre><code>X = data.frame(x1 = c(0,1,2),x2 = c(0,1,2),y = c(0,1,2))
lm(data=X, y~x1+x2)
Call:
lm(formula = y ~ x1 + x2, data = X)
#Coefficients:
#(Intercept) x1 x2
# 1.282e-16 1.000e+00 NA
</code></pre>
<p>Obviously <code>x1</code> and <code>x2</code> are completely linearly dependent so the OLS will fail. Why the SKlearn still works and gives this results? Am I getting sklearn in a wrong way? Thanks.</p>
| 1 | 2016-10-11T01:06:23Z | 39,979,016 | <p>Both solutions are correct (assuming that NA behaves like a zero). Which solution is favored depends on the numerical solver used by the OLS estimator.</p>
<p><code>sklearn.linear_model.LinearRegression</code> is based on <code>scipy.linalg.lstsq</code> which in turn calls the LAPACK <code>gelsd</code> routine which is described here:</p>
<p><a href="http://www.netlib.org/lapack/lug/node27.html" rel="nofollow">http://www.netlib.org/lapack/lug/node27.html</a></p>
<p>In particular it says that when the problem is rank deficient it seeks the minimum norm least squares solution.</p>
<p>If you want to favor the other solution, you can use a coordinate descent solver with a tiny bit of L1 penalty as implemented in th Lasso class:</p>
<pre><code>>>> from sklearn.linear_model import Lasso
>>> reg = Lasso(alpha=1e-8)
>>> reg.fit([[0, 0], [1, 1], [2, 2]], [0, 1, 2])
Lasso(alpha=1e-08, copy_X=True, fit_intercept=True, max_iter=1000,
normalize=False, positive=False, precompute=False, random_state=None,
selection='cyclic', tol=0.0001, warm_start=False)
>>> reg.coef_
array([ 9.99999985e-01, 3.97204719e-17])
</code></pre>
| 3 | 2016-10-11T13:59:36Z | [
"python",
"scikit-learn",
"regression",
"linear"
] |
Two select query at a time python | 39,969,030 | <p>I want to calculate distance between two points. For that for each point in one table i have to calculate distance with all the other point in another table in same database. I am using python for that but I am not able to execute two query at a time. </p>
<pre><code>import mysql.connector
from haversine import haversine
cnx = mysql.connector.connect(host='localhost',user='xxxxx',passwd='xxxxxx',db='xxxxxx')
cursor = cnx.cursor()
cursor2 = cnx.cursor()
query = ("select longitude,latitude from roadData limit 5")
cursor.execute(query)
query2=("SELECT geo_coordinates_latitude, geo_coordinates_longitude from tweetmelbourne limit 2")
cursor2.execute(query2)
for (longitude,latitude) in cursor:
print longitude
print latitude
for (geo_coordinates_longitude,geo_coordinates_latitude) in cursor2:
print geo_coordinates_longitude
print geo_coordinates_latitude
cursor.close()
cnx.close()
</code></pre>
<p>But, I am getting error for second query execution </p>
<blockquote>
<p>InternalError: Unread result found.</p>
</blockquote>
<p>I tried buffer=true for cursor but still same error.
And also is it efficient to do like this or any other better way.</p>
| 1 | 2016-10-11T01:11:16Z | 39,969,092 | <p>One trick you could use here would be to cross join the two tables together:</p>
<pre><code>SELECT t1.longitude,
t1.latitude,
t2.geo_coordinates_latitude,
t2.geo_coordinates_longitude
FROM
(
SELECT longitude, latitude
FROM roadData
LIMIT 5
) t1
CROSS JOIN
(
SELECT geo_coordinates_latitude, geo_coordinates_longitude
FROM tweetmelbourne
LIMIT 2
) t2
</code></pre>
<p>This should work because the way you iterate over the result set in your Python code resembles a cross join. In this case, using the above query you would only need to iterate once over the entire result set.</p>
| 0 | 2016-10-11T01:17:38Z | [
"python",
"mysql",
"sql"
] |
Trying to build an Organizational Tree From a List | 39,969,031 | <p>I have an input file that's in the following format.</p>
<pre><code>Fred,Karl,Technician,2010--Karl,Cathy,VP,2009--Cathy,NULL,CEO,2007--
--Vince,Cathy,Technician,2010
</code></pre>
<p>I need to parse this information to where it ends up looking something like this in an output file:</p>
<pre><code>Cathy (CEO) 2007
-Karl (VP) 2009
--Fred (Technician) 2010
-Vince (Technician) 2010
</code></pre>
<p>With the CEO at the top, each subordinate should be under their superior. So whatever the second name is, that is the supervisor. The trick is that if an employee has 2 supervisors, they need to be indented twice "--" with their immediate supervisor above.</p>
<p>I've tried iterating through the list and parsing through the "--" and the commas but I'm struggling with the structure itself. This is what I have so far.</p>
<pre><code>with open('org_chart_sample.in', 'r') as reader: # Open the input file
with open('output.out', 'w') as writer: # Make output file writable
reader.readline() # Ignore first line
lines = reader.readlines() # Read input lines
for line in lines: # Parse out input by the -- which separated attributes of people in the org
employees = line.split('--')
hierarchy = [] # Exterior list to aid in hierarchy
for employee in employees: # Logic that adds to the hierarchy list as algorithm runs
info = employee.split(',')
hierarchy.append(info)
</code></pre>
<p>I've been stuck on this problem for longer that I'd like to admit :(</p>
| 0 | 2016-10-11T01:11:41Z | 39,969,529 | <p>Cool question, it was fun to work on. I tried to be thorough, and it ended up getting kind of long, I hope it's still readable.</p>
<p>Code:</p>
<pre><code>##########################
#Input data cleaned a bit#
##########################
lines = ["Fred,Karl,Technician,2010",
"Karl,Cathy,VP,2009",
"Cathy,NULL,CEO,2007",
"Vince,Cathy,Technician,2010",
"Mary,NULL,CEO,2010",
"Steve,Mary,IT,2013"]
##################################
#Worker class to make things neat#
##################################
class Worker(object):
#Variables assigned to this worker
__slots__ = ["name","boss","job","year","employees","level"]
#Initialize this worker with a string in the form of:
#"name,boss,job,year"
def __init__(self,line):
self.name,self.boss,self.job,self.year = line.split(",")
self.level = 0 if self.boss == "NULL" else -1 #If boss is NULL, they are '0' level
self.employees = []
#A function to add another worker as this worker's employee
def employ(self,worker):
worker.level = self.level+1
self.employees.append(worker)
#This is a recursive function which returns a string of this worker
#and all of this workers employees (depth first)
def __repr__(self):
rep_str = ""
rep_str += "-"*self.level
rep_str += str(self.name)+" works for "+str(self.boss)
rep_str += " as a "+str(self.job)+" since "+str(self.year)+"\n"
for employee in self.employees:
rep_str += str(employee)
return rep_str
########################################
#Prepare to assign the bosses employees#
########################################
#1. Turn all of the lines into worker objects
workers = [Worker(line) for line in lines]
#2. Start from the top level bosses (the ones that had NULL as boss)
boss_level = 0
#3. Get a list of all the workers that have a boss_level of 0
bosses = [w for w in workers if w.level == boss_level]
#While there are still boses looking to employ then keep going
while len(bosses) > 0:
#For each boss look through all the workers and see if they work for this boss
#If they do, employ that worker to the boss
for boss in bosses:
for worker in workers:
if worker.level == -1 and boss.name == worker.boss:
boss.employ(worker)
#Move down a tier of management to sub-bosses
#If there are no sub-bosses at this level, then stop, otherwise while loop again
boss_level += 1
bosses = [w for w in workers if w.level == boss_level]
##########################
#Printing out the workers#
##########################
#1. Loop through the top bosses and
# print out them and all their workers
top_bosses = [w for w in workers if w.level == 0]
for top_boss in top_bosses:
print top_boss
</code></pre>
<p>Output:</p>
<pre><code>Cathy works for NULL as a CEO since 2007
-Karl works for Cathy as a VP since 2009
--Fred works for Karl as a Technician since 2010
-Vince works for Cathy as a Technician since 2010
Mary works for NULL as a CEO since 2010
-Steve works for Mary as a IT since 2013
</code></pre>
| 0 | 2016-10-11T02:17:34Z | [
"python",
"algorithm",
"sorting",
"parsing"
] |
How to create pie chart? | 39,969,089 | <p>new to Python and stuck with a pie chart.
Apologies for the complexity but I am at a lost as how to proceed ..
I have this dataset in the form of a dictionary (part of it)</p>
<pre><code>{'Deaths5': 94, 'Deaths10': 379, 'Deaths12': 388, 'Deaths8': 138, 'Deaths25': None,
'IM_Deaths2': None, 'Deaths14': 511, 'Deaths1': 20535, 'Deaths23': 2643, 'Deaths6': 62,
'IM_Deaths1': 4349, 'Deaths17': 1036, 'Deaths18': 1234, 'Sex': '2', 'Deaths11': 358, 'Deaths22': 1708,
'Deaths21': 1922, 'IM_Frmat': '08', 'SubDiv': '', 'Deaths15': 600, 'Deaths4': 157, 'Admin1': '',
'IM_Deaths3': None, 'Deaths19': 1125, 'Deaths24': None, 'Frmat': '01', 'Deaths20': 1602, 'Deaths3': 350,
'Year': '1964', 'Deaths7': 149, 'Deaths9': 311, 'Deaths26': 33, 'Country': '2150',
'Deaths16': 932, 'Deaths13': 454, 'Deaths2': 4349, 'IM_Deaths4': None, 'Cause': 'A000', 'List': '07A' .......
</code></pre>
<p>I need to generate a pie chart that shows the latest year - 2013,
and shows the top 8 causes of death code 'Cause' from field 'Deaths1'</p>
<p>So to sum it up:</p>
<p>So for example the data should be filtered as</p>
<pre><code>Year CAUSE Top8
2013 A000 5000
2013 A411 400
2013 A50 200
.....
</code></pre>
<p>and then shown as a pie chart with anything after the top 8 treated as 'other'</p>
<p>I could do this very easily with SQL but with Python...I am not sure.</p>
| 2 | 2016-10-11T01:17:31Z | 39,969,548 | <p>You can use <a href="http://matplotlib.org/examples/pie_and_polar_charts/pie_demo_features.html" rel="nofollow">Matplotlib</a> for creating Pie charts in Python</p>
<p>Example Pie Chart:-</p>
<pre><code>import matplotlib.pyplot as plt
labels = 'A', 'B', 'C', 'D'
sizes = [40, 20, 20, 20]
colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral']
explode = (0, 0.1, 0, 0)
plt.pie(sizes, explode=explode, labels=labels, colors=colors,
autopct='%1.1f%%', shadow=True, startangle=90)
plt.axis('equal')
plt.title('Year 2013')
plt.show()
</code></pre>
| 1 | 2016-10-11T02:19:46Z | [
"python",
"python-3.x",
"dictionary",
"charts",
"pie-chart"
] |
How to create pie chart? | 39,969,089 | <p>new to Python and stuck with a pie chart.
Apologies for the complexity but I am at a lost as how to proceed ..
I have this dataset in the form of a dictionary (part of it)</p>
<pre><code>{'Deaths5': 94, 'Deaths10': 379, 'Deaths12': 388, 'Deaths8': 138, 'Deaths25': None,
'IM_Deaths2': None, 'Deaths14': 511, 'Deaths1': 20535, 'Deaths23': 2643, 'Deaths6': 62,
'IM_Deaths1': 4349, 'Deaths17': 1036, 'Deaths18': 1234, 'Sex': '2', 'Deaths11': 358, 'Deaths22': 1708,
'Deaths21': 1922, 'IM_Frmat': '08', 'SubDiv': '', 'Deaths15': 600, 'Deaths4': 157, 'Admin1': '',
'IM_Deaths3': None, 'Deaths19': 1125, 'Deaths24': None, 'Frmat': '01', 'Deaths20': 1602, 'Deaths3': 350,
'Year': '1964', 'Deaths7': 149, 'Deaths9': 311, 'Deaths26': 33, 'Country': '2150',
'Deaths16': 932, 'Deaths13': 454, 'Deaths2': 4349, 'IM_Deaths4': None, 'Cause': 'A000', 'List': '07A' .......
</code></pre>
<p>I need to generate a pie chart that shows the latest year - 2013,
and shows the top 8 causes of death code 'Cause' from field 'Deaths1'</p>
<p>So to sum it up:</p>
<p>So for example the data should be filtered as</p>
<pre><code>Year CAUSE Top8
2013 A000 5000
2013 A411 400
2013 A50 200
.....
</code></pre>
<p>and then shown as a pie chart with anything after the top 8 treated as 'other'</p>
<p>I could do this very easily with SQL but with Python...I am not sure.</p>
| 2 | 2016-10-11T01:17:31Z | 39,987,843 | <p>Full disclosure, I'm a member of the ZingChart team.</p>
<p>You can use <a href="https://www.zingchart.com/" rel="nofollow">ZingChart</a> for free to accomplish this. I'm not sure if you were looking for the answer to include how to parse the dictionary or just the data visualization portion. With some simple attributes we can display the data in a legible manner. From there we can hover nodes to get more information about the node and we can click on the legend to remove a node from the graph. This will re calculate the percentage taken up be each node amongst remaining, non hidden nodes.</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>var myConfig = {
type: 'pie',
title:{
text: '2013 Deaths',
adjustlayout: true
},
legend:{
toggleAction: 'remove'
},
plot:{
valueBox:{ // hard label
placement:'out'
}
},
tooltip:{ // for node hover
text:'%t: Had %v deaths in 2013'
},
series: [
{
values: [5000],
text: 'A000'
},
{
values: [400],
text: 'A411'
},
{
values: [200],
text: 'A00'
},
{
values: [900],
text: 'Other'
}
]
};
zingchart.render({
id: 'myChart',
data: myConfig,
height: '100%',
width: '100%'
});</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>html, body {
height:100%;
width:100%;
margin:0;
padding:0;
}
#myChart {
height:100%;
width:100%;
min-height:150px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<!--Assets will be injected here on compile. Use the assets button above-->
<script src= "https://cdn.zingchart.com/zingchart.min.js"></script>
<script> zingchart.MODULESDIR = "https://cdn.zingchart.com/modules/";
ZC.LICENSE = ["569d52cefae586f634c54f86dc99e6a9","ee6b7db5b51705a13dc2339db3edaf6d"];</script>
<!--Inject End-->
</head>
<body>
<div id="myChart"></div>
</body>
</html></code></pre>
</div>
</div>
</p>
| 4 | 2016-10-11T22:36:33Z | [
"python",
"python-3.x",
"dictionary",
"charts",
"pie-chart"
] |
adding accessing and deleting items from a python list | 39,969,124 | <p>Learning lists and arrays and I am not sure where I went wrong with this program. Keep in mind I am still new to python. Unsure if i am doing it right. Ive read a few tutorials and maybe Im not grasping list and arrays. Ive got it to where you can type a name but it doesnt transfer to a list and then i get list is empty constantly as well as other errors under other functions in the code.</p>
<pre><code> def display_menu():
print("")
print("1. Roster ")
print("2. Add")
print("3. Remove ")
print("4. Edit ")
print("9. Exit ")
print("")
return int(input("Selection> "))
def printmembers():
if namelist > 0:
print(namelist)
else:
print("List is empty")
def append(name):
pass
def addmember():
name = input("Type in a name to add: ")
append(name)
def remove():
pass
def removemember():
m = input("Enter Member name to delete:")
if m in namelist:
remove(m)
else:
print(m, "was not found")
def index():
pass
def editmember():
old_name = input("What would you like to change?")
if old_name in namelist:
item_number = namelist.index(old_name)
new_name = input("What is the new name? ")
namelist[item_number] = new_name
else:
print(old_name, 'was not found')
print("Welcome to the Team Manager")
namelist = 0
menu_item = display_menu()
while menu_item != 9:
if menu_item == 1:
printmembers()
elif menu_item == 2:
addmember()
elif menu_item == 3:
removemember()
elif menu_item == 4:
editmember()
menu_item = display_menu()
print("Exiting Program...")
</code></pre>
| 0 | 2016-10-11T01:22:23Z | 39,969,299 | <p>For starting out, you've got the right ideas and you're making good progress. The main problem is how you defined <code>namelist = 0</code>, making it a number. Instead, <code>namelist</code> needs to be an actual <code>list</code> for you to add or append anything to it. Also, you're <code>append()</code> method is not necessary since once you define <code>namelist</code> as a <code>list</code>, you can use the built-in <code>list.append()</code> method, without having to write your own method.
So here are a few suggestions/corrections, which once you have the basis working correctly, you should be able to work out the rest of the bug fixes and logic.</p>
<ol>
<li><p>Since you don't have any main() method, you can define <code>namelist</code> on
the <strong>first line of code</strong>, before any other code, so that it is
referenced in each method:<br>
<code>namelist = [] # an empty list</code></p></li>
<li><p>Change <code>addmember()</code> method to: </p>
<p><code>def addmember():
name = raw_input("Type in a name to add: ")
namelist.append(name)</code></p></li>
<li><p>Since <code>namelist</code> is a list, we can use the <code>built-in</code> <code>len()</code> method on <code>nameslist</code> to check if it's empty when printing out its contents (if any):</p>
<p><code>def printmembers():
if len(namelist) > 0: # Get the length of the list
print(namelist)
else:
print("List is empty")</code></p></li>
</ol>
<p>Now that the <code>Add()</code> menu option is working for adding a name to the <code>namelist</code>, you should be able to implement removing, and editing names to the list using similar logic.</p>
| 0 | 2016-10-11T01:45:44Z | [
"python"
] |
adding accessing and deleting items from a python list | 39,969,124 | <p>Learning lists and arrays and I am not sure where I went wrong with this program. Keep in mind I am still new to python. Unsure if i am doing it right. Ive read a few tutorials and maybe Im not grasping list and arrays. Ive got it to where you can type a name but it doesnt transfer to a list and then i get list is empty constantly as well as other errors under other functions in the code.</p>
<pre><code> def display_menu():
print("")
print("1. Roster ")
print("2. Add")
print("3. Remove ")
print("4. Edit ")
print("9. Exit ")
print("")
return int(input("Selection> "))
def printmembers():
if namelist > 0:
print(namelist)
else:
print("List is empty")
def append(name):
pass
def addmember():
name = input("Type in a name to add: ")
append(name)
def remove():
pass
def removemember():
m = input("Enter Member name to delete:")
if m in namelist:
remove(m)
else:
print(m, "was not found")
def index():
pass
def editmember():
old_name = input("What would you like to change?")
if old_name in namelist:
item_number = namelist.index(old_name)
new_name = input("What is the new name? ")
namelist[item_number] = new_name
else:
print(old_name, 'was not found')
print("Welcome to the Team Manager")
namelist = 0
menu_item = display_menu()
while menu_item != 9:
if menu_item == 1:
printmembers()
elif menu_item == 2:
addmember()
elif menu_item == 3:
removemember()
elif menu_item == 4:
editmember()
menu_item = display_menu()
print("Exiting Program...")
</code></pre>
| 0 | 2016-10-11T01:22:23Z | 39,969,314 | <p>You should consider initializing the list to be empty instead of zero (unless you want that element).</p>
<pre><code>namelist = list()
</code></pre>
<p>Also, your append method does not perform any actions. It's also pretty unnecessary since you can just use the append method of list.</p>
<pre><code>def addmember():
name = input("Type in a name to add: ")
namelist.append(name)
</code></pre>
<p>If you did want to make your own append method you should understand that the variables in the function definition are inputs, so just saying <code>def append(name)</code> won't perform any action. In this case <code>name</code> is the identifier you are applying to the input argument. You could just as easily call it anything you wanted. A good way to understand this is by assigning the argument a different variable name than the one you pass it. Like this:</p>
<pre><code>def append(nameToAppend):
namelist.append(nameToAppend)
</code></pre>
<p>You can call your append method in addmember like this:</p>
<pre><code>def addmember():
name = input("Type in a name to add: ")
append(name)
</code></pre>
| 0 | 2016-10-11T01:47:35Z | [
"python"
] |
adding accessing and deleting items from a python list | 39,969,124 | <p>Learning lists and arrays and I am not sure where I went wrong with this program. Keep in mind I am still new to python. Unsure if i am doing it right. Ive read a few tutorials and maybe Im not grasping list and arrays. Ive got it to where you can type a name but it doesnt transfer to a list and then i get list is empty constantly as well as other errors under other functions in the code.</p>
<pre><code> def display_menu():
print("")
print("1. Roster ")
print("2. Add")
print("3. Remove ")
print("4. Edit ")
print("9. Exit ")
print("")
return int(input("Selection> "))
def printmembers():
if namelist > 0:
print(namelist)
else:
print("List is empty")
def append(name):
pass
def addmember():
name = input("Type in a name to add: ")
append(name)
def remove():
pass
def removemember():
m = input("Enter Member name to delete:")
if m in namelist:
remove(m)
else:
print(m, "was not found")
def index():
pass
def editmember():
old_name = input("What would you like to change?")
if old_name in namelist:
item_number = namelist.index(old_name)
new_name = input("What is the new name? ")
namelist[item_number] = new_name
else:
print(old_name, 'was not found')
print("Welcome to the Team Manager")
namelist = 0
menu_item = display_menu()
while menu_item != 9:
if menu_item == 1:
printmembers()
elif menu_item == 2:
addmember()
elif menu_item == 3:
removemember()
elif menu_item == 4:
editmember()
menu_item = display_menu()
print("Exiting Program...")
</code></pre>
| 0 | 2016-10-11T01:22:23Z | 39,969,349 | <p>After getting name from input, you call the append(name) method, yet your append method doesn't do anything yet.</p>
<p>In your append method you have to add the name you get to your namelist, like how you do in the editmember method.</p>
| 0 | 2016-10-11T01:53:08Z | [
"python"
] |
Convert to np.array, some values automatically being divided | 39,969,143 | <p>I'm converting a list of strings into a list of lists, and then converting that list into a np.array. The format of each list 5 element array within the np.array of arrays is [latitude, longitude, elevation, index, classifier]. The classifier is <code>1</code> if the elevation is above 0.00 (land) or <code>0</code> if the elevation is 0.00 (sea).</p>
<p>I've just noticed something strange, which is that list before being converted to an np.array has the correct values for each entry, ie:</p>
<pre><code>[-33.765, 151.303, 49.227, 1373, 1],
[-33.765, 151.305, 0.0, 1374, 0]
</code></pre>
<p>where after being converted to an np.array, entries that have a classifier value of <code>1</code> (land) have been represented using e, whereas sea entries have remained the same, ie:</p>
<pre><code>[ -33.792 151.402 0. 3635. 0. ]
[ -3.37950000e+01 1.50900000e+02 7.75430000e+01 3.63600000e+03
1.00000000e+00]
</code></pre>
<p>I'm not sure even where to begin to try to figure out why this could/would happen. Is this some functionality of numpy arrays that I don't yet understand?</p>
<p>It's just taking in a .txt file containing geodesic coords in this format:</p>
<p>-33.750 151.025 90.882</p>
| 0 | 2016-10-11T01:25:51Z | 39,969,362 | <p>The <code>e</code> represents scientific notation. I am not sure why this only happens with the land case, but <a href="http://stackoverflow.com/questions/4205259/how-to-force-a-ndarray-show-in-normal-way-instead-of-scientific-notation">this StackOverflow question</a> could be helpful in setting up <code>numpy.set_print_options</code> with <code>suppress=True</code> to force floating-point formatting.</p>
| 1 | 2016-10-11T01:55:37Z | [
"python"
] |
python django id to hex | 39,969,151 | <p>I'm looking to take the default ID key from the django model turn it into hexadecimal and display it on a page when the user sumbits the post, I've tried several of methods with no success can anyone point me in the right direction?</p>
<p>views.py</p>
<pre><code>def post_new(request):
if request.method == "POST":
form = PostForm(request.POST)
if form.is_valid():
post = form.save(commit=False)
post.author = request.user
post.published_date = timezone.now()
post.save()
return redirect('post_detail', pk=post.pk)
else:
form = PostForm()
return render(request, 'books_log/post_edit.html', {'form': form})
</code></pre>
<p>Can supply more information if needed.</p>
| 1 | 2016-10-11T01:27:19Z | 39,969,326 | <p>Python's hex function is all you need here, but the problem is you can't call it directly from your template. So the solution is to add a method to your model.</p>
<pre><code>class MyModel(models.Model):
def to_hex(self):
return hex(self.pk)
</code></pre>
<p>Then in your template</p>
<pre><code> {{ my_object.to_hex }}
</code></pre>
| 0 | 2016-10-11T01:49:44Z | [
"python",
"django"
] |
Recommender engine in python - incorporate custom similarity metrics | 39,969,168 | <p>I am currently building a recommender engine in python and I faced the following problem.</p>
<p>I want to incorporate collaborative filtering approach, its user-user variant. To recap, its idea is that we have an information on different users and which items they liked (if applicable - which ratings these users assigned to items). When we have new user who liked couple of things we just find users who liked same items and recommend to this new user items which were liked by users similar to new user.</p>
<p>But I want to add some twist to it. I will be recommending places to users, namely 'where to go tonight'. I know user preferences, but I want to also incorporate the distance to each item I could recommend. The father the place I am going to recommend to the user - the least attractive it should be.</p>
<p>So in general I want to incorporate a penalty into recommendation engine and the amount of penalty for each place will be based on the distance from user to the place.</p>
<p>I tried to googleif anyone did something similar but wasn't able to find anything. Any advice on how to properly add such penalty? </p>
| 0 | 2016-10-11T01:29:20Z | 40,001,529 | <p>I would keep it simple and separate:</p>
<p>Your focus is collaborative filtering, so your recommender should generate scores for the top N recommendations <em>regardless of location</em>.</p>
<p>Then you can <strong>re-score</strong> using distance among those top-N. For a simple MVP, you could start with an inverse distance decay (e.g. <code>final-score = cf-score * 1/distance</code>), and adjust the decay function based on behavioral evidence if necessary.</p>
| 1 | 2016-10-12T14:41:31Z | [
"python",
"machine-learning",
"recommendation-engine",
"data-science"
] |
Convert UPPERCASE string to sentence case in Python | 39,969,202 | <p>How does one convert an uppercase string to proper sentence-case? Example string:</p>
<pre><code>"OPERATOR FAIL TO PROPERLY REMOVE SOLID WASTE"
</code></pre>
<p>Using <code>titlecase(str)</code> gives me:</p>
<pre><code>"Operator Fail to Properly Remove Solid Waste"
</code></pre>
<p>What I need is:</p>
<pre><code>"Operator fail to properly remove solid waste"
</code></pre>
<p>Is there an easy way to do this?</p>
| 1 | 2016-10-11T01:33:30Z | 39,969,233 | <p>This will work for any sentence, or any paragraph. Note that the sentence must end with a <code>.</code> or it won't be treated as a new sentence. (Stealing <code>.capitalize()</code> which is the better method, hats off to brianpck for that)</p>
<pre><code>a = 'hello. i am a sentence.'
a = '. '.join(i.capitalize() for i in a.split('. '))
</code></pre>
| 1 | 2016-10-11T01:37:50Z | [
"python"
] |
Convert UPPERCASE string to sentence case in Python | 39,969,202 | <p>How does one convert an uppercase string to proper sentence-case? Example string:</p>
<pre><code>"OPERATOR FAIL TO PROPERLY REMOVE SOLID WASTE"
</code></pre>
<p>Using <code>titlecase(str)</code> gives me:</p>
<pre><code>"Operator Fail to Properly Remove Solid Waste"
</code></pre>
<p>What I need is:</p>
<pre><code>"Operator fail to properly remove solid waste"
</code></pre>
<p>Is there an easy way to do this?</p>
| 1 | 2016-10-11T01:33:30Z | 39,969,258 | <p>Let's use an even more appropriate function for this: <a href="https://docs.python.org/2/library/string.html#string.capitalize" rel="nofollow"><code>string.capitalize</code></a></p>
<pre><code>>>> s="OPERATOR FAIL TO PROPERLY REMOVE SOLID WASTE"
>>> s.capitalize()
'Operator fail to properly remove solid waste'
</code></pre>
| 3 | 2016-10-11T01:40:23Z | [
"python"
] |
YTick overlapping in Matplotlib | 39,969,217 | <p>I have been trying to plot data on Matplotlib and I seem to have overlapping YTicks. I am not sure how to adjust them.</p>
<p><strong>Code</strong></p>
<pre><code>import matplotlib.pyplot as plt
data= [4270424, 4257372, 4100352, 4100356, 4100356]
plt.figure(figsize=(10,5))
plt.plot(data, 'ko-')
plt.ylabel('Data point')
plt.xlabel('Iteration point')
plt.yticks(data)
plt.margins(0.05, 0.1)
plt.show()
</code></pre>
<p><a href="http://i.stack.imgur.com/u8H5n.png" rel="nofollow"><img src="http://i.stack.imgur.com/u8H5n.png" alt="enter image description here"></a></p>
<p>What I wanted is that the numbers to be there, but is it possible to increase the space between the data points?</p>
| 2 | 2016-10-11T01:35:12Z | 39,996,352 | <p>If there are many close datapoints on y-axis, they overlap. You can avoid showing all of them. You can show only one of too close y-ticks. But the rest can be shown on the plot itself (not on y-axis).</p>
<p>Something like that can be used:</p>
<pre><code>import matplotlib.pyplot as plt
data= [4270424, 4257372, 4100352, 4100356, 4100356]
fig, ax = plt.subplots(figsize=(10,8))
#Collect only those ticks that are distant enough from each other
#in order to get rid of ticks overlapping on y-axis:
yticks = [min(data)]
for i in sorted(data[0:]):
if i-yticks[-1] > 3500:
yticks.append(i)
#################################################################
plt.plot(data, 'ko-')
plt.ylabel('Data point', fontsize=12)
plt.xlabel('Iteration point', fontsize=12)
plt.yticks(yticks)
plt.margins(0.05, 0.1)
#Showing y-ticks right on the plot
offset = -1.45
x = ax.get_xticks()
for xp, yp in zip(x, data):
label = "%s" % yp
plt.text(xp-offset, yp+offset, label, fontsize=12, horizontalalignment='right', verticalalignment='bottom')
#################################
ax.grid()
plt.show()
</code></pre>
<p><strong>Output:</strong>
<a href="https://i.stack.imgur.com/oaFir.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/oaFir.jpg" alt="enter image description here"></a></p>
<p>You can also switch off displaying <strong>yticks</strong> on y-axis completely. In this case change this line <code>plt.yticks(yticks)</code> to this: <code>plt.yticks(yticks, visible=False)</code>
In this case you don't need ticks collecting part of code at all. But if you keep it, you can turn displaying on later if needed. </p>
| 2 | 2016-10-12T10:29:40Z | [
"python",
"matplotlib"
] |
How to check for a range of values in a pandas dataframe? | 39,969,219 | <p>I have a pandas dataframe in which I want to check if a future value is greater than the given value for a range of future dates.
For example</p>
<pre><code>np.where((df['Close'].shift(-1) - df['Close']) > 0 , 1, 0)
</code></pre>
<p>This will give me if next value is greater than current value, I want to check if current value is greater than say next 5 values ?</p>
| 1 | 2016-10-11T01:35:26Z | 39,969,284 | <p>You could use <code>pd.rolling_max</code> for this, something like</p>
<pre><code>window = 5
pd.rolling_max(df['Close'], window).shift(-window) - df['Close']) > 0
</code></pre>
| 1 | 2016-10-11T01:43:43Z | [
"python",
"numpy",
"dataframe"
] |
Read a text file into a pandas dataframe or numpy array | 39,969,302 | <p>I have a file that looks like this - <a href="http://pastebin.com/u1A7v1CV" rel="nofollow">http://pastebin.com/u1A7v1CV</a></p>
<p>It's just a sample of two rows from a file.
The rows contain <code>word_label_id</code> followed by <code>freq</code>.
For example, <code>word_label_id</code> 1237 occurs 1 time in the first row, 1390 occurs 1 time and so on...</p>
<p>I need to use this sparse representation but I'm unable to convert it into a <code>DataFrame</code> or any other usable format. </p>
<p>Edit: I know that pandas has a <code>read_csv</code> method where I can use a space as the delimiter. This is not ideal as I need two separators - one between <code>word_label_id</code> and <code>freq</code> and a different separator between this pair and the next. </p>
| 0 | 2016-10-11T01:46:17Z | 39,969,403 | <p>Ok, it's not ideal but you can use notepad++.</p>
<p>It had a "find and replace" feature and you can use \t to replace tabs as \n</p>
<p>Then you can record a macro to move any given line to the previous, skipping lines.</p>
<p>Then you can use pandas, pd.from_csv but you have to define delimiters as tabs instead of commas </p>
<p>Another option is to read each line,and process it separately. Basically a while loop with the condition being not m_line == null</p>
<p>Then inside the loop, split the string up with str.split ()</p>
<p>And have another loop that makes a dictionary, for each row. In the end, you'd have a list of dictionaries where each entry is ID:frequency</p>
| 0 | 2016-10-11T02:00:01Z | [
"python",
"numpy",
"text",
"dataframe"
] |
Read a text file into a pandas dataframe or numpy array | 39,969,302 | <p>I have a file that looks like this - <a href="http://pastebin.com/u1A7v1CV" rel="nofollow">http://pastebin.com/u1A7v1CV</a></p>
<p>It's just a sample of two rows from a file.
The rows contain <code>word_label_id</code> followed by <code>freq</code>.
For example, <code>word_label_id</code> 1237 occurs 1 time in the first row, 1390 occurs 1 time and so on...</p>
<p>I need to use this sparse representation but I'm unable to convert it into a <code>DataFrame</code> or any other usable format. </p>
<p>Edit: I know that pandas has a <code>read_csv</code> method where I can use a space as the delimiter. This is not ideal as I need two separators - one between <code>word_label_id</code> and <code>freq</code> and a different separator between this pair and the next. </p>
| 0 | 2016-10-11T01:46:17Z | 39,969,916 | <p>Have you tried work separately with each item?</p>
<p>For example:</p>
<p>Open document:</p>
<pre><code>with open('delimiters.txt') as r:
lines = r.readlines()
linecontent = ' '.join(lines)
</code></pre>
<p>Create a list for each item:</p>
<pre><code>result = linecontent.replace(' ', ',').split(',')
</code></pre>
<p>Create sublist for ids and freqs:</p>
<pre><code>newResult = [result[x:x+2] for x in range(0, len(result), 2)]
</code></pre>
<p>Working with each data type:</p>
<pre><code>ids = [x[0][:] for x in newResult]
freq = [x[1][:] for x in newResult]
</code></pre>
<p>Create a DataFrame</p>
<pre><code>df = pandas.DataFrame({'A ids': ids, 'B freq': freq})
</code></pre>
<p><a href="http://i.stack.imgur.com/e7kOt.png" rel="nofollow"><img src="http://i.stack.imgur.com/e7kOt.png" alt="enter image description here"></a></p>
| 0 | 2016-10-11T03:07:00Z | [
"python",
"numpy",
"text",
"dataframe"
] |
Read a text file into a pandas dataframe or numpy array | 39,969,302 | <p>I have a file that looks like this - <a href="http://pastebin.com/u1A7v1CV" rel="nofollow">http://pastebin.com/u1A7v1CV</a></p>
<p>It's just a sample of two rows from a file.
The rows contain <code>word_label_id</code> followed by <code>freq</code>.
For example, <code>word_label_id</code> 1237 occurs 1 time in the first row, 1390 occurs 1 time and so on...</p>
<p>I need to use this sparse representation but I'm unable to convert it into a <code>DataFrame</code> or any other usable format. </p>
<p>Edit: I know that pandas has a <code>read_csv</code> method where I can use a space as the delimiter. This is not ideal as I need two separators - one between <code>word_label_id</code> and <code>freq</code> and a different separator between this pair and the next. </p>
| 0 | 2016-10-11T01:46:17Z | 39,989,718 | <p>Here's what I did.
This creates a dictionary containing key-value pairs
from each row. </p>
<pre><code>data = []
with open('../data/input.mat', 'r') as file:
for i, line in enumerate(file):
l = line.split()
d = dict([(k, v) for k, v in zip(l[::2], l[1::2])])
data.append(d)
</code></pre>
| 0 | 2016-10-12T02:45:59Z | [
"python",
"numpy",
"text",
"dataframe"
] |
Variable referenced before assignment error in prime factorization program? | 39,969,305 | <p>I am writing some code that is supposed to find the prime factorization of numbers. The main function increments through numbers; I'm doing that because I want to use the code to conduct timing experiments. I don't mind it not being super-efficient, part of the project for me will be making it more efficient myself. It is also not yet totally complete.</p>
<pre><code>import math
import time
primfac=[]
def primcheck(n):
for x in xrange(2, int(n**0.5)+1):
if n % x == 0:
return False
return True
def primes(n):
sieve = [True] * n
for i in xrange(3,int(n**0.5)+1,2):
if sieve[i]:
sieve[i*i::2*i]=[False]*((n-i*i-1)/(2*i)+1)
return [2] + [i for i in xrange(3,n,2) if sieve[i]]
def factfind(lsp,n): #finds factors of n among primes
for i in lsp:
if n%i==0:
primfac.append(i)
else:
i+=1
def simplify(lsp, n):
x = 1
for i in lsp:
x=i*x
if x != n:
print "needs exponent, computing"
for i in lsp:
y=n/i
if primcheck(y) == True:
lsp.append(y)
else:
lsp.append(factfind(primes,y))
def primfacfind(n1,n2):
while n1 <= n2:
time_start = time.clock()
if primcheck(n1) == True:
print "prime"
time_elapsed = time.clock() - time_start
print "time:", time_elapsed
n1+=1
else:
n = n1
print "starting #", n
factfind(primes(n),n)
print primfac
del primfac
primfac[:] = []
simplify(primfac, n)
time_elapsed = time.clock() - time_start
print "time:", time_elapsed
n1+=1
primfacfind(6,15)
</code></pre>
<p>When I run the code, it gives this error message:</p>
<pre class="lang-none prettyprint-override"><code>Traceback (most recent call last):
File "python", line 65, in <module>
File "python", line 54, in primfacfind
UnboundLocalError: local variable 'primfac' referenced before assignment
</code></pre>
<p>Which I don't understand because I've tested every function except the <code>simplify</code> function and even then the only new part is the lines after <code>print</code>.</p>
| 0 | 2016-10-11T01:46:31Z | 39,969,376 | <p>Functions in python can only access variables declared outside of function scope read-only without the global keyword.</p>
<pre><code>import math
import time
primfac=[]
def primcheck(n):
for x in xrange(2, int(n**0.5)+1):
if n % x == 0:
return False
return True
def primes(n):
sieve = [True] * n
for i in xrange(3,int(n**0.5)+1,2):
if sieve[i]:
sieve[i*i::2*i]=[False]*((n-i*i-1)/(2*i)+1)
return [2] + [i for i in xrange(3,n,2) if sieve[i]]
def factfind(lsp,n): #finds factors of n among primes
for i in lsp:
if n%i==0:
primfac.append(i)
else:
i+=1
def simplify(lsp, n):
x = 1
for i in lsp:
x=i*x
if x != n:
print "needs exponent, computing"
for i in lsp:
y=n/i
if primcheck(y) == True:
lsp.append(y)
else:
lsp.append(factfind(primes,y))
def primfacfind(n1,n2):
global primfac
while n1 <= n2:
time_start = time.clock()
if primcheck(n1) == True:
print "prime"
time_elapsed = time.clock() - time_start
print "time:", time_elapsed
n1+=1
else:
n = n1
print "starting #", n
factfind(primes(n),n)
print primfac
del primfac
primfac = []
simplify(primfac, n)
time_elapsed = time.clock() - time_start
print "time:", time_elapsed
n1+=1
primfacfind(6,15)
</code></pre>
| 1 | 2016-10-11T01:56:46Z | [
"python"
] |
Finding average of n numbers in a list | 39,969,308 | <p>Everything is working except when the user types N to end the while loop, it doesn't go to the For Statement (this happens when you run the program, works fine in the shell and in the py).</p>
<pre><code>potato = []
count = 0
avg = 0
question = input('Finding averages, continue? Y or N: ')
while question == 'Y' and count <= 12:
num = int(input('Enter a number: '))
potato.append(num)
count += 1
question = input('Continue? Y or N: ')
for fries in potato:
avg = sum(potato)/count
print(fries,fries-avg)
print('average is: ' + str(avg))
</code></pre>
| -3 | 2016-10-11T01:47:09Z | 39,969,387 | <p>It was breaking for me until I changed the input to raw_input. Now it exits the while loop when input is not Y:</p>
<pre><code>question = raw_input('Finding averages, continue? Y or N: ')
</code></pre>
| -3 | 2016-10-11T01:57:48Z | [
"python",
"python-3.x",
"input"
] |
How can I get values from python file to my html? | 39,969,388 | <p>I'm trying to get values from my phython file to my html. </p>
<p>Here's my form: </p>
<pre><code><div class="form-group ">
<label class="col-sm-3 col-sm-3 control-label">Direccion IP: </label>
<div class="col-sm-9">
<input type="text" class="form-control" value="{{ address }}" >
</div>
</div>
</code></pre>
<p>Here's my python file: </p>
<pre><code>def getinterfaces():
with open('/etc/network/interfaces', 'r+') as f:
for line in f:
found_address = line.find('address')
if found_address != -1:
address = line[found_address+len('address:'):]
print 'Address: ', address
return address
</code></pre>
<p>I tried with "FLASK" but nothing worked.. </p>
<blockquote>
<p>I think my problem is in my path , because my project is in
"project/app/Mensajeria/views.py", my html is in:
"project/app/templates/test.html"</p>
</blockquote>
<p>I'm importing Flask and everything, I have flask installed, I tried to reinstalled but nothing worked...</p>
| 1 | 2016-10-11T01:57:58Z | 39,974,135 | <p>If you're sending the data to be served up on a webpage, using the HTML template, how about something like this?</p>
<pre><code>@app.route('/test')
def showPage():
# your code here
address = # however you assign it
return render_template('test.html', address=address)
</code></pre>
<p>In order to use a variable inside <code>{{}}</code> in a template, you'll have to pass that variable to the template, such as here with <code>return render_template('test.html', address=address)</code>. </p>
<p>If you need <code>address</code> to contain many things you can always send it as a <code>list</code> or <code>dict</code> and extract the individual variables you need in your template with <code>jinja</code>. For example, if you need multiple <code><div></code> elements each containing an address:</p>
<h3>python file</h3>
<pre><code>@app.route('/test')
def showPage():
# your code here
addresses = # however you assign it
return render_template('test.html', addresses=addresses)
</code></pre>
<h3>test.html</h3>
<pre><code>{% for address in addresses %}
<div class="form-group ">
<label class="col-sm-3 col-sm-3 control-label">Direccion IP: </label>
<div class="col-sm-9">
<input type="text" class="form-control" value="{{ address }}" >
</div>
</div>
{% endfor %}
</code></pre>
| 0 | 2016-10-11T09:23:18Z | [
"python",
"html",
"python-2.7",
"flask",
"debian"
] |
Update Access table with value from another table via INNER JOIN | 39,969,438 | <p>I'm trying to update a column using pyodbc with data from a column in another table in the same database. I've tried:</p>
<pre><code>cursor.execute('''
UPDATE Prospect_SC_Fin_102016
SET Prospect_SC_Fin_102016.Sym_Ky=Symbol_Ref_102016.Sym_Ky
FROM Prospect_SC_Fin_102016
INNER JOIN Symbol_Ref_102016
ON Prospect_SC_Fin_102016.Symbol=Symbol_Ref_102016.Symbol;
''')
con.commit()
cursor.close()
con.close()
</code></pre>
<p>and get a "missing operator" syntax error.</p>
<p>I've also tried:</p>
<pre><code>cursor.execute('''
UPDATE Prospect_SC_Fin_102016
SET Prospect_SC_Fin_102016.Sym_Ky=(SELECT Sym_Ky
FROM Symbol_Ref_102016 WHERE Symbol IN
(SELECT Symbol FROM Prospect_SC_Fin_102016));
''')
con.commit()
cursor.close()
con.close()
</code></pre>
<p>which also errors out. What's the correct logic here?</p>
| 2 | 2016-10-11T02:04:05Z | 39,981,804 | <p>For an Access database you would want to use a query of the following form:</p>
<pre class="lang-sql prettyprint-override"><code>UPDATE Prospect_SC_Fin_102016
INNER JOIN Symbol_Ref_102016
ON Prospect_SC_Fin_102016.Symbol=Symbol_Ref_102016.Symbol
SET Prospect_SC_Fin_102016.Sym_Ky=Symbol_Ref_102016.Sym_Ky
</code></pre>
| 2 | 2016-10-11T16:08:23Z | [
"python",
"sql",
"ms-access",
"pyodbc"
] |
checking if a random value exists from previous loop | 39,969,463 | <p>I'm trying to generate a random value for each loop and save it to variable <code>minimum</code> WHILE doing a check if that number has already been generated before in one of the previous loops. </p>
<p><code>listQ</code> basically contains <strong>6 lines</strong> that were randomly chosen from a file. The lines were chosen from between <code>1</code> to <code>max_line</code> (which is basically 6 steps less than <code>max_line</code> value). So it's important that I have to generate a number that's a multiplier of 6.</p>
<pre><code>for x in range(0, 10):
minimum = random.randrange(0, max_line,6)
maximum = minimum+6
listQ = listQ[minimum:maximum]
</code></pre>
<p>A bit stuck here. A list maybe?</p>
| 3 | 2016-10-11T02:07:39Z | 39,969,921 | <p>Keep a list of all the previous values and check each subsequent iteration.</p>
<pre><code># sets have faster "val in set?" checks than lists
# do this once, somewhere in your program
previous_vals = set()
# other stuff here, including main program loop
for x in range(0, 10):
# find a unique, new random number while
# limiting number of tries to prevent infinite looping
number_of_tries = 0
MAX_TRIES = 10
generating_random = true
while generating_random:
minimum = random.randrange(0, max_line,6)
if minimum not in previous_vals:
previous_vals.add(minimum)
generating_random = false
number_of_tries += 1
if number_of_tries == MAX_TRIES:
raise RunTimeError("Maximum number of random tries reached!")
maximum = minimum+6
listQ = listQ[minimum:maximum]
</code></pre>
<p>Note that <a href="https://docs.python.org/2/library/stdtypes.html#set.add" rel="nofollow">there are other functions for <code>set</code> than add</a> if you want to modify your example. </p>
<p>I added a maximum number of tries too in order to prevent your code from getting stuck in an infinite loop, since I don't know anything about your input data to know what the likilhood of getting into this situation is.</p>
| 1 | 2016-10-11T03:07:22Z | [
"python",
"loops",
"random"
] |
Sort data within group - Pandas Dataframe | 39,969,493 | <p>I have the following data frame: </p>
<pre><code> As Comb Mu(+) Name Zone f´c
33 0.37 2 6.408225 Beam_13 Final 30.0
29 0.37 2 6.408225 Beam_13 Begin 30.0
31 0.94 2 16.408225 Beam_13 Middle 30.0
15 0.54 2 9.504839 Beam_7 Final 30.0
11 0.54 2 9.504839 Beam_7 Begin 30.0
13 1.12 2 19.504839 Beam_7 Middle 30.0
</code></pre>
<p>I need to sort the data by <code>Name</code> and then by <code>Zone</code> within a group as shown in the expected output below:</p>
<pre><code> As Comb Mu(+) Name Zone f´c
11 0.54 2 9.504839 Beam_7 Begin 30.0
13 1.12 2 19.504839 Beam_7 Middle 30.0
15 0.54 2 9.504839 Beam_7 Final 30.0
29 0.37 2 6.408225 Beam_13 Begin 30.0
31 0.94 2 16.408225 Beam_13 Middle 30.0
33 0.37 2 6.408225 Beam_13 Final 30.0
</code></pre>
<p>I can order by index, but not by name and zone within the <code>Name</code> group. Any ideas?</p>
| 1 | 2016-10-11T02:12:50Z | 39,969,891 | <p>The cleanest way is to convert the <code>Name</code> and <code>Zone</code> columns to the category type, specifying the categories and order. </p>
<pre><code>from io import StringIO
data = """
As,Comb,Mu(+),Name,Zone,f´c
33,0.37,2,6.408225,Beam_13,Final,30.0
29,0.37,2,6.408225,Beam_13,Begin,30.0
31,0.94,2,16.408225,Beam_13,Middle,30.0
15,0.54,2,9.504839,Beam_7,Final,30.0
11,0.54,2,9.504839,Beam_7,Begin,30.0
13,1.12,2,19.504839,Beam_7,Middle,30.0
"""
df = pd.read_csv(StringIO(data))
# convert Name and Zone to ordinal/category type
df.Name = df.Name.astype('category', categories=["Beam_7", "Beam_13"], ordered=True)
df.Zone = df.Zone.astype('category', categories=["Begin", "Middle", "Final"], ordered=True)
df.sort_values(by=['Name', 'Zone'])
</code></pre>
<p>Here's the output:</p>
<p><a href="http://i.stack.imgur.com/1PNzu.png" rel="nofollow"><img src="http://i.stack.imgur.com/1PNzu.png" alt="enter image description here"></a></p>
<p>Other options can be found <a href="http://stackoverflow.com/a/13839029/3453737">here</a></p>
| 3 | 2016-10-11T03:03:53Z | [
"python",
"sorting",
"pandas",
"group"
] |
Django Sanity Test Reveals 404 is not 404 | 39,969,494 | <p>I was creating sanity checks in my django tests and came across an error I had accounted for. Unfortunately my test fails when it should be successful. I am testing when a page is not there (a 404 status code). The error message and code are below. When I added quotes I received 404 is not '404'.</p>
<p>Django-1.10.2 & Python 3.4.5</p>
<pre><code>./manage.py test app
Traceback (most recent call last):
File "/tests/dir/tests.py", line 26, in test_404
self.assertIs(response.status_code,404)
AssertionError: 404 is not 404
from django.test import TestCase
from django.test import Client
class SanityCheckTests(TestCase):
def test_404(self):
"""
Http Code 404
"""
client = Client()
response = client.get('/test404')
print(response)
self.assertIs(response.status_code,404)
</code></pre>
| 1 | 2016-10-11T02:12:53Z | 39,969,883 | <p>You're on the right track - but <a href="https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertIs" rel="nofollow"><code>assertIs</code></a> ensures you have the same instance of an object. You just want to make sure they are <a href="https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertEqual" rel="nofollow">equal</a>.</p>
<p>Therefore, change your last line to </p>
<pre><code>self.assertEqual(response.status_code, 404)
</code></pre>
| 1 | 2016-10-11T03:02:59Z | [
"python",
"django",
"unit-testing",
"automated-tests",
"http-status-code-404"
] |
Conditionally update Data Frame column | 39,969,549 | <p>I'm trying to update a column from a value of 0 to a value of 1 if certain conditions are true. Here is my code:</p>
<pre><code>df_['win'] = 0
df_.loc[df_['predicted_spread'] > df_['vegas_spread'] and df_['actual_spread'] > df_['vegas_spread'], 'win'] = 1
</code></pre>
<p>This is the error I'm getting:</p>
<pre><code>ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
</code></pre>
<p>Does anybody have any ideas of what's going on here?</p>
| 0 | 2016-10-11T02:20:05Z | 39,970,018 | <p>Try</p>
<pre><code>df_['win'] = 0
df_.loc[df_['predicted_spread'].gt(df_['vegas_spread']) and df_['actual_spread'].gt(df_['vegas_spread']), 'win'] = 1
</code></pre>
| 1 | 2016-10-11T03:19:39Z | [
"python",
"pandas"
] |
Conditionally update Data Frame column | 39,969,549 | <p>I'm trying to update a column from a value of 0 to a value of 1 if certain conditions are true. Here is my code:</p>
<pre><code>df_['win'] = 0
df_.loc[df_['predicted_spread'] > df_['vegas_spread'] and df_['actual_spread'] > df_['vegas_spread'], 'win'] = 1
</code></pre>
<p>This is the error I'm getting:</p>
<pre><code>ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
</code></pre>
<p>Does anybody have any ideas of what's going on here?</p>
| 0 | 2016-10-11T02:20:05Z | 39,970,090 | <p>When doing boolean indexing you need to use the logical operator for <code>and</code> which is <code>&</code>. See the doc <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow">here</a> for more info</p>
<pre><code>df['win'] = 0
cond_1 = df['predicted_spread'] > df['vegas_spread']
cond_2 = df['actual_spread'] > df['vegas_spread']
df.loc[cond_1 & cond_2, 'win'] = 1
</code></pre>
<p>Basically just your answer with <code>&</code> instead of <code>and</code>. I just rewrote it to make it a little clearer.</p>
| 1 | 2016-10-11T03:28:24Z | [
"python",
"pandas"
] |
Why is this python code producing extremely large numbers? | 39,969,632 | <p>I have a python code which is the written below. What is disturbing to me is the large number that I am getting as output in the array <code>rhot</code>. This can't be true as <code>val</code> is mostly small number and these small numbers are further suppressed by the exponential factor as in the line</p>
<pre><code> rhot[i, j, k] = (rhot[i, j, k] + val[j, k, l] *
np.exp(-(vlist[i] - velz[j, k, l]) ** 2 / (2 * beta)))
</code></pre>
<p>Does any one know why I am getting large numbers as output for <code>rhot</code>?</p>
<pre><code>import numpy as np
import random
n = 6
val = np.empty((n, n, n)) # produces n*n*n empty matrix
for i in range(0, n - 1):
for j in range(0, n - 1):
for k in range(0, n - 1):
val[i, j, k] = random.lognormvariate(0, 1)
# produces lognormal random numbers with mean 1 and standard deviation 1
velz = np.empty((n, n, n))
for i in range(0, n - 1):
for j in range(0, n - 1):
for k in range(0, n - 1):
velz[i, j, k] = random.normalvariate(0, 1)
# produces normal random numbers with mean 1 and standard deviation 1
vmax = np.amax(velz) # maximum of flat velz array
vmin = np.amin(velz) # minimum
vlist = np.linspace(vmin, vmax, n)
# print(velz)
# print(val)
# print (vlist)
beta = 0.2
rhot = np.empty((n, n, n))
for i in range(0, n - 1): # index of velocity
for j in range(0, n - 1):
for k in range(0, n - 1):
for l in range(0, n - 1): # z index
rhot[i, j, k] = (rhot[i, j, k] + val[j, k, l] *
np.exp(-(vlist[i] - velz[j, k, l]) ** 2 / (2 * beta))) # sums over 3rd dimension l, and stores the sum.
print(rhot)
</code></pre>
| -1 | 2016-10-11T02:28:37Z | 39,969,828 | <p>I could be wrong, but when I run your code I get small values. Could it be that you're seeing things like <code>-3.53107108e-310</code> and confusing them for large numbers?
That's: </p>
<pre><code>-0.0 ... <307 '0's> ... 0353107108
</code></pre>
<p>See below for the full output:</p>
<pre><code>[[[ 1.27490729e+000 2.48048100e+000 3.07058432e+000 7.30862963e-001
3.61289051e-002 0.00000000e+000]
[ 1.29285884e+000 9.53558990e-001 1.16462089e+000 6.18595057e-001
4.56208365e-001 0.00000000e+000]
[ 3.48843064e-002 3.51048158e-001 6.72572870e-001 1.44242671e-004
1.08715529e-002 0.00000000e+000]
[ 1.34866696e+000 3.61798504e-002 4.94111513e-001 1.67366765e-001
1.45956417e+000 0.00000000e+000]
[ 2.11027716e+000 1.15784556e+000 6.16183788e-002 1.58361518e-001
5.75876010e-001 0.00000000e+000]
[ 0.00000000e+000 -2.22731705e-310 7.48734566e-315 7.48735151e-315
8.63509807e-312 0.00000000e+000]]
[[ 8.71788238e-001 8.75201841e+000 4.64974371e+000 2.59647886e+000
1.16994333e+000 0.00000000e+000]
[ 1.19599140e+000 8.74687167e-001 2.50158015e+000 2.75257757e+000
9.92597288e-001 0.00000000e+000]
[ 1.84015219e+000 1.12041236e+000 3.52262073e-001 1.49498067e-001
7.51724231e-001 0.00000000e+000]
[ 5.34739555e+000 2.75435540e+000 1.61068778e+001 1.59134588e+000
9.67835496e-001 0.00000000e+000]
[ 2.76116504e+000 2.03916401e+000 1.90723731e-001 2.82388640e+000
3.04602826e+000 0.00000000e+000]
[ 0.00000000e+000 -2.55325566e-310 7.48734566e-315 7.48735293e-315
8.63509811e-312 0.00000000e+000]]
[[ 5.24104854e+000 9.34017262e+000 4.00934108e+000 3.83152870e+000
1.62852403e+000 0.00000000e+000]
[ 3.32402433e-001 5.13142568e-001 1.56460377e+000 3.98199095e+000
3.10752863e+000 0.00000000e+000]
[ 7.32201046e+000 4.60614519e+000 6.65947236e-001 3.50609348e+000
2.43255192e+000 0.00000000e+000]
[ 1.20735878e+001 1.43430640e+001 1.13987763e+001 2.33564499e+000
4.11797274e+000 0.00000000e+000]
[ 4.56305322e+000 2.19230864e+000 2.04935419e+000 5.93349070e+000
1.34685870e+000 0.00000000e+000]
[ 0.00000000e+000 -2.87919425e-310 7.48734566e-315 7.48735435e-315
8.63509811e-312 0.00000000e+000]]
[[ 2.00871165e+000 1.07657987e+001 1.73466587e+000 5.37829126e+000
1.67186888e+000 0.00000000e+000]
[ 7.04409708e-001 9.18488325e-001 5.65912359e+000 3.07782156e+000
1.90251174e+000 0.00000000e+000]
[ 2.61090422e+000 1.76056043e+000 4.02183805e+000 5.16605380e+000
2.54000338e+000 0.00000000e+000]
[ 5.83011318e+000 3.84800152e+000 1.52000638e+000 2.67037387e+000
3.79550774e+000 0.00000000e+000]
[ 4.66619590e-001 4.10817751e+000 5.59173904e+000 1.44794224e+000
3.69302488e-001 0.00000000e+000]
[ 0.00000000e+000 -3.20513286e-310 7.48734566e-315 7.48734803e-315
8.63509813e-312 0.00000000e+000]]
[[ 1.79494277e-002 3.42477445e-001 1.69493310e-002 4.18988338e-001
2.47334739e+000 0.00000000e+000]
[ 1.06263981e-001 3.27704176e-001 6.35008094e-001 1.01981741e-001
8.65984592e+000 0.00000000e+000]
[ 1.19169164e-001 1.93839020e-001 1.63208875e+000 1.34924978e+000
2.13064890e+000 0.00000000e+000]
[ 7.85718993e-001 4.96021083e+000 3.80732389e-001 3.45316057e+000
2.54260569e-001 4.11408160e-304]
[ 3.11511258e-003 3.52866964e-001 2.00264974e+000 2.47368641e-002
6.53491661e-001 3.70335798e-318]
[ 0.00000000e+000 -3.53107108e-310 7.48734328e-315 7.48734249e-315
8.63509820e-312 0.00000000e+000]]
[[ 0.00000000e+000 -3.58539416e-310 7.48734407e-315 7.48734234e-315
8.63509829e-312 0.00000000e+000]
[ 0.00000000e+000 -3.63971726e-310 7.48734313e-315 7.48734866e-315
8.63509783e-312 0.00000000e+000]
[ 0.00000000e+000 -3.69404039e-310 7.48734392e-315 7.48734265e-315
8.63509828e-312 0.00000000e+000]
[ 0.00000000e+000 -3.74836347e-310 7.48734360e-315 7.48734249e-315
8.63509814e-312 0.00000000e+000]
[ 0.00000000e+000 -3.80268659e-310 7.48734439e-315 7.48734234e-315
8.63509327e-312 0.00000000e+000]
[ 0.00000000e+000 -3.85700970e-310 7.48734392e-315 7.48734249e-315
8.63509814e-312 0.00000000e+000]]]
</code></pre>
| 0 | 2016-10-11T02:55:15Z | [
"python",
"loops",
"random",
"iteration"
] |
How do I delete a substring from a string without using .replace()? | 39,969,686 | <p>For my CS class we try to focus on creating and using algorithms instead of just using built in methods. For this program I have to remove a substring from a string (if the substring is in the string), but I can't use .replace(). I can't figure out how to do this without 'hardcoding' and not coming up with an algorithm that works for all cases. I've tried just adding the characters into a new list unless they are in the substring, but this doesn't work if there's a character in the substring but not part of the substring within the string. Can anyone point me in a direction that can help me solve this?</p>
<p>The string I'm having trouble with is 'eph' in 'catelephant' and 'eph' in 'cephatelephant'. </p>
<p>I've tried iterating using something like this:</p>
<pre><code>string2 = ""
if substring in string1:
for i in string1:
if i != substring1
string2 += i
</code></pre>
<p>But this is obviously problematic as it doesn't account for multiples of the same character in the substring but are not within the substring in the string. i.e. the first e in catelephant would be removed. </p>
<p>edit: i can only use the len() or append functions</p>
| -2 | 2016-10-11T02:34:50Z | 39,969,868 | <p>You can do that:</p>
<pre><code>myString = myString[0:myString.index(mySubstring)] + myString[myString.index(mySubstring)+len(mySubstring):]
</code></pre>
<p>But of course it will replace just the first occurrence. So if mySubstring is <em>eph</em> and myString is <em>cephatelephant</em> and you would like to remove the two substrings, you would have to call the code above twice. For example (I'm using ipython here):</p>
<pre><code>In [14]: mySubstring = 'eph'
In [15]: myString = 'cephatelephant'
In [16]: myString = myString[0:myString.index(mySubstring)] + myString[myString.index(mySubstring)+len(mySubstring):]
In [17]: print myString
catelephant
In [18]: myString = myString[0:myString.index(mySubstring)] + myString[myString.index(mySubstring)+len(mySubstring):]
In [19]: print myString
catelant
</code></pre>
| 0 | 2016-10-11T03:00:14Z | [
"python",
"python-2.7"
] |
How to process input and output shape for keras LSTM | 39,969,717 | <p>I am learning about RNN and I wrote this simple LSTM model in keras (theano) using a sample dataset generated using sklearn.</p>
<pre><code>from sklearn.datasets import make_regression
from keras.models import Sequential
from keras.layers import Dense,Activation,LSTM
#creating sample dataset
X,Y=make_regression(100,9,9,2)
X.shape
Y.shape
#creating LSTM model
model = Sequential()
model.add(LSTM(32, input_dim=9))
model.add(Dense(2))
model.compile(loss='mean_squared_error', optimizer='adam')
#model fitting
model.fit(X, Y, nb_epoch=1, batch_size=32)
</code></pre>
<p>The sample data set contains 9 features and 2 targets. when I tried to fit my model using those features and targets its giving me this error</p>
<pre><code>Exception: Error when checking model input: expected lstm_input_9 to have 3 dimensions, but got array with shape (100, 9)
</code></pre>
| 0 | 2016-10-11T02:39:27Z | 39,970,734 | <p>If I'm correct, then LSTM expects a 3D input.</p>
<pre><code>X = np.random.random((100, 10, 64))
y = np.random.random((100, 2))
model = Sequential()
model.add(LSTM(32, input_shape=(10, 64)))
model.add(Dense(2))
model.compile(loss='mean_squared_error', optimizer='adam')
model.fit(X, Y, nb_epoch=1, batch_size=32)
</code></pre>
<p><strong>UPDATE</strong>: If you want to convert <code>X, Y = make_regression(100, 9, 9, 2)</code> into 3D, then you can use this.</p>
<pre><code>from sklearn.datasets import make_regression
from keras.models import Sequential
from keras.layers import Dense,Activation,LSTM
#creating sample dataset
X, Y = make_regression(100, 9, 9, 2)
X = X.reshape(X.shape + (1,))
#creating LSTM model
model = Sequential()
model.add(LSTM(32, input_shape=(9, 1)))
model.add(Dense(2))
model.compile(loss='mean_squared_error', optimizer='adam')
model.fit(X, Y, nb_epoch=1, batch_size=32)
</code></pre>
| 1 | 2016-10-11T04:57:43Z | [
"python",
"theano",
"keras"
] |
Exponentiation Recursive | 39,969,737 | <p>I am learning this Exponentiation Recursive algorithm, it works well.
But I don't understand why this works?
Because I expect that always returns 1,1,1...if <code>n</code> is even because a doesn't multiply in the <code>return</code>.<br>
When I try <code>recPower(3,2)</code>, and print the factor step by step, it will be like:</p>
<p>1
3
9</p>
<p>But, why does 3 come out?</p>
<pre><code> def recPower(a, n):
# raises a to the int power n
if n == 0:
return 1
else:
factor = recPower(a, n//2)
if n%2 == 0: # n is even
return factor * factor
else: # n is odd
return factor * factor * a
</code></pre>
| -2 | 2016-10-11T02:42:48Z | 39,969,808 | <p>Just follow it step by step:</p>
<pre><code>recPower(3, 2)
</code></pre>
<p><code>n != 0</code> so go down the else branch:</p>
<pre><code>factor = recPower(3, 2//2)
</code></pre>
<p>Which is:</p>
<pre><code>recPower(3, 1)
</code></pre>
<p>In this recursive step <code>n != 0</code> we follow the first else branches, <code>1%2 != 0</code> so we follow the second else branch. The factor is therefore 1 and <code>a</code> == 3.</p>
<p>The return value of this step is therefore:</p>
<pre><code>factor * factor * a
</code></pre>
<p>or</p>
<pre><code>1 * 1 * 3
</code></pre>
| 0 | 2016-10-11T02:52:39Z | [
"python",
"python-3.x",
"computer-science"
] |
digest of a pandas Index | 39,969,773 | <p>I would like to <strong>efficiently</strong> compute a digest of a Pandas DataFrame that uniquely and reproducibly identifies its content (for versioning purposes). Assume for now that I don't worry about endianness, dtypes, types of the index nor columns. Also assume that both index and columns are already sorted monotonic_increasing.</p>
<p>Things go reasonably well with the values (again, for simplification, assume <code>np.float64</code>). But I am having trouble with the index (and columns) and don't get a consistent digest. Of course I can do things such as converting the index into String and then utf-8 bytes, but that is slow.</p>
<p>Here is a simplified example:</p>
<pre><code>import hashlib
def pd_val_sha1(df):
x = df.values
if not x.flags.c_contiguous:
x = x.copy(order='C')
return hashlib.sha1(x).hexdigest()
</code></pre>
<p>Test:</p>
<pre><code>import pandas as pd
import io
str = """s,e,id,x,y,z
2012-01-01,2013-01-01,b,NaN,2,3
2015-10-27,2015-11-03,a,0.04,12.7,NaN
2015-11-15,2016-01-01,a,7.3,-1.2,8
"""
df = pd.read_csv(io.StringIO(str), parse_dates=[0,1], index_col=[0,1,2]).sort_index()
df
</code></pre>
<p>Out:</p>
<pre><code> x y z
s e id
2012-01-01 2013-01-01 b NaN 2.0 3.0
2015-10-27 2015-11-03 a 0.04 12.7 NaN
2015-11-15 2016-01-01 a 7.30 -1.2 8.0
</code></pre>
<p>SHA-1 of the values:</p>
<pre><code>pd_val_sha1(df)
>>> 'a7f0335988a967606bd030864e0e30ce03f32ec9'
pd_val_sha1(df.head())
>>> 'a7f0335988a967606bd030864e0e30ce03f32ec9'
pd_val_sha1(pd.concat([df.ix[0:2], df.ix[2:3]]))
>>> 'a7f0335988a967606bd030864e0e30ce03f32ec9'
</code></pre>
<p>So far, so good. But when it comes to the index:</p>
<pre><code>pd_val_sha1(df.index)
>>> inconsistent value (re-run the example from read_csv and we'll get
... a different result).
</code></pre>
<p>I tried various other things, e.g. using <code>index.data</code> or <code>index.to_native_types()</code> or <code>np.array(index.tolist())</code> instead of <code>index.values</code>, but I still get inconsistent results, as I suppose the underlying data can vary.</p>
<p>One thing that seems to be working so far is <code>hashlib.sha1(np.array(df.index.format())).hexdigest()</code>. But it is slow, e.g. 2min 34s for a (5000000,12) dataframe, whereas the content itself is fingerprinted in 900ms. </p>
<p>Any suggestions?</p>
| 1 | 2016-10-11T02:47:51Z | 39,969,817 | <p>Sometimes the solution is right under our nose...</p>
<pre><code>from sklearn.externals import joblib
%%time
joblib.hash(df, hash_name='sha1')
>>> consistent value that depends on values and axes
Wall time: 1.66 s (for the (5000000,12) DataFrame mentioned above)
</code></pre>
| 1 | 2016-10-11T02:54:07Z | [
"python",
"pandas",
"digest"
] |
More memory efficient way of making a dictionary? | 39,969,798 | <p>VERY sorry for the vagueness, but I don't actually know what part of what I'm doing is inefficient. </p>
<p>I've made a program that takes a list of positive integers (example*):</p>
<pre><code>[1, 1, 3, 5, 16, 2, 4, 6, 6, 8, 9, 24, 200,]
</code></pre>
<p>*the real lists can be up to 2000 in length and the elements between 0 and 100,000 exclusive</p>
<p>And creates a dictionary where each number tupled with its index (like so: <code>(number, index)</code>) is a key and the value for each key is a list of every number (and that number's index) in the input that it goes evenly into.</p>
<p>So the entry for the 3 would be: <code>(3, 2): [(16, 4), (6, 7), (6, 8), (9, 10), (24, 11)]</code></p>
<p>My code is this:</p>
<pre><code>num_dict = {}
sorted_list = sorted(beginning_list)
for a2, a in enumerate(sorted_list):
num_dict[(a, a2)] = []
for x2, x in enumerate(sorted_list):
for y2, y in enumerate(sorted_list[x2 + 1:]):
if y % x == 0:
pair = (y, y2 + x2 + 1)
num_dict[(x, x2)].append(pair)
</code></pre>
<p>But, when I run this script, I hit a <code>MemoryError</code>.</p>
<p>I understand that this means that I am running out of memory but in the situation I'm in, adding more ram or updating to a 64-bit version of python is not an option.</p>
<p>I am certain that the problem is not coming from the list sorting or the first for loop. It has to be the second for loop. I just included the other lines for context.</p>
<p>The full output for the list above would be (sorry for the unsortedness, that's just how dictionaries do):</p>
<pre><code>(200, 12): []
(6, 7): [(24, 11)]
(16, 10): []
(6, 6): [(6, 7), (24, 11)]
(5, 5): [(200, 12)]
(4, 4): [(8, 8), (16, 10), (24, 11), (200, 12)]
(9, 9): []
(8, 8): [(16, 10), (24, 11), (200, 12)]
(2, 2): [(4, 4), (6, 6), (6, 7), (8, 8), (16, 10), (24, 11), (200, 12)]
(24, 11): []
(1, 0): [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (6, 7), (8, 8), (9, 9), (16, 10), (24, 11), (200, 12)]
(1, 1): [(2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (6, 7), (8, 8), (9, 9), (16, 10), (24, 11), (200, 12)]
(3, 3): [(6, 6), (6, 7), (9, 9), (24, 11)]
</code></pre>
<p>Is there a better way of going about this?</p>
<h3>EDIT:</h3>
<p>This dictionary will then be fed into this:</p>
<pre><code>ans_set = set()
for x in num_dict:
for y in num_dict[x]:
for z in num_dict[y]:
ans_set.add((x[0], y[0], z[0]))
return len(ans_set)
</code></pre>
<p>to find all unique possible triplets in which the 3rd value can be evenly divided by the 2nd value which can be evenly divided by the 1st.</p>
<p>If you think you know of a better way of doing the entire thing, I'm open to redoing the whole of it.</p>
<h1>Final Edit</h1>
<p>I've found the best way to find the number of triples by reevaluating what I needed it to do. This method doesn't actually find the triples, it just counts them.</p>
<pre><code>def foo(l):
llen = len(l)
total = 0
cache = {}
for i in range(llen):
cache[i] = 0
for x in range(llen):
for y in range(x + 1, llen):
if l[y] % l[x] == 0:
cache[y] += 1
total += cache[x]
return total
</code></pre>
<p>And here's a version of the function that explains the thought process as it goes (not good for huge lists though because of spam prints):</p>
<pre><code>def bar(l):
list_length = len(l)
total_triples = 0
cache = {}
for i in range(list_length):
cache[i] = 0
for x in range(list_length):
print("\n\nfor index[{}]: {}".format(x, l[x]))
for y in range(x + 1, list_length):
print("\n\ttry index[{}]: {}".format(y, l[y]))
if l[y] % l[x] == 0:
print("\n\t\t{} can be evenly diveded by {}".format(l[y], l[x]))
cache[y] += 1
total_triples += cache[x]
print("\t\tcache[{0}] is now {1}".format(y, cache[y]))
print("\t\tcount is now {}".format(total_triples))
print("\t\t(+{} from cache[{}])".format(cache[x], x))
else:
print("\n\t\tfalse")
print("\ntotal number of triples:", total_triples)
</code></pre>
| 3 | 2016-10-11T02:50:40Z | 39,969,874 | <p>Well, you could <em>start</em> by not unnecessarily duplicating information.</p>
<p>Storing full tuples (number and index) for each multiple is inefficient when you already have that information available.</p>
<p>For example, rather than:</p>
<pre><code>(3, 2): [(16, 4), (6, 7), (6, 8), (9, 10), (24, 11)]
</code></pre>
<p>(the <code>16</code> appears to be wrong there as it's <em>not</em> a multiple of <code>3</code> so I'm guessing you meant <code>15</code>) you could instead opt for:</p>
<pre><code>(3, 2): [15, 6, 9, 24]
(6, 7): ...
</code></pre>
<p>That pretty much halves your storage needs since you can go from the <code>6</code> in the list and find all its indexes by searching the tuples. That will, of course, be extra <em>processing</em> effort to traverse the list but it's probably better to have a slower working solution than a faster non-working one :-)</p>
<hr>
<p>You could reduce the storage even more by not storing the multiples at all, instead running through the tuple list using <code>%</code> to see if you have a multiple.</p>
<hr>
<p>But, of course, this all depends on your <em>actual</em> requirements which would be better off stating the <em>intent</em> of what your trying to achieve rather than pre-supposing a solution.</p>
| 2 | 2016-10-11T03:01:22Z | [
"python",
"algorithm",
"dictionary"
] |
More memory efficient way of making a dictionary? | 39,969,798 | <p>VERY sorry for the vagueness, but I don't actually know what part of what I'm doing is inefficient. </p>
<p>I've made a program that takes a list of positive integers (example*):</p>
<pre><code>[1, 1, 3, 5, 16, 2, 4, 6, 6, 8, 9, 24, 200,]
</code></pre>
<p>*the real lists can be up to 2000 in length and the elements between 0 and 100,000 exclusive</p>
<p>And creates a dictionary where each number tupled with its index (like so: <code>(number, index)</code>) is a key and the value for each key is a list of every number (and that number's index) in the input that it goes evenly into.</p>
<p>So the entry for the 3 would be: <code>(3, 2): [(16, 4), (6, 7), (6, 8), (9, 10), (24, 11)]</code></p>
<p>My code is this:</p>
<pre><code>num_dict = {}
sorted_list = sorted(beginning_list)
for a2, a in enumerate(sorted_list):
num_dict[(a, a2)] = []
for x2, x in enumerate(sorted_list):
for y2, y in enumerate(sorted_list[x2 + 1:]):
if y % x == 0:
pair = (y, y2 + x2 + 1)
num_dict[(x, x2)].append(pair)
</code></pre>
<p>But, when I run this script, I hit a <code>MemoryError</code>.</p>
<p>I understand that this means that I am running out of memory but in the situation I'm in, adding more ram or updating to a 64-bit version of python is not an option.</p>
<p>I am certain that the problem is not coming from the list sorting or the first for loop. It has to be the second for loop. I just included the other lines for context.</p>
<p>The full output for the list above would be (sorry for the unsortedness, that's just how dictionaries do):</p>
<pre><code>(200, 12): []
(6, 7): [(24, 11)]
(16, 10): []
(6, 6): [(6, 7), (24, 11)]
(5, 5): [(200, 12)]
(4, 4): [(8, 8), (16, 10), (24, 11), (200, 12)]
(9, 9): []
(8, 8): [(16, 10), (24, 11), (200, 12)]
(2, 2): [(4, 4), (6, 6), (6, 7), (8, 8), (16, 10), (24, 11), (200, 12)]
(24, 11): []
(1, 0): [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (6, 7), (8, 8), (9, 9), (16, 10), (24, 11), (200, 12)]
(1, 1): [(2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (6, 7), (8, 8), (9, 9), (16, 10), (24, 11), (200, 12)]
(3, 3): [(6, 6), (6, 7), (9, 9), (24, 11)]
</code></pre>
<p>Is there a better way of going about this?</p>
<h3>EDIT:</h3>
<p>This dictionary will then be fed into this:</p>
<pre><code>ans_set = set()
for x in num_dict:
for y in num_dict[x]:
for z in num_dict[y]:
ans_set.add((x[0], y[0], z[0]))
return len(ans_set)
</code></pre>
<p>to find all unique possible triplets in which the 3rd value can be evenly divided by the 2nd value which can be evenly divided by the 1st.</p>
<p>If you think you know of a better way of doing the entire thing, I'm open to redoing the whole of it.</p>
<h1>Final Edit</h1>
<p>I've found the best way to find the number of triples by reevaluating what I needed it to do. This method doesn't actually find the triples, it just counts them.</p>
<pre><code>def foo(l):
llen = len(l)
total = 0
cache = {}
for i in range(llen):
cache[i] = 0
for x in range(llen):
for y in range(x + 1, llen):
if l[y] % l[x] == 0:
cache[y] += 1
total += cache[x]
return total
</code></pre>
<p>And here's a version of the function that explains the thought process as it goes (not good for huge lists though because of spam prints):</p>
<pre><code>def bar(l):
list_length = len(l)
total_triples = 0
cache = {}
for i in range(list_length):
cache[i] = 0
for x in range(list_length):
print("\n\nfor index[{}]: {}".format(x, l[x]))
for y in range(x + 1, list_length):
print("\n\ttry index[{}]: {}".format(y, l[y]))
if l[y] % l[x] == 0:
print("\n\t\t{} can be evenly diveded by {}".format(l[y], l[x]))
cache[y] += 1
total_triples += cache[x]
print("\t\tcache[{0}] is now {1}".format(y, cache[y]))
print("\t\tcount is now {}".format(total_triples))
print("\t\t(+{} from cache[{}])".format(cache[x], x))
else:
print("\n\t\tfalse")
print("\ntotal number of triples:", total_triples)
</code></pre>
| 3 | 2016-10-11T02:50:40Z | 39,970,466 | <p>You rebuild tuples in places like <code>pair = (y, y2 + x2 + 1)</code> and <code>num_dict[(x, x2)].append(pair)</code> when you could build a canonical set of tuples early on and then just put references in the containers. I cobbled up a 2000 item test my machine that works. I have python 3.4 64 bit with a relatively modest 3.5 GIG of RAM...</p>
<pre><code>import random
# a test list that should generate longish lists
l = list(random.randint(0, 2000) for _ in range(2000))
# setup canonical index and sort ascending
sorted_index = sorted((v,i) for i,v in enumerate(l))
num_dict = {}
for idx, vi in enumerate(sorted_index):
v = vi[0]
num_dict[vi] = [vi2 for vi2 in sorted_index[idx+1:] if not vi2[0] % v]
for item in num_dict.items():
print(item)
</code></pre>
| 2 | 2016-10-11T04:21:57Z | [
"python",
"algorithm",
"dictionary"
] |
Import Eve, but upon running run.py, says there is no module named eve | 39,969,864 | <p>I have recently begun looking at Eve. </p>
<p>I have read the Eve <a href="http://python-eve.org/install.html" rel="nofollow">install guide</a> and imported it successfully. </p>
<p>Then, I tried the <a href="http://python-eve.org/quickstart.html" rel="nofollow">quick start guide</a>, and made a few changes to the settings.py. When I try running run.py, it gives me this error:</p>
<pre><code>Traceback (most recent call last): File "run.py", line 1, in
<module> from eve import Eve ImportError: No module named eve
</code></pre>
<p>This is my code for run.py:</p>
<pre><code>from eve import Eve
app = Eve()
if __name__ == '__main__':
app.run()
</code></pre>
<p>And this is my code for settings.py</p>
<pre><code>MONGO_HOST = 'localhost'
MONGO_PORT = 27017
MONGO_DBNAME = 'clownsighting'
RESOURCE_METHODS = ['GET', 'POST', 'DELETE']
ITEM_METHODS = ['GET', 'PATCH', 'PUT', 'DELETE']
schema = {
'scarinesslevel' : {'type' : 'string'},
'date' : {'type' : 'date'},
'address' : { 'type' : 'string' },
'city' : {'type' : 'string'},
'state' : {'type' : 'string'},
'country' : {'type' : 'string'},
'continent' : {'type' : 'string'}
}
sightings = {
'additional_lookup' : {
'url' : 'regex("[\w]+")',
'field' : 'date'
},
'schema' : schema
}
DOMAIN = {'sightings': sightings,}
</code></pre>
<p>The two files are in the same directory, if that helps.</p>
| 1 | 2016-10-11T02:59:34Z | 39,971,100 | <p>Looks like Eve is not installed (or you are not in the correct virtual environment). A <code>pip freeze</code> will tell you which modules are currently installed. If Eve is not listed, try <code>pip install eve</code>.</p>
| 0 | 2016-10-11T05:42:57Z | [
"python",
"mongodb",
"eve"
] |
Import Eve, but upon running run.py, says there is no module named eve | 39,969,864 | <p>I have recently begun looking at Eve. </p>
<p>I have read the Eve <a href="http://python-eve.org/install.html" rel="nofollow">install guide</a> and imported it successfully. </p>
<p>Then, I tried the <a href="http://python-eve.org/quickstart.html" rel="nofollow">quick start guide</a>, and made a few changes to the settings.py. When I try running run.py, it gives me this error:</p>
<pre><code>Traceback (most recent call last): File "run.py", line 1, in
<module> from eve import Eve ImportError: No module named eve
</code></pre>
<p>This is my code for run.py:</p>
<pre><code>from eve import Eve
app = Eve()
if __name__ == '__main__':
app.run()
</code></pre>
<p>And this is my code for settings.py</p>
<pre><code>MONGO_HOST = 'localhost'
MONGO_PORT = 27017
MONGO_DBNAME = 'clownsighting'
RESOURCE_METHODS = ['GET', 'POST', 'DELETE']
ITEM_METHODS = ['GET', 'PATCH', 'PUT', 'DELETE']
schema = {
'scarinesslevel' : {'type' : 'string'},
'date' : {'type' : 'date'},
'address' : { 'type' : 'string' },
'city' : {'type' : 'string'},
'state' : {'type' : 'string'},
'country' : {'type' : 'string'},
'continent' : {'type' : 'string'}
}
sightings = {
'additional_lookup' : {
'url' : 'regex("[\w]+")',
'field' : 'date'
},
'schema' : schema
}
DOMAIN = {'sightings': sightings,}
</code></pre>
<p>The two files are in the same directory, if that helps.</p>
| 1 | 2016-10-11T02:59:34Z | 40,002,657 | <p>I figured it out. I was not running the command </p>
<pre><code>python run.py
</code></pre>
<p>inside the virtual environment. I have now, and it works.</p>
| 0 | 2016-10-12T15:33:59Z | [
"python",
"mongodb",
"eve"
] |
ValueError: math domain error While Using Logarithms | 39,969,882 | <p>I am currently working on a code to find a value C which I will then compare against other parameters. However, whenever I try to run my code I receive this error: ValueError: math domain error. I am unsure why I am receiving this error, though I think it's how I setup my equation. Maybe there is a better way to write it. This is my code:</p>
<pre><code>import os
import math
path = "C:\Users\Documents\Research_Papers"
uH2 =5
uHe = 3
eH2 = 2
eHe = 6
R = ((uH2*eH2)/(uHe*eHe))
kH2=[]
kHe=[]
print(os.getcwd()) # see where you are
os.chdir(path) # use a raw string so the backslashes are ok
print(os.getcwd()) # convince yourself that you're in the right place
print(os.listdir(path)) # make sure the file is in here
myfile=open("[email protected]","r")
lines=myfile.readlines()
for x in lines:
kH2.append(x.split(' ')[1])
kHe.append(x.split(' ')[0])
myfile.close()
print kH2
print kHe
g = len(kH2)
f = len(kHe)
print g
print f
for n in range(0,7):
C = (((math.log(float(kH2[n]),10)))-(math.log(float(kHe[n]),10)))/math.log(R,10)
print C
</code></pre>
<p>It then returns this line saying that there is a domain error.</p>
<pre><code>C = (((math.log(float(kH2[n]),10)))-(math.log(float(kHe[n]),10)))/math.log(R,10)
ValueError: math domain error
</code></pre>
<p>Also, for the text file, I am just using a random list of 6 numbers for now as I am trying to get my code working before I put the real list of numbers in. The numbers I am using are: </p>
<pre><code>5 10 4 2
6 20 1 2
7 30 4 2
8 40 3 2
9 23 1 2
4 13 6 2
</code></pre>
| 0 | 2016-10-11T03:02:28Z | 39,970,900 | <p>Try to check if the value inside the log is not a negative value as negative value to a log function is a domain error.</p>
<p>Hope this helps.</p>
| 0 | 2016-10-11T05:16:57Z | [
"python"
] |
Python removal of items after iteration | 39,969,896 | <p>Why is my code not working? I can't figure it out</p>
<pre><code>matchList = [['g', 'h', 'i'], ['a', 'b', 'c'] ... ]]
myList = []
for i in match_list:
for j in i:
for word in first_list:
if j in word:
myList.append(j)
match_list.remove(j)
</code></pre>
<p>I am getting the error <code>ValueError: list.remove(x): x not in list</code></p>
<p>EDIT:</p>
<pre><code>first_list = ['i', 'am', 'an', 'old', 'man']
</code></pre>
| 0 | 2016-10-11T03:04:42Z | 39,969,923 | <p>You want: </p>
<pre><code>i.remove(j)
</code></pre>
<p>match_list is a list of lists</p>
| 2 | 2016-10-11T03:07:40Z | [
"python"
] |
Python removal of items after iteration | 39,969,896 | <p>Why is my code not working? I can't figure it out</p>
<pre><code>matchList = [['g', 'h', 'i'], ['a', 'b', 'c'] ... ]]
myList = []
for i in match_list:
for j in i:
for word in first_list:
if j in word:
myList.append(j)
match_list.remove(j)
</code></pre>
<p>I am getting the error <code>ValueError: list.remove(x): x not in list</code></p>
<p>EDIT:</p>
<pre><code>first_list = ['i', 'am', 'an', 'old', 'man']
</code></pre>
| 0 | 2016-10-11T03:04:42Z | 39,970,028 | <pre><code>list_of_lists = [['g', 'h', 'i'], ['a', 'b', 'c'] ... ]]
first_list = ['i', 'am', 'an', 'old', 'man']
myList = []
for current_list in list_of_lists:
for item in current_list:
for word in first_list:
if item in word:
myList.append(item)
list_of_lists.remove(item)
</code></pre>
<p>I edited your code so it would read more sensibly, to me, so I can think I know what you're trying to do.</p>
<p>In my mind, you are reading through a list, from within a set of lists to check to see if an item from that "sublist" is in another list (first_list).</p>
<p>If the item is in one of the words in first list, you are trying to remove the "sublist" from list_of_lists, correct? If so, that's where you are getting your error. Say you are on the first iteration of the set of lists, and you are checking to see if the letter "i" from the first sublist in list_of_lists is in the first word from first_list. It should evaluate to true. At that point, you are then telling Python the following in plain english, "Python, remove the item from list_of_lists that has a value of i." However, because list_of_lists contains lists, that won't work, because none of the values within list_of_lists are strings, just lists.</p>
<p>What you need to do is specify the list you are currently iterating on, which will be represented by current_list in the above code.</p>
<p>So maybe instead of </p>
<pre><code>list_of_lists.remove(item)
</code></pre>
<p>or rather in your code</p>
<pre><code>match_list.remove(j)
</code></pre>
<p>try </p>
<pre><code>list_of_lists.remove(current_list)
</code></pre>
<p>or rather in your code </p>
<pre><code>match_list.remove(i).
</code></pre>
<p>I have a feeling you are going to experience other errors with the iterations that will likely remain in some scenarios if you get another match, but that's not the problem you're having now....</p>
| 0 | 2016-10-11T03:20:59Z | [
"python"
] |
Python removal of items after iteration | 39,969,896 | <p>Why is my code not working? I can't figure it out</p>
<pre><code>matchList = [['g', 'h', 'i'], ['a', 'b', 'c'] ... ]]
myList = []
for i in match_list:
for j in i:
for word in first_list:
if j in word:
myList.append(j)
match_list.remove(j)
</code></pre>
<p>I am getting the error <code>ValueError: list.remove(x): x not in list</code></p>
<p>EDIT:</p>
<pre><code>first_list = ['i', 'am', 'an', 'old', 'man']
</code></pre>
| 0 | 2016-10-11T03:04:42Z | 39,970,191 | <p>Try this:</p>
<p><em>btw: you used <code>matchList</code> and <code>match_list</code> in your post. I corrected that for my answer to make it consistent.</em></p>
<pre><code>matchList = [['g', 'h', 'i'], ['a', 'b', 'c']]
myList = []
first_list = ['i', 'am', 'an', 'old', 'man']
for i in matchList:
for j in i:
for word in first_list:
if j in word:
myList.append(j)
for s in myList:
if s in i:
i.remove(s)
print(myList)
['i', 'a', 'a', 'a']
print(matchList)
[['g', 'h'], ['b', 'c']]
</code></pre>
| 0 | 2016-10-11T03:41:41Z | [
"python"
] |
Python removal of items after iteration | 39,969,896 | <p>Why is my code not working? I can't figure it out</p>
<pre><code>matchList = [['g', 'h', 'i'], ['a', 'b', 'c'] ... ]]
myList = []
for i in match_list:
for j in i:
for word in first_list:
if j in word:
myList.append(j)
match_list.remove(j)
</code></pre>
<p>I am getting the error <code>ValueError: list.remove(x): x not in list</code></p>
<p>EDIT:</p>
<pre><code>first_list = ['i', 'am', 'an', 'old', 'man']
</code></pre>
| 0 | 2016-10-11T03:04:42Z | 39,970,296 | <p>You could try a list comprehesion after iteration.</p>
<pre><code>matchList = [['g', 'h', 'i'], ['a', 'b', 'c']]
first_list = ['i', 'am', 'an', 'old', 'man']
myList = []
for i in matchList:
for j in i:
for word in first_list:
if j in word:
myList.append(j)
# Remove items from sublists
matchList = [[j for j in matchList[i] if j not in myList] for i in range(len(matchList))]
</code></pre>
<p>Output:</p>
<pre><code>In [7]: myList
Out[7]: ['i', 'a', 'a', 'a']
In [8]: matchList
Out[8]: [['g', 'h'], ['b', 'c']]
</code></pre>
| 0 | 2016-10-11T03:57:55Z | [
"python"
] |
Python - KeyboardInterrupt or RuntimeError implementation | 39,970,040 | <p>New to python and programming. I have a program consist of several classes, module and functions. the program runs from a main class which calls several modules and function</p>
<p>My question is how to implement keyboardinterrupt if the user wants to terminate a running program at any point. Do I need to implement 'try/except' method in all the functions? or this can be implementable in the main function? </p>
<p>To catch interrupt at any moment do I need to use try/except in all the calling functions?</p>
<pre><code>def KEYBOARD_INTERRUPT():
while True:
yesnoinput=raw_input('Do you want to exit from software [Y/N]:')
if yesnoinput=='y' or yesnoinput.upper()=='Y':
sys.exit()
elif yesnoinput=='n' or yesnoinput.upper()=='N':
break
else:
continue
def A():
while True:
try:
userInput=raw_input("Please enter A")
if userInput=='A':
break
else:
continue
except KeyboardInterrupt:
KEYBOARD_INTERRUPT()
def B():
userInput=raw_input("Please enter B")
if userInput=='B':
break
else:
continue
def main():
try:
A()
B()
except:
KEYBOARD_INTERRUPT()
</code></pre>
<p>when main program is calling function B, at this moment if the user presses keyboardInterrupt the program will quit with error messgage, I am worried if I want to handle interrupt like KEYBOARD_INTERRUPT function I need to implement this in very function such as function A?</p>
<p>Did I understand wrong? </p>
| 0 | 2016-10-11T03:22:29Z | 39,970,073 | <p>You could do something like :</p>
<pre><code>try:
...
except KeyboardInterrupt:
Do something
</code></pre>
| 0 | 2016-10-11T03:26:19Z | [
"python"
] |
Python - KeyboardInterrupt or RuntimeError implementation | 39,970,040 | <p>New to python and programming. I have a program consist of several classes, module and functions. the program runs from a main class which calls several modules and function</p>
<p>My question is how to implement keyboardinterrupt if the user wants to terminate a running program at any point. Do I need to implement 'try/except' method in all the functions? or this can be implementable in the main function? </p>
<p>To catch interrupt at any moment do I need to use try/except in all the calling functions?</p>
<pre><code>def KEYBOARD_INTERRUPT():
while True:
yesnoinput=raw_input('Do you want to exit from software [Y/N]:')
if yesnoinput=='y' or yesnoinput.upper()=='Y':
sys.exit()
elif yesnoinput=='n' or yesnoinput.upper()=='N':
break
else:
continue
def A():
while True:
try:
userInput=raw_input("Please enter A")
if userInput=='A':
break
else:
continue
except KeyboardInterrupt:
KEYBOARD_INTERRUPT()
def B():
userInput=raw_input("Please enter B")
if userInput=='B':
break
else:
continue
def main():
try:
A()
B()
except:
KEYBOARD_INTERRUPT()
</code></pre>
<p>when main program is calling function B, at this moment if the user presses keyboardInterrupt the program will quit with error messgage, I am worried if I want to handle interrupt like KEYBOARD_INTERRUPT function I need to implement this in very function such as function A?</p>
<p>Did I understand wrong? </p>
| 0 | 2016-10-11T03:22:29Z | 39,970,215 | <p>Exceptions flow up the stack, terminating each function execution block as it goes. If all you want is a nice message, catch it at the top, in your main. This script has two mains - one that catches, one that doesnt. As you can see, the non-catcher shows a stack trace of where each function broke execution but its kinda ugly. The catcher masks all that - although it could still write the info to a log file if it wanted to.</p>
<pre><code>import sys
import time
def do_all_the_things():
thing1()
def thing1():
thing2()
def thing2():
time.sleep(120)
def main_without_handler():
do_all_the_things()
def main_with_handler():
try:
do_all_the_things()
except KeyboardInterrupt:
sys.stderr.write("Program terminated by user\n")
exit(2)
if __name__ == "__main__":
# any param means catch the exception
if len(sys.argv) == 1:
main_without_handler()
else:
main_with_handler()
</code></pre>
<p>Run it from the console and hit ctrl-c and you get:</p>
<pre><code>td@mintyfresh ~/tmp $ python3 test.py
^CTraceback (most recent call last):
File "test.py", line 26, in <module>
main_without_handler()
File "test.py", line 14, in main_without_handler
do_all_the_things()
File "test.py", line 5, in do_all_the_things
thing1()
File "test.py", line 8, in thing1
thing2()
File "test.py", line 11, in thing2
time.sleep(120)
KeyboardInterrupt
td@mintyfresh ~/tmp $
td@mintyfresh ~/tmp $
td@mintyfresh ~/tmp $ python3 test.py handled
^CProgram terminated by user
</code></pre>
| 0 | 2016-10-11T03:45:40Z | [
"python"
] |
ValueError for comparison of np.arrays | 39,970,099 | <p>I have a list of lists of np.arrays, representing islands > island > geodesic point on the island.</p>
<p>I'm trying to use:</p>
<pre><code>if not groups:
createNewGroup(point)
else:
for group in groups:
if point in group:
continue
else:
createNewGroup(point)
</code></pre>
<p>The first island is being created correctly, but for the second island I am getting this error:</p>
<pre><code>File "A2.py", line 371, in findIslands
if point in group:
ValueError: The truth value of an array with more than
one element is ambiguous. Use a.any() or a.all()
</code></pre>
<p>I've researched this error and am trying to understand how this applies to my situation, and have tried applying <code>.any()</code> and <code>.all()</code> to <code>point</code> but I am getting the same error regardless.</p>
<p>I'm trying to check if the current geodesic point is already in the list of lists for any of the islands. Point is multidimensional and I think that's where the issue is coming from.</p>
| 0 | 2016-10-11T03:29:21Z | 39,972,291 | <p>This error arises when a boolean array is used in a scalar context, such as an <code>if</code> statement. Or maybe in the <code>in</code> part of the expression.</p>
<p>Is <code>point</code> an array, and <code>group</code> a list of arrays?</p>
<p>In general <code>in</code> is not a good test when working with arrays.</p>
<p>To get more help print <code>point</code>, <code>group</code>, <code>point in group</code>. Or at least their type, shape and dtype.</p>
<p>Make a small list of <code>point</code>, and focus on to perform an <code>in</code> test or equivalent. How do you tell whether one equals another? <code>point1 == point2</code>?</p>
| 0 | 2016-10-11T07:27:33Z | [
"python",
"numpy"
] |
Codec error when writing Python dictionary into CSV | 39,970,213 | <p>Below is a sample of my dictionary:</p>
<pre><code>dict = {'Croatia': '191', 'Cuba': '192', 'Curaçao': '531',
'Cyprus': '196', 'Czechia': '203', 'Czechoslovakia': '200',
"Côte d'Ivoire": '384', "Dem. People's Rep. of Korea": '408',
'Dem. Rep. of the Congo': '180', 'Denmark': '208'}
</code></pre>
<p>My goal is to try to write the diction into a csv file so each row will have one key and one value, such as:</p>
<blockquote>
<p>Croatia, 191 </p>
<p>Cuba, 192</p>
</blockquote>
<p>and I am using <code>csv</code> for this purpose:</p>
<pre><code>import csv
with open('dict.csv', 'w') as csv_file:
writer = csv.writer(csv_file)
for key, value in dict.items():
writer.writerow([key.encode('utf-8'), value])
</code></pre>
<p>when not using <code>key.encode('utf-8')</code>, Python gives the error of <strong>'ascii' codec can't encode character '\xf4' in position 1: ordinal not in range(128)</strong>, presumably cuased by <code>Côte d'Ivoire</code> in the dictionary. However, even when a csv file can be successfully produced now, the csv file itself contains additional characters <code>b'countryname'</code> instead of <code>countryname</code>.</p>
<p>(see the image for reference: <a href="http://imgur.com/a/WH2gF" rel="nofollow">http://imgur.com/a/WH2gF</a>)</p>
<p>How do I solve this particular issue?</p>
| 0 | 2016-10-11T03:45:35Z | 39,970,241 | <p><a href="https://docs.python.org/2/library/csv.html" rel="nofollow">The docs</a> cover how to handle encoding. Trying to encode individual elements does not, as you have seen, work out well.</p>
| 0 | 2016-10-11T03:49:54Z | [
"python",
"csv",
"dictionary"
] |
Codec error when writing Python dictionary into CSV | 39,970,213 | <p>Below is a sample of my dictionary:</p>
<pre><code>dict = {'Croatia': '191', 'Cuba': '192', 'Curaçao': '531',
'Cyprus': '196', 'Czechia': '203', 'Czechoslovakia': '200',
"Côte d'Ivoire": '384', "Dem. People's Rep. of Korea": '408',
'Dem. Rep. of the Congo': '180', 'Denmark': '208'}
</code></pre>
<p>My goal is to try to write the diction into a csv file so each row will have one key and one value, such as:</p>
<blockquote>
<p>Croatia, 191 </p>
<p>Cuba, 192</p>
</blockquote>
<p>and I am using <code>csv</code> for this purpose:</p>
<pre><code>import csv
with open('dict.csv', 'w') as csv_file:
writer = csv.writer(csv_file)
for key, value in dict.items():
writer.writerow([key.encode('utf-8'), value])
</code></pre>
<p>when not using <code>key.encode('utf-8')</code>, Python gives the error of <strong>'ascii' codec can't encode character '\xf4' in position 1: ordinal not in range(128)</strong>, presumably cuased by <code>Côte d'Ivoire</code> in the dictionary. However, even when a csv file can be successfully produced now, the csv file itself contains additional characters <code>b'countryname'</code> instead of <code>countryname</code>.</p>
<p>(see the image for reference: <a href="http://imgur.com/a/WH2gF" rel="nofollow">http://imgur.com/a/WH2gF</a>)</p>
<p>How do I solve this particular issue?</p>
| 0 | 2016-10-11T03:45:35Z | 39,970,270 | <p>Well, I recommend you to use <code>Pandas</code> for your purpose.</p>
<pre><code>import pandas as pd
country_name = dict.keys()
cnt = dict.values()
df = pd.DataFrame({'countryname':country_name,'count':cnt})
df.to_csv('result.csv',sep=',',encoding='utf-8')
</code></pre>
| 0 | 2016-10-11T03:53:25Z | [
"python",
"csv",
"dictionary"
] |
Python3 parse XML into dictionary | 39,970,288 | <p>It seems the original post was too vague, so I'm narrowing down the focus of this post. I have an XML file from which I want to pull values from specific branches, and I am having difficulty in understanding how to effectively navigate the XML paths. Consider the XML file below. There are several <code><mi></code> branches. I want to store the <code><r></code> value of certain branches, but not others. In this example, I want the <code><r></code> values of counter1 and counter3, but not counter2.</p>
<pre><code><?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="Data.xsl" ?>
<!DOCTYPE mdc SYSTEM "Data.dtd">
<mdc xmlns:HTML="http://www.w3.org/TR/REC-xml">
<mfh>
<vn>TEST</vn>
<cbt>20140126234500.0+0000</cbt>
</mfh>
<mi>
<mts>20140126235000.0+0000</mts>
<mt>counter1</mt>
<mv>
<moid>DEFAULT</moid>
<r>58</r>
</mv>
</mi>
<mi>
<mts>20140126235000.0+0000</mts>
<mt>counter2</mt>
<mv>
<moid>DEFAULT</moid>
<r>100</r>
</mv>
</mi>
<mi>
<mts>20140126235000.0+0000</mts>
<mt>counter3</mt>
<mv>
<moid>DEFAULT</moid>
<r>7</r>
</mv>
</mi>
</mdc>
</code></pre>
<p>From that I would like to build a tuple with the following:
('20140126234500.0+0000', 58, 7)
where 20140126234500.0+0000 is taken from <code><cbt></code>, 58 is taken from the <code><r></code> value of the <code><mi></code> element that has <code><mt>counter1</mt></code> and 7 is taken from the <code><mi></code> element that has <code><mt>counter3</mt></code>.</p>
<p>I would like to use <code>xml.etree.cElementTree</code> since it seems to be standard and should be more than capable for my purposes. But I am having difficulty in navigating the tree and extracting the values I need. Below is some of what I have tried.</p>
<pre><code>try:
import xml.etree.cElementTree as ET
except ImportError:
import xml.etree.ElementTree as ET
tree = ET.ElementTree(file='Data.xml')
root = tree.getroot()
for mi in root.iter('mi'):
print(mi.tag)
for mt in mi.findall("./mt") if mt.value == 'counter1':
print(mi.find("./mv/r").value) #I know this is invalid syntax, but it's what I want to do :)
</code></pre>
<p>From a pseudo code standpoint, what I am wanting to do is:</p>
<pre><code>find the <cbt> value and store it in the first position of the tuple.
find the <mi> element where <mt>counter1</mt> exists and store the <r> value in the second position of the tuple.
find the <mi> element where <mt>counter3</mt> exists and store the <r> value in the third position of the tuple.
</code></pre>
<p>I'm not clear when to use <code>element.iter()</code> or <code>element.findall()</code>. Also, I'm not having the best of luck with using <code>XPath</code> within the functions, or being able to extract the info I'm needing.</p>
<p>Thanks,
Rusty</p>
| -1 | 2016-10-11T03:56:47Z | 39,982,781 | <p>Starting with:</p>
<pre><code>import xml.etree.cElementTree as ET # or with try/except as per your edit
xml_data1 = """<?xml version="1.0"?> and the rest of your XML here"""
tree = ET.fromstring(xml_data) # or `ET.parse(<filename>)`
xml_dict = {}
</code></pre>
<p>Now <code>tree</code> has the xml tree and <code>xml_dict</code> will be the dictionary you're trying to get the result.</p>
<pre><code># first get the key & val for 'cbt'
cbt_val = tree.find('mfh').find('cbt').text
xml_dict['cbt'] = cbt_val
</code></pre>
<p>The counters are in <code>'mi'</code>:</p>
<pre><code>for elem in tree.findall('mi'):
counter_name = elem.find('mt').text # key
counter_val = elem.find('mv').find('r').text # value
xml_dict[counter_name] = counter_val
</code></pre>
<p>At this point, <code>xml_dict</code> is:</p>
<pre><code>>>> xml_dict
{'counter2': '100', 'counter1': '58', 'cbt': '20140126234500.0+0000', 'counter3': '7'}
</code></pre>
<hr>
<p>Some shortening, though possibly not as read-able: the code in the <code>for elem in tree.findall('mi'):</code> loop can be:</p>
<pre><code>xml_dict[elem.find('mt').text] = elem.find('mv').find('r').text
# that combines the key/value extraction to one line
</code></pre>
<p>Or further, building the <code>xml_dict</code> can be done in just two lines with the counters first and <code>cbt</code> after:</p>
<pre><code>xml_dict = {elem.find('mt').text: elem.find('mv').find('r').text for elem in tree.findall('mi')}
xml_dict['cbt'] = tree.find('mfh').find('cbt').text
</code></pre>
<hr>
<p><em>Edit:</em></p>
<p><a href="https://docs.python.org/3/library/xml.etree.elementtree.html#finding-interesting-elements" rel="nofollow">From the docs</a>, <a href="https://docs.python.org/3/library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.findall" rel="nofollow"><code>Element.findall()</code></a> finds only elements with a tag which are direct children of the current element.</p>
<p><code>find()</code> only finds the first direct child.</p>
<p><a href="https://docs.python.org/3/library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.iter" rel="nofollow"><code>iter()</code></a> iterates over all the elements recursively.</p>
| 1 | 2016-10-11T17:05:03Z | [
"python",
"xml",
"elementtree"
] |
why it is skipping the whole for loop? | 39,970,333 | <p>I have created a website scraper which will scrape all info from yellow pages (for educational purposes) </p>
<pre><code>def actual_yellow_pages_scrape(link,no,dir,gui,sel,ypfind,terminal,user,password,port,type):
print(link,no,dir,gui,sel,ypfind,terminal,user,password,port,type)
r = requests.get(link,headers=REQUEST_HEADERS)
soup = BeautifulSoup(r.content,"html.parser")
workbook = xlwt.Workbook()
sheet = workbook.add_sheet(str(ypfind))
count = 0
for i in soup.find_all(class_="business-name"):
sheet.write(count,0,str(i.text))
sheet.write(count,1,str("http://www.yellowpages.com"+i.get("href")))
r1 = requests.get("http://www.yellowpages.com"+i.get("href"))
soup1 = BeautifulSoup(r1.content,"html.parser")
website = soup1.find("a",class_="custom-link")
try:
print("Acquiring Website")
sheet.write(count,2,str(website.get("href")))
except:
sheet.write(count,2,str("None"))
email = soup1.find("a",class_="email-business")
try:
print(email.get("href"))
EMAIL = re.sub("mailto:","",str(email.get("href")))
sheet.write(count,3,str(EMAIL))
except:
sheet.write(count,3,str("None"))
phonetemp = soup1.find("div",class_="contact")
try:
phone = phonetemp.find("p")
print(phone.text)
sheet.write(count,4,str(phone.text))
except:
sheet.write(count,4,str("None"))
reviews = soup1.find(class_="count")
try:
print(reviews.text)
sheet.write(count,5,str(reviews.text))
except:
sheet.write(count,5,str("None"))
count+=1
save = dir+"\\"+ypfind+str(no)+".xls"
workbook.save(save)
no+=1
for i in soup.find_all("a",class_="next ajax-page"):
print(i.get("href"))
actual_yellow_pages_scrape("http://www.yellowpages.com"+str(i.get("href")),no,dir,gui,sel,ypfind,terminal,user,password,port,type)
</code></pre>
<p>The code is my above portion of the scraper. I have created the break points at soup and in the for loop not even a single line of for loop gets executed. No errors thrown. I tried the same with printing numbers from 1-10 it works but this is not working why?</p>
<p>Thank you</p>
| -2 | 2016-10-11T04:02:27Z | 39,971,098 | <p>Answer has been found,</p>
<p>I used a text visulaizer to find what is in "r.content" I soupified it and got a clean HTML and gone through the HTML file and finally found that the browser is unsupported so I removed the requests header and ran the code finally got what I wanted</p>
| 0 | 2016-10-11T05:42:43Z | [
"python"
] |
importing issues between modules | 39,970,364 | <pre><code>|--------FlaskApp
|----------------FlaskApp
|----------------__init__.py
|----------------view.py
|----------------models.py
|----------------db_create.py
|-----------------------static
|-----------------------templates
|-----------------------venv
|-----------------------__init__.py
|----------------flaskapp.wsgi
</code></pre>
<p>this is my modules and folder layout i have a import problem in init i have <pre>db = sqlalchemy</pre> im trying to import <strong>db</strong> to <strong>views.py, models.py and db_create.py</strong> but im getting all kinds of importing errors because im not importing thr proper way now my question is if i want to import db to the modules i specified how would i do it without getting a error</p>
<p><strong>some of the code importing db</strong></p>
<p><strong>models.py</strong></p>
<pre><code>from FlaskApp import db
class UserInfo(db.Model):
__tablename_ = 'user_info'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True)
email = db.Column(db.String(80), unique=True)
password = db.Column(db.String(100), nullable=False)
posts = relationship('UserPosts', backref='posts')
def __init__(self, username, email, password):
self.username = username
self.email = email
self.password = password
def __repr__(self):
return '{}-{}'.format(self.username, self.email)
</code></pre>
<p><strong>views.py</strong></p>
<pre><code>from FlaskApp import db
@app.route('/')
@login_required
def home():
user = db.session.query(UserInfo).all()
return render_template('home.html', user=user)
</code></pre>
<p><strong>__init__.py</strong></p>
<pre><code>from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy(app)
tail /var/log/apache2/error.log
[Tue Oct 11 04:17:20.925573 2016] [wsgi:error] [pid 5049:tid 139870897813248] [client 174.58.31.189:55884] Traceback (most recent call last):, referer: http://localhost/
[Tue Oct 11 04:17:20.925618 2016] [wsgi:error] [pid 5049:tid 139870897813248] [client 174.58.31.189:55884] File "/var/www/FlaskApp/flaskapp.wsgi", line 14, in <module>, referer: http://localhost/
[Tue Oct 11 04:17:20.925626 2016] [wsgi:error] [pid 5049:tid 139870897813248] [client 174.58.31.189:55884] from FlaskApp import app as application, referer: http://localhost/
[Tue Oct 11 04:17:20.925638 2016] [wsgi:error] [pid 5049:tid 139870897813248] [client 174.58.31.189:55884] File "/var/www/FlaskApp/FlaskApp/__init__.py", line 4, in <module>, referer: http://localhost/
[Tue Oct 11 04:17:20.925644 2016] [wsgi:error] [pid 5049:tid 139870897813248] [client 174.58.31.189:55884] import FlaskApp.main, referer: http://localhost/
[Tue Oct 11 04:17:20.925653 2016] [wsgi:error] [pid 5049:tid 139870897813248] [client 174.58.31.189:55884] File "/var/www/FlaskApp/FlaskApp/main.py", line 7, in <module>, referer: http://localhost/
[Tue Oct 11 04:17:20.925658 2016] [wsgi:error] [pid 5049:tid 139870897813248] [client 174.58.31.189:55884] from models import UserInfo, referer: http://localhost/
[Tue Oct 11 04:17:20.925668 2016] [wsgi:error] [pid 5049:tid 139870897813248] [client 174.58.31.189:55884] File "/var/www/FlaskApp/FlaskApp/models.py", line 2, in <module>, referer: http://localhost/
[Tue Oct 11 04:17:20.925673 2016] [wsgi:error] [pid 5049:tid 139870897813248] [client 174.58.31.189:55884] from FlaskApp import db, referer: http://localhost/
[Tue Oct 11 04:17:20.925707 2016] [wsgi:error] [pid 5049:tid 139870897813248] [client 174.58.31.189:55884] ImportError: cannot import name 'db', referer: http://localhost/
</code></pre>
<p>my goal is not just to solve one error is to be able to import the right way from now on</p>
| -1 | 2016-10-11T04:07:58Z | 39,971,777 | <p>This is actually the most painful moment for a Flask learner. Basically, your <code>FlaskApp</code> is dependent on <code>FlaskApp.main</code> then <code>FlaskApp.models</code> and then back to <code>FlaskApp</code> which create a perfect case of circular dependency.</p>
<p>Here's the way which I think is elegant and pythonic, by attaching the <code>db</code> variable to <code>app</code> in <code>__init__.py</code>:</p>
<pre><code>from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy(app)
app.db = db
with app.app_context():
import FlaskApp.main
</code></pre>
<p>In <code>main.py</code>:</p>
<pre><code>from flask import current_app as app
from .models import UserInfo
@app.route('/')
@login_required
def home():
user = app.db.session.query(UserInfo).all()
return render_template('home.html', user=user)
</code></pre>
<p>In <code>models.py</code>:</p>
<pre><code>from flask import current_app as app
db = app.db
class UserInfo(db.Model):
__tablename_ = 'user_info'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True)
email = db.Column(db.String(80), unique=True)
password = db.Column(db.String(100), nullable=False)
posts = relationship('UserPosts', backref='posts')
def __init__(self, username, email, password):
self.username = username
self.email = email
self.password = password
def __repr__(self):
return '{}-{}'.format(self.username, self.email)
</code></pre>
<p>Then you can use <code>app.db</code> or <code>current_app.db</code> inside of any functions/methods in your application and don't need to worry about the circular dependency.</p>
| 1 | 2016-10-11T06:49:06Z | [
"python",
"flask",
"flask-sqlalchemy",
"python-3.5"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.