title
stringlengths 10
172
| question_id
int64 469
40.1M
| question_body
stringlengths 22
48.2k
| question_score
int64 -44
5.52k
| question_date
stringlengths 20
20
| answer_id
int64 497
40.1M
| answer_body
stringlengths 18
33.9k
| answer_score
int64 -38
8.38k
| answer_date
stringlengths 20
20
| tags
sequence |
---|---|---|---|---|---|---|---|---|---|
Python searching through columns | 40,008,998 | <p>I have a CSV file that I need to loop through in a specific pattern for specific columns and have the output patterns be stored in new files with the same name + "_pattern" + [1,2,3,etc.] + .csv.</p>
<p>This is the search pattern: Loop through column 1 and find the same # and grab them, then loop through column 2 of the grabbed list and then grab all that have the same date in column 2, then go to column 4 and grab all #s that are NOT the same, and then create a file with the pattern from column 1 and 2 and 4 organized by column time.</p>
<p>Example: </p>
<pre class="lang-none prettyprint-override"><code>1 2 time 4
13.45 9/29/2016 6:00 98765
12.56 9/29/2016 6:05 76548
13.45 9/29/2016 6:07 98764
13.45 9/29/2016 6:21 98766
13.45 9/29/2016 6:20 96765
12.56 9/29/2016 6:06 76553
</code></pre>
<p><a href="https://i.stack.imgur.com/OqxcG.jpg" rel="nofollow">Better view of table</a></p>
<p>The result would be, file_pattern_1.csv would have:</p>
<pre class="lang-none prettyprint-override"><code>1. 13.45 9/29/2016 6:00 98765
2. 13.45 9/29/2016 6:07 98764
3. 13.45 9/29/2016 6:21 98766
</code></pre>
<p>But would not include:</p>
<pre class="lang-none prettyprint-override"><code>4. 13.45 9/29/2016 6:20 96765
</code></pre>
<p>Because column 4 repeats from a previous entry, file_pattern_2.csv would have:</p>
<pre class="lang-none prettyprint-override"><code>1. 12.56 9/29/2016 6:05 76548
2. 12.56 9/29/2016 6:06 76553
</code></pre>
<p>This is what I have so far but I have become lost on the looping logic:</p>
<pre><code>import os
infile = raw_input("Which file are we working with? ")
assert os.path.exists(infile), "Path is incorrect."
os.chdir(infile)
def createFile(csvFile, fileName):
with open (fileName, 'wb') as ftext:
ftext.write(csvFile)
def appendFile(csvFile, fileName):
with open (fileName, 'a') as ftext:
ftext.write(csvFile)
def setfilename(tread):
fileName = tread[0:tread.index('.')] + '_patterns' + str(countItem) + '.csv'
return fileName
for i in pcolumn:
if pcolumn == pcolumn:
return pfile
for x in date:
if date == date:
return date
for a in acolumn:
if acolumn != acolumn:
createFile(fileName)
else:
print "Finished."
</code></pre>
| 3 | 2016-10-12T21:53:05Z | 40,110,795 | <p>As you loop over your files you need to keep a record of which patterns are not eligible for saving. You could use a <code>set</code> for this purpose. To group your entries in each file you could use <code>itertools.groupby</code>. Using your example:</p>
<pre class="lang-python prettyprint-override"><code>import itertools
f = [i.split(" ") for i in """1 2 time 4
13.45 9/29/2016 6:00 98765
12.56 9/29/2016 6:05 76548
13.45 9/29/2016 6:07 98764
13.45 9/29/2016 6:21 98766
13.45 9/29/2016 6:20 96765
12.56 9/29/2016 6:06 76553""".split("\n")[1:]]
seen_patterns = set([('9/29/2016', '96765')]) # You need to add entries to this set which you want to exclude
# Sort and group your entries by the first and second columns
col1 = itertools.groupby(sorted(f, key=lambda x: (x[0], x[1])), key=lambda x: (x[0], x[1]))
for k, v in col1:
v = list(v)
# Filter out patterns which are not allowed
to_save = [" ".join(i) for i in v if (i[1], i[3]) not in seen_patterns]
for i in to_save:
print i # Save this to an appropriate file
print
>>>
12.56 9/29/2016 6:05 76548
12.56 9/29/2016 6:06 76553
13.45 9/29/2016 6:00 98765
13.45 9/29/2016 6:07 98764
13.45 9/29/2016 6:21 98766
</code></pre>
<p>As a further suggestion, have a look at the <code>glob</code> module for collecting file paths from directories, it is really useful. </p>
| 0 | 2016-10-18T14:21:19Z | [
"python",
"loops",
"csv"
] |
Python searching through columns | 40,008,998 | <p>I have a CSV file that I need to loop through in a specific pattern for specific columns and have the output patterns be stored in new files with the same name + "_pattern" + [1,2,3,etc.] + .csv.</p>
<p>This is the search pattern: Loop through column 1 and find the same # and grab them, then loop through column 2 of the grabbed list and then grab all that have the same date in column 2, then go to column 4 and grab all #s that are NOT the same, and then create a file with the pattern from column 1 and 2 and 4 organized by column time.</p>
<p>Example: </p>
<pre class="lang-none prettyprint-override"><code>1 2 time 4
13.45 9/29/2016 6:00 98765
12.56 9/29/2016 6:05 76548
13.45 9/29/2016 6:07 98764
13.45 9/29/2016 6:21 98766
13.45 9/29/2016 6:20 96765
12.56 9/29/2016 6:06 76553
</code></pre>
<p><a href="https://i.stack.imgur.com/OqxcG.jpg" rel="nofollow">Better view of table</a></p>
<p>The result would be, file_pattern_1.csv would have:</p>
<pre class="lang-none prettyprint-override"><code>1. 13.45 9/29/2016 6:00 98765
2. 13.45 9/29/2016 6:07 98764
3. 13.45 9/29/2016 6:21 98766
</code></pre>
<p>But would not include:</p>
<pre class="lang-none prettyprint-override"><code>4. 13.45 9/29/2016 6:20 96765
</code></pre>
<p>Because column 4 repeats from a previous entry, file_pattern_2.csv would have:</p>
<pre class="lang-none prettyprint-override"><code>1. 12.56 9/29/2016 6:05 76548
2. 12.56 9/29/2016 6:06 76553
</code></pre>
<p>This is what I have so far but I have become lost on the looping logic:</p>
<pre><code>import os
infile = raw_input("Which file are we working with? ")
assert os.path.exists(infile), "Path is incorrect."
os.chdir(infile)
def createFile(csvFile, fileName):
with open (fileName, 'wb') as ftext:
ftext.write(csvFile)
def appendFile(csvFile, fileName):
with open (fileName, 'a') as ftext:
ftext.write(csvFile)
def setfilename(tread):
fileName = tread[0:tread.index('.')] + '_patterns' + str(countItem) + '.csv'
return fileName
for i in pcolumn:
if pcolumn == pcolumn:
return pfile
for x in date:
if date == date:
return date
for a in acolumn:
if acolumn != acolumn:
createFile(fileName)
else:
print "Finished."
</code></pre>
| 3 | 2016-10-12T21:53:05Z | 40,111,537 | <p>The following should do what you need. It reads a csv file in and generates a matching <code>datetime</code> for each of the entries to allow them to be correctly sorted. It creates output csv files based on the pattern number with the entries sorted by date. Column 4 entries already seen are omitted:</p>
<pre><code>from itertools import groupby
from datetime import datetime
import csv
import os
filename = 'my_data.csv'
data = []
with open(filename, 'rb') as f_input:
csv_input = csv.reader(f_input, delimiter='\t')
header = next(csv_input)
for row in csv_input:
dt = datetime.strptime('{} {}'.format(row[2], row[1]), '%H:%M %m/%d/%Y')
data.append([dt] + row)
for index, (k, g) in enumerate(groupby(sorted(data, key=lambda x: x[1]), key=lambda x: x[1]), start=1):
line = 1
seen = set()
with open('{}_pattern_{}.csv'.format(os.path.splitext(filename)[0], index), 'wb') as f_output:
csv_output = csv.writer(f_output)
for item in sorted(g, key=lambda x: x[0]):
if item[4] not in seen:
seen.add(item[4])
csv_output.writerow([line] + item[1:])
line += 1
</code></pre>
| 0 | 2016-10-18T14:52:46Z | [
"python",
"loops",
"csv"
] |
Finding index by iterating over each row of matrix | 40,009,008 | <p>I have an numpy array 'A' of size <code>5000x10</code>. I also have another number <code>'Num'</code>. I want to apply the following to each row of A:</p>
<pre><code>import numpy as np
np.max(np.where(Num > A[0,:]))
</code></pre>
<p>Is there a pythonic way than writing a for loop for above.</p>
| 1 | 2016-10-12T21:54:09Z | 40,009,044 | <p>You could use <code>argmax</code> -</p>
<pre><code>A.shape[1] - 1 - (Num > A)[:,::-1].argmax(1)
</code></pre>
<p>Alternatively with <code>cumsum</code> and <code>argmax</code> -</p>
<pre><code>(Num > A).cumsum(1).argmax(1)
</code></pre>
<p><strong>Explanation :</strong> With <code>np.max(np.where(..)</code>, we are basically looking to get the last occurrence of matches along each row on the comparison.</p>
<p>For the same, we can use <code>argmax</code>. But, <code>argmax</code> on a boolean array gives us the first occurrence and not the last one. So, one trick is to perform the comparison and flip the columns with <code>[:,::-1]</code> and then use <code>argmax</code>. The column indices are then subtracted by the number of cols in the array to make it trace back to the original order.</p>
<p>On the second approach, it's very similar to a <a href="http://stackoverflow.com/a/39959511/3293881"><code>related post</code></a> and therefore quoting from it :</p>
<p>One of the uses of argmax is to get ID of the first occurence of the max element along an axis in an array . So, we get the cumsum along the rows and get the first max ID, which represents the last non-zero elem. This is because cumsum on the leftover elements won't increase the sum value after that last non-zero element.</p>
| 2 | 2016-10-12T21:56:59Z | [
"python",
"numpy",
"vectorization"
] |
Ho to use if Function? | 40,009,011 | <p>I have been making a text-based RPG in python 3.5. I had it fine (or so i thought...) until i tried to say that no I did not want to play. And also when I wanted to make the option to run from Mobs, but instead it combines both if functions, and says the amount of damage AND that you 'Ran away.' I tried to switch around some code but that made it even worse! I need help.
</p>
<pre><code>import time
import random
import sys
import time
global gold
global player_HP
global Mob_HP_1
global Mob_HP_2
global Mob_HP_3
global Mob_HP_0
mob_HP_1 = 100
mob_HP_2 = 125
mob_HP_3 = 130
gold = 0
def Demon_attack():
global Mob_HP_3
Mob_HP_3 = 130
global gold
attack_damage=random.randint(50,200)
rewards=random.randint(1,5)
print('You do')
print(attack_damage)
print('damage!')
Mob_HP_3 = Mob_HP_3 - attack_damage
if Mob_HP_3 < 0:
print ('You killed the')
print ('Demon!')
if Mob_HP_3 > 0:
print('The Demon has')
print(Mob_HP_3)
print('HP left!')
choice_attack_3 = input('Do you attack?')
if choice_attack_3 == 'A'or 'a':
Demon_attack()
if choice_attack_3 == 'R' or 'r':
print('You run away!')
time.sleep (2)
battle_start()
time.sleep (3)
gold=gold+rewards
print('You have')
print(gold)
print('Gold!')
battle_start()
def Headless_Horseman_attack():
global Mob_HP_2
Mob_HP_2 = 125
global gold
attack_damage=random.randint(50,200)
rewards=random.randint(1,5)
print('You do')
print(attack_damage)
print('damage!')
Mob_HP_2 = Mob_HP_2 - attack_damage
if Mob_HP_2 < 0:
print ('You killed the')
print ('Headless Horseman')
if Mob_HP_2 > 0:
print('The Headless Horseman has')
print(Mob_HP_2)
print('HP left!')
choice_attack_2 = input('Do you attack?')
if choice_attack_2 == 'A' or 'a':
Headless_Horseman_attack()
if choice_attack_2 == 'R' or 'r':
print('You run away!')
time.sleep (2)
battle_start()
time.sleep (2)
gold=gold+rewards
print ('You have')
print(gold)
print('Gold!')
battle_start()
def Zombie_attack():
global Mob_HP_1
Mob_HP_1 = 100
global gold
attack_damage=random.randint(50,200)
rewards=random.randint(0,5)
print('You do')
print(attack_damage)
print('damage!')
Mob_HP_1 = Mob_HP_1 - attack_damage
if Mob_HP_1 < 0:
print ('You killed the')
print ('Zombie!')
if Mob_HP_1 > 0:
print('The Headless Horseman has')
print(Mob_HP_1)
print('HP left!')
choice_attack_1 = input('Do you attack?')
if choice_attack_1 == 'A' or 'a':
Zombie_attack()
if choice_attack_1 == 'R' or 'r':
print('You run away!')
time.sleep (2)
battle_start()
time.sleep (1.5)
gold=gold+rewards
print('You have')
print(gold)
print('Gold!')
battle_start()
def battle_start():
global gold
if gold > 50:
print ('You have killed all the monsters!')
play = input('Do you want to play again? Y/N?')
if choice == 'Y' or 'y':
game_start()
if choice == 'N' or 'a':
print ('Okay, battle later')
time.sleep(4)
sys.exit(0)
time.sleep (3)
attack_damage=random.randint(50,200)
rewards=random.randint(1,3)
mob=random.randint(1,3)
if mob==1:
mob_alive = True
print('You ran into a Zombie!')
print('The Zombie has 100 HP!')
choice_attack_1 = input('Do you attack?')
if choice_attack_1 == 'A' or 'a':
Zombie_attack()
if choice_attack_1 == 'R' or 'r':
print('You run away!')
time.sleep (2)
battle_start()
if mob==2:
mob_alive = True
print('You ran into a Headless Horseman!')
print('The Headless Horseman has 125 HP!')
choice_attack_2 = input('Do you attack?')
if choice_attack_2 == 'A' or 'a':
Headless_Horseman_attack()
if choice_attack_2 == 'R' or 'r':
print('You run away!')
time.sleep (2)
battle_start()
if mob==3:
mob_alive = True
print('You ran into a Demon!')
print('The Demon has 130 HP!')
choice_attack_3 = input('Do you attack?')
if choice_attack_3 == 'A' or 'a':
Demon_attack()
if choice_attack_3 == 'R' or 'r':
print('You run away!')
time.sleep (2)
battle_start()
def game_start():
global gold
global Mob_HP_0
Mob_HP_0 = 25
print('You have to get 50 Gold to win!')
attack_damage=random.randint(50,200)
rewards=random.randint(1,3)
print('To Attack, type "A". To Run Away, type "R". Lets pratice...')
print('Pratice Mob has 25 HP!')
choice_attack = input('Do you attack?')
if choice_attack == 'A' or 'a':
print('You do')
print(attack_damage)
print('damage!')
Mob_HP_0 = Mob_HP_0 - attack_damage
if choice_attack == 'R' or 'r':
print('You ran away!')
time.sleep (2)
game_start()
time.sleep (1.5)
gold = gold + rewards
print('You have ')
print(gold)
print('gold!')
print ('Good job')
print ('Lets start the battle...')
battle_start()
print ('Welcome to Battle Deongeons')
myName = input('Whats your name?')
print ('Ok ' + myName + ' you need to kill monsters... Be careful though, its capital Sentsive.')
choice = input("Do you want to play? Y/N")
if choice == "Y" or "y":
print('Lets start the Battle')
game_start()
if choice == "N" or "n":
print ('Okay, battle later')
time.sleep (4)
sys.exit(0)
</code></pre>
| -3 | 2016-10-12T21:54:16Z | 40,009,033 | <pre><code> if choice_attack_3 == 'A'or choice_attack_3 == 'a':
Demon_attack()
elif choice_attack_3 == 'R' or choice_attack_3 == 'r':
print('You run away!')
time.sleep (2)
battle_start()
</code></pre>
<p>You need to add choice_attack_3 == on the other side of your <code>or</code> statement. <code>'a'</code> by itself is technically true so it is entering both if statements. </p>
<p>Edit: same with</p>
<pre><code>if choice == "Y" or choice == "y":
print('Lets start the Battle')
game_start()
if choice == "N" or choice == "n":
</code></pre>
| 0 | 2016-10-12T21:56:10Z | [
"python"
] |
Ho to use if Function? | 40,009,011 | <p>I have been making a text-based RPG in python 3.5. I had it fine (or so i thought...) until i tried to say that no I did not want to play. And also when I wanted to make the option to run from Mobs, but instead it combines both if functions, and says the amount of damage AND that you 'Ran away.' I tried to switch around some code but that made it even worse! I need help.
</p>
<pre><code>import time
import random
import sys
import time
global gold
global player_HP
global Mob_HP_1
global Mob_HP_2
global Mob_HP_3
global Mob_HP_0
mob_HP_1 = 100
mob_HP_2 = 125
mob_HP_3 = 130
gold = 0
def Demon_attack():
global Mob_HP_3
Mob_HP_3 = 130
global gold
attack_damage=random.randint(50,200)
rewards=random.randint(1,5)
print('You do')
print(attack_damage)
print('damage!')
Mob_HP_3 = Mob_HP_3 - attack_damage
if Mob_HP_3 < 0:
print ('You killed the')
print ('Demon!')
if Mob_HP_3 > 0:
print('The Demon has')
print(Mob_HP_3)
print('HP left!')
choice_attack_3 = input('Do you attack?')
if choice_attack_3 == 'A'or 'a':
Demon_attack()
if choice_attack_3 == 'R' or 'r':
print('You run away!')
time.sleep (2)
battle_start()
time.sleep (3)
gold=gold+rewards
print('You have')
print(gold)
print('Gold!')
battle_start()
def Headless_Horseman_attack():
global Mob_HP_2
Mob_HP_2 = 125
global gold
attack_damage=random.randint(50,200)
rewards=random.randint(1,5)
print('You do')
print(attack_damage)
print('damage!')
Mob_HP_2 = Mob_HP_2 - attack_damage
if Mob_HP_2 < 0:
print ('You killed the')
print ('Headless Horseman')
if Mob_HP_2 > 0:
print('The Headless Horseman has')
print(Mob_HP_2)
print('HP left!')
choice_attack_2 = input('Do you attack?')
if choice_attack_2 == 'A' or 'a':
Headless_Horseman_attack()
if choice_attack_2 == 'R' or 'r':
print('You run away!')
time.sleep (2)
battle_start()
time.sleep (2)
gold=gold+rewards
print ('You have')
print(gold)
print('Gold!')
battle_start()
def Zombie_attack():
global Mob_HP_1
Mob_HP_1 = 100
global gold
attack_damage=random.randint(50,200)
rewards=random.randint(0,5)
print('You do')
print(attack_damage)
print('damage!')
Mob_HP_1 = Mob_HP_1 - attack_damage
if Mob_HP_1 < 0:
print ('You killed the')
print ('Zombie!')
if Mob_HP_1 > 0:
print('The Headless Horseman has')
print(Mob_HP_1)
print('HP left!')
choice_attack_1 = input('Do you attack?')
if choice_attack_1 == 'A' or 'a':
Zombie_attack()
if choice_attack_1 == 'R' or 'r':
print('You run away!')
time.sleep (2)
battle_start()
time.sleep (1.5)
gold=gold+rewards
print('You have')
print(gold)
print('Gold!')
battle_start()
def battle_start():
global gold
if gold > 50:
print ('You have killed all the monsters!')
play = input('Do you want to play again? Y/N?')
if choice == 'Y' or 'y':
game_start()
if choice == 'N' or 'a':
print ('Okay, battle later')
time.sleep(4)
sys.exit(0)
time.sleep (3)
attack_damage=random.randint(50,200)
rewards=random.randint(1,3)
mob=random.randint(1,3)
if mob==1:
mob_alive = True
print('You ran into a Zombie!')
print('The Zombie has 100 HP!')
choice_attack_1 = input('Do you attack?')
if choice_attack_1 == 'A' or 'a':
Zombie_attack()
if choice_attack_1 == 'R' or 'r':
print('You run away!')
time.sleep (2)
battle_start()
if mob==2:
mob_alive = True
print('You ran into a Headless Horseman!')
print('The Headless Horseman has 125 HP!')
choice_attack_2 = input('Do you attack?')
if choice_attack_2 == 'A' or 'a':
Headless_Horseman_attack()
if choice_attack_2 == 'R' or 'r':
print('You run away!')
time.sleep (2)
battle_start()
if mob==3:
mob_alive = True
print('You ran into a Demon!')
print('The Demon has 130 HP!')
choice_attack_3 = input('Do you attack?')
if choice_attack_3 == 'A' or 'a':
Demon_attack()
if choice_attack_3 == 'R' or 'r':
print('You run away!')
time.sleep (2)
battle_start()
def game_start():
global gold
global Mob_HP_0
Mob_HP_0 = 25
print('You have to get 50 Gold to win!')
attack_damage=random.randint(50,200)
rewards=random.randint(1,3)
print('To Attack, type "A". To Run Away, type "R". Lets pratice...')
print('Pratice Mob has 25 HP!')
choice_attack = input('Do you attack?')
if choice_attack == 'A' or 'a':
print('You do')
print(attack_damage)
print('damage!')
Mob_HP_0 = Mob_HP_0 - attack_damage
if choice_attack == 'R' or 'r':
print('You ran away!')
time.sleep (2)
game_start()
time.sleep (1.5)
gold = gold + rewards
print('You have ')
print(gold)
print('gold!')
print ('Good job')
print ('Lets start the battle...')
battle_start()
print ('Welcome to Battle Deongeons')
myName = input('Whats your name?')
print ('Ok ' + myName + ' you need to kill monsters... Be careful though, its capital Sentsive.')
choice = input("Do you want to play? Y/N")
if choice == "Y" or "y":
print('Lets start the Battle')
game_start()
if choice == "N" or "n":
print ('Okay, battle later')
time.sleep (4)
sys.exit(0)
</code></pre>
| -3 | 2016-10-12T21:54:16Z | 40,009,116 | <p>This is a very poor question, but is a result of you not understanding boolean logic rather than if statements.</p>
<pre><code>If choice == "Y" or "y":
</code></pre>
<p>is always true. That expands to </p>
<pre><code>If choice == "Y" or If "y":
</code></pre>
<p>you either need to do a case insensitive comparison (if choice.lower() = "y"), a list comparison (if choice in "Yy") or explicitly state both conditions on eiterh side of your or (if choice == "y" or choice == "Y"</p>
| 1 | 2016-10-12T22:03:06Z | [
"python"
] |
How is python storing strings so that the 'is' operator works on literals? | 40,009,015 | <p>In python </p>
<pre><code>>>> a = 5
>>> a is 5
True
</code></pre>
<p>but </p>
<pre><code>>>> a = 500
>>> a is 500
False
</code></pre>
<p>This is because it stores low integers as a single address. But once the numbers begin to be complex, each int gets its own unique address space. This makes sense to me.</p>
<blockquote>
<p>The current implementation keeps an array of integer objects for all integers between -5 and 256, when you create an int in that range you actually just get back a reference to the existing object. </p>
</blockquote>
<p>So now, why does this not apply to strings? Are not strings just as complex as large integers (if not moreso)?</p>
<pre><code>>>> a = '1234567'
>>> a is '1234567'
True
</code></pre>
<p>How does python use the same address for all string literals efficiently? It cant keep an array of every possible string like it does for numbers.</p>
| 5 | 2016-10-12T21:54:26Z | 40,009,138 | <p>It's an optimisation technique called interning. CPython recognises the <a href="https://github.com/python/cpython/blob/c21f17c6e9d3218812b593f6ec5647e91c16896b/Objects/codeobject.c#L59" rel="nofollow">equal values of <strong>string constants</strong></a> and doesn't allocate extra memory for new instances but simply points to the same one (interns it), giving both the same <code>id()</code>. </p>
<p>One can play around to confirm that only constants are treated this way (simple operations like <code>b</code> are recognised):</p>
<pre><code># Two string constants
a = "aaaa"
b = "aa" + "aa"
# Prevent interpreter from figuring out string constant
c = "aaa"
c += "a"
print id(a) # 4509752320
print id(b) # 4509752320
print id(c) # 4509752176 !!
</code></pre>
<p>However you can manually force a string to be mapped to an already existing one using <a href="https://docs.python.org/2/library/functions.html#intern" rel="nofollow"><code>intern()</code></a>:</p>
<pre><code>c = intern(c)
print id(a) # 4509752320
print id(b) # 4509752320
print id(c) # 4509752320 !!
</code></pre>
<p>Other interpreters may do it differently. Since strings are immutable, changing one of the two will not change the other.</p>
| 3 | 2016-10-12T22:04:21Z | [
"python",
"string"
] |
How is python storing strings so that the 'is' operator works on literals? | 40,009,015 | <p>In python </p>
<pre><code>>>> a = 5
>>> a is 5
True
</code></pre>
<p>but </p>
<pre><code>>>> a = 500
>>> a is 500
False
</code></pre>
<p>This is because it stores low integers as a single address. But once the numbers begin to be complex, each int gets its own unique address space. This makes sense to me.</p>
<blockquote>
<p>The current implementation keeps an array of integer objects for all integers between -5 and 256, when you create an int in that range you actually just get back a reference to the existing object. </p>
</blockquote>
<p>So now, why does this not apply to strings? Are not strings just as complex as large integers (if not moreso)?</p>
<pre><code>>>> a = '1234567'
>>> a is '1234567'
True
</code></pre>
<p>How does python use the same address for all string literals efficiently? It cant keep an array of every possible string like it does for numbers.</p>
| 5 | 2016-10-12T21:54:26Z | 40,009,292 | <p>It doesn't store an array of all possible strings, instead it has a hash table which point to memory addresses of all currently declared strings, indexed by the hash of the string.</p>
<p>For example</p>
<p>when you say <code>a = 'foo'</code>, it first hashes the string <code>foo</code> and checks if an entry already exists in the hash table. If yes, then variable <code>a</code> now references that address. </p>
<p>If no entry is found in the table, python allocates memory to store the string, hashes <code>foo</code> and adds an entry in the table with the address of the allocated memory.</p>
<p>See:</p>
<ol>
<li><a href="http://stackoverflow.com/questions/2987958/how-is-the-is-keyword-implemented-in-python">How is the 'is' keyword implemented in Python?</a></li>
<li><a href="https://en.wikipedia.org/wiki/String_interning" rel="nofollow">https://en.wikipedia.org/wiki/String_interning</a></li>
</ol>
| 0 | 2016-10-12T22:18:14Z | [
"python",
"string"
] |
Convert decimal separator | 40,009,017 | <p>I'm loading a CSV where decimal value separator is <code>,</code> and I would like to replace it by <code>.</code> in order to proceed the analysis.</p>
<p>I see the <code>converters</code> option in <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow">pandas.read_csv</a> but to use it I need to provide a list of all column names (which I want to convert), which might not be a good idea since there are lots of columns.</p>
<p>What I have in mind is to look each cell in all columns and replace it. </p>
<pre><code>ii = len(list(df))-1
print ii
jj = len(df.ix[:,0])
print jj
for i in range(0, ii):
for j in range(0, jj):
df.ix[i,j] = df.ix[i,j].to_string().replace(',' , '.')
</code></pre>
<p>Is there a better approach?</p>
| 1 | 2016-10-12T21:54:42Z | 40,009,079 | <p>You don't have to provide all the column names to <code>converter</code>. </p>
<p>Give only those columns you want to convert </p>
<p>It would be <code>converter = {'col_name':lambda x : str(x).replace(',','.')}</code></p>
<p><b>EDIT</b> after rewording question.</p>
<p>Is this the best way to do it?</p>
<p>I would say yes. OP mentioned that there are a large number of columns he/she wants to convert and feels that a <code>dict</code> go out of hand. IMO, it will not. There are two reasons to why it wouldn't. </p>
<p>The first reason is that eventhough you have a large number of columns, I assume there is some pattern to it, (like the column numbers 2, 4... need to be converted). You could run a <code>for</code> loop or a list comprehension to generate this <code>dict</code> and pass it to the converter. Another advantage is that converters accept both column label as well as column index as keys so you don't have to mention the column labels.</p>
<p>Second, a <code>dict</code> is implemented using a hash table. This ensures that worst case look-up is constant time. So you don't have to worry about slow runtimes when using a large number of elements in the dictionary.</p>
<p>Though your method is correct, IMO it is reinventing the wheel.</p>
| 0 | 2016-10-12T21:59:42Z | [
"python",
"python-2.7",
"pandas",
"dataframe"
] |
Convert decimal separator | 40,009,017 | <p>I'm loading a CSV where decimal value separator is <code>,</code> and I would like to replace it by <code>.</code> in order to proceed the analysis.</p>
<p>I see the <code>converters</code> option in <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow">pandas.read_csv</a> but to use it I need to provide a list of all column names (which I want to convert), which might not be a good idea since there are lots of columns.</p>
<p>What I have in mind is to look each cell in all columns and replace it. </p>
<pre><code>ii = len(list(df))-1
print ii
jj = len(df.ix[:,0])
print jj
for i in range(0, ii):
for j in range(0, jj):
df.ix[i,j] = df.ix[i,j].to_string().replace(',' , '.')
</code></pre>
<p>Is there a better approach?</p>
| 1 | 2016-10-12T21:54:42Z | 40,009,131 | <p>there is no need to specify <em>all</em> the column converters, but only the ones you need. Given</p>
<pre><code>id;name;value
0;asd;1,2
1;spam;1,5
2;lol;10,5
</code></pre>
<p>for example:</p>
<pre><code>import pandas as pd
df = pd.read_csv('asd', sep=';', converters={'value': lambda x: float(x.replace(',', '.'))})
print df
id name value
0 0 asd 1.2
1 1 spam 1.5
2 2 lol 10.5
</code></pre>
| 0 | 2016-10-12T22:03:51Z | [
"python",
"python-2.7",
"pandas",
"dataframe"
] |
Convert decimal separator | 40,009,017 | <p>I'm loading a CSV where decimal value separator is <code>,</code> and I would like to replace it by <code>.</code> in order to proceed the analysis.</p>
<p>I see the <code>converters</code> option in <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow">pandas.read_csv</a> but to use it I need to provide a list of all column names (which I want to convert), which might not be a good idea since there are lots of columns.</p>
<p>What I have in mind is to look each cell in all columns and replace it. </p>
<pre><code>ii = len(list(df))-1
print ii
jj = len(df.ix[:,0])
print jj
for i in range(0, ii):
for j in range(0, jj):
df.ix[i,j] = df.ix[i,j].to_string().replace(',' , '.')
</code></pre>
<p>Is there a better approach?</p>
| 1 | 2016-10-12T21:54:42Z | 40,009,329 | <p>You can use the <code>decimal</code> parameter of <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow"><code>read_csv</code></a>:</p>
<pre><code>df = pd.read_csv(file.csv, decimal=',')
</code></pre>
| 3 | 2016-10-12T22:20:48Z | [
"python",
"python-2.7",
"pandas",
"dataframe"
] |
extract files inside zip sub folders with python zipfile | 40,009,022 | <p>i have a zip folder that contains files and child zip folders. I am able to read the files placed in the parent folder but how can i get to the files inside the child zip folders? here is my code to get the files inside the parent folder</p>
<pre><code>from io import BytesIO
import pandas as pd
import requests
import zipfile
url1 = 'https://www.someurl.com/abc.zip'
r = requests.get(url1)
z = zipfile.ZipFile(BytesIO(r.content))
temp = pd.read_csv(z.open('mno.csv')
</code></pre>
<p>my question is, if lets say, I have a child sub folder </p>
<pre><code>xyz.zip
</code></pre>
<p>containing file</p>
<pre><code>pqr.csv
</code></pre>
<p>how can I read this file</p>
| -1 | 2016-10-12T21:55:04Z | 40,009,399 | <p>Use another <code>BytesIO</code> object to open the contained zipfile</p>
<pre><code>from io import BytesIO
import pandas as pd
import requests
import zipfile
# Read outer zip file
url1 = 'https://www.someurl.com/abc.zip'
r = requests.get(url1)
z = zipfile.ZipFile(BytesIO(r.content))
# lets say the archive is:
# zippped_folder/pqr.zip (which contains pqr.csv)
# Read contained zip file
pqr_zip = zipfile.ZipFile(BytesIO(z.open('zippped_folder/pqr.zip')))
temp = pd.read_csv(pqr_zip.open('prq.csv'))
</code></pre>
| 0 | 2016-10-12T22:28:19Z | [
"python",
"pandas",
"zipfile"
] |
extract files inside zip sub folders with python zipfile | 40,009,022 | <p>i have a zip folder that contains files and child zip folders. I am able to read the files placed in the parent folder but how can i get to the files inside the child zip folders? here is my code to get the files inside the parent folder</p>
<pre><code>from io import BytesIO
import pandas as pd
import requests
import zipfile
url1 = 'https://www.someurl.com/abc.zip'
r = requests.get(url1)
z = zipfile.ZipFile(BytesIO(r.content))
temp = pd.read_csv(z.open('mno.csv')
</code></pre>
<p>my question is, if lets say, I have a child sub folder </p>
<pre><code>xyz.zip
</code></pre>
<p>containing file</p>
<pre><code>pqr.csv
</code></pre>
<p>how can I read this file</p>
| -1 | 2016-10-12T21:55:04Z | 40,029,280 | <p>After trying some permutation-combination, i hatched the problem with this code</p>
<pre><code>zz = zipfile.ZipFile(z.namelist()[i])
temp2 = pd.read_csv(zz.open('pqr.csv'))
# where i is the index position of the child zip folder in the namelist() list. In this case, the 'xyz.zip' folder
# for eg if the 'xyz.zip' folder was third in the list, the command would be:
zz = zipfile.ZipFile(z.namelist()[2])
</code></pre>
<p>alternatively, if the index position is not known, the same can be achieved like this:</p>
<pre><code>zz = zipfile.ZipFile(z.namelist()[z.namelist().index('xyz.zip')])
</code></pre>
| 0 | 2016-10-13T19:22:04Z | [
"python",
"pandas",
"zipfile"
] |
Serving Excel 2007 file generated by Python | 40,009,088 | <p>I am looking to generate an Excel workbook based on the input from users in an HTML form. After the form is submitted, a Python script will generate the file and send it to the user. I am using xlsxwriter to create the spreadsheet. </p>
<p>I have been able to create a sample file and then provide a link to it, but I want to create the file in memory so there is no clean up. </p>
<p>My code creates a file and sends it to me but when I try to open it in Excel, I receive a message saying</p>
<blockquote>
<p>Excel found unreadable content in 'sample.xlsx'. Do you want to recover the contents of this workbook? If you trust the source of this workbook, click Yes.</p>
</blockquote>
<p>If i click yes, I get a blank sheet. If I open it in a text editor, I can see the file is not empty; the file is 6k in size. Do I need to change my content-type? Or make some other change?</p>
<pre><code>#!/Temp/Python27/python
import io
from sys import stdout
import xlsxwriter
output = io.BytesIO()
workbook = xlsxwriter.Workbook(output)
worksheet = workbook.add_worksheet()
worksheet.write(1, 1, 'Hello, world!')
workbook.close()
contents = output.getvalue()
output.close()
print('Content-Type:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\nContent-Disposition:attachment; filename="sample.xlsx"\n')
print (contents)
</code></pre>
| 1 | 2016-10-12T22:00:26Z | 40,044,389 | <p>I continued searching after I posted my question and found the answer <a href="http://stackoverflow.com/questions/2374427/python-2-x-write-binary-output-to-stdout">here</a></p>
| 1 | 2016-10-14T13:28:19Z | [
"python",
"python-2.7",
"mime-types",
"xlsxwriter"
] |
How to plot two different graphs in python | 40,009,106 | <p>I want to get two lines in the same graph.</p>
<p>This is my code: </p>
<pre><code> x=sorted(true_strain)
y=sorted(true_stress_1)
plt.plot(x,y)
plt.title('$Tensile Stress-Strain Curve$')
plt.xlabel('True Strain [-]')
plt.ylabel('$True Stress (MPa)$')
a=(true_stress_2)
b=sorted(true_strain)
plt.plot(a,b)
</code></pre>
<p>But the image I got is blank. What am I missing?</p>
| 1 | 2016-10-12T22:01:41Z | 40,009,145 | <p>you haven't actually called plt.show(), try adding it at the bottom.</p>
<pre><code>x=sorted(true_strain)
y=sorted(true_stress_1)
plt.plot(x,y)
plt.title('$Tensile Stress-Strain Curve$')
plt.xlabel('True Strain [-]')
plt.ylabel('$True Stress (MPa)$')
a=(true_stress_2)
b=sorted(true_strain)
plt.plot(a,b)
plt.show()
</code></pre>
| 0 | 2016-10-12T22:04:51Z | [
"python"
] |
Error with Speaker Recognition API: "Resource or path can't be found." | 40,009,127 | <p>I'm trying to run the enroll profile code of speaker recognition API using Jupyter Python.</p>
<p>Unfortunately, I am getting an error:</p>
<pre><code>{ "error": { "code": "NotFound", "message": "Resource or path can't be found." } }
</code></pre>
<p>Here is the code:</p>
<pre><code>#Loading .wav file
w = wave.open("Harshil_recording_final.wav", "rb")
binary_data = w.readframes(w.getnframes())
#User Enrollment
headers = {
# Request headers
'Content-Type': 'application/octet-stream',
'Ocp-Apim-Subscription-Key': '*subscription-key*',
}
params = urllib.urlencode({
# Request parameters
'identificationProfileId':user1,
'shortAudio': 'true',
})
body = w
try:
conn = httplib.HTTPSConnection('api.projectoxford.ai')
conn.request("POST", "/spid/v1.0/identificationProfiles/{identificationProfileId}/enroll?%s" % params, str(body), headers)
response = conn.getresponse()
data = response.read()
print(data)
conn.close()
except Exception as e:
print("[Errno {0}] {1}".format(e.errno, e.strerror))
</code></pre>
| 0 | 2016-10-12T22:03:29Z | 40,024,245 | <p>identificationProfileId is part of the URL path, not a query parameter. You should do the following instead:</p>
<pre><code>params = urllib.urlencode({
# Request parameters
'shortAudio': 'true',
})
...
conn.request("POST", "/spid/v1.0/identificationProfiles/{0}/enroll?{1}".format(user1, params), body, headers)
</code></pre>
| 0 | 2016-10-13T14:46:11Z | [
"python",
"python-2.7",
"microsoft-cognitive"
] |
Install SCIP solver on Python3.5 Numberjack (OSX) | 40,009,141 | <p>I am learning Constraint Programming in Python and, for the solving of the problems, I am supposed to use the SCIP solver. I have installed the Numberjack standard package from Github witch includes Mistral, Mistral2, Toulbar2, MipWrapper, SatWrapper, MiniSat and Walksat solvers.</p>
<p>Running my code I got the following error:</p>
<pre><code>Traceback (most recent call last):
File "/Users/angelocoelho/anaconda3/lib/python3.5/site-packages/Numberjack/__init__.py", line 910, in load
lib = __import__(solverstring, fromlist=[solverspkg])
ImportError: No module named 'Numberjack.solvers.SCIP'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "grafosdefluxos.py", line 42, in <module>
solver = model.load('SCIP')
File "/Users/angelocoelho/anaconda3/lib/python3.5/site-packages/Numberjack/__init__.py", line 915, in load
solvername)
ImportError: ERROR: Failed during import, wrong module name? (SCIP)
</code></pre>
<p>I already ran <code>make</code> in '<strong>scipoptsuite-3.1.0</strong>' and in '<strong>scip-3.2.1</strong>', installed <strong>Numberjack-master</strong>'s 'setup.py' and tried this:</p>
<p><code>python setup.py -solver SCIP</code></p>
<p>witch returned the error</p>
<pre><code>Error: the solver 'SCIP' is not known, please use one of: Mistral, SatWrapper, Toulbar2, Walksat, MipWrapper, MiniSat, Mistral2
</code></pre>
<p>I have the SCIP folders alongside and inside the Numberjack folders.
I read and ran all the commands in the README and INSTALL files on how I could get this solver configured but I couldn't get it right.
How can I get SCIP available to solve the problems in Numberjack?</p>
| 0 | 2016-10-12T22:04:41Z | 40,013,421 | <p>Why is there a <code>scip-3.2.1</code> directory? The SCIP Opt Suite 3.1.0 contains SCIP 3.1.0. You need to make sure to run all setup and make commands <em>exactly</em> as stated on the <a href="https://github.com/eomahony/Numberjack#scip" rel="nofollow">Numberjack install page</a>.</p>
| 1 | 2016-10-13T06:04:02Z | [
"python",
"python-3.x",
"jupyter-notebook",
"solver",
"scip"
] |
Install SCIP solver on Python3.5 Numberjack (OSX) | 40,009,141 | <p>I am learning Constraint Programming in Python and, for the solving of the problems, I am supposed to use the SCIP solver. I have installed the Numberjack standard package from Github witch includes Mistral, Mistral2, Toulbar2, MipWrapper, SatWrapper, MiniSat and Walksat solvers.</p>
<p>Running my code I got the following error:</p>
<pre><code>Traceback (most recent call last):
File "/Users/angelocoelho/anaconda3/lib/python3.5/site-packages/Numberjack/__init__.py", line 910, in load
lib = __import__(solverstring, fromlist=[solverspkg])
ImportError: No module named 'Numberjack.solvers.SCIP'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "grafosdefluxos.py", line 42, in <module>
solver = model.load('SCIP')
File "/Users/angelocoelho/anaconda3/lib/python3.5/site-packages/Numberjack/__init__.py", line 915, in load
solvername)
ImportError: ERROR: Failed during import, wrong module name? (SCIP)
</code></pre>
<p>I already ran <code>make</code> in '<strong>scipoptsuite-3.1.0</strong>' and in '<strong>scip-3.2.1</strong>', installed <strong>Numberjack-master</strong>'s 'setup.py' and tried this:</p>
<p><code>python setup.py -solver SCIP</code></p>
<p>witch returned the error</p>
<pre><code>Error: the solver 'SCIP' is not known, please use one of: Mistral, SatWrapper, Toulbar2, Walksat, MipWrapper, MiniSat, Mistral2
</code></pre>
<p>I have the SCIP folders alongside and inside the Numberjack folders.
I read and ran all the commands in the README and INSTALL files on how I could get this solver configured but I couldn't get it right.
How can I get SCIP available to solve the problems in Numberjack?</p>
| 0 | 2016-10-12T22:04:41Z | 40,047,557 | <p>After talking to the assistant teacher I got the answer for this problem.</p>
<p>The folder where Numberjack/SCIP was being installed was not the one it was supposed to be, therefore it was not really included in the solver list. After completing the <code>python setup.py build</code> and <code>python setup.py install</code> installation I ran <code>python setup.py build -solver SCIP</code> and the terminal feedback stated </p>
<p><code>Successfully built solver interfaces for MipWrapper, SCIP</code></p>
<p>But the jupyter notebook didn't recognize the solver. </p>
<p>What solution should work having Anaconda (python3.5) already installed:</p>
<ol>
<li>Download <a href="https://github.com/eomahony/Numberjack#scip" rel="nofollow">Numberjack</a> (file "Numberjack-master.zip") and unpack it.</li>
<li>Download <a href="http://scip.zib.de/download.php?fname=scipoptsuite-3.1.0.tgz" rel="nofollow">SCIP</a> and copy the downloaded file, <code>scipoptsuite-3.1.0.tgz</code>. Paste it <strong>inside</strong> Numberjack-master unpacked directory. The path of it should be <code>~/Downloads/Numberjack-master/scipoptsuite-3.1.0.tgz</code>.</li>
<li>In terminal run <code>cd ~/Downloads/Numberjack-master</code> (or your Numberjack-master directory path).</li>
<li><p>Then run <code>python3.5 setup.py install --user</code>.</p>
<p>In my case Jupyter was looking for the solvers in
<code>~/anaconda3/lib/python3.5/site-packages/Numberjack/</code> and they were
not being installed there so, instead of using <code>python</code>, I used <code>python3.5</code> since my Anaconda was the Python 3.5 package. </p></li>
</ol>
| 0 | 2016-10-14T16:04:49Z | [
"python",
"python-3.x",
"jupyter-notebook",
"solver",
"scip"
] |
How to Catch a 503 Error and retry request | 40,009,167 | <p>I'm using <code>grequests</code> to make about 10,000 calls, but some of these calls return as <code>503</code>. This problem goes away if I don't queue all 10,000 calls at once. Breaking it into groups of 1000 seems to do the trick. However I was wondering if there's a way to catch this <code>503</code> error and just retry the <code>request</code>.</p>
<p>This is how I'm calling and combining the threads:</p>
<pre><code>import grequests
rs = (grequests.get(u, headers=header) for u in urls)
response = grequests.map(rs)
</code></pre>
<p>I know this is really vague, but I don't even know if this is possible using <code>grequests</code>. </p>
<p>I naivley tried </p>
<pre><code>import grequests
rs = (grequests.get(u, headers=header) for u in urls)
time.sleep(1)
response = grequests.map(rs)
</code></pre>
<p>But this does nothing to slow it down. </p>
| 1 | 2016-10-12T22:07:21Z | 40,010,389 | <p>Maybe you can try using event hooks to catch the error and re-launch the requests <a href="http://docs.python-requests.org/en/master/user/advanced/#event-hooks" rel="nofollow">http://docs.python-requests.org/en/master/user/advanced/#event-hooks</a></p>
<pre><code> import grequests
def response_handler(response):
if response.status_code == '503':
print('error.503')
rs = (grequests.get(u, headers=header, hooks = dict('response' : response_handler)) for u in urls)
response = grequests.map(rs)`
</code></pre>
| 1 | 2016-10-13T00:22:35Z | [
"python",
"python-requests",
"grequests"
] |
Python threading with strange output errors | 40,009,172 | <p>I am new to threading in general and have been playing around with different ideas to get my feet under me. However, I came across something I am not sure how to explain. Here is the code:</p>
<pre><code>import threading, datetime
class ThreadClass(threading.Thread):
def run(self):
for _ in range(3):
now = datetime.datetime.now()
print "%s: %s" %(self.getName(), now)
for i in range(2):
t = ThreadClass()
t.start()
</code></pre>
<p>The program does exactly what I wanted it to do, however, the output has some random errors in it.</p>
<pre><code>Thread-1: 2016-10-12 17:34:23.012462
Thread-1: 2016-10-12 17:34:23.012802
Thread-2: 2016-10-12 17:34:23.013025
Thread-2: 2016-10-12 17:34:23.013108
Thread-2: 2016-10-12 17:34:23.013225
Thread-1: 2016-10-12 17:34:23.013252
</code></pre>
<p>The errors are relatively consistent (i.e. the same space and new line show up in the output, just in different places). I suspect it has something to do with the threads trying to write to the output stream at about the same time, but in this particular run both errors occur when Thread-2 is running.</p>
<p>Any assistance in describe why this issue is occuring is greatly appreciated!</p>
<p>I am running this code with Python 2.7 on Ubuntu 14.04 (dual-core CPU), if that would make any difference.</p>
| 2 | 2016-10-12T22:07:45Z | 40,009,259 | <p>You're looking for the <a href="https://docs.python.org/2/library/logging.html" rel="nofollow">logging</a> module:</p>
<blockquote>
<p>15.7.9. Thread Safety</p>
<p>The logging module is intended to be thread-safe without any special work needing to be done by its clients. It achieves this though using threading locks; there is one lock to serialize access to the moduleâs shared data, and each handler also creates a lock to serialize access to its underlying I/O.</p>
</blockquote>
<p>Here is an example:</p>
<pre><code>FORMAT = '%(threadName)s %(asctime)s'
logging.basicConfig(format=FORMAT, level=logging.DEBUG) # "level" default is to only print WARN and above.
logger = logging.getLogger('MyThreadClass')
logger.debug('')
</code></pre>
| 1 | 2016-10-12T22:16:02Z | [
"python",
"multithreading"
] |
Python threading with strange output errors | 40,009,172 | <p>I am new to threading in general and have been playing around with different ideas to get my feet under me. However, I came across something I am not sure how to explain. Here is the code:</p>
<pre><code>import threading, datetime
class ThreadClass(threading.Thread):
def run(self):
for _ in range(3):
now = datetime.datetime.now()
print "%s: %s" %(self.getName(), now)
for i in range(2):
t = ThreadClass()
t.start()
</code></pre>
<p>The program does exactly what I wanted it to do, however, the output has some random errors in it.</p>
<pre><code>Thread-1: 2016-10-12 17:34:23.012462
Thread-1: 2016-10-12 17:34:23.012802
Thread-2: 2016-10-12 17:34:23.013025
Thread-2: 2016-10-12 17:34:23.013108
Thread-2: 2016-10-12 17:34:23.013225
Thread-1: 2016-10-12 17:34:23.013252
</code></pre>
<p>The errors are relatively consistent (i.e. the same space and new line show up in the output, just in different places). I suspect it has something to do with the threads trying to write to the output stream at about the same time, but in this particular run both errors occur when Thread-2 is running.</p>
<p>Any assistance in describe why this issue is occuring is greatly appreciated!</p>
<p>I am running this code with Python 2.7 on Ubuntu 14.04 (dual-core CPU), if that would make any difference.</p>
| 2 | 2016-10-12T22:07:45Z | 40,009,378 | <p>Complement to Joseph's reply, you can use Semaphore</p>
<pre><code>from threading import Semaphore
writeLock = Semaphore(value = 1)
</code></pre>
<p>...</p>
<p>When you are about to print in the thread:</p>
<pre><code>writeLock.acquire()
print ("%s: %s" %(self.getName(), now))
writeLock.release()
</code></pre>
<p>writeLock makes sure only one thread can print at any single moment until release().</p>
<p>Image Semaphore as the conch in the "Lord of the flies", only the one who gets it can speak. When the first speaker finishes, he gives it to the next speaker.</p>
| 2 | 2016-10-12T22:25:33Z | [
"python",
"multithreading"
] |
Python threading with strange output errors | 40,009,172 | <p>I am new to threading in general and have been playing around with different ideas to get my feet under me. However, I came across something I am not sure how to explain. Here is the code:</p>
<pre><code>import threading, datetime
class ThreadClass(threading.Thread):
def run(self):
for _ in range(3):
now = datetime.datetime.now()
print "%s: %s" %(self.getName(), now)
for i in range(2):
t = ThreadClass()
t.start()
</code></pre>
<p>The program does exactly what I wanted it to do, however, the output has some random errors in it.</p>
<pre><code>Thread-1: 2016-10-12 17:34:23.012462
Thread-1: 2016-10-12 17:34:23.012802
Thread-2: 2016-10-12 17:34:23.013025
Thread-2: 2016-10-12 17:34:23.013108
Thread-2: 2016-10-12 17:34:23.013225
Thread-1: 2016-10-12 17:34:23.013252
</code></pre>
<p>The errors are relatively consistent (i.e. the same space and new line show up in the output, just in different places). I suspect it has something to do with the threads trying to write to the output stream at about the same time, but in this particular run both errors occur when Thread-2 is running.</p>
<p>Any assistance in describe why this issue is occuring is greatly appreciated!</p>
<p>I am running this code with Python 2.7 on Ubuntu 14.04 (dual-core CPU), if that would make any difference.</p>
| 2 | 2016-10-12T22:07:45Z | 40,009,737 | <p>Part of your question is <strong>why</strong> is this occurring? And its a good question as you'll notice in your output there is a completely spurious space that <em>neither of the threads actually tried to print</em></p>
<pre><code>Thread-1: 2016-10-12 17:34:23.012802
Thread-2: 2016-10-12 17:34:23.013025
^
</code></pre>
<p>How did that get there? None of your threads tried to print it! Its due to the way the <code>print</code> statement in Python 2.x implements <em>soft spacing</em>.</p>
<p>For example ... when you execute <code>print 1,</code> you receive on <code>stdout</code></p>
<pre><code>1 # there is no space after that 1 yet!
</code></pre>
<p>Then a subsequent <code>print 2</code> will cause a space to be inserted to give a final output of:</p>
<pre><code>1 2
</code></pre>
<p>What is happening is that a <code>print <something>,</code> statement gets compiled to the bytecode operation <code>PRINT_ITEM</code>. The implementation of <code>PRINT_ITEM</code>:</p>
<ul>
<li>checks the output stream to see if the last <code>PRINT_ITEM</code> to this stream marked it as needing a soft space printed;</li>
<li>if it does, print a " ";</li>
<li>then print our item and remark the stream as needing another soft space.</li>
</ul>
<p>And there is another bytecode operation <code>PRINT_NEWLINE</code> which prints a new line and clears any soft space marker on the stream.</p>
<p>Now in your code, each thread will do the following:</p>
<pre><code>print "%s: %s" %(self.getName(), now)
</code></pre>
<p>This gets compiled to:</p>
<pre><code>PRINT_ITEM # print the top of the stack
PRINT_NEWLINE # print a new line
</code></pre>
<p>Thus, thread interaction can mean that:</p>
<ul>
<li><code>Thread-1</code> can perform <code>PRINT_ITEM</code> and mark the stream as needing a softspace for the next <code>PRINT_ITEM</code>;</li>
<li><code>Thread-2</code> can begin <code>PRINT_ITEM</code>, and see the stream needs a soft space;</li>
<li><code>Thread-1</code> now prints a new line;</li>
<li><code>Thread-2</code> now prints that space and its item;</li>
</ul>
<p>Note that this error would not occur if:</p>
<ul>
<li>you used <code>sys.stdout.write</code> to perform your output; or</li>
<li>you were using Python 3.x which has a different io structure</li>
</ul>
| 1 | 2016-10-12T23:03:13Z | [
"python",
"multithreading"
] |
Error importing cv2 in python3, Anaconda | 40,009,184 | <p>I get the following error when importing opencv in python:</p>
<pre><code>> python
>>> import cv2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: /usr/lib/x86_64-linux-gnu/libpangoft2-1.0.so.0: undefined symbol: hb_buffer_set_cluster_level
</code></pre>
<p>The system is Linux debian 4.7.0-1-amd64, stretch. I have created an environment for Python 3 in Anaconda:</p>
<pre><code>conda create --name=envPython3 python=3 anaconda
source activate envPython3
</code></pre>
<p>and then installed OpenCV:</p>
<pre><code>conda install -c https://conda.anaconda.org/menpo opencv3
</code></pre>
<p>It should be installed because</p>
<pre><code>conda list | grep cv
</code></pre>
<p>returns</p>
<pre><code>opencv3 3.1.0 py35_0 menpo
</code></pre>
<p>Everything works fine with Python 2</p>
<p><a href="http://unix.stackexchange.com/questions/235012/problem-with-gtk-application-s">May be this post is related</a> </p>
| 1 | 2016-10-12T22:09:07Z | 40,012,908 | <p>Try again by installing </p>
<p><code>conda install -c https//conda.binstar.org/menpo opencv3</code></p>
| 1 | 2016-10-13T05:25:28Z | [
"python",
"python-3.x",
"opencv",
"anaconda",
"opencv3.0"
] |
Error importing cv2 in python3, Anaconda | 40,009,184 | <p>I get the following error when importing opencv in python:</p>
<pre><code>> python
>>> import cv2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: /usr/lib/x86_64-linux-gnu/libpangoft2-1.0.so.0: undefined symbol: hb_buffer_set_cluster_level
</code></pre>
<p>The system is Linux debian 4.7.0-1-amd64, stretch. I have created an environment for Python 3 in Anaconda:</p>
<pre><code>conda create --name=envPython3 python=3 anaconda
source activate envPython3
</code></pre>
<p>and then installed OpenCV:</p>
<pre><code>conda install -c https://conda.anaconda.org/menpo opencv3
</code></pre>
<p>It should be installed because</p>
<pre><code>conda list | grep cv
</code></pre>
<p>returns</p>
<pre><code>opencv3 3.1.0 py35_0 menpo
</code></pre>
<p>Everything works fine with Python 2</p>
<p><a href="http://unix.stackexchange.com/questions/235012/problem-with-gtk-application-s">May be this post is related</a> </p>
| 1 | 2016-10-12T22:09:07Z | 40,077,448 | <p>i also had the same issue. I found an answer that may work for you. Try</p>
<pre><code>source activate envPython3
conda install -c asmeurer pango
python
>>> import cv2
</code></pre>
<p>Please see this <a href="https://github.com/ContinuumIO/anaconda-issues/issues/368" rel="nofollow">github link</a></p>
| 0 | 2016-10-17T01:51:51Z | [
"python",
"python-3.x",
"opencv",
"anaconda",
"opencv3.0"
] |
python - to extract a specific string | 40,009,212 | <p>I have a string like : </p>
<pre><code> string="(tag, index: develop-AB123-2s), (index: develop-CD123-2s)"
</code></pre>
<p>I want to extract only "develop-CD123-2s", i.e. the string that comes after "(index:" and not the one with tag. How do I do in python? Thanks!</p>
| 1 | 2016-10-12T22:11:46Z | 40,009,267 | <pre><code>>>> string.split("), (")[1].split(":")[1].split(")")[0].strip()
'develop-CD123-2s'
>>>
</code></pre>
<p>The first split separates each tuple, then split on : and take the second result</p>
| 1 | 2016-10-12T22:16:27Z | [
"python"
] |
python - to extract a specific string | 40,009,212 | <p>I have a string like : </p>
<pre><code> string="(tag, index: develop-AB123-2s), (index: develop-CD123-2s)"
</code></pre>
<p>I want to extract only "develop-CD123-2s", i.e. the string that comes after "(index:" and not the one with tag. How do I do in python? Thanks!</p>
| 1 | 2016-10-12T22:11:46Z | 40,009,287 | <p>You could do it like this:</p>
<pre><code>string = "(tag, index: develop-AB123-2s), (index: develop-CD123-2s)"
string = string.split('(index:')
string = string[1].strip(')')
print(string)
</code></pre>
<p>split the string on <code>(index:</code> and strip off the closing curly bracket</p>
| 1 | 2016-10-12T22:17:37Z | [
"python"
] |
python - to extract a specific string | 40,009,212 | <p>I have a string like : </p>
<pre><code> string="(tag, index: develop-AB123-2s), (index: develop-CD123-2s)"
</code></pre>
<p>I want to extract only "develop-CD123-2s", i.e. the string that comes after "(index:" and not the one with tag. How do I do in python? Thanks!</p>
| 1 | 2016-10-12T22:11:46Z | 40,009,289 | <p><sup>Warning: I'm not the best at regex</sup></p>
<pre><code>import re
s='(tag, index: develop-AB123-2s), (index: develop-CD123-2s)'
print re.findall("\\(.*?index: ([^)]+)", s)[1] # 'develop-CD123-2s'
</code></pre>
<p><a href="https://regex101.com/r/zF786N/1" rel="nofollow">Regex Demo</a></p>
<p>Alternative regex</p>
<pre><code>re.findall("index: ([^\s)]+)", s)[1]
</code></pre>
| 2 | 2016-10-12T22:18:08Z | [
"python"
] |
python - to extract a specific string | 40,009,212 | <p>I have a string like : </p>
<pre><code> string="(tag, index: develop-AB123-2s), (index: develop-CD123-2s)"
</code></pre>
<p>I want to extract only "develop-CD123-2s", i.e. the string that comes after "(index:" and not the one with tag. How do I do in python? Thanks!</p>
| 1 | 2016-10-12T22:11:46Z | 40,009,848 | <p>One way is using python regex - <a href="https://docs.python.org/2/library/re.html" rel="nofollow">positive lookbehind assertion</a></p>
<pre><code>import re
string = "(tag, index: develop-AB123-2s), (index: develop-CD123-2s)"
re.findall(r"(?<=\(index:) ([^)]+)", string)
</code></pre>
<p>This pattern only matches things that start with <code>(index:</code>. You can also look at negative lookbehind assertions to try and match the <code>(tag,</code> part.</p>
| 1 | 2016-10-12T23:16:46Z | [
"python"
] |
connecting to a remote server and downloading and extracting binary tar file using python | 40,009,230 | <p>I would like to connect to a remote server, download and extract binary tar file into a specific directory on that host. I am using python 2.6.8</p>
<ol>
<li>What would be a simple way to ssh to that server?</li>
<li><p>I see the below errors on my script to download the tar file and extract it</p>
<p>Traceback (most recent call last):
File "./wgetscript.py", line 16, in
tar = tarfile.open(file_tmp)
File "/usr/lib64/python2.6/tarfile.py", line 1653, in open
return func(name, "r", fileobj, **kwargs)
File "/usr/lib64/python2.6/tarfile.py", line 1715, in gzopen
fileobj = bltn_open(name, mode + "b")
TypeError: coercing to Unicode: need string or buffer, tuple found</p></li>
</ol>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>#!/usr/bin/env python
import os
import tarfile
import urllib
url = 'http://**************/Lintel/Mongodb/mongodb-linux-x86_64-enterprise-suse12-3.2.6.tgz'
fullfilename = os.path.join('/tmp/demo1','file.tgz')
file_tmp = urllib.urlretrieve(url,fullfilename)
print file_tmp
base_name = os.path.basename(url)
print base_name
file_name, file_extension = os.path.splitext(base_name)
print file_name, file_extension
tar = tarfile.open(file_tmp)
nameoffile = os.path.join('/tmp/demo1','file')
tar.extractall(file_name,nameoffile)
tar.close()</code></pre>
</div>
</div>
</p>
| 1 | 2016-10-12T22:14:02Z | 40,014,207 | <p>There are 2 errors here:</p>
<ul>
<li><code>urllib.urlretrieve</code> (or <code>urllib.requests.urlretrieve</code> in Python 3) returns a <code>tuple</code>: filename, httprequest. You have to unpack the result in 2 values (or in the original <code>fullfilename</code>)</li>
<li>download is OK but the <code>tarfile</code> module doesn't work the way to think it works: <code>tar.extractall</code> takes 2 arguments: path of the .tar/.tgz file and optional <code>list</code> of members (that you can get with <code>tar.getmembers()</code> in your case). For this example, I propose that we drop that filter and extract all the contents in the temp directory.</li>
</ul>
<p>Fixed code:</p>
<pre><code>url = 'http://**************/Lintel/Mongodb/mongodb-linux-x86_64-enterprise-suse12-3.2.6.tgz'
temp_dir = '/tmp/demo1'
fullfilename = os.path.join(temp_dir,'file.tgz')
# urllib.request in Python 3
file_tmp,http_message = urllib.urlretrieve(url,fullfilename)
base_name = os.path.basename(url)
file_name, file_extension = os.path.splitext(base_name)
tar = tarfile.open(file_tmp)
#print(tar.getmembers()[0:5]) # would print 5 first members of the archive
tar.extractall(os.path.join(temp_dir,file_name))
tar.close()
</code></pre>
| 0 | 2016-10-13T06:53:34Z | [
"python",
"remote-server"
] |
Python Higher-Lower program (not higher-lower game) | 40,009,358 | <p>I'm a 1st year CS student been struggling over the past few days on this lab task I received for python(2.7):</p>
<hr>
<p>Write a Python script named higher-lower.py which:
first reads exactly one integer from standard input (10, in the example below),
then reads exactly five more integers from standard input and
for each of those five values outputs the message higher, lower or equal depending upon whether the new value is higher than, lower than or equal to the previous value.</p>
<p>(Must have good use of a while loop)</p>
<p>(Must not use a list)</p>
<p>Example standard input:</p>
<pre><code>10
20
10
8
8
12
</code></pre>
<p>Example standard output:</p>
<pre><code>higher
lower
lower
equal
higher
</code></pre>
<p>(1 string per line)</p>
<hr>
<p>I have a working solution but when I upload it for correction I am told it's incorrect, This is my solution:</p>
<pre><code> prev = input()
output = ""
s = 1
while s <= 5:
curr = input()
if prev < curr:
output = output + "higher\n"
elif curr < prev:
output = output + "lower\n"
else:
output = output + "equal\n"
s = s + 1
prev = curr
print output
</code></pre>
<p>I think it's incorrect because each higher/lower/equal is printed on a single string over 5 lines, where the task wants each higher/lower/equal to be printed as an individual string on each line.</p>
<p>Could anyone give me any hints in the right direction? I searched stackoverflow as well as google for a similar problem and couldn't find anything related to this. Any help would be appreciated! </p>
| -3 | 2016-10-12T22:23:21Z | 40,009,674 | <p>Given your description, I suspect that the validation program wants to see a single result after each additional input. Have you tried that?</p>
<pre><code>while s <= 5:
curr = input()
if prev < curr:
print "higher"
elif curr < prev:
print "lower"
else:
print "equal"
s = s + 1
prev = curr
</code></pre>
| 0 | 2016-10-12T22:55:43Z | [
"python"
] |
acos getting error math domain error | 40,009,384 | <p>Trying to figure out why I am getting an error. My numbers are between -1 and 1, but still errors. </p>
<blockquote>
<p>ValueError: math domain error</p>
</blockquote>
<p>Any ideas?</p>
<p>Thanks</p>
<pre><code>from math import sqrt, acos, pi
from decimal import Decimal, getcontext
getcontext().prec = 30
class Vector(object):
CANNOT_NORMALIZE_ZERO_VECTOR_MSG = 'Cannot normalize the zero vector'
def __init__(self, coordinates):
try:
if not coordinates:
raise ValueError
self.coordinates = tuple([Decimal(x) for x in coordinates])
self.dimension = len(self.coordinates)
except ValueError:
raise ValueError('The coordinates must be nonempty')
except TypeError:
raise TypeError('The coordinates must be an iterable')
def __str__(self):
return 'Vector: {}'.format(self.coordinates)
def __eq__(self, v):
return self.coordinates == v.coordinates
def magnitude(self):
coordinates_squared = [x ** 2 for x in self.coordinates]
return sqrt(sum(coordinates_squared))
def normalized(self):
try:
magnitude = self.magnitude()
return self.times_scalar(Decimal(1.0 / magnitude))
except ZeroDivisionError:
raise Exception('Cannot normalize the zero vector')
def plus(self, v):
new_coordinates = [x + y for x, y in zip(self.coordinates, v.coordinates)]
return Vector(new_coordinates)
def minus(self, v):
new_coordinates = [x - y for x, y in zip(self.coordinates, v.coordinates)]
return Vector(new_coordinates)
def times_scalar(self, c):
new_coordinates = [Decimal(c) * x for x in self.coordinates]
return Vector(new_coordinates)
def dot(self, v):
return sum([x * y for x, y in zip(self.coordinates, v.coordinates)])
def angle_with(self, v, in_degrees=False):
try:
u1 = self.normalized()
u2 = v.normalized()
angle_in_radians = acos(u1.dot(u2))
if in_degrees:
degrees_per_radian = 180. / pi
return angle_in_radians * degrees_per_radian
else:
return angle_in_radians
except Exception as e:
if str(e) == self.CANNOT_NORMALIZE_ZERO_VECTOR_MSG:
raise Exception('Cannot comput an angle with a zero vector')
else:
raise e
def is_orthogonal_to(self, v, tolerance=1e-10):
return abs(self.dot(v)) < tolerance
def is_parallel_to(self, v):
return self.is_zero() or v.is_zero() or self.angle_with(v) == 0 or self.angle_with(v) == pi
def is_zero(self, tolerance=1e-10):
return self.magnitude() < tolerance
print('first pair...')
v = Vector(['-7.579', '-7.88'])
w = Vector(['22.737', '23.64'])
print('is parallel:', v.is_parallel_to(w))
print('is orthogonal:', v.is_orthogonal_to(w))
print('second pair...')
v = Vector(['-2.029', '9.97', '4.172'])
w = Vector(['-9.231', '-6.639', '-7.245'])
print('is parallel:', v.is_parallel_to(w))
print('is orthogonal:', v.is_orthogonal_to(w))
print('third pair...')
v = Vector(['-2.328', '-7.284', '-1.214'])
w = Vector(['-1.821', '1.072', '-2.94'])
print('is parallel:', v.is_parallel_to(w))
print('is orthogonal:', v.is_orthogonal_to(w))
print('fourth pair...')
v = Vector(['2.118', '4.827'])
w = Vector(['0', '0'])
print('is parallel:', v.is_parallel_to(w))
print('is orthogonal:', v.is_orthogonal_to(w))
</code></pre>
| 0 | 2016-10-12T22:26:27Z | 40,009,442 | <p>Could it be that <code>u1.dot(u2)</code> equals <code>-1.00000000000000018058942747512</code></p>
<pre><code>print(u2)
print(u1.dot(u2))
angle_in_radians = acos(u1.dot(u2))
</code></pre>
<p>This is around line 60</p>
<p>Update, with further tests:</p>
<pre><code>getcontext().prec = 16
......
def dot(self, v):
print(self.coordinates, v.coordinates)
print("asf")
result = 0
for x, y in zip(self.coordinates, v.coordinates):
print("=================")
print("x: ", x)
print("y: ", y)
print("x*y: ", x*y)
result += (x*y)
print("=================")
print("Result: ", result)
print(sum([x * y for x, y in zip(self.coordinates, v.coordinates)]))
return sum([x * y for x, y in zip(self.coordinates, v.coordinates)])
</code></pre>
<p>Results in:</p>
<pre><code>=================
x: -0.6932074151971374
y: 0.6932074151971375
x*y: -0.4805365204842965
=================
=================
x: -0.7207381490636552
y: 0.7207381490636553
x*y: -0.5194634795157037
=================
Result: -1.000000000000000
-1.000000000000000
</code></pre>
<p>But with:</p>
<pre><code>getcontext().prec = 30
</code></pre>
<p>The decimal begins to drift.</p>
<pre><code>=================
x: -0.693207415197137377521618972764
y: 0.693207415197137482701372768190
x*y: -0.480536520484296481693529594664
=================
=================
x: -0.720738149063655170190045851086
y: 0.720738149063655279547013776664
x*y: -0.519463479515703698895897880460
=================
Result: -1.00000000000000018058942747512
</code></pre>
<p>Which leaves the result less than -1 breaking the <code>acos()</code> function.</p>
<p>After finding the floats were out, I looked through your code I noticed a couple of functions that return floats. The culprit is the <code>sqrt()</code> function which doesn't have a high enough accuracy.</p>
<pre><code>def magnitude(self):
coordinates_squared = [x ** 2 for x in self.coordinates]
return Decimal(sum(coordinates_squared)).sqrt()
def normalized(self):
try:
magnitude = self.magnitude()
return self.times_scalar(Decimal(1.0) / magnitude)
</code></pre>
<p>Using the <code>Decimal(x).sqrt()</code> function will fix your issue. You'll then need to update the <code>normalized()</code> function a bit too.</p>
| 2 | 2016-10-12T22:32:03Z | [
"python",
"math",
"vector"
] |
What's the closest implementation of scala's '@transient lazy val' in Python? | 40,009,409 | <p>According to this post:</p>
<p><a href="http://stackoverflow.com/questions/3012421/python-memoising-deferred-lookup-property-decorator">Python memoising/deferred lookup property decorator</a></p>
<p>A mnemonic decorator can be used to declare a lazy property in a class. There is even an 'official' package that can be used out of the box:</p>
<p><a href="https://pypi.python.org/pypi/lazy" rel="nofollow">https://pypi.python.org/pypi/lazy</a></p>
<p>however, both of these implementation has a severe problem: any memorized values will be attempted to be pickled by python. If these values are unpicklable it will cause the program to break down.</p>
<p>My question is: is there an easy way to implement scala's "@transient lazy val" declaration without too much tinkering? This declaration should remember the property in case of multiple invocation, and drop it once the class/object is serialized.</p>
| 1 | 2016-10-12T22:29:10Z | 40,009,646 | <p>Unaware of scala implementation details, but the easiest solution comes to my mind, if you're satisfied with other aspects of the 'lazy property' library you've found, would be implementing <code>__getstate__</code> and <code>__setstate__</code> object methods, as described in <a href="https://docs.python.org/2/library/pickle.html#pickling-and-unpickling-normal-class-instances" rel="nofollow">Pickling and unpickling normal class instances</a></p>
<p>These methods are called by pickle/unpickle handler during object instance (de)serialization.</p>
<p>This way you can have fine-grained control of how/which attributes of your object serialized.
You should read corresponding documentation on another two pickle-related methods as well (take care of <code>__getinitargs__</code> specifically).
Python deserialized objects initialization differes from common <code>__new__</code> & <code>__init__</code> sequence</p>
| 1 | 2016-10-12T22:53:02Z | [
"python",
"serialization",
"pickle",
"lazy-evaluation"
] |
removing elements from a list of genes | 40,009,437 | <p>I have a list like this:</p>
<pre><code>['>ENST00000262144 cds:known chromosome:GRCh37:16:74907468:75019046:-1 gene:ENSG00000103091 gene_biotype:protein_coding transcript_biotype:protein_coding',
'>ENST00000446813 cds:known chromosome:GRCh37:7:72349936:72419009:1 gene:ENSG00000196313 gene_biotype:protein_coding transcript_biotype:protein_coding']
</code></pre>
<p>I want to make a new list with the same dimension and order but in the new list I will keep only gene id. the results would be like this:</p>
<pre><code>['ENSG00000103091', 'ENSG00000196313']
</code></pre>
<p>I am using python. do you guys know how to do that? thanks</p>
| -3 | 2016-10-12T22:31:45Z | 40,009,497 | <pre><code>For each string in the list:
Split the string on spaces (Python **split** command)
Find the element starting with "gene:"
Keep the rest of the string (grab the slice [5:] of that element)
</code></pre>
<p>Do you have enough basic Python knowledge to take it from there? If not, I suggest that you consult the <a href="https://docs.python.org/release/2.5.2/lib/string-methods.html" rel="nofollow">string method documentation</a>.</p>
| 0 | 2016-10-12T22:36:46Z | [
"python"
] |
removing elements from a list of genes | 40,009,437 | <p>I have a list like this:</p>
<pre><code>['>ENST00000262144 cds:known chromosome:GRCh37:16:74907468:75019046:-1 gene:ENSG00000103091 gene_biotype:protein_coding transcript_biotype:protein_coding',
'>ENST00000446813 cds:known chromosome:GRCh37:7:72349936:72419009:1 gene:ENSG00000196313 gene_biotype:protein_coding transcript_biotype:protein_coding']
</code></pre>
<p>I want to make a new list with the same dimension and order but in the new list I will keep only gene id. the results would be like this:</p>
<pre><code>['ENSG00000103091', 'ENSG00000196313']
</code></pre>
<p>I am using python. do you guys know how to do that? thanks</p>
| -3 | 2016-10-12T22:31:45Z | 40,009,587 | <p>This is by no means the most Pythonic way to achieve this but it should do what you want.</p>
<pre><code>l = [
'>ENST00000262144 cds:known chromosome:GRCh37:16:74907468:75019046:-1 gene:ENSG00000103091 gene_biotype:protein_coding transcript_biotype:protein_coding',
'>ENST00000446813 cds:known chromosome:GRCh37:7:72349936:72419009:1 gene:ENSG00000196313 gene_biotype:protein_coding transcript_biotype:protein_coding'
]
genes = []
for e in l:
e = e.split('gene:')
gene = ''
for c in e[1]:
if c != ' ':
gene += c
else:
break
genes.append(gene)
print(genes)
</code></pre>
<p>Loop through the elements in the list then split them on <code>gene:</code> after that append all the chars to a string and add it to an array.</p>
| 0 | 2016-10-12T22:48:21Z | [
"python"
] |
removing elements from a list of genes | 40,009,437 | <p>I have a list like this:</p>
<pre><code>['>ENST00000262144 cds:known chromosome:GRCh37:16:74907468:75019046:-1 gene:ENSG00000103091 gene_biotype:protein_coding transcript_biotype:protein_coding',
'>ENST00000446813 cds:known chromosome:GRCh37:7:72349936:72419009:1 gene:ENSG00000196313 gene_biotype:protein_coding transcript_biotype:protein_coding']
</code></pre>
<p>I want to make a new list with the same dimension and order but in the new list I will keep only gene id. the results would be like this:</p>
<pre><code>['ENSG00000103091', 'ENSG00000196313']
</code></pre>
<p>I am using python. do you guys know how to do that? thanks</p>
| -3 | 2016-10-12T22:31:45Z | 40,009,605 | <p>Just use some basic list comprehension:</p>
<pre><code>lst = ['>ENST00000262144 cds:known chromosome:GRCh37:16:74907468:75019046:-1 gene:ENSG00000103091 gene_biotype:protein_coding transcript_biotype:protein_coding', '>ENST00000446813 cds:known chromosome:GRCh37:7:72349936:72419009:1 gene:ENSG00000196313 gene_biotype:protein_coding transcript_biotype:protein_coding']
res = [el[5:] for s in lst for el in s.split() if el.startswith('gene:')]
</code></pre>
<p>If you prefer to do this using regular for-loops instead, use this:</p>
<pre><code>lst = ['>ENST00000262144 cds:known chromosome:GRCh37:16:74907468:75019046:-1 gene:ENSG00000103091 gene_biotype:protein_coding transcript_biotype:protein_coding', '>ENST00000446813 cds:known chromosome:GRCh37:7:72349936:72419009:1 gene:ENSG00000196313 gene_biotype:protein_coding transcript_biotype:protein_coding']
res = []
for el in lst: # for each string in your list
l = el.split() # create a second list, of split strings
for s in l: # for each string in the 'split strings' list
if s.startswith('gene:'): # if the string starts with 'gene:' we know we have match
res.append(s[5:]) # so skip the 'gene:' part of the string, and append the rest to a list
</code></pre>
| 1 | 2016-10-12T22:49:58Z | [
"python"
] |
html table header locked to the top of the page even when scrolling down | 40,009,461 | <p>I've used both <code>to_html()</code> and <code>style.render()</code> of Pandas DataFrame to generate html page from CSV data. It's cool!</p>
<p>But when I scroll the page down I lose sight of the column names, that's the problem.</p>
<p>Is there some way of hanging it up on the top of the page?</p>
| 1 | 2016-10-12T22:33:38Z | 40,009,594 | <p>Is this what you need?</p>
<pre><code>#NAME HERE{
position: fixed;
{
</code></pre>
<p>You can also do the width ect with this code...</p>
<pre><code> #NAME HERE{
position: fixed;
bottom:0px;
right: 0;
width: 0px;
height: 0px;
}
</code></pre>
<p>Also, if you want the width to span across the page just change the 0px to 100% Also depending on what you want, change " fixed " to " absolute "</p>
| 1 | 2016-10-12T22:48:53Z | [
"python",
"html",
"python-2.7",
"pandas",
"dataframe"
] |
requests - Gateway Timeout | 40,009,499 | <p>this is a test script to request data from <code>Rovi API</code>, provided by the <code>API</code> itself.</p>
<p><strong>test.py</strong></p>
<pre><code>import requests
import time
import hashlib
import urllib
class AllMusicGuide(object):
api_url = 'http://api.rovicorp.com/data/v1.1/descriptor/musicmoods'
key = 'my key'
secret = 'secret'
def _sig(self):
timestamp = int(time.time())
m = hashlib.md5()
m.update(self.key)
m.update(self.secret)
m.update(str(timestamp))
return m.hexdigest()
def get(self, resource, params=None):
"""Take a dict of params, and return what we get from the api"""
if not params:
params = {}
params = urllib.urlencode(params)
sig = self._sig()
url = "%s/%s?apikey=%s&sig=%s&%s" % (self.api_url, resource, self.key, sig, params)
resp = requests.get(url)
if resp.status_code != 200:
# THROW APPROPRIATE ERROR
print ('unknown err')
return resp.content
</code></pre>
<p>from another <code>script</code> I import the <code>module</code>:</p>
<pre><code>from roviclient.test import AllMusicGuide
</code></pre>
<p>and create an instance of the <code>class</code> inside a <code>mood function</code>:</p>
<pre><code>def mood():
test = AllMusicGuide()
print (test.get('[moodids=moodids]'))
</code></pre>
<p>according to <a href="http://developer.rovicorp.com/docs" rel="nofollow">documentation</a>, the following is the <code>syntax</code> for requests:</p>
<pre><code>descriptor/musicmoods?apikey=apikey&sig=sigâ[&moodids=moodids]â[&format=format]â[&country=country]â[&language=language]
</code></pre>
<p>but running the script I get the following error:</p>
<p><code>unknown err
<h1>Gateway Timeout</h1>:</code></p>
<p>what is wrong?</p>
| 0 | 2016-10-12T22:37:09Z | 40,009,792 | <p>"504, try once more. 502, it went through."</p>
<p>Your code is fine, this is a network issue. "Gateway Timeout" is a 504. The intermediate host handling your request was unable to complete it. It made its own request to another server on your behalf in order to handle yours, but this request took too long and timed out. Usually this is because of network congestion in the backend; if you try a few more times, does it sometimes work?</p>
<p>In any case, I would talk to your network administrator. There could be any number of reasons for this and they should be able to help fix it for you.</p>
| 0 | 2016-10-12T23:09:36Z | [
"python",
"api",
"python-requests"
] |
find indices of lat lon point on a grid using python | 40,009,528 | <p>I am new to python, and I can't figure out how to find the minimum distance from a given lat/lon point (which is not given from the grid, but selected by me) to a find the closest indices of a lat/lon point on a grid.</p>
<p>Basically , I am reading in an ncfile that contains 2D coordinates:</p>
<pre><code>coords = 'coords.nc'
fh = Dataset(coords,mode='r')
lons = fh.variables['latitudes'][:,:]
lats = fh.variables['longitudes'][:,:]
fh.close()
>>> lons.shape
(94, 83)
>>> lats.shape
(94, 83)
</code></pre>
<p>I want to find the indices in the above grid for the nearest lat lon to the below values: </p>
<pre><code>sel_lat=71.60556
sel_lon=-161.458611
</code></pre>
<p>I tried to make lat/lon pairs in order to use the scipy.spatial.distance function, but I still am having problems because I did not set up the input arrays to the format it wants, but I don't understand how to do that:</p>
<pre><code>latLon_pairsGrid = np.vstack(([lats.T],[lons.T])).T
>>> latLon_pairsGrid.shape
(94, 83, 2)
distance.cdist([sel_lat,sel_lon],latLon_pairsGrid,'euclidean')
</code></pre>
<p>Any help or hints would be appreciated</p>
| 0 | 2016-10-12T22:40:42Z | 40,010,836 | <p>I think I found an answer, but it is a workaround that avoids calculating distance between the chosen lat/lon and the lat/lons on the grid. This doesn't seem completely accurate because I am never calculating distances, just the closest difference between lat/lon values themselves.</p>
<p>I used the answer to the question <a href="http://stackoverflow.com/questions/28006077/find-i-j-location-of-closest-long-lat-values-in-a-2d-array">find (i,j) location of closest (long,lat) values in a 2D array</a></p>
<pre><code>a = abs(lats-sel_lat)+abs(lons-sel_lon)
i,j = np.unravel_index(a.argmin(),a.shape)
</code></pre>
<p>Using those returned indices i,j, I can then find on the grid the coordinates that correspond most closely to my selected lat, lon value:</p>
<pre><code>>>> lats[i,j]
71.490295
>>> lons[i,j]
-161.65045
</code></pre>
| 1 | 2016-10-13T01:24:43Z | [
"python",
"coordinates",
"netcdf"
] |
find indices of lat lon point on a grid using python | 40,009,528 | <p>I am new to python, and I can't figure out how to find the minimum distance from a given lat/lon point (which is not given from the grid, but selected by me) to a find the closest indices of a lat/lon point on a grid.</p>
<p>Basically , I am reading in an ncfile that contains 2D coordinates:</p>
<pre><code>coords = 'coords.nc'
fh = Dataset(coords,mode='r')
lons = fh.variables['latitudes'][:,:]
lats = fh.variables['longitudes'][:,:]
fh.close()
>>> lons.shape
(94, 83)
>>> lats.shape
(94, 83)
</code></pre>
<p>I want to find the indices in the above grid for the nearest lat lon to the below values: </p>
<pre><code>sel_lat=71.60556
sel_lon=-161.458611
</code></pre>
<p>I tried to make lat/lon pairs in order to use the scipy.spatial.distance function, but I still am having problems because I did not set up the input arrays to the format it wants, but I don't understand how to do that:</p>
<pre><code>latLon_pairsGrid = np.vstack(([lats.T],[lons.T])).T
>>> latLon_pairsGrid.shape
(94, 83, 2)
distance.cdist([sel_lat,sel_lon],latLon_pairsGrid,'euclidean')
</code></pre>
<p>Any help or hints would be appreciated</p>
| 0 | 2016-10-12T22:40:42Z | 40,044,540 | <p>Checkout the <a href="http://pyresample.readthedocs.io" rel="nofollow">pyresample</a> package. It provides spatial nearest neighbour search using a fast kdtree approach:</p>
<pre><code>import pyresample
import numpy as np
# Define lat-lon grid
lon = np.linspace(30, 40, 100)
lat = np.linspace(10, 20, 100)
lon_grid, lat_grid = np.meshgrid(lon, lat)
grid = pyresample.geometry.GridDefinition(lats=lat_grid, lons=lon_grid)
# Generate some random data on the grid
data_grid = np.random.rand(lon_grid.shape[0], lon_grid.shape[1])
# Define some sample points
my_lons = np.array([34.5, 36.5, 38.5])
my_lats = np.array([12.0, 14.0, 16.0])
swath = pyresample.geometry.SwathDefinition(lons=my_lons, lats=my_lats)
# Determine nearest (w.r.t. great circle distance) neighbour in the grid.
_, _, index_array, distance_array = pyresample.kd_tree.get_neighbour_info(
source_geo_def=grid, target_geo_def=swath, radius_of_influence=50000,
neighbours=1)
# get_neighbour_info() returns indices in the flattened lat/lon grid. Compute
# the 2D grid indices:
index_array_2d = np.unravel_index(index_array, grid.shape)
print "Indices of nearest neighbours:", index_array_2d
print "Longitude of nearest neighbours:", lon_grid[index_array_2d]
print "Latitude of nearest neighbours:", lat_grid[index_array_2d]
print "Great Circle Distance:", distance_array
</code></pre>
<p>There is also a shorthand method for directly obtaining the data values at the nearest grid points:</p>
<pre><code>data_swath = pyresample.kd_tree.resample_nearest(
source_geo_def=grid, target_geo_def=swath, data=data_grid,
radius_of_influence=50000)
print "Data at nearest grid points:", data_swath
</code></pre>
| 0 | 2016-10-14T13:35:54Z | [
"python",
"coordinates",
"netcdf"
] |
In pandas, set a new column and update existing column | 40,009,553 | <p>In a <code>pandas</code> dataframe, I have a last name field that looks like</p>
<pre><code>df = pd.DataFrame(['Jones Jr', 'Smith'], columns=['LastName'])
</code></pre>
<p>I am trying to set a new column named 'Generation', while stripping out the Generation for the last name, so the outcome would look like this:</p>
<pre><code>df2 = pd.DataFrame([('Jones', 'Jr'), ('Smith', '')], columns=['LastName', 'Generation'])
</code></pre>
<p>I could set the Generation column then go back and remove the Generation from the last name:</p>
<pre><code>df.loc[df['LastName'].str[-3:] == ' Jr', 'Generation'] = 'Jr'
df.loc[df['LastName'].str[-3:] == ' Jr', 'LastName'] = df['LastName'].str[:-3]
</code></pre>
<p>However, that's two steps and it seems like performing an update in one swoop would be best. </p>
<p>I thought about apply, but it's an apply to two columns where matching X and I couldn't find anything close to that. </p>
| 1 | 2016-10-12T22:44:56Z | 40,009,647 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.extract.html" rel="nofollow">.str.extract()</a> method:</p>
<pre><code>In [19]: df2 = df.LastName.str.extract(r'(?P<LastName>\w+)\s?(?P<Generation>Jr|Sr)?', expand=True)
In [20]: df2
Out[20]:
LastName Generation
0 Jones Jr
1 Smith NaN
</code></pre>
| 3 | 2016-10-12T22:53:05Z | [
"python",
"pandas",
"dataframe"
] |
Google service account access token request: "Required parameter is missing: grant_type" | 40,009,577 | <p><strong>UPDATE:</strong> Solved. I was indeed making a basic mistake, among other things. My usage of the <code>session.headers.update</code> function was incorrect; instead of <code>session.headers.update = {foo:bar}</code>, I needed to be doing <code>session.headers.update({foo:bar})</code>. Additionally, I changed the following section of code:</p>
<p>From this:</p>
<pre><code>payload = urllib.parse.urlencode({
"grant_type":"urn:ietf:params:oauth:grant-type:jwt-bearer",
"assertion": str(token)
})
</code></pre>
<p>To this:</p>
<pre><code> payload = "grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer&assertion=" + token.decode("utf-8")
</code></pre>
<p>The code now works as intended.</p>
<hr>
<p><strong>Original question below</strong></p>
<p>I've seen several hits on SO and Google about this problem; none of them have helped, although I've certainly made sure to double-check my code to make sure I'm not guilty of the same problems they detail. The problems people tend to have involve passing the POST data as parameters or POSTing to the wrong URL, which I'm not doing, as far as I can tell. Additionally, most of the hits I've found involve 3-legged OAuth2 involving users; I've found comparatively few hits pertaining to service accounts and JWTs, which differ enough from the user flow that I'm concerned about how relevant they are to my problem.</p>
<hr>
<p>I'm trying to get an access token from the Google Authentication server for a service account. I've generated my JWT and now want to POST to the server to receive back my access token. I've set the headers according to the documentation described <a href="https://developers.google.com/identity/protocols/OAuth2ServiceAccount" rel="nofollow">here</a>, under "Making the access token request," and as far as I can tell, my request is up to spec, but Google responds back with a 400 response, and the following JSON:</p>
<pre><code>{'error': 'invalid_request', 'error_description': 'Required parameter is missing: grant_type'}
</code></pre>
<p>Here's the code causing the problem:</p>
<pre><code># Returns the session, now with the Host and Authorization headers set.
def gAuthenticate(session):
token = createJWT()
session.headers.update = {
"Host": "www.googleapis.com",
"Content-Type": "application/x-www-form-urlencoded"
}
payload = urllib.parse.urlencode({
"grant_type":"urn:ietf:params:oauth:grant-type:jwt-bearer",
"assertion": str(token)
})
response = session.post("https://www.googleapis.com/oauth2/v4/token", data = payload)
session.headers.update = {"Authorization": "Bearer " + response.json()["access_token"]}
return session
</code></pre>
<p>I'm having a lot of strange issues with this code. First of all, if I don't <code>urllib.parse.urlencode</code> my dictionary (i.e. simply <code>payload = {dictionary}</code>), I get only a <code>Bad Request / 'invalid_request'</code> error, which I assume from the less specific error message means that this is less acceptable than what I'm currently doing. Why do I have to do this? Isn't Requests supposed to encode my data for me? I've never had this problem when POSTing with Requests before.</p>
<p>Second, examining the prepared request before it's sent reveals that my headers aren't being correctly set, despite the header update. Neither of the headers I've added to the request are being transmitted. </p>
<p>I've examined the request body and it looks to be identical (except of course the content of the JWT) to the one that Google provides as an example in the documentation.</p>
<p>All of this leads me to believe that I'm making a very basic error somewhere, but I haven't had any success finding it. What am I doing wrong here? Links to any helpful documentation would be extremely appreciated; thanks for your time and attention.</p>
| 0 | 2016-10-12T22:47:04Z | 40,027,453 | <p>Try "grant_type": "authorization_code". And add grant type as header.</p>
<p>Also, check this link - <a href="http://stackoverflow.com/questions/32919099/accessing-google-oauth-giving-invalid-grant-type-bad-request?rq=1">Accessing Google oAuth giving invalid grant_type (Bad request)</a></p>
| 0 | 2016-10-13T17:32:39Z | [
"python",
"google-api",
"python-requests",
"google-oauth",
"google-oauth2"
] |
Pandas Dataframe VWAP calculation for custom duration | 40,009,591 | <p>I have a slightly unique problem to solve using Pandas Dataframe. I have following two dataframes:</p>
<pre><code>df1
time, Date, Stock, StartTime, EndTime
2016-10-11 12:00:00 2016-10-11 ABC 12:00:00.243 13:06:34.232
2016-10-11 12:01:00 2016-10-11 ABC 12:02:00.243 13:04:34.232
2016-10-11 12:03:00 2016-10-11 XYZ 08:02:00.243 11:24:23.533
df2
time, Date, Stock, Price, Volume
2016-10-11 12:00:00 2016-10-11 ABC 10.0 100
2016-10-11 12:01:00 2016-10-11 ABC 10.1 300
...
2016-10-11 16:01:00 2016-10-11 ABC 10.4 600
2016-10-11 12:01:00 2016-10-11 XYZ 5.1 1500
...
2016-10-11 17:01:00 2016-10-11 XYZ 10.1 200
...
</code></pre>
<p>Now for each row in df1, I want to join it to df2 on Date and Stock column such that in df2, I am able to calculate the weighted price of all the rows within StartTime and EndTime in df1.<br></p>
<p>Thanks a lot for your help.<br></p>
| 0 | 2016-10-12T22:48:32Z | 40,010,083 | <p>A merge, groupby, and apply weighted average function.</p>
<p>Migrated your data to code so easy for people to load.</p>
<pre><code>df1 = pd.DataFrame({'Date': {0: '2016-10-11', 1: '2016-10-11', 2: '2016-10-11'}, 'Stock': {0: 'ABC', 1: 'ABC', 2: 'XYZ'}, 'EndTime': {0: '13:06:34.232', 1: '13:04:34.232', 2: '11:24:23.533'}, 'StartTime': {0: '12:00:00.243', 1: '12:02:00.243', 2: '08:02:00.243'}, 'time': {0: '12:00:00', 1: '12:01:00', 2: '12:03:00'}})
df2 = pd.DataFrame({'Date': {0: '2016-10-11', 1: '2016-10-11', 2: '2016-10-11', 3: '2016-10-11', 4: '2016-10-11'}, 'Volume': {0: 100, 1: 300, 2: 600, 3: 1500, 4: 200}, 'Price': {0: 10.0, 1: 10.1, 2: 10.4, 3: 5.0999999999999996, 4: 10.1}, 'Stock': {0: 'ABC', 1: 'ABC', 2: 'ABC', 3: 'XYZ', 4: 'XYZ'}, 'time': {0: '12:00:00', 1: '12:01:00', 2: '16:01:00', 3: '12:01:00', 4: '17:01:00'}})
print df1
print df2
</code></pre>
<p>I am assuming your dataframes are as follows, the question is a little unclear, let me know and we can revise this example so the answer matches the question as desired, the <em>redundant</em> date has in time field I have omitted:</p>
<pre><code> Date EndTime StartTime Stock time
0 2016-10-11 13:06:34.232 12:00:00.243 ABC 12:00:00
1 2016-10-11 13:04:34.232 12:02:00.243 ABC 12:01:00
2 2016-10-11 11:24:23.533 08:02:00.243 XYZ 12:03:00
Date Price Stock Volume time
0 2016-10-11 10.0 ABC 100 12:00:00
1 2016-10-11 10.1 ABC 300 12:01:00
2 2016-10-11 10.4 ABC 600 16:01:00
3 2016-10-11 5.1 XYZ 1500 12:01:00
4 2016-10-11 10.1 XYZ 200 17:01:00
df_merged= df1.merge(df2, on=['Date','Stock']) # Merge
df_merged = df_merged[['StartTime','EndTime','Price','Volume','Stock']] #Filter Columns
Without Stock Partition:
print df_merged.groupby(['StartTime','EndTime']).apply(lambda x: np.average(x['Price'],weights=x['Volume']))
With Stock Partition:
print df_merged.groupby(['StartTime','EndTime','Stock']).apply(lambda x: np.average(x['Price'],weights=x['Volume']))
</code></pre>
<p>gives:</p>
<pre><code>StartTime EndTime
08:02:00.243 11:24:23.533 5.688235
12:00:00.243 13:06:34.232 10.270000
12:02:00.243 13:04:34.232 10.270000
dtype: float64
StartTime EndTime Stock
08:02:00.243 11:24:23.533 XYZ 5.688235
12:00:00.243 13:06:34.232 ABC 10.270000
12:02:00.243 13:04:34.232 ABC 10.270000
</code></pre>
| 0 | 2016-10-12T23:44:20Z | [
"python",
"pandas"
] |
Importing modules fails in Codeship | 40,009,619 | <p>I have a repository with the following directory structure:</p>
<pre><code>repo_folder\
----src\
----__init__.py
----src1.py
----src2.py
----src3.py
----testing\
----specific_test.py
----requirements.txt
</code></pre>
<hr>
<p><code>specific_test.py</code> has on it's first lines:</p>
<pre><code>import os
import sys
sys.path.insert(0, os.path.dirname(os.getcwd()))
import src.src1
import src.src2
import src.src3
# lots of asserts
</code></pre>
<hr>
<p>When I run <code>specific_test.py</code> from within <code>testing</code> folder or from <code>repo_folder</code> folder it works, but <strong>only</strong> on my <strong>local machine.</strong></p>
<p>The problem is that when I try to run this from my <code>codeship</code> account, it gives me an <code>Import Error</code>.
The error looks like this:</p>
<ul>
<li><code>ImportError</code> while importing test module </li>
<li>ERROR collecting <code>testing/specific_test.py</code></li>
<li>No module named <code>src.src1</code></li>
<li>Make sure your test modules/packages have valid Python names.</li>
</ul>
<hr>
<p>Do you know what would the problem be?</p>
<p>Do you have suggestions for better alternatives?</p>
| 0 | 2016-10-12T22:50:55Z | 40,010,121 | <p>This seems to be a pathing issue. What seems to be happening on your local machine is you insert into your path your CWD, which is most likely returning as <code>repo_folder\</code>. from there, you can import your src files via <code>src.src1</code> because src is containe. On your codeship account, the cwd (current working directory) is not correct, thus is cannot find the <code>src.</code> part of <code>src.src1</code>. Check what the line <code>sys.path.insert(0, os.path.dirname(os.getcwd()))</code> returns, more importantly <code>os.path.dirname(os.getcwd())</code> and verify that it is leading to <code>repo_folder\</code></p>
| 0 | 2016-10-12T23:49:03Z | [
"python",
"continuous-integration",
"python-import",
"importerror",
"codeship"
] |
Python syntax checkers that test edge cases | 40,009,629 | <p>Are there syntax checkers able to detect broken code based on edge cases. An example:</p>
<pre><code>def run():
for j in [0, 1]:
if j == 0:
yield j
else:
yield None
for i in run():
print i * 2
</code></pre>
<p>This code is broken because <code>None * 2</code> does not make sense. Are there tools to detect this kind of error ?</p>
<p>Thank you</p>
| -1 | 2016-10-12T22:51:54Z | 40,009,755 | <p>You're looking for a type checker, not a syntax checker. Here's one attempt to make one: <a href="http://mypy-lang.org/" rel="nofollow">http://mypy-lang.org/</a></p>
| 2 | 2016-10-12T23:05:14Z | [
"python",
"syntax-checking"
] |
Python syntax checkers that test edge cases | 40,009,629 | <p>Are there syntax checkers able to detect broken code based on edge cases. An example:</p>
<pre><code>def run():
for j in [0, 1]:
if j == 0:
yield j
else:
yield None
for i in run():
print i * 2
</code></pre>
<p>This code is broken because <code>None * 2</code> does not make sense. Are there tools to detect this kind of error ?</p>
<p>Thank you</p>
| -1 | 2016-10-12T22:51:54Z | 40,010,163 | <p>You need a type checker, not a syntax checker. <a href="https://github.com/python/mypy" rel="nofollow">github.com/python/mypy</a></p>
| 1 | 2016-10-12T23:55:01Z | [
"python",
"syntax-checking"
] |
Using python Basemap.pcolormesh with non-monotonic longitude jumps | 40,009,652 | <p>I have satellite sweep data that I am attempting to plot on a basemap using pcolormesh.</p>
<p>The data is organized as a 2d matrix, (bTemp), with two corresponding 2D arrays lat and lon, that give the corresponding latitude and longitude at each point. So my plotting code looks like</p>
<pre><code>m = Basemap()
m.drawcoastlines()
m.pcolormesh(lon, lat, bTemp)
</code></pre>
<p>However, this doesn't quite give me the result I am looking for. A large stripe runs across the map.
<a href="https://i.stack.imgur.com/S9unj.png" rel="nofollow"><img src="https://i.stack.imgur.com/S9unj.png" alt="enter image description here"></a></p>
<p>I think the cause of this is that my longitude increases non-monotonically along a given ray, at the wrap-around point.</p>
<p>Here is a plot of on ray in my longitude array</p>
<pre><code>plot(lon[100,:])
</code></pre>
<p><a href="https://i.stack.imgur.com/Sv1Yq.png" rel="nofollow"><img src="https://i.stack.imgur.com/Sv1Yq.png" alt="enter image description here"></a></p>
<p>What would the best way to fix this be, so that the pcolormesh plot just jumps to the other side of the map without connecting the two points with a filled in area?</p>
| 1 | 2016-10-12T22:53:35Z | 40,009,718 | <p>You could try using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.unwrap.html" rel="nofollow"><code>numpy.unwrap</code></a> to unwrap your data. It was designed exactly for this: to unwrap angular jumps (in radians) that are artifacts due to the way how we use single-valued functions.</p>
<p>You need to convert your longitudes back and forth between degrees and radians for this to work, but the gist is this:</p>
<pre><code>import numpy as np
lon_unwrapped = np.rad2deg(np.unwrap(np.deg2rad(lon)))
</code></pre>
<p>This will find those jumps in your data that are larger than 180 degrees, and take their 360-degree complement. Example:</p>
<pre><code>np.rad2deg(np.unwrap(np.deg2rad([150,-150])))
# array([ 150., 210.])
</code></pre>
<p>Additionally, <code>unwrap</code> accepts ndarray data, and you can tell it along which axes to perform the unravelling. By default this is the last dimension, which seems to be fine for your case, where you want to unwrap <code>lon[i,:]</code>.</p>
| 0 | 2016-10-12T23:00:32Z | [
"python",
"matplotlib-basemap"
] |
pandas panel data update | 40,009,667 | <p>I am using panel datastructure in pandas for storing a 3d panel. </p>
<pre><code>T=pd.Panel(data=np.zeros((n1,n2,n3)),items=n1_label, major_axis=n2_label, minor_axis=n3_label)
</code></pre>
<p>Later on, I am trying to update (increment) the values stored at individual locations inside a loop. Currently I am doing:</p>
<pre><code> u=T.get_value(n1_loop,n2_loop,n3_loop)
T.set_value(n1_loop,n2_loop,n3_loop,u+1)
</code></pre>
<p>My question- is this the simplest way? Is there any other simpler way? The following dont work:</p>
<pre><code>T[n1_loop,n2_loop,n3_loop] +=1
</code></pre>
<p>or </p>
<pre><code>T[n1_loop,n2_loop,n3_loop] = T[n1_loop,n2_loop,n3_loop] +1
</code></pre>
| 2 | 2016-10-12T22:54:21Z | 40,010,287 | <p><strong><em>TL;DR</em></strong> </p>
<pre><code>T.update(T.loc[[n1_loop], [n2_loop], [n3_loop]].add(1))
</code></pre>
<hr>
<p>The analogous exercise for a DataFrame would be to assign with <code>loc</code></p>
<pre><code>df = pd.DataFrame(np.zeros((5, 5)), list('abcde'), list('ABCDE'), int)
df.loc['b':'d', list('AE')] += 1
df
</code></pre>
<p><a href="https://i.stack.imgur.com/qIupI.png" rel="nofollow"><img src="https://i.stack.imgur.com/qIupI.png" alt="enter image description here"></a></p>
<hr>
<p>Exact <code>pd.Panel</code> analog generates an Error</p>
<pre><code>pn = pd.Panel(np.zeros((5, 5, 2)), list('abcde'), list('ABCDE'), list('XY'), int)
pn.loc['b':'d', list('AE'), ['X']] += 1
pn
</code></pre>
<blockquote>
<pre><code>NotImplementedError: cannot set using an indexer with a Panel yet!
</code></pre>
</blockquote>
<hr>
<p>But we can still slice it</p>
<pre><code>pn = pd.Panel(np.zeros((5, 5, 2)), list('abcde'), list('ABCDE'), list('XY'), int)
pn.loc['b':'d', list('AE'), ['X']]
<class 'pandas.core.panel.Panel'>
Dimensions: 3 (items) x 2 (major_axis) x 1 (minor_axis)
Items axis: b to d
Major_axis axis: A to E
Minor_axis axis: X to X
</code></pre>
<hr>
<p>And we can use the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Panel.update.html" rel="nofollow"><code>update</code> method</a></p>
<pre><code>pn.update(pn.loc['b':'d', list('AE'), ['X']].add(1))
</code></pre>
<p>Which we can see did stuff if we use the <code>to_frame</code> method</p>
<pre><code>pn.to_frame().astype(int)
</code></pre>
<p><a href="https://i.stack.imgur.com/59N5f.png" rel="nofollow"><img src="https://i.stack.imgur.com/59N5f.png" alt="enter image description here"></a></p>
<p><strong><em>OR</em></strong></p>
<pre><code>pn.loc[:, :, 'X'].astype(int).T
</code></pre>
<p><a href="https://i.stack.imgur.com/qIupI.png" rel="nofollow"><img src="https://i.stack.imgur.com/qIupI.png" alt="enter image description here"></a></p>
<hr>
<p><strong><em>YOUR CASE</em></strong><br>
This should work</p>
<pre><code>T.update(T.loc[[n1_loop], [n2_loop], [n3_loop]].add(1))
</code></pre>
| 1 | 2016-10-13T00:09:09Z | [
"python",
"panel-data",
"pandas"
] |
OSError: .pynative/... : file too short | 40,009,710 | <p>When I try to apply OCRopus (a python-based OCR tool) to a TIFF image, I get the following python error:</p>
<pre><code> Traceback (most recent call last):
File "/usr/local/bin/ocropus-nlbin", line 10, in <module>
import ocrolib
File "/usr/local/lib/python2.7/dist-packages/ocrolib/__init__.py", line 12, in <module>
from common import *
File "/usr/local/lib/python2.7/dist-packages/ocrolib/common.py", line 18, in <module>
import lstm
File "/usr/local/lib/python2.7/dist-packages/ocrolib/lstm.py", line 32, in <module>
import nutils
File "/usr/local/lib/python2.7/dist-packages/ocrolib/nutils.py", line 25, in <module>
lstm_native = compile_and_load(lstm_utils)
File "/usr/local/lib/python2.7/dist-packages/ocrolib/native.py", line 68, in compile_and_load
return ctypes.CDLL(path)
File "/usr/lib/python2.7/ctypes/__init__.py", line 365, in __init__
self._handle = _dlopen(self._name, mode)
OSError: .pynative/cccd32009099f8dade0fe6cd205bf188.so: file too short
Traceback (most recent call last):
File "/usr/local/bin/ocropus-gpageseg", line 22, in <module>
import ocrolib
File "/usr/local/lib/python2.7/dist-packages/ocrolib/__init__.py", line 12, in <module>
from common import *
File "/usr/local/lib/python2.7/dist-packages/ocrolib/common.py", line 18, in <module>
import lstm
File "/usr/local/lib/python2.7/dist-packages/ocrolib/lstm.py", line 32, in <module>
import nutils
File "/usr/local/lib/python2.7/dist-packages/ocrolib/nutils.py", line 25, in <module>
lstm_native = compile_and_load(lstm_utils)
File "/usr/local/lib/python2.7/dist-packages/ocrolib/native.py", line 68, in compile_and_load
return ctypes.CDLL(path)
File "/usr/lib/python2.7/ctypes/__init__.py", line 365, in __init__
self._handle = _dlopen(self._name, mode)
OSError: .pynative/cccd32009099f8dade0fe6cd205bf188.so: file too short
Traceback (most recent call last):
File "/usr/local/bin/ocropus-rpred", line 7, in <module>
import ocrolib
File "/usr/local/lib/python2.7/dist-packages/ocrolib/__init__.py", line 12, in <module>
from common import *
File "/usr/local/lib/python2.7/dist-packages/ocrolib/common.py", line 18, in <module>
import lstm
File "/usr/local/lib/python2.7/dist-packages/ocrolib/lstm.py", line 32, in <module>
import nutils
File "/usr/local/lib/python2.7/dist-packages/ocrolib/nutils.py", line 25, in <module>
lstm_native = compile_and_load(lstm_utils)
File "/usr/local/lib/python2.7/dist-packages/ocrolib/native.py", line 68, in compile_and_load
return ctypes.CDLL(path)
File "/usr/lib/python2.7/ctypes/__init__.py", line 365, in __init__
self._handle = _dlopen(self._name, mode)
OSError: .pynative/cccd32009099f8dade0fe6cd205bf188.so: file too short
Traceback (most recent call last):
File "/usr/local/bin/ocropus-hocr", line 8, in <module>
import ocrolib
File "/usr/local/lib/python2.7/dist-packages/ocrolib/__init__.py", line 12, in <module>
from common import *
File "/usr/local/lib/python2.7/dist-packages/ocrolib/common.py", line 18, in <module>
import lstm
File "/usr/local/lib/python2.7/dist-packages/ocrolib/lstm.py", line 32, in <module>
import nutils
File "/usr/local/lib/python2.7/dist-packages/ocrolib/nutils.py", line 25, in <module>
lstm_native = compile_and_load(lstm_utils)
File "/usr/local/lib/python2.7/dist-packages/ocrolib/native.py", line 68, in compile_and_load
return ctypes.CDLL(path)
File "/usr/lib/python2.7/ctypes/__init__.py", line 365, in __init__
self._handle = _dlopen(self._name, mode)
OSError: .pynative/cccd32009099f8dade0fe6cd205bf188.so: file too short
</code></pre>
<p>Since this is as python issue, I haven't tagged OCROpus, should I tag it as well?
Could it be an Python installation matter? If so, how can I solve it?</p>
| 1 | 2016-10-12T22:59:54Z | 40,031,518 | <p>Problem solved.
I saw other people having trouble (on diverse matters) with: </p>
<blockquote>
<p>OSError:<strong>[X]</strong>... : file too short</p>
</blockquote>
<p>My suggestion is: whatever you are doing, check for hidden directories named [X] in the current directory and delete them.</p>
| 0 | 2016-10-13T21:44:31Z | [
"python"
] |
Maya python. parentConstraint by distance | 40,009,763 | <p>I have two sets of skeletons (A and B), and trying to parent constraint A set of joints to B joints.</p>
<p>What I did was put A selection into A array and B selection to B array.
but how can I proceed parent constraint A to B by distance, which the distance is 0 basically so the toe joint doesn't hook up with fingers.
something like bellow. </p>
<p>I'd appreciate if some one can advise me.</p>
<pre><code>firstSel = []
secondSel = []
def firstSelection(*args):
sel = mc.select(hi = True)
joints = mc.ls(sl=True, type = "joint")
firstSel.append(joints)
print "this is first selection"
def secondSelection(*args):
tsmgRoot = mc.select(hi = True)
tsmgJoints = mc.ls(sl=True, type = "joint")
secondSel.append(tsmgJoints)
</code></pre>
| 0 | 2016-10-12T23:06:28Z | 40,017,021 | <p>Here's an example of how you can constrain objects from one list to another by their world positions. There may be smarter ways of doing it, like adding the values to a <code>dict</code> then sorting it, but this feels more readable.</p>
<pre><code>import math
# Add code here to get your two selection lists
# Loop through skeleton A
for obj in first_sel:
closest_jnt = None # Name of the closest joint
closest_dist = 0 # Distance of the closest joint
obj_pos = cmds.xform(obj, q=True, ws=True, t=True)
# Loop through skeleton B to find the nearest joint
for target in second_sel:
target_pos = cmds.xform(target, q=True, ws=True, t=True)
# Calculate the distance between the 2 objects
dist = math.sqrt((target_pos[0]-obj_pos[0])**2 +
(target_pos[1]-obj_pos[1])**2 +
(target_pos[2]-obj_pos[2])**2)
# If this is the first object we loop through, automatically say it's the closest
# Otherwise, check to see if this distance beats the closest distance
if closest_jnt is None or dist < closest_dist:
closest_jnt = target
closest_dist = dist
cmds.parentConstraint(closest_jnt, obj, mo=True)
</code></pre>
<p>Also as a side note, no need to do <code>firstSel.append(joints)</code> when you're getting your selection (you're actually adding a list to a list!). You can either just assign it directly like <code>firstSel = mc.ls(sl=True, type = "joint")</code>, or if the list already exists with some items and you want to add to it, you can use <code>firstSel.extend(joints)</code></p>
| 0 | 2016-10-13T09:21:30Z | [
"python",
"maya"
] |
Coloring cells of a grid overlaid on top of a polygon with different colors | 40,009,795 | <p>There is a grid which has been overlaid on top of a polygon. To make the discussion concrete, assume the following picture:</p>
<p><a href="https://i.stack.imgur.com/tLIHQ.png" rel="nofollow"><img src="https://i.stack.imgur.com/tLIHQ.png" alt="enter image description here"></a></p>
<p>I had the yellow polygon and I want to overlay a grid as shown in the image. I wish to color the grid cells based on certain rules. They are not as simple as coloring the intersecting cells red and rest green. I want to preform a conditional check on each grid cell and then color them based on the result. I am at a loss to think how to represent the grid cells and then proceed with my conditional checks on them. This is my first issue. This is more of a data structure question.</p>
<p>Next if I know which certain cells to color orange, how do I do it? This is a graphics question.</p>
<p>I could figure out how to for <code>1x1</code> grid cells basically the points like this:</p>
<pre><code>figure
hold on
roi=[264.418629550321 234.728971962617;207.673447537473 220.710280373832;206.60278372591 78.1869158878505;75.9817987152034 66.5046728971964;58.8511777301927 447.345794392523;201.249464668094 454.355140186916;294.39721627409 380.757009345795;447.502141327623 430.990654205608;476.410064239829 262.766355140187;464.632762312634 213.700934579439;428.230192719486 145.943925233645;365.061027837259 134.261682242991;307.245182012848 152.953271028038;285.831905781585 193.841121495327];
axis([0 500 0 500])
axis equal
view([0 -90])
X=roi(:,1);
Y=roi(:,2);
[a b] = meshgrid(1:500);
inPoly1 = inpolygon(a,b,X,Y);
imagesc(inPoly1);
line(X, Y,'Color','r');
for k = 1:25:500
x = [1 500];
y = [k k];
plot(x,y,'Color','w','LineStyle','-');
plot(x,y,'Color','k','LineStyle',':');
end
for k = 1:25:500
x = [k k];
y = [1 500];
plot(x,y,'Color','w','LineStyle','-');
plot(x,y,'Color','k','LineStyle',':');
end
</code></pre>
<p>This code snippet can also be used to produce above image. But this is not helpful. I want to be able to work with general <code>nxn</code> grid cells in this same way.</p>
<p>I had a naïve idea that I will form a Matlab-cell of all the quadrilaterals that are the grid cells and then do my conditional check over them and color them just as polygons using fill command. Is there a better, easier way so that I have to reinvent the wheel as less as possible? If your advice is that I should go ahead with this idea, then can you suggest a way to form the Matlab-cell of all these quadrilaterals in a smart way?</p>
<p>I saw <a href="http://stackoverflow.com/a/12269837">here</a> but this uses Mapping toolbox which I don't have. So if someone can suggest within the realm of basic matlab toolboxes, it will be highly appreciated. Else please suggest python solutions. If it is difficult to provide code snippets, algorithmic advice would also be helpful.</p>
| 2 | 2016-10-12T23:09:54Z | 40,015,703 | <p>You can consider using <code>fill</code> command, but try to avoid it and use <a href="http://www.mathworks.com/help/matlab/ref/patch.html" rel="nofollow"><code>patch</code></a> if you can. The problem with <code>fill</code> is that you will face serious performance issues when the number of lattice points increases. Take a look at the two answers I provided on <a href="http://stackoverflow.com/questions/39556915/hexagonal-lattice-which-is-randomly-colored-with-black-and-white-color/39636195#39636195">this question</a> to see how to use them with a conditional coloring.</p>
<p><strong>My suggestion</strong> is to keep using <code>imagesc</code> and <code>inpolygon</code>, and try to numerically classify the conditions you want to apply on the bordering lattice points.</p>
<p>Let's count the number of corners per lattice cell that falls inside the polygon and call it <code>w</code>. My coloring conditions are:</p>
<ul>
<li><p><code>w == 0</code>: black</p></li>
<li><p><code>w == 1</code>: blue</p></li>
<li><p><code>w == 2</code>: red</p></li>
<li><p><code>w == 3</code>: green</p></li>
<li><p><code>w == 4</code>: yellow</p></li>
</ul>
<p>So I define <code>myColors = [0 0 0; 0 0 1; 1 0 0; 0 1 0; 1 1 0];</code> as my colormap. This is how I count <code>w</code>:</p>
<pre><code>X = [264; 208; 207; 76; 59; 201; 294; 448; 476; 465; 428; 365; 307; 286];
Y = [235; 221; 78; 67; 447; 454; 381; 431; 263; 214; 146; 134; 153; 194];
xl = 10; % xl is your lattice length
yl = 25; % yl is your lattice height
xv = 0:xl:500;
yv = 0:yl:500;
[a, b] = meshgrid(xv, yv);
v = inpolygon(a, b, X, Y);
% summing up 4 adjacent lattice points and decreasing lattice dimensions by 1:
w = v(1:end-1,1:end-1) + v(2:end,1:end-1) + v(1:end-1,2:end) + v(2:end,2:end);
% shifting the new lattice to the center of previous lattice:
xw = xl/2:xl:500 - xl/2;
yw = yl/2:yl:500 - yl/2;
% plotting
myColors = [0 0 0; 0 0 1; 1 0 0; 0 1 0; 1 1 0];
colormap(myColors)
imagesc(xw, yw, w)
axis equal tight off
</code></pre>
<p>And this is the result:</p>
<p><a href="https://i.stack.imgur.com/RT8Ho.png" rel="nofollow"><img src="https://i.stack.imgur.com/RT8Ho.png" alt="enter image description here"></a></p>
<p>Note that I shift the lattice. You should pass the coordinates of the center of lattice cells to <code>imagesc</code>, and therefore you need to do a half-lattice shift to go from borders to centers (and to reduce the size to one row and one column less, which I did when calculating <code>w</code>).</p>
<p>Also note that if you are interested only in the bordering cells, <code>w > 0 & w < 4</code> separates them.</p>
| 0 | 2016-10-13T08:16:32Z | [
"python",
"matlab"
] |
How to delete the contents of a file before writing into it in a python script? | 40,009,858 | <p>I have a file called fName.txt in a directory. Running the following python snippet (coming from a simulation) would add 6 numbers into 3 rows and 2 columns into the text file through executing the loop (containing the snippet) three times. However, I would like to empty the file completely before writing new data into it. (Otherwise running the script for many times would produce more than three rows needed for the simulation which would produce nonsense results; in other words the script needs to <em>see</em> only three rows just produced from the simulation). I have come across the following page <a href="http://stackoverflow.com/questions/17126037/how-to-delete-only-the-content-of-file-in-python">how to delete only the contents of file in python</a> where it explains how to do it but I am not able to implement it into my example. In particular, after <code>pass</code> statement, I am not sure of the order of statements given the fact that my file is closed to begin with and that it must be closed again once <code>print</code> statement is executed. Each time, I was receiving a different error message which I could not avoid in any case. Here is one sort of error I was receiving which indicated that the content is deleted (mostly likely after print statement):</p>
<blockquote>
<p>/usr/lib/python3.4/site-packages/numpy/lib/npyio.py:1385: UserWarning: genfromtxt: Empty input file: "output/Images/MW_Size/covering_fractions.txt"
warnings.warn('genfromtxt: Empty input file: "%s"' % fname)
Traceback (most recent call last):
File "Collector2.py", line 81, in
LLSs, DLAs = np.genfromtxt(r'output/Images/MW_Size/covering_fractions.txt', comments='#', usecols = (0,1), unpack=True)
ValueError: need more than 0 values to unpack</p>
</blockquote>
<p>This is why I decided to leave the snippet in its simplest form without using any one of those suggestions in that page:</p>
<pre><code>covering_fraction_data = "output/Images/MW_Size/covering_fractions.txt"
with open(covering_fraction_data,"mode") as fName:
print('{:.2e} {:.2e}'.format(lls_number/grid_number, dla_number/grid_number), file=fName)
fName.close()
</code></pre>
<p>Each run of the simulation produces 3 rows that should be printed into the file. When <code>mode</code> is 'a', the three produced lines are added to the existing file producing a text file that would contain more than three rows because it already included some contents. After changing 'a' to 'w', instead of having 3 rows printed in the text file, there is only 1 row printed; the first two rows are deleted unwantedly. </p>
<p><strong>Workaround:</strong></p>
<p>The only way around to avoid all this is to choose the 'a' <code>mode</code> and manually delete the contents of the file before running the code. This way, only three rows are produced in the text file after running the code which is what is expected from the output.</p>
<p><strong>Question:</strong></p>
<p>So, my question is basically, "how can I modify the above code to actually do the deletion of the file <em>automatically</em> and <em>before</em> it is filled with three new rows?"</p>
<p>Your help is greatly appreciated.</p>
| 2 | 2016-10-12T23:18:21Z | 40,009,972 | <p>You are using 'append' mode (<code>'a'</code>) to open your file. When this mode is specified, new text is appended to the existing file content. You're looking for the 'write' mode, that is <code>open(filename, 'w')</code>. This will override the file contents every time you <strong>open</strong> it.</p>
| 2 | 2016-10-12T23:30:26Z | [
"python",
"python-3.x",
"file-io",
"seek"
] |
How to delete the contents of a file before writing into it in a python script? | 40,009,858 | <p>I have a file called fName.txt in a directory. Running the following python snippet (coming from a simulation) would add 6 numbers into 3 rows and 2 columns into the text file through executing the loop (containing the snippet) three times. However, I would like to empty the file completely before writing new data into it. (Otherwise running the script for many times would produce more than three rows needed for the simulation which would produce nonsense results; in other words the script needs to <em>see</em> only three rows just produced from the simulation). I have come across the following page <a href="http://stackoverflow.com/questions/17126037/how-to-delete-only-the-content-of-file-in-python">how to delete only the contents of file in python</a> where it explains how to do it but I am not able to implement it into my example. In particular, after <code>pass</code> statement, I am not sure of the order of statements given the fact that my file is closed to begin with and that it must be closed again once <code>print</code> statement is executed. Each time, I was receiving a different error message which I could not avoid in any case. Here is one sort of error I was receiving which indicated that the content is deleted (mostly likely after print statement):</p>
<blockquote>
<p>/usr/lib/python3.4/site-packages/numpy/lib/npyio.py:1385: UserWarning: genfromtxt: Empty input file: "output/Images/MW_Size/covering_fractions.txt"
warnings.warn('genfromtxt: Empty input file: "%s"' % fname)
Traceback (most recent call last):
File "Collector2.py", line 81, in
LLSs, DLAs = np.genfromtxt(r'output/Images/MW_Size/covering_fractions.txt', comments='#', usecols = (0,1), unpack=True)
ValueError: need more than 0 values to unpack</p>
</blockquote>
<p>This is why I decided to leave the snippet in its simplest form without using any one of those suggestions in that page:</p>
<pre><code>covering_fraction_data = "output/Images/MW_Size/covering_fractions.txt"
with open(covering_fraction_data,"mode") as fName:
print('{:.2e} {:.2e}'.format(lls_number/grid_number, dla_number/grid_number), file=fName)
fName.close()
</code></pre>
<p>Each run of the simulation produces 3 rows that should be printed into the file. When <code>mode</code> is 'a', the three produced lines are added to the existing file producing a text file that would contain more than three rows because it already included some contents. After changing 'a' to 'w', instead of having 3 rows printed in the text file, there is only 1 row printed; the first two rows are deleted unwantedly. </p>
<p><strong>Workaround:</strong></p>
<p>The only way around to avoid all this is to choose the 'a' <code>mode</code> and manually delete the contents of the file before running the code. This way, only three rows are produced in the text file after running the code which is what is expected from the output.</p>
<p><strong>Question:</strong></p>
<p>So, my question is basically, "how can I modify the above code to actually do the deletion of the file <em>automatically</em> and <em>before</em> it is filled with three new rows?"</p>
<p>Your help is greatly appreciated.</p>
| 2 | 2016-10-12T23:18:21Z | 40,073,770 | <p>Using mode 'w' is able to delete the content of the file and overwrite the file but prevents the loop containing the above snippet from printing two more times to produce two more rows of data. In other words, using 'w' mode is not compatible with the code I have given the fact that it is supposed to print into the file three times (since the loop containing this snippet is executing three times). For this reason, I had to empty the file through the following command line inside the main.py code: </p>
<pre><code>os.system("> output/Images/MW_Size/covering_fractions.txt")
</code></pre>
<p>And only then use the 'a' mode in the code snippet mentioned above. This way the loop is executing AND printing into the empty file three times as expected without deleting the first two rows.</p>
| 0 | 2016-10-16T18:18:20Z | [
"python",
"python-3.x",
"file-io",
"seek"
] |
List/Conditional Comprehension in Python | 40,009,897 | <p>I was wondering how to make the following into a comprehension:</p>
<pre><code>for g in a:
for f in g[::3]:
if f == clf.best_params_:
print g
</code></pre>
<p>I tried this:</p>
<pre><code>p = [[print g for g in a] if f==clf.best_params for f in [g[::3] for g in a]]
p
</code></pre>
<p>but got an error at <code>for f in</code> </p>
<p>Would love some help! Thanks!</p>
| 0 | 2016-10-12T23:22:55Z | 40,009,941 | <p>The correct way to translate those loops would be</p>
<pre><code>[print g for g in a for f in g[::3] if f == clf.best_params_]
</code></pre>
<p>However, in Python 2 <code>print g</code> is a statement, and that's why you get a SyntaxError. The Python 3 counterpart (i.e. with <code>print(g)</code>) would work, but note that a list comprehension here is completely useless. A list comprehension is useful when you have to gather values into a list - here it just hampers the readability.</p>
<p>Regarding the SyntaxError, it's not the primary issue here. Note that you can use</p>
<pre><code>from __future__ import print_function
</code></pre>
<p>and then use the <code>print()</code> function in your list comprehension as you would in Python 3.</p>
| 2 | 2016-10-12T23:27:20Z | [
"python",
"list",
"scikit-learn",
"conditional",
"list-comprehension"
] |
List/Conditional Comprehension in Python | 40,009,897 | <p>I was wondering how to make the following into a comprehension:</p>
<pre><code>for g in a:
for f in g[::3]:
if f == clf.best_params_:
print g
</code></pre>
<p>I tried this:</p>
<pre><code>p = [[print g for g in a] if f==clf.best_params for f in [g[::3] for g in a]]
p
</code></pre>
<p>but got an error at <code>for f in</code> </p>
<p>Would love some help! Thanks!</p>
| 0 | 2016-10-12T23:22:55Z | 40,009,947 | <p>I think you've confused the construct: it's a <strong>list</strong> comprehension, not a macro of some sort.</p>
<p>You don't get this sort of side effect; the purpose of a list comprehension is to construct a list.</p>
| 1 | 2016-10-12T23:27:47Z | [
"python",
"list",
"scikit-learn",
"conditional",
"list-comprehension"
] |
List/Conditional Comprehension in Python | 40,009,897 | <p>I was wondering how to make the following into a comprehension:</p>
<pre><code>for g in a:
for f in g[::3]:
if f == clf.best_params_:
print g
</code></pre>
<p>I tried this:</p>
<pre><code>p = [[print g for g in a] if f==clf.best_params for f in [g[::3] for g in a]]
p
</code></pre>
<p>but got an error at <code>for f in</code> </p>
<p>Would love some help! Thanks!</p>
| 0 | 2016-10-12T23:22:55Z | 40,009,950 | <p><strong>Rule 1</strong> - Keep the order of the <code>for</code> and <code>if</code> parts the same. The only part that changes order is the last part, <code>print g</code>: that moves to the front.</p>
<pre><code>[print g for g in a for f in g[::3] if f == clf.best_params_]
</code></pre>
<p><strong>Rule 2</strong> - List comprehensions should not <em>do</em> anything. Instead of <em>printing</em> <code>g</code>, have <code>g</code> be the value that is accumulated.</p>
<pre><code>[g for g in a for f in g[::3] if f == clf.best_params_]
</code></pre>
<p>If your entire goal was simply to print things, stick with the original loops; a list comprehension wouldn't add any value.</p>
<hr>
<p>If we take another look at your original nested loops, there may be a better way to write them. Is your goal to find all the items <code>g</code> that have <code>clf.best_params_</code> in one of the matching positions? If so, I recommend replacing the inner loop with a single <code>if any</code> statement.</p>
<pre><code>for g in a:
if any(f == clf.best_params_ for f in g[::3]):
print g
</code></pre>
<p>To me, this reads better. The logic is clearer. It will only print any one value of <code>g</code> once, instead of multiple times if <code>clf.best_params_</code> is present more than once.</p>
<p>If that is an improvement, then you could convert that version to a list comprehension like so:</p>
<pre><code>[g for g in a if any(f == clf.best_params_ for f in g[::3])]
</code></pre>
| 1 | 2016-10-12T23:27:59Z | [
"python",
"list",
"scikit-learn",
"conditional",
"list-comprehension"
] |
django-pipeline throwing ValueError: the file could not be found | 40,010,040 | <p>When running <code>python manage.py collectstatic --noinput</code> I'm getting the following error:</p>
<pre><code>Post-processing 'jquery-ui-dist/jquery-ui.css' failed!
Traceback (most recent call last):
File "manage_local.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/Users/michaelbates/GoogleDrive/Development/inl/venv/lib/python3.4/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line
utility.execute()
File "/Users/michaelbates/GoogleDrive/Development/inl/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 "/Users/michaelbates/GoogleDrive/Development/inl/venv/lib/python3.4/site-packages/django/core/management/base.py", line 294, in run_from_argv
self.execute(*args, **cmd_options)
File "/Users/michaelbates/GoogleDrive/Development/inl/venv/lib/python3.4/site-packages/django/core/management/base.py", line 345, in execute
output = self.handle(*args, **options)
File "/Users/michaelbates/GoogleDrive/Development/inl/venv/lib/python3.4/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 193, in handle
collected = self.collect()
File "/Users/michaelbates/GoogleDrive/Development/inl/venv/lib/python3.4/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 145, in collect
raise processed
File "/Users/michaelbates/GoogleDrive/Development/inl/venv/lib/python3.4/site-packages/django/contrib/staticfiles/storage.py", line 257, in post_process
content = pattern.sub(converter, content)
File "/Users/michaelbates/GoogleDrive/Development/inl/venv/lib/python3.4/site-packages/django/contrib/staticfiles/storage.py", line 187, in converter
hashed_url = self.url(unquote(target_name), force=True)
File "/Users/michaelbates/GoogleDrive/Development/inl/venv/lib/python3.4/site-packages/django/contrib/staticfiles/storage.py", line 132, in url
hashed_name = self.stored_name(clean_name)
File "/Users/michaelbates/GoogleDrive/Development/inl/venv/lib/python3.4/site-packages/django/contrib/staticfiles/storage.py", line 292, in stored_name
cache_name = self.clean_name(self.hashed_name(name))
File "/Users/michaelbates/GoogleDrive/Development/inl/venv/lib/python3.4/site-packages/django/contrib/staticfiles/storage.py", line 95, in hashed_name
(clean_name, self))
ValueError: The file 'jquery-ui-dist/"images/ui-icons_555555_256x240.png"' could not be found with <pipeline.storage.PipelineCachedStorage object at 0x1073e2c50>.
</code></pre>
<p>If I run <code>python manage.py findstatic jquery-ui-dist/"images/ui-icons_555555_256x240.png"</code> I get:</p>
<pre><code>Found 'jquery-ui-dist/images/ui-icons_555555_256x240.png' here:
/Users/michaelbates/GoogleDrive/Development/inl/node_modules/jquery-ui-dist/images/ui-icons_555555_256x240.png
/Users/michaelbates/GoogleDrive/Development/inl/staticfiles/jquery-ui-dist/images/ui-icons_555555_256x240.png
</code></pre>
<p>Here are some relevant settings:</p>
<pre><code>STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'pipeline.finders.AppDirectoriesFinder',
'pipeline.finders.PipelineFinder',
)
STATICFILES_STORAGE = 'pipeline.storage.PipelineCachedStorage'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
os.path.join(BASE_DIR, 'node_modules'),
)
</code></pre>
<p>My <code>PIPELINE</code> settings dict is huge so I won't post the entire thing, but some parts of it are:</p>
<pre><code>PIPELINE = {
'STYLESHEETS': {
'pricing': {
'source_filenames': (
'jquery-ui-dist/jquery-ui.min.css',
),
'output_filename': 'css/pricing.min.css'
},
}
'JS_COMPRESSOR': 'pipeline.compressors.yuglify.YuglifyCompressor',
'CSS_COMPRESSOR': 'pipeline.compressors.yuglify.YuglifyCompressor',
'COMPILERS': (
'pipeline.compilers.sass.SASSCompiler',
)
}
</code></pre>
<p>I've tried changing the STATICFILES_FINDERS to the django-pipeline specific ones but it makes no difference.</p>
<p>Can anyone shed some light on why that png file can't be found during collectstatic but can with findstatic?</p>
| 0 | 2016-10-12T23:39:52Z | 40,142,068 | <p>Your problem is related to <a href="https://code.djangoproject.com/ticket/21080" rel="nofollow">this bug</a> on the Django project.</p>
<p>In short, django-pipeline is post-processing the <code>url()</code> calls with Django's <code>CachedStaticFilesStorage</code> to append the md5 checksum to the filename (<a href="https://docs.djangoproject.com/en/1.10/ref/contrib/staticfiles/#manifeststaticfilesstorage" rel="nofollow">more details here</a>) and doesn't detect when it is inside a comment.</p>
<p>If you look on the header of the <code>jquery-ui.css</code> (and similar) files there is a comment that starts with </p>
<blockquote>
<ul>
<li>To view and modify this theme, visit [...]</li>
</ul>
</blockquote>
<p>Inside the URL on this line there is a parameter that is being interpreted as an <code>url()</code> call and generating the error you see.</p>
<p>To work around this issue you can simply remove the above line from <code>jquery-ui.css</code> and <code>collectstatic</code> should work properly.</p>
| 1 | 2016-10-19T21:47:59Z | [
"python",
"django",
"asset-pipeline",
"django-pipeline"
] |
Counting number of vowels in a merged string | 40,010,066 | <p>I am trying to figure out how to calculate the score of two merged lists of names. I need to give one point for each character (including spaces between first and last name) plus one point for each vowel in the name. I can currently calculate score for the the lengths of the names but cannot figure out how to include the number of vowels. </p>
<pre><code>a = ["John", "Kate", "Oli"]
b = ["Green", "Fletcher", "Nelson"]
vowel = ["a", "e", "i", "o", "u"]
gen = ((x, y) for x in a for y in b)
score = 0
for first, second in gen:
print first, second
name = first, second
score = len(first) + len(second) +1
for letter in name:
if letter in vowel:
score+1
print score
</code></pre>
<p><strong>This is what i currently have and this is the output I get:</strong></p>
<pre><code>John Green
10
John Fletcher
13
John Nelson
11
Kate Green
10
Kate Fletcher
13
Kate Nelson
11
Oli Green
9
Oli Fletcher
12
Oli Nelson
10
</code></pre>
<p><strong>This is the output I need:</strong></p>
<pre><code>Full Name: John Green Score: 13
Full Name: John Fletcher Score: 16
Full Name: John Nelson Score: 14
Full Name: Kate Green Score: 14
Full Name: Kate Fletcher Score: 17
Full Name: Kate Nelson Score: 15
Full Name: Oli Green Score: 13
Full Name: Oli Fletcher Score: 16
Full Name: Oli Nelson Score: 14
</code></pre>
| 3 | 2016-10-12T23:42:14Z | 40,010,101 | <p>The reason you're not calculating the vowels is because the score variable is not getting incremented. To increment it, you have to set the variable score to previous score + 1.</p>
<p>This should work:</p>
<pre><code>for letter in name:
if letter in vowel:
score+=1
</code></pre>
<p>Edit: It's worth writing that score+=1 is the same as score=score+1</p>
<p>I worked out the error - instead of creating name = first, second, initialize name to first+second. You will get the results you want. The reason it was failing is because name=first, second creates a tuple, and iterating through the tuple makes letter = "Kate", "John" etc, and not the actual individual characters.</p>
| 2 | 2016-10-12T23:46:15Z | [
"python",
"list"
] |
Counting number of vowels in a merged string | 40,010,066 | <p>I am trying to figure out how to calculate the score of two merged lists of names. I need to give one point for each character (including spaces between first and last name) plus one point for each vowel in the name. I can currently calculate score for the the lengths of the names but cannot figure out how to include the number of vowels. </p>
<pre><code>a = ["John", "Kate", "Oli"]
b = ["Green", "Fletcher", "Nelson"]
vowel = ["a", "e", "i", "o", "u"]
gen = ((x, y) for x in a for y in b)
score = 0
for first, second in gen:
print first, second
name = first, second
score = len(first) + len(second) +1
for letter in name:
if letter in vowel:
score+1
print score
</code></pre>
<p><strong>This is what i currently have and this is the output I get:</strong></p>
<pre><code>John Green
10
John Fletcher
13
John Nelson
11
Kate Green
10
Kate Fletcher
13
Kate Nelson
11
Oli Green
9
Oli Fletcher
12
Oli Nelson
10
</code></pre>
<p><strong>This is the output I need:</strong></p>
<pre><code>Full Name: John Green Score: 13
Full Name: John Fletcher Score: 16
Full Name: John Nelson Score: 14
Full Name: Kate Green Score: 14
Full Name: Kate Fletcher Score: 17
Full Name: Kate Nelson Score: 15
Full Name: Oli Green Score: 13
Full Name: Oli Fletcher Score: 16
Full Name: Oli Nelson Score: 14
</code></pre>
| 3 | 2016-10-12T23:42:14Z | 40,010,535 | <pre><code>a = ["John", "Kate", "Oli"]
b = ["Green", "Fletcher", "Nelson"]
vowel = {"a", "e", "i", "o", "u"}
names = (first + ' ' + last for first in a for last in b)
for name in names:
score = len(name) + sum(c in vowel for c in name.lower())
print "Full Name: {name} Score: {score}".format(name=name, score=score)
</code></pre>
<hr>
<pre><code>Full Name: John Green Score: 13
Full Name: John Fletcher Score: 16
Full Name: John Nelson Score: 14
Full Name: Kate Green Score: 14
Full Name: Kate Fletcher Score: 17
Full Name: Kate Nelson Score: 15
Full Name: Oli Green Score: 13
Full Name: Oli Fletcher Score: 16
Full Name: Oli Nelson Score: 14
</code></pre>
| 1 | 2016-10-13T00:40:29Z | [
"python",
"list"
] |
Maya PySide Window - Remember position and size | 40,010,166 | <p>I am working in Pyside. Every time I re-open the window it pops back to the middle of the screen. How can I get either Maya or Windows to remember the position and size?</p>
<p>Here is some basic code I am working with:</p>
<pre><code>import traceback
from PySide import QtCore
from PySide import QtGui
from shiboken import wrapInstance
import maya.cmds as cmds
import maya.OpenMayaUI as omui
import pymel.core as pm
import maya.cmds as cmds
def maya_main_window():
'''
Return the Maya main window widget as a Python object
'''
main_window_ptr = omui.MQtUtil.mainWindow()
return wrapInstance(long(main_window_ptr), QtGui.QWidget)
class TestTool(QtGui.QDialog):
def __init__(self, parent=maya_main_window()):
super(TestTool, self).__init__(parent)
self.qtSignal = QtCore.Signal()
#################################################################
def create(self):
'''
Set up the UI prior to display
'''
self.setWindowTitle("Test")
self.setWindowFlags(QtCore.Qt.Tool)
#self.resize(400, 250) # re-size the window
self.setGeometry(650, 200, 600, 300)
self.setFixedHeight(580)
self.setFixedWidth(300)
QtGui.QToolTip.setFont(QtGui.QFont('SansSerif', 10))
if __name__ == "__main__":
try:
ui.deleteLater()
except:
pass
ui = TestTool()
try:
ui.create()
ui.show()
except:
ui.deleteLater()
traceback.print_exc()
</code></pre>
| 0 | 2016-10-12T23:55:20Z | 40,017,712 | <p>One option you can use is <code>QWidget.saveGeometry()</code> and <code>QWidget.restoreGeometry()</code>. With this you can save your window's position and size when your tool closes, then restore it back when it initializes. </p>
<p>Normally for stuff like this where it's saving a state of the tool, I'll store the data to an ini file somewhere with <code>QtCore.QSettings</code>. This way it will restore to the last state even if you close Maya, or have multiple sessions running.</p>
<p>Here's an example:</p>
<pre><code>import traceback
from PySide import QtCore
from PySide import QtGui
from shiboken import wrapInstance
import maya.cmds as cmds
import maya.OpenMayaUI as omui
import pymel.core as pm
import maya.cmds as cmds
import os
def maya_main_window():
'''
Return the Maya main window widget as a Python object
'''
main_window_ptr = omui.MQtUtil.mainWindow()
return wrapInstance(long(main_window_ptr), QtGui.QWidget)
class TestTool(QtGui.QDialog):
def __init__(self, parent=maya_main_window()):
super(TestTool, self).__init__(parent)
self.qtSignal = QtCore.Signal()
# Using an env variable makes the path more generic, but use whatever you want
self.settings_path = os.path.join(os.getenv('HOME'), "settingsFile.ini")
#################################################################
def create(self):
'''
Set up the UI prior to display
'''
self.setWindowTitle("Test")
self.setWindowFlags(QtCore.Qt.Tool)
self.resize(400, 250) # re-size the window
self.setGeometry(650, 200, 600, 300)
self.setFixedHeight(580)
self.setFixedWidth(300)
QtGui.QToolTip.setFont(QtGui.QFont('SansSerif', 10))
# Restore window's previous geometry from file
if os.path.exists(self.settings_path):
settings_obj = QtCore.QSettings(self.settings_path, QtCore.QSettings.IniFormat)
self.restoreGeometry(settings_obj.value("windowGeometry"))
def closeEvent(self, event):
# Save window's geometry
settings_obj = QtCore.QSettings(self.settings_path, QtCore.QSettings.IniFormat)
settings_obj.setValue("windowGeometry", self.saveGeometry())
if __name__ == "__main__":
try:
ui.deleteLater()
except:
pass
ui = TestTool()
try:
ui.create()
ui.show()
except:
ui.deleteLater()
traceback.print_exc()
</code></pre>
<p>Since you're setting the size to be fixed, this will only effect position. Hope it helps!</p>
| 0 | 2016-10-13T09:50:56Z | [
"python",
"window",
"pyside",
"maya"
] |
Summation of elements of dictionary that are list of lists | 40,010,175 | <pre><code>d = {
'a': [[1, 2, 3], [1, 2, 3]],
'b': [[2, 4, 1], [1, 6, 1]],
}
def add_element(lst):
ad = [sum(i) for i in zip(*lst)]
return ad
def csv_reducer2(dicty):
return {k: list(map(add_element, v)) for k, v in dicty.items()}
csv_reducer2(d)
</code></pre>
<p>required output:</p>
<pre><code>{'b': [3, 10, 2], 'a': [2, 4, 6]}
</code></pre>
<p>Above is the code I have been trying but it gives an error</p>
<blockquote>
<p>zip argument #1 must support iteration</p>
</blockquote>
| 6 | 2016-10-12T23:56:33Z | 40,010,243 | <pre><code>>>> d = {'a': [[1, 2, 3], [1, 2, 3]], 'b': [[2, 4, 1], [1, 6, 1]]}
>>> {k: map(sum, zip(*v)) for k, v in d.items()}
{'a': [2, 4, 6], 'b': [3, 10, 2]}
</code></pre>
| 6 | 2016-10-13T00:04:23Z | [
"python",
"list",
"dictionary"
] |
Summation of elements of dictionary that are list of lists | 40,010,175 | <pre><code>d = {
'a': [[1, 2, 3], [1, 2, 3]],
'b': [[2, 4, 1], [1, 6, 1]],
}
def add_element(lst):
ad = [sum(i) for i in zip(*lst)]
return ad
def csv_reducer2(dicty):
return {k: list(map(add_element, v)) for k, v in dicty.items()}
csv_reducer2(d)
</code></pre>
<p>required output:</p>
<pre><code>{'b': [3, 10, 2], 'a': [2, 4, 6]}
</code></pre>
<p>Above is the code I have been trying but it gives an error</p>
<blockquote>
<p>zip argument #1 must support iteration</p>
</blockquote>
| 6 | 2016-10-12T23:56:33Z | 40,010,268 | <p>The following will work on Python 2 or 3:</p>
<pre><code>>>> {k: [a + b for a, b in zip(*v)] for k, v in d.items()}
{'a': [2, 4, 6], 'b': [3, 10, 2]}
</code></pre>
<p>The issue with your code is you are mapping <code>add_element</code> to every individual element in <code>v</code> inside your dictionary comprehension. This passes a one-dimensional list to <code>zip</code> in <code>add_element</code>, resulting in your error (since individual integers don't support iteration.</p>
| 4 | 2016-10-13T00:06:46Z | [
"python",
"list",
"dictionary"
] |
Summation of elements of dictionary that are list of lists | 40,010,175 | <pre><code>d = {
'a': [[1, 2, 3], [1, 2, 3]],
'b': [[2, 4, 1], [1, 6, 1]],
}
def add_element(lst):
ad = [sum(i) for i in zip(*lst)]
return ad
def csv_reducer2(dicty):
return {k: list(map(add_element, v)) for k, v in dicty.items()}
csv_reducer2(d)
</code></pre>
<p>required output:</p>
<pre><code>{'b': [3, 10, 2], 'a': [2, 4, 6]}
</code></pre>
<p>Above is the code I have been trying but it gives an error</p>
<blockquote>
<p>zip argument #1 must support iteration</p>
</blockquote>
| 6 | 2016-10-12T23:56:33Z | 40,010,367 | <p>To fix your original code, the only change you need to make is:</p>
<pre><code>return {k: list(map(add_element, v)) for k, v in dicty.items()}
</code></pre>
<p>-></p>
<pre><code>return {k: add_element(v) for k, v in dicty.items()}
</code></pre>
<p>Because <code>zip(*lst)</code> is trying to transpose multiple rows into columns, but you are only passing it single rows through your original <code>map</code></p>
| 4 | 2016-10-13T00:18:42Z | [
"python",
"list",
"dictionary"
] |
Numpy: Read csv, deal with undefined values | 40,010,178 | <p>What is the best way to read data from a csv file into a numpy array when some of the values are labelled as 'undefined' as follows:</p>
<pre><code>0.231620,0.00001,444.157
0.225370,--undefined--,1914.637
0.237870,0.0003,--undefined--
</code></pre>
<p>I have a lot of these files that I will have to loop over, and it is fine to assume that an undefined value should be zero.</p>
| 1 | 2016-10-12T23:56:37Z | 40,010,319 | <p>I'd suggest you to try to cast each value you read to float, then catch typecast ValueError exception and assign it to zero in exception handler.</p>
<p>This will be the most pythonic way</p>
<p>Assuming your CSV contains float values, you should end with something like:</p>
<pre><code>with open('data.csv', 'r') as fd:
# iterate over all lines in csv
for line in fd:
# split and iterate over values in line, maintaining item index
for i, value in enumerate(line.split(',')):
try:
value = float(value)
except ValueError:
# consider undefined/non-float value equals to 0
value = 0.0
# store parsed value wherever you need it
print('value[%d] = %f' % (i, value))
</code></pre>
<p>Alternatively, of only '--undefined--' strings to be handled as '0.0', you can write it like (the innermost loop)</p>
<pre><code> value = float(value) if value != '--undefined--' else 0
</code></pre>
| 0 | 2016-10-13T00:12:30Z | [
"python",
"csv",
"numpy"
] |
Numpy: Read csv, deal with undefined values | 40,010,178 | <p>What is the best way to read data from a csv file into a numpy array when some of the values are labelled as 'undefined' as follows:</p>
<pre><code>0.231620,0.00001,444.157
0.225370,--undefined--,1914.637
0.237870,0.0003,--undefined--
</code></pre>
<p>I have a lot of these files that I will have to loop over, and it is fine to assume that an undefined value should be zero.</p>
| 1 | 2016-10-12T23:56:37Z | 40,010,512 | <p>To read CSV files and replace the values the best way I think it is using Pandas which uses numpy as well</p>
<pre><code>import pandas as pd
df = pd.read_csv('foo.csv', header=None)
df.replace("--undefined--",0.0, inplace=True)
df
0 1 2
0 0.23162 0.00001 444.157
1 0.22537 0 1914.637
2 0.23787 0.0003 0
</code></pre>
| 1 | 2016-10-13T00:37:43Z | [
"python",
"csv",
"numpy"
] |
Numpy: Read csv, deal with undefined values | 40,010,178 | <p>What is the best way to read data from a csv file into a numpy array when some of the values are labelled as 'undefined' as follows:</p>
<pre><code>0.231620,0.00001,444.157
0.225370,--undefined--,1914.637
0.237870,0.0003,--undefined--
</code></pre>
<p>I have a lot of these files that I will have to loop over, and it is fine to assume that an undefined value should be zero.</p>
| 1 | 2016-10-12T23:56:37Z | 40,014,406 | <p>No need for Pandas, just use Numpy.</p>
<pre><code>import numpy as np
x = np.genfromtxt('data.csv', dtype=np.float, delimiter=',',
missing_values='--undefined--', filling_values=0.0,
)
</code></pre>
| 0 | 2016-10-13T07:05:27Z | [
"python",
"csv",
"numpy"
] |
Python plot base64 string as image | 40,010,237 | <p>I am attempting to convert a jpg, which is encoded as a base64 string that I receive over the server into an RGB image that I can use with numpy, but also plot with matplot lib. I am unable to find docs on how to take a raw base64 string and plot that using python.</p>
<p>I also have the option to receive as a png.</p>
<p>Here is where I am currently, which does not work. Feel free to snag the image bytes.</p>
<pre><code>image = '/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCAA2AGADASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwDxNYvapBF7VoLaH0qVbM+ldCgYOZmCH2p3k+1aosm9KeLFv7tVyE85keT7Unk+1bP2Fv7tJ9hb+7RyBzmN5PtSGL2ro7LQri/l2RrgDlnboK318FWqwqWujK7HopC4/A8/lScRqR52YvamGKuzl0/S7G7ltpbaWZkbaSW4BHp0qbUbPT9JZfLtUklcE7GBIA+p/H8qXKNSOEMRPam+Q7EAIST0AFd1pqRXrySC2jhKYxtUd/wrM1K/ljvJooAjRI5VW65APXIqXErmJEnAAJt1x/vH/CrCXSf8+6f99n/Ckg1W6jRUMgkjUYVJVDqPoDxWha6nZGUNe6Vbzj+IoWjJ9OhwPy/xquaXYhwj2/r8Cul0n/PvH/32f8KtWrC5mWJLeAM3QvPtH5kYq0kPhq5iiUTX1pMzfOzqsiKPwwfT/CraeEorwudM1uxnXO2NJGMcjnHQKffgc0/atf0xezh/V/8AhvxMySRY5GRreAlSQcTZH5gc1YtJNPYFrsJHg8KrFs/pUn/CIaul8LOZYopmjMiqZA2QP93OPxwK6rRfBcVvKJry0jmVR92acjnC84UdM7uCe/tk8GJzejh9G7vy/wCHBUoP/h/+CZM7XMFqklnpszW2zfvMbKoXrnOOfXNVtKm36pFLcqqKc5dpOnB9q2tZ0OwW2mjt4hDcyAmGMSNkYySMZIPbv9AO/AXtw1rcvFBOZY1+65UDP4Anv71WDzGGJT5F95bgv6/4c39RFvca1OFWIo05/eCTPG7r0qHxI8BuLfYIpQIsE+Z0O5uKwIdYvbWQyQXDxORgsjYOPTim3Wt3t5t+03EsxX7u9ycV2e0fYlU1tY3tDhE3noERC20D5s+tctLGdx/dL/31/wDWpr3rn/8AXUo1ydI1TyrbCjGTAhP545pObK5Cuj1OsnvWeklTLJQmOxoLJUqykHIOPpWestSCWncRpiefPEsu4rlMHitZbzUTp2A6mTH38n+WK4ya5kEhUOwA6YOKeuqXax7BMdvuAa8qvgZVHdNFqTOosbq7+1RJJI4ZzjkkgjvxW1aaP4U1Wadb7WHtr92fIP3A2TgkkY9+tefR6teRA7LhhkYz3/D0qGO5bzSzsSW6k1vh8NKnJylb5Cep6ZP8LVmtUm0vXba53HgsNq49iCc81z+ofDzxDZNJttlnjQZ3xODnjsOv6Vz6Xk0Lq8UroynKlWxg1q2/jTXrWMomoyMucnzMOfzNddn3/r5Cu/6/4BkXek6lZoHubG4iQnALxkDNZr5U4IIPvXfRfEu8IIu7OKUdtpxj880lx4m8Oak8n2mxVWdfmkeIZPbqOaWvYd/I87SQ1OshoopgSLIakEhoopgRzDd83eq+40UUAG40m7miigC0H+UU1pDRRQBEzmoWkNFFJgf/2Q=='
import base64
import io
from matplotlib import pyplot as plt
from array import array
import numpy as np
i = base64.b64decode(image)
i = np.fromstring(image, np.ubyte)
plt.imshow(i, interpolation='nearest')
plt.show()
</code></pre>
<p>Any assistance is greatly appreciated.</p>
<p>Here is code that generates the encoded string that is sent out by the server:</p>
<pre><code>byte[] bytes = image.EncodeToJPG();
return Convert.ToBase64String(bytes);
</code></pre>
| 1 | 2016-10-13T00:03:34Z | 40,014,667 | <pre><code>image = '/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCAA2AGADASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwDxNYvapBF7VoLaH0qVbM+ldCgYOZmCH2p3k+1aosm9KeLFv7tVyE85keT7Unk+1bP2Fv7tJ9hb+7RyBzmN5PtSGL2ro7LQri/l2RrgDlnboK318FWqwqWujK7HopC4/A8/lScRqR52YvamGKuzl0/S7G7ltpbaWZkbaSW4BHp0qbUbPT9JZfLtUklcE7GBIA+p/H8qXKNSOEMRPam+Q7EAIST0AFd1pqRXrySC2jhKYxtUd/wrM1K/ljvJooAjRI5VW65APXIqXErmJEnAAJt1x/vH/CrCXSf8+6f99n/Ckg1W6jRUMgkjUYVJVDqPoDxWha6nZGUNe6Vbzj+IoWjJ9OhwPy/xquaXYhwj2/r8Cul0n/PvH/32f8KtWrC5mWJLeAM3QvPtH5kYq0kPhq5iiUTX1pMzfOzqsiKPwwfT/CraeEorwudM1uxnXO2NJGMcjnHQKffgc0/atf0xezh/V/8AhvxMySRY5GRreAlSQcTZH5gc1YtJNPYFrsJHg8KrFs/pUn/CIaul8LOZYopmjMiqZA2QP93OPxwK6rRfBcVvKJry0jmVR92acjnC84UdM7uCe/tk8GJzejh9G7vy/wCHBUoP/h/+CZM7XMFqklnpszW2zfvMbKoXrnOOfXNVtKm36pFLcqqKc5dpOnB9q2tZ0OwW2mjt4hDcyAmGMSNkYySMZIPbv9AO/AXtw1rcvFBOZY1+65UDP4Anv71WDzGGJT5F95bgv6/4c39RFvca1OFWIo05/eCTPG7r0qHxI8BuLfYIpQIsE+Z0O5uKwIdYvbWQyQXDxORgsjYOPTim3Wt3t5t+03EsxX7u9ycV2e0fYlU1tY3tDhE3noERC20D5s+tctLGdx/dL/31/wDWpr3rn/8AXUo1ydI1TyrbCjGTAhP545pObK5Cuj1OsnvWeklTLJQmOxoLJUqykHIOPpWestSCWncRpiefPEsu4rlMHitZbzUTp2A6mTH38n+WK4ya5kEhUOwA6YOKeuqXax7BMdvuAa8qvgZVHdNFqTOosbq7+1RJJI4ZzjkkgjvxW1aaP4U1Wadb7WHtr92fIP3A2TgkkY9+tefR6teRA7LhhkYz3/D0qGO5bzSzsSW6k1vh8NKnJylb5Cep6ZP8LVmtUm0vXba53HgsNq49iCc81z+ofDzxDZNJttlnjQZ3xODnjsOv6Vz6Xk0Lq8UroynKlWxg1q2/jTXrWMomoyMucnzMOfzNddn3/r5Cu/6/4BkXek6lZoHubG4iQnALxkDNZr5U4IIPvXfRfEu8IIu7OKUdtpxj880lx4m8Oak8n2mxVWdfmkeIZPbqOaWvYd/I87SQ1OshoopgSLIakEhoopgRzDd83eq+40UUAG40m7miigC0H+UU1pDRRQBEzmoWkNFFJgf/2Q=='
import base64
import io
from matplotlib import pyplot as plt
import matplotlib.image as mpimg
i = base64.b64decode(image)
i = io.BytesIO(i)
i = mpimg.imread(i, format='JPG')
plt.imshow(i, interpolation='nearest')
plt.show()
</code></pre>
| 0 | 2016-10-13T07:20:08Z | [
"python",
"numpy",
"image-processing"
] |
Native Android mobile app test automaton navigation with multiple class elements | 40,010,238 | <p><a href="https://i.stack.imgur.com/Jbt8l.png" rel="nofollow"><img src="https://i.stack.imgur.com/Jbt8l.png" alt="enter image description here"></a></p>
<p>How do you enter text (password), when there is no <code>text</code>, <code>resource-id</code>, <code>content-desc</code> and there is more than one class? i.e. the class name for the <code>username</code> is also <code>android.widget.EditText</code>. I've tried xpath or UISelector as follows, yet it doesn't work:</p>
<pre><code>driver.find_element_by_xpath("//android.widget.EditText[@text='']").send_keys("xxxx")
driver.find_element_by_android_uiautomator("new UiSelector().text('')")
</code></pre>
| 1 | 2016-10-13T00:03:44Z | 40,011,008 | <p>Did you try looking by a class name? You can try the following:</p>
<pre><code>element = driver.find_element_by_class_name('android.widget.EditText')
</code></pre>
<p>If you have more than one element with similar class, find all of them:</p>
<pre><code>elements = driver.find_elements_by_class_name('android.widget.EditText')
</code></pre>
<p>And then you have 2 options.:</p>
<ol>
<li><p>You can iterate over the located elements and check if you can get some meaningful text from each one of them by calling <code>element.text</code>. This is as an attempt to find which element might return something related to password.</p></li>
<li><p>If there is no way to reliably identify which one of the elements is the one you need you will have to just select a predefined element from the list. For example: <code>passField = elements[0]</code>.</p></li>
</ol>
| 2 | 2016-10-13T01:49:40Z | [
"android",
"python",
"automation",
"appium",
"uiautomator"
] |
django-background-tasks indefinite run | 40,010,257 | <p>The docs says,</p>
<p>In Django Background Task, all tasks are implemented as functions (or any other callable).</p>
<p>There are two parts to using background tasks:</p>
<pre><code>creating the task functions and registering them with the scheduler
setup a cron task (or long running process) to execute the tasks
</code></pre>
<p>It appears there is no way to run django-background-tasks indefinitely and periodically, is that correct?</p>
| 1 | 2016-10-13T00:05:28Z | 40,012,554 | <p>If I am understood correctly then You want to execute your tasks periodically without using cron.</p>
<p>You can do using django celery(<a href="https://github.com/celery/django-celery" rel="nofollow">https://github.com/celery/django-celery</a>) or Task Master (<a href="https://github.com/dcramer/taskmaster" rel="nofollow">https://github.com/dcramer/taskmaster</a>)</p>
<p>Hope you are wanting this.</p>
| 0 | 2016-10-13T04:53:33Z | [
"python",
"django",
"django-views"
] |
While reading multiple files with Python, how can I search for the recurrence of an error string? | 40,010,266 | <p>I've just started to play with Python and I'm trying to do some tests on my environment ... the idea is trying to create a simple script to find the recurrence of errors in a given period of time.</p>
<p>Basically I want to count the number of times a server fails on my daily logs, if the failure happens more than a given number of times (let's say 10 times) over a given period of time (let's say 30 days) I should be able to raise an alert on a log, but, I´m not trying to just count the repetition of errors on a 30 day interval... What I would actually want to do is to count the number of times the error happened, recovered and them happened again, this way I would avoid reporting more than once if the problem persists for several days. </p>
<p>For instance, let's say :</p>
<pre><code>file_2016_Oct_01.txt@hostname@YES
file_2016_Oct_02.txt@hostname@YES
file_2016_Oct_03.txt@hostname@NO
file_2016_Oct_04.txt@hostname@NO
file_2016_Oct_05.txt@hostname@YES
file_2016_Oct_06.txt@hostname@NO
file_2016_Oct_07.txt@hostname@NO
</code></pre>
<p>Giving the scenario above I want the script to interpret it as 2 failures instead of 4, cause sometimes a server may present the same status for days before recovering, and I want to be able to identify the recurrence of the problem instead of just counting the total of failures.</p>
<p>For the record, this is how I'm going through the files:</p>
<pre><code># Creates an empty list
history_list = []
# Function to find the files from the last 30 days
def f_findfiles():
# First define the cut-off day, which means the last number
# of days which the scritp will consider for the analysis
cut_off_day = datetime.datetime.now() - datetime.timedelta(days=30)
# We'll now loop through all history files from the last 30 days
for file in glob.iglob("/opt/hc/*.txt"):
filetime = datetime.datetime.fromtimestamp(os.path.getmtime(file))
if filetime > cut_off_day:
history_list.append(file)
# Just included the function below to show how I'm going
# through the files, this is where I got stuck...
def f_openfiles(arg):
for file in arg:
with open(file, "r") as file:
for line in file:
clean_line = line.strip().split("@")
# Main function
def main():
f_findfiles()
f_openfiles(history_list)
</code></pre>
<p>I'm opening the files using 'with' and reading all the lines from all the files in a 'for', but I'm not sure how I can navigate through the data to compare the value related to one file with the older files. </p>
<p>I've tried putting all the data in a dictionary, on a list, or just enumerating and comparing, but I've failed on all these methods :-(</p>
<p>Any tips on what would be the best approach here? Thank you!</p>
| 0 | 2016-10-13T00:06:37Z | 40,010,425 | <p>I'd better handle such with shell utilities (i.e uniq), but, as long as you prefer to use python:</p>
<p>With minimal effor, you can handle it creating appropriate <code>dict</code> object with stings (like 'file_2016_Oct_01.txt@hostname@YES') being the keys.
Iterating over log, you'd check corresponding key exists in dictionary (with <code>if 'file_2016_Oct_01.txt@hostname@YES' in my_log_dict</code>), then assign or increment dict value appropriately.</p>
<p>A short sample:</p>
<pre><code>data_log = {}
lookup_string = 'foobar'
if lookup_string in data_log:
data_log[lookup_string] += 1
else:
data_log[lookup_string] = 1
</code></pre>
<p>Alternatively (one-liner, yet it looks ugly in python most of time, I have had edited it to use line breaks to be visible):</p>
<pre><code>data_log[lookup_string] = data_log[lookup_string] + 1 \
if lookup_string in data_log \
else 1
</code></pre>
| 0 | 2016-10-13T00:26:28Z | [
"python",
"scripting",
"string-iteration"
] |
Python Plotting Pandas SQL Dataframe with Seaborn | 40,010,317 | <p>I am new to data visualization and attempting to make a simple time series plot using an SQL output and seaborn. I am having difficulty inserting the data retrieved from the SQL query into Seaborn. Is there some direction you can give me on how to visualize this dataframe using Seaborn?</p>
<p>My Python Code:</p>
<pre><code>#!/usr/local/bin/python3.5
import cx_Oracle
import pandas as pd
from IPython.display import display, HTML
import matplotlib.pyplot as plt
import seaborn as sns
orcl = cx_Oracle.connect('sql_user/sql_pass//sql_database_server.com:9999/SQL_REPORT')
sql = '''
select DATETIME, FRUIT,
COUNTS
from FRUITS.HEALTHY_FRUIT
WHERE DATETIME > '01-OCT-2016'
AND FRUIT = 'APPLE'
'''
curs = orcl.cursor()
df = pd.read_sql(sql, orcl)
display(df)
sns.kdeplot(df)
plt.show()
</code></pre>
<p>Dataframe (df) output:</p>
<pre><code> DATETIME FRUIT COUNTS
0 2016-10-02 APPLE 1.065757e+06
1 2016-10-03 APPLE 1.064369e+06
2 2016-10-04 APPLE 1.067552e+06
3 2016-10-05 APPLE 1.068010e+06
4 2016-10-06 APPLE 1.067118e+06
5 2016-10-07 APPLE 1.064925e+06
6 2016-10-08 APPLE 1.066576e+06
7 2016-10-09 APPLE 1.065982e+06
8 2016-10-10 APPLE 1.072131e+06
9 2016-10-11 APPLE 1.076429e+06
</code></pre>
<p>When I try to run plt.show() I get the following error:</p>
<pre><code>TypeError: cannot astype a datetimelike from [datetime64[ns]] to [float64]
</code></pre>
| 1 | 2016-10-13T00:12:21Z | 40,010,584 | <p>Instead of <code>sns.kdeplot</code> try the following:</p>
<pre><code># make time the index (this will help with plot ticks)
df.set_index('DATETIME', inplace=True)
# make figure and axis objects
fig, ax = sns.plt.subplots(1, 1, figsize=(6,4))
df.plot(y='COUNTS', ax=ax, color='red', alpha=.6)
fig.savefig('test.pdf')
plt.show()
</code></pre>
<p>The function <code>kdeplot()</code> is not what you want if you're trying to make a line graph. It does make a line, but the line is intended to approximate the distribution of a variable rather than show how a variable changes over time. By far the easiest way to make a line plot is from pandas <code>df.plot()</code>. If you want the styling options of seaborn, you can use <code>sns.plt.subplots</code> to create your axis object (what I do). You can also use <code>sns.set_style()</code> like in <a href="http://stackoverflow.com/questions/31069191/simple-line-plots-using-seaborn">this question</a>. </p>
| 2 | 2016-10-13T00:49:41Z | [
"python",
"pandas",
"matplotlib",
"sqlplus",
"seaborn"
] |
Getting a Generator Object returned when I want the data | 40,010,322 | <p>I am very very new to Python 3, so please be nice.</p>
<p>I have looked at all the documentation I could find regarding this - there does seem to be a lot, it's just I still cannot figure out what to do.</p>
<p>This is my code:</p>
<pre><code>poly = [[36606.0,53223.0],[37332.0,52224.0],[39043.0,53223.0],
[41603.0,53223.0],[42657.0,53278.0],[43123.0,52060.0],
[44054.0,51156.0],[45806.0,51498.0],[46751.0,53237.0],
[46983.0,54606.0],[45861.0,57057.0],[44971.0,58836.0],
[44054.0,60616.0],[43451.0,58138.0],[41850.0,59179.0],
[40850.0,60370.0],[39906.0,59233.0],[38674.0,59179.0],
[35566.0,56249.0],[37592.0,57536.0]]
def perimeter():
return (sum((abs((x1 - x0)**2)+abs((y1 - y0)**2))**.5)
for ((x0, y0), (x1, y1)) in parts1(poly))
def parts1(poly):
return poly[0:] + [poly[0]]
print(perimeter())
</code></pre>
<p>It is running <em>without</em> any errors but I am getting a return of:</p>
<p><code>generator object perimeter.locals.genexpr at 0x7f47d8671c50</code></p>
<p>How do I make it so that it gives me the value/answer?
I am really not sure what is going on.</p>
| 1 | 2016-10-13T00:12:36Z | 40,010,409 | <p>Wrapping an <code>item for item in iterable</code> construct in parentheses makes it a lazy generator expression, which has the appearance you see. Now, the reason it does this instead of giving you an error that you would get from trying to send a non-iterable to <code>sum()</code> is because it doesn't evaluate anything. If you sent this generator expression to <code>list()</code> to evaluate it, you would get an error.</p>
<p>You need to move some parentheses around:</p>
<pre><code>sum((abs((x1 - x0)**2)+abs((y1 - y0)**2))**.5
for ((x0, y0), (x1, y1)) in parts1(poly))
</code></pre>
<p>Now you have <code>sum(expression for element in parts1(poly))</code> rather than <code>(sum(expression) for element in parts1(poly))</code>.</p>
<p>Small test:</p>
<pre><code>>>> x1, x0, y1, y0 = 3, 1, 5, 4
>>> sum((abs((x1 - x0)**2)+abs((y1 - y0)**2))**.5
... for ((x0, y0), (x1, y1)) in [((x0,y0), (x1, y1))])
2.23606797749979
</code></pre>
| 1 | 2016-10-13T00:25:20Z | [
"python",
"python-3.x",
"generator"
] |
Getting a Generator Object returned when I want the data | 40,010,322 | <p>I am very very new to Python 3, so please be nice.</p>
<p>I have looked at all the documentation I could find regarding this - there does seem to be a lot, it's just I still cannot figure out what to do.</p>
<p>This is my code:</p>
<pre><code>poly = [[36606.0,53223.0],[37332.0,52224.0],[39043.0,53223.0],
[41603.0,53223.0],[42657.0,53278.0],[43123.0,52060.0],
[44054.0,51156.0],[45806.0,51498.0],[46751.0,53237.0],
[46983.0,54606.0],[45861.0,57057.0],[44971.0,58836.0],
[44054.0,60616.0],[43451.0,58138.0],[41850.0,59179.0],
[40850.0,60370.0],[39906.0,59233.0],[38674.0,59179.0],
[35566.0,56249.0],[37592.0,57536.0]]
def perimeter():
return (sum((abs((x1 - x0)**2)+abs((y1 - y0)**2))**.5)
for ((x0, y0), (x1, y1)) in parts1(poly))
def parts1(poly):
return poly[0:] + [poly[0]]
print(perimeter())
</code></pre>
<p>It is running <em>without</em> any errors but I am getting a return of:</p>
<p><code>generator object perimeter.locals.genexpr at 0x7f47d8671c50</code></p>
<p>How do I make it so that it gives me the value/answer?
I am really not sure what is going on.</p>
| 1 | 2016-10-13T00:12:36Z | 40,010,467 | <p>I would try something a bit more explicit like this, this matches your expected answer</p>
<pre><code>import itertools
def calculate_length(x0, x1, y0, y1):
return ((x1 - x0)**2+(y1 - y0)**2)**.5
def make_point_pairs(poly):
pairs = zip(poly, poly[1:])
# Close the shape
chain = itertools.chain(pairs, [[poly[-1],poly[0]]])
return chain
def perimeter(poly):
return sum([calculate_length(x0, x1, y0, y1) for ((x0, y0), (x1, y1)) in make_point_pairs(poly)])
</code></pre>
| 0 | 2016-10-13T00:32:07Z | [
"python",
"python-3.x",
"generator"
] |
Getting a Generator Object returned when I want the data | 40,010,322 | <p>I am very very new to Python 3, so please be nice.</p>
<p>I have looked at all the documentation I could find regarding this - there does seem to be a lot, it's just I still cannot figure out what to do.</p>
<p>This is my code:</p>
<pre><code>poly = [[36606.0,53223.0],[37332.0,52224.0],[39043.0,53223.0],
[41603.0,53223.0],[42657.0,53278.0],[43123.0,52060.0],
[44054.0,51156.0],[45806.0,51498.0],[46751.0,53237.0],
[46983.0,54606.0],[45861.0,57057.0],[44971.0,58836.0],
[44054.0,60616.0],[43451.0,58138.0],[41850.0,59179.0],
[40850.0,60370.0],[39906.0,59233.0],[38674.0,59179.0],
[35566.0,56249.0],[37592.0,57536.0]]
def perimeter():
return (sum((abs((x1 - x0)**2)+abs((y1 - y0)**2))**.5)
for ((x0, y0), (x1, y1)) in parts1(poly))
def parts1(poly):
return poly[0:] + [poly[0]]
print(perimeter())
</code></pre>
<p>It is running <em>without</em> any errors but I am getting a return of:</p>
<p><code>generator object perimeter.locals.genexpr at 0x7f47d8671c50</code></p>
<p>How do I make it so that it gives me the value/answer?
I am really not sure what is going on.</p>
| 1 | 2016-10-13T00:12:36Z | 40,010,529 | <p>The first problem is that you have your parentheses in the wrong places. You want to call <code>sum()</code> on a generator expression, but instead you have written a generator expression using <code>sum()</code>. So you might try this:</p>
<pre><code>def perimeter():
return sum(((x1 - x0) ** 2) + ((y1 - y0) ** 2) ** .5
for (x0, y0), (x1, y1) in parts1(poly))
</code></pre>
<p>(I have also taken out your <code>abs()</code> calls, since squaring a number will make it positive, making <code>abs()</code> irrelevant, and deleted some unnecessary parentheses.)</p>
<p>But this still doesn't work: now you get <code>'float' object is not iterable</code>.</p>
<p>This is because you are trying to unpack four values from each element of the list, but each element contains only two. Python unpacks each element to two floats, then tries to unpack each float to two variables. This is where the error message rears its ugly head.</p>
<p>So you need to change <code>parts1()</code> to return a list of a list of lists of lists. That is, each item in the list is a list, which contains two lists, each containing the coordinates of a point (a given point and its successor). One way to do this is to use the built-in <code>zip()</code> function with an offset or rotated copy of the list.</p>
<pre><code>def parts1(poly):
return zip(poly, poly[1:] + poly[:1])
</code></pre>
<p>Finally, you don't really need the separate function <code>parts1()</code>âit can go right in the <code>perimeter()</code> function. And you should pass <code>poly</code> into <code>perimeter()</code>.</p>
<pre><code>def perimeter(poly):
return sum(((x1 - x0) ** 2) + ((y1 - y0) ** 2) ** .5
for (x0, y0), (x1, y1) in zip(poly, poly[1:] + poly[:1]))
</code></pre>
<p>You could do this without the extra copy of the list by iterating over the coordinates in <code>poly</code> and keeping track of the last items you saw. But you couldn't write it as a generator expression. Instead you'd use a regular <code>for</code> loop.</p>
<pre><code>def perimeter(poly):
x0, y0 = poly[-1][0], poly[-1][1]
per = 0.0
for x1, y1 in poly:
per += ((x1 - x0) ** 2) + ((y1 - y0) ** 2) ** .5
x0, y0 = x1, y1
return per
</code></pre>
<p>Not quite as succinct, and not as fast either, but doesn't use as much memory.</p>
| 1 | 2016-10-13T00:39:38Z | [
"python",
"python-3.x",
"generator"
] |
Getting a Generator Object returned when I want the data | 40,010,322 | <p>I am very very new to Python 3, so please be nice.</p>
<p>I have looked at all the documentation I could find regarding this - there does seem to be a lot, it's just I still cannot figure out what to do.</p>
<p>This is my code:</p>
<pre><code>poly = [[36606.0,53223.0],[37332.0,52224.0],[39043.0,53223.0],
[41603.0,53223.0],[42657.0,53278.0],[43123.0,52060.0],
[44054.0,51156.0],[45806.0,51498.0],[46751.0,53237.0],
[46983.0,54606.0],[45861.0,57057.0],[44971.0,58836.0],
[44054.0,60616.0],[43451.0,58138.0],[41850.0,59179.0],
[40850.0,60370.0],[39906.0,59233.0],[38674.0,59179.0],
[35566.0,56249.0],[37592.0,57536.0]]
def perimeter():
return (sum((abs((x1 - x0)**2)+abs((y1 - y0)**2))**.5)
for ((x0, y0), (x1, y1)) in parts1(poly))
def parts1(poly):
return poly[0:] + [poly[0]]
print(perimeter())
</code></pre>
<p>It is running <em>without</em> any errors but I am getting a return of:</p>
<p><code>generator object perimeter.locals.genexpr at 0x7f47d8671c50</code></p>
<p>How do I make it so that it gives me the value/answer?
I am really not sure what is going on.</p>
| 1 | 2016-10-13T00:12:36Z | 40,010,552 | <p>Your code has two problems. One is due to parentheses as @TigerhawkT3 pointed out, and the other is you're not iterating through the points properly. The code below addresses both these issues.</p>
<pre><code>poly = [[36606.0,53223.0],[37332.0,52224.0],[39043.0,53223.0],
[41603.0,53223.0],[42657.0,53278.0],[43123.0,52060.0],
[44054.0,51156.0],[45806.0,51498.0],[46751.0,53237.0],
[46983.0,54606.0],[45861.0,57057.0],[44971.0,58836.0],
[44054.0,60616.0],[43451.0,58138.0],[41850.0,59179.0],
[40850.0,60370.0],[39906.0,59233.0],[38674.0,59179.0],
[35566.0,56249.0],[37592.0,57536.0]]
def pairwise(iterable):
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
a, b = iter(iterable), iter(iterable)
next(b, None)
return zip(a, b)
def parts1(poly):
return poly[0:] + [poly[0]]
def perimeter():
return sum((abs((x1 - x0)**2)+abs((y1 - y0)**2))**.5
for ((x0, y0), (x1, y1)) in pairwise(parts1(poly)))
print(perimeter()) # -> 41095.327046386046
</code></pre>
<p>Also note that you could simplify (and speed up) the calculation you're doing by using the built-in <a href="https://docs.python.org/3/library/math.html#math.hypot" rel="nofollow"><code>math.hypot()</code></a> function:</p>
<pre><code>import math
def perimeter2():
return sum(math.hypot(x1-x0, y1-y0)
for ((x0, y0), (x1, y1)) in pairwise(parts1(poly)))
print(perimeter2()) # -> 41095.327046386046
</code></pre>
| 1 | 2016-10-13T00:43:51Z | [
"python",
"python-3.x",
"generator"
] |
Getting a Generator Object returned when I want the data | 40,010,322 | <p>I am very very new to Python 3, so please be nice.</p>
<p>I have looked at all the documentation I could find regarding this - there does seem to be a lot, it's just I still cannot figure out what to do.</p>
<p>This is my code:</p>
<pre><code>poly = [[36606.0,53223.0],[37332.0,52224.0],[39043.0,53223.0],
[41603.0,53223.0],[42657.0,53278.0],[43123.0,52060.0],
[44054.0,51156.0],[45806.0,51498.0],[46751.0,53237.0],
[46983.0,54606.0],[45861.0,57057.0],[44971.0,58836.0],
[44054.0,60616.0],[43451.0,58138.0],[41850.0,59179.0],
[40850.0,60370.0],[39906.0,59233.0],[38674.0,59179.0],
[35566.0,56249.0],[37592.0,57536.0]]
def perimeter():
return (sum((abs((x1 - x0)**2)+abs((y1 - y0)**2))**.5)
for ((x0, y0), (x1, y1)) in parts1(poly))
def parts1(poly):
return poly[0:] + [poly[0]]
print(perimeter())
</code></pre>
<p>It is running <em>without</em> any errors but I am getting a return of:</p>
<p><code>generator object perimeter.locals.genexpr at 0x7f47d8671c50</code></p>
<p>How do I make it so that it gives me the value/answer?
I am really not sure what is going on.</p>
| 1 | 2016-10-13T00:12:36Z | 40,010,750 | <p>I am also a little confused about your question, it seems that you are not intentionally using the generator and just wants to get the perimeter?
I think it would be better to clean up the function <code>perimeter()</code> a little bit and not use a generator there, and simply iterate through the list <code>poly</code> and taking every adjacent pair and calculate it this way.</p>
<pre><code>poly = [[36606.0,53223.0],[37332.0,52224.0],[39043.0,53223.0],
[41603.0,53223.0],[42657.0,53278.0],[43123.0,52060.0],
[44054.0,51156.0],[45806.0,51498.0],[46751.0,53237.0],
[46983.0,54606.0],[45861.0,57057.0],[44971.0,58836.0],
[44054.0,60616.0],[43451.0,58138.0],[41850.0,59179.0],
[40850.0,60370.0],[39906.0,59233.0],[38674.0,59179.0],
[35566.0,56249.0],[37592.0,57536.0]]
def perimeter():
#return (sum((abs((x1 - x0)**2)+abs((y1 - y0)**2))**.5) \
#for ((x0, y0), (x1, y1)) in parts1(poly))
peri=0
for [x0, y0], [x1, y1] in get_pair(poly):
peri+=((x1-x0)**2 + (y1-y0)**2)**0.5
return peri
def get_pair(poly):
i=0
while i<len(poly):
yield [poly [i],poly [(i+1)%len(poly)]] #The modulo takes the pair of last and first coordinates into account
#So that when poly [i] is the last coordinate it is returned with the first coordinate
i+=1
print(perimeter())
</code></pre>
<p>I used a generator function for <code>get_pair()</code> function, but you can also do it with a loop or some other way. It basically just returns a new pair in the list every time you call it.</p>
| 0 | 2016-10-13T01:12:13Z | [
"python",
"python-3.x",
"generator"
] |
Two Y axis Bar plot: custom xticks | 40,010,524 | <p>I am trying to add custom xticks to a relatively complicated bar graph plot and I am stuck.</p>
<p>I am plotting from two data frames, <code>merged_90</code> and <code>merged_15</code>:</p>
<pre><code>merged_15
Volume y_err_x Area_2D y_err_y
TripDate
2015-09-22 1663.016032 199.507503 1581.591701 163.473202
merged_90
Volume y_err_x Area_2D y_err_y
TripDate
1990-06-10 1096.530711 197.377497 1531.651913 205.197493
</code></pre>
<p>I want to create a bar graph with two axes (i.e. <code>Area_2D</code> and <code>Volume</code>) where the <code>Area_2D</code> and <code>Volume</code> bars are grouped based on their respective data frame. An example script would look like:</p>
<pre><code>import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import scipy
fig = plt.figure()
ax1 = fig.add_subplot(111)
merged_90.Volume.plot(ax=ax1, color='orange', kind='bar',position=2.5, yerr=merged_90['y_err_x'] ,use_index=False , width=0.1)
merged_15.Volume.plot(ax=ax1, color='red', kind='bar',position=0.9, yerr=merged_15['y_err_x'] ,use_index=False, width=0.1)
ax2 = ax1.twinx()
merged_90.Area_2D.plot(ax=ax2,color='green', kind='bar',position=3.5, yerr=merged_90['y_err_y'],use_index=False, width=0.1)
merged_15.Area_2D.plot(ax=ax2,color='blue', kind='bar',position=0, yerr=merged_15['y_err_y'],use_index=False, width=0.1)
ax1.set_xlim(-0.5,0.2)
x = scipy.arange(1)
ax2.set_xticks(x)
ax2.set_xticklabels(['2015'])
plt.tight_layout()
plt.show()
</code></pre>
<p>The resulting plot is:</p>
<p><a href="https://i.stack.imgur.com/jykyX.png" rel="nofollow"><img src="https://i.stack.imgur.com/jykyX.png" alt="Plot missing xtick"></a></p>
<p>One would think I could change:</p>
<pre><code>x = scipy.arange(1)
ax2.set_xticks(x)
ax2.set_xticklabels(['2015'])
</code></pre>
<p>to</p>
<pre><code>x = scipy.arange(2)
ax2.set_xticks(x)
ax2.set_xticklabels(['1990','2015'])
</code></pre>
<p>but that results in:</p>
<p><a href="https://i.stack.imgur.com/9NcYA.png" rel="nofollow"><img src="https://i.stack.imgur.com/9NcYA.png" alt="Disorganized plot"></a></p>
<p>I would like to see the ticks ordered in chronological order (i.e. 1990,2015)</p>
<p>Thanks!</p>
| 0 | 2016-10-13T00:38:55Z | 40,010,901 | <p>Have you considered dropping the second axis and plotting them as follows:</p>
<pre><code>ind = np.array([0,0.3])
width = 0.1
fig, ax = plt.subplots()
Rects1 = ax.bar(ind, [merged_90.Volume.values, merged_15.Volume.values], color=['orange', 'red'] ,width=width)
Rects2 = ax.bar(ind + width, [merged_90.Area_2D.values, merged_15.Area_2D.values], color=['green', 'blue'] ,width=width)
ax.set_xticks([.1,.4])
ax.set_xticklabels(('1990','2015'))
</code></pre>
<p>This produces:</p>
<p><a href="https://i.stack.imgur.com/rLgrF.png" rel="nofollow"><img src="https://i.stack.imgur.com/rLgrF.png" alt="enter image description here"></a></p>
<p>I omitted the error and colors but you can easily add them. That would produce a readable graph given your test data. As you mentioned in comments you would still rather have two axes, presumably for different data with proper scales. To do this you could do:
fig = plt.figure()
ax1 = fig.add_subplot(111)
merged_90.Volume.plot(ax=ax, color='orange', kind='bar',position=2.5, use_index=False , width=0.1)
merged_15.Volume.plot(ax=ax, color='red', kind='bar',position=1.0, use_index=False, width=0.1)
ax2 = ax1.twinx()
merged_90.Area_2D.plot(ax=ax,color='green', kind='bar',position=3.5,use_index=False, width=0.1)
merged_15.Area_2D.plot(ax=ax,color='blue', kind='bar',position=0,use_index=False, width=0.1)
ax1.set_xlim([-.45, .2])
ax2.set_xlim(-.45, .2])
ax1.set_xticks([-.35, 0])
ax1.set_xticklabels([1990, 2015])</p>
<p>This produces:
<a href="https://i.stack.imgur.com/gMrmr.png" rel="nofollow"><img src="https://i.stack.imgur.com/gMrmr.png" alt="enter image description here"></a></p>
<p>Your problem was with resetting just one axis limit and not the other, they are created as twins but do not necessarily follow the changes made to one another.</p>
| 0 | 2016-10-13T01:34:47Z | [
"python",
"pandas",
"matplotlib",
"bar-chart"
] |
How to execute a repeated command in pygame? | 40,010,562 | <p>I've been struggling to get my code to work. I want my image to move continuously while pressing W,A,S, or D instead of having to repeatedly tap the key, but my code keeps having problems. Right now, it says that the video system is not initialized. I don't understand why this is popping up - I already have pygame.init() in my code.</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
left_side = 50
height = 50
screen.blit(my_image, [left_side, height])
#Display changes
pygame.display.flip()
moveLeft = False
moveRight = False
moveUp = False
moveDown = False
#set up pygame event loop
while True:
for event in pygame.event.get():
print event
if event.type == pygame.quit():
running = False
if event.type == pygame.KEYDOWN:
# change the keyboard variables
if event.key == K_LEFT or event.key == ord('a'):
moveRight = False
moveLeft = True
if event.key == K_RIGHT or event.key == ord('d'):
moveLeft = False
moveRight = True
if event.key == K_UP or event.key == ord('w'):
moveDown = False
moveUp = True
if event.key == K_DOWN or event.key == ord('s'):
moveUp = False
moveDown = True
if event.type == pygame.KEYUP:
if event.key == K_ESCAPE:
pygame.quit()
sys.exit()
if event.key == K_LEFT or event.key == ord('a'):
moveLeft = False
if event.key == K_RIGHT or event.key == ord('d'):
moveRight = False
if event.key == K_UP or event.key == ord('w'):
moveUp = False
if event.key == K_DOWN or event.key == ord('s'):
moveDown = False
pygame.quit()
</code></pre>
<p>Thanks!</p>
| 0 | 2016-10-13T00:45:56Z | 40,036,184 | <p>I've had a bit of a muck around with your code and have fixed some of your little errors... Hopefully you can read through my comments some of the reasoning of why I've changed a few things. Also, your code was getting the video error because of a few reasons I believe: 1. You were constantly calling <code>pygame.quit()</code> because it was checking if the key 'escape' was not being pressed (<code>pygame.KEYUP</code>) 2. You are meant to put '<code>pygame.display.flip()</code>' into the game loop itself so it can update the screen not just once and that's it.</p>
<p>You also needed to <code>import sys</code> in order to use the <code>sys.exit()</code> call.</p>
<p>Although the video error is fixed, your image doesn't move... Hopefully you figure out why.. :) Happy Coding!</p>
<p>-Travis</p>
<pre><code>import pygame
# Initialize pygame and create the window!
pygame.init()
screen = pygame.display.set_mode((800,600))
#Creating background Surface and setting the colour.
background = pygame.Surface(screen.get_size())
background.fill((255,255,0))
# Loading a few needed variables.
my_image = pygame.image.load("dogtest.png")
left_side = 50
height = 50
moveLeft = False
moveRight = False
moveUp = False
moveDown = False
# These varibales are standard when making a game of some sort!
total_frames = 0 #How many frames have passed.
clock = pygame.time.Clock() # Use this in the main loop to set game running
# at a certain speed!
FPS = 60
running = True #The game condition (whether the loop runs or not!)
while running:
# This is constantly repeating if the user presses the 'x' to close the
# program so the program closes safely and efficiently!
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.quit()
if event.type == pygame.KEYDOWN: # This handles Key Presses!
if event.key == pygame.K_ESCAPE:
running = False
pygame.quit()
sys.exit()
if event.key == pygame.K_LEFT or event.key == ord('a'):
moveRight = False
moveLeft = True
if event.key == pygame.K_RIGHT or event.key == ord('d'):
moveLeft = False
moveRight = True
if event.key == pygame.K_UP or event.key == ord('w'):
moveDown = False
moveUp = True
if event.key == pygame.K_DOWN or event.key == ord('s'):
moveUp = False
moveDown = True
if event.type == pygame.KEYUP: # This is checking if the key ISN'T being pressed!
if event.key == pygame.K_LEFT or event.key == ord('a'):
moveLeft = False
if event.key == pygame.K_RIGHT or event.key == ord('d'):
moveRight = False
if event.key == pygame.K_UP or event.key == ord('w'):
moveUp = False
if event.key == pygame.K_DOWN or event.key == ord('s'):
moveDown = False
# Blitting the Background surface and image!
screen.blit(background, (0, 0))
screen.blit(my_image, (left_side, height))
clock.tick(FPS) # Sets the speed in which the code runs, (and the game!)
total_frames += 1 # Keeps a variable storing the number of frames have passed
pygame.display.update() # Constanly updates the screen! You can also use: pygame.display.flip()
quit()
</code></pre>
| 0 | 2016-10-14T06:15:44Z | [
"python"
] |
elif statement not working as expected | 40,010,630 | <p>I'm trying to look through multiple sources to see which one has a specific entry.</p>
<p>My input looks like:</p>
<pre><code>json_str2 = urllib2.urlopen(URL2).read()
u = json.loads(json_str2)
#load all five results
One = u['flightStatuses'][0]
Two = u['flightStatuses'][1]
Three = u['flightStatuses'][2]
Four = u['flightStatuses'][3]
Five = u['flightStatuses'][4]
</code></pre>
<p>My <code>if</code> statement works correctly and I get the correct result:</p>
<pre><code>if One['flightNumber'] == str(FlEnd):
fnumber = One['flightId']
print fnumber
</code></pre>
<p>But when I add the <code>elif:</code> the answer is wrong (nothing) even when the first statement is <code>True</code>.</p>
<p>I don't understand why the <code>elif</code> doesn't work?</p>
<pre><code># if statement checks each result to define flightId, needed for tracking.
if One['flightNumber'] == str(FlEnd):
fnumber = One['flightId']
elif Two['flightNumber'] == str(FlEnd):
fnumber = Two['flightId']
print fnumber
</code></pre>
| 0 | 2016-10-13T00:55:53Z | 40,010,662 | <p>You should write this as a loop over the five flight statuses instead of using five variables and five conditions.</p>
<pre><code>results = json.loads(urllib2.urlopen(URL2).read())['flightStstuses']
for result in results:
if result['flightNumber'] == str(FlEnd):
fnumber = result['flightId']
break
else:
fnumber = None
print fnumber
</code></pre>
| 3 | 2016-10-13T01:00:30Z | [
"python",
"if-statement",
"comparison"
] |
Script for sorting lines | 40,010,631 | <p>I have a file that has content as below</p>
<pre><code>hi hello 123
cat dog 456
boy 456
Ind us 90
Can 67
</code></pre>
<p>I am trying to sort lines in this file to something like this</p>
<pre><code> boy 456
Can 67
hi hello 123
cat dog 456
Ind us 90
</code></pre>
<p>My code:</p>
<pre><code>file = open("filename",'w')
column = []
for line in file:
column.append(int(line.split()[0]))
column.sort()
file.close()
</code></pre>
<p>I didn't get desired output. </p>
<p>I am trying to sort elements based on first element of the row. If first element is empty that line should be printed first. Lines with first element of the row not empty should be printed later</p>
<p>Please help</p>
| -1 | 2016-10-13T00:55:56Z | 40,010,857 | <p>File content</p>
<pre><code>hi hello 123
cat dog 456
boy 456
Ind us 90
Can 67
</code></pre>
<p>Basically, use the <code>key</code> of the <code>sorted</code> function to sort based upon the length of the split string. </p>
<pre><code>with open("filename") as f:
lines = f.read().splitlines()
lines = sorted(lines, key=lambda l: len(l.split()))
for line in lines:
print(line)
</code></pre>
<p>Output</p>
<pre><code> boy 456
Can 67
hi hello 123
cat dog 456
Ind us 90
</code></pre>
| 1 | 2016-10-13T01:28:35Z | [
"python",
"python-3.x",
"sorting"
] |
How to carry a digit when doing binary addition? | 40,010,655 | <p>Code:</p>
<pre><code>def add_bitwise(b1, b2):
'''Adds two binary numbers.'''
if b1 == '':
return b2
elif b2 == '':
return b1
else:
sum_rest = add_bitwise(b1[:-1],b2[:-1])
if b1[-1] == '0' and b2[-1] == '0':
return sum_rest + '0'
elif b1[-1] == '1' and b2[-1] == '0':
return sum_rest + '1'
elif b1[-1] == '0' and b2[-1] == '1':
return sum_rest + '1'
elif b1[-1] == '1' and b2[-1] == '1':
return sum_rest + add_bitwise(b2[:-1],'1') + '0'
</code></pre>
<p>So I have to make this function that takes two binary numbers and adds them. This has to be done using recursion and cannot convert the numbers to decimal, add and then convert back to binary. So my base cases say that if one binary number is empty return the other and vice a versa. Then for my recursive call if two zeroes are added it returns 0 and the recursive call. If a 0 and a 1 are added it adds one and a recursive call. </p>
<p>Now here's where I'm stuck. Two ones makes 0 and then you have to carry a 1 to the next side but I can't figure out how to do this within the second recursive call. Sum rest is the normal recursive call, then follows the recursive call to carry the digit, and then the 0. The function must stay as designed but the recursive call needs to be fixed. </p>
| 1 | 2016-10-13T00:59:59Z | 40,010,869 | <p>Your overflow recursions must sum up <code>'1'</code> against <code>sum_rest</code>, not <code>b2[:-1]</code>. Overflow is carried over to the higher-valued digits.</p>
<p>Here's a slightly shorter implementation:</p>
<pre><code>def ab(b1, b2):
if not (b1 and b2): # b1 or b2 is empty
return b1 + b2
head = ab(b1[:-1], b2[:-1])
if b1[-1] == '0': # 0+1 or 0+0
return head + b2[-1]
if b2[-1] == '0': # 1+0
return head + '1'
# V NOTE V <<< push overflow 1 to head
return ab(head, '1') + '0'
</code></pre>
<p>For example, consider the binaries <code>'011'</code> and <code>110</code>. You'd do the following operations by hand:</p>
<ul>
<li><code>0 + 1 => 1</code>, keep 1, no overflow</li>
<li><code>1 + 1 => 10</code>, keep 0, overflow</li>
<li><code>0 + 1 + 1 => 10</code>, keep 0, overflow</li>
<li><code>/ + / + 1 => 1</code>, keep 1, no overflow</li>
</ul>
| 2 | 2016-10-13T01:29:53Z | [
"python",
"recursion",
"binary",
"addition"
] |
Apache2 server run script as specific user | 40,010,657 | <p>I am using Ubuntu server 12.04 to run Apache2 web server.</p>
<p>I am hosting several webpages, and most are working fine.</p>
<p>One page is running a cgi script which mostly works (I have the python code working outside Apache building the html code nicely.)</p>
<p>However, I am calling a home automation program (heyu) and it is returning different answers then when I run it in my user account.</p>
<p>Is there a way I can...</p>
<p>1 call the heyu program from my python script as a specific user, (me) and leave the rest of the python code and cgi code alone?</p>
<p>2, configure apache2 to run the cgi code, as a whole, as me? I would like to leave all the other pages unchanged. Maybe using the sites_available part.</p>
<p>3, at least determine which user is running the cgi code so maybe I can get heyu to be OK with that user.</p>
<p>Thanks, Mark.</p>
| 0 | 2016-10-13T01:00:17Z | 40,065,573 | <p>It looks like I could use suEXEC.</p>
<p>It is an Apache module that is not installed at default because they really don't want you to use it. It can be installed using the apt-get scheme.</p>
<p>That said, I found the real answer to my issue, heyu uses the serial ports to do it's work. I needed to add www-data to the dialout group then reboot.</p>
<p>This circumvented the need to run my code as me (as I had already add me to the dialout group a long time ago) in favor of properly changing the permissions.</p>
<p>Thanks.</p>
| 0 | 2016-10-16T00:24:26Z | [
"php",
"python",
"apache"
] |
Apache2 server run script as specific user | 40,010,657 | <p>I am using Ubuntu server 12.04 to run Apache2 web server.</p>
<p>I am hosting several webpages, and most are working fine.</p>
<p>One page is running a cgi script which mostly works (I have the python code working outside Apache building the html code nicely.)</p>
<p>However, I am calling a home automation program (heyu) and it is returning different answers then when I run it in my user account.</p>
<p>Is there a way I can...</p>
<p>1 call the heyu program from my python script as a specific user, (me) and leave the rest of the python code and cgi code alone?</p>
<p>2, configure apache2 to run the cgi code, as a whole, as me? I would like to leave all the other pages unchanged. Maybe using the sites_available part.</p>
<p>3, at least determine which user is running the cgi code so maybe I can get heyu to be OK with that user.</p>
<p>Thanks, Mark.</p>
| 0 | 2016-10-13T01:00:17Z | 40,076,879 | <p>Seeing as you are using python, you can use the following to extract the user that the python script as running as;</p>
<pre><code>from getpass import getuser
print getuser()
</code></pre>
<p>When you hit the page, you'll get the username that the script ran as - and you can from there adjust the permissions of that specific user accordingly.</p>
| 0 | 2016-10-17T00:11:57Z | [
"php",
"python",
"apache"
] |
Checking if the value for the key is the same as before | 40,010,727 | <p>I have been working on this code and I cannot find a answer.</p>
<ol>
<li><p>I have 2 lists</p>
<pre><code>point_values = [1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, 3, 1, 1, 3, 10, 1, 1, 1, 1, 4, 4, 8, 4, 10]
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
</code></pre></li>
<li><p>I want to set <code>a:1</code> and <code>b:3</code> and so on...and I want them put in a dictionary called <code>point_letters</code>.</p></li>
</ol>
<p>This is my starter code.</p>
<pre><code>point_letters = {}
point_values = [1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, 3, 1, 1, 3, 10, 1, 1, 1, 1, 4, 4, 8, 4, 10]
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
for x in letters:
for i in point_values:
if point_letters[x] != i: # is what I'm trying to do
point_letters[x] = i
print(point_letters)
</code></pre>
<p>How should I do this?</p>
| -3 | 2016-10-13T01:08:44Z | 40,010,740 | <pre><code>point_letters = dict(zip(letters, point_values))
</code></pre>
<p><code>zip</code> makes a list of pairs of corresponding elements; <code>dict</code> converts the list of pairs to a dictionary.</p>
<p>EDIT: changed the dict name. Also in response to comments, and the posted code:</p>
<blockquote>
<p>This is great, but I still have not learned this. Is there a way to for loop it?</p>
</blockquote>
<p>In general, in the real world, you'd use the above method. <code>for</code> is very low-level and you'd want to avoid it when you can. For the class, I won't solve your problem, but give you hints instead (so it's not plagiarism):</p>
<ul>
<li><p>You want to pair up the <code>letters[i]</code> and <code>point_values[i]</code> for the same <code>i</code></p></li>
<li><p><code>i</code> should be going from <code>0</code> to the maximum index - one less than the length of your lists</p></li>
<li><p>You can get a length of a list using <code>len</code></p></li>
<li><p>You can get a range using <code>range</code> (Python 3) or <code>xrange</code> (Python 2)</p></li>
</ul>
<p>In your code,</p>
<ul>
<li><p>Having two loops is not what you need to do</p></li>
<li><p>Your <code>if</code> cannot ever be true.</p></li>
</ul>
<p>EDIT2: Changed "array" to "list", because Python has to be a special snowflake.</p>
| 4 | 2016-10-13T01:11:05Z | [
"python",
"dictionary"
] |
Basic unittest TestCase | 40,010,819 | <p>I have written the below code to test a basic unittest case for learning. When I execute the below code. I do not get any output. Could someone let me know what could be issue.</p>
<pre><code>import unittest
class test123(unittest.TestCase):
def test1(self):
print "test1"
if __name__ == "main":
x=test123()
x.test1()
unittest.main()
</code></pre>
| 0 | 2016-10-13T01:22:05Z | 40,010,973 | <p>your code should look like this:</p>
<pre><code>import unittest
class test123(unittest.TestCase):
def test1(self):
print "test1"
if __name__ == "__main__":
unittest.main()
</code></pre>
<p>hence it is name and main with two underscores at the start and end, when you change it and run it with your code then you will get an error with using:</p>
<pre><code>x = test123()
x.test1()
ValueError: no such test method in <class '__main__.test123'>: runTest
</code></pre>
| 2 | 2016-10-13T01:43:43Z | [
"python",
"python-unittest"
] |
Basic unittest TestCase | 40,010,819 | <p>I have written the below code to test a basic unittest case for learning. When I execute the below code. I do not get any output. Could someone let me know what could be issue.</p>
<pre><code>import unittest
class test123(unittest.TestCase):
def test1(self):
print "test1"
if __name__ == "main":
x=test123()
x.test1()
unittest.main()
</code></pre>
| 0 | 2016-10-13T01:22:05Z | 40,011,908 | <p>In your test you need two things:</p>
<ol>
<li>Define your test function with 'test'</li>
<li>You need a expected result</li>
</ol>
<p>test.py</p>
<pre><code>import unittest
class TestHello(unittest.TestCase):
def test_hello(self): # Your test function usually need define her name with test
str_hello = 'hello'
self.assertEqual(str_hello, 'hello') # you need return a expected result
def test_split(self):
str_hello = 'hello world'
self.assertEqual(str_hello.split(), ['hello', 'world'])
if __name__ == '__main__':
unittest.main()
</code></pre>
<p>for execute use:</p>
<pre><code>python -m unittest test
</code></pre>
<p>out:</p>
<pre><code>stackoverflow$ python -m unittest test
..
----------------------------------------------------------------------
Ran 2 tests in 0.000s
OK
</code></pre>
| 1 | 2016-10-13T03:38:31Z | [
"python",
"python-unittest"
] |
How to extract exif data into a csv file? | 40,010,954 | <pre><code>import pyexiv2
import os
print "Enter the full path to the directory that your images are conatined in."
print "-------------------------------------------"
newFileObj = open('C:\\users\\wilson\\desktop\\Metadata.csv', 'w')
targ_dir = raw_input('Path: ')
targ_files = os.listdir(targ_dir)
def getEXIFdata (imageFile):
if imageFile.endswith(".db"):
f = 1
else:
EXIFData = pyexiv2.ImageMetadata(imageFile)
EXIFData.read()
CamMake = EXIFData['Exif.Image.Make']
DateTime = EXIFData['Exif.Image.DateTime']
CamModel = EXIFData['Exif.Image.Model']
for image in targ_files:
getEXIFdata(targ_dir+"\\"+img)
newFileObj.write(DateTime+' , '+CamMake+' , '+CamModel+'\r\n')
newFileObj.close()
end = raw_input("Press Enter to Finish: ")
</code></pre>
<p>This is what I have so far, but I just dont understand how to actually get the data into the file. It crates the file, but it is just blank. I've tried moving around the bottom for, but I just can't seem to get it to work. I am new to python, so please if you could keep it simple when you hint at what I should do.</p>
| 0 | 2016-10-13T01:41:34Z | 40,019,272 | <p>If you want to get data of exif, use <code>.value</code> to get value of data.
Here is an example.</p>
<pre><code># -*-coding:utf-8-*-
import sys
import csv
import os
import argparse
import pyexiv2
def main():
parser = argparse.ArgumentParser(description="Change the txt file to csv.")
parser.add_argument("-i", action="store", dest="infile")
parser.add_argument("-o", action="store", dest="outfile")
parser_argument = parser.parse_args()
fatherdir = os.getcwd() # code directory
inputfile = outputfile = None
# input exif file
if parser_argument.infile:
infilepaths = os.path.split(parser_argument.infile)
# 'C:\User\lenovo\Desktop\pakistan.txt' ---> ['C:\User\lenovo\Desktop','pakistan.txt']
if infilepaths[0]: # full path
inputfile = parser_argument.infile
fatherdir = infilepaths[0]
# 'pakistan.txt' ---> ['','pakistan.txt']
else: # only file name
inputfile = fatherdir + '/' + parser_argument.infile
# output csv file
if parser_argument.outfile:
outfilepaths = os.path.split(parser_argument.outfile)
if outfilepaths[0]: # full path
outputfile = parser_argument.outfile
else:
outputfile = fatherdir + '/' + parser_argument.outfile
else:
outputfile = fatherdir + '/test_csv.csv'
parse(inputfile, outputfile)
def parse(inputfile, outputfile):
csvcontent = file(outputfile, 'wb')
writer = csv.writer(csvcontent)
exif_data = getEXIFdata(inputfile)
writer.writerow([exif_data['Exif.Image.Orientation'].value,
exif_data['Exif.Photo.PixelXDimension'].value,
exif_data['Exif.Photo.PixelYDimension'].value])
# for line in open(inputfile).readlines():
# writer.writerow([a for a in line.split('\t')])
csvcontent.close()
def getEXIFdata (imageFile):
if imageFile.endswith(".db"):
print 'Skip this file'
else:
exif_data = pyexiv2.ImageMetadata(imageFile)
exif_data.read()
for s, v in exif_data.items():
print s, v
cam_a = exif_data['Exif.Image.Orientation'].value
cam_b = exif_data['Exif.Photo.PixelXDimension'].value
cam_c = exif_data['Exif.Photo.PixelYDimension'].value
# add exif value
ekey = 'Exif.Photo.UserComment'
evalue = 'A comment.'
exif_data[ekey] = pyexiv2.ExifTag(ekey, evalue)
#metadata.write()
return exif_data
if __name__ == '__main__':
main()
</code></pre>
<p>run this code like this </p>
<pre><code>python exif2csv.py -i wifi.jpg -o demo_csv.csv
</code></pre>
<p>If you want to loop files in directory, I think you can figure it out by yourself.</p>
| 0 | 2016-10-13T11:05:16Z | [
"python",
"csv",
"metadata",
"exif",
"pyexiv2"
] |
How to output array in hive python UDF | 40,011,104 | <p>I used python to do UDF in hive. Is there some method to output array/map such structured data from UDF?
I am tried to return a python list in UDF, but it can't be convert to a hive array.</p>
| 0 | 2016-10-13T02:03:37Z | 40,016,073 | <p>When you are trying to return a python list in UDF, I suggest that you split the list and process each data step by step.
Here is an example.Use 'TRANSFORM' in hive wisely.</p>
<pre><code>#!/usr/bin/env python
#-*- coding:utf-8 -*-
# demo.py
import sys
import datetime
import time
#Turn the timestamp into string
def timestamp_toString(stamp):
return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(stamp))
for line in sys.stdin:
print timestamp_toString(float(line))
</code></pre>
<p>in hive console </p>
<pre><code>hive> add file /ebs/hive/test/demo.py;
select TRANSFORM(time) using 'python demo.py' as (time) from (select * from access_fccs where week=41 limit 10) a ;
</code></pre>
| 0 | 2016-10-13T08:35:50Z | [
"python",
"hive",
"udf"
] |
tracking all child process spawned by a root process | 40,011,209 | <p>I'm inspecting a certain make system that runs compilers. I want to track all child processes ever spawned by such a "root" process.</p>
<p>I'm aware there's the <code>ps</code> command and as I'm a Python user, the <code>psutil</code> package. But I'm not sure if I'll miss some short lived processes between the calls.</p>
<p>I think what I really want is something like <code>inotify</code> (or <code>watchdog</code> in Python), but instead of tracking directory, it tracks all child process activity.</p>
<p>Is there such a system call, or preferably, package of Python, that does this?</p>
<p>Thanks in advance.</p>
| 1 | 2016-10-13T02:14:57Z | 40,011,910 | <p><code>sttace</code> can provide that info. But you may have to parse the output to get just the info you are interested in.</p>
<pre><code>strace -f -e trace=process <executable>
</code></pre>
<p>That will trace all child processes of <code><executable></code> and will trace only the process related syscalls (essentially <code>wait</code>, <code>fork</code>, <code>clone</code> and <code>exec</code>).</p>
| 1 | 2016-10-13T03:38:46Z | [
"python",
"linux",
"process"
] |
How to ensure repeated characters are accounted for in a for loop in python | 40,011,226 | <p>I'm working through the exercises in a textbook and I'm asked to create a numerology program that takes a name, assigns each letter a value based on ascending order in the alphabet and returns the sum of the letters. </p>
<p>The code I've written works fine for any name that doesn't repeat a letter. For example if the name is 'kayla', I know the if statement will stop at the first instance of 'a'. Is there a way within its current design to catch multiple letters or does it need to sort through the letters a different way?</p>
<pre><code>def main():
alphabet = 'abcdefghijklmnopqrstuvwxyxz'
user_name = raw_input('Please enter your name ')
value = sum = 0
for char in alphabet:
value = value + 1
if char in user_name:
sum = sum + value
print sum
</code></pre>
| 1 | 2016-10-13T02:18:10Z | 40,011,272 | <p>Since you are working through a textbook, and I presume don't just want the answer, here is a hint. You are iterating (looping) over the wrong thing. You should be looping over <code>user_name</code>, not <code>alphabet</code>.</p>
<p><strong>Update</strong>. If you want a nice "Pythonic" solution to your problem, this is one way:</p>
<pre><code>user_name = raw_input('Please enter your name ')
print sum(ord(letter.upper())-64 for letter in user_name)
</code></pre>
<p><strong>Explanation</strong>:</p>
<ol>
<li><code>ord</code> returns an ASCII code for a character, such as <code>65</code> for <code>'A'</code></li>
<li>ASCII codes for A-Z are 65 through 90, in just the right order</li>
<li>Subtracting 64 gives you <code>1</code> for <code>A</code>, <code>2</code> for <code>B</code>, and so on</li>
<li><code>sum</code> is a built-in function that does just what you would expect</li>
<li>the parameter to <code>sum</code> is an expression that evaluates to a sequence of numbers, one for each of the letters in <code>user_name</code></li>
</ol>
| 1 | 2016-10-13T02:23:02Z | [
"python",
"for-loop"
] |
How to ensure repeated characters are accounted for in a for loop in python | 40,011,226 | <p>I'm working through the exercises in a textbook and I'm asked to create a numerology program that takes a name, assigns each letter a value based on ascending order in the alphabet and returns the sum of the letters. </p>
<p>The code I've written works fine for any name that doesn't repeat a letter. For example if the name is 'kayla', I know the if statement will stop at the first instance of 'a'. Is there a way within its current design to catch multiple letters or does it need to sort through the letters a different way?</p>
<pre><code>def main():
alphabet = 'abcdefghijklmnopqrstuvwxyxz'
user_name = raw_input('Please enter your name ')
value = sum = 0
for char in alphabet:
value = value + 1
if char in user_name:
sum = sum + value
print sum
</code></pre>
| 1 | 2016-10-13T02:18:10Z | 40,011,408 | <p>The <code>in</code> function only verifies if an element is present in a list. You can resolve the problem in a lot of ways but I think a good approach to learn is to create a dictionary to store letter, value pairs and then iterate over the name characters to sum the values:</p>
<pre><code>def main():
alphabet = 'abcdefghijklmnopqrstuvwxyxz'
values, val = {}, 1
for char in alphabet:
values[char] = val
val += 1
print values
user_name = raw_input('Please enter your name ')
value = sum = 0
for char in user_name.lower():
sum += values[char]
print sum
if __name__ == '__main__':
main()
</code></pre>
<p>Another form is using index string function to get the value of the position of the letter in the string.
Here is the example code:</p>
<pre><code>def main():
alphabet = 'abcdefghijklmnopqrstuvwxyxz'
user_name = raw_input('Please enter your name ')
sum = 0
for char in user_name.lower():
sum += alphabet.index(char) + 1
print sum
if __name__ == '__main__':
main()
</code></pre>
| 1 | 2016-10-13T02:40:45Z | [
"python",
"for-loop"
] |
How to ensure repeated characters are accounted for in a for loop in python | 40,011,226 | <p>I'm working through the exercises in a textbook and I'm asked to create a numerology program that takes a name, assigns each letter a value based on ascending order in the alphabet and returns the sum of the letters. </p>
<p>The code I've written works fine for any name that doesn't repeat a letter. For example if the name is 'kayla', I know the if statement will stop at the first instance of 'a'. Is there a way within its current design to catch multiple letters or does it need to sort through the letters a different way?</p>
<pre><code>def main():
alphabet = 'abcdefghijklmnopqrstuvwxyxz'
user_name = raw_input('Please enter your name ')
value = sum = 0
for char in alphabet:
value = value + 1
if char in user_name:
sum = sum + value
print sum
</code></pre>
| 1 | 2016-10-13T02:18:10Z | 40,011,669 | <p>A very simple way using list comprehension and the built-in <code>sum</code> function:</p>
<pre><code> alphabet = 'abcdefghijklmnopqrstuvwxyxz'
user_name = raw_input('Please enter your name ')
user_name = user_name.lower().strip()
value = sum([alphabet.index(c)+1 for c in user_name])
print(value)
</code></pre>
| 0 | 2016-10-13T03:10:58Z | [
"python",
"for-loop"
] |
If Statement - Nested Conditional Using Modulus Operator in Python | 40,011,264 | <p>I need to create a program in Python that asks the user for a number, then tells the user if that number is even or if it's divisible by 5. If neither is true, do not print anything. For example: </p>
<pre><code>Please enter a number: 5
This number is divisible by 5!
Please enter a number: 7
Please enter a number: 20
This number is even!
This number is divisible by 5!
</code></pre>
<p>I tried to copy the method that was used in <a href="http://stackoverflow.com/questions/8002217/how-do-you-check-whether-a-number-is-divisible-by-another-number-python">this answer</a>, but I'm getting an error message on line 8: </p>
<pre><code>SyntaxError: invalid syntax (<string>, line 8) (if Num_1 % 2 == 0)
</code></pre>
<p>Here is my code: </p>
<pre><code>#TODO 1: Ask for user input
Num1 = input("Please enter a number")
#TODO 2: Turn input into integer
Num_1 = int(Num1)
#TODO 2: Use conditionals to tell the user whether or not their
#number is even and/or divisible by 5
if Num_1 % 2 == 0
print ("This number is even!")
if Num_1 % 5 == 0
print ("This number is divisible by 5!")
</code></pre>
<p>Since I'm using the modulus operator to determine whether or not Num_1 is an exact multiple of 2, I should be returning a value of True and therefore should print "This number is even!" But instead I'm getting this error message - why? Thanks!</p>
| 0 | 2016-10-13T02:21:56Z | 40,011,350 | <p>The start of each Python block should end with a colon <code>:</code>. Also take note of the indentation.</p>
<pre><code>Num1 = input("Please enter a number")
Num_1 = int(Num1)
if Num_1 % 2 == 0:
print ("This number is even!")
if Num_1 % 5 == 0:
print ("This number is divisible by 5!")
</code></pre>
| 2 | 2016-10-13T02:31:39Z | [
"python",
"if-statement",
"int",
"modulus"
] |
'B': "{:0<4.0f}" | How should I read this? | 40,011,269 | <p>While studying <a href="http://pandas.pydata.org/pandas-docs/stable/style.html" rel="nofollow">Pandas Style</a>, I got to the following:</p>
<pre><code>df.style.format("{:.2%}")
</code></pre>
<p>Which I understand means, turn every value to 2 decimal places and add a <code>%</code> in the end.</p>
<p>Just after that, there is:</p>
<pre><code>df.style.format({'B': "{:0<4.0f}", 'D': '{:+.2f}'})
</code></pre>
<p>How should I read <code>'B': "{:0<4.0f}"</code>?</p>
| 0 | 2016-10-13T02:22:50Z | 40,011,358 | <p>As according to the <a href="http://pandas.pydata.org/pandas-docs/stable/style.html#Finer-Control:-Display-Values" rel="nofollow">Pandas Style documentation</a> you linked to, it's a python <a href="https://docs.python.org/3/library/string.html#format-specification-mini-language" rel="nofollow">format specification string</a>.</p>
<p>The specific options break down to:</p>
<ul>
<li><code>0<</code> Forces the field to be left-aligned within the available space, and pads with zeros</li>
<li><code>4</code> Specifies the width of the field</li>
<li><code>.0</code> Specifies the precision of the number, i.e. how many decimal points should be displayed</li>
<li><code>f</code> Displays the number as a fixed-point number.</li>
</ul>
| 0 | 2016-10-13T02:32:48Z | [
"python",
"python-2.7",
"pandas"
] |
'B': "{:0<4.0f}" | How should I read this? | 40,011,269 | <p>While studying <a href="http://pandas.pydata.org/pandas-docs/stable/style.html" rel="nofollow">Pandas Style</a>, I got to the following:</p>
<pre><code>df.style.format("{:.2%}")
</code></pre>
<p>Which I understand means, turn every value to 2 decimal places and add a <code>%</code> in the end.</p>
<p>Just after that, there is:</p>
<pre><code>df.style.format({'B': "{:0<4.0f}", 'D': '{:+.2f}'})
</code></pre>
<p>How should I read <code>'B': "{:0<4.0f}"</code>?</p>
| 0 | 2016-10-13T02:22:50Z | 40,011,362 | <p>This is the "new" formatting string syntax, explained in <a href="https://docs.python.org/2/library/string.html#format-specification-mini-language" rel="nofollow">https://docs.python.org/2/library/string.html#format-specification-mini-language</a>.</p>
<ul>
<li>The first <code>0</code> means pad with "0"</li>
<li>The <code><</code> means <a href="https://docs.python.org/2/library/string.html#grammar-token-align" rel="nofollow">align</a> to the left (so the number will be followed by a bunch of 0's, e.g. '4' will be formatted as "400000â¦")</li>
<li>The <code>4</code> means the <a href="https://docs.python.org/2/library/string.html#grammar-token-width" rel="nofollow">minimum width</a> is 4 characters</li>
<li>The <code>.0</code> means the <a href="https://docs.python.org/2/library/string.html#grammar-token-precision" rel="nofollow">precision</a> is 0, i.e. don't show any decimal parts.</li>
<li>The <code>f</code> means the <a href="https://docs.python.org/2/library/string.html#grammar-token-type" rel="nofollow">type</a> is a fixed-point number.</li>
</ul>
<p>Examples:</p>
<pre><code>>>> '{:0<4.0f}'.format(1)
'1000'
>>> '{:0<4.0f}'.format(3.14)
'3000'
>>> '{:0<4.0f}'.format(26)
'2600'
>>> '{:0<4.0f}'.format(77777)
'77777'
>>> '{:0<4.0f}'.format(-3)
'-300'
</code></pre>
| 1 | 2016-10-13T02:33:26Z | [
"python",
"python-2.7",
"pandas"
] |
'B': "{:0<4.0f}" | How should I read this? | 40,011,269 | <p>While studying <a href="http://pandas.pydata.org/pandas-docs/stable/style.html" rel="nofollow">Pandas Style</a>, I got to the following:</p>
<pre><code>df.style.format("{:.2%}")
</code></pre>
<p>Which I understand means, turn every value to 2 decimal places and add a <code>%</code> in the end.</p>
<p>Just after that, there is:</p>
<pre><code>df.style.format({'B': "{:0<4.0f}", 'D': '{:+.2f}'})
</code></pre>
<p>How should I read <code>'B': "{:0<4.0f}"</code>?</p>
| 0 | 2016-10-13T02:22:50Z | 40,011,367 | <p>The <a href="https://docs.python.org/3/library/string.html#format-specification-mini-language" rel="nofollow" title="format specification mini language">Python documentation for format strings</a> explains what this means.</p>
<p>In the case of <code>0<4.0f</code>, it means:</p>
<pre><code>0 0-filled
< left-aligned
4.0 width.precision (4 digits wide, 0 after decimal point)
f floating-point number
</code></pre>
| 1 | 2016-10-13T02:33:56Z | [
"python",
"python-2.7",
"pandas"
] |
Installing python 3 for a specific environment | 40,011,373 | <p>I have <code>python 2.7.10</code> installed on my <code>mac</code>.</p>
<p>but I happen to need <code>Python 3</code> to use a <code>python wrapper</code> for a given <code>API</code>.</p>
<p>this is my folder structure:</p>
<pre><code>apps/
myapp/
app.py
gracenote/
pygn.py
</code></pre>
<p>where <code>pygn.py</code> is the wrapper wich requires <code>Python 3</code>, while <code>app.py</code> requires <code>Python 2.7</code></p>
<p>is there a way to run an isolated <code>Python</code> environment for the <code>wrapper</code>?</p>
| 0 | 2016-10-13T02:34:29Z | 40,011,419 | <p>You'll need to install both versions of python at the same time</p>
<pre><code>$ which python3 # copy the output of this command
$ mkvirtualenv --python=/path/to/python3 ~/.virtualenvs/{your env name}
$ workon {your env name}
</code></pre>
| 0 | 2016-10-13T02:42:25Z | [
"python",
"python-2.7",
"python-3.x",
"development-environment"
] |
in Pandas, when using read_csv(), how to assign a NaN to a value that's not the dtype intended? | 40,011,531 | <p><strong>Note:</strong> Please excuse my very low skilled English, feel free to modify the question's title, or the following text to be more understandable</p>
<p>I have this line in my code:</p>
<pre><code>moto = pd.read_csv('reporte.csv')
</code></pre>
<p>It sends a <strong><code>DtypeWarning: Columns (2,3,4,5,6,7,8,9,10,12,13) have mixed types.</code></strong> warning, so I change it to</p>
<pre><code>moto = pd.read_csv('reporte.csv', dtype={'TP': np.float64})
</code></pre>
<p>Now it drops a <strong><code>ValueError: could not convert string to float: 'None'</code></strong>.</p>
<p>I checked the file (around 200K lines) with Excel, and yes, I found some cells with "<strong>None</strong>" value.</p>
<p>So my question is: <strong>Is there a way to ignore the error, or force python to fill the offending error with NaN or something else?</strong></p>
<p>I tried the solution <a href="http://stackoverflow.com/questions/30314153/python-pandas-dtypewarning-specify-dtype-option-on-import-how">here</a> but it didn't work.</p>
| 2 | 2016-10-13T02:55:06Z | 40,011,736 | <p>I tried creating a csv to replicate this feedback but couldn't on pandas 0.18, so I can only recommend two methods to handle this:</p>
<p><strong>First</strong></p>
<p>If you know that your missing values are all marked by a string 'none', then do this:</p>
<pre><code>moto = pd.read_csv("test.csv", na_values=['none'])
</code></pre>
<p>You can also add, to the na_values list, other markers that should be converted to NaNs.</p>
<p><strong>Second</strong></p>
<p>Try your first line again without using the dtype option. </p>
<pre><code>moto = pd.read_csv('reporte.csv')
</code></pre>
<p>The read is successful because you are only getting a warning. Now execute <code>moto.dtypes</code> to show you which columns are objects. For the ones you want to change do the following:</p>
<pre><code>moto.test_column = pd.to_numeric(data.test_column, errors='coerce')
</code></pre>
<p>The 'coerce' option will convert any problematic entries, like 'none', to NaNs. </p>
<p>To convert the entire dataframe at once, you can use convert_objects. You could also use it on a single column, but that usage is deprecated in favor of to_numeric. The option, convert_numeric, does the coercion to NaNs:</p>
<pre><code>moto = moto.convert_objects(convert_numeric=True)
</code></pre>
<p>After any of these methods, proceed with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.fillna.html" rel="nofollow">fillna</a> to do what you need to.</p>
| 2 | 2016-10-13T03:19:46Z | [
"python",
"pandas"
] |
How to find the non-repeating string from the list of string | 40,011,539 | <p>There is given a list of strings out which we have to print the unique strings. Unique string is a string which is not repeated in the list of string.</p>
<pre><code>Ex li = [ram,raj,ram,dev,dev]
unique string = raj.
</code></pre>
<p>I thought of one algorithm. </p>
<p>First sort the String array, then check the adjacent string if its equal then move forward otherwise its a unique string.
But here the time Complexity is very high for sorting the string array.</p>
<p>Can any body help me in finding the more efficient algorithm then mine algo?
Thanks in advance.</p>
| -2 | 2016-10-13T02:55:44Z | 40,011,825 | <p>You could try below</p>
<pre><code> List<String> names = Arrays.asList("ram", "raj", "ram", "dev", "dev");
Map<String, Long> nameCount = names.stream().collect(Collectors.groupingBy(s -> s, Collectors.counting()));
List<String> unique = nameCount.entrySet().stream().filter(e -> e.getValue() == 1L).map(Map.Entry::getKey).collect(Collectors.toList());
System.out.println(nameCount);
System.out.println(unique);
</code></pre>
<p>ouput</p>
<pre><code>{dev=2, raj=1, ram=2}
[raj]
</code></pre>
<p><strong>EDIT</strong></p>
<pre><code> List<String> uniq = new ArrayList<>();
names.stream().sorted().forEach(n -> {
if (uniq.contains(n)) {
uniq.remove(n);
} else {
uniq.add(n);
}
});
</code></pre>
<p>Instead of list map cab be used to check contains in O(1)</p>
| 0 | 2016-10-13T03:28:15Z | [
"java",
"python",
"c++",
"string",
"algorithm"
] |
How to find the non-repeating string from the list of string | 40,011,539 | <p>There is given a list of strings out which we have to print the unique strings. Unique string is a string which is not repeated in the list of string.</p>
<pre><code>Ex li = [ram,raj,ram,dev,dev]
unique string = raj.
</code></pre>
<p>I thought of one algorithm. </p>
<p>First sort the String array, then check the adjacent string if its equal then move forward otherwise its a unique string.
But here the time Complexity is very high for sorting the string array.</p>
<p>Can any body help me in finding the more efficient algorithm then mine algo?
Thanks in advance.</p>
| -2 | 2016-10-13T02:55:44Z | 40,011,886 | <h2>Solution 1</h2>
<p>You can solve your problem in O(n) complexity.</p>
<p>just create a <a href="https://en.wikipedia.org/wiki/Hash_table" rel="nofollow">hash table</a> to store the word counters, and than access just the words with <code>count == 1</code></p>
<h2>Solution 2</h2>
<p>This solution is not Liniar time, but stil been a good one.</p>
<p>You can create a <a href="https://en.wikipedia.org/wiki/Trie" rel="nofollow">Trie</a> with a count property, so will be easy to find the nodes with <code>count == 1</code></p>
| 0 | 2016-10-13T03:35:35Z | [
"java",
"python",
"c++",
"string",
"algorithm"
] |
How to find the non-repeating string from the list of string | 40,011,539 | <p>There is given a list of strings out which we have to print the unique strings. Unique string is a string which is not repeated in the list of string.</p>
<pre><code>Ex li = [ram,raj,ram,dev,dev]
unique string = raj.
</code></pre>
<p>I thought of one algorithm. </p>
<p>First sort the String array, then check the adjacent string if its equal then move forward otherwise its a unique string.
But here the time Complexity is very high for sorting the string array.</p>
<p>Can any body help me in finding the more efficient algorithm then mine algo?
Thanks in advance.</p>
| -2 | 2016-10-13T02:55:44Z | 40,012,806 | <p>You can try out this simple python implementation, which is based on the concept of using a <strong>HashMap</strong>:</p>
<pre><code>li = ['ram','raj','ram','dev','dev']
hash = dict()
for item in li:
if item in hash:
hash[item] += 1
else:
hash[item] = 1
print "unique string(s):",
for key, value in hash.iteritems():
if value == 1:
print key,
</code></pre>
| 0 | 2016-10-13T05:15:45Z | [
"java",
"python",
"c++",
"string",
"algorithm"
] |
How to select all values from one threshold to another? | 40,011,617 | <p>I have an ordered tuple of data:</p>
<pre><code>my_data = (1,2,3,2,4,2,3,3,5,7,5,3,6,8,7)
</code></pre>
<p>How can I subset the tuple items such that all items including and after the first instance of 3 are kept until the first value == 7? For example, the result should be:</p>
<pre><code>desired_output = (3,2,4,2,3,3,5,7)
</code></pre>
| -1 | 2016-10-13T03:04:14Z | 40,011,676 | <p>I am not sure what you mean by threshold (value == 7, or any value >= 7), but here is a solution:</p>
<pre><code>my_data = (1,2,3,2,4,2,3,3,5,7,5,3,6,8,7)
index1 = my_data.index(3)
index2 = my_data.index(7)
desired_output = my_data[index1:index2+1]
print desired_output
</code></pre>
| 4 | 2016-10-13T03:12:00Z | [
"python",
"tuples"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.