title
stringlengths 10
172
| question_id
int64 469
40.1M
| question_body
stringlengths 22
48.2k
| question_score
int64 -44
5.52k
| question_date
stringlengths 20
20
| answer_id
int64 497
40.1M
| answer_body
stringlengths 18
33.9k
| answer_score
int64 -38
8.38k
| answer_date
stringlengths 20
20
| tags
list |
---|---|---|---|---|---|---|---|---|---|
Add a new column to a csv file in python
| 39,733,158 |
<p>I am trying to add a column to a csv file that combines strings from two other columns. Whenever I try this I either get an output csv with only the new column or an output with all of the original data and not the new column. </p>
<p>This is what I have so far:</p>
<pre><code>with open(filename) as csvin:
readfile = csv.reader(csvin, delimiter=',')
with open(output, 'w') as csvout:
writefile = csv.writer(csvout, delimiter=',', lineterminator='\n')
for row in readfile:
result = [str(row[10]) + ' ' + str(row[11])]
writefile.writerow(result)
</code></pre>
<p>Any help would be appreciated.</p>
| 2 |
2016-09-27T19:49:28Z
| 39,734,612 |
<p>Below code snippet combines strings in column 10 and column 11 in each row and add that to the end of the each row</p>
<pre><code>import csv
input = 'test.csv'
output= 'output.csv'
with open(input, 'rb') as csvin:
readfile = csv.reader(csvin, delimiter=',')
with open(output, 'wb') as csvout:
writefile = csv.writer(csvout, delimiter=',', lineterminator='\n')
for row in readfile:
result = row + [row[10]+row[11]]
writefile.writerow(result)
</code></pre>
| 0 |
2016-09-27T21:30:04Z
|
[
"python",
"python-2.7",
"csv"
] |
Beginner : python len() closes file?
| 39,733,269 |
<p>I am new to Python and going through the book of Zed. I stumbled upon the following exercise, scope of which is to copy one txt to another.</p>
<p>The original code from the book <em>works perfectly</em> and I copy below - so that I can show the difference:</p>
<pre><code>1 from sys import argv
2 from os.path import exists
3
4 script, from_file, to_file = argv
5
6 print "Copying from %s to %s" % (from_file, to_file)
7
8 # we could do these two on one line too, how?
9 in_file = open(from_file)
10 indata = in_file.read()
11
12 print "The input file is %d bytes long" % len(indata)
13
14 print "Does the output file exist? %r" % exists(to_file)
15 print "Ready, hit RETURN to continue, CTRL- C to abort."
16 raw_input()
17
18 out_file = open(to_file, 'w')
19 out_file.write(indata)
20
21 print "Alright, all done."
22
23 out_file.close()
24 in_file.close()
</code></pre>
<p>What I decided to do, is to avoid having a variable <strong>in_file</strong> AND <strong>indata</strong> so I did some changes in lines 9-10, 12 and 19 and wrote the following code:</p>
<pre><code>from sys import argv
from os.path import exists
script, from_file, to_file = argv
print "Copying from %s to %s" % (from_file, to_file)
# we could do these two on one line too, how?
in_file = open(from_file)
print "The input file is %d bytes long" % len(in_file.read())
print "Does the output file exist? %r" % exists(to_file)
print "Ready, hit RETURN to continue, CTRL- C to abort."
raw_input()
out_file = open(to_file, 'w')
out_file.write(in_file.read())
print "Alright, all done."
out_file.close()
in_file.close()
</code></pre>
<p>My problem is:</p>
<p>1) As written the <strong>amended</strong> code, althouhg it prints correctly the bytes of the in_file.read(), it never copies the text from the from_file to the to_file</p>
<p>2) If in the <strong>amended</strong> I ommit only the line which counts the bytes - so the len() function - then it copies normally the one file to the other . </p>
<p>From my understanding, by evoking the len() function it then closes the in_file.</p>
<p>Is my thought correct? Can I avoid that, by not having to repeat the code in_file = open(from_file)? What else could be the reason?</p>
<p>I would appreciate the help, because this drives me a bit nuts :)</p>
| 4 |
2016-09-27T19:57:47Z
| 39,733,305 |
<p>It's actually the act of calling <code>in_file.read()</code> twice that's causing your problem. You can fix it by assigning the result to a variable, as in the original:</p>
<pre><code>indata = in_file.read()
</code></pre>
<p>The reason is that when you call <code>in_file.read()</code>, you "exhaust" the file. Think of the file as a book - as the computer reads it, it leaves a bookmark where it leaves off. So when it's done, the bookmark is left on the last page of the book. And when you call <code>in_file.read()</code> the second time, python starts where the bookmark was left - at the end, with no more pages left to read.</p>
<p>If you want to avoid creating a variable for some reason, you could "move the bookmark" back to the beginning of the file, as suggested by @WayneWerner in the comments.</p>
<pre><code>in_file.seek(0)
</code></pre>
| 2 |
2016-09-27T19:59:49Z
|
[
"python"
] |
Why do I have an infinite loop in my code?
| 39,733,302 |
<p>Below I have a piece of code which calculates credit card balance, but it doesn't work when <code>balance</code> has an extreme value (such as <code>balance=9999999999</code>below). It throws the code through an infinite loop. I have a couple of theories as to how to fix this flaw, but don't know how to move forward with them. Here's my code:</p>
<pre><code>balance = 9999999999
annualInterestRate = 0.2
monthlyPayment = 0
monthlyInterestRate = annualInterestRate /12
newbalance = balance
month = 0
while newbalance > 0:
monthlyPayment += .1
newbalance = balance
for month in range(1,13):
newbalance -= monthlyPayment
newbalance += monthlyInterestRate * newbalance
month += 1
print("Lowest Payment:" + str(round(monthlyPayment,2)))
</code></pre>
<p>My theory is that
<code>while newbalance > 0</code>
is causing the infinite loop, because newbalance is always larger than 0. </p>
<p>How can I change this <code>while</code> loop so that it doesn't cause my code to run infinitely? </p>
<p>By the way:
With moderate numbers, the program runs for a long time and finally gives an answer. For the larger numbers, the program just keeps on going.</p>
| 1 |
2016-09-27T19:59:37Z
| 39,733,390 |
<p>This loop is not infinite, but will take a long time to resolve. For very large values of <code>balance</code>, <code>monthlyPayment</code> will have to get very large in order to drop it past zero. </p>
| 3 |
2016-09-27T20:05:04Z
|
[
"python",
"python-3.x",
"infinite-loop"
] |
Why do I have an infinite loop in my code?
| 39,733,302 |
<p>Below I have a piece of code which calculates credit card balance, but it doesn't work when <code>balance</code> has an extreme value (such as <code>balance=9999999999</code>below). It throws the code through an infinite loop. I have a couple of theories as to how to fix this flaw, but don't know how to move forward with them. Here's my code:</p>
<pre><code>balance = 9999999999
annualInterestRate = 0.2
monthlyPayment = 0
monthlyInterestRate = annualInterestRate /12
newbalance = balance
month = 0
while newbalance > 0:
monthlyPayment += .1
newbalance = balance
for month in range(1,13):
newbalance -= monthlyPayment
newbalance += monthlyInterestRate * newbalance
month += 1
print("Lowest Payment:" + str(round(monthlyPayment,2)))
</code></pre>
<p>My theory is that
<code>while newbalance > 0</code>
is causing the infinite loop, because newbalance is always larger than 0. </p>
<p>How can I change this <code>while</code> loop so that it doesn't cause my code to run infinitely? </p>
<p>By the way:
With moderate numbers, the program runs for a long time and finally gives an answer. For the larger numbers, the program just keeps on going.</p>
| 1 |
2016-09-27T19:59:37Z
| 39,733,646 |
<p>The bisection method will execute much quicker if you're allowed to use it in your assignment. Will not help you though, if you're required to increment the monthly payment by .01.</p>
<pre><code>static_balance = balance
interest = (annualInterestRate/12)
epsilon = 0.01
lo = balance/12
hi = balance
while abs(balance) > epsilon:
balance = static_balance
min_pmt = (hi+lo)/2
for i in range(12):
balance -= min_pmt
balance *= 1+interest
if balance > 0:
lo = min_pmt
else:
hi = min_pmt
print("Lowest payment: ", round(min_pmt, 2))
</code></pre>
| 0 |
2016-09-27T20:22:15Z
|
[
"python",
"python-3.x",
"infinite-loop"
] |
Python regex numbers and underscores
| 39,733,358 |
<p>I'm trying to get a list of files from a directory whose file names follow this pattern:</p>
<pre><code>PREFIX_YYYY_MM_DD.dat
</code></pre>
<p>For example</p>
<pre><code>FOO_2016_03_23.dat
</code></pre>
<p>Can't seem to get the right regex. I've tried the following:</p>
<pre><code>pattern = re.compile(r'(\d{4})_(\d{2})_(\d{2}).dat')
>>> []
pattern = re.compile(r'*(\d{4})_(\d{2})_(\d{2}).dat')
>>> sre_constants.error: nothing to repeat
</code></pre>
<p>Regex is certainly a weakpoint for me. Can anyone explain where I'm going wrong?</p>
<p>To get the files, I'm doing:</p>
<pre><code>files = [f for f in os.listdir(directory) if pattern.match(f)]
</code></pre>
<p>PS, how would I allow for .dat and .DAT (case insensitive file extension)?</p>
<p>Thanks</p>
| 1 |
2016-09-27T20:03:11Z
| 39,733,412 |
<p>Use <code>pattern.search()</code> instead of <code>pattern.match()</code>.</p>
<p><code>pattern.match()</code> always matches from the start of the string (which includes the PREFIX).
<code>pattern.search()</code> searches anywhere within the string.</p>
| 1 |
2016-09-27T20:06:38Z
|
[
"python",
"regex"
] |
Python regex numbers and underscores
| 39,733,358 |
<p>I'm trying to get a list of files from a directory whose file names follow this pattern:</p>
<pre><code>PREFIX_YYYY_MM_DD.dat
</code></pre>
<p>For example</p>
<pre><code>FOO_2016_03_23.dat
</code></pre>
<p>Can't seem to get the right regex. I've tried the following:</p>
<pre><code>pattern = re.compile(r'(\d{4})_(\d{2})_(\d{2}).dat')
>>> []
pattern = re.compile(r'*(\d{4})_(\d{2})_(\d{2}).dat')
>>> sre_constants.error: nothing to repeat
</code></pre>
<p>Regex is certainly a weakpoint for me. Can anyone explain where I'm going wrong?</p>
<p>To get the files, I'm doing:</p>
<pre><code>files = [f for f in os.listdir(directory) if pattern.match(f)]
</code></pre>
<p>PS, how would I allow for .dat and .DAT (case insensitive file extension)?</p>
<p>Thanks</p>
| 1 |
2016-09-27T20:03:11Z
| 39,733,418 |
<p>Does this do what you want?</p>
<pre><code>>>> import re
>>> pattern = r'\A[a-z]+_\d{4}_\d{2}_\d{2}\.dat\Z'
>>> string = 'FOO_2016_03_23.dat'
>>> re.search(pattern, string, re.IGNORECASE)
<_sre.SRE_Match object; span=(0, 18), match='FOO_2016_03_23.dat'>
>>>
</code></pre>
<p>It appears to match the format of the string you gave as an example.</p>
| 1 |
2016-09-27T20:06:53Z
|
[
"python",
"regex"
] |
Python regex numbers and underscores
| 39,733,358 |
<p>I'm trying to get a list of files from a directory whose file names follow this pattern:</p>
<pre><code>PREFIX_YYYY_MM_DD.dat
</code></pre>
<p>For example</p>
<pre><code>FOO_2016_03_23.dat
</code></pre>
<p>Can't seem to get the right regex. I've tried the following:</p>
<pre><code>pattern = re.compile(r'(\d{4})_(\d{2})_(\d{2}).dat')
>>> []
pattern = re.compile(r'*(\d{4})_(\d{2})_(\d{2}).dat')
>>> sre_constants.error: nothing to repeat
</code></pre>
<p>Regex is certainly a weakpoint for me. Can anyone explain where I'm going wrong?</p>
<p>To get the files, I'm doing:</p>
<pre><code>files = [f for f in os.listdir(directory) if pattern.match(f)]
</code></pre>
<p>PS, how would I allow for .dat and .DAT (case insensitive file extension)?</p>
<p>Thanks</p>
| 1 |
2016-09-27T20:03:11Z
| 39,733,492 |
<p>You have two issues with your expression:
<code>re.compile(r'(\d{4})_(\d{2})_(\d{2}).dat')</code></p>
<p>The first one, as a previous comment stated, is that the <code>.</code> right before <code>dat</code> should be escaped by putting a backslash (<code>\</code>) before. Otherwise, python will treat it as a special character, because in regex <code>.</code> represents "any character".</p>
<p>Besides that, you're not handling uppercase exceptions on your expression. You should make a group for this with <code>dat</code> and <code>DAT</code> as possible choices.</p>
<p>With both changes made, it should look like:</p>
<p><code>re.compile(r'(\d{4})_(\d{2})_(\d{2})\.(?:dat|DAT)')</code></p>
<p>As an extra note, I added <code>?:</code> at the beginning of the group so the regex matcher ignores it at the results.</p>
| 2 |
2016-09-27T20:12:07Z
|
[
"python",
"regex"
] |
Python regex numbers and underscores
| 39,733,358 |
<p>I'm trying to get a list of files from a directory whose file names follow this pattern:</p>
<pre><code>PREFIX_YYYY_MM_DD.dat
</code></pre>
<p>For example</p>
<pre><code>FOO_2016_03_23.dat
</code></pre>
<p>Can't seem to get the right regex. I've tried the following:</p>
<pre><code>pattern = re.compile(r'(\d{4})_(\d{2})_(\d{2}).dat')
>>> []
pattern = re.compile(r'*(\d{4})_(\d{2})_(\d{2}).dat')
>>> sre_constants.error: nothing to repeat
</code></pre>
<p>Regex is certainly a weakpoint for me. Can anyone explain where I'm going wrong?</p>
<p>To get the files, I'm doing:</p>
<pre><code>files = [f for f in os.listdir(directory) if pattern.match(f)]
</code></pre>
<p>PS, how would I allow for .dat and .DAT (case insensitive file extension)?</p>
<p>Thanks</p>
| 1 |
2016-09-27T20:03:11Z
| 39,733,509 |
<p>The following should match for what you requested. </p>
<pre><code>[^_]+[_]\d{4}[_]\d{2}[_]\d{2}[\.]\w+
</code></pre>
<p>I recommend using <a href="https://regex101.com/" rel="nofollow">https://regex101.com/</a> (for python regular expressions) or <a href="http://regexr.com/" rel="nofollow">http://regexr.com/</a> (for javascript regular expressions) in the future if you want to validate your regular expressions. </p>
| 1 |
2016-09-27T20:13:39Z
|
[
"python",
"regex"
] |
TemplateDoesNotExist at /accounts/register/ Error
| 39,733,402 |
<p>So I am new to Django and am currently trying to build registration into my app. I have already followed this <a href="http://code.techandstartup.com/django/registration/#app-download" rel="nofollow">guide</a>. However I am running into an issue in which the application is not able to find the template somehow.</p>
<blockquote>
<pre><code>Traceback:
</code></pre>
<p>File
"/usr/local/lib/python3.5/site-packages/django/core/handlers/exception.py"
in inner
39. response = get_response(request)</p>
<p>File
"/usr/local/lib/python3.5/site-packages/django/core/handlers/base.py"
in _get_response
217. response = self.process_exception_by_middleware(e, request)</p>
<p>File
"/usr/local/lib/python3.5/site-packages/django/core/handlers/base.py"
in _get_response
215. response = response.render()</p>
<p>File
"/usr/local/lib/python3.5/site-packages/django/template/response.py"
in render
109. self.content = self.rendered_content</p>
<p>File
"/usr/local/lib/python3.5/site-packages/django/template/response.py"
in rendered_content
84. template = self.resolve_template(self.template_name)</p>
<p>File
"/usr/local/lib/python3.5/site-packages/django/template/response.py"
in resolve_template
66. return select_template(template, using=self.using)</p>
<p>File
"/usr/local/lib/python3.5/site-packages/django/template/loader.py" in
select_template
53. raise TemplateDoesNotExist(', '.join(template_name_list), chain=chain)</p>
<p>Exception Type: TemplateDoesNotExist at /accounts/register/ Exception
Value: registration/registration_form.html</p>
</blockquote>
<p>I have checked to make sure my URL are set and everything should be in order. I have spent the past 2 hours looking for a solution to this and nothing is working. </p>
<p>The things that gets me the most is that in the error I can see where it checks for the template in the exact place I have it yet I am still seeing the following next to the actual path in which this template should be.</p>
<blockquote>
<p>(Source does not exist)</p>
</blockquote>
<p>Please help</p>
| 0 |
2016-09-27T20:06:09Z
| 39,733,901 |
<p>Please check that you have defined TEMPLATES_DIRS properly</p>
<p>In Django 1.8 upwards:</p>
<pre><code>TEMPLATES = [
{
'DIRS': [
# insert your TEMPLATE_DIRS here (absolute path)
],
},
]
</code></pre>
| 0 |
2016-09-27T20:40:06Z
|
[
"python",
"django",
"templates",
"django-templates",
"django-registration"
] |
Python dictionary sumUp values
| 39,733,443 |
<p>The function below should return a new dictionary which has summed the values up. </p>
<pre><code>import functools
def sumUp(d):
for k in d:
d.update({k: functools.reduce(lambda x, y: x + y, d[k])})
print(d)
</code></pre>
<p>When i call the function as follows i get the following <code>TypeError</code> which i can't understand why:</p>
<pre><code>sumUp({"Ungefucht": (165, 165, 165, 255, 286.25, 255, 165, 240, 240, 150), "Malsch": (120, 240, 120, 120, 120, 120, 120), "AAA": (1, 2), "Fens": (115.20, 69.60, 28.80, 50.40), "Betti": (82.50,)})
</code></pre>
<blockquote>
<p>Traceback (most recent call last):</p>
<p>File "", line 1, in </p>
<p>File "/home/amir/programming/python/lern.py", line 6, in sumUp
print(d)</p>
<p>TypeError: reduce() arg 2 must support iteration</p>
</blockquote>
<p>When i omit one of the key-values it works fine:</p>
<pre><code>sumUp({"Ungefucht": (165, 165, 165, 255, 286.25, 255, 165, 240, 240, 150), "Malsch": (120, 240, 120, 120, 120, 120, 120), "AAA": (1, 2), "Fens": (115.20, 69.60, 28.80, 50.40)})
</code></pre>
<blockquote>
<p>{'Malsch': 960, 'Ungefucht': 2086.25, 'Fens': 264.0, 'AAA': 3}</p>
</blockquote>
<p>Why is the first example with one more item not working as expected?</p>
| 2 |
2016-09-27T20:09:10Z
| 39,733,502 |
<p>This works:</p>
<pre><code>def sumUp(d):
new_d = {k: sum(v) for k, v in d.items()}
print(new_d)
return new_d
</code></pre>
<p>Keep in mind you are updating the dictionary while iterating over it, which causes all sorts of strange behavior.</p>
<p>The behavior is quite random and depends on the salting of the key's hashes (which modifies the dict order). You can't reproduce it consistently in Python 3.</p>
<p>This is your code fixed:</p>
<pre><code>def sumUp2(d):
for k in d:
d[k] = functools.reduce(lambda x, y: x + y, d[k])
print(d)
</code></pre>
<p>It sets the key instead of updating the dict, which is safe.</p>
| 2 |
2016-09-27T20:13:01Z
|
[
"python",
"python-3.x",
"dictionary"
] |
I am learning Python, need some pushing in the right direction
| 39,733,476 |
<p>I am trying to learn Python through Coursera, and have some questions about an assignment.</p>
<blockquote>
<p>Write a program that prompts for a file name, then opens that file and reads through the file, looking for lines of the form:</p>
<pre><code>X-DSPAM-Confidence: 0.8475
</code></pre>
<p>Count these lines and extract the floating point values from each of the lines and compute the average of those values and produce an output as shown below. Do not use the <code>sum()</code> function or a variable named <code>sum</code> in your solution.</p>
</blockquote>
<p>My code so far is as follows:</p>
<pre><code>fname = raw_input("Enter file name: ")
f = open(fname)
for line in f:
if not line.startswith("X-DSPAM-Confidence:") : continue
print line
print "Done"
</code></pre>
<p>I am a bit confused. Should I store each line I get into a file or variable or something and then extract the floating point values for each?
How should this be tackled in the simplest way since this is just the beginning of the course?</p>
| 3 |
2016-09-27T20:10:29Z
| 39,733,609 |
<p>The reason not to use a variable named <code>sum</code> is because there is a function with the same name.</p>
<p>The assignment asks you to do the work of the <code>sum()</code> function explicitly. You are on the right track with the <code>if not</code> line but might be more successful if you reverse the logic (like this: <code>if line.startswith</code> ...), then put the handling inside an indented block that follows.</p>
<p>The handling you need is to keep track of how many such lines you handle and the accumulated sum. Use a term that is a synonym for <code>sum</code> that is not already a Python identifier. Extract the float value from the end of <code>line</code> and then <code><your sum variable> += float(the float from "line")</code>.</p>
<p>Don't forget to initialize both counter and accumulator before the loop.</p>
| 1 |
2016-09-27T20:19:39Z
|
[
"python"
] |
I am learning Python, need some pushing in the right direction
| 39,733,476 |
<p>I am trying to learn Python through Coursera, and have some questions about an assignment.</p>
<blockquote>
<p>Write a program that prompts for a file name, then opens that file and reads through the file, looking for lines of the form:</p>
<pre><code>X-DSPAM-Confidence: 0.8475
</code></pre>
<p>Count these lines and extract the floating point values from each of the lines and compute the average of those values and produce an output as shown below. Do not use the <code>sum()</code> function or a variable named <code>sum</code> in your solution.</p>
</blockquote>
<p>My code so far is as follows:</p>
<pre><code>fname = raw_input("Enter file name: ")
f = open(fname)
for line in f:
if not line.startswith("X-DSPAM-Confidence:") : continue
print line
print "Done"
</code></pre>
<p>I am a bit confused. Should I store each line I get into a file or variable or something and then extract the floating point values for each?
How should this be tackled in the simplest way since this is just the beginning of the course?</p>
| 3 |
2016-09-27T20:10:29Z
| 39,733,633 |
<pre><code>with open(fname) as f:
s = 0
linecount = 0
for line in f:
l = line.split()
try:
num = float(l[1])
except ValueError:
continue
if l[0] == 'X-DSPAM-Confidence:':
s += num
linecount += 1
print(s/linecount)
</code></pre>
<p>Here's how I would do it. I'll happily answer any questions.</p>
| 1 |
2016-09-27T20:21:27Z
|
[
"python"
] |
I am learning Python, need some pushing in the right direction
| 39,733,476 |
<p>I am trying to learn Python through Coursera, and have some questions about an assignment.</p>
<blockquote>
<p>Write a program that prompts for a file name, then opens that file and reads through the file, looking for lines of the form:</p>
<pre><code>X-DSPAM-Confidence: 0.8475
</code></pre>
<p>Count these lines and extract the floating point values from each of the lines and compute the average of those values and produce an output as shown below. Do not use the <code>sum()</code> function or a variable named <code>sum</code> in your solution.</p>
</blockquote>
<p>My code so far is as follows:</p>
<pre><code>fname = raw_input("Enter file name: ")
f = open(fname)
for line in f:
if not line.startswith("X-DSPAM-Confidence:") : continue
print line
print "Done"
</code></pre>
<p>I am a bit confused. Should I store each line I get into a file or variable or something and then extract the floating point values for each?
How should this be tackled in the simplest way since this is just the beginning of the course?</p>
| 3 |
2016-09-27T20:10:29Z
| 39,733,688 |
<p>@PatrickHaugh beat me to it but here's my answer. It's less complex than his in that it does not implement try/except. I assume you haven't learned try/except yet.</p>
<pre><code>fname = raw_input("Enter file name: ")
sum = 0
lines = 0
f = open(fname)
for line in f:
if line.startswith("X-DSPAM-Confidence:"):
lines += 1
line = line.rstrip('\n') # get rid of the trailing new-line
number = float(line.split()[-1]) # get last value after splitting the string
sum += number
f.close() # Don't forget to close the file!
print (sum / lines)
print "Done"
</code></pre>
| 0 |
2016-09-27T20:25:04Z
|
[
"python"
] |
I am learning Python, need some pushing in the right direction
| 39,733,476 |
<p>I am trying to learn Python through Coursera, and have some questions about an assignment.</p>
<blockquote>
<p>Write a program that prompts for a file name, then opens that file and reads through the file, looking for lines of the form:</p>
<pre><code>X-DSPAM-Confidence: 0.8475
</code></pre>
<p>Count these lines and extract the floating point values from each of the lines and compute the average of those values and produce an output as shown below. Do not use the <code>sum()</code> function or a variable named <code>sum</code> in your solution.</p>
</blockquote>
<p>My code so far is as follows:</p>
<pre><code>fname = raw_input("Enter file name: ")
f = open(fname)
for line in f:
if not line.startswith("X-DSPAM-Confidence:") : continue
print line
print "Done"
</code></pre>
<p>I am a bit confused. Should I store each line I get into a file or variable or something and then extract the floating point values for each?
How should this be tackled in the simplest way since this is just the beginning of the course?</p>
| 3 |
2016-09-27T20:10:29Z
| 39,733,730 |
<p>Using <strong>Regular expression</strong>.</p>
<p><a href="https://pymotw.com/2/re/" rel="nofollow">More info regarding re module, check here !!!</a></p>
<p><strong>Code:</strong></p>
<pre><code>import re
fname = raw_input("Enter file name: ")
f = open(fname)
val_list = []
tot = 0
line_cnt = 0
for line in f:
a = re.findall("X-DSPAM-Confidence:\s*(\d+\.?\d*)",line)
if len(a) != 0:
tot += float(a[0])
line_cnt +=1
print ("Line Count is ",line_cnt)
print ("Average is ",tot/line_cnt)
f.close()
</code></pre>
<p><strong>Content of y.txt:</strong></p>
<pre><code>a
X-DSPAM-Confidence: 0.8475
b
X-DSPAM-Confidence: 0.8476
c
X-DSPAM-Confidence: 0.8477
d
X-DSPAM-Confidence: 0.8478
</code></pre>
<p><strong>Output:</strong></p>
<pre><code>C:\Users\dinesh_pundkar\Desktop>python c.py
Enter file name: y.txt
Line Count is 4
Average is 0.84765
C:\Users\dinesh_pundkar\Desktop>
</code></pre>
<p><strong>Points:</strong></p>
<ul>
<li><em>You can open file using <code>with</code> as Patrick has done in his answer. If file is opened using <code>with</code> then no need to close the file explicit.</em></li>
</ul>
| 1 |
2016-09-27T20:28:23Z
|
[
"python"
] |
I am learning Python, need some pushing in the right direction
| 39,733,476 |
<p>I am trying to learn Python through Coursera, and have some questions about an assignment.</p>
<blockquote>
<p>Write a program that prompts for a file name, then opens that file and reads through the file, looking for lines of the form:</p>
<pre><code>X-DSPAM-Confidence: 0.8475
</code></pre>
<p>Count these lines and extract the floating point values from each of the lines and compute the average of those values and produce an output as shown below. Do not use the <code>sum()</code> function or a variable named <code>sum</code> in your solution.</p>
</blockquote>
<p>My code so far is as follows:</p>
<pre><code>fname = raw_input("Enter file name: ")
f = open(fname)
for line in f:
if not line.startswith("X-DSPAM-Confidence:") : continue
print line
print "Done"
</code></pre>
<p>I am a bit confused. Should I store each line I get into a file or variable or something and then extract the floating point values for each?
How should this be tackled in the simplest way since this is just the beginning of the course?</p>
| 3 |
2016-09-27T20:10:29Z
| 39,733,950 |
<p>Here is a code snippet that suffices your work. I am reading the float values from the line with "X-DSPAM-Confidence:" and adding them and in the end, I am taking the mean. Also, since you are a beginner, I suggest to keep in mind that when you are dealing with division and you are expecting a float, either numerator or denominator should be float to give the answer in float. Since in the below code snippet, our number is float, we wont have that issue. </p>
<pre><code>fname = raw_input("Enter file name: ")
f = open(fname)
cnt = 0
mean_val = 0
for line in f:
if not line.startswith("X-DSPAM-Confidence:") : continue
mean_val += float(line.split(':')[1])
cnt += 1
f.close()
mean_val /= cnt
print mean_val
</code></pre>
| 1 |
2016-09-27T20:42:22Z
|
[
"python"
] |
tornado web application fails to decode compressed http body
| 39,733,500 |
<p>I am writing some simple prototype tornado web applications and found that tornado fails to decode the http request body with</p>
<pre><code>Error -3 while decompressing: incorrect header check
</code></pre>
<p>From one of the tornado web application, I am sending http request by compressing the body using zlib.</p>
<pre><code>http_body = zlib.compress(data)
</code></pre>
<p>And also added http header:</p>
<pre><code>'Content-Encoding': 'gzip'
</code></pre>
<p>However, when I receive this http request in another tornado web application, I see that it results in decompressing failure as mentioned above.</p>
<p>Sample Code to handle the http request: </p>
<pre><code>class MyRequestHandler(tornado.web.RequestHandler):
def post(self):
global num
message = self.request.body
self.set_status(200)
</code></pre>
<p>I have also ensured that <strong>decompress_request=True</strong> when application listen.</p>
<p>I have checked the tornado documentation and earlier post and found nothing regarding compressed http body part or any example of it. The only thing mentioned is decompress_response parameter which just ensures compressed http response from a server.</p>
<p>Am I missing any settings here?</p>
| 0 |
2016-09-27T20:12:44Z
| 39,760,582 |
<p><code>gzip</code> and <code>zlib</code> are both based on the same underlying compression algorithm, but they are not the same thing. You must use <code>gzip</code> and not just <code>zlib</code> here:</p>
<pre><code>def post_gzip(self, body):
bytesio = BytesIO()
gzip_file = gzip.GzipFile(mode='w', fileobj=bytesio)
gzip_file.write(utf8(body))
gzip_file.close()
compressed_body = bytesio.getvalue()
return self.fetch('/', method='POST', body=compressed_body,
headers={'Content-Encoding': 'gzip'})
</code></pre>
<p>Some <code>zlib</code> functions also take cryptic options that cause them to produce <code>gzip</code>-format output. These can be used with <code>zlib.decompressobj</code> and <code>zlib.compressobj</code> to do streaming compression and decompression.</p>
| 0 |
2016-09-29T02:46:55Z
|
[
"python",
"http",
"tornado"
] |
how to keep pd.read_csv() from changing datatype
| 39,733,518 |
<p>I save a DataFrame using to_csv(), then retrieve it with csv_read() and it comes back with a different datatype.</p>
<pre><code>df1i=['00','01']
df1=pd.DataFrame( columns=['00','01'],index=df1i)
df1
df1.iloc[0,0]=([11, 22])
df1
print((df1.iloc[0,0]))
print(type(df1.iloc[0,0]))
print(df1.iloc[0,0][0])
print(type(df1.iloc[0,0][0]))
df1.to_csv('C:\Thomas\paradigm\\df1.csv')
df1=pd.read_csv('c:\\Thomas\\paradigm\\df1.csv',index_col=0)
print((df1.iloc[0,0]))
print(type(df1.iloc[0,0]))
print(df1.iloc[0,0][0])
print(type(df1.iloc[0,0][0]))
[11, 22]
<class 'list'>
11
<class 'int'>
[11, 22]
<class 'str'>
[
<class 'str'>
</code></pre>
<p>If anyone can tell me how to control this I will appreciate it.</p>
<p>Clarification of my question>>></p>
<p>What I am asking is if there is a way to get back the same type that you put in. For instance, if I input the element as an integer, it comes back as a string, an ndarray in also comes back as a string.</p>
| 1 |
2016-09-27T20:14:08Z
| 39,734,021 |
<p>It is a bit weird to store lists as elements of a DataFrame, but if it is what you need to do then consider using a converter along with <code>ast.literal_eval</code> in order to get a list back. </p>
<pre><code>import pandas as pd
import ast
df1i = ['00', '01']
df1=pd.DataFrame( columns=['00','01'],index=df1i)
df1.iloc[0,0]=([11, 22])
print((df1.iloc[0,0]))
print(type(df1.iloc[0,0]))
print(df1.iloc[0,0][0])
print(type(df1.iloc[0,0][0]))
df1.to_csv('df1.csv')
df1=pd.read_csv('df1.csv', index_col=0, converters={'00': lambda x: ast.literal_eval(str(x)) if len(str(x)) > 0 else x})
print((df1.iloc[0,0]))
print(type(df1.iloc[0,0]))
print(df1.iloc[0,0][0])
print(type(df1.iloc[0,0][0]))
</code></pre>
| 1 |
2016-09-27T20:47:13Z
|
[
"python"
] |
Python Selenium 'module' object is not callable in python selenium script
| 39,733,650 |
<p>Learning Selenium driven by Python and in my practice I keep getting the following error. I am stuck and could use some guidance </p>
<blockquote>
<p>Traceback (most recent call last): File "test_login.py", line 14, in
test_Login
loginpage = homePage(self.driver) TypeError: 'module' object is not callable</p>
</blockquote>
<p>Here is my code</p>
<blockquote>
<p>test_login.py</p>
</blockquote>
<pre><code>import unittest
import homePage
from selenium import webdriver
class Login(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Firefox()
self.driver.get("https://hub.docker.com/login/")
def test_Login(self):
loginpage = homePage(self.driver)
loginpage.login(email,password)
def tearDown(self):
self.driver.close()
if __name__ == '__main__': unittest.main()
</code></pre>
<blockquote>
<p>homePage.py</p>
</blockquote>
<pre><code>from selenium.webdriver.common.by import By
class BasePage(object):
def __init__(self, driver):
self.driver = drive
class LoginPage(BasePage):
locator_dictionary = {
"userID": (By.XPATH, '//input[@placeholder="Username"]'),
"passWord": (By.XPATH, '//input[@placeholder="Password"]'),
"submittButton": (By.XPATH, '//button[text()="Log In"]'),
}
def set_userID(self, id):
userIdElement = self.driver.find_element(*LoginPage.userID)
userIdElement.send_keys(id)
def login_error_displayed(self):
notifcationElement = self.driver.find_element(*LoginPage.loginError)
return notifcationElement.is_displayed()
def set_password(self, password):
pwordElement = self.driver.find_element(*LoginPage.passWord)
pwordElement.send_keys(password)
def click_submit(self):
submitBttn = self.driver.find_element(*LoginPage.submitButton)
submitBttn.click()
def login(self, id, password):
self.set_password(password)
self.set_email(id)
self.click_submit()
</code></pre>
<p>Any help is appreciated </p>
| 1 |
2016-09-27T20:22:25Z
| 39,733,672 |
<p>I think here:</p>
<pre><code>loginpage = homePage(self.driver)
</code></pre>
<p>you meant to instantiate the <code>LoginPage</code> class:</p>
<pre><code>loginpage = homePage.LoginPage(self.driver)
</code></pre>
| 1 |
2016-09-27T20:23:49Z
|
[
"python",
"selenium"
] |
Iterate through worksheets in workbook- Python Nested For loop
| 39,733,669 |
<p>I am trying to open an excel workbook and iterate through each of the worksheets in a loop. Here is first loop:</p>
<pre><code>wb = openpyxl.load_workbook('snakes.xlsx')
for i in wb.worksheets:
i= 0
wb.get_sheet_names()
i = i + 1
</code></pre>
<p>Once I can successful go through each one of these worksheets, i would like to do a nested loop which takes each one of my png files and places them in the worksheets. It is important to note that the sheet names and the png files have the same names (country names) stored in a dataframe called country_names. </p>
<p>Second loop:</p>
<pre><code>for ws in wb.worksheets:
img = openpyxl.drawing.image.Image(folder + str(var) + '.png')
ws.add_image(img, 'K1')
wb.save('snakes.xlsx')
</code></pre>
<p>Any ideas on how to do the nested for loop so the code loops through the images and write them to the worksheets?</p>
| 1 |
2016-09-27T20:23:41Z
| 39,733,924 |
<p>Your code snippets seem to show a fundamental misunderstanding of how the <code>for</code> loop works in Python.</p>
<p>To loop through each sheet, you were on the right track:</p>
<pre><code>wb = openpyxl.load_workbook('test.xlsx')
for sheet in wb.worksheets:
# do stuff with "sheet"
pass
</code></pre>
<p>The variable in the <code>for</code> loop (<code>sheet</code> in my example, <code>i</code> in yours) is the member of the list (<code>wb.worksheets</code>): it is not an integer index. In your example, you immediately overwrite the value of <code>i</code> with 0 in <em>every loop</em> and thus do not have a sheet to work with. </p>
<p>It is also worth noting <code>get_sheet_names()</code> is called from the workbook object, so there is no need to call it within the for loop:</p>
<pre><code>>>> wb.worksheets
[<Worksheet "Sheet1">, <Worksheet "Sheet2">, <Worksheet "Sheet3">]
</code></pre>
<p>Finally, your second "nested for loop" (which isn't even nested) is correct, except it saves the new Excel file every loop, which is wasteful. </p>
<p>Since you indicate that the worksheet name is the same as PNG name, you can just call the attribute <code>title</code> for the worksheet when finding the image. </p>
<p>Below should be a working example:</p>
<pre><code>wb = openpyxl.load_workbook('snakes.xlsx')
for ws in wb.worksheets:
img = openpyxl.drawing.image.Image(ws.title + '.png')
ws.add_image(img, 'K1')
wb.save('new.xlsx')
</code></pre>
| 1 |
2016-09-27T20:41:03Z
|
[
"python",
"for-loop",
"openpyxl"
] |
Python, Scrapy problems when parsing tables in Earning Reports
| 39,733,693 |
<p>I am trying to parse some data from the table (the balance sheet) under every earning report. Here I use AMD as an example, but not limited to AMD.</p>
<p>Here is <a href="http://www.marketwired.com/press-release/amd-reports-2016-second-quarter-results-nasdaq-amd-2144535.htm" rel="nofollow">the link</a></p>
<p>The problem I have now is that I cannot get any reading - my spider always returns EMPTY result. I used <code>scrapy shell "http://example.com"</code> to test my xpath, which I directly copied from Google Chrome Inspector, and it still didn't work.</p>
<p>Here is my xpath (Chrome browser provided):</p>
<pre><code>//*[@id="newsroom-copy"]/div[2]/div[8]/table/tbody/tr[9]/td[4]/text()
</code></pre>
<p>Here is my code:</p>
<pre><code>import scrapy
class ESItem(scrapy.Item):
Rev = scrapy.Field()
class ESSpider(scrapy.Spider):
name = "es"
start_urls = [
'http://www.marketwired.com/press-release/amd-reports-2016-second-quarter-results-nasdaq-amd-2144535.htm',
]
def parse(self, response):
item = ESItem()
for earning in response.xpath('//*[@id="newsroom-copy"]/div[2]/div[8]/table/tbody'):
item['Rev'] = earning.xpath('tr[9]/td[4]/text()').extract_first()
yield item
</code></pre>
<p>I am looking for retrieving the "revenue numbers" from the table on the bottom of the report.</p>
<p>Thanks!</p>
<p>I run my code by using this command:</p>
<pre><code>scrapy runspider ***.py -o ***.json
</code></pre>
<p>Code runs fine, no error, just didn't return what I really look for.</p>
<p><strong>UPDATE</strong>: I kind of figure out something... I have to remove that "tbody" tag from the XPATH, which I don't understand... Can anyone explain this a little bit please?</p>
| 1 |
2016-09-27T20:25:35Z
| 39,736,933 |
<p>The html provided by the inspect tool in chrome is the result of the browser interpretation of the actual code that it is sent by the server to your browser.</p>
<p>The <code>tbody</code> tag is a prime example. If you view the page source of a website you'll see a structure like this</p>
<pre><code><table>
<tr>
<td></td>
</tr>
</table>
</code></pre>
<p>Now if you inspect the page this happens</p>
<pre><code><table>
<tbody>
<tr>
<td></td>
</tr>
</tbody>
</table>
</code></pre>
<p>What scrapy gets is the page source and not the "inspector" so whenever you try to select something in a page make sure it exists on the page source.</p>
<p>Another example of this is when you try to select some element that is generated by javascript while the page is being loaded. Scrapy won't get this either so you'll need to use something else to interpret it like scrapy-splash or selenium.</p>
<p>As a side note, take the time to learn xpath and css selectors. It's a time saver when you know how to query elements just right.</p>
<pre><code>//*[@id='newsroom-copy']/div[2]/div[8]/table/tr[9]/td[4]/text()
</code></pre>
<p>is equivalent to</p>
<pre><code>//table/tr[td/text()='Net revenue']/td[4]/text()
</code></pre>
<p>See how much nicer it looks?</p>
| 0 |
2016-09-28T02:07:44Z
|
[
"python",
"python-2.7",
"scrapy",
"scrapy-spider"
] |
Python Query list for oldest date
| 39,733,775 |
<p>My query returns the following in a list:</p>
<pre><code>"Alex";"275467125";"2015-02-03 02:55:36-05";"1"
"Alex";"275467125";"2015-01-13 02:09:39-05";"1"
"Alex";"275467125";"2015-01-05 04:13:35-05";"1"
"Alex";"275467125";"2014-12-27 04:55:47-05";"1"
"Alex";"275467125";"2014-12-27 04:54:52-05";"1"
"Alex";"275467125";"2014-12-07 03:13:24-05";"1"
"Alex";"275467125";"2014-12-04 03:34:56-05";"1"
"Alex";"275467125";"2014-12-02 04:16:33-05";"1"
"Ali";"275464747";"2016-02-17 10:52:12-05";"2"
"Alladin";"275467455";"2016-03-13 06:51:52-04";"2"
"Alladin";"275467455";"2016-03-13 06:51:47-04";"2"
"Anna";"275467401";"2016-03-26 03:56:41-04";"1"
"Anna";"275467401";"2016-03-26 03:55:21-04";"1"
"Anna";"275467401";"2016-03-21 23:04:28-04";"1"
"Anna";"275467401";"2016-02-12 13:24:44-05";"1"
"Anna";"275467401";"2015-12-03 08:20:35-05";"1"
"Anna";"275467401";"2015-11-09 04:18:27-05";"1"
"Anna";"275467401";"2015-11-09 04:11:59-05";"1"
"Anna";"275467401";"2015-09-13 21:27:12-04";"1"
</code></pre>
<p>I want to create a dictionary of person's name with the oldest record they have. I've figured out:</p>
<pre><code>oldestlist = {d[0]:d[2] for d in records}
</code></pre>
<p>This returns a correct answer but my worry is that if I am presented a list that is not formatted in a descending order of date/time it will not provide the correct answer. What is the best way to create a dictionary with a name and the oldest date?</p>
| 1 |
2016-09-27T20:31:49Z
| 39,733,851 |
<p>Since you need last record for each <code>name</code> instead of doing it explicitly with the <code>dict</code> make your queryset to perform <code>GROUP BY</code> on name. In Django you can do that using <code>.annotate</code> as is mentioned here: <a href="http://stackoverflow.com/questions/19923877/django-orm-get-latest-for-each-group">Django Orm get latest for each group</a></p>
<p>Hence, your querset should be like:</p>
<pre><code>YourModel.objects.values('name_column').annotate(latest_date=Max('date'))
</code></pre>
<hr>
<p><em>Additional piece of information</em>, you should be using <a href="https://docs.djangoproject.com/en/1.10/ref/models/querysets/#django.db.models.query.QuerySet.order_by" rel="nofollow"><code>order_by(-your_date_column)</code></a> with your queryset in order to ensure data is always returned in desc order where <code>-</code> ensure desc order when list is needed. </p>
| 0 |
2016-09-27T20:36:01Z
|
[
"python",
"list",
"date",
"dictionary",
"time"
] |
Python Query list for oldest date
| 39,733,775 |
<p>My query returns the following in a list:</p>
<pre><code>"Alex";"275467125";"2015-02-03 02:55:36-05";"1"
"Alex";"275467125";"2015-01-13 02:09:39-05";"1"
"Alex";"275467125";"2015-01-05 04:13:35-05";"1"
"Alex";"275467125";"2014-12-27 04:55:47-05";"1"
"Alex";"275467125";"2014-12-27 04:54:52-05";"1"
"Alex";"275467125";"2014-12-07 03:13:24-05";"1"
"Alex";"275467125";"2014-12-04 03:34:56-05";"1"
"Alex";"275467125";"2014-12-02 04:16:33-05";"1"
"Ali";"275464747";"2016-02-17 10:52:12-05";"2"
"Alladin";"275467455";"2016-03-13 06:51:52-04";"2"
"Alladin";"275467455";"2016-03-13 06:51:47-04";"2"
"Anna";"275467401";"2016-03-26 03:56:41-04";"1"
"Anna";"275467401";"2016-03-26 03:55:21-04";"1"
"Anna";"275467401";"2016-03-21 23:04:28-04";"1"
"Anna";"275467401";"2016-02-12 13:24:44-05";"1"
"Anna";"275467401";"2015-12-03 08:20:35-05";"1"
"Anna";"275467401";"2015-11-09 04:18:27-05";"1"
"Anna";"275467401";"2015-11-09 04:11:59-05";"1"
"Anna";"275467401";"2015-09-13 21:27:12-04";"1"
</code></pre>
<p>I want to create a dictionary of person's name with the oldest record they have. I've figured out:</p>
<pre><code>oldestlist = {d[0]:d[2] for d in records}
</code></pre>
<p>This returns a correct answer but my worry is that if I am presented a list that is not formatted in a descending order of date/time it will not provide the correct answer. What is the best way to create a dictionary with a name and the oldest date?</p>
| 1 |
2016-09-27T20:31:49Z
| 39,734,355 |
<p>It was a bit frustrating to get your given "list" into an actual list format. If you can't deal with this task in the query itself, you could try:</p>
<pre><code>from itertools import groupby
from operator import itemgetter
lst = '''"Alex";"275467125";"2015-02-03 02:55:36-05";"1",
"Alex";"275467125";"2015-01-13 02:09:39-05";"1",
"Alex";"275467125";"2015-01-05 04:13:35-05";"1",
"Alex";"275467125";"2014-12-27 04:55:47-05";"1",
"Alex";"275467125";"2014-12-27 04:54:52-05";"1",
"Alex";"275467125";"2014-12-07 03:13:24-05";"1",
"Alex";"275467125";"2014-12-04 03:34:56-05";"1",
"Alex";"275467125";"2014-12-02 04:16:33-05";"1",
"Ali";"275464747";"2016-02-17 10:52:12-05";"2",
"Alladin";"275467455";"2016-03-13 06:51:52-04";"2",
"Alladin";"275467455";"2016-03-13 06:51:47-04";"2",
"Anna";"275467401";"2016-03-26 03:56:41-04";"1",
"Anna";"275467401";"2016-03-26 03:55:21-04";"1",
"Anna";"275467401";"2016-03-21 23:04:28-04";"1",
"Anna";"275467401";"2016-02-12 13:24:44-05";"1",
"Anna";"275467401";"2015-12-03 08:20:35-05";"1",
"Anna";"275467401";"2015-11-09 04:18:27-05";"1",
"Anna";"275467401";"2015-11-09 04:11:59-05";"1",
"Anna";"275467401";"2015-09-13 21:27:12-04";"1"'''
broken_list = lst.split(',')
stripped = [item.replace('\n', '') for item in broken_list]
rebuilt = []
for line in stripped:
line = line.split(';')
rebuilt.append([item.strip('"') for item in line])
# Now actually sorting this
grouped = []
for key, group in groupby(rebuilt, key=itemgetter(0)):
grouped.append(list(group))
sort_grouped = [sorted(item, key=itemgetter(2)) for item in grouped]
#sort_grouped =
oldestlist = {d[0][0]:d[0][2] for d in sort_grouped}
</code></pre>
| 1 |
2016-09-27T21:09:47Z
|
[
"python",
"list",
"date",
"dictionary",
"time"
] |
Python Query list for oldest date
| 39,733,775 |
<p>My query returns the following in a list:</p>
<pre><code>"Alex";"275467125";"2015-02-03 02:55:36-05";"1"
"Alex";"275467125";"2015-01-13 02:09:39-05";"1"
"Alex";"275467125";"2015-01-05 04:13:35-05";"1"
"Alex";"275467125";"2014-12-27 04:55:47-05";"1"
"Alex";"275467125";"2014-12-27 04:54:52-05";"1"
"Alex";"275467125";"2014-12-07 03:13:24-05";"1"
"Alex";"275467125";"2014-12-04 03:34:56-05";"1"
"Alex";"275467125";"2014-12-02 04:16:33-05";"1"
"Ali";"275464747";"2016-02-17 10:52:12-05";"2"
"Alladin";"275467455";"2016-03-13 06:51:52-04";"2"
"Alladin";"275467455";"2016-03-13 06:51:47-04";"2"
"Anna";"275467401";"2016-03-26 03:56:41-04";"1"
"Anna";"275467401";"2016-03-26 03:55:21-04";"1"
"Anna";"275467401";"2016-03-21 23:04:28-04";"1"
"Anna";"275467401";"2016-02-12 13:24:44-05";"1"
"Anna";"275467401";"2015-12-03 08:20:35-05";"1"
"Anna";"275467401";"2015-11-09 04:18:27-05";"1"
"Anna";"275467401";"2015-11-09 04:11:59-05";"1"
"Anna";"275467401";"2015-09-13 21:27:12-04";"1"
</code></pre>
<p>I want to create a dictionary of person's name with the oldest record they have. I've figured out:</p>
<pre><code>oldestlist = {d[0]:d[2] for d in records}
</code></pre>
<p>This returns a correct answer but my worry is that if I am presented a list that is not formatted in a descending order of date/time it will not provide the correct answer. What is the best way to create a dictionary with a name and the oldest date?</p>
| 1 |
2016-09-27T20:31:49Z
| 39,734,564 |
<p>I was pretty close. The answer I found that works best was a tweak of my original code but using the sorted() function. </p>
<p>For the newest I'd do:</p>
<pre><code>newestlist = {d[0]:d[2] for d in sorted(records)}
</code></pre>
<p>For the oldest I'd do:</p>
<pre><code>oldestlist = {d[0]:d[2] for d in sorted(records, reverse=True)}
</code></pre>
<p>Thanks to everyone who answered. I'll keep in mind the django references for if I use a queryset. </p>
| 0 |
2016-09-27T21:26:22Z
|
[
"python",
"list",
"date",
"dictionary",
"time"
] |
Python Query list for oldest date
| 39,733,775 |
<p>My query returns the following in a list:</p>
<pre><code>"Alex";"275467125";"2015-02-03 02:55:36-05";"1"
"Alex";"275467125";"2015-01-13 02:09:39-05";"1"
"Alex";"275467125";"2015-01-05 04:13:35-05";"1"
"Alex";"275467125";"2014-12-27 04:55:47-05";"1"
"Alex";"275467125";"2014-12-27 04:54:52-05";"1"
"Alex";"275467125";"2014-12-07 03:13:24-05";"1"
"Alex";"275467125";"2014-12-04 03:34:56-05";"1"
"Alex";"275467125";"2014-12-02 04:16:33-05";"1"
"Ali";"275464747";"2016-02-17 10:52:12-05";"2"
"Alladin";"275467455";"2016-03-13 06:51:52-04";"2"
"Alladin";"275467455";"2016-03-13 06:51:47-04";"2"
"Anna";"275467401";"2016-03-26 03:56:41-04";"1"
"Anna";"275467401";"2016-03-26 03:55:21-04";"1"
"Anna";"275467401";"2016-03-21 23:04:28-04";"1"
"Anna";"275467401";"2016-02-12 13:24:44-05";"1"
"Anna";"275467401";"2015-12-03 08:20:35-05";"1"
"Anna";"275467401";"2015-11-09 04:18:27-05";"1"
"Anna";"275467401";"2015-11-09 04:11:59-05";"1"
"Anna";"275467401";"2015-09-13 21:27:12-04";"1"
</code></pre>
<p>I want to create a dictionary of person's name with the oldest record they have. I've figured out:</p>
<pre><code>oldestlist = {d[0]:d[2] for d in records}
</code></pre>
<p>This returns a correct answer but my worry is that if I am presented a list that is not formatted in a descending order of date/time it will not provide the correct answer. What is the best way to create a dictionary with a name and the oldest date?</p>
| 1 |
2016-09-27T20:31:49Z
| 39,734,569 |
<p>You don't need to sort any data, just use a <em>defaultdict</em> and check the current date vs any new date and update accordingly:</p>
<pre><code>s = """"Alex";"275467125";"2015-02-03 02:55:36-05";"1"
"Alex";"275467125";"2015-01-13 02:09:39-05";"1"
"Alex";"275467125";"2015-01-05 04:13:35-05";"1"
"Alex";"275467125";"2014-12-27 04:55:47-05";"1"
"Alex";"275467125";"2014-12-27 04:54:52-05";"1"
"Alex";"275467125";"2014-12-07 03:13:24-05";"1"
"Alex";"275467125";"2014-12-04 03:34:56-05";"1"
"Alex";"275467125";"2014-12-02 04:16:33-05";"1"
"Ali";"275464747";"2016-02-17 10:52:12-05";"2"
"Alladin";"275467455";"2016-03-13 06:51:52-04";"2"
"Alladin";"275467455";"2016-03-13 06:51:47-04";"2"
"Anna";"275467401";"2016-03-26 03:56:41-04";"1"
"Anna";"275467401";"2016-03-26 03:55:21-04";"1"
"Anna";"275467401";"2016-03-21 23:04:28-04";"1"
"Anna";"275467401";"2016-02-12 13:24:44-05";"1"
"Anna";"275467401";"2015-12-03 08:20:35-05";"1"
"Anna";"275467401";"2015-11-09 04:18:27-05";"1"
"Anna";"275467401";"2015-11-09 04:11:59-05";"1"
"Anna";"275467401";"2015-09-13 21:27:12-04";"1"
"""
import csv
from collections import defaultdict
d = defaultdict(str)
for name,_, date, _ in csv.reader(s.splitlines(), delimiter=";"):
if not d[name] or d[name] > date:
d[name] = date
from pprint import pprint as pp
pp(dict(d))
</code></pre>
<p>Output:</p>
<pre><code> {'Alex': '2014-12-02 04:16:33-05',
'Ali': '2016-02-17 10:52:12-05',
'Alladin': '2016-03-13 06:51:47-04',
'Anna': '2015-09-13 21:27:12-04'}
</code></pre>
<p>because the dates are in the <em>y-m-d time</em> format it is safe to do a lexicographical comparison.</p>
| 1 |
2016-09-27T21:26:41Z
|
[
"python",
"list",
"date",
"dictionary",
"time"
] |
Python: count TP, FP, FN и TN
| 39,733,934 |
<p>I have dataframe with true class and class, that were predicted by some algorithm.</p>
<pre><code> true pred
0 1 0
1 1 1
2 1 1
3 0 0
4 1 1
</code></pre>
<p>I try to use</p>
<pre><code>def classification(y_actual, y_hat):
TP = 0
FP = 0
TN = 0
FN = 0
for i in range(len(y_hat)):
if y_actual[i] == y_hat[i] == 1:
TP += 1
for i in range(len(y_hat)):
if y_actual[i] == 1 and y_actual != y_hat[i]:
FP += 1
for i in range(len(y_hat)):
if y_actual[i] == y_hat[i] == 0:
TN += 1
for i in range(len(y_hat)):
if y_actual[i] == 0 and y_actual != y_hat[i]:
FN += 1
return(TP, FP, TN, FN)
</code></pre>
<p>but it return me</p>
<blockquote>
<p>ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
How can I fix that or maybe there are the better decision?</p>
</blockquote>
| 0 |
2016-09-27T20:41:41Z
| 39,733,979 |
<p>The error message happens because Python tries to convert an array to a boolean and fails.</p>
<p>That's because you're comparing <code>y_actual</code> with <code>y_hat[i]</code>.</p>
<p>It should be <code>y_actual[i] != y_hat[i]</code> (2 times in the code)</p>
<p>(I realize that it's just a typo, but the message is cryptic enough for the problem to become interesting)</p>
<p>While we're at it, you could make a more efficient routine by merging all your counters in a sole loop and using enumerate to avoid at least one access by index:</p>
<pre><code>def classification(y_actual, y_hat):
TP = 0
FP = 0
TN = 0
FN = 0
for i,yh in enumerate(y_hat):
if y_actual[i] == yh == 1:
TP += 1
if y_actual[i] == 1 and y_actual[i] != yh:
FP += 1
if y_actual[i] == yh == 0:
TN += 1
if y_actual[i] == 0 and y_actual[i] != yh:
FN += 1
return(TP, FP, TN, FN)
</code></pre>
<p>you see that this way it can be even be simplified even more
, cutting a lot through tests and branches:</p>
<pre><code>def classification(y_actual, y_hat):
TP = 0
FP = 0
TN = 0
FN = 0
for i,yh in enumerate(y_hat):
if y_actual[i] == yh:
if yh == 1:
TP += 1
elif yh == 0:
TN += 1
else: # y_actual[i] != yh
if y_actual[i] == 1 and :
FP += 1
elif y_actual[i] == 0:
FN += 1
return(TP, FP, TN, FN)
</code></pre>
| 1 |
2016-09-27T20:44:41Z
|
[
"python",
"machine-learning",
"scikit-learn"
] |
Python: count TP, FP, FN и TN
| 39,733,934 |
<p>I have dataframe with true class and class, that were predicted by some algorithm.</p>
<pre><code> true pred
0 1 0
1 1 1
2 1 1
3 0 0
4 1 1
</code></pre>
<p>I try to use</p>
<pre><code>def classification(y_actual, y_hat):
TP = 0
FP = 0
TN = 0
FN = 0
for i in range(len(y_hat)):
if y_actual[i] == y_hat[i] == 1:
TP += 1
for i in range(len(y_hat)):
if y_actual[i] == 1 and y_actual != y_hat[i]:
FP += 1
for i in range(len(y_hat)):
if y_actual[i] == y_hat[i] == 0:
TN += 1
for i in range(len(y_hat)):
if y_actual[i] == 0 and y_actual != y_hat[i]:
FN += 1
return(TP, FP, TN, FN)
</code></pre>
<p>but it return me</p>
<blockquote>
<p>ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
How can I fix that or maybe there are the better decision?</p>
</blockquote>
| 0 |
2016-09-27T20:41:41Z
| 39,734,245 |
<p>I use <code>confusion_matrix</code> from <code>sklearn.metrics</code> and it return me need matrix.</p>
| 1 |
2016-09-27T21:01:51Z
|
[
"python",
"machine-learning",
"scikit-learn"
] |
Counting Mulitple Values in a Python pandas Dataframe Column
| 39,733,948 |
<p>I'm trying to count unique values in a pandas dataframe column that contains multiple values separated by a string. I could do this using value_counts() if this were a series, but how would I do this in a dataframe? It seems like a dataframe should be easier. </p>
<p>Data:</p>
<pre><code> ID Tags
Created at
2016-03-10 09:46:00 3074 tag_a
2016-04-13 11:50:00 3524 tag_a tag_b
2016-05-18 15:22:00 3913 tag_a tag_b tag_c
</code></pre>
<p>Code:</p>
<pre><code>%matplotlib inline
import pandas as pd
# read csv into the data dataframe
allData = r'myData.csv'
tickets_df = pd.read_csv((allData),usecols=['Id','Created at','Tags'],parse_dates=['Created at'], index_col=['Created at'])
tickets_df.fillna(0,inplace=True)
tickets_df['2016':'2016']
# this would work with a series:
tickets_df[tickets_df['Tags'].str.split().apply(lambda x: pd.Series(x).value_counts()).sum()]
</code></pre>
<p>Error:</p>
<pre><code>KeyError: '[ 3. 2. 3. 5. 2. 102. 9. 5. 1. 4. 1. 161.\n 4. 4. 1. 6. 4. 34. 1. 1. 1. 6. 2. 5.\n 1. 1. 1. 1. 11. 2. 1. 1. 3. 1. 1. 1.\n 1. 1. 1. 1. 2. 1. 1. 2. 2. 6. 1. 4.\n 2. 1. 1. 2. 1. 1. 1. 3. 2. 1. 4. 35.\n 11. 2. 1. 13. 3. 8. 63. 87. 2. 2. 1. 1.\n 1. 1. 1. 1. 150. 1. 24. 3. 7. 5. 1. 1.\n 3. 4. 2. 6. 1. 2. 3. 5. 2. 5. 15. 1.\n 42. 1. 14. 1. 1. 1. 6. 13. 13. 9. 2. 11.\n 3. 1. 1.] not in index'
</code></pre>
<p>Desired Output: </p>
<pre><code>tag_a 3
tag_b 2
tag_c 1
</code></pre>
| 1 |
2016-09-27T20:42:20Z
| 39,734,034 |
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.split.html" rel="nofollow"><code>str.split</code></a> with <code>expand=True</code> to separate each string into different columns, then use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.stack.html" rel="nofollow"><code>stack</code></a> followed by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.value_counts.html" rel="nofollow"><code>value_counts</code></a>:</p>
<pre><code>df['Tags'].str.split(expand=True).stack().value_counts()
</code></pre>
<p>The resulting output:</p>
<pre><code>tag_a 3
tag_b 2
tag_c 1
</code></pre>
| 3 |
2016-09-27T20:48:00Z
|
[
"python",
"pandas"
] |
Python str.format() list of dictionaries
| 39,734,016 |
<p>I am trying to develop a format that prints a certain way when iterating through a list of dictionaries. </p>
<p>Error Raised: "tuple index out of range"</p>
<p>I have looked at several other questions that with a similar topic and know that you can't key in using a numerical value and format(). At least that's what I got from it. </p>
<p>In my case I am not using a numerical value so not sure why it isn't working. I think I know how to solve this using the other (%S) formatting method but trying to condense and make my code more pythonic. </p>
<p>So when I remove the .formate statement and leave the indexing arguments I get the correct values, but as soon as I try to format them I get the error. </p>
<p>My code:</p>
<pre><code>def namelist(names):
n = len(names)
return_format = {
0: '{}',
1: '{} & {}',
2:'{}, {} & {}'
}
name_stucture = return_format[n-1]
for idx, element in enumerate(names):
print name_stucture.format(names[idx]["name"])
</code></pre>
<p>Looking for why this is happening and how to resolve it, thanks!</p>
| 1 |
2016-09-27T20:46:58Z
| 39,734,231 |
<p>The error you are getting occurs when you try to unpack a format string with too few arguments. Here is a basic example:</p>
<pre><code>>>> '{}{}'.format('test')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: tuple index out of range
</code></pre>
<p>This occurs even if you pass a list as one argument. You need to <em>unpack</em> the list with the asterisk:</p>
<p>Without unpacking:</p>
<pre><code>>>> x = ['one', 'two']
>>> '{}{}'.format(x)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: tuple index out of range
</code></pre>
<p>With unpacking:</p>
<pre><code>>>> x = ['one', 'two']
>>> '{}{}'.format(*x)
'onetwo'
</code></pre>
<h2>Edit</h2>
<p>There are some other issues as well: you are looping through each name and printing the specified format, but there is no need for looping at all unless you want to print the names three times each. The use of <code>names[idx]</code>, instead of just <code>element</code> is also unnecessary and unpythonic.</p>
<p>Preserving some of your patterns, here is a working example:</p>
<pre><code>names = [ {'name': 'George'}, {'name': 'Alfred'}, {'name': 'Abe'}]
def namelist(names):
name_structure = ['{}', '{} & {}', '{}, {}, & {}'][min(2, len(names) - 1)]
name_structure.format(*[name['name'] for name in names])
</code></pre>
<p>Note that this function will have unexpected behavior if you have more than three names: it will only print the first three names.</p>
| 0 |
2016-09-27T21:01:04Z
|
[
"python",
"list",
"dictionary",
"format"
] |
Python str.format() list of dictionaries
| 39,734,016 |
<p>I am trying to develop a format that prints a certain way when iterating through a list of dictionaries. </p>
<p>Error Raised: "tuple index out of range"</p>
<p>I have looked at several other questions that with a similar topic and know that you can't key in using a numerical value and format(). At least that's what I got from it. </p>
<p>In my case I am not using a numerical value so not sure why it isn't working. I think I know how to solve this using the other (%S) formatting method but trying to condense and make my code more pythonic. </p>
<p>So when I remove the .formate statement and leave the indexing arguments I get the correct values, but as soon as I try to format them I get the error. </p>
<p>My code:</p>
<pre><code>def namelist(names):
n = len(names)
return_format = {
0: '{}',
1: '{} & {}',
2:'{}, {} & {}'
}
name_stucture = return_format[n-1]
for idx, element in enumerate(names):
print name_stucture.format(names[idx]["name"])
</code></pre>
<p>Looking for why this is happening and how to resolve it, thanks!</p>
| 1 |
2016-09-27T20:46:58Z
| 39,736,244 |
<p>The problem seems simpler than you're trying to make it:</p>
<pre><code>formats = [None, '{}', '{} & {}']
def namelist(names):
length = len(names)
if length > 2:
name_format = '{}, ' * (length - 2) + formats[2] # handle any number of names
else:
name_format = formats[length]
print(name_format.format(*names))
namelist(['Tom'])
namelist(['Tom', 'Dick'])
namelist(['Tom', 'Dick', 'Harry'])
namelist(['Groucho', 'Chico', 'Harpo', 'Zeppo'])
# the data structure is messy so clean it up rather than dirty the function:
namelist([d['name'] for d in [{'name': 'George'}, {'name': 'Alfred'}, {'name': 'Abe'}]])
</code></pre>
<p><strong>OUTPUT</strong></p>
<pre><code>> python3 test.py
Tom
Tom & Dick
Tom, Dick & Harry
Groucho, Chico, Harpo & Zeppo
George, Alfred & Abe
>
</code></pre>
| 1 |
2016-09-28T00:25:53Z
|
[
"python",
"list",
"dictionary",
"format"
] |
How to get all API tokens from a JSON list
| 39,734,033 |
<p>So, basically I have a loop that retrieves all of the API tokens I need in order to run another get call.</p>
<p>Here is a segment of my code:</p>
<pre><code>tokens = [result['apiToken'] for result in data_2['result']['apiToken']]
for i in tokens:
url = "https://swag.com"
headers = {
'x-api-token': i
}
response = requests.get(url, headers=headers)
data = json.loads(response.text)
</code></pre>
<p>Here is an example of the json:</p>
<pre><code>{"result":{"apiToken":"sdfagdsfgdfagfdagda"},"meta":
{"httpStatus":"200 - OK","requestId":"12343-232-424332428-432-
4234555","notice":"Request proxied. For faster response times, use this
host instead: swag.com"}}
</code></pre>
<p>With my code I am getting an error on the first line.</p>
<blockquote>
<p>typeerror string indices must be integers</p>
</blockquote>
<p>I just do not know how to only pull the API tokens.</p>
<p>data_2 :</p>
<pre><code>{'meta': {'httpStatus': '200 - OK', 'requestId': 'ewrfsdafasffds'}, 'result': {'apiToken': 'sdfdagfdfsgsd'}}
</code></pre>
| 0 |
2016-09-27T20:47:58Z
| 39,734,284 |
<p>As per your comment</p>
<blockquote>
<p>typeerror string indices must be integers</p>
</blockquote>
<p>try updating your list comprehension (assuming that <code>data_2</code> is a list of dicts and not a <code>JSON</code> string). It looks like you are iterating over the token characters.</p>
<pre><code>tokens = [result['apiToken'] for result in data_2['result']]
for i in tokens:
url = "https://swag.com"
headers = {
'x-api-token': i
}
response = requests.get(url, headers=headers)
data = json.loads(response.text)
</code></pre>
<p><strong>EDIT2</strong></p>
<p>So <code>data_2</code> may be a <code>JSON</code> string, not an dictionary (based on comments). In that case you can try the following:</p>
<pre><code>import json
tokens = [result['apiToken'] for result in json.loads(data_2)]
for i in tokens:
url = "https://swag.com"
headers = {
'x-api-token': i
}
response = requests.get(url, headers=headers)
data = json.loads(response.text)
</code></pre>
<p><strong>EDIT3</strong></p>
<p>Ok, so</p>
<blockquote>
<p>Earlier in the code I got a response named response.text and I did
data_2 = json.loads(resopnse.text)</p>
</blockquote>
<p>therefore <code>data_2</code> is a dictionary.</p>
<pre><code>tokens = [data_2['result']['apiToken']]
for i in tokens:
url = "https://swag.com"
headers = {
'x-api-token': i
}
response = requests.get(url, headers=headers)
data = json.loads(response.text)
</code></pre>
| 2 |
2016-09-27T21:04:01Z
|
[
"python",
"json"
] |
How to view variables within a function when warning is thrown pdb in python?
| 39,734,045 |
<p>Im running into a problem where</p>
<pre><code>cds_to_protein = str(feature.extract(record).seq.translate(to_stop = True))
</code></pre>
<p>will throw a Biopython warning. So I need to see what record and feature is being passed to it that causes that warning.</p>
<p>Is there a way to use pdb or another debugger to view parameters within a function?</p>
<p>EDIT: I'm using <code>python -Werror -m pdb script.py</code> which works to stop pdb when the warning appears</p>
<p>I've also added</p>
<pre><code> saved_record = record
saved_feature = feature
</code></pre>
<p>in order to save them but I don't know if they're necessary. Should I make them global in order to view them?</p>
<p>Here's the function:</p>
<pre><code>def validate_cds(record, feature):
saved_record = record
saved_feature = feature
protein_in_file = str(feature.qualifiers.get('translation', 'no_translation')).strip('\'[]')
cds_to_protein = str(feature.extract(record).seq.translate(to_stop = True))
return
</code></pre>
| 1 |
2016-09-27T20:48:21Z
| 39,734,180 |
<p>Try adding a trace to your function:</p>
<pre><code>def validate_cds(record, feature):
import pdb; pdb.set_trace()
saved_record = record
saved_feature = feature
protein_in_file = str(feature.qualifiers.get('translation', 'no_translation')).strip('\'[]')
cds_to_protein = str(feature.extract(record).seq.translate(to_stop = True))
return
</code></pre>
<p>Now when your function is called you will be popped into <code>pdb</code> and can interactively step through the function line by line, inspect variables, etc. Keep in mind though, that when you first see the <code>pdb</code> prompt, the variables you are interested in will not yet be initialized, so you can start stepping through the function with <code>n</code>, until you pass the points in the function that you are interested in.</p>
<p>I like having the import and the function call on the same line like this because there is only one line you have to clean up after debugging, and also, many syntax checkers will flag the line as since pep 8 discourages compound statements like this, so it will be a reminder to get rid of the line later.</p>
| 1 |
2016-09-27T20:57:48Z
|
[
"python",
"python-2.7",
"biopython"
] |
How to view variables within a function when warning is thrown pdb in python?
| 39,734,045 |
<p>Im running into a problem where</p>
<pre><code>cds_to_protein = str(feature.extract(record).seq.translate(to_stop = True))
</code></pre>
<p>will throw a Biopython warning. So I need to see what record and feature is being passed to it that causes that warning.</p>
<p>Is there a way to use pdb or another debugger to view parameters within a function?</p>
<p>EDIT: I'm using <code>python -Werror -m pdb script.py</code> which works to stop pdb when the warning appears</p>
<p>I've also added</p>
<pre><code> saved_record = record
saved_feature = feature
</code></pre>
<p>in order to save them but I don't know if they're necessary. Should I make them global in order to view them?</p>
<p>Here's the function:</p>
<pre><code>def validate_cds(record, feature):
saved_record = record
saved_feature = feature
protein_in_file = str(feature.qualifiers.get('translation', 'no_translation')).strip('\'[]')
cds_to_protein = str(feature.extract(record).seq.translate(to_stop = True))
return
</code></pre>
| 1 |
2016-09-27T20:48:21Z
| 39,734,676 |
<p>thanks to @TomaszPlaskota for his suggestion to use a <code>try: except</code></p>
<p>Added the following to turn a warning into an exception</p>
<pre><code>import warnings
from Bio import BiopythonWarning
warnings.filterwarnings('error')
</code></pre>
<p>And a simple <code>try: except</code> correctly stops it</p>
<pre><code>def validate_cds(record, feature):
try:
protein_in_file = str(feature.qualifiers.get('translation', 'no_translation')).strip('\'[]')
cds_to_protein = str(feature.extract(record).seq.translate(to_stop = True))
except:
print record.id
return
</code></pre>
| 0 |
2016-09-27T21:35:18Z
|
[
"python",
"python-2.7",
"biopython"
] |
How to view variables within a function when warning is thrown pdb in python?
| 39,734,045 |
<p>Im running into a problem where</p>
<pre><code>cds_to_protein = str(feature.extract(record).seq.translate(to_stop = True))
</code></pre>
<p>will throw a Biopython warning. So I need to see what record and feature is being passed to it that causes that warning.</p>
<p>Is there a way to use pdb or another debugger to view parameters within a function?</p>
<p>EDIT: I'm using <code>python -Werror -m pdb script.py</code> which works to stop pdb when the warning appears</p>
<p>I've also added</p>
<pre><code> saved_record = record
saved_feature = feature
</code></pre>
<p>in order to save them but I don't know if they're necessary. Should I make them global in order to view them?</p>
<p>Here's the function:</p>
<pre><code>def validate_cds(record, feature):
saved_record = record
saved_feature = feature
protein_in_file = str(feature.qualifiers.get('translation', 'no_translation')).strip('\'[]')
cds_to_protein = str(feature.extract(record).seq.translate(to_stop = True))
return
</code></pre>
| 1 |
2016-09-27T20:48:21Z
| 39,734,762 |
<p>Per the <a href="https://docs.python.org/2/library/pdb.html" rel="nofollow">docs</a>:</p>
<blockquote>
<p>The typical usage to break into the debugger from a running program is to insert</p>
</blockquote>
<p><code>import pdb; pdb.set_trace()</code></p>
<blockquote>
<p>at the location you want to break into the debugger. You can then step through the code following this statement, and continue running without the debugger using the c command.</p>
</blockquote>
| 0 |
2016-09-27T21:41:30Z
|
[
"python",
"python-2.7",
"biopython"
] |
Tokenise line containing string literals
| 39,734,209 |
<p>Using <code>str.split</code> on <code>"print 'Hello, world!' times 3"</code> returns the list <code>["print", "'Hello,", "world!'", "times", "3"]</code>. However, I want the result <code>["print", "'Hello, world!'", "times", "3"]</code>. How can I do that?</p>
| 2 |
2016-09-27T20:59:33Z
| 39,734,294 |
<p>If you're going to exclude the words in quote out of the <em>split</em>, you could use <a href="https://docs.python.org/2/library/shlex.html#shlex.split" rel="nofollow"><code>shlex.split</code></a>:</p>
<pre><code>import shlex
s = "print 'Hello, world!' times 3"
print(shlex.split(s))
# ['print', 'Hello, world!', 'times', '3']
</code></pre>
| 3 |
2016-09-27T21:04:43Z
|
[
"python",
"string",
"parsing"
] |
Tokenise line containing string literals
| 39,734,209 |
<p>Using <code>str.split</code> on <code>"print 'Hello, world!' times 3"</code> returns the list <code>["print", "'Hello,", "world!'", "times", "3"]</code>. However, I want the result <code>["print", "'Hello, world!'", "times", "3"]</code>. How can I do that?</p>
| 2 |
2016-09-27T20:59:33Z
| 39,734,318 |
<p><a href="https://www.tutorialspoint.com/python/string_split.htm" rel="nofollow"><code>.split()</code></a> function splits the <code>str</code> based on the delimiter. The default delimiter is a <code>blank space</code>. It doesn't care about the <code>'</code> within your string. In case you want to treat words within <code>'</code> as a single word. You should be using <a href="https://docs.python.org/2/library/shlex.html#shlex.split" rel="nofollow">shlex</a> library or you may write <code>regex</code> expression. Surely, <code>split()</code> is not what you are looking for.</p>
| 0 |
2016-09-27T21:06:22Z
|
[
"python",
"string",
"parsing"
] |
Tokenise line containing string literals
| 39,734,209 |
<p>Using <code>str.split</code> on <code>"print 'Hello, world!' times 3"</code> returns the list <code>["print", "'Hello,", "world!'", "times", "3"]</code>. However, I want the result <code>["print", "'Hello, world!'", "times", "3"]</code>. How can I do that?</p>
| 2 |
2016-09-27T20:59:33Z
| 39,734,684 |
<p>This regex will capture the quotes, if you want them.</p>
<pre><code>import re
s = "print 'hello, world!' 3 times"
re.findall(r'(\w+|\'.+\')',s)
</code></pre>
| 1 |
2016-09-27T21:35:37Z
|
[
"python",
"string",
"parsing"
] |
How do I get PyOpenGL to work with a wxPython context, based on this C++ Modern OpenGL tutorial?
| 39,734,211 |
<p>I've been following <a href="https://open.gl/drawing" rel="nofollow">this tutorial</a> for drawing a simple triangle using shaders and modern OpenGL features such as Vertex Array Objects andVertex Buffer Objects. The tutorial code is in C++, but I figured that as OpenGL is the same whichever bindings you use, it would be easy to transpose into Python. The main difference is I am using the wxPython glCanvas context to create a window to draw in. This is what I have so far:</p>
<pre><code>import wx
from wx import glcanvas
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
from OpenGL.GL.ARB.shader_objects import *
from OpenGL.GL.ARB.fragment_shader import *
from OpenGL.GL.ARB.vertex_shader import *
import numpy as np
vertexSource = """
#version 130
in vec2 position;
void main()
{
gl_Position = vec4(position, 0.0, 1.0);
}
"""
fragmentSource = """
#version 130
out vec4 outColor;
void main()
{
outColor = vec4(1.0, 1.0, 1.0, 1.0);
}
"""
class OpenGLCanvas(glcanvas.GLCanvas):
def __init__(self, parent):
glcanvas.GLCanvas.__init__(self, parent, -1, size=(640, 480))
self.init = False
self.context = glcanvas.GLContext(self)
self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
self.Bind(wx.EVT_PAINT, self.OnPaint)
def OnEraseBackground(self, event):
pass # Do nothing, to avoid flashing on MSW.
def OnPaint(self, event):
dc = wx.PaintDC(self)
self.SetCurrent(self.context)
if not self.init:
self.InitGL()
self.init = True
self.OnDraw()
def InitGL(self):
# Vertex Input
## Vertex Array Objects
vao = glGenVertexArrays(1)
glBindVertexArray(vao)
## Vertex Buffer Object
vbo = glGenBuffers(1) # Generate 1 buffer
vertices = np.array([0.0, 0.5, 0.5, -0.5, -0.5, -0.5], dtype=np.float32)
## Upload data to GPU
glBindBuffer(GL_ARRAY_BUFFER, vbo)
glBufferData(GL_ARRAY_BUFFER, vertices.nbytes, vertices, GL_STATIC_DRAW)
# Compile shaders and combining them into a program
## Create and compile the vertex shader
vertexShader = glCreateShader(GL_VERTEX_SHADER)
glShaderSource(vertexShader, vertexSource)
glCompileShader(vertexShader)
## Create and compile the fragment shader
fragmentShader = glCreateShader(GL_FRAGMENT_SHADER)
glShaderSource(fragmentShader, fragmentSource)
glCompileShader(fragmentShader)
## Link the vertex and fragment shader into a shader program
shaderProgram = glCreateProgram()
glAttachShader(shaderProgram, vertexShader)
glAttachShader(shaderProgram, fragmentShader)
glBindFragDataLocation(shaderProgram, 0, "outColor")
glLinkProgram(shaderProgram)
glUseProgram(shaderProgram)
# Making the link between vertex data and attributes
posAttrib = glGetAttribLocation(shaderProgram, "position")
glEnableVertexAttribArray(posAttrib)
glVertexAttribPointer(posAttrib, 2, GL_FLOAT, GL_FALSE, 0, 0)
def OnDraw(self):
# Set clear color
glClearColor(0.0, 0.0, 0.0, 1.0)
#Clear the screen to black
glClear(GL_COLOR_BUFFER_BIT)
# draw six faces of a cube
glDrawArrays(GL_TRIANGLES, 0, 3)
self.SwapBuffers()
class Frame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, title="Hello World", size=(640,480))
canvas = OpenGLCanvas(self)
app = wx.App()
frame = Frame()
frame.Show()
app.MainLoop()
</code></pre>
<p>When I run the code there are no python errors or OpenGL errors, and the shaders appear to compile correctly. However, it just draws a black window, with no triangle. I don't think this is a problem with wxPython's glcanvas.GLContext, as I have sucessfully used it to draw a triangle before using the deprecated glBegin() and glEnd() commands. </p>
<p>Incidentally, <a href="https://github.com/01AutoMonkey/open.gl-tutorials-to-pyglet/blob/master/2-1-Drawing_Polygons-Triangle.py" rel="nofollow">someone has converted the same tutorial to use Python and a pyglet context</a>, which works perfectly, however I want to use wxPython for my GUI. Has anyone got this to work before?</p>
| 1 |
2016-09-27T20:59:40Z
| 39,803,714 |
<p>If you are still having this problem, I think the issue is in this following line and the way PyOpenGL works. I found just making this following fix got your demo to work.</p>
<pre><code>glVertexAttribPointer(posAttrib, 2, GL_FLOAT, GL_FALSE, 0, None)
</code></pre>
<p>Apparently 0 != None in the bindings!</p>
| 0 |
2016-10-01T06:32:05Z
|
[
"python",
"python-2.7",
"wxpython",
"opengl-3",
"pyopengl"
] |
Formatting negative fixed-length string
| 39,734,252 |
<p>In <code>python</code>, I'm trying to format a number to be a fixed-length string with leading zeros, which can be done like so:</p>
<pre><code>'{:0>10}'.format('10.0040')
'00010.0040'
</code></pre>
<p>I have a negative number and want to express the negative, I would get this:</p>
<pre><code>'{:0>10}'.format('-10.0040')
'00-10.0040'
</code></pre>
<p>If I wanted to format the string to be:</p>
<pre><code>'-0010.0040'
</code></pre>
<p>how could I do this? </p>
<p>I could do an if/then, but wondering if format would handle this already. </p>
| 2 |
2016-09-27T21:01:57Z
| 39,734,358 |
<p>I don't know how to do it with <code>str.format</code>. May I propose using <a href="https://docs.python.org/2/library/string.html#string.zfill" rel="nofollow"><code>str.zfill</code></a> instead?</p>
<pre><code>>>> '-10.0040'.zfill(10)
'-0010.0040'
>>> '10.0040'.zfill(10)
'00010.0040'
</code></pre>
<p>If you can bear converting to a number before formatting:</p>
<pre><code>>>> from decimal import Decimal
>>> '{:010.4f}'.format(Decimal('10.0040'))
'00010.0040'
>>> '{:010.4f}'.format(Decimal('-10.0040'))
'-0010.0040'
</code></pre>
| 4 |
2016-09-27T21:09:52Z
|
[
"python"
] |
Formatting negative fixed-length string
| 39,734,252 |
<p>In <code>python</code>, I'm trying to format a number to be a fixed-length string with leading zeros, which can be done like so:</p>
<pre><code>'{:0>10}'.format('10.0040')
'00010.0040'
</code></pre>
<p>I have a negative number and want to express the negative, I would get this:</p>
<pre><code>'{:0>10}'.format('-10.0040')
'00-10.0040'
</code></pre>
<p>If I wanted to format the string to be:</p>
<pre><code>'-0010.0040'
</code></pre>
<p>how could I do this? </p>
<p>I could do an if/then, but wondering if format would handle this already. </p>
| 2 |
2016-09-27T21:01:57Z
| 39,734,420 |
<p>You're problem is that your "number" is being represented as a string, so python has no way of knowing whether it's positive or negative, because it doesn't know it's a number.</p>
<pre><code>>>> '{: 010.4f}'.format(10.0400)
' 0010.0400'
>>> '{: 010.4f}'.format(-10.0400)
'-0010.0400'
</code></pre>
<p>This fills with <code>0</code>'s and has a fixed precision. It will use a <code>space</code> for positive numbers and a <code>-</code> for negative.</p>
<p>You can change the behavior (i.e. <code>+</code> for positive signs, or just fill with an extra <code>0</code>) using the <a href="https://docs.python.org/2/library/string.html#format-specification-mini-language"><code>sign</code></a> portion of the formatting token</p>
| 5 |
2016-09-27T21:15:30Z
|
[
"python"
] |
Formatting negative fixed-length string
| 39,734,252 |
<p>In <code>python</code>, I'm trying to format a number to be a fixed-length string with leading zeros, which can be done like so:</p>
<pre><code>'{:0>10}'.format('10.0040')
'00010.0040'
</code></pre>
<p>I have a negative number and want to express the negative, I would get this:</p>
<pre><code>'{:0>10}'.format('-10.0040')
'00-10.0040'
</code></pre>
<p>If I wanted to format the string to be:</p>
<pre><code>'-0010.0040'
</code></pre>
<p>how could I do this? </p>
<p>I could do an if/then, but wondering if format would handle this already. </p>
| 2 |
2016-09-27T21:01:57Z
| 39,734,468 |
<p>If you can convert the string to a float, you can do this:</p>
<pre><code>>>> '{:0=10.4f}'.format(float('-10.0040'))
'-0010.0040'
>>> '{:0=10.4f}'.format(float('10.0040'))
'00010.0040'
</code></pre>
| 2 |
2016-09-27T21:18:29Z
|
[
"python"
] |
covariance between two columns in pandas groupby pandas
| 39,734,304 |
<p>I am trying to calculate the covariance between two columns by group. I am doing doing the following:</p>
<pre><code>A = pd.DataFrame({'group':['A','A','A','A','B','B','B'],
'value1':[1,2,3,4,5,6,7],
'value2':[8,5,4,3,7,8,8]})
B = A.groupby('group')
B['value1'].cov(B['value2'])
</code></pre>
<p>Ideally, I would like to get the covariance between X and Y and not the whole variance-covariance matrix, since I only have two columns.</p>
<p>Thank you,</p>
| 1 |
2016-09-27T21:05:20Z
| 39,734,367 |
<p>The following code gives you the grouped variance-covariance matrix. You can subset it as you wish to just get the covariances. </p>
<pre><code>import pandas as pd
A = pd.DataFrame({'group':['A','A','A','A','B','B','B'],
'value1':[1,2,3,4,5,6,7],
'value2':[8,5,4,3,7,8,8]})
print A.groupby('group').cov()
</code></pre>
| 2 |
2016-09-27T21:11:03Z
|
[
"python",
"pandas"
] |
covariance between two columns in pandas groupby pandas
| 39,734,304 |
<p>I am trying to calculate the covariance between two columns by group. I am doing doing the following:</p>
<pre><code>A = pd.DataFrame({'group':['A','A','A','A','B','B','B'],
'value1':[1,2,3,4,5,6,7],
'value2':[8,5,4,3,7,8,8]})
B = A.groupby('group')
B['value1'].cov(B['value2'])
</code></pre>
<p>Ideally, I would like to get the covariance between X and Y and not the whole variance-covariance matrix, since I only have two columns.</p>
<p>Thank you,</p>
| 1 |
2016-09-27T21:05:20Z
| 39,734,585 |
<p>You are almost there, only that you do not clear understand the groupby object, see <a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html" rel="nofollow">Pandas-GroupBy</a> for more details.</p>
<p>For your problem, if I understand correctly, you would like to calculate cov between two columns in same group.</p>
<p>The simplest one is to use <code>groupeby.cov</code> function, which gives pairwise cov between groups.</p>
<pre><code>A.groupby('group').cov()
value1 value2
group
A value1 1.666667 -2.666667
value2 -2.666667 4.666667
B value1 1.000000 0.500000
value2 0.500000 0.333333
</code></pre>
<p>If you only need cov(grouped_v1, grouped_v2)</p>
<pre><code>grouped = A.groupby('group')
grouped.apply(lambda x: x['value1'].cov(x['value2']))
group
A -2.666667
B 0.500000
</code></pre>
<p>In which, <code>grouped</code> is a <code>groupby</code> object. For <code>grouped.apply</code> function, it need a callback function as argument and each group will be the argument for the callback function. Here, the callback function is a <code>lambda</code> function, and the argument <code>x</code> is a group (a DataFrame).</p>
<p>Hope this will be helpful for your understanding of groupby.</p>
| 3 |
2016-09-27T21:27:58Z
|
[
"python",
"pandas"
] |
Changed Django model attribute and now getting error for it
| 39,734,334 |
<p>I had a model with a DateField that worked just fine. I wanted to change it from a DateField to a CharField. </p>
<p><strong>Before:</strong></p>
<pre><code>class NWEAScore(models.Model):
test_date = models.DateField(default=date.today, verbose_name='Test Date')
</code></pre>
<p><strong>After:</strong></p>
<pre><code>class NWEAScore(models.Model):
year = models.CharField(max_length=50, choices=YEAR_CHOICES, default=SIXTEEN)
season = models.CharField(max_length=50, choices=SESSION_CHOICES, default=FALL)
</code></pre>
<p>Not sure what went wrong but now I'm getting an error.</p>
<p>Making migrations is no problem. I make them and then upload them to my server, then when I migrate, I get an error.
The Error I get when I try to apply my migrations:</p>
<pre><code>(venv) alex@newton:~/newton$ python manage.py migrate
Operations to perform:
Apply all migrations: admin, amc, auth, brain, contenttypes, ixl, nwea, sessions
Running migrations:
Rendering model states... DONE
Applying brain.0021_auto_20160927_0038... OK
Applying nwea.0011_auto_20160927_0038...Traceback (most recent call last):
File "/home/alex/newton/venv/lib/python3.4/site-packages/django/db/models/options.py", line 612, in get_field
return self.fields_map[field_name]
KeyError: 'test_date'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/home/alex/newton/venv/lib/python3.4/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line
utility.execute()
File "/home/alex/newton/venv/lib/python3.4/site-packages/django/core/management/__init__.py", line 359, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/alex/newton/venv/lib/python3.4/site-packages/django/core/management/base.py", line 305, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/alex/newton/venv/lib/python3.4/site-packages/django/core/management/base.py", line 356, in execute
output = self.handle(*args, **options)
File "/home/alex/newton/venv/lib/python3.4/site-packages/django/core/management/commands/migrate.py", line 202, in handle
targets, plan, fake=fake, fake_initial=fake_initial
File "/home/alex/newton/venv/lib/python3.4/site-packages/django/db/migrations/executor.py", line 97, in migrate
state = self._migrate_all_forwards(plan, full_plan, fake=fake, fake_initial=fake_initial)
File "/home/alex/newton/venv/lib/python3.4/site-packages/django/db/migrations/executor.py", line 132, in _migrate_all_forwards
state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
File "/home/alex/newton/venv/lib/python3.4/site-packages/django/db/migrations/executor.py", line 237, in apply_migration
state = migration.apply(state, schema_editor)
File "/home/alex/newton/venv/lib/python3.4/site-packages/django/db/migrations/migration.py", line 129, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
File "/home/alex/newton/venv/lib/python3.4/site-packages/django/db/migrations/operations/models.py", line 525, in database_forwards
getattr(new_model._meta, self.option_name, set()),
File "/home/alex/newton/venv/lib/python3.4/site-packages/django/db/backends/base/schema.py", line 329, in alter_unique_together
self._delete_composed_index(model, fields, {'unique': True}, self.sql_delete_unique)
File "/home/alex/newton/venv/lib/python3.4/site-packages/django/db/backends/base/schema.py", line 352, in _delete_composed_index
columns = [model._meta.get_field(field).column for field in fields]
File "/home/alex/newton/venv/lib/python3.4/site-packages/django/db/backends/base/schema.py", line 352, in <listcomp>
columns = [model._meta.get_field(field).column for field in fields]
File "/home/alex/newton/venv/lib/python3.4/site-packages/django/db/models/options.py", line 614, in get_field
raise FieldDoesNotExist('%s has no field named %r' % (self.object_name, field_name))
django.core.exceptions.FieldDoesNotExist: NWEAScore has no field named 'test_date'
</code></pre>
<p>I went through and deleted all my instances from all my models, just incase a remaining "NWEAScore" Instance with a test_date was throwing the error. </p>
<p>I searched through my entire project for the term "test_date", trying to delete every instance, and the only remaining instances are in old migrations. Should I go back and delete those? Could that be throwing that off? I'm not too clear on how to wipe migrations and make new ones if that's it. </p>
<p>I gave it a shot for a few days, if anyone has suggestions thanks in advance!</p>
| 1 |
2016-09-27T21:07:52Z
| 39,734,393 |
<p>Go to the <em>migrations</em> folder of your app and delete all files, except <code>__init__.py</code>. Then run the command:</p>
<pre><code>python manage.py makemigrations
</code></pre>
<p>to make new migrations with the updated fields</p>
| 1 |
2016-09-27T21:13:30Z
|
[
"python",
"django",
"django-models"
] |
Ordered Dictionary and Sorting
| 39,734,360 |
<p>I'm trying to solve a simple practice test question:</p>
<blockquote>
<p>Parse the CSV file to:</p>
<ul>
<li>Find only the rows where the user started before September 6th, 2010. </li>
<li>Next, order the values from the "words" column in ascending order (by start date) </li>
<li>Return the compiled "hidden" phrase</li>
</ul>
</blockquote>
<p>The csv file has 19 columns and 1000 rows of data. Most of which are irrelevant. As the problem states, we're only concerned with sorting the the start_date column in ascending order to get the associated word from the 'words' column. Together, the words will give the "hidden" phrase.</p>
<p>The dates in the source file are in UTC time format so I had to convert them. I'm at the point now where I think I've got the right rows selected, but I'm having issues sorting the dates. </p>
<p>Here's my code:</p>
<pre><code>import csv
from collections import OrderedDict
from datetime import datetime
with open('TSE_sample_data.csv', 'rb') as csvIn:
reader = csv.DictReader(csvIn)
for row in reader:
#convert from UTC to more standard date format
startdt = datetime.fromtimestamp(int(row['start_date']))
new_startdt = datetime.strftime(startdt, '%Y%m%d')
# find dates before Sep 6th, 2010
if new_startdt < '20100906':
# add the values from the 'words' column to a list
words = []
words.append(row['words'])
# add the dates to a list
dates = []
dates.append(new_startdt)
# create an ordered dictionary to sort the dates... this is where I'm having issues
dict1 = OrderedDict(zip(words, dates))
print dict1
#print list(dict1.items())[0][1]
#dict2 = sorted([(y,x) for x,y in dict1.items()])
#print dict2
</code></pre>
<p>When I <code>print dict1</code> I'm expecting to have one ordered dictionary with the words and the dates included as items. Instead, what I'm getting is multiple ordered dictionaries for each key-value pair created.</p>
| 0 |
2016-09-27T21:10:11Z
| 39,734,446 |
<p>Here's the corrected version:</p>
<pre><code>import csv
from collections import OrderedDict
from datetime import datetime
with open('TSE_sample_data.csv', 'rb') as csvIn:
reader = csv.DictReader(csvIn)
words = []
dates = []
for row in reader:
#convert from UTC to more standard date format
startdt = datetime.fromtimestamp(int(row['start_date']))
new_startdt = datetime.strftime(startdt, '%Y%m%d')
# find dates before Sep 6th, 2010
if new_startdt < '20100906':
# add the values from the 'words' column to a list
words.append(row['words'])
# add the dates to a list
dates.append(new_startdt)
# This is where I was going wrong! Had to move the lines below outside of the for loop
# Originally, because I was still inside the for loop, I was creating a new Ordered Dict for each "row in reader" that met my if condition
# By doing this outside of the for loop, I'm able to create the ordered dict storing all of the values that have been found in tuples inside the ordered dict
# create an ordered dictionary to sort by the dates
dict1 = OrderedDict(zip(words, dates))
dict2 = sorted([(y,x) for x,y in dict1.items()])
# print the hidden message
for i in dict2:
print i[1]
</code></pre>
| 0 |
2016-09-27T21:17:17Z
|
[
"python",
"sorting",
"for-loop",
"dictionary",
"ordereddictionary"
] |
Flask wtforms DecimalField not displaying in HTML
| 39,734,361 |
<p>My TextField forms are displaying fine in the html page, but not the DecimalFields. The DecimalFields don't display at all.</p>
<p>My forms.py:</p>
<pre><code>from flask.ext.wtf import Form
from wtforms import TextField, validators, IntegerField, DateField, BooleanField, DecimalField
class EnterPart(Form):
Description = TextField(label='label', description="description", validators=[validators.required()])
VendorCost = DecimalField(label='label',description="cost")
</code></pre>
<p>My application.py:</p>
<pre><code>from flask import Flask, render_template, request, redirect, url_for
def index():
form = EnterPart(request.form)
return render_template('index.html', form=form)
</code></pre>
<p>My index.html:</p>
<pre><code>{% extends "base.html" %} {% import 'macros.html' as macros %}
{% block content %}
{{ form.hidden_tag() }}
{{ macros.render_field(form.Description, placeholder='Description', type='dbSerial', label_visible=false) }}
{{ macros.render_field(form.VendorCost, placeholder='Category', type='dbSerial', label_visible=false) }}
{% endblock %}
</code></pre>
<p>I've been building from the tutorial here:
<a href="http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world" rel="nofollow">http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world</a></p>
<p>Thanks in advance.</p>
| -1 |
2016-09-27T21:10:16Z
| 39,734,882 |
<p>Macros.html didn't have an option for dealing with DecimalField. By adding a rendering option for DecimalField, it now displays correctly.</p>
<p>I changed a block in macros.html from:</p>
<pre><code><div class="form-group {% if field.errors %}has-error{% endif %} {{ kwargs.pop('class_', '') }}">
{% if (field.type != 'HiddenField' or field.type !='CSRFTokenField') and label_visible %}
<label for="{{ field.id }}" class="control-label">{{ field.label }}</label>
{% endif %}
{% if field.type == 'TextField' %}
{{ field(class_='form-control', **kwargs) }}
{% endif %}
{% if field.errors %}
{% for e in field.errors %}
<p class="help-block">{{ e }}</p>
{% endfor %}
{% endif %}
</div>
</code></pre>
<p>to:</p>
<pre><code><div class="form-group {% if field.errors %}has-error{% endif %} {{ kwargs.pop('class_', '') }}">
{% if (field.type != 'HiddenField' or field.type !='CSRFTokenField') and label_visible %}
<label for="{{ field.id }}" class="control-label">{{ field.label }}</label>
{% endif %}
{% if field.type == 'TextField' %}
{{ field(class_='form-control', **kwargs) }}
{% endif %}
{% if field.type == 'DecimalField' %}
{{ field(class_='form-control', **kwargs) }}
{% endif %}
{% if field.errors %}
{% for e in field.errors %}
<p class="help-block">{{ e }}</p>
{% endfor %}
{% endif %}
</div>
</code></pre>
| 0 |
2016-09-27T21:50:46Z
|
[
"python",
"flask",
"wtforms",
"flask-wtforms"
] |
Python: Combining two lists and removing duplicates in a functional programming way
| 39,734,485 |
<p>I'm trying to write a function that would combine two lists while removing duplicate items, but in a pure functional way.
For example:</p>
<pre><code>a = [1,2,2]
b = [1,3,3,4,5,0]
union(a,b) --> [1,2,3,4,5,0]
</code></pre>
<p>The imperative form of the code would be:</p>
<pre><code>def union(a,b):
c = []
for i in a + b:
if i not in c:
c.append(i)
return c
</code></pre>
<p>I've tried several approaches, but couldn't find a way to do that without using a loop to go over the items - what am I missing?</p>
| 1 |
2016-09-27T21:19:48Z
| 39,734,524 |
<p>If you want to keep the order you can use <code>collections.OrderedDict</code>, otherwise just use <code>set</code>. These data structures use hash values of their items for preserving them, thus they don't keep the duplicates.</p>
<pre><code>In [11]: from collections import OrderedDict
In [12]: list(OrderedDict.fromkeys(a+b))
Out[12]: [1, 2, 3, 4, 5, 0]
</code></pre>
| 1 |
2016-09-27T21:23:26Z
|
[
"python",
"functional-programming"
] |
Python: Combining two lists and removing duplicates in a functional programming way
| 39,734,485 |
<p>I'm trying to write a function that would combine two lists while removing duplicate items, but in a pure functional way.
For example:</p>
<pre><code>a = [1,2,2]
b = [1,3,3,4,5,0]
union(a,b) --> [1,2,3,4,5,0]
</code></pre>
<p>The imperative form of the code would be:</p>
<pre><code>def union(a,b):
c = []
for i in a + b:
if i not in c:
c.append(i)
return c
</code></pre>
<p>I've tried several approaches, but couldn't find a way to do that without using a loop to go over the items - what am I missing?</p>
| 1 |
2016-09-27T21:19:48Z
| 39,734,533 |
<p>To combine the two lists:</p>
<pre><code>a = [1,2,2]
b = [1,3,3,4,5,0]
</code></pre>
<p>Using sets:</p>
<pre><code>union = set(a) | set(b)
# -> set([0, 1, 2, 3, 4, 5])
</code></pre>
<p>Using comprehension list:</p>
<pre><code>union = a + [x for x in b if x not in a]
# -> [1, 2, 2, 3, 3, 4, 5, 0]
</code></pre>
<p>Using loop, without duplicates, preserving order:</p>
<pre><code>union = []
for x in a + b:
if x not in union:
union.append(x)
# -> [1, 2, 3, 4, 5, 0]
</code></pre>
| 0 |
2016-09-27T21:23:52Z
|
[
"python",
"functional-programming"
] |
Python: Combining two lists and removing duplicates in a functional programming way
| 39,734,485 |
<p>I'm trying to write a function that would combine two lists while removing duplicate items, but in a pure functional way.
For example:</p>
<pre><code>a = [1,2,2]
b = [1,3,3,4,5,0]
union(a,b) --> [1,2,3,4,5,0]
</code></pre>
<p>The imperative form of the code would be:</p>
<pre><code>def union(a,b):
c = []
for i in a + b:
if i not in c:
c.append(i)
return c
</code></pre>
<p>I've tried several approaches, but couldn't find a way to do that without using a loop to go over the items - what am I missing?</p>
| 1 |
2016-09-27T21:19:48Z
| 39,734,546 |
<p>Have you tried using <code>sets</code>?</p>
<pre><code>>>> a = [1,2,2]
>>> b = [1,3,3,4,5,0]
>>> list(set(a).union(set(b)))
[0, 1, 2, 3, 4, 5]
</code></pre>
| 1 |
2016-09-27T21:25:04Z
|
[
"python",
"functional-programming"
] |
Python: Combining two lists and removing duplicates in a functional programming way
| 39,734,485 |
<p>I'm trying to write a function that would combine two lists while removing duplicate items, but in a pure functional way.
For example:</p>
<pre><code>a = [1,2,2]
b = [1,3,3,4,5,0]
union(a,b) --> [1,2,3,4,5,0]
</code></pre>
<p>The imperative form of the code would be:</p>
<pre><code>def union(a,b):
c = []
for i in a + b:
if i not in c:
c.append(i)
return c
</code></pre>
<p>I've tried several approaches, but couldn't find a way to do that without using a loop to go over the items - what am I missing?</p>
| 1 |
2016-09-27T21:19:48Z
| 39,734,553 |
<p>How about </p>
<pre><code>>>> x = [1,2,3]
>>> y = [1,3,5,7,9]
>>> list(set(x).union(set(y)))
</code></pre>
| 0 |
2016-09-27T21:25:41Z
|
[
"python",
"functional-programming"
] |
Python: Combining two lists and removing duplicates in a functional programming way
| 39,734,485 |
<p>I'm trying to write a function that would combine two lists while removing duplicate items, but in a pure functional way.
For example:</p>
<pre><code>a = [1,2,2]
b = [1,3,3,4,5,0]
union(a,b) --> [1,2,3,4,5,0]
</code></pre>
<p>The imperative form of the code would be:</p>
<pre><code>def union(a,b):
c = []
for i in a + b:
if i not in c:
c.append(i)
return c
</code></pre>
<p>I've tried several approaches, but couldn't find a way to do that without using a loop to go over the items - what am I missing?</p>
| 1 |
2016-09-27T21:19:48Z
| 39,734,678 |
<pre><code>list(set(a+b))
</code></pre>
<p>This combines two lists a and b and using set takes only unique vales and then we can make it back to list. </p>
| 0 |
2016-09-27T21:35:28Z
|
[
"python",
"functional-programming"
] |
Sum numbers by letter in list of tuples
| 39,734,549 |
<p>I have a list of tuples: </p>
<pre><code>[ ('A',100), ('B',50), ('A',50), ('B',20), ('C',10) ]
</code></pre>
<p>I am trying to sum up all numbers that have the same letter. I.e. I want to output </p>
<pre><code>[('A', 150), ('B', 70), ('C',10)]
</code></pre>
<p>I have tried using set to get the unique values but then when I try and compare the first elements to the set I get </p>
<pre><code>TypeError: unsupported operand type(s) for +: 'int' and 'str'
</code></pre>
<p>Any quick solutions to match the numbers by letter?</p>
| 1 |
2016-09-27T21:25:12Z
| 39,734,639 |
<p>In order to achieve this, firstly create a dictionary to store your values. Then convert the <code>dict</code> object to <code>tuple list</code> using <code>.items()</code> Below is the sample code on how to achieve this:</p>
<pre><code>my_list = [ ('A',100), ('B',50), ('A',50), ('B',20), ('C',10) ]
my_dict = {}
for key, val in my_list:
if key in my_dict:
my_dict[key] += val
else:
my_dict[key] = val
my_dict.items()
# Output: [('A', 150), ('C', 10), ('B', 70)]
</code></pre>
| 0 |
2016-09-27T21:32:08Z
|
[
"python",
"list",
"tuples"
] |
Sum numbers by letter in list of tuples
| 39,734,549 |
<p>I have a list of tuples: </p>
<pre><code>[ ('A',100), ('B',50), ('A',50), ('B',20), ('C',10) ]
</code></pre>
<p>I am trying to sum up all numbers that have the same letter. I.e. I want to output </p>
<pre><code>[('A', 150), ('B', 70), ('C',10)]
</code></pre>
<p>I have tried using set to get the unique values but then when I try and compare the first elements to the set I get </p>
<pre><code>TypeError: unsupported operand type(s) for +: 'int' and 'str'
</code></pre>
<p>Any quick solutions to match the numbers by letter?</p>
| 1 |
2016-09-27T21:25:12Z
| 39,734,640 |
<p>How about this: (assuming <code>a</code> is the name of the tuple you have provided)</p>
<pre><code>letters_to_numbers = {}
for i in a:
if i[0] in letters_to_numbers:
letters_to_numbers[i[0]] += i[1]
else:
letters_to_numbers[i[0]] = i[1]
b = letters_to_numbers.items()
</code></pre>
<p>The elements of the resulting tuple <code>b</code> will be in no particular order.</p>
| 0 |
2016-09-27T21:32:17Z
|
[
"python",
"list",
"tuples"
] |
Sum numbers by letter in list of tuples
| 39,734,549 |
<p>I have a list of tuples: </p>
<pre><code>[ ('A',100), ('B',50), ('A',50), ('B',20), ('C',10) ]
</code></pre>
<p>I am trying to sum up all numbers that have the same letter. I.e. I want to output </p>
<pre><code>[('A', 150), ('B', 70), ('C',10)]
</code></pre>
<p>I have tried using set to get the unique values but then when I try and compare the first elements to the set I get </p>
<pre><code>TypeError: unsupported operand type(s) for +: 'int' and 'str'
</code></pre>
<p>Any quick solutions to match the numbers by letter?</p>
| 1 |
2016-09-27T21:25:12Z
| 39,734,647 |
<p>Here is a one(and a half?)-liner: group by letter (for which you need to sort before), then take the sum of the second entries of your tuples.</p>
<pre><code>from itertools import groupby
from operator import itemgetter
data = [('A', 100), ('B', 50), ('A', 50), ('B', 20), ('C', 10)]
res = [(k, sum(map(itemgetter(1), g)))
for k, g in groupby(sorted(data, key=itemgetter(0)), key=itemgetter(0))]
print(res)
// => [('A', 150), ('B', 70), ('C', 10)]
</code></pre>
<p>The above is O(n log n) — sorting is the most expensive operation. If your input list is truly large, you might be better served by the following O(n) approach:</p>
<pre><code>from collections import defaultdict
data = [('A', 100), ('B', 50), ('A', 50), ('B', 20), ('C', 10)]
d = defaultdict(int)
for letter, value in data:
d[letter] += value
res = list(d.items())
print(res)
// => [('B', 70), ('C', 10), ('A', 150)]
</code></pre>
| 0 |
2016-09-27T21:32:49Z
|
[
"python",
"list",
"tuples"
] |
Sum numbers by letter in list of tuples
| 39,734,549 |
<p>I have a list of tuples: </p>
<pre><code>[ ('A',100), ('B',50), ('A',50), ('B',20), ('C',10) ]
</code></pre>
<p>I am trying to sum up all numbers that have the same letter. I.e. I want to output </p>
<pre><code>[('A', 150), ('B', 70), ('C',10)]
</code></pre>
<p>I have tried using set to get the unique values but then when I try and compare the first elements to the set I get </p>
<pre><code>TypeError: unsupported operand type(s) for +: 'int' and 'str'
</code></pre>
<p>Any quick solutions to match the numbers by letter?</p>
| 1 |
2016-09-27T21:25:12Z
| 39,734,656 |
<p>What is generating the list of tuples? Is it you? If so, why not try a defaultdict(list) to append the values to the right letter at the time of making the list of tuples. Then you can simply sum them. See example below. </p>
<pre><code>>>> from collections import defaultdict
>>> val_store = defaultdict(list)
>>> # next lines are me simulating the creation of the tuple
>>> val_store['A'].append(10)
>>> val_store['B'].append(20)
>>> val_store['C'].append(30)
>>> val_store
defaultdict(<class 'list'>, {'C': [30], 'A': [10], 'B': [20]})
>>> val_store['A'].append(10)
>>> val_store['C'].append(30)
>>> val_store['B'].append(20)
>>> val_store
defaultdict(<class 'list'>, {'C': [30, 30], 'A': [10, 10], 'B': [20, 20]})
>>> for val in val_store:
... print(val, sum(val_store[val]))
...
C 60
A 20
B 40
</code></pre>
| 0 |
2016-09-27T21:33:42Z
|
[
"python",
"list",
"tuples"
] |
Sum numbers by letter in list of tuples
| 39,734,549 |
<p>I have a list of tuples: </p>
<pre><code>[ ('A',100), ('B',50), ('A',50), ('B',20), ('C',10) ]
</code></pre>
<p>I am trying to sum up all numbers that have the same letter. I.e. I want to output </p>
<pre><code>[('A', 150), ('B', 70), ('C',10)]
</code></pre>
<p>I have tried using set to get the unique values but then when I try and compare the first elements to the set I get </p>
<pre><code>TypeError: unsupported operand type(s) for +: 'int' and 'str'
</code></pre>
<p>Any quick solutions to match the numbers by letter?</p>
| 1 |
2016-09-27T21:25:12Z
| 39,734,663 |
<p>Try this:</p>
<pre><code>a = [('A',100), ('B',50), ('A',50), ('B',20), ('C',10) ]
letters = set([s[0] for s in a])
new_a = []
for l in letters:
nums = [s[1] for s in a if s[0] == l]
new_a.append((l, sum(nums)))
print new_a
</code></pre>
<p>Results:</p>
<pre><code>[('A', 150), ('C', 10), ('B', 70)]
</code></pre>
| -1 |
2016-09-27T21:33:58Z
|
[
"python",
"list",
"tuples"
] |
Sum numbers by letter in list of tuples
| 39,734,549 |
<p>I have a list of tuples: </p>
<pre><code>[ ('A',100), ('B',50), ('A',50), ('B',20), ('C',10) ]
</code></pre>
<p>I am trying to sum up all numbers that have the same letter. I.e. I want to output </p>
<pre><code>[('A', 150), ('B', 70), ('C',10)]
</code></pre>
<p>I have tried using set to get the unique values but then when I try and compare the first elements to the set I get </p>
<pre><code>TypeError: unsupported operand type(s) for +: 'int' and 'str'
</code></pre>
<p>Any quick solutions to match the numbers by letter?</p>
| 1 |
2016-09-27T21:25:12Z
| 39,734,681 |
<p>A simpler approach</p>
<pre><code>x = [('A',100),('B',50),('A',50),('B',20),('C',10)]
y = {}
for _tuple in x:
if _tuple[0] in y:
y[_tuple[0]] += _tuple[1]
else:
y[_tuple[0]] = _tuple[1]
print [(k,v) for k,v in y.iteritems()]
</code></pre>
| -1 |
2016-09-27T21:35:31Z
|
[
"python",
"list",
"tuples"
] |
Sum numbers by letter in list of tuples
| 39,734,549 |
<p>I have a list of tuples: </p>
<pre><code>[ ('A',100), ('B',50), ('A',50), ('B',20), ('C',10) ]
</code></pre>
<p>I am trying to sum up all numbers that have the same letter. I.e. I want to output </p>
<pre><code>[('A', 150), ('B', 70), ('C',10)]
</code></pre>
<p>I have tried using set to get the unique values but then when I try and compare the first elements to the set I get </p>
<pre><code>TypeError: unsupported operand type(s) for +: 'int' and 'str'
</code></pre>
<p>Any quick solutions to match the numbers by letter?</p>
| 1 |
2016-09-27T21:25:12Z
| 39,734,696 |
<p>A one liner:</p>
<pre><code>>>> x = [ ('A',100), ('B',50), ('A',50), ('B',20), ('C',10) ]
>>> {
... k: reduce(lambda u, v: u + v, [y[1] for y in x if y[0] == k])
... for k in [y[0] for y in x]
... }.items()
[('A', 150), ('C', 10), ('B', 70)]
</code></pre>
| -1 |
2016-09-27T21:36:12Z
|
[
"python",
"list",
"tuples"
] |
Sum numbers by letter in list of tuples
| 39,734,549 |
<p>I have a list of tuples: </p>
<pre><code>[ ('A',100), ('B',50), ('A',50), ('B',20), ('C',10) ]
</code></pre>
<p>I am trying to sum up all numbers that have the same letter. I.e. I want to output </p>
<pre><code>[('A', 150), ('B', 70), ('C',10)]
</code></pre>
<p>I have tried using set to get the unique values but then when I try and compare the first elements to the set I get </p>
<pre><code>TypeError: unsupported operand type(s) for +: 'int' and 'str'
</code></pre>
<p>Any quick solutions to match the numbers by letter?</p>
| 1 |
2016-09-27T21:25:12Z
| 39,740,468 |
<pre><code>>>> from collections import Counter
>>> c = Counter()
>>> for k, num in items:
c[k] += num
>>> c.items()
[('A', 150), ('C', 10), ('B', 70)]
</code></pre>
<p>Less efficient (but nicer looking) one liner version:</p>
<pre><code>>>> Counter(k for k, num in items for i in range(num)).items()
[('A', 150), ('C', 10), ('B', 70)]
</code></pre>
| -1 |
2016-09-28T07:13:49Z
|
[
"python",
"list",
"tuples"
] |
parse html tables with lxml
| 39,734,584 |
<p>I have been trying to parse the table contents from <a href="https://nseindia.com/products/content/derivatives/equities/fo_underlying_home.htm" rel="nofollow">here</a>
i have tried a couple of alternatives, like </p>
<pre><code>xpath('//table//tr/td//text()')
xpath('//div[@id="replacetext"]/table/tbody//tr/td/a//text()')
</code></pre>
<p>here is my last code:</p>
<pre><code>import requests, lxml.html
url ='https://nseindia.com/products/content/derivatives/equities/fo_underlying_home.htm'
url = requests.get(url)
html = lxml.html.fromstring(url.content)
packages = html.xpath('//div[@id="replacetext"]/table/tbody//tr/td/a//text()') # get the text inside all "<tr><td><a ...>text</a></td></tr>"
</code></pre>
<p>however none of the alternatives seems to be working. In the past, i have scraped data with similar code (although not from this url!). Any guidance will be really helpful.</p>
| -1 |
2016-09-27T21:27:55Z
| 39,734,743 |
<p>In the HTML page, there is a namespace:</p>
<pre><code><html xmlns="http://www.w3.org/1999/xhtml">
</code></pre>
<p>So, you need to specify it:</p>
<pre><code>NSMAP = {'html' : "http://www.w3.org/1999/xhtml"}
path = '//html:div[@id="replacetext"]/html:table/html:tbody//html:tr/html:td/html:a//text()'
packages = html.xpath(path, namespaces=NSMAP)
</code></pre>
<p>See <a href="http://lxml.de/xpathxslt.html#namespaces-and-prefixes" rel="nofollow">http://lxml.de/xpathxslt.html#namespaces-and-prefixes</a></p>
<h2>Interpreting Ajax call</h2>
<pre><code>import requests
from lxml import html
base_url = 'https://nseindia.com'
# sumulate the JavaScript
url = base_url + "/products/content/derivatives/equities/fo_underlyinglist.htm"
url = requests.get(url)
content = url.content
# -> <table>
# <tr><th>S. No.</td>
# <th>Underlying</td>
# <th>Symbol</th></tr>
# <tr>
# <td style='text-align: right;' >1</td>
# <td class="normalText" ><a href=fo_INDIAVIX.htm>INDIA VIX</a></td>
# <td class="normalText" ><a href="/products/dynaContent/derivatives/equities/fomwatchsymbol.jsp?key=INDIAVIX">INDIAVIX</a></td>
# </tr>
# ...
html = html.fromstring(content)
packages = html.xpath('//td/a//text()')
# -> ['INDIA VIX',
# 'INDIAVIX',
# 'Nifty 50',
# 'NIFTY',
# 'Nifty IT',
# 'NIFTYIT',
# 'Nifty Bank',
# 'BANKNIFTY',
# 'Nifty Midcap 50',
</code></pre>
| 0 |
2016-09-27T21:39:57Z
|
[
"python",
"parsing",
"lxml"
] |
parse html tables with lxml
| 39,734,584 |
<p>I have been trying to parse the table contents from <a href="https://nseindia.com/products/content/derivatives/equities/fo_underlying_home.htm" rel="nofollow">here</a>
i have tried a couple of alternatives, like </p>
<pre><code>xpath('//table//tr/td//text()')
xpath('//div[@id="replacetext"]/table/tbody//tr/td/a//text()')
</code></pre>
<p>here is my last code:</p>
<pre><code>import requests, lxml.html
url ='https://nseindia.com/products/content/derivatives/equities/fo_underlying_home.htm'
url = requests.get(url)
html = lxml.html.fromstring(url.content)
packages = html.xpath('//div[@id="replacetext"]/table/tbody//tr/td/a//text()') # get the text inside all "<tr><td><a ...>text</a></td></tr>"
</code></pre>
<p>however none of the alternatives seems to be working. In the past, i have scraped data with similar code (although not from this url!). Any guidance will be really helpful.</p>
| -1 |
2016-09-27T21:27:55Z
| 39,735,268 |
<p>I tried you code. The problem is not caused by <code>lxml</code>. It is caused by how you load the webpage.</p>
<p>I know that you use the <code>requests</code> to get the content of webpage, however, the content you get from <code>requests</code> may be different from the content you see in the browser.</p>
<p>In this page, '<a href="https://nseindia.com/products/content/derivatives/equities/fo_underlying_home.htm" rel="nofollow">https://nseindia.com/products/content/derivatives/equities/fo_underlying_home.htm</a>', print the content of <code>request.get</code>, you will find that the source code of this page contains no table!!! The table is loaded by <code>ajax</code> query.</p>
<p>So find a way to load the 'really' page you want, the you can use 'lxml`.</p>
<p>By the way, in web scraping, there are also something you need to mention, for example, <code>request headers</code>. It's a good practice to set your request headers when you do the http request. Some sites may block you, if you do not provide a reasonable <code>User-Agent</code> in the header. Though there is nothing to do with your current problem.</p>
<p>Thanks.</p>
| 0 |
2016-09-27T22:25:24Z
|
[
"python",
"parsing",
"lxml"
] |
Is there an equivalent to the C++ pre/postfix operators for use in Python list comprehensions?
| 39,734,722 |
<p>I writing a function which populates a list of lists of two elements, where the first element is an element from a different list and the second element is a value which increments.</p>
<pre><code>def list_of_pairs(seq, start):
""" Returns a list of pairs """
>>> list_of_pairs([3, 2, 1], 1)
[ [3, 1], [2, 2], [1, 3] ]
return [[i, start++] for i in seq]
</code></pre>
<p>Is there an equivalent to the C++ postfix operators which can be used? Thanks!</p>
<p>Bonus question: Is it more Pythonic to use the list constructor, than to construct the list using square brackets? </p>
<p>Edit: Here is my current (less beautiful) workaround -</p>
<pre><code>def list_of_pairs(seq, start):
""" Returns a list of pairs """
>>> list_of_pairs([3, 2, 1], 1)
[ [3, 1], [2, 2], [1, 3] ]
return [[seq[i], start+i] for i in range(len(seq))]
</code></pre>
| 0 |
2016-09-27T21:38:09Z
| 39,734,752 |
<p>You can achieve the same with <a href="https://docs.python.org/2/library/itertools.html#itertools.count" rel="nofollow"><code>itertools.count</code></a>, calling <code>next</code> on the <code>count</code> object for each element of the sequence:</p>
<pre><code>from itertools import count
c = count(start)
lst = [[x, next(c)] for x in seq]
</code></pre>
<blockquote>
<p>construct the list using square brackets</p>
</blockquote>
<p>That's a <em>list comprehension</em>. It's pretty standard and most certainly Pythonic to use list comprehensions for creating lists.</p>
| 2 |
2016-09-27T21:40:39Z
|
[
"python",
"list"
] |
Is there an equivalent to the C++ pre/postfix operators for use in Python list comprehensions?
| 39,734,722 |
<p>I writing a function which populates a list of lists of two elements, where the first element is an element from a different list and the second element is a value which increments.</p>
<pre><code>def list_of_pairs(seq, start):
""" Returns a list of pairs """
>>> list_of_pairs([3, 2, 1], 1)
[ [3, 1], [2, 2], [1, 3] ]
return [[i, start++] for i in seq]
</code></pre>
<p>Is there an equivalent to the C++ postfix operators which can be used? Thanks!</p>
<p>Bonus question: Is it more Pythonic to use the list constructor, than to construct the list using square brackets? </p>
<p>Edit: Here is my current (less beautiful) workaround -</p>
<pre><code>def list_of_pairs(seq, start):
""" Returns a list of pairs """
>>> list_of_pairs([3, 2, 1], 1)
[ [3, 1], [2, 2], [1, 3] ]
return [[seq[i], start+i] for i in range(len(seq))]
</code></pre>
| 0 |
2016-09-27T21:38:09Z
| 39,734,802 |
<p>You may use <a href="https://docs.python.org/2/library/functions.html#enumerate" rel="nofollow"><code>enumerate()</code></a> to achieve this. Enumerate return the index along with value while iterating over the list of values. And as per your requirement, you need list of <code>list</code> as <code>[val, index + count]</code>. Below is the sample code to achieve that:</p>
<pre><code>>>> seq = [2, 6, 9]
>>> count = 2
>>> [[val, count+i] for i, val in enumerate(seq)]
[[2, 2], [6, 3], [9, 4]]
</code></pre>
| 2 |
2016-09-27T21:44:45Z
|
[
"python",
"list"
] |
Is there an equivalent to the C++ pre/postfix operators for use in Python list comprehensions?
| 39,734,722 |
<p>I writing a function which populates a list of lists of two elements, where the first element is an element from a different list and the second element is a value which increments.</p>
<pre><code>def list_of_pairs(seq, start):
""" Returns a list of pairs """
>>> list_of_pairs([3, 2, 1], 1)
[ [3, 1], [2, 2], [1, 3] ]
return [[i, start++] for i in seq]
</code></pre>
<p>Is there an equivalent to the C++ postfix operators which can be used? Thanks!</p>
<p>Bonus question: Is it more Pythonic to use the list constructor, than to construct the list using square brackets? </p>
<p>Edit: Here is my current (less beautiful) workaround -</p>
<pre><code>def list_of_pairs(seq, start):
""" Returns a list of pairs """
>>> list_of_pairs([3, 2, 1], 1)
[ [3, 1], [2, 2], [1, 3] ]
return [[seq[i], start+i] for i in range(len(seq))]
</code></pre>
| 0 |
2016-09-27T21:38:09Z
| 39,734,834 |
<p><code>++</code> and <code>--</code> have been deliberately excluded from Python, because using them in expressions tends to lead to confusing code and off-by-one errors.</p>
<p>You should use <a href="https://docs.python.org/3/library/functions.html#enumerate" rel="nofollow"><code>enumerate</code></a> instead:</p>
<pre><code>def list_of_pairs(seq, start):
return [[elem, i] for i, elem in enumerate(seq, start)]
</code></pre>
| 1 |
2016-09-27T21:46:36Z
|
[
"python",
"list"
] |
Python - Switch translations dynamically in a PyQt4 application
| 39,734,775 |
<p>I want to add a feature in my program. The user should be able to switch/change the language at runtime - without restart. Imagine the UI displays in English and he wants to switch in German.</p>
<p>Well, I wrote a small example - can't be executed, because you have missing some translation-files and ui-files. But I need your help - for logical. Here is my current code.</p>
<pre><code>import sys
from PyQt4.uic import loadUi
from PyQt4.QtCore import Qt, QFile, QMetaObject
from PyQt4 import QtCore
from PyQt4.QtGui import QMainWindow, QApplication
class Test_Window(QMainWindow):
def __init__(self,
app):
QMainWindow.__init__(self, parent=None)
UI_PATH = QFile("testlangs.ui")
# save reference to app for later
self._app = app
# Load ui dynamically
UI_PATH.open(QFile.ReadOnly)
self.ui = loadUi(UI_PATH, self)
UI_PATH.close()
self.init_current_language()
self.init_connect_menu_item()
def init_current_language(self):
self.current_translator = QtCore.QTranslator(self._app)
self.current_translator.load("langs_en")
self._app.installTranslator(self.current_translator)
def init_connect_menu_item(self):
self.actionDeutsch.triggered.connect(lambda: self.change_language("langs_de"))
self.actionEnglish.triggered.connect(lambda: self.change_language("langs_en"))
# Change the language to German
def change_language(self, language):
self._app.removeTranslator(self.current_translator)
self.current_translator = QtCore.QTranslator(self._app)
self.current_translator.load(language)
self._app.installTranslator(self.current_translator)
self.retranslateUi(self.ui)
</code></pre>
<p>Now, I have some problem:</p>
<p>First of all: I can't call and execute the <strong>retranslateUi()</strong>-method. The "problem" is I load the ui-file at runtime dynamically. And this method is a part of generated ui-file. That means, the ui-file is converted in py-file. And there you will finde the <strong>retranslateUi()</strong>-method.</p>
<p>What can i do?</p>
<p>Simple and dirty way looks like:</p>
<pre><code>def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(self._app.translate("MainWindow", "MainWindow", None, self._app.UnicodeUTF8))
self.nameLabel.setText(self._app.translate("MainWindow", "Name", None, self._app.UnicodeUTF8))
self.ageLabel.setText(self._app.translate("MainWindow", "Age", None, self._app.UnicodeUTF8))
self.menuMenu.setTitle(self._app.translate("MainWindow", "File", None, self._app.UnicodeUTF8))
self.menuEdit.setTitle(self._app.translate("MainWindow", "Edit", None, self._app.UnicodeUTF8))
self.menuLanguage.setTitle(self._app.translate("MainWindow", "Language", None, self._app.UnicodeUTF8))
self.actionOpen.setText(self._app.translate("MainWindow", "Open", None, self._app.UnicodeUTF8))
self.actionSave.setText(self._app.translate("MainWindow", "Save", None, self._app.UnicodeUTF8))
self.actionClear.setText(self._app.translate("MainWindow", "Clear", None, self._app.UnicodeUTF8))
self.actionEnglish.setText(self._app.translate("MainWindow", "English", None, self._app.UnicodeUTF8))
self.actionDeutsch.setText(self._app.translate("MainWindow", "Deutsch", None, self._app.UnicodeUTF8))
</code></pre>
<p>I re-implement the missing method by copying this method from a generated ui. This dirty way works fine, but I think this isn't elegant solution.</p>
<p>There a any other and elegant ways to solve it? </p>
| 1 |
2016-09-27T21:42:15Z
| 39,735,770 |
<p>Use <a href="http://pyqt.sourceforge.net/Docs/PyQt4/designer.html#PyQt4.uic.loadUiType" rel="nofollow">loadUiType</a> to load the ui file, which will give you the base-class and the ui-class needed for creating a subclass. As with your previous approach, this will result in all the child widgets becoming attributes of the main window, and you will also be able to call <code>self.retranslateUi(self)</code>:</p>
<pre><code>from PyQt4.uic import loadUiType
UiClass, BaseClass = loadUiType('testlangs.ui')
class Test_Window(BaseClass, UiClass):
def __init__(self, app):
super(Test_Window, self).__init__(parent=None)
self.setupUi(self)
# save reference to app for later
self._app = app
self.init_current_language()
self.init_connect_menu_item()
</code></pre>
| 1 |
2016-09-27T23:21:32Z
|
[
"python",
"pyqt4",
"translation"
] |
Drawing a polygon in Python with a set of random colors
| 39,734,780 |
<p>I am working on a simple python program which prompts the user to enter the length of the side of a polygon and the program (using turtle) will draw the polygon with a random color that has been set using the random.randint</p>
<p>my code so far is:</p>
<pre><code>import turtle
polygonSideLength = int(input('Enter length of polygon side: \n'))
numberOfSides = 5 + (7 / 4)
turnAngle = 360 / numberOfSides
import random
randomColor = random.randint(0,5)
if randomColor == 0:
fillcolor="red"
elif randomColor == 1:
fillcolor="green"
elif randomColor == 2:
fillcolor="blue"
elif randomColor == 3:
fillcolor="cyan"
elif randomColor == 4:
fillcolor="magenta"
elif randomColor == 5:
fillcolor="yellow"
turtle.begin_fill()
turtle.pen(pensize = 5, pencolor="black", fillcolor = randomColor)
for i in range(numberOfSides):
turtle.forward(polygonSideLength)
turtle.right(turnAngle)
turtle.end_fill()
turtle.done()
</code></pre>
<p>I have found the problem in the code is with the "fillcolor = randomColor"</p>
<p>the error I receive is "unknown color name for: 5"
I know the randint is working because sometimes the error gives me 1,2,3,4,5</p>
<p>So to sum it up, how do I get the fillcolor to match the set colors in the random randint?</p>
| 0 |
2016-09-27T21:42:42Z
| 39,735,132 |
<p>I am agree with the fact that you are choosing a random color with</p>
<pre><code>randomColor = random.randint(0,5)
</code></pre>
<p>but when you want to set the random color to your polygon</p>
<p>you specify an integer (value of randomColor variable) instead of a string (value of fillcolor variable)</p>
<p>fillcolor variable is expected to be a string type with a color name value ( "blue","white","red", etc) but never an integer.</p>
<p>so may you please change the following line:</p>
<pre><code>turtle.pen(pensize = 5, pencolor="black", fillcolor = randomColor)
</code></pre>
<p>to</p>
<pre><code>turtle.pen(pensize = 5, pencolor="black", fillcolor = fillcolor)
</code></pre>
| 0 |
2016-09-27T22:10:08Z
|
[
"python"
] |
Return value in generator function Python 2
| 39,734,786 |
<p>I'm wondering how I can write a generator function that also has the option to return a value. In Python 2, you get the following error message if a generator function tries to return a value. <code>SyntaxError: 'return' with argument inside generator</code></p>
<p>Is it possible to write a function where I specify if I want to receive a generator or not?</p>
<p>For example:</p>
<pre><code>def f(generator=False):
if generator:
yield 3
else:
return 3
</code></pre>
| 0 |
2016-09-27T21:43:01Z
| 39,735,017 |
<p>Mandatory reading: <a href="http://stackoverflow.com/questions/1756096/understanding-generators-in-python">Understanding Generators in Python</a></p>
<p>Key information: </p>
<blockquote>
<p><code>yield</code> anywhere in a function makes it a generator.</p>
</blockquote>
<p>Function is marked as generator when code is parsed. Therefore, it's impossible to toggle function behavior (generator / not generator) based on argument passed in runtime.</p>
| 4 |
2016-09-27T22:01:12Z
|
[
"python"
] |
Join Python dataframe time series efficiently
| 39,734,836 |
<p>I have the following 2 dataframes with:</p>
<pre><code>day
date val
11740 2016-01-04 1.3970
11741 2016-01-05 1.3991
11742 2016-01-06 1.4084
11743 2016-01-07 1.4061
</code></pre>
<p>and</p>
<pre><code>df
Adj_Close Close Date High Low
182 12927.200195 12927.200195 2016-01-04 12928.900391 12748.50
181 12920.099609 12920.099609 2016-01-05 12954.900391 12839.799805
180 12726.799805 12726.799805 2016-01-06 12854.599609 12701.700195
179 12448.200195 12448.200195 2016-01-07 12661.200195 12439.099609
</code></pre>
<p>I have a cheesy loop to aligh the date to create a new dataframe (new_df) by 'joining' the common date. </p>
<pre><code>new_df = pd.DataFrame(columns=['date', 'close', 'fx', 'usd'])
for indexFx, rowFx in day.iterrows():
for indexSt, rowSt in df.iterrows(): #this is not efficient
fxDate = str(rowFx.date)[:10] #only keep data component not time
if str(rowSt['Date']) == fxDate:
dateObj = datetime.strptime(rowSt.Date,'%Y-%m-%d')
row = [dateObj, rowSt.Close,rowFx.val, float(rowSt.Close) * float(rowFx.val)]
new_df.loc[len(new_df)] = row
</code></pre>
<p>I know there is an efficient way to Pythonize this loop. Can someone help? </p>
<p>Thanks </p>
| 2 |
2016-09-27T21:46:38Z
| 39,735,030 |
<pre><code>pd.concat([day.set_index('date'), df.set_index('Date')], axis=1)
>>>
val Adj_Close Close High \
2016-01-04 1.3970 12927.200195 12927.200195 12928.900391
2016-01-05 1.3991 12920.099609 12920.099609 12954.900391
2016-01-06 1.4084 12726.799805 12726.799805 12854.599609
2016-01-07 1.4061 12448.200195 12448.200195 12661.200195
Low
2016-01-04 12748.500000
2016-01-05 12839.799805
2016-01-06 12701.700195
2016-01-07 12439.099609
</code></pre>
<p>Depending on if you want an inner or outer join, you can specify that with <code>join='inner'</code> or <code>join='outer'</code>.</p>
| 1 |
2016-09-27T22:02:09Z
|
[
"python",
"pandas",
"dataframe",
"time-series"
] |
Having output issues with python; loop totals and averages
| 39,734,909 |
<p>Having a few output issues with my nested loop, normally I use <code>break</code> to add some lines into my code or <code>print()</code></p>
<p>When I use <code>print()</code> within my code my output looks like I am typing totals on a new line all together that is not what I want</p>
<p>Following is a picture of my current output and where I need a blank line;</p>
<p><a href="http://i.stack.imgur.com/q77bU.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/q77bU.jpg" alt="enter image description here"></a></p>
<p>Second thing:</p>
<p>My code is not calculating the information correctly to find the total and average rainfall per month.</p>
<p>code follows</p>
<pre><code>def main():
#define accumulators
monthRain = 0
year = 0
monthTotal = 0
months = 0
total = 0
#get # of years
year = int(input("Enter the number of years to collect data for: "))
#blank line
print()
#define month total befor it is changed below with year + 1
monthTotal = year * 12
#define how many months per year
months = 12
#Find average rainfall per month
for year in range(year):
#accumulator for rain per month
total = 0
#get rainfall per month
print('Next you will enter 12 months of rainfall data for year', year + 1)
for month in range(months):
print("Enter the rainfall for month", month + 1, end='')
monthRain = float(input(': '))
#add monthly raingfall to accumulator
total += monthRain
average = total / monthTotal
#total months of data
print('You have entered data for', monthTotal,'months')
#blank line
print()
#total rainfall
print('The total rainfall for the collected months is:', total)
print('The average monthly rainfall for the collected months is:', average)
main()
</code></pre>
| 1 |
2016-09-27T21:52:56Z
| 39,735,038 |
<blockquote>
<p><em>Following is a picture of my current output and where I need a blank line</em></p>
</blockquote>
<p>In order to get a blank line before <code>You have entered data for</code>, add <code>\n</code> at the start of the string. It represents new line. Hence your print statement should be as:</p>
<pre><code>print("\nYou have entered data for")
</code></pre>
<blockquote>
<p><em>my code is not calculating the information correctly to find the total and average rainfall per month.</em></p>
</blockquote>
<p>On dividing two <code>int</code> values, python returns <code>int</code> as by default excluding the float precision. In order to get the <code>float</code> value, conver either of numerator or denomenator to <code>float</code>. Example:</p>
<pre><code>>>> 1/5
0 # <-- Ignored float value as between two int
>>> 1/float(5)
0.2 #<-- Float value to conversion of denomenator to float
</code></pre>
<p>Also, in <code>average = total / monthTotal</code>, I believe that the <code>average</code> is need for per month basis. It should be <code>month</code> instead of <code>monthTotal</code>. Because <code>total</code> will be having the sum of rain for <code>month</code> months. In order to get average of rain in <code>month</code> months, your equation should be:</p>
<pre><code>average = total / float(month)
</code></pre>
| 0 |
2016-09-27T22:02:55Z
|
[
"python",
"loops",
"nested"
] |
Validating where the "@" symbol is in an email. Not validation of the email itself
| 39,734,943 |
<p>"it must contain an â@â symbol
which is NEITHER the first character nor the last character in the string."</p>
<p>So I have this assignment in my class and I can't for the life of me figure out how to make the boolean false for having it at the front or end of the email. This is what I have so far.</p>
<pre><code>def validEmail1(myString):
for i in myString:
if i == "@":
return True
else:
return False
</code></pre>
| 0 |
2016-09-27T21:55:22Z
| 39,735,142 |
<p>With <code>s</code> as your string, you can do:</p>
<pre><code>not (s.endswith('@') or s.startswith('@')) and s.count('@')==1
</code></pre>
<p>Test:</p>
<pre><code>def valid(s):
return not (s.endswith('@') or s.startswith('@')) and s.count('@')==1
cases=('@abc','abc@','abc@def', 'abc@@def')
for case in cases:
print(case, valid(case))
</code></pre>
<p>Prints:</p>
<pre><code>@abc False
abc@ False
abc@def True
abc@@def False
</code></pre>
<hr>
<p>You can also use a slice, but you also need to make sure (indirectly) that the string does not start or end with <code>'@'</code> by making sure the count is 1:</p>
<pre><code>def valid(s):
return '@' in s[1:-1] and s.count('@')==1
</code></pre>
| 2 |
2016-09-27T22:11:22Z
|
[
"python",
"python-3.x",
"character",
"email-validation"
] |
python, smart way of storing repeating entries
| 39,734,944 |
<p>I've log files containing all sort of junk as well as useful data.
I'm extracting some information by matching certain patterns and able to get in following format while reading the file line by line in python and applying some if statements </p>
<pre><code>job id: job#33ABC
Bin 1:30.86
Bin2: 30.86
job id: job#44BC
Bin1: 27.22
Bin2: 8.53
Bin3: 35.75
job id: job#65A
Bin2: 17.135075
Bin4: 17.135120
job id: job#P17
Bin 3: 7.328211
Bin 4: 15.918724
</code></pre>
<p>Now the issue is the same log set repeats with same job ids (with different values)</p>
<pre><code>job id: job#33ABC
Bin1: 99
Bin2: 1099
...
...
...
</code></pre>
<p>If there is some smart way of writing in a file/csv in a tabular format such that by only looking at job_id, it presents all Bin1, Bin2 jobs per set, Right now it is basically lot of duplication, same job comes again with a different set of values like job#33ABC keep coming 10,11 times with different values</p>
<pre><code>job_id bin 1, bin2, bin3,bin4
set#1 set #2 set #3
job#33ABC 30.86, 30.86, 0, 0 30.86, 30.86, 0,0
job#44BC 27.22, 8.53, 35.75, 0 0,0,0,34.56
....
...
</code></pre>
<p>I'm reading that log line by line</p>
<pre><code> for line in input_file:
if job_name in line:
<extract job_name logic>
print job_name[0]
if 'bin1 matches'
bin1[0]=<all logic>
print "bin1",
bin1[0]
..
...
</code></pre>
<p>UPDATE
I tried using a dictionary like</p>
<pre><code>records{}
for line in input_file:
if job_name in line:
<extract job_name logic>
print job_name[0]
if 'bin1 matches'
bin1[0]=<all logic>
print "bin1",
bin1[0]
records[job_name[0]]=records.get(job_name[0],[])+[bin1[0]]
if 'bin2 matches'
...
..
records[job_name[0]]=records.get(job_name[0],[])+[bin2[0]]
for key, value in records.items():
writer.writerow([key, value])
</code></pre>
<p>but it is presenting in following format;</p>
<pre><code> 33ABC, " ['30.86','30.86','99.0','1099' ]
</code></pre>
<p>My question is how can i identify and present like
33ABC, " ['30.86','30.86',,'99.0','1099',, ] Since there has to be 4 job bins, right now it is taking all values as one large list, instead of breaking into 4, 4 bins or is there any way of doing that in current logic?</p>
| 1 |
2016-09-27T21:55:25Z
| 39,735,571 |
<p>Putting the issue of IO aside, you could use a <a href="https://docs.python.org/3/library/collections.html#defaultdict-objects" rel="nofollow"><code>defaultdict</code></a> for easy logistics. Or a <code>defaultdict</code> of <code>defaultdict</code>s to be precise.</p>
<p>Your outer dict can have keys corresponding to job names. The value for each job name is a dict itself, with keys corresponding to bin names. So for each job name and key name you try to append an element to the value of the inner dict. If the bin had come up by then, the value gets appended. If the bin is new, the default empty list is used, and the first value is appended (<code>defaultdict</code>s are only needed to avoid testing for existing keys all the time):</p>
<pre><code>from collections import defaultdict
logs = defaultdict(lambda: defaultdict(list))
# simulate the following input stream:
#
# job1:
# bin1: val1
# bin1: val2
# bin2: val3
#
# job2:
# bin2: val4
#
# job1:
# bin1: val5
logs['job1']['bin1'].append('val1')
logs['job1']['bin1'].append('val2')
logs['job1']['bin2'].append('val3')
logs['job2']['bin2'].append('val4')
logs['job1']['bin1'].append('val5')
# see what we've got, converted to a non-default dict for prettiness
print({k:dict(logs[k]) for k in logs})
</code></pre>
<p>This will return</p>
<pre><code>{'job1': {'bin1': ['val1', 'val2', 'val5'], 'bin2': ['val3']}, 'job2': {'bin2': ['val4']}}
</code></pre>
<p>You can see that values are collected across job and bin names. You can perform the writing according to your taste, but I don't think a CSV makes sense in this context. You probably have to use a printer of your own.</p>
<p>You just have to loop over <code>logs</code> first, this will give you the unique job names (the keys), then loop over each bin for the given job, then print the lists of values:</p>
<pre><code>for lkey in logs:
# lkey is a job name, logs[lkey] is a defaultdict
print(lkey)
for bkey in logs[lkey]:
# logs[lkey][bkey] is a list of values which you can print
print(bkey)
print(logs[lkey][bkey])
</code></pre>
<p>The output from the above is</p>
<pre><code>job1
bin1
['val1', 'val2', 'val5']
bin2
['val3']
job2
bin2
['val4']
</code></pre>
<p>which is what we'd expect.</p>
| 2 |
2016-09-27T22:55:15Z
|
[
"python",
"file",
"dictionary",
"text"
] |
Plotting the Degree Distribution in Python iGraph
| 39,734,974 |
<p>I want to plot the histogram of a degree distribution, but using the iGraph's plot() on the degree_distribution gives just that...a plot, but with no title, no labels, no nothing, like this:
<a href="http://i.stack.imgur.com/zC6tl.png" rel="nofollow"><img src="http://i.stack.imgur.com/zC6tl.png" alt="enter image description here"></a></p>
<p>How can I add annotations to this plot?</p>
| 0 |
2016-09-27T21:57:21Z
| 39,779,771 |
<p>Igraph is not meant to be a fully functional plotting library - the plot that it can generate for degree distributions is meant only for quock "eyeballing". Use a dedicated plotting library like matplotlib. The <code>bins()</code> method of the degree distribution object may be used to extract the bin counts of the histogram.</p>
| 0 |
2016-09-29T20:49:59Z
|
[
"python",
"plot",
"igraph",
"cairo"
] |
Pandas crosstab, but with values from aggregation of third column
| 39,735,068 |
<p>Here is my problem:</p>
<pre><code>df = pd.DataFrame({'A': ['one', 'one', 'two', 'two', 'one'] ,
'B': ['Ar', 'Br', 'Cr', 'Ar','Ar'] ,
'C': [1, 0, 0, 1,0 ]})
</code></pre>
<p>I would like to generate something like output of <code>pd.crosstab</code> function, but values on the intersection of column and row should come from aggregation of third column:</p>
<pre><code> Ar, Br, Cr
one 0.5 0 0
two 1 0 0
</code></pre>
<p>For example, there are two cases of 'one' and 'Ar' corresponding values in column 'C' are 1,0 we sum up values in column 'C' (0+1) and divide by number of values in column 'C', so we get (0+1)/2 =0.5. Whenever combination is not present we (like 'Cr' and 'one') we set it to zero. Any thoughts?</p>
| 3 |
2016-09-27T22:05:10Z
| 39,735,093 |
<p>you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.pivot_table.html" rel="nofollow">pivot_table()</a> method, which uses <code>aggfunc='mean'</code> per-default:</p>
<pre><code>In [46]: df.pivot_table(index='A', columns='B', values='C', fill_value=0)
Out[46]:
B Ar Br Cr
A
one 0.5 0 0
two 1.0 0 0
</code></pre>
| 3 |
2016-09-27T22:07:06Z
|
[
"python",
"pandas",
"aggregate"
] |
Pandas crosstab, but with values from aggregation of third column
| 39,735,068 |
<p>Here is my problem:</p>
<pre><code>df = pd.DataFrame({'A': ['one', 'one', 'two', 'two', 'one'] ,
'B': ['Ar', 'Br', 'Cr', 'Ar','Ar'] ,
'C': [1, 0, 0, 1,0 ]})
</code></pre>
<p>I would like to generate something like output of <code>pd.crosstab</code> function, but values on the intersection of column and row should come from aggregation of third column:</p>
<pre><code> Ar, Br, Cr
one 0.5 0 0
two 1 0 0
</code></pre>
<p>For example, there are two cases of 'one' and 'Ar' corresponding values in column 'C' are 1,0 we sum up values in column 'C' (0+1) and divide by number of values in column 'C', so we get (0+1)/2 =0.5. Whenever combination is not present we (like 'Cr' and 'one') we set it to zero. Any thoughts?</p>
| 3 |
2016-09-27T22:05:10Z
| 39,735,113 |
<p>I like <code>groupby</code> and <code>unstack</code></p>
<pre><code>df.groupby(['A', 'B']).C.mean().unstack(fill_value=0)
</code></pre>
<p><a href="http://i.stack.imgur.com/ek6hU.png" rel="nofollow"><img src="http://i.stack.imgur.com/ek6hU.png" alt="enter image description here"></a></p>
| 2 |
2016-09-27T22:08:45Z
|
[
"python",
"pandas",
"aggregate"
] |
How to make an image move diagonally in pygame
| 39,735,193 |
<p>I've been taught how to move an image in pygame left, right, up and down. Our next task is to make the image move diagonally, but I don't understand how. This is my code so far: (sorry for the weird names)
Oh and also, I have two images in my code. I was wondering if there was a way that I could move both images without one disappearing on the screen? For example, I can move one image using the arrow keys, but the other image will disappear. I can also move the other image using WASD, but the first image will disappear. Thank you so much!</p>
<pre><code>import pygame
#set up the initial pygame window
pygame.init()
screen = pygame.display.set_mode([900,600])
#set background color
background = pygame.Surface(screen.get_size())
background.fill([204,255,229])
screen.blit(background, (0,0))
#Pull in the image to the program
my_image = pygame.image.load("google_logo.png")
person = pygame.image.load("google_logo2.png")
#copy the image pixels to the screen
left_side = 50
height = 50
diagonal = 100
down_diagonal = 100
screen.blit(my_image, [left_side, height])
screen.blit (person, [diagonal, down_diagonal])
#Display changes
pygame.display.flip()
#set up pygame event loop
running = True
while running:
for event in pygame.event.get():
print event
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
print "QUITTING NOW..."
pygame.time.delay(2000)
running = False
if event.key == pygame.K_h:
print "HELLO!"
pygame.time.delay(2500)
running = False
if event.key == pygame.K_c:
print "To move the original Google logo, use the arrow keys. To move the second logo, use the WASD keys."
elif event.key == pygame.K_RIGHT:
screen.blit(background, (0,0))
left_side = left_side + 10
screen.blit(my_image, [left_side, height])
pygame.display.flip()
elif event.key == pygame.K_LEFT:
screen.blit(background, (0,0))
left_side = left_side - 10
screen.blit(my_image, [left_side, height])
pygame.display.flip()
elif event.key == pygame.K_UP:
screen.blit(background, (0,0))
height = height - 10
screen.blit(my_image, [left_side, height])
pygame.display.flip()
elif event.key == pygame.K_DOWN:
screen.blit(background, (0,0))
height = height + 10
screen.blit(my_image, [left_side, height])
pygame.display.flip()
elif event.key == pygame.K_w:
screen.blit(background, (0,0))
down_diagonal = down_diagonal - 10
screen.blit(person, [diagonal, down_diagonal])
pygame.display.flip()
elif event.key == pygame.K_a:
screen.blit(background, (0,0))
diagonal = diagonal - 10
screen.blit(person, [diagonal, down_diagonal])
pygame.display.flip()
elif event.key == pygame.K_s:
screen.blit(background, (0,0))
down_diagonal = down_diagonal + 10
screen.blit(person, [diagonal, down_diagonal])
pygame.display.flip()
elif event.key == pygame.K_d:
screen.blit(background, (0,0))
diagonal = diagonal + 10
screen.blit(person, [diagonal, down_diagonal])
pygame.display.flip()
pygame.quit()
</code></pre>
<p>EDIT: I've revised my code like you said, but it's still not quite working for me. (I apologize again for these questions as I am very new to Python) I would be eternally grateful for help.</p>
<pre><code>import pygame
#set up the initial pygame window
pygame.init()
screen = pygame.display.set_mode([900,600])
#set background color
background = pygame.Surface(screen.get_size())
background.fill([204,255,229])
screen.blit(background, (0,0))
#Pull in the image to the program
my_image = pygame.image.load("google_logo.png")
#copy the image pixels to the screen
screen.blit(my_image, [x, y])
#Display changes
pygame.display.flip()
keys = {'right':False, 'up':False, 'left':False, 'down':False}
#set up pygame event loop
running = True
while running:
for event in pygame.event.get():
print event
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
print "QUITTING NOW..."
pygame.time.delay(2000)
running = False
if event.key == pygame.K_h:
print "HELLO!"
pygame.time.delay(2500)
running = False
if event.key == pygame.K_c:
print "To move the original Google logo, use the arrow keys. To move the second logo, use the WASD keys."
if event.key == pygame.K_RIGHT:
keys['right'] = True
if event.key == pygame.K_UP:
keys['up'] = True
if event.key == pygame.K_DOWN:
keys['down'] = True
if event.key == pygame.K_RIGHT:
keys['right'] = True
if event.key == pygame.K_LEFT:
keys['left'] = True
elif event.type == pygame.KEYUP:
if event.key == pygame.K_RIGHT:
keys['right'] = False
if event.key == pygame.K_UP:
keys['up'] = False
if event.key == pygame.K_DOWN:
keys['down'] = False
if event.key == pygame.K_LEFT:
keys['left'] = False
x = 0
y = 0
if keys['right']:
x += 10
if keys['up']:
y += 10
if keys['down']:
y -=10
if keys['left']:
x -=10
pygame.quit()
</code></pre>
| 0 |
2016-09-27T22:17:53Z
| 39,735,342 |
<p>I think you should monitor key down and key up and then do the maths.</p>
<p>First set this :</p>
<pre><code>keys = {'right':False, 'up':False, 'left':False, 'down':False}
</code></pre>
<p>Then on event <code>KEYDOWN</code> set your <code>dict[key]</code> to <code>True</code> :</p>
<pre><code>if event.key == pygame.K_RIGHT:
keys['right'] = True
if event.key == pygame.K_UP:
keys['up'] = True
...
</code></pre>
<p>And on event type <code>KEYUP</code> do the same thing but set <code>keys[key]</code> to <code>False</code>.</p>
<p>Then in your event loop :</p>
<pre><code>x = 0
y = 0
if keys['right']:
x += 10
if keys['up']:
y += 10
....
</code></pre>
<p>And then move your object using <code>x</code> and <code>y</code>.</p>
<pre><code>screen.blit(my_image, [x, y])
</code></pre>
<p>Now you can keep key pressed, and your image will be moving, and when you release your keys, it'll stop (no need to repeatedly tap keys to move)</p>
<p><strong>EDIT :</strong></p>
<pre><code>import pygame
#set up the initial pygame window
pygame.init()
screen = pygame.display.set_mode([900,600])
#set background color
background = pygame.Surface(screen.get_size())
background.fill([204,255,229])
screen.blit(background, (0,0))
#Pull in the image to the program
my_image = pygame.image.load("google_logo.png")
#copy the image pixels to the screen
screen.blit(my_image, [x, y])
#Display changes
pygame.display.flip()
keys = {'right':False, 'up':False, 'left':False, 'down':False}
x = 0
y = 0
#set up pygame event loop
running = True
while running:
screen.blit(my_image, [x, y])
pygame.display.flip()
for event in pygame.event.get():
print event
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
print "QUITTING NOW..."
pygame.time.delay(2000)
running = False
if event.key == pygame.K_h:
print "HELLO!"
pygame.time.delay(2500)
running = False
if event.key == pygame.K_c:
print "To move the original Google logo, use the arrow keys. To move the second logo, use the WASD keys."
if event.key == pygame.K_RIGHT:
keys['right'] = True
if event.key == pygame.K_UP:
keys['up'] = True
if event.key == pygame.K_DOWN:
keys['down'] = True
if event.key == pygame.K_LEFT:
keys['left'] = True
elif event.type == pygame.KEYUP:
if event.key == pygame.K_RIGHT:
keys['right'] = False
if event.key == pygame.K_UP:
keys['up'] = False
if event.key == pygame.K_DOWN:
keys['down'] = False
if event.key == pygame.K_LEFT:
keys['left'] = False
x = 0
y = 0
if keys['right']:
x += 10
if keys['up']:
y += 10
if keys['down']:
y -=10
if keys['left']:
x -=10
pygame.quit()
</code></pre>
| 0 |
2016-09-27T22:32:26Z
|
[
"python",
"image",
"move"
] |
Can't get SVC Score function to work
| 39,735,235 |
<p>I am trying to run this machine learning platform and I get the following error: </p>
<pre><code>ValueError: X.shape[1] = 574 should be equal to 11, the number of features at training time
</code></pre>
<p>My Code:</p>
<pre><code>from pylab import *
from sklearn.svm import SVC
from sklearn.ensemble import RandomForestClassifier
import numpy as np
X = list ()
Y = list ()
validationX = list ()
validationY = list ()
file = open ('C:\\Users\\User\\Desktop\\csci4113\\project1\\whitewineTraining.txt','r')
for eachline in file:
strArray = eachline.split(";")
row = list ()
for i in range(len(strArray) - 1):
row.append(float(strArray[i]))
X.append(row)
if (int(strArray[-1]) > 6):
Y.append(1)
else:
Y.append(0)
file2 = open ('C:\\Users\\User\\Desktop\\csci4113\\project1\\whitewineValidation.txt', 'r')
for eachline in file2:
strArray = eachline.split(";")
row2 = list ()
for i in range(len(strArray) - 1):
row2.append(float(strArray[i]))
validationX.append(row2)
if (int(strArray[-1]) > 6):
validationY.append(1)
else:
validationY.append(0)
X = np.array(X)
print (X)
Y = np.array(Y)
print (Y)
validationX = np.array(validationX)
validationY = np.array(validationY)
clf = svm.SVC()
clf.fit(X,Y)
result = clf.predict(validationX)
clf.score(result, validationY)
</code></pre>
<p>The goal of the program is to to build a model from the fit() command where we can use it to compare to a validation set in validationY and see the validity of our machine learning model. Here is the rest of the console output: keep in mind X is confusingly a 11x574 array!</p>
<pre><code>[[ 7. 0.27 0.36 ..., 3. 0.45 8.8 ]
[ 6.3 0.3 0.34 ..., 3.3 0.49 9.5 ]
[ 8.1 0.28 0.4 ..., 3.26 0.44 10.1 ]
...,
[ 6.3 0.28 0.22 ..., 3. 0.33 10.6 ]
[ 7.4 0.16 0.33 ..., 3.04 0.68 10.5 ]
[ 8.4 0.27 0.3 ..., 2.89 0.3
11.46666667]]
[0 0 0 ..., 0 1 0]
C:\Users\User\Anaconda3\lib\site-packages\sklearn\utils\validation.py:386: DeprecationWarning: Passing 1d arrays as data is deprecated in 0.17 and willraise ValueError in 0.19. Reshape your data either using X.reshape(-1, 1) if your data has a single feature or X.reshape(1, -1) if it contains a single sample.
DeprecationWarning)
Traceback (most recent call last):
File "<ipython-input-68-31c649fe24b3>", line 1, in <module>
runfile('C:/Users/User/Desktop/csci4113/project1/program1.py', wdir='C:/Users/User/Desktop/csci4113/project1')
File "C:\Users\User\Anaconda3\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 714, in runfile
execfile(filename, namespace)
File "C:\Users\User\Anaconda3\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 89, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "C:/Users/User/Desktop/csci4113/project1/program1.py", line 43, in <module>
clf.score(result, validationY)
File "C:\Users\User\Anaconda3\lib\site-packages\sklearn\base.py", line 310, in score
return accuracy_score(y, self.predict(X), sample_weight=sample_weight)
File "C:\Users\User\Anaconda3\lib\site-packages\sklearn\svm\base.py", line 568, in predict
y = super(BaseSVC, self).predict(X)
File "C:\Users\User\Anaconda3\lib\site-packages\sklearn\svm\base.py", line 305, in predict
X = self._validate_for_predict(X)
File "C:\Users\User\Anaconda3\lib\site-packages\sklearn\svm\base.py", line 474, in _validate_for_predict
(n_features, self.shape_fit_[1]))
ValueError: X.shape[1] = 574 should be equal to 11, the number of features at training time
runfile('C:/Users/User/Desktop/csci4113/project1/program1.py', wdir='C:/Users/User/Desktop/csci4113/project1')
10
[[ 7. 0.27 0.36 ..., 3. 0.45 8.8 ]
[ 6.3 0.3 0.34 ..., 3.3 0.49 9.5 ]
[ 8.1 0.28 0.4 ..., 3.26 0.44 10.1 ]
...,
[ 6.3 0.28 0.22 ..., 3. 0.33 10.6 ]
[ 7.4 0.16 0.33 ..., 3.04 0.68 10.5 ]
[ 8.4 0.27 0.3 ..., 2.89 0.3
11.46666667]]
[0 0 0 ..., 0 1 0]
C:\Users\User\Anaconda3\lib\site-packages\sklearn\utils\validation.py:386: DeprecationWarning: Passing 1d arrays as data is deprecated in 0.17 and willraise ValueError in 0.19. Reshape your data either using X.reshape(-1, 1) if your data has a single feature or X.reshape(1, -1) if it contains a single sample.
DeprecationWarning)
Traceback (most recent call last):
File "<ipython-input-69-31c649fe24b3>", line 1, in <module>
runfile('C:/Users/User/Desktop/csci4113/project1/program1.py', wdir='C:/Users/User/Desktop/csci4113/project1')
File "C:\Users\User\Anaconda3\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 714, in runfile
execfile(filename, namespace)
File "C:\Users\User\Anaconda3\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 89, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "C:/Users/User/Desktop/csci4113/project1/program1.py", line 46, in <module>
clf.score(result, validationY)
File "C:\Users\User\Anaconda3\lib\site-packages\sklearn\base.py", line 310, in score
return accuracy_score(y, self.predict(X), sample_weight=sample_weight)
File "C:\Users\User\Anaconda3\lib\site-packages\sklearn\svm\base.py", line 568, in predict
y = super(BaseSVC, self).predict(X)
File "C:\Users\User\Anaconda3\lib\site-packages\sklearn\svm\base.py", line 305, in predict
X = self._validate_for_predict(X)
File "C:\Users\User\Anaconda3\lib\site-packages\sklearn\svm\base.py", line 474, in _validate_for_predict
(n_features, self.shape_fit_[1]))``
</code></pre>
| 0 |
2016-09-27T22:22:08Z
| 39,735,457 |
<p>You are simply passing <strong>wrong object</strong> to score function, <a href="http://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestClassifier.html#sklearn.ensemble.RandomForestClassifier.score" rel="nofollow">documentation</a> clearly states</p>
<blockquote>
<p>score(X, y, sample_weight=None)</p>
<p>X : array-like, shape = <strong>(n_samples, n_features)</strong>
Test samples.</p>
</blockquote>
<p>and you pass <strong>predictions</strong> instead, thus </p>
<pre><code>result = clf.predict(validationX)
clf.score(result, validationY)
</code></pre>
<p>is invalid, and should be just</p>
<pre><code>clf.score(validationX, validationY)
</code></pre>
<p>What you tried to do would be fine if you use some <strong>scorer</strong>, and not <strong>classifier</strong>, classifier .score methods call .predict on their own, thus you pass <strong>raw data</strong> as an argument. </p>
| 0 |
2016-09-27T22:43:22Z
|
[
"python",
"numpy",
"machine-learning"
] |
Installing plyfile to Anaconda3
| 39,735,461 |
<p>I run the following line from Spyder (Anaconda3):</p>
<pre><code> from plyfile import PlyData, PlyElement
</code></pre>
<p>and I get the following error message:</p>
<pre><code> Traceback (most recent call last):
File "<ipython-input-269-2c796028388e>", line 1, in <module>
from plyfile import PlyData, PlyElement
ImportError: No module named 'plyfile'
</code></pre>
<p>Next I went to the Anaconda3 Scripts subdirectory and using the Windows Commander I wrote:</p>
<pre><code>conda install plyfile
</code></pre>
<p>I received the following error message:</p>
<pre><code>PackageNotFound: Package not found: "Package missing in current win 64 channels:
-plyfile
</code></pre>
<p>I made a search using the Google and I found the plyfile in the following address <a href="https://pypi.python.org/pypi/plyfile" rel="nofollow">https://pypi.python.org/pypi/plyfile</a>, but then I do not know what to do with it.</p>
<p>Could you please help me?</p>
| 0 |
2016-09-27T22:43:37Z
| 39,735,681 |
<p><code>pip install plyfile</code>, if something isn't in the default anaconda repository but still a pypi package you can pip install and conda will still track the package within your environment.</p>
| 0 |
2016-09-27T23:08:35Z
|
[
"python"
] |
OpenCV Installation failure due to QTKit
| 39,735,485 |
<p>I'm trying to install openCV for Python on my Mac but after going through a bunch of tutorials, none seem to work for me. These are the steps I took</p>
<ol>
<li>Installed <code>CMake</code></li>
<li>Downloaded the OpenCV library</li>
<li>Used <code>CMake</code> to generate the Unix Makefiles</li>
<li>Run <code>make</code> on the generated files</li>
</ol>
<p>And this is where the error arises.</p>
<blockquote>
<p>fatal error: 'QTKit/QTKit.h' file not found</p>
</blockquote>
<p>I searched and I found <strong><em>QTKitDefines.h</em></strong> instead at
<em>/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/System/Library/Frameworks/QTKit.framework/Versions/A/Headers/</em></p>
<p>Upon opening, it read</p>
<blockquote>
<p>QTKit has been deprecated in 10.9.
AVFoundation and AVKit are the frameworks recommended for all new development
involving time-based audiovisual media on OS X. In order to transition your
project from QTKit to AVFoundation please refer to:
"Technical Note TN2300 Transitioning QTKit code to AV Foundation".</p>
</blockquote>
<p>I tried searching and nothing has deem fruitful. All similar issues I found, the users still had <code>QTKit.h</code>. Take for instance this <a href="http://stackoverflow.com/questions/39590741/fatal-error-qtkit-qtkit-h-file-not-found-when-i-build-opencv-on-mac">folk</a></p>
<p>Any help will sincerely be appreciated.</p>
| 1 |
2016-09-27T22:46:34Z
| 39,735,943 |
<p>I found a workaround by downloading the QTKit framework from <a href="https://github.com/phracker/MacOSX-SDKs/releases" rel="nofollow">this</a> repo then I simply merged my framework with the one included in the repo and continued with my installation process successfully.</p>
<p><strong>EDIT for Merging files</strong></p>
<p>By dragging and dropping the downloaded framework into the same location as my current QTKit framework; since they both have the same name, a popup prompted me with three choices of either <em>replacing</em>, <em>merging</em> or <em>cancel</em> then I simply went for merging because this allows me to still keep my updated framework along with the repo one.</p>
| 0 |
2016-09-27T23:43:41Z
|
[
"python",
"osx",
"opencv",
"opencv3.0"
] |
How to prompt user for two dates and output date difference in YY, M, DD?
| 39,735,535 |
<p>I have been searching for a clarified answer on this. I have read many threads and other websites about using datetime, but how can I build a simple program that prompts a user for two certain dates, and then calculate the difference between those dates? I am stuck on figuring out how to get the month and days.</p>
<p>This is what I have so far:</p>
<pre><code>print ("How old will you be when you graduate?")
print ("If you want to know, I'll have to ask you a few questions.")
name = input('What is your name? ')
bYear = int(input("What year were you born? "))
print ("Don't worry. Your information is safe with me.")
bMonth = int(input("What month were you born? "))
bDay = int(input("How about the day you were born? "))
print ("Fantastic. We're almost done here.")
gYear = int(input("What year do you think you'll graduate? "))
gMonth = int(input("What about the month? "))
gDay = int(input("While you're at it, give me the day too. "))
age = gYear - bYear
if bMonth > gMonth:
age = age - 1
aMonth =
if bMonth == gMonth and bDay > gDay:
age = age - 1
print(name, 'you will be', age, 'years old by the time you graduate. Thanks for the information.')
</code></pre>
<p>I am just beginning to use Python, but it's seems pretty simple just coming in. So, for example I want to prompt the user for the year they were born, the month they were born, and the day they were born. Then I want to prompt the user for the year they will graduate, the month they will graduate, and the day they will graduate. Then I want the program to calculate the difference between those dates and output the age of the person in years, months, and days. </p>
<p>For example</p>
<pre><code>BORN AUGUST 23, 1995
WILL GRADUATE: JUNE 11, 2018
AGE AT GRADUATION : 22 YEARS 9 MONTHS AND 18 DAYS
</code></pre>
| -1 |
2016-09-27T22:50:59Z
| 39,736,907 |
<p>You can use the <code>datetime</code> and <a href="http://dateutil.readthedocs.io/en/stable/index.html" rel="nofollow"><code>dateutil</code></a> modules. <code>datetime</code> is in the Python standard library, however, <code>dateutil</code> is 3rd party - it can be installed with pip.</p>
<pre><code>from datetime import date
from dateutil.relativedelta import relativedelta
birth_date = date(year=1992, month=12, day=21)
graduation_date = date(year=2016, month=9, day=28)
diff = relativedelta(graduation_date, birth_date)
>>> print(diff)
relativedelta(years=+23, months=+9, days=+7)
>>> print('AGE AT GRADUATION : {0.years} YEARS {0.months} MONTHS AND {0.days} DAYS'.format(diff))
AGE AT GRADUATION : 23 YEARS 9 MONTHS AND 7 DAYS
</code></pre>
| 0 |
2016-09-28T02:04:13Z
|
[
"python",
"datetime",
"difference"
] |
Could not browse django site
| 39,735,541 |
<p>I'm trying to follow the the django <a href="https://docs.djangoproject.com/en/1.10/intro/tutorial01/" rel="nofollow">tutorial</a> but when when I get to the <code>python manage.py runserver</code> step, I can't browse <a href="http://127.0.0.1:8000/" rel="nofollow">http://127.0.0.1:8000/</a> in chrome or IE. But when I wget in bash, I was able to get the html from <a href="http://127.0.0.1:8000" rel="nofollow">http://127.0.0.1:8000</a>. I'm using windows 10 anniversary edition and I'm using virtualenv.</p>
| 0 |
2016-09-27T22:51:31Z
| 39,735,592 |
<p>Since you say you use wget in bash I'll assume you aren't using windows, so maybe it's another machine.</p>
<p>When you tell django to listen on <code>127.0.0.1</code> it will only accept local connections.</p>
<p>Now to open django to everyone you'll have to run it as such :</p>
<pre><code>python manage.py runserver 0.0.0.0:8000
</code></pre>
<p>Also you'll have to make sure your gateway accepts connections on port 8000 and forwards them to your computer, where django runs. (see port forwarding).</p>
| 2 |
2016-09-27T22:58:21Z
|
[
"python",
"django",
"virtualenv"
] |
Selenium iterating over paginator: optimization
| 39,735,573 |
<p>I have a website with a paginator in it. Each page shows 32 links and I get each of them and store them in separate files in a folder. I'm using the Firefox driver from Selenium in Python.</p>
<p>The procedure is basically:</p>
<pre><code>get the 32 elements
for element in elements:
open new file and save element
repeat
</code></pre>
<p>I am monitoring the time that each cycle takes. I started with 4 seconds, then 8 seconds (when I had saved 10000 links), and now it's spending 10 seconds, and I have saved 13000 links.</p>
<p>Before, I was opening the same file and appending the links, this also slowed down the cycles, I guess because as the size of the file increased, it had to load it and append during each cycle.</p>
<p>But right now I don't know what could be slowing the cycles. Going to the next page always spends 3-4 seconds, so this is not the source of the problem. What could be slowing down the cycles?</p>
<p>This is the cycle:</p>
<pre><code>while True:
propiedades = driver.find_elements_by_xpath("//*[@class='hlisting']")
info_propiedades = [propiedad.find_element_by_xpath(".//*[@class='propertyInfo item']")
for propiedad in propiedades]
for propiedad in info_propiedades:
try:
link = [l.get_attribute("href") for l in propiedad.find_elements_by_xpath(".//a")]
thelink = link[0]
id_ = thelink.split("id-")[-1]
with open(os.path.join(linkspath, id_), "w") as f:
f.write(link[0])
numlinks += 1
except:
print("link not found")
siguiente = driver.find_element_by_id("paginador_pagina_{0}".format(paginador))
siguiente.click() # goes to the next page
while new_active_page == old_active_page: # checks if page has loaded completely
try:
new_active_page = driver.find_element_by_class_name("pagina_activa").text
except:
new_active_page = old_active_page
time.sleep(0.3)
old_active_page = new_active_page
paginador += 1
</code></pre>
| 0 |
2016-09-27T22:55:34Z
| 39,736,441 |
<p>A few suggestions...</p>
<ol>
<li><p>You have a lot of nested <code>.find_elements_*</code> at the start. You should be able to craft a single find that gets the elements you are looking for. From the site and your code, it looks like you are getting codes that look like, "MC1595226". If you grab one of these MC codes and do a search in the HTML, you will find that code all over that particluar listing. It's in the URL, it's part of ids of a bunch of the elements, and so on. A faster way to find this code is to use a CSS selector, <code>"a[id^='btnContactResultados_'"</code>. It searches for <code>A</code> tags that contain an id that starts with "btnContactResultados_". The rest of that id is the MC number, e.g.</p>
<pre><code><a id="btnContactResultados_MC1595226" ...>
</code></pre>
<p>So with that CSS selector we find the desired elements and then grab the ID and split it by "_" and grab the last part. NOTE: This is more of a code efficiency. I don't think this is going to make your script go super fast but it should speed up the search portion some.</p></li>
<li><p>I would recommend writing a log per page and write only once per page. So basically you process the codes for the page and append the result to a list. Once all the codes for the page are processed, you write that list to the log. Writing to disk is slow... you should do it as little as possible. In the end you can write a little script that opens all those files and appends them to get the final product all in one file. You can also do some middle ground where you write once to file per page but write 100 pages to file before closing that file and using a different one. You'll have to play with these settings to see where you get the best performance.</p></li>
</ol>
<p>If we combine the logic for these two, we get something like this...</p>
<pre><code>while True:
links = driver.find_elements_by_css_selector("a[id^='btnContactResultados_'")
codes = []
for link in links:
codes.append(link.get_attribute("id").split("_")[-1])
with open(os.path.join(linkspath, paginador), "w") as f:
f.write(codes)
driver.find_element_by_link_text("Siguiente »").click() # this should work
while new_active_page == old_active_page: # checks if page has loaded completely
try:
new_active_page = driver.find_element_by_class_name("pagina_activa").text
except:
new_active_page = old_active_page
time.sleep(0.3)
old_active_page = new_active_page
paginador += 1
</code></pre>
<p>NOTE: python is not my native language... I'm more of a Java/C# guy so you may find errors, inefficiencies, or non-pythony code in here. You have been warned... :)</p>
| 1 |
2016-09-28T00:57:22Z
|
[
"python",
"selenium",
"pagination"
] |
Adding lazy constraint in python-Gurobi interface
| 39,735,659 |
<p>I am trying to add some lazy constraints to the first stage of a stochastic programming problem. For example, the optimal solution shows me that locations 16 and 20 are chosen together which I don't want to so I want to add a lazy constraint as follows:</p>
<pre><code> First Stage
x1 + x2 + ... + x40 = 5
z_i,l <= x_i i=1,..,40 and l=1,2
Second Stage
....
def mycallback(model,where):
if where == GRB.Callback.MIPSOL:
sol = model.cbGetSolution([model._vars[s] for s in range(1,40)])
if sol[16] + sol[20] == 2:
Exp = LinExpr([(1,model._vars[16]),(1,model._vars[20])])
model.cbLazy(Exp <= 1)
model._vars = x
model.optimize(mycallback)
</code></pre>
<p>But after running this function, locations 16 and 20 are still in the optimal solution. Could you please let me know how should I attack this issue?</p>
| 1 |
2016-09-27T23:06:33Z
| 39,757,166 |
<p>In your code, the test </p>
<pre><code>if sol[16] + sol[20] == 2:
</code></pre>
<p>is comparing the sum of two floating point numbers with an integer using equality. Even if you declare decision variables to be integer, the solution values are floating point numbers. The floating point numbers don't even need to have integer values. Gurobi has a parameter <a href="https://www.gurobi.com/documentation/6.5/refman/intfeastol.html#parameter:IntFeasTol" rel="nofollow">IntFeasTol</a>, which determines how far a value can be from 0 or 1 and still be considered binary. The default is 1e-5, so 0.999991 would be considered an integer. Your check should something like</p>
<pre><code>if sol[16] + sol[20] > 1.5:
</code></pre>
| 1 |
2016-09-28T20:34:27Z
|
[
"python",
"lazy-evaluation",
"gurobi"
] |
Binarize a float64 Pandas Dataframe in Python
| 39,735,676 |
<p>I've got a Panda DF with various columns (each indicating the frequency of a word in a corpus). Each row corresponds to a document and each is of type float64. </p>
<p>for example:</p>
<pre><code>word1 word2 word3
0.0 0.3 1.0
0.1 0.0 0.5
etc
</code></pre>
<p>I want to Binarize this and instead of the frequency end up with a boolean (0s and 1s DF) that indicates the existence of a word</p>
<p>so the above example would be transformed to :</p>
<pre><code>word1 word2 word3
0 1 1
1 0 1
etc
</code></pre>
<p>I looked at get_dummies(), but the output was not the expected.</p>
| 3 |
2016-09-27T23:08:17Z
| 39,735,754 |
<p>Code:</p>
<pre><code>import numpy as np
import pandas as pd
""" create some test-data """
random_data = np.random.random([3, 3])
random_data[0,0] = 0.0
random_data[1,2] = 0.0
df = pd.DataFrame(random_data,
columns=['A', 'B', 'C'], index=['first', 'second', 'third'])
print(df)
""" binarize """
threshold = lambda x: x > 0
df_ = df.apply(threshold).astype(int)
print(df_)
</code></pre>
<p>Output:</p>
<pre><code>A B C
first 0.000000 0.610263 0.301024
second 0.728070 0.229802 0.000000
third 0.243811 0.335131 0.863908
A B C
first 0 1 1
second 1 1 0
third 1 1 1
</code></pre>
<p>Remarks:</p>
<ul>
<li>get_dummies() analyze each unique value per column and introduces new columns (for each unique value) to mark if this value is active</li>
<li>= if column A has 20 unique values, 20 new columns are added, where exactly one column is true, the others are false</li>
</ul>
| 0 |
2016-09-27T23:19:33Z
|
[
"python",
"pandas",
"dataframe"
] |
Binarize a float64 Pandas Dataframe in Python
| 39,735,676 |
<p>I've got a Panda DF with various columns (each indicating the frequency of a word in a corpus). Each row corresponds to a document and each is of type float64. </p>
<p>for example:</p>
<pre><code>word1 word2 word3
0.0 0.3 1.0
0.1 0.0 0.5
etc
</code></pre>
<p>I want to Binarize this and instead of the frequency end up with a boolean (0s and 1s DF) that indicates the existence of a word</p>
<p>so the above example would be transformed to :</p>
<pre><code>word1 word2 word3
0 1 1
1 0 1
etc
</code></pre>
<p>I looked at get_dummies(), but the output was not the expected.</p>
| 3 |
2016-09-27T23:08:17Z
| 39,735,878 |
<p>Casting to boolean will result in <code>True</code> for anything that is not zero — and <code>False</code> for any zero entry. If you then cast to integer, you get ones and zeroes.</p>
<pre><code>import io
import pandas as pd
data = io.StringIO('''\
word1 word2 word3
0.0 0.3 1.0
0.1 0.0 0.5
''')
df = pd.read_csv(data, delim_whitespace=True)
res = df.astype(bool).astype(int)
print(res)
</code></pre>
<p>Output:</p>
<pre><code> word1 word2 word3
0 0 1 1
1 1 0 1
</code></pre>
| 4 |
2016-09-27T23:36:02Z
|
[
"python",
"pandas",
"dataframe"
] |
Binarize a float64 Pandas Dataframe in Python
| 39,735,676 |
<p>I've got a Panda DF with various columns (each indicating the frequency of a word in a corpus). Each row corresponds to a document and each is of type float64. </p>
<p>for example:</p>
<pre><code>word1 word2 word3
0.0 0.3 1.0
0.1 0.0 0.5
etc
</code></pre>
<p>I want to Binarize this and instead of the frequency end up with a boolean (0s and 1s DF) that indicates the existence of a word</p>
<p>so the above example would be transformed to :</p>
<pre><code>word1 word2 word3
0 1 1
1 0 1
etc
</code></pre>
<p>I looked at get_dummies(), but the output was not the expected.</p>
| 3 |
2016-09-27T23:08:17Z
| 39,736,116 |
<p>I would have answered as @Alberto Garcia-Raboso answered but here is an alternative that is very quick and leverages the same idea.</p>
<p>Use <code>np.where</code></p>
<pre><code>pd.DataFrame(np.where(df, 1, 0), df.index, df.columns)
</code></pre>
<p><a href="http://i.stack.imgur.com/YE8F7.png" rel="nofollow"><img src="http://i.stack.imgur.com/YE8F7.png" alt="enter image description here"></a></p>
<hr>
<h1>Timing</h1>
<p><a href="http://i.stack.imgur.com/EB5Eb.png" rel="nofollow"><img src="http://i.stack.imgur.com/EB5Eb.png" alt="enter image description here"></a></p>
| 2 |
2016-09-28T00:09:23Z
|
[
"python",
"pandas",
"dataframe"
] |
Binarize a float64 Pandas Dataframe in Python
| 39,735,676 |
<p>I've got a Panda DF with various columns (each indicating the frequency of a word in a corpus). Each row corresponds to a document and each is of type float64. </p>
<p>for example:</p>
<pre><code>word1 word2 word3
0.0 0.3 1.0
0.1 0.0 0.5
etc
</code></pre>
<p>I want to Binarize this and instead of the frequency end up with a boolean (0s and 1s DF) that indicates the existence of a word</p>
<p>so the above example would be transformed to :</p>
<pre><code>word1 word2 word3
0 1 1
1 0 1
etc
</code></pre>
<p>I looked at get_dummies(), but the output was not the expected.</p>
| 3 |
2016-09-27T23:08:17Z
| 39,860,720 |
<p>Found an alternative way using Pandas Indexing.</p>
<p>This can be simply done by </p>
<pre><code>df[df>0] = 1
</code></pre>
<p>simple as that!</p>
| 0 |
2016-10-04T19:55:36Z
|
[
"python",
"pandas",
"dataframe"
] |
"Tuple index out of range" Error?
| 39,735,686 |
<p>I'm not sure what I'm doing wrong here, does anyone know? I keep getting an error that says "Tuple index out of range." I'm following a tutorial for school and I seem to be doing everything right, however I keep getting this error. Any help would be appreciated! Thank you so much.</p>
<pre><code>animal = input("Enter any LARGE animal: ")
smallAnimal = input("Enter any SMALL animal: ")
weapon = input("Enter a sharp weapon: ")
def createDictionary():
storyDict = dict()
storyDict['animal'] = animal
storyDict['smallAnimal'] = smallAnimal
storyDict['weapon'] = weapon
return storyDict
def main():
dictionary = createDictionary()
animalFormat = """Once upon a time, there was a very, very large {animal}. This {animal} was the meanest, baddest, most gruesome {animal} there was. And one day, a wild {1} had
stepped on the {animal}'s foot. At that moment, the {1} knew it had messed up. This made the {animal} angry, so he took a {weapon} and STABBED the
{smallAnimal}with it! The {smallAnimal} squirmed and fought to get out, but it was no match for the {animal} with a {weapon}.
The End."""
withSubstitutions = animalFormat.format(**dictionary)
print(withSubstitutions)
main()
</code></pre>
| 0 |
2016-09-27T23:09:35Z
| 39,735,732 |
<p>In animalFormat, replace:</p>
<pre><code>{1}
</code></pre>
<p>With:</p>
<pre><code>{smallAnimal}
</code></pre>
<p>This change must be made in two places.</p>
<p>Since you are supplying arguments to <code>format</code> with keywords, there is nothing for <code>1</code> to refer to.</p>
<h3>Simpler example</h3>
<p>Observe that this works:</p>
<pre><code>>>> d = {'a':1, 'b':2}
>>> 'Twice {a} is {b}'.format(**d)
'Twice 1 is 2'
</code></pre>
<p>But this does not work:</p>
<pre><code>>>> 'Twice {1} is {b}'.format(**d)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: tuple index out of range
</code></pre>
<p>If you are supplying <code>format</code> with keyword arguments, there is nothing for <code>1</code> to refer to.</p>
<p>It is possible to supply both positional arguments and keyword arguments. For example:</p>
<pre><code>>>> 'Twice {1} is {b}'.format('Arg0', 'ArgOne', **d)
'Twice ArgOne is 2'
</code></pre>
<h3>Complete working code</h3>
<pre><code>animal = input("Enter any LARGE animal: ")
smallAnimal = input("Enter any SMALL animal: ")
weapon = input("Enter a sharp weapon: ")
def createDictionary():
storyDict = dict()
storyDict['animal'] = animal
storyDict['smallAnimal'] = smallAnimal
storyDict['weapon'] = weapon
return storyDict
def main():
dictionary = createDictionary()
animalFormat = """Once upon a time, there was a very, very large {animal}. This {animal} was the meanest, baddest, most gruesome {animal} there was. And one day, a wild {smallAnimal} had
stepped on the {animal}'s foot. At that moment, the {smallAnimal} knew it had messed up. This made the {animal} angry, so he took a {weapon} and STABBED the_
{smallAnimal}with it! The {smallAnimal} squirmed and fought to get out, but it was no match for the {animal} with a {weapon}.
The End."""
withSubstitutions = animalFormat.format(**dictionary)
print(withSubstitutions)
main()
</code></pre>
<p>Sample run:</p>
<pre><code>Enter any LARGE animal: Lion
Enter any SMALL animal: Mouse
Enter a sharp weapon: knife
Once upon a time, there was a very, very large Lion. This Lion was the meanest, baddest, most gruesome Lion there was. And one day, a wild Mouse had
stepped on the Lion's foot. At that moment, the Mouse knew it had messed up. This made the Lion angry, so he took a knife and STABBED the
Mousewith it! The Mouse squirmed and fought to get out, but it was no match for the Lion with a knife.
The End.
</code></pre>
| 0 |
2016-09-27T23:16:07Z
|
[
"python",
"tuples"
] |
"Tuple index out of range" Error?
| 39,735,686 |
<p>I'm not sure what I'm doing wrong here, does anyone know? I keep getting an error that says "Tuple index out of range." I'm following a tutorial for school and I seem to be doing everything right, however I keep getting this error. Any help would be appreciated! Thank you so much.</p>
<pre><code>animal = input("Enter any LARGE animal: ")
smallAnimal = input("Enter any SMALL animal: ")
weapon = input("Enter a sharp weapon: ")
def createDictionary():
storyDict = dict()
storyDict['animal'] = animal
storyDict['smallAnimal'] = smallAnimal
storyDict['weapon'] = weapon
return storyDict
def main():
dictionary = createDictionary()
animalFormat = """Once upon a time, there was a very, very large {animal}. This {animal} was the meanest, baddest, most gruesome {animal} there was. And one day, a wild {1} had
stepped on the {animal}'s foot. At that moment, the {1} knew it had messed up. This made the {animal} angry, so he took a {weapon} and STABBED the
{smallAnimal}with it! The {smallAnimal} squirmed and fought to get out, but it was no match for the {animal} with a {weapon}.
The End."""
withSubstitutions = animalFormat.format(**dictionary)
print(withSubstitutions)
main()
</code></pre>
| 0 |
2016-09-27T23:09:35Z
| 39,735,735 |
<p>You are mixing up formatting string by keywords and ordered data.</p>
<p>MCVE:</p>
<pre><code>s = "{0}{k}".format(k='something')
</code></pre>
<p>Exception:</p>
<pre><code>Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: tuple index out of range
</code></pre>
<p>Since your template contains placeholders for ordered arguments (<code>{1}</code>), you need to pass them to your function:</p>
<pre><code>animalFormat = """Once upon a time, there was a very, very large {animal}. This {animal} was the meanest, baddest, most gruesome {animal} there was. And one day, a wild {1} had
stepped on the {animal}'s foot. At that moment, the {1} knew it had messed up. This made the {animal} angry, so he took a {weapon} and STABBED the
{smallAnimal}with it! The {smallAnimal} squirmed and fought to get out, but it was no match for the {animal} with a {weapon}.
The End."""
d = {'animal': 'X', 'smallAnimal': 'Y', 'weapon': 'Z'}
a = ['A', 'B'] # placeholder
animalFormat.format(*a, **d) # works fine
</code></pre>
| 0 |
2016-09-27T23:16:58Z
|
[
"python",
"tuples"
] |
"Tuple index out of range" Error?
| 39,735,686 |
<p>I'm not sure what I'm doing wrong here, does anyone know? I keep getting an error that says "Tuple index out of range." I'm following a tutorial for school and I seem to be doing everything right, however I keep getting this error. Any help would be appreciated! Thank you so much.</p>
<pre><code>animal = input("Enter any LARGE animal: ")
smallAnimal = input("Enter any SMALL animal: ")
weapon = input("Enter a sharp weapon: ")
def createDictionary():
storyDict = dict()
storyDict['animal'] = animal
storyDict['smallAnimal'] = smallAnimal
storyDict['weapon'] = weapon
return storyDict
def main():
dictionary = createDictionary()
animalFormat = """Once upon a time, there was a very, very large {animal}. This {animal} was the meanest, baddest, most gruesome {animal} there was. And one day, a wild {1} had
stepped on the {animal}'s foot. At that moment, the {1} knew it had messed up. This made the {animal} angry, so he took a {weapon} and STABBED the
{smallAnimal}with it! The {smallAnimal} squirmed and fought to get out, but it was no match for the {animal} with a {weapon}.
The End."""
withSubstitutions = animalFormat.format(**dictionary)
print(withSubstitutions)
main()
</code></pre>
| 0 |
2016-09-27T23:09:35Z
| 39,735,743 |
<p>This error is because you have <strong>named substitution</strong> (such as <code>.. very large {animal} ..</code>) as well as <strong>positional substitution</strong> (such as <code>At that moment, the {1} knew ..</code>).</p>
<p>Consider passing something like:</p>
<pre><code>animalFormat.format("Replacement for {0}", "Replacement for {1}", **dictionary)
</code></pre>
<p>In the above case, positional portion of the substition will read:</p>
<pre><code>At the moment, the Replacement for {1} knew ..
</code></pre>
| 0 |
2016-09-27T23:17:26Z
|
[
"python",
"tuples"
] |
How can I filter exported tickets from database using Django?
| 39,735,803 |
<p>I am working on a Django based web project where we handle tickets based requests. I am working on an implementation where I need to export all closed tickets everyday.</p>
<p>My ticket table database looks like,</p>
<pre><code>-------------------------------------------------
| ID | ticket_number | ticket_data | is_closed |
-------------------------------------------------
| 1 | 123123 | data 1 | 1 |
-------------------------------------------------
| 2 | 123124 | data 2 | 1 |
-------------------------------------------------
| 3 | 123125 | data 3 | 1 |
-------------------------------------------------
| 4 | 123126 | data 4 | 1 |
-------------------------------------------------
</code></pre>
<p>And my ticket_exported table in database is similar to </p>
<pre><code>----------------------------------
| ID | ticket_id | ticket_number |
----------------------------------
| 10 | 1 | 123123 |
----------------------------------
| 11 | 2 | 123124 |
----------------------------------
</code></pre>
<p>so my question is that when I process of exporting tickets, is there any way where I can make a single query to get list of all tickets which are closed but <code>ticket_id</code> and <code>ticket_number</code> is not in <code>ticket_exported</code> table? So when I run functions it should get tickets with <code>ticket_id</code> '3' and '4' because they are not exported in <code>ticket_export</code> database.</p>
<p>I don't want to go through all possible tickets and check one by one if their id exists in exported tickets table if I can just do it in one query whether it is raw SQL query or Django's queries.</p>
<p>Thanks everyone.</p>
| 0 |
2016-09-27T23:25:55Z
| 39,735,884 |
<p>you can do without <code>is_exported</code> field: </p>
<pre><code>exported_tickets = TicketsExported.objects.all()
unexported_tickets = Tickets.object.exclude(id__in=[et.id for et in exported_tickets])
</code></pre>
<p>but <code>is_exported</code> field can be useful somewhere else </p>
| 2 |
2016-09-27T23:36:54Z
|
[
"python",
"mysql",
"django"
] |
How can I filter exported tickets from database using Django?
| 39,735,803 |
<p>I am working on a Django based web project where we handle tickets based requests. I am working on an implementation where I need to export all closed tickets everyday.</p>
<p>My ticket table database looks like,</p>
<pre><code>-------------------------------------------------
| ID | ticket_number | ticket_data | is_closed |
-------------------------------------------------
| 1 | 123123 | data 1 | 1 |
-------------------------------------------------
| 2 | 123124 | data 2 | 1 |
-------------------------------------------------
| 3 | 123125 | data 3 | 1 |
-------------------------------------------------
| 4 | 123126 | data 4 | 1 |
-------------------------------------------------
</code></pre>
<p>And my ticket_exported table in database is similar to </p>
<pre><code>----------------------------------
| ID | ticket_id | ticket_number |
----------------------------------
| 10 | 1 | 123123 |
----------------------------------
| 11 | 2 | 123124 |
----------------------------------
</code></pre>
<p>so my question is that when I process of exporting tickets, is there any way where I can make a single query to get list of all tickets which are closed but <code>ticket_id</code> and <code>ticket_number</code> is not in <code>ticket_exported</code> table? So when I run functions it should get tickets with <code>ticket_id</code> '3' and '4' because they are not exported in <code>ticket_export</code> database.</p>
<p>I don't want to go through all possible tickets and check one by one if their id exists in exported tickets table if I can just do it in one query whether it is raw SQL query or Django's queries.</p>
<p>Thanks everyone.</p>
| 0 |
2016-09-27T23:25:55Z
| 39,735,953 |
<p>Per my comment- you could probably save yourself a bunch of trouble and just add another BooleanField for <code>'is_exported'</code> instead of having a separate model assuming there aren't fields specific to TicketExported. </p>
<p>@doniyor's answer gets you the queryset you're looking for though. In response to your raw SQL statement question: you want: <code>unexported_tickets.query</code>.</p>
| 1 |
2016-09-27T23:44:54Z
|
[
"python",
"mysql",
"django"
] |
Pycharm: Type hint list of items
| 39,735,843 |
<p>My question is different because I made a mistake using type hint.</p>
<p>I found a weird type hinging in pycharm:
<a href="http://i.stack.imgur.com/KFi0B.png" rel="nofollow"><img src="http://i.stack.imgur.com/KFi0B.png" alt="enter image description here"></a></p>
<p><code>Example</code> is my own class. But I guess this is less important because the IDE is complaining about <code>list</code> type does not define <code>__getitem__</code> method which is no true. I'm wondering if it's a bug or I used it in a wrong way.</p>
| 3 |
2016-09-27T23:31:25Z
| 39,735,879 |
<p>Accoring to <a href="https://www.python.org/dev/peps/pep-0484/">official PEP</a> to denote list of objects you should use <code>typing.List</code>, not <code>list</code> builtin.</p>
<pre><code>from typing import List
class Something:
pass
def f(seq: List[Something]): # no warning
for o in seq:
print(o)
</code></pre>
| 6 |
2016-09-27T23:36:35Z
|
[
"python",
"pycharm"
] |
Pycharm: Type hint list of items
| 39,735,843 |
<p>My question is different because I made a mistake using type hint.</p>
<p>I found a weird type hinging in pycharm:
<a href="http://i.stack.imgur.com/KFi0B.png" rel="nofollow"><img src="http://i.stack.imgur.com/KFi0B.png" alt="enter image description here"></a></p>
<p><code>Example</code> is my own class. But I guess this is less important because the IDE is complaining about <code>list</code> type does not define <code>__getitem__</code> method which is no true. I'm wondering if it's a bug or I used it in a wrong way.</p>
| 3 |
2016-09-27T23:31:25Z
| 39,736,086 |
<p>Åukasz explained how to correct your code. I'll explain why the error message says what it does.</p>
<p><code>list</code> defines <code>__getitem__</code>, true, but that isn't what the error message is complaining about. The error message is saying that <code>type</code> itself, which is the <code>list</code> <em>type's</em> type, doesn't support <code>__getitem__</code>. For <code>list[whatever]</code> to be valid, <code>type</code> would have to define a <code>__getitem__</code> method, not <code>list</code>.</p>
| 1 |
2016-09-28T00:05:49Z
|
[
"python",
"pycharm"
] |
Cant get inner loops to add up properly
| 39,735,921 |
<p>My issue is with my user input totals for rainfall not adding up properly</p>
<p>my assumption is that it is not adding the 1st month in when asked on multiple years as </p>
<p><img src="http://i.stack.imgur.com/XKqhg.jpg" alt="problem explained"></p>
<pre><code>def main():
#define accumulators
monthRain = 0
year = 0
monthTotal = 0
months = 0
total = 0
#get # of years
year = int(input("Enter the number of years to collect data for: "))
#define month total befor it is changed below with year + 1
monthTotal = year * 12
#define how many months per year
months = 12
#Find average rainfall per month
for year in range(year):
#accumulator for rain per month
total = 0
#get rainfall per month
print('\nNext you will enter 12 months of rainfall data for year', year + 1)
for month in range(months):
print("Enter the rainfall for month", month + 1, end=" ")
monthRain = float(input(': '))
#add monthly raingfall to accumulator
total += monthRain
average = total / monthTotal
#total months of data
print('\nYou have entered data for', monthTotal,'months')
#total rainfall
print('\nThe total rainfall for the collected months is:', total)
print('The average monthly rainfall for the collected months is:', format(average, '.2f' ))
main()
</code></pre>
| 0 |
2016-09-27T23:41:04Z
| 39,735,974 |
<p>Take <code>total = 0</code> out of the for loop. Every time you enter the loop, it sets <code>total</code> to zero. Take it out and put it before the for loop. I think that will fix it.</p>
<p>Let me know...</p>
| 2 |
2016-09-27T23:48:45Z
|
[
"python",
"loops",
"nested"
] |
Cant get inner loops to add up properly
| 39,735,921 |
<p>My issue is with my user input totals for rainfall not adding up properly</p>
<p>my assumption is that it is not adding the 1st month in when asked on multiple years as </p>
<p><img src="http://i.stack.imgur.com/XKqhg.jpg" alt="problem explained"></p>
<pre><code>def main():
#define accumulators
monthRain = 0
year = 0
monthTotal = 0
months = 0
total = 0
#get # of years
year = int(input("Enter the number of years to collect data for: "))
#define month total befor it is changed below with year + 1
monthTotal = year * 12
#define how many months per year
months = 12
#Find average rainfall per month
for year in range(year):
#accumulator for rain per month
total = 0
#get rainfall per month
print('\nNext you will enter 12 months of rainfall data for year', year + 1)
for month in range(months):
print("Enter the rainfall for month", month + 1, end=" ")
monthRain = float(input(': '))
#add monthly raingfall to accumulator
total += monthRain
average = total / monthTotal
#total months of data
print('\nYou have entered data for', monthTotal,'months')
#total rainfall
print('\nThe total rainfall for the collected months is:', total)
print('The average monthly rainfall for the collected months is:', format(average, '.2f' ))
main()
</code></pre>
| 0 |
2016-09-27T23:41:04Z
| 39,735,985 |
<p>At the start of every year entry, you zero <code>total</code>, then print <code>total</code> at the end. The 64 you see is actually the 2nd year's rainfall, and the 1st year is being thrown out.</p>
| 1 |
2016-09-27T23:50:01Z
|
[
"python",
"loops",
"nested"
] |
Cant get inner loops to add up properly
| 39,735,921 |
<p>My issue is with my user input totals for rainfall not adding up properly</p>
<p>my assumption is that it is not adding the 1st month in when asked on multiple years as </p>
<p><img src="http://i.stack.imgur.com/XKqhg.jpg" alt="problem explained"></p>
<pre><code>def main():
#define accumulators
monthRain = 0
year = 0
monthTotal = 0
months = 0
total = 0
#get # of years
year = int(input("Enter the number of years to collect data for: "))
#define month total befor it is changed below with year + 1
monthTotal = year * 12
#define how many months per year
months = 12
#Find average rainfall per month
for year in range(year):
#accumulator for rain per month
total = 0
#get rainfall per month
print('\nNext you will enter 12 months of rainfall data for year', year + 1)
for month in range(months):
print("Enter the rainfall for month", month + 1, end=" ")
monthRain = float(input(': '))
#add monthly raingfall to accumulator
total += monthRain
average = total / monthTotal
#total months of data
print('\nYou have entered data for', monthTotal,'months')
#total rainfall
print('\nThe total rainfall for the collected months is:', total)
print('The average monthly rainfall for the collected months is:', format(average, '.2f' ))
main()
</code></pre>
| 0 |
2016-09-27T23:41:04Z
| 39,735,988 |
<p>I think you shouldn't be resetting the <code>total</code> for each year. That's why you were missing a year's worth of data. The total rainfall in the example you provided was <code>131</code> and the average is approximately <code>5.46</code>. I ran your example and got the following.</p>
<pre><code>Enter the number of years to collect data for: 2
('\nNext you will enter 12 months of rainfall data for year', 1)
Enter the rainfall for month 1
: 3
Enter the rainfall for month 2
: 4
Enter the rainfall for month 3
: 6
Enter the rainfall for month 4
: 7
Enter the rainfall for month 5
: 9
Enter the rainfall for month 6
: 8
Enter the rainfall for month 7
: 5
Enter the rainfall for month 8
: 3
Enter the rainfall for month 9
: 4
Enter the rainfall for month 10
: 1
Enter the rainfall for month 11
: 8
Enter the rainfall for month 12
: 9
('\nNext you will enter 12 months of rainfall data for year', 2)
Enter the rainfall for month 1
: 3
Enter the rainfall for month 2
: 6
Enter the rainfall for month 3
: 7
Enter the rainfall for month 4
: 3
Enter the rainfall for month 5
: 4
Enter the rainfall for month 6
: 1
Enter the rainfall for month 7
: 9
Enter the rainfall for month 8
: 7
Enter the rainfall for month 9
: 8
Enter the rainfall for month 10
: 4
Enter the rainfall for month 11
: 5
Enter the rainfall for month 12
: 7
('\nYou have entered data for', 24, 'months')
('\nThe total rainfall for the collected months is:', 131.0)
('The average monthly rainfall for the collected months is:', '5.46')
</code></pre>
<p>Here is the corrected code: </p>
<pre><code>#define accumulators
monthRain = 0
year = 0
monthTotal = 0
months = 0
total = 0
#get # of years
year = int(input("Enter the number of years to collect data for: "))
#define month total befor it is changed below with year + 1
monthTotal = year * 12
#define how many months per year
months = 12
#Find average rainfall per month
for year in range(year):
#accumulator for rain per month
#get rainfall per month
print('\nNext you will enter 12 months of rainfall data for year', year + 1)
for month in range(months):
print ("Enter the rainfall for month", month + 1, " ")
monthRain = float(input(': '))
#add monthly raingfall to accumulator
total += monthRain
average = total / monthTotal
#total months of data
print('\nYou have entered data for', monthTotal,'months')
#total rainfall
print('\nThe total rainfall for the collected months is:', total)
print('The average monthly rainfall for the collected months is:', format(average, '.2f' ))
</code></pre>
| 0 |
2016-09-27T23:50:20Z
|
[
"python",
"loops",
"nested"
] |
Cant get inner loops to add up properly
| 39,735,921 |
<p>My issue is with my user input totals for rainfall not adding up properly</p>
<p>my assumption is that it is not adding the 1st month in when asked on multiple years as </p>
<p><img src="http://i.stack.imgur.com/XKqhg.jpg" alt="problem explained"></p>
<pre><code>def main():
#define accumulators
monthRain = 0
year = 0
monthTotal = 0
months = 0
total = 0
#get # of years
year = int(input("Enter the number of years to collect data for: "))
#define month total befor it is changed below with year + 1
monthTotal = year * 12
#define how many months per year
months = 12
#Find average rainfall per month
for year in range(year):
#accumulator for rain per month
total = 0
#get rainfall per month
print('\nNext you will enter 12 months of rainfall data for year', year + 1)
for month in range(months):
print("Enter the rainfall for month", month + 1, end=" ")
monthRain = float(input(': '))
#add monthly raingfall to accumulator
total += monthRain
average = total / monthTotal
#total months of data
print('\nYou have entered data for', monthTotal,'months')
#total rainfall
print('\nThe total rainfall for the collected months is:', total)
print('The average monthly rainfall for the collected months is:', format(average, '.2f' ))
main()
</code></pre>
| 0 |
2016-09-27T23:41:04Z
| 39,735,994 |
<p>The 64 is actually the result of your second year.</p>
<p>Because you have <code>total = 0</code> inside your loop, it is <strong>rest</strong> after every year. Thus the values of the first year are overwritten by the values of the second year.</p>
<p>Take <code>total=0</code> outside of the loop. That should fix the problem.</p>
<p>Other than that I wonder, why you have a variable for month, if you're using a constant 12 to calculate <code>monthTotal</code>.</p>
| 0 |
2016-09-27T23:51:02Z
|
[
"python",
"loops",
"nested"
] |
Unable to ftp a file using python ftplib, but successful using curl
| 39,735,937 |
<p>I receive the following error when uploading a small text file to an ftp site when using python's ftplib:</p>
<pre><code> File "ftpuploader.py", line 13, in uploadFilePath
ftp.storbinary("STOR {}".format(filepath), file)
File "/usr/lib64/python2.7/ftplib.py", line 471, in storbinary
conn = self.transfercmd(cmd, rest)
File "/usr/lib64/python2.7/ftplib.py", line 376, in transfercmd
return self.ntransfercmd(cmd, rest)[0]
File "/usr/lib64/python2.7/ftplib.py", line 358, in ntransfercmd
resp = self.sendcmd(cmd)
File "/usr/lib64/python2.7/ftplib.py", line 249, in sendcmd
return self.getresp()
File "/usr/lib64/python2.7/ftplib.py", line 224, in getresp
raise error_perm, resp
ftplib.error_perm: 553 Could not create file.
</code></pre>
<p>I am using the following code successfully when connecting to another system. I can log in, change directories, but am unable to create the file. I can load a file using either filezilla or a simple curl command, curl -T '/path/to/file' <a href="ftp://192.168.18.75" rel="nofollow">ftp://192.168.18.75</a> --user admin:password</p>
<pre><code>ftp = FTP(address)
ftp.login(username, password)
ftp.cwd('/gui')
file = open(filepath, 'rb')
ftp.storbinary("STOR {}".format(filepath), file)
ftp.retrlines('LIST') # list directory contents
file.close()
ftp.quit()
</code></pre>
<p>any ideas?</p>
| 0 |
2016-09-27T23:42:39Z
| 39,763,819 |
<p>You are passing a path to a local path to the <code>STOR</code> command (the same path you use with the <code>open(filepath, 'rb')</code>).</p>
<p>While with the CURL, you do not specify any path to the remote file. So the file gets uploaded to the current FTP working directory.</p>
<p>As already suggested in the comments by @acw1668, use the:</p>
<pre><code>ftp.storbinary("STOR {}".format(os.path.basename(filepath)), file)
</code></pre>
| 2 |
2016-09-29T07:17:50Z
|
[
"python",
"curl",
"ftp"
] |
Simple data transmission from multiple Arduinos (client) to Raspberry pi (server) wirelessly
| 39,735,991 |
<p>I'm building a project where I have multiple Arduinos, each having a temperature sensor and a [input wireless transmission method here]. </p>
<p>This data would be received by a controller, a Raspberry pi, which would act as the server: call to Arduino, collect the data, and store it. This data would be accessible to a Mobile App, but this is out of the scope of the question.</p>
<p><strong>Requirements</strong>: </p>
<ul>
<li><p>Arduinos must read simple raw data (in this case, the temperature reading from the sensor) and make it accessible to the Raspberry pi, which would make calls to each Arduino board (from 1 sec to 1 min time frame).</p></li>
<li><p>Arduino side must have a low energy consumption, as it would be powered by a small battery;</p></li>
<li><p>Data transmission on Arduino end must be as cheap as possible and work in low temperatures (around -5 degrees Celsius). They would be stored be inside a freezer, so temperature and a thick-ish metal layer are obstacles to overcome.</p></li>
</ul>
<p><strong>Question</strong>: is Bluetooth a viable transmission method? Is it possible to pair multiple Arduinos to one Raspberry pi at a single time?
If Bluetooth isn't any good, what is? Correct me if I'm wrong, but Wifi is a high energy consumption solution.</p>
<p>OBS: if needed, the Raspberry Pi board could be swapped for an Arduino one.</p>
| 0 |
2016-09-27T23:50:25Z
| 39,738,705 |
<p>Cheap, low power and tiny row data? </p>
<p>I suggest you to use nRF 2.4GHz transceiver module. It may look some old school way but will meet with your requirements. </p>
<p>It consumes 0.9 nA while deep-sleep mode and ~10mA for just transmission.</p>
<p>Also it is easy to program and due to its connectionless arch, you will not need to know states about the connection. Just being sure to send and received successfully, suggest you to add deviceId and succeed flag in your raw requests.</p>
<p>Here is vendor site :
<a href="http://www.nordicsemi.com/eng/Products/2.4GHz-RF/nRF24L01" rel="nofollow">http://www.nordicsemi.com/eng/Products/2.4GHz-RF/nRF24L01</a></p>
<p>Good luck!</p>
| 0 |
2016-09-28T05:27:12Z
|
[
"python",
"bluetooth",
"arduino",
"wireless",
"transmission"
] |
Exception: Cannot find PyQt5 plugin directories when using Pyinstaller despite PyQt5 not even being used
| 39,736,000 |
<p>A month ago I solved my applcation freezing issues for Python 2.7 as you can see <a href="http://stackoverflow.com/questions/39135408/using-pyinstaller-on-parmap-causes-a-tkinter-matplotlib-import-error-why">here</a>. I have since adapted my code to python 3.5 (using Anaconda) and it appears to be working. couldn't get pyinstaller working with Anaconda so switched to trying to generate an .exe using the standard Python 3.5 compiler. I am using the same settings as in the link above (<code>pyinstaller --additional-hooks-dir=. --clean --win-private-assemblies pipegui.py</code>), except I get the following error message instead: </p>
<pre><code>`Exception: Cannot find PyQt5 plugin directories`
</code></pre>
<p><a href="http://stackoverflow.com/questions/19207746/using-cx-freeze-in-pyqt5-cant-find-pyqt5">This</a> may be related? Except I'm using Pyinstaller and I don't have a setup.py so don't know how I can make use of the solution there, if at all</p>
<p>I find this error message bizarre because I am not using PyQt5, but PyQt4. Here is the full output:</p>
<pre><code>C:\Users\Cornelis Dirk Haupt\PycharmProjects\Mesoscale-Brain-Explorer\src>pyinstaller --additional-hooks-dir=. --clean --win-private-assemblies pipegui.py
62 INFO: PyInstaller: 3.2
62 INFO: Python: 3.5.0
62 INFO: Platform: Windows-10.0.14393
62 INFO: wrote C:\Users\Cornelis Dirk Haupt\PycharmProjects\Mesoscale-Brain-Explorer\src\pipegui.spec
62 INFO: UPX is not available.
62 INFO: Removing temporary files and cleaning cache in C:\Users\Cornelis Dirk Haupt\AppData\Roaming\pyinstaller
62 INFO: Extending PYTHONPATH with paths
['C:\\Users\\Cornelis Dirk Haupt\\PycharmProjects\\Mesoscale-Brain-Explorer',
'C:\\Users\\Cornelis Dirk '
'Haupt\\PycharmProjects\\Mesoscale-Brain-Explorer\\src']
62 INFO: checking Analysis
62 INFO: Building Analysis because out00-Analysis.toc is non existent
62 INFO: Initializing module dependency graph...
62 INFO: Initializing module graph hooks...
62 INFO: Analyzing base_library.zip ...
1430 INFO: running Analysis out00-Analysis.toc
1727 WARNING: Can not get binary dependencies for file: C:\Anaconda3\api-ms-win-crt-math-l1-1-0.dll
Traceback (most recent call last):
File "c:\users\cornelis dirk haupt\appdata\local\programs\python\python35\lib\site-packages\PyInstaller\depend\bindepend.py", line 695, in getImports
return _getImports_pe(pth)
File "c:\users\cornelis dirk haupt\appdata\local\programs\python\python35\lib\site-packages\PyInstaller\depend\bindepend.py", line 122, in _getImports_pe
dll, _ = sym.forwarder.split('.')
TypeError: a bytes-like object is required, not 'str'
1742 WARNING: Can not get binary dependencies for file: C:\Anaconda3\api-ms-win-crt-runtime-l1-1-0.dll
Traceback (most recent call last):
File "c:\users\cornelis dirk haupt\appdata\local\programs\python\python35\lib\site-packages\PyInstaller\depend\bindepend.py", line 695, in getImports
return _getImports_pe(pth)
File "c:\users\cornelis dirk haupt\appdata\local\programs\python\python35\lib\site-packages\PyInstaller\depend\bindepend.py", line 122, in _getImports_pe
dll, _ = sym.forwarder.split('.')
TypeError: a bytes-like object is required, not 'str'
1742 WARNING: Can not get binary dependencies for file: C:\Anaconda3\api-ms-win-crt-locale-l1-1-0.dll
Traceback (most recent call last):
File "c:\users\cornelis dirk haupt\appdata\local\programs\python\python35\lib\site-packages\PyInstaller\depend\bindepend.py", line 695, in getImports
return _getImports_pe(pth)
File "c:\users\cornelis dirk haupt\appdata\local\programs\python\python35\lib\site-packages\PyInstaller\depend\bindepend.py", line 122, in _getImports_pe
dll, _ = sym.forwarder.split('.')
TypeError: a bytes-like object is required, not 'str'
1758 WARNING: Can not get binary dependencies for file: C:\Anaconda3\api-ms-win-crt-stdio-l1-1-0.dll
Traceback (most recent call last):
File "c:\users\cornelis dirk haupt\appdata\local\programs\python\python35\lib\site-packages\PyInstaller\depend\bindepend.py", line 695, in getImports
return _getImports_pe(pth)
File "c:\users\cornelis dirk haupt\appdata\local\programs\python\python35\lib\site-packages\PyInstaller\depend\bindepend.py", line 122, in _getImports_pe
dll, _ = sym.forwarder.split('.')
TypeError: a bytes-like object is required, not 'str'
1758 WARNING: Can not get binary dependencies for file: C:\Anaconda3\api-ms-win-crt-heap-l1-1-0.dll
Traceback (most recent call last):
File "c:\users\cornelis dirk haupt\appdata\local\programs\python\python35\lib\site-packages\PyInstaller\depend\bindepend.py", line 695, in getImports
return _getImports_pe(pth)
File "c:\users\cornelis dirk haupt\appdata\local\programs\python\python35\lib\site-packages\PyInstaller\depend\bindepend.py", line 122, in _getImports_pe
dll, _ = sym.forwarder.split('.')
TypeError: a bytes-like object is required, not 'str'
1774 WARNING: Can not get binary dependencies for file: C:\Anaconda3\api-ms-win-crt-string-l1-1-0.dll
Traceback (most recent call last):
File "c:\users\cornelis dirk haupt\appdata\local\programs\python\python35\lib\site-packages\PyInstaller\depend\bindepend.py", line 695, in getImports
return _getImports_pe(pth)
File "c:\users\cornelis dirk haupt\appdata\local\programs\python\python35\lib\site-packages\PyInstaller\depend\bindepend.py", line 122, in _getImports_pe
dll, _ = sym.forwarder.split('.')
TypeError: a bytes-like object is required, not 'str'
1774 WARNING: Can not get binary dependencies for file: C:\Anaconda3\api-ms-win-crt-environment-l1-1-0.dll
Traceback (most recent call last):
File "c:\users\cornelis dirk haupt\appdata\local\programs\python\python35\lib\site-packages\PyInstaller\depend\bindepend.py", line 695, in getImports
return _getImports_pe(pth)
File "c:\users\cornelis dirk haupt\appdata\local\programs\python\python35\lib\site-packages\PyInstaller\depend\bindepend.py", line 122, in _getImports_pe
dll, _ = sym.forwarder.split('.')
TypeError: a bytes-like object is required, not 'str'
1774 WARNING: Can not get binary dependencies for file: C:\Anaconda3\api-ms-win-crt-time-l1-1-0.dll
Traceback (most recent call last):
File "c:\users\cornelis dirk haupt\appdata\local\programs\python\python35\lib\site-packages\PyInstaller\depend\bindepend.py", line 695, in getImports
return _getImports_pe(pth)
File "c:\users\cornelis dirk haupt\appdata\local\programs\python\python35\lib\site-packages\PyInstaller\depend\bindepend.py", line 122, in _getImports_pe
dll, _ = sym.forwarder.split('.')
TypeError: a bytes-like object is required, not 'str'
1789 WARNING: Can not get binary dependencies for file: C:\Anaconda3\api-ms-win-crt-filesystem-l1-1-0.dll
Traceback (most recent call last):
File "c:\users\cornelis dirk haupt\appdata\local\programs\python\python35\lib\site-packages\PyInstaller\depend\bindepend.py", line 695, in getImports
return _getImports_pe(pth)
File "c:\users\cornelis dirk haupt\appdata\local\programs\python\python35\lib\site-packages\PyInstaller\depend\bindepend.py", line 122, in _getImports_pe
dll, _ = sym.forwarder.split('.')
TypeError: a bytes-like object is required, not 'str'
1789 WARNING: Can not get binary dependencies for file: C:\Anaconda3\api-ms-win-crt-conio-l1-1-0.dll
Traceback (most recent call last):
File "c:\users\cornelis dirk haupt\appdata\local\programs\python\python35\lib\site-packages\PyInstaller\depend\bindepend.py", line 695, in getImports
return _getImports_pe(pth)
File "c:\users\cornelis dirk haupt\appdata\local\programs\python\python35\lib\site-packages\PyInstaller\depend\bindepend.py", line 122, in _getImports_pe
dll, _ = sym.forwarder.split('.')
TypeError: a bytes-like object is required, not 'str'
1789 WARNING: Can not get binary dependencies for file: C:\Anaconda3\api-ms-win-crt-process-l1-1-0.dll
Traceback (most recent call last):
File "c:\users\cornelis dirk haupt\appdata\local\programs\python\python35\lib\site-packages\PyInstaller\depend\bindepend.py", line 695, in getImports
return _getImports_pe(pth)
File "c:\users\cornelis dirk haupt\appdata\local\programs\python\python35\lib\site-packages\PyInstaller\depend\bindepend.py", line 122, in _getImports_pe
dll, _ = sym.forwarder.split('.')
TypeError: a bytes-like object is required, not 'str'
1805 WARNING: Can not get binary dependencies for file: C:\Anaconda3\api-ms-win-crt-convert-l1-1-0.dll
Traceback (most recent call last):
File "c:\users\cornelis dirk haupt\appdata\local\programs\python\python35\lib\site-packages\PyInstaller\depend\bindepend.py", line 695, in getImports
return _getImports_pe(pth)
File "c:\users\cornelis dirk haupt\appdata\local\programs\python\python35\lib\site-packages\PyInstaller\depend\bindepend.py", line 122, in _getImports_pe
dll, _ = sym.forwarder.split('.')
TypeError: a bytes-like object is required, not 'str'
1805 INFO: Caching module hooks...
1805 INFO: Analyzing C:\Users\Cornelis Dirk Haupt\PycharmProjects\Mesoscale-Brain-Explorer\src\pipegui.py
1992 INFO: Processing pre-find module path hook distutils
2055 INFO: Processing pre-safe import module hook six.moves
3181 INFO: Processing pre-find module path hook site
3181 INFO: site: retargeting to fake-dir 'c:\\users\\cornelis dirk haupt\\appdata\\local\\programs\\python\\python35\\lib\\site-packages\\PyInstaller\\fake-modules'
4298 INFO: Processing pre-safe import module hook win32com
9975 INFO: Loading module hooks...
9975 INFO: Loading module hook "hook-_tkinter.py"...
10121 INFO: checking Tree
10121 INFO: Building Tree because out00-Tree.toc is non existent
10122 INFO: Building Tree out00-Tree.toc
10184 INFO: checking Tree
10184 INFO: Building Tree because out01-Tree.toc is non existent
10185 INFO: Building Tree out01-Tree.toc
10198 INFO: Loading module hook "hook-matplotlib.py"...
10404 INFO: Loading module hook "hook-pywintypes.py"...
10526 INFO: Loading module hook "hook-xml.py"...
10526 INFO: Loading module hook "hook-pydoc.py"...
10527 INFO: Loading module hook "hook-scipy.linalg.py"...
10527 INFO: Loading module hook "hook-scipy.sparse.csgraph.py"...
10529 INFO: Loading module hook "hook-plugins.py"...
10721 INFO: Processing pre-find module path hook PyQt4.uic.port_v3
10726 INFO: Processing pre-find module path hook PyQt4.uic.port_v2
12402 INFO: Loading module hook "hook-OpenGL.py"...
12583 INFO: Loading module hook "hook-PyQt4.QtGui.py"...
12802 INFO: Loading module hook "hook-encodings.py"...
12807 INFO: Loading module hook "hook-PyQt4.uic.py"...
12812 INFO: Loading module hook "hook-PyQt5.QtWidgets.py"...
12813 INFO: Loading module hook "hook-xml.etree.cElementTree.py"...
12813 INFO: Loading module hook "hook-setuptools.py"...
12814 INFO: Loading module hook "hook-scipy.special._ufuncs.py"...
12814 INFO: Loading module hook "hook-PyQt5.QtCore.py"...
Traceback (most recent call last):
File "<string>", line 2, in <module>
ImportError: DLL load failed: The specified procedure could not be found.
Traceback (most recent call last):
File "c:\users\cornelis dirk haupt\appdata\local\programs\python\python35\lib\runpy.py", line 170, in _run_module_as_main
"__main__", mod_spec)
File "c:\users\cornelis dirk haupt\appdata\local\programs\python\python35\lib\runpy.py", line 85, in _run_code
exec(code, run_globals)
File "C:\Users\Cornelis Dirk Haupt\AppData\Local\Programs\Python\Python35\Scripts\pyinstaller.exe\__main__.py", line 9, in <module>
File "c:\users\cornelis dirk haupt\appdata\local\programs\python\python35\lib\site-packages\PyInstaller\__main__.py", line 90, in run
run_build(pyi_config, spec_file, **vars(args))
File "c:\users\cornelis dirk haupt\appdata\local\programs\python\python35\lib\site-packages\PyInstaller\__main__.py", line 46, in run_build
PyInstaller.building.build_main.main(pyi_config, spec_file, **kwargs)
File "c:\users\cornelis dirk haupt\appdata\local\programs\python\python35\lib\site-packages\PyInstaller\building\build_main.py", line 788, in main
build(specfile, kw.get('distpath'), kw.get('workpath'), kw.get('clean_build'))
File "c:\users\cornelis dirk haupt\appdata\local\programs\python\python35\lib\site-packages\PyInstaller\building\build_main.py", line 734, in build
exec(text, spec_namespace)
File "<string>", line 16, in <module>
File "c:\users\cornelis dirk haupt\appdata\local\programs\python\python35\lib\site-packages\PyInstaller\building\build_main.py", line 212, in __init__
self.__postinit__()
File "c:\users\cornelis dirk haupt\appdata\local\programs\python\python35\lib\site-packages\PyInstaller\building\datastruct.py", line 178, in __postinit__
self.assemble()
File "c:\users\cornelis dirk haupt\appdata\local\programs\python\python35\lib\site-packages\PyInstaller\building\build_main.py", line 470, in assemble
module_hook.post_graph()
File "c:\users\cornelis dirk haupt\appdata\local\programs\python\python35\lib\site-packages\PyInstaller\building\imphook.py", line 409, in post_graph
self._load_hook_module()
File "c:\users\cornelis dirk haupt\appdata\local\programs\python\python35\lib\site-packages\PyInstaller\building\imphook.py", line 376, in _load_hook_module
self.hook_module_name, self.hook_filename)
File "c:\users\cornelis dirk haupt\appdata\local\programs\python\python35\lib\site-packages\PyInstaller\compat.py", line 725, in importlib_load_source
return mod_loader.load_module()
File "<frozen importlib._bootstrap_external>", line 385, in _check_name_wrapper
File "<frozen importlib._bootstrap_external>", line 806, in load_module
File "<frozen importlib._bootstrap_external>", line 665, in load_module
File "<frozen importlib._bootstrap>", line 268, in _load_module_shim
File "<frozen importlib._bootstrap>", line 693, in _load
File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 662, in exec_module
File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
File "c:\users\cornelis dirk haupt\appdata\local\programs\python\python35\lib\site-packages\PyInstaller\hooks\hook-PyQt5.QtCore.py", line 15, in <module>
binaries = qt_plugins_binaries('codecs', namespace='PyQt5')
File "c:\users\cornelis dirk haupt\appdata\local\programs\python\python35\lib\site-packages\PyInstaller\utils\hooks\qt.py", line 64, in qt_plugins_binaries
pdir = qt_plugins_dir(namespace=namespace)
File "c:\users\cornelis dirk haupt\appdata\local\programs\python\python35\lib\site-packages\PyInstaller\utils\hooks\qt.py", line 38, in qt_plugins_dir
raise Exception('Cannot find {0} plugin directories'.format(namespace))
Exception: Cannot find PyQt5 plugin directories
</code></pre>
<p>I will say I also have no clue what to make of the <code>TypeError: a bytes-like object is required, not 'str'</code><a href="http://stackoverflow.com/questions/33054527/python-3-5-typeerror-a-bytes-like-object-is-required-not-str">This</a> may be related? I only use binary mode with pickle a handful of times as far as I can tell this is my only usage:</p>
<pre><code>pickle.dump( roiState, open( fileName, "wb" ) )
roiState = pickle.load(open(fileName, "rb"))
</code></pre>
<p>I don't have any errors when I run the application, only getting these errors when trying to generate an .exe using pyinstaller. Why?</p>
<p>Note also that Anaconda3 does pop up in the traceback above (why is it looking for binaries there?) but I:</p>
<ol>
<li>Uninstalled pyinstaller from Anaconda</li>
<li>Am using the standard Python 3.5 (64-bit) compiler</li>
</ol>
<p>Only thing I can think of that may be the culprit is that I'm no longer using the developer version of Pyinstaller (it just flat does not run in Python 3.5). I had to use the developer version to solve my freezing issue <a href="http://stackoverflow.com/questions/39135408/using-pyinstaller-on-parmap-causes-a-tkinter-matplotlib-import-error-why">here</a> when my code was written for python 2.7</p>
| 2 |
2016-09-27T23:51:55Z
| 39,823,782 |
<p>Uninstall Anaconda and everything works... I conclude that you simply cannot have Anaconda installed and use the standard Python 3.5 compiler at the same time if you're using Pyinstaller. Maybe <a href="http://stackoverflow.com/questions/39728108/running-pyinstaller-after-anaconda-install-results-in-importerror-no-module-nam">this</a> is related. </p>
<p>This is not the <a href="http://stackoverflow.com/a/37398710/2734863">first</a> time that uninstalling Anaconda appears to solve my issues... If I should report this issue somewhere please comment below. I don't know where.</p>
| 0 |
2016-10-03T02:19:36Z
|
[
"python",
"python-2.7",
"python-3.x",
"pyinstaller"
] |
Python : Extract one string from 100 lines of text
| 39,736,110 |
<ol>
<li><p>I need to extract a particular string from 100 lines of log data. I
tried split and then tried to get the needed string but couldn't
succeed. Any suggestions/help appreciated. Thanks!</p>
<p>In the log below, I would like to extract the highlighted part, that
is
<strong>zqn.2005- 04.com.sanblaze:virtualun.init74-2.initiator-00000000-0000</strong> (its in line 57)</p>
<pre><code>1 Out[19]:
2 {'portstatus': {'errors': {'busy_errors': '0',
3 'checkcondition_errors': '0',
4 'compare_errors': '0',
5 'ioc_errors': '0',
6 'notready_errors': '0',
7 'read_errors': '0',
8 'read_retries': '0',
9 'scsi_errors': '0',
10 'test_errors': '0',
11 'timeout_errors': '0',
12 'write_errors': '0',
13 'write_retries': '0'},
14 'net_counters': {'RxBytes': '148476788547060',
15 'RxCompressed': '0',
16 'RxDrop': '96188',
17 'RxErrs': '0',
18 'RxFIFO': '0',
19 'RxFrame': '0',
20 'RxMulticast': '259513',
21 'RxPFCPause': '0',
22 'RxPackets': '77165581759',
23 'RxStandardPause': '0',
24 'TxBytes': '20440169002909',
25 'TxCompressed': '0',
26 'TxDrop': '0',
27 'TxErrs': '0',
28 'TxFIFO': '0',
29 'TxFrame': '0',
30 'TxMulticast': '0',
31 'TxPFCPause': '0',
32 'TxPackets': '55075507366',
33 'TxStandardPause': '5349727',
34 'net_avgriops': '0',
35 'net_avgrrate': '0.00',
36 'net_avgtiops': '0',
37 'net_avgtrate': '0.00',
38 'net_riops': '0',
39 'net_rrate': '0.00',
40 'net_tiops': '0',
41 'net_trate': '0.00'},
42 'perfdata': {'avg_oiocnt': '0',
43 'avgiops': '0',
44 'avgriops': '0',
45 'avgrrate': '0.00',
46 'avgtrate': '0.00',
47 'avgwiops': '0',
48 'avgwrate': '0.00',
49 'iops': '0',
50 'max_oiocnt': '509',
51 'oiocnt': '0',
52 'riops': '0',
53 'rrate': '0.00',
54 'trate': '0.00',
55 'wiops': '0',
56 'wrate': '0.00'},
57 'status': {'initiator0_iqn': 'zqn.2005- 04.com.sanblaze:virtualun.init74-2.initiator-00000000-0000',
58 'initiator10_iqn': 'zqn.2005-04.com.sanblaze:virtualun.init74-2.initiator-00000000-0010',
59 'initiator11_iqn': 'iqn.2003-04.com.sanblaze:virtualun.init74-2.initiator-00000000-0011',
60 'initiator12_iqn': 'iqn.2003-04.com.sanblaze:virtualun.init74-2.initiator-00000000-0012',
61 'initiator13_iqn': 'iqn.2003-04.com.sanblaze:virtualun.init74-2.initiator-00000000-0013',
62 'initiator14_iqn': 'iqn.2003-04.com.sanblaze:virtualun.init74-2.initiator-00000000-0014',
63 'initiator15_iqn': 'iqn.2003-04.com.sanblaze:virtualun.init74-2.initiator-00000000-0015',
64 'initiator16_iqn': 'iqn.2003-04.com.sanblaze:virtualun.init74-2.initiator-00000000-0016',
65 'initiator17_iqn': 'iqn.2003-04.com.sanblaze:virtualun.init74-2.initiator-00000000-0017',
66 'initiator18_iqn': 'iqn.2003-04.com.sanblaze:virtualun.init74-2.initiator-00000000-0018',
67 'initiator19_iqn': 'iqn.2003-04.com.sanblaze:virtualun.init74-2.initiator-00000000-0019',
68 'initiator1_iqn': 'iqn.2003-04.com.sanblaze:virtualun.init74-2.initiator-00000000-0001',
69 'initiator20_iqn': 'iqn.2003-04.com.sanblaze:virtualun.init74-2.initiator-00000000-0020',
70 'initiator21_iqn': 'iqn.2003-04.com.sanblaze:virtualun.init74-2.initiator-00000000-0021',
71 'initiator22_iqn': 'iqn.2003-04.com.sanblaze:virtualun.init74-2.initiator-00000000-0022',
72 'initiator23_iqn': 'iqn.2003-04.com.sanblaze:virtualun.init74-2.initiator-00000000-0023',
73 'initiator24_iqn': 'iqn.2003-04.com.sanblaze:virtualun.init74-2.initiator-00000000-0024',
74 'initiator25_iqn': 'iqn.2003-04.com.sanblaze:virtualun.init74-2.initiator-00000000-0025',
75 'initiator26_iqn': 'iqn.2003-04.com.sanblaze:virtualun.init74-2.initiator-00000000-0026',
76 'initiator27_iqn': 'iqn.2003-04.com.sanblaze:virtualun.init74-2.initiator-00000000-0027',
77 'initiator28_iqn': 'iqn.2003-04.com.sanblaze:virtualun.init74-2.initiator-00000000-0028',
78 'initiator29_iqn': 'iqn.2003-04.com.sanblaze:virtualun.init74-2.initiator-00000000-0029',
79 'initiator2_iqn': 'iqn.2003-04.com.sanblaze:virtualun.init74-2.initiator-00000000-0002',
80 'initiator30_iqn': 'iqn.2003-04.com.sanblaze:virtualun.init74-2.initiator-00000000-0030',
81 'initiator31_iqn': 'iqn.2003-04.com.sanblaze:virtualun.init74-2.initiator-00000000-0031',
82 'initiator32_iqn': 'iqn.2003-04.com.sanblaze:virtualun.init74-2.initiator-00000000-0032',
83 'initiator33_iqn': 'iqn.2003-04.com.sanblaze:virtualun.init74-2.initiator-00000000-0033',
84 'initiator34_iqn': 'iqn.2003-04.com.sanblaze:virtualun.init74-2.initiator-00000000-0034',
85 'initiator35_iqn': 'iqn.2003-04.com.sanblaze:virtualun.init74-2.initiator-00000000-0035',
86 'initiator36_iqn': 'iqn.2003-04.com.sanblaze:virtualun.init74-2.initiator-00000000-0036',
87 'initiator37_iqn': 'iqn.2003-04.com.sanblaze:virtualun.init74-2.initiator-00000000-0037',
88 'initiator38_iqn': 'iqn.2003-04.com.sanblaze:virtualun.init74-2.initiator-00000000-0038',
89 'initiator39_iqn': 'iqn.2003-04.com.sanblaze:virtualun.init74-2.initiator-00000000-0039',
90 'initiator3_iqn': 'iqn.2003-04.com.sanblaze:virtualun.init74-2.initiator-00000000-0003',
91 'initiator40_iqn': 'iqn.2003-04.com.sanblaze:virtualun.init74-2.initiator-00000000-0040',
92 'initiator41_iqn': 'iqn.2003-04.com.sanblaze:virtualun.init74-2.initiator-00000000-0041',
93 'initiator42_iqn': 'iqn.2003-04.com.sanblaze:virtualun.init74-2.initiator-00000000-0042',
94 'initiator43_iqn': 'iqn.2003-04.com.sanblaze:virtualun.init74-2.initiator-00000000-0043',
95 'mode': 'Init',
96 'numinitiators': '50',
97 'numtargets': '0',
98 'port': '0',
99 'portwwnn': '90:e2:ba:82:92:1c',
100 'portwwpn': '90:e2:ba:82:92:1c',
101 'speed': '10G',
102 'state': 'Online',
103 'topo': 'iSCSI'},
104 'sympn': '-',
</code></pre></li>
</ol>
| -1 |
2016-09-28T00:08:30Z
| 39,736,155 |
<p>Looks like the string is in dictionary format (correct me if I'm wrong), so you could try converting it to one. Then you won't need regex.</p>
<pre><code>import ast
your_dict = ast.literal_eval(your_string)
</code></pre>
<p>Then what you want would be: </p>
<pre><code>your_dict['status']['initiator0_iqn']
</code></pre>
| 1 |
2016-09-28T00:13:48Z
|
[
"python",
"regex",
"logging"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.