title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Removing List from List of Lists with condition
39,381,769
<p>I have this list of projects, and I want to remove it one by one start from last item to item-n until it reach some total value of budget = 325.000</p> <pre><code>from collections import namedtuple Item = namedtuple('Item', 'region sector name budget target performance'.split()) sorted_KP = [Item(region='H', sector='2', name='H3', budget=7000.0, target=1.0, performance=4.0), Item(region='H', sector='2', name='H10', budget=35000.0, target=15.0, performance=1.0), Item(region='I', sector='2', name='I6', budget=50000.0, target=5.0, performance=0.40598931548848194), Item(region='E', sector='4', name='E5', budget=75000.0, target=30.0, performance=0.0663966081766), Item(region='C', sector='1', name='C1', budget=75000.0, target=50.0, performance=0.0308067750379), Item(region='C', sector='1', name='C2', budget=75000.0, target=50.0, performance=0.0308067750379), Item(region='C', sector='5', name='C4', budget=75000.0, target=50.0, performance=0.0308067750379), Item(region='I', sector='2', name='I5', budget=100000.0, target=5.0, performance=0.40598931548848194), Item(region='E', sector='4', name='E1', budget=100000.0, target=30.0, performance=0.0663966081766), Item(region='D', sector='5', name='D21', budget=60000.0, target=4.0, performance=0.2479775110248), Item(region='D', sector='5', name='D30', budget=10000.0, target=1.0, performance=0.1653183406832), Item(region='D', sector='1', name='D23', budget=30000.0, target=20.0, performance=0.023659703723372342), Item(region='C', sector='5', name='C3', budget=150000.0, target=75.0, performance=0.0308067750379), Item(region='D', sector='5', name='D20', budget=30000.0, target=5.0, performance=0.0826591703416), Item(region='H', sector='2', name='H6', budget=310576.0, target=1.0, performance=4.0), Item(region='H', sector='3', name='H5', budget=9500.0, target=1.0, performance=0.1172008400616), Item(region='E', sector='6', name='E3', budget=100000.0, target=30.0, performance=0.03747318294316411), Item(region='G', sector='3', name='G17', budget=75000.0, target=20.0, performance=0.04132095963602382), Item(region='C', sector='4', name='C5', budget=75000.0, target=25.0, performance=0.0308067750379), Item(region='C', sector='2', name='C6', budget=30000.0, target=5.0, performance=0.0616135500758), Item(region='C', sector='2', name='C7', budget=30000.0, target=5.0, performance=0.0616135500758), Item(region='D', sector='6', name='D22', budget=65190.0, target=30.0, performance=0.020332158889648923), Item(region='D', sector='5', name='D3', budget=100000.0, target=20.0, performance=0.0413295851708), Item(region='D', sector='5', name='D4', budget=100000.0, target=20.0, performance=0.0413295851708), Item(region='A', sector='1', name='A12', budget=25000.0, target=25.0, performance=0.00749432996938), Item(region='A', sector='1', name='A13', budget=25000.0, target=25.0, performance=0.00749432996938), Item(region='A', sector='3', name='A25', budget=4500.0, target=1.0, performance=0.02997731987752), Item(region='A', sector='5', name='A26', budget=4500.0, target=1.0, performance=0.02997731987752), Item(region='A', sector='1', name='A27', budget=4500.0, target=1.0, performance=0.02997731987752), Item(region='A', sector='1', name='A29', budget=4500.0, target=1.0, performance=0.02997731987752), Item(region='A', sector='3', name='A30', budget=4500.0, target=1.0, performance=0.02997731987752)] </code></pre> <p>But beside the total value, I have two others conditions of the item whether it should be removed or not.</p> <p>First, after the item is removed there still remain at least one item in the list of lists that represent the same <em>region</em></p> <p>Second, after the item is removed there still remain at least one item that represent the same <em>sector</em></p> <p>For example, I can remove the last item because it represent region "A" and there left 5 items that also represent region "A". Also it represent sector "3" and there left 3 items that represent sector "3".</p> <p>This removal and checking repeated until I reach total budget of removal at least 325.000</p> <p>I did this code, but I can not get what I need. Please help me to correct it.</p> <pre><code>from collections import Counter unpack = [] for item in sorted_KP: item_budget = item[3] sum_unpack = sum(item[3] for item in unpack) budget = 325000 remaining = [] for item in sorted_KP: if item not in unpack: remaining.append(item) region_el = [item[0] for item in remaining] counter_R_el = Counter(region_el) sector_el = [item[1] for item in remaining] counter_S_el = Counter(sector_el) if counter_R_el &gt;= 1 or counter_S_el &gt;= 1: if sum_unpack &lt;= budget: unpack.append(item) for item in unpack: print "\t", item </code></pre> <p>Here is what I got with my code, item-25 is still removed when it should not:</p> <pre><code>unpack =Item(region='A', sector='3', name='A30', budget=4500.0, target=1.0, performance=0.02997731987752) Item(region='A', sector='1', name='A29', budget=4500.0, target=1.0, performance=0.02997731987752) Item(region='A', sector='1', name='A27', budget=4500.0, target=1.0, performance=0.02997731987752) Item(region='A', sector='5', name='A26', budget=4500.0, target=1.0, performance=0.02997731987752) Item(region='A', sector='3', name='A25', budget=4500.0, target=1.0, performance=0.02997731987752) Item(region='A', sector='1', name='A13', budget=25000.0, target=25.0, performance=0.00749432996938) Item(region='A', sector='1', name='A12', budget=25000.0, target=25.0, performance=0.00749432996938) Item(region='D', sector='5', name='D4', budget=100000.0, target=20.0, performance=0.0413295851708) Item(region='D', sector='5', name='D3', budget=100000.0, target=20.0, performance=0.0413295851708) Item(region='D', sector='6', name='D22', budget=65190.0, target=30.0, performance=0.020332158889648923) </code></pre> <p>Item-25 (project name: "A12") can not be removed even though we still have budget to be removed, because if it was remove, there'll be no more item represent region "A", and so on.</p> <p>While the solution should be:</p> <pre><code>unpack = [Item(region='A', sector='3', name='A30', budget=4500.0, target=1.0, performance=0.02997731987752), Item(region='A', sector='1', name='A29', budget=4500.0, target=1.0, performance=0.02997731987752), Item(region='A', sector='1', name='A27', budget=4500.0, target=1.0, performance=0.02997731987752), Item(region='A', sector='5', name='A26', budget=4500.0, target=1.0, performance=0.02997731987752), Item(region='A', sector='3', name='A25', budget=4500.0, target=1.0, performance=0.02997731987752), Item(region='A', sector='1', name='A13', budget=25000.0, target=25.0, performance=0.00749432996938), Item(region='D', sector='5', name='D4', budget=100000.0, target=20.0, performance=0.0413295851708), Item(region='D', sector='5', name='D3', budget=100000.0, target=20.0, performance=0.0413295851708), Item(region='D', sector='6', name='D22', budget=65190.0, target=30.0, performance=0.020332158889648923), Item(region='C', sector='2', name='C7', budget=30000.0, target=5.0, performance=0.0616135500758)] </code></pre> <p>Thank you in advance for your help</p>
3
2016-09-08T02:39:17Z
39,383,320
<p>I couldn't easily sort through your code. <code>if counter_R_el &gt;= 1 or counter_S_el &gt;= 1:</code> just can't work, you can't compare a Counter() to an int(). It also looks like you continually remake/reset <em>things</em> in your loop suite and it became confusing.</p> <p>You seem to be on the right track.</p> <ul> <li>To keep track of the number of regions and sectors collections.Counter() is a good choice.</li> <li>look at each item in the list, and check if it meets your constraints</li> <li>if removed, update the counters and the total cost</li> </ul> <p>Here is what I came up with:</p> <pre><code>import collections, operator Item = collections.namedtuple('Item', ['region', 'sector', 'name', 'budget', 'target', 'performance']) a = [Item(region='H', sector='2', name='H3', budget=7000.0, target=1.0, performance=4.0), Item(region='H', sector='2', name='H10', budget=35000.0, target=15.0, performance=1.0), Item(region='I', sector='2', name='I6', budget=50000.0, target=5.0, performance=0.40598931548848194), .....] budget = 325000 # sort highest to lowest cost a.sort(key = operator.attrgetter('budget'), reverse = True) project_cost = sum(item.budget for item in a) # constraint counters region_count = collections.Counter(item.region for item in a) sector_count = collections.Counter(item.sector for item in a) # iterate over a copy of the list b = a.copy() for item in b: if project_cost &lt;= budget: break # check item against constraints if region_count[item.region] &gt; 1 and sector_count[item.sector] &gt; 1: # remove the item from the original list a.remove(item) # uodate the counters and cost region_count[item.region] -= 1 sector_count[item.sector] -= 1 project_cost -= item.budget </code></pre> <p><code>a</code> contains the items that meet the constraints and have a total cost less than the budget.</p>
0
2016-09-08T05:41:33Z
[ "python", "list", "condition" ]
Removing List from List of Lists with condition
39,381,769
<p>I have this list of projects, and I want to remove it one by one start from last item to item-n until it reach some total value of budget = 325.000</p> <pre><code>from collections import namedtuple Item = namedtuple('Item', 'region sector name budget target performance'.split()) sorted_KP = [Item(region='H', sector='2', name='H3', budget=7000.0, target=1.0, performance=4.0), Item(region='H', sector='2', name='H10', budget=35000.0, target=15.0, performance=1.0), Item(region='I', sector='2', name='I6', budget=50000.0, target=5.0, performance=0.40598931548848194), Item(region='E', sector='4', name='E5', budget=75000.0, target=30.0, performance=0.0663966081766), Item(region='C', sector='1', name='C1', budget=75000.0, target=50.0, performance=0.0308067750379), Item(region='C', sector='1', name='C2', budget=75000.0, target=50.0, performance=0.0308067750379), Item(region='C', sector='5', name='C4', budget=75000.0, target=50.0, performance=0.0308067750379), Item(region='I', sector='2', name='I5', budget=100000.0, target=5.0, performance=0.40598931548848194), Item(region='E', sector='4', name='E1', budget=100000.0, target=30.0, performance=0.0663966081766), Item(region='D', sector='5', name='D21', budget=60000.0, target=4.0, performance=0.2479775110248), Item(region='D', sector='5', name='D30', budget=10000.0, target=1.0, performance=0.1653183406832), Item(region='D', sector='1', name='D23', budget=30000.0, target=20.0, performance=0.023659703723372342), Item(region='C', sector='5', name='C3', budget=150000.0, target=75.0, performance=0.0308067750379), Item(region='D', sector='5', name='D20', budget=30000.0, target=5.0, performance=0.0826591703416), Item(region='H', sector='2', name='H6', budget=310576.0, target=1.0, performance=4.0), Item(region='H', sector='3', name='H5', budget=9500.0, target=1.0, performance=0.1172008400616), Item(region='E', sector='6', name='E3', budget=100000.0, target=30.0, performance=0.03747318294316411), Item(region='G', sector='3', name='G17', budget=75000.0, target=20.0, performance=0.04132095963602382), Item(region='C', sector='4', name='C5', budget=75000.0, target=25.0, performance=0.0308067750379), Item(region='C', sector='2', name='C6', budget=30000.0, target=5.0, performance=0.0616135500758), Item(region='C', sector='2', name='C7', budget=30000.0, target=5.0, performance=0.0616135500758), Item(region='D', sector='6', name='D22', budget=65190.0, target=30.0, performance=0.020332158889648923), Item(region='D', sector='5', name='D3', budget=100000.0, target=20.0, performance=0.0413295851708), Item(region='D', sector='5', name='D4', budget=100000.0, target=20.0, performance=0.0413295851708), Item(region='A', sector='1', name='A12', budget=25000.0, target=25.0, performance=0.00749432996938), Item(region='A', sector='1', name='A13', budget=25000.0, target=25.0, performance=0.00749432996938), Item(region='A', sector='3', name='A25', budget=4500.0, target=1.0, performance=0.02997731987752), Item(region='A', sector='5', name='A26', budget=4500.0, target=1.0, performance=0.02997731987752), Item(region='A', sector='1', name='A27', budget=4500.0, target=1.0, performance=0.02997731987752), Item(region='A', sector='1', name='A29', budget=4500.0, target=1.0, performance=0.02997731987752), Item(region='A', sector='3', name='A30', budget=4500.0, target=1.0, performance=0.02997731987752)] </code></pre> <p>But beside the total value, I have two others conditions of the item whether it should be removed or not.</p> <p>First, after the item is removed there still remain at least one item in the list of lists that represent the same <em>region</em></p> <p>Second, after the item is removed there still remain at least one item that represent the same <em>sector</em></p> <p>For example, I can remove the last item because it represent region "A" and there left 5 items that also represent region "A". Also it represent sector "3" and there left 3 items that represent sector "3".</p> <p>This removal and checking repeated until I reach total budget of removal at least 325.000</p> <p>I did this code, but I can not get what I need. Please help me to correct it.</p> <pre><code>from collections import Counter unpack = [] for item in sorted_KP: item_budget = item[3] sum_unpack = sum(item[3] for item in unpack) budget = 325000 remaining = [] for item in sorted_KP: if item not in unpack: remaining.append(item) region_el = [item[0] for item in remaining] counter_R_el = Counter(region_el) sector_el = [item[1] for item in remaining] counter_S_el = Counter(sector_el) if counter_R_el &gt;= 1 or counter_S_el &gt;= 1: if sum_unpack &lt;= budget: unpack.append(item) for item in unpack: print "\t", item </code></pre> <p>Here is what I got with my code, item-25 is still removed when it should not:</p> <pre><code>unpack =Item(region='A', sector='3', name='A30', budget=4500.0, target=1.0, performance=0.02997731987752) Item(region='A', sector='1', name='A29', budget=4500.0, target=1.0, performance=0.02997731987752) Item(region='A', sector='1', name='A27', budget=4500.0, target=1.0, performance=0.02997731987752) Item(region='A', sector='5', name='A26', budget=4500.0, target=1.0, performance=0.02997731987752) Item(region='A', sector='3', name='A25', budget=4500.0, target=1.0, performance=0.02997731987752) Item(region='A', sector='1', name='A13', budget=25000.0, target=25.0, performance=0.00749432996938) Item(region='A', sector='1', name='A12', budget=25000.0, target=25.0, performance=0.00749432996938) Item(region='D', sector='5', name='D4', budget=100000.0, target=20.0, performance=0.0413295851708) Item(region='D', sector='5', name='D3', budget=100000.0, target=20.0, performance=0.0413295851708) Item(region='D', sector='6', name='D22', budget=65190.0, target=30.0, performance=0.020332158889648923) </code></pre> <p>Item-25 (project name: "A12") can not be removed even though we still have budget to be removed, because if it was remove, there'll be no more item represent region "A", and so on.</p> <p>While the solution should be:</p> <pre><code>unpack = [Item(region='A', sector='3', name='A30', budget=4500.0, target=1.0, performance=0.02997731987752), Item(region='A', sector='1', name='A29', budget=4500.0, target=1.0, performance=0.02997731987752), Item(region='A', sector='1', name='A27', budget=4500.0, target=1.0, performance=0.02997731987752), Item(region='A', sector='5', name='A26', budget=4500.0, target=1.0, performance=0.02997731987752), Item(region='A', sector='3', name='A25', budget=4500.0, target=1.0, performance=0.02997731987752), Item(region='A', sector='1', name='A13', budget=25000.0, target=25.0, performance=0.00749432996938), Item(region='D', sector='5', name='D4', budget=100000.0, target=20.0, performance=0.0413295851708), Item(region='D', sector='5', name='D3', budget=100000.0, target=20.0, performance=0.0413295851708), Item(region='D', sector='6', name='D22', budget=65190.0, target=30.0, performance=0.020332158889648923), Item(region='C', sector='2', name='C7', budget=30000.0, target=5.0, performance=0.0616135500758)] </code></pre> <p>Thank you in advance for your help</p>
3
2016-09-08T02:39:17Z
39,386,444
<p>Assume that you are using Python 2 as you use <code>print</code> without <code>()</code>.</p> <p>See the comments in the modified code:</p> <pre><code>unpack = [] for item in sorted_KP[::-1]: # loop the items in reverse order #item_budget = item[3] # variable not used sum_unpack = sum(item[3] for item in unpack) budget = 325000 remaining = [] for x in sorted_KP: # don't use 'item' here as in Python 2, it will modify the variable 'item' in the outer loop if x not in unpack: remaining.append(x) region_el = [x[0] for x in remaining] # don't use 'item' here as well counter_R_el = Counter(region_el) sector_el = [x[1] for x in remaining] # don't use 'item' here as well counter_S_el = Counter(sector_el) #if counter_R_el &gt;= 1 or counter_S_el &gt;= 1: # note that result is always True in Python 2 if counter_R_el[item.region] &gt; 1 and counter_S_el[item.sector] &gt; 1: # check '&gt; 1' instead of '&gt;= 1', and use 'and' instead of 'or' if sum_unpack &lt;= budget: unpack.append(item) for item in unpack: print "\t", item </code></pre> <p>My proposed solution:</p> <pre><code>budget = 325000 sum = 0 # accumulated budget of removed items removed_KP = [] # holds the removed items for item in sorted_KP[::-1]: # stop checking if over-budget if sum &gt;= budget: break # check whether there are items with same region and sector rcnt = scnt = 0 for tmp in sorted_KP: if tmp.region == item.region: rcnt += 1 if tmp.sector == item.sector: scnt += 1 if scnt &gt; 1 and rcnt &gt; 1: # this item can be removed based on the constraints sorted_KP.remove(item) removed_KP.append(item) sum += item.budget # print the removed items for item in removed_KP: print(item) </code></pre>
1
2016-09-08T08:47:01Z
[ "python", "list", "condition" ]
Python How to use global verables and DRY
39,381,845
<p>So I have finally got my base class set up nicely and ready to build a class to test. However when I started buildign this I noticed that I had to repeat myself Lot with setting everything to global</p> <p>the start() event is called to set up everything Update() is called every tick (20 ticks a sec)</p> <p>Is there a more efficient way to use global venerable then this.</p> <pre><code>class BodyClass(BaseClass): def __init__(self, name): super().__init__(name) def Start(self): global i i = 0 global d d = True global obj1 obj1 = ChildClassA('Obj1') global obj2 obj2 = ChildClassB('Obj2') global obj3 obj3 = ChildClassC('Obj3') global obj4 obj4 = ChildClassB('Obj4') global obj5 obj5 = ChildClassB('Obj5') global obj6 obj6 = ChildClassB('Obj6') def Update(self): global i global d global obj1 global obj2 global obj3 global obj4 global obj5 global obj6 print ("TYPE:", obj3.CType()) i = i+ 1 time.sleep(0.05) print("i: ", i) if i &gt;= 10: if d: print("UNLOADING") obj2.Unload() obj4.Unload() obj5.Unload() obj6.Unload() d=False </code></pre>
1
2016-09-08T02:49:11Z
39,381,886
<p><strong>Replace global variables</strong></p> <p>example:</p> <pre><code> global obj1; obj1 = ChildClassA('Obj1'); =&gt; self.obj1 = ChildClassA('Obj1'); </code></pre>
1
2016-09-08T02:55:00Z
[ "python", "global-variables", "dry" ]
Python How to use global verables and DRY
39,381,845
<p>So I have finally got my base class set up nicely and ready to build a class to test. However when I started buildign this I noticed that I had to repeat myself Lot with setting everything to global</p> <p>the start() event is called to set up everything Update() is called every tick (20 ticks a sec)</p> <p>Is there a more efficient way to use global venerable then this.</p> <pre><code>class BodyClass(BaseClass): def __init__(self, name): super().__init__(name) def Start(self): global i i = 0 global d d = True global obj1 obj1 = ChildClassA('Obj1') global obj2 obj2 = ChildClassB('Obj2') global obj3 obj3 = ChildClassC('Obj3') global obj4 obj4 = ChildClassB('Obj4') global obj5 obj5 = ChildClassB('Obj5') global obj6 obj6 = ChildClassB('Obj6') def Update(self): global i global d global obj1 global obj2 global obj3 global obj4 global obj5 global obj6 print ("TYPE:", obj3.CType()) i = i+ 1 time.sleep(0.05) print("i: ", i) if i &gt;= 10: if d: print("UNLOADING") obj2.Unload() obj4.Unload() obj5.Unload() obj6.Unload() d=False </code></pre>
1
2016-09-08T02:49:11Z
39,381,889
<p>Don't use global variables. You're literally not using self at all. Move all your shared state to <code>self</code>. That's what it's for. Don't use global variables.</p>
0
2016-09-08T02:55:08Z
[ "python", "global-variables", "dry" ]
float object has no attribute __getitem__ [Looked elsewhere but haven't been able to find anything applicable]
39,381,895
<p>Here is the data frame i'm working with:</p> <pre><code> patient_id marker_1 marker_2 subtype patient_age patient_gender 0 619681 21.640523 144.001572 0.0 3 female 1 619711 13.787380 162.408932 0.0 15 female 2 619595 22.675580 130.227221 0.0 6 female 3 619990 13.500884 138.486428 0.0 17 male 4 619157 2.967811 144.105985 0.0 6 female 5 619320 5.440436 154.542735 0.0 9 female 6 619663 11.610377 141.216750 0.0 7 female 7 619910 8.438632 143.336743 0.0 5 female 8 619199 18.940791 137.948417 0.0 7 male 9 619430 7.130677 131.459043 0.0 17 female 10 619766 -21.529898 146.536186 0.0 17 female 11 619018 12.644362 132.578350 0.0 12 female 12 619864 26.697546 125.456343 0.0 4 male 13 619273 4.457585 138.128162 0.0 8 female 14 619846 19.327792 154.693588 0.0 12 male 15 619487 5.549474 143.781625 0.0 8 male 16 619311 -4.877857 120.192035 0.0 7 female 17 619804 0.520879 141.563490 0.0 12 female 18 619331 16.302907 152.023798 0.0 16 female 19 619880 0.126732 136.976972 0.0 15 male 20 619428 -6.485530 125.799821 0.0 4 female 21 619554 -13.062702 159.507754 0.0 6 male 22 619072 -1.096522 135.619257 0.0 6 female 23 619095 -8.527954 147.774904 0.0 6 male 24 619706 -12.138978 137.872597 0.0 14 male 25 619708 -4.954666 143.869025 0.0 7 male 26 619693 -1.108051 128.193678 0.0 13 male 27 619975 3.718178 144.283319 0.0 7 female 28 619289 4.665172 143.024719 0.0 9 male 29 619911 -2.343221 136.372588 0.0 7 female .. ... ... ... ... ... </code></pre> <p>Now, I'm calculating basic statistics of the entire data frame and plan to extract specific values later on</p> <pre><code>#mean, median, sd of subset data mean_children = np.mean(children) med_children = np.median(children) sd_children = np.std(children) children_mark1 = [mean_children['marker_1'], med_children['marker_1'], sd_children['marker_1']] children_mark2 = [mean_children['marker_2'], med_children['marker_2'], sd_children['marker_2']] children_age = [mean_children['patient_age'], med_children['patient_age'], sd_children['patient_age']] </code></pre> <p>This is where I get the error. When I print out <code>mean_children['marker_2']</code> I get <code>121.396907126</code> so i'm not quite understanding why it won't allow me to add it to this vector. </p>
3
2016-09-08T02:55:45Z
39,382,171
<p>With children being your dataframe, I think if you use:</p> <pre><code>children.describe() </code></pre> <p>or</p> <pre><code>children.describe().transpose() </code></pre> <p>You will save yourself some time.</p>
1
2016-09-08T03:31:24Z
[ "python", "pandas", "dataframe" ]
float object has no attribute __getitem__ [Looked elsewhere but haven't been able to find anything applicable]
39,381,895
<p>Here is the data frame i'm working with:</p> <pre><code> patient_id marker_1 marker_2 subtype patient_age patient_gender 0 619681 21.640523 144.001572 0.0 3 female 1 619711 13.787380 162.408932 0.0 15 female 2 619595 22.675580 130.227221 0.0 6 female 3 619990 13.500884 138.486428 0.0 17 male 4 619157 2.967811 144.105985 0.0 6 female 5 619320 5.440436 154.542735 0.0 9 female 6 619663 11.610377 141.216750 0.0 7 female 7 619910 8.438632 143.336743 0.0 5 female 8 619199 18.940791 137.948417 0.0 7 male 9 619430 7.130677 131.459043 0.0 17 female 10 619766 -21.529898 146.536186 0.0 17 female 11 619018 12.644362 132.578350 0.0 12 female 12 619864 26.697546 125.456343 0.0 4 male 13 619273 4.457585 138.128162 0.0 8 female 14 619846 19.327792 154.693588 0.0 12 male 15 619487 5.549474 143.781625 0.0 8 male 16 619311 -4.877857 120.192035 0.0 7 female 17 619804 0.520879 141.563490 0.0 12 female 18 619331 16.302907 152.023798 0.0 16 female 19 619880 0.126732 136.976972 0.0 15 male 20 619428 -6.485530 125.799821 0.0 4 female 21 619554 -13.062702 159.507754 0.0 6 male 22 619072 -1.096522 135.619257 0.0 6 female 23 619095 -8.527954 147.774904 0.0 6 male 24 619706 -12.138978 137.872597 0.0 14 male 25 619708 -4.954666 143.869025 0.0 7 male 26 619693 -1.108051 128.193678 0.0 13 male 27 619975 3.718178 144.283319 0.0 7 female 28 619289 4.665172 143.024719 0.0 9 male 29 619911 -2.343221 136.372588 0.0 7 female .. ... ... ... ... ... </code></pre> <p>Now, I'm calculating basic statistics of the entire data frame and plan to extract specific values later on</p> <pre><code>#mean, median, sd of subset data mean_children = np.mean(children) med_children = np.median(children) sd_children = np.std(children) children_mark1 = [mean_children['marker_1'], med_children['marker_1'], sd_children['marker_1']] children_mark2 = [mean_children['marker_2'], med_children['marker_2'], sd_children['marker_2']] children_age = [mean_children['patient_age'], med_children['patient_age'], sd_children['patient_age']] </code></pre> <p>This is where I get the error. When I print out <code>mean_children['marker_2']</code> I get <code>121.396907126</code> so i'm not quite understanding why it won't allow me to add it to this vector. </p>
3
2016-09-08T02:55:45Z
39,382,175
<pre><code>np.mean </code></pre> <p>Sums entire dataframe and returns float</p> <p>Use</p> <pre><code>children.mean() </code></pre>
2
2016-09-08T03:31:57Z
[ "python", "pandas", "dataframe" ]
Printing multiple objects without spaces
39,381,936
<p>I'm writing a basic program to convert any 4 digit number in reverse.</p> <p>I know I'm taking a very complex approach, but that's what my professor requires. So far I've got:</p> <pre><code>print("This program will display any 4-digit integer in reverse order") userNum = eval(input("Enter any 4-digit integer: ")) num1 = userNum % 10 userNum2 = userNum // 10 num2 = userNum2 % 10 userNum3 = userNum // 100 num3 = userNum3 % 10 userNum4 = userNum // 1000 num4 = userNum4 % 10 print(num1,num2,num3,num4) </code></pre> <p>The issue I'm having is the output from the print statement gives me</p> <pre><code>x x x x </code></pre> <p>When I would prefer to have</p> <pre><code>xxxx </code></pre> <p>Any advice?</p>
1
2016-09-08T03:00:43Z
39,381,971
<p>If you read the description of the <a href="https://docs.python.org/3.5/library/functions.html#print"><code>print()</code></a>, you can see that you can change your last line for:</p> <pre><code>print(num1,num2,num3,num4, sep='') </code></pre>
5
2016-09-08T03:04:59Z
[ "python", "printing", "reverse", "spaces" ]
Printing multiple objects without spaces
39,381,936
<p>I'm writing a basic program to convert any 4 digit number in reverse.</p> <p>I know I'm taking a very complex approach, but that's what my professor requires. So far I've got:</p> <pre><code>print("This program will display any 4-digit integer in reverse order") userNum = eval(input("Enter any 4-digit integer: ")) num1 = userNum % 10 userNum2 = userNum // 10 num2 = userNum2 % 10 userNum3 = userNum // 100 num3 = userNum3 % 10 userNum4 = userNum // 1000 num4 = userNum4 % 10 print(num1,num2,num3,num4) </code></pre> <p>The issue I'm having is the output from the print statement gives me</p> <pre><code>x x x x </code></pre> <p>When I would prefer to have</p> <pre><code>xxxx </code></pre> <p>Any advice?</p>
1
2016-09-08T03:00:43Z
39,382,375
<p>Since you just want to convert the input in reverse order. You can take the following approach.</p> <pre><code>print("This program will display any 4-digit integer in reverse order") userNum = input("Enter any 4-digit integer: ") reverse_input = userNum[::-1] reverse_input = int(reverse_input) # If you want to keep input as an int class print(reverse_input) </code></pre> <p>If you want to use your own code then just change the print statement.</p> <pre><code>print(str(num1) + str(num2) + str(num3) + str(num4)) </code></pre> <p>String concatenation does not add space so you should get desired result.</p>
1
2016-09-08T03:59:28Z
[ "python", "printing", "reverse", "spaces" ]
Printing multiple objects without spaces
39,381,936
<p>I'm writing a basic program to convert any 4 digit number in reverse.</p> <p>I know I'm taking a very complex approach, but that's what my professor requires. So far I've got:</p> <pre><code>print("This program will display any 4-digit integer in reverse order") userNum = eval(input("Enter any 4-digit integer: ")) num1 = userNum % 10 userNum2 = userNum // 10 num2 = userNum2 % 10 userNum3 = userNum // 100 num3 = userNum3 % 10 userNum4 = userNum // 1000 num4 = userNum4 % 10 print(num1,num2,num3,num4) </code></pre> <p>The issue I'm having is the output from the print statement gives me</p> <pre><code>x x x x </code></pre> <p>When I would prefer to have</p> <pre><code>xxxx </code></pre> <p>Any advice?</p>
1
2016-09-08T03:00:43Z
39,383,276
<p>I used this as a sort of exercise for myself to nail down loops. There are a few loops you can use.</p> <pre><code>#if using python &lt;3 from __future__ import print_function x = 3456 z = x print('While:') while z &gt; 0: print(z % 10, end="") z = z / 10; print() print('For:') for y in xrange(4): z=x%10 print(z, end="") x = x / 10 </code></pre> <p>Thanks for asking this question. It encouraged me to go look at python syntax, myself, and I think it's a good exercise.</p>
0
2016-09-08T05:37:50Z
[ "python", "printing", "reverse", "spaces" ]
How to set the max thread a python script could use when calling from shell
39,381,974
<p>Have script a.py, it will run some task with multiple-thread, please noticed that I have no control over the a.py.</p> <p>I'm looking for a way to limit the number of thread it could use, as I found that using more threads than my CPU core will slow down the script.</p> <p>It could be something like:</p> <p>python --nthread=2 a.py </p> <p>or Modifying something in my OS is also acceptable . </p> <p>I am using ubuntu 16.04</p> <p>As requested: </p> <p>the a.py is just a module in scikit-learn the <a href="https://github.com/scikit-learn/scikit-learn/blob/183722475189b8e21ee2e621b19acca3c9e054d8/sklearn/neural_network/multilayer_perceptron.py" rel="nofollow">MLPRegressor</a> . I also asked this question <a href="https://github.com/scikit-learn/scikit-learn/issues/7280" rel="nofollow">here</a>.</p>
2
2016-09-08T03:05:12Z
39,382,195
<p>Read the <a href="https://docs.python.org/2/library/threading.html" rel="nofollow">threading</a> doc, it said:</p> <blockquote> <p>CPython implementation detail: In CPython, due to the Global Interpreter Lock, only one thread can execute Python code at once (even though certain performance-oriented libraries might overcome this limitation). If you want your application to make better use of the computational resources of multi-core machines, you are advised to use multiprocessing. However, threading is still an appropriate model if you want to run multiple I/O-bound tasks simultaneously.</p> </blockquote> <p>If you will like to take advantage of the multi-core processing better update the code to use <a href="https://docs.python.org/2/library/multiprocessing.html" rel="nofollow">multiprocessing</a> module.</p> <p>In case that you prefer anyway continue using threading, you have one option passing the number of threads to the application as an argument like:</p> <pre><code>python a.py --nthread=2 </code></pre> <p>Then you can update the script code to limit the threads.</p>
0
2016-09-08T03:34:53Z
[ "python", "multithreading", "scikit-learn" ]
How to set the max thread a python script could use when calling from shell
39,381,974
<p>Have script a.py, it will run some task with multiple-thread, please noticed that I have no control over the a.py.</p> <p>I'm looking for a way to limit the number of thread it could use, as I found that using more threads than my CPU core will slow down the script.</p> <p>It could be something like:</p> <p>python --nthread=2 a.py </p> <p>or Modifying something in my OS is also acceptable . </p> <p>I am using ubuntu 16.04</p> <p>As requested: </p> <p>the a.py is just a module in scikit-learn the <a href="https://github.com/scikit-learn/scikit-learn/blob/183722475189b8e21ee2e621b19acca3c9e054d8/sklearn/neural_network/multilayer_perceptron.py" rel="nofollow">MLPRegressor</a> . I also asked this question <a href="https://github.com/scikit-learn/scikit-learn/issues/7280" rel="nofollow">here</a>.</p>
2
2016-09-08T03:05:12Z
39,384,723
<p>A more general way, not specific to python: </p> <pre><code>taskset -c 1-3 python yourProgram.py </code></pre> <p>In this case the threads 1-3 (3 in total) will be used. Any parallelization invoked by your program will share those resources. </p> <p>For a solution that fits your exact problem you should better identify which part of the code parellelizes. For instance, if it is due to numpy routines, you could limit it by using: </p> <pre><code>OMP_NUM_THREADS=4 python yourProgram.py </code></pre> <p>Again, the first solution is general and handled by the os, whereas the second is python (numpy) specific. </p>
1
2016-09-08T07:16:15Z
[ "python", "multithreading", "scikit-learn" ]
Getting an IndexError: string index out of range
39,382,010
<p>I'm not sure why I'm getting an </p> <blockquote> <p>IndexError: string index out of range </p> </blockquote> <p>with this code. </p> <pre><code>s = 'oobbobobo' a = 0 for b in range(len(s)-1): if (s[b] == 'b') and (s[b+1] == 'o') and (s[b+2] == s[b]): a += 1 elif (s[b] == 'b') and (s[b+1] == 'o') and None: break print("Number of times bob occurs is: ", a) </code></pre> <p>I thought the <code>elif</code> statement would fix the error, so I'm lost.</p>
1
2016-09-08T03:11:09Z
39,382,039
<p>In this case, the length of <code>s</code> is 9 which means that you're looping over <code>range(8)</code> and therefore the highest value that <code>b</code> will have is <code>7</code> (Stay with me, I'm going somewhere with this ...)</p> <p>When <code>b = 7</code> (on the last iteration of the loop), the conditional expression in the <code>if</code> statement is being checked which contains:</p> <pre><code>(s[b+2] == s[b]) </code></pre> <p>Well, since <code>b = 7</code>, <code>b + 2 = 9</code>, but <code>s[9]</code> will be out of bounds (remember, python is 0 indexed so the highest index in a a string of length <code>9</code> is <code>8</code>).</p> <p>I'm guessing that the fix is to just modify the <code>range</code> statement:</p> <pre><code>for b in range(len(s)-2): ... </code></pre>
1
2016-09-08T03:15:55Z
[ "python" ]
AWS API Gateway's querystring is not json format
39,382,068
<p>In aws api gateway, I wanna pass the entire query string into the kinesis through api gateway,</p> <pre><code>#set($querystring = $input.params().querystring) "Data": "$util.base64Encode($querystring)" </code></pre> <p>but the data fetching from kinesis record looks like '{tracker_name=xxxx, tracker=yyyy}', which is not json string format, So I need to take special care of this weird string to make it to json string in aws lambda (Python engine). Any good idea?</p>
0
2016-09-08T03:19:17Z
39,385,078
<p>I'm not familiar with the AWS API Gateway, but focusing on the string formatting issue, it is not that hard to write a simple parser to convert it to any other format you want.</p> <p>As for your description, I write a simple Python parser, hope it can give you some ideas.</p> <pre><code>class MyParser: def __init__(self, source): # the source string self.source = source # current position self.at = 0 # current character self.ch = source[0] if len(source) &gt; 0 else '' def error(self, msg): '''Print an error message and raise an exception''' print '-- Parser abort due to a fatal error: \n-- %s' % msg raise ValueError() def check_char(self, expected): ''' Check if current character is same as the given character. If not, raise an exception. ''' if self.at &gt;= len(self.source): self.error('At position %d: %c expected, but reached string end' % (self.at, expected)) elif self.ch != expected: self.error('At position %d: %c expected, but %c given' % (self.at, expected, self.ch)) def next_char(self): '''Move on to next character in source string.''' self.at += 1 self.ch = self.source[self.at] if len(self.source) &gt; self.at else '' return self.ch def eat_spaces(self): '''Eat up white spaces.''' while self.ch == ' ': self.next_char() def parse_string(self): '''Parse a string value.''' s = '' while self.ch != '=' and self.ch != ',' and self.ch != '}' and self.at &lt; len(self.source): s += self.ch self.next_char() return s.strip() def parse_object(self): '''Parse an object value.''' obj = {} # eat '{' self.next_char() self.eat_spaces() while self.ch != '}': if self.at &gt;= len(self.source): self.error('Malformed source string') key = self.parse_string() # eat '=' self.check_char('=') self.next_char() val = self.parse_value() obj[key] = val # eat ',' if self.ch == ',': self.next_char() self.eat_spaces() # eat '}' self.next_char() return obj def parse_value(self): '''Parse a value.''' self.eat_spaces() if self.ch == '{': return self.parse_object() else: return self.parse_string() def parse(self): '''Let the game begin.''' self.eat_spaces() if self.ch != '{': self.error('Source string must begin with \'{\'') else: return self.parse_value() </code></pre> <p>To use it:</p> <pre><code>MyParser('{tracker_name=xxxx, tracker=yyyy}').parse() </code></pre>
1
2016-09-08T07:34:53Z
[ "python", "amazon-lambda", "amazon-api-gateway" ]
Got stuck with pxssh. It doesn't login again after the first successful login?
39,382,077
<p>I'm working on simple ssh login using pxssh. Following T.J. Connor scripts from Cookbook.</p> <p>I was able to successfully get into the remote machine using pxssh and pass commands when trying from the python interpreter. Below is the view.</p> <pre><code>&gt;&gt;&gt; from pexpect import pxssh &gt;&gt;&gt; s = pxssh.pxssh() &gt;&gt;&gt; s.login("192.168.1.107", "shineesh", "password123") True &gt;&gt;&gt; s &lt;pexpect.pxssh.pxssh object at 0xb72d772c&gt; &gt;&gt;&gt; s.sendline("ifconfig") 9 &gt;&gt;&gt; s.prompt() True &gt;&gt;&gt; print s.before ifconfig eth0 Link encap:Ethernet HWaddr 3X:XX:XX:XX:XX:X4 UP BROADCAST MULTICAST MTU:1500 Metric:1 RX packets:0 errors:0 dropped:0 overruns:0 frame:0 TX packets:0 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:0 (0.0 B) TX bytes:0 (0.0 B) </code></pre> <p>Now when I try the same thing again, I get this</p> <pre><code>&gt;&gt;&gt; s = pxssh.pxssh() &gt;&gt;&gt; s.login("192.168.1.107", "shineesh", "password123") Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/lib/python2.7/dist-packages/pexpect/pxssh.py", line 331, in login if not self.sync_original_prompt(sync_multiplier): File "/usr/lib/python2.7/dist-packages/pexpect/pxssh.py", line 218, in sync_original_prompt b = self.try_read_prompt(sync_multiplier) File "/usr/lib/python2.7/dist-packages/pexpect/pxssh.py", line 182, in try_read_prompt prompt += self.read_nonblocking(size=1, timeout=timeout) File "/usr/lib/python2.7/dist-packages/pexpect/pty_spawn.py", line 455, in read_nonblocking return super(spawn, self).read_nonblocking(size) File "/usr/lib/python2.7/dist-packages/pexpect/spawnbase.py", line 149, in read_nonblocking raise EOF('End Of File (EOF). Exception style platform.') pexpect.exceptions.EOF: End Of File (EOF). Exception style platform. &gt;&gt;&gt; </code></pre> <p>The script below also throws an EOF exeception </p> <pre><code>#! /usr/bin/python -tt from pexpect import pxssh import pexpect def send_commands(s, command): s.sendline(command) s.prompt(pexpect.EOF) print s.before def connect(host, username, password): try: child = pxssh.pxssh() child.login(host, username, password) return child except Exception, e: print "[-] Error Connecting\n" + str(e) exit(0) def main(): s = connect('192.168.1.107', 'shineesh', 'password123') send_commands(s, 'ifconfig') if __name__ == '__main__': main() </code></pre> <p>-----Output Below--------------</p> <pre><code>[-] Error Connecting End Of File (EOF). Exception style platform. </code></pre> <hr> <p>Again followed a few threads/references from</p> <pre><code>http://stackoverflow.com/questions/24919980/pxssh-throwing-end-of-file-eof-exception-style-platform-exception http://pexpect.sourceforge.net/doc/ </code></pre> <p>----------New Script--------------</p> <pre><code>#! /usr/bin/python -tt from pexpect import pxssh import pexpect def send_commands(s, command): s.sendline(command) s.prompt(pexpect.EOF) print s.before def connect(host, username, password): try: child = pxssh.pxssh() child.login(host, username, password) child.expect(pexpect.EOF, timeout=None) return child except Exception, e: print "[-] Error Connecting\n" + str(e) exit(0) def main(): s = connect('192.168.1.107', 'shineesh', 'password123') send_commands(s, 'ls -all') if __name__ == '__main__': main() </code></pre> <p>-------Output-------------</p> <pre><code>[-] Error Connecting End Of File (EOF). Exception style platform. </code></pre> <hr> <p>Where am I going wrong here ?</p>
3
2016-09-08T03:20:21Z
39,502,625
<p>After going through a lot of examples/articles, finally figured what was stopping pxssh from a successful SSH login. </p> <p>The connect() method from pxssh takes in "login_timeout=10" by default. In here the SSH login to the remote machine was taking more than 10 secs and thus login() was raising a ExceptionPxssh exception. The exception was misleading as it said "pexpect.exceptions.EOF: End Of File (EOF). Exception style platform."</p> <p>Anyways on setting login_timeout=15, pxssh script gets through. Below is the solution code. </p> <hr> <pre><code>#! /usr/bin/python -tt from pexpect import pxssh def send_commands(s, command): s.sendline(command) s.prompt() print s.before def connect(host, username, password): try: child = pxssh.pxssh() child.login(host, username, password, login_timeout=15) return child except pxssh.ExceptionPxssh, e: print "[-] Error Connecting\n" + str(e) exit(0) def main(): s = connect('192.168.1.107', 'shineesh', 'password123') send_commands(s, 'ifconfig') if __name__ == '__main__': main() </code></pre> <hr>
1
2016-09-15T03:20:25Z
[ "python", "python-2.7", "ssh", "pexpect", "pxssh" ]
How to check if a list already contains an element in Python?
39,382,078
<p>i have been working on this for quite a time and my if statement does not seem to have any effect on the code. what I am trying to do is that I want to enter words in a list without repetition.</p> <pre><code>fname = raw_input("Enter file name: ") fh = open(fname) lst = list() for line in fh: line.rstrip() words = line.split() if lst.count(words) == 0: lst = lst + words lst.sort() print lst </code></pre>
2
2016-09-08T03:20:24Z
39,382,102
<p>Use a <a href="https://docs.python.org/2/library/sets.html" rel="nofollow"><code>set()</code></a>, it ensures unique elements. Alternatively, you can use the <a href="https://docs.python.org/3/reference/expressions.html#membership-test-operations" rel="nofollow"><code>in</code></a> operator to check for membership in a list (<em>albeit an order of magnitude less efficient</em>).</p>
5
2016-09-08T03:23:09Z
[ "python", "python-2.7", "python-3.x" ]
How to check if a list already contains an element in Python?
39,382,078
<p>i have been working on this for quite a time and my if statement does not seem to have any effect on the code. what I am trying to do is that I want to enter words in a list without repetition.</p> <pre><code>fname = raw_input("Enter file name: ") fh = open(fname) lst = list() for line in fh: line.rstrip() words = line.split() if lst.count(words) == 0: lst = lst + words lst.sort() print lst </code></pre>
2
2016-09-08T03:20:24Z
39,382,158
<pre><code>&gt;&gt;&gt; instuff = """one two three ... two three four ... three four five ... """ &gt;&gt;&gt; lst = set() &gt;&gt;&gt; for line in instuff.split("\n"): ... lst |= set(line.split()) ... &gt;&gt;&gt; lst set(['four', 'five', 'two', 'three', 'one']) &gt;&gt;&gt; </code></pre>
2
2016-09-08T03:29:53Z
[ "python", "python-2.7", "python-3.x" ]
Why is math.sqrt(r**2 - (x-h)**2) + k returning a ValueError: math domain error
39,382,197
<pre><code>def drawCircle(h, k, r): #(x-h)^2 + (y-k)^2 = r^2 for x in range(screen.Width): y = (math.sqrt(r**2 - (x-h)**2) + k) if y % 1 == 0: screen.Set(x, int(y), "X") drawCircle(0, 0, 5) </code></pre> <p>screen is a simple console renderer library that I wrote that positions items in a 2D array with the most top-left corner being (0,0) </p>
0
2016-09-08T03:35:27Z
39,382,234
<p>It is my guess that the result in parens that you are <code>sqrt</code>ing ends up being negative at some point. If and when it does, the error you are seeing will be raised when you try to take the square root of that number. </p> <p>To confirm this, try saving <code>r**2 - (x-h)**2</code> to a variable and printing it before taking the <code>sqrt</code>. </p>
3
2016-09-08T03:40:15Z
[ "python", "math" ]
Using BetaBinomial in PyMC3
39,382,396
<p>I have a table of counts of binary outcomes and I would like to fit a beta binomial distribution to estimate $\alpha$ and $\beta$ parameters, but I am getting errors when I try to fit/sample the model distribution the way I do for other cases:</p> <pre><code>import pymc3 as pm import pandas as pd df = pd.read_csv('~/data.csv', low_memory=False) df = df[df.Clicks &gt;= 0] C0=df.C.values I0=df.N.values N0 = C0 + I0 with pm.Model() as model: C=pm.constant(C0) I=pm.constant(I0) C1=pm.constant(C0 + 1) I1=pm.constant(I0 + 1) N=pm.constant(N0) alpha = pm.Exponential('alpha', 1/(C0.sum()+1)) beta = pm.Exponential('beta', 1/(I0.sum()+1)) obs = pm.BetaBinomial('obs', alpha, beta, N, observed=C0) with model: advi_fit = pm.variational.advi(n=int(1e4)) trace1 = pm.variational.sample_vp(advi_fit, draws=int(1e4)) pm.traceplot(trace1[::10]) with model: step = pm.NUTS() #step = pm.Metropolis() # &lt;== same problem trace2 = pm.sample(int(1e3), step) pm.traceplot(trace2[::10]) </code></pre> <p>In both cases the sampling fails with:</p> <pre><code>MissingInputError: ("An input of the graph, used to compute Elemwise{neg,no_inplace}(P_logodds_), was not provided and not given a value.Use the Theano flag exception_verbosity='high',for more information on this error.", P_logodds </code></pre> <p>In the <code>advi</code> case the full stack trace is:</p> <hr> <pre><code>MissingInputError Traceback (most recent call last) &lt;ipython-input-46-8947c7c798e5&gt; in &lt;module&gt;() ----&gt; 1 import codecs, os;__pyfile = codecs.open('''/tmp/py7996Jip''', encoding='''utf-8''');__code = __pyfile.read().encode('''utf-8''');__pyfile.close();os.remove('''/tmp/py7996Jip''');exec(compile(__code, '''/home/dmahler/Scripts/adops-bayes2.py''', 'exec')); /home/dmahler/Scripts/adops-bayes2.py in &lt;module&gt;() 59 advi_fit = pm.variational.advi(n=int(J*6.4e4), learning_rate=1e-3/J, epsilon=1e-8, accurate_elbo=False) 60 #advi_fit = pm.variational.advi_minibatch(minibatch_RVs=[alpha, beta, p], minibatch_tensors=[C,I,N]) ---&gt; 61 trace = pm.variational.sample_vp(advi_fit, draws=int(2e4)) 62 63 pm.traceplot(trace[::10]) /home/dmahler/Anaconda/lib/python2.7/site-packages/pymc3/variational/advi.pyc in sample_vp(vparams, draws, model, local_RVs, random_seed, hide_transformed) 317 318 varnames = [str(var) for var in model.unobserved_RVs] --&gt; 319 trace = NDArray(model=model, vars=vars_sampled) 320 trace.setup(draws=draws, chain=0) 321 /home/dmahler/Anaconda/lib/python2.7/site-packages/pymc3/backends/ndarray.pyc in __init__(self, name, model, vars) 21 """ 22 def __init__(self, name=None, model=None, vars=None): ---&gt; 23 super(NDArray, self).__init__(name, model, vars) 24 self.draw_idx = 0 25 self.draws = None /home/dmahler/Anaconda/lib/python2.7/site-packages/pymc3/backends/base.pyc in __init__(self, name, model, vars) 34 self.vars = vars 35 self.varnames = [var.name for var in vars] ---&gt; 36 self.fn = model.fastfn(vars) 37 38 /home/dmahler/Anaconda/lib/python2.7/site-packages/pymc3/model.pyc in fastfn(self, outs, mode, *args, **kwargs) 374 Compiled Theano function as point function. 375 """ --&gt; 376 f = self.makefn(outs, mode, *args, **kwargs) 377 return FastPointFunc(f) 378 /home/dmahler/Anaconda/lib/python2.7/site-packages/pymc3/memoize.pyc in memoizer(*args, **kwargs) 12 13 if key not in cache: ---&gt; 14 cache[key] = obj(*args, **kwargs) 15 16 return cache[key] /home/dmahler/Anaconda/lib/python2.7/site-packages/pymc3/model.pyc in makefn(self, outs, mode, *args, **kwargs) 344 on_unused_input='ignore', 345 accept_inplace=True, --&gt; 346 mode=mode, *args, **kwargs) 347 348 def fn(self, outs, mode=None, *args, **kwargs): /home/dmahler/Anaconda/lib/python2.7/site-packages/theano/compile/function.pyc in function(inputs, outputs, mode, updates, givens, no_default_updates, accept_inplace, name, rebuild_strict, allow_input_downcast, profile, on_unused_input) 318 on_unused_input=on_unused_input, 319 profile=profile, --&gt; 320 output_keys=output_keys) 321 # We need to add the flag check_aliased inputs if we have any mutable or 322 # borrowed used defined inputs /home/dmahler/Anaconda/lib/python2.7/site-packages/theano/compile/pfunc.pyc in pfunc(params, outputs, mode, updates, givens, no_default_updates, accept_inplace, name, rebuild_strict, allow_input_downcast, profile, on_unused_input, output_keys) 477 accept_inplace=accept_inplace, name=name, 478 profile=profile, on_unused_input=on_unused_input, --&gt; 479 output_keys=output_keys) 480 481 /home/dmahler/Anaconda/lib/python2.7/site-packages/theano/compile/function_module.pyc in orig_function(inputs, outputs, mode, accept_inplace, name, profile, on_unused_input, output_keys) 1774 profile=profile, 1775 on_unused_input=on_unused_input, -&gt; 1776 output_keys=output_keys).create( 1777 defaults) 1778 /home/dmahler/Anaconda/lib/python2.7/site-packages/theano/compile/function_module.pyc in __init__(self, inputs, outputs, mode, accept_inplace, function_builder, profile, on_unused_input, fgraph, output_keys) 1426 # OUTPUT VARIABLES) 1427 fgraph, additional_outputs = std_fgraph(inputs, outputs, -&gt; 1428 accept_inplace) 1429 fgraph.profile = profile 1430 else: /home/dmahler/Anaconda/lib/python2.7/site-packages/theano/compile/function_module.pyc in std_fgraph(input_specs, output_specs, accept_inplace) 175 176 fgraph = gof.fg.FunctionGraph(orig_inputs, orig_outputs, --&gt; 177 update_mapping=update_mapping) 178 179 for node in fgraph.apply_nodes: /home/dmahler/Anaconda/lib/python2.7/site-packages/theano/gof/fg.pyc in __init__(self, inputs, outputs, features, clone, update_mapping) 169 170 for output in outputs: --&gt; 171 self.__import_r__(output, reason="init") 172 for i, output in enumerate(outputs): 173 output.clients.append(('output', i)) /home/dmahler/Anaconda/lib/python2.7/site-packages/theano/gof/fg.pyc in __import_r__(self, variable, reason) 358 # Imports the owners of the variables 359 if variable.owner and variable.owner not in self.apply_nodes: --&gt; 360 self.__import__(variable.owner, reason=reason) 361 if (variable.owner is None and 362 not isinstance(variable, graph.Constant) and /home/dmahler/Anaconda/lib/python2.7/site-packages/theano/gof/fg.pyc in __import__(self, apply_node, check, reason) 472 "for more information on this error." 473 % str(node)), --&gt; 474 r) 475 476 for node in new_nodes: MissingInputError: ("An input of the graph, used to compute Elemwise{neg,no_inplace}(P_logodds_), was not provided and not given a value.Use the Theano flag exception_verbosity='high',for more information on this error.", P_logodds_) &gt; /home/dmahler/Anaconda/lib/python2.7/site-packages/theano/gof/fg.py(474)__import__() 472 "for more information on this error." 473 % str(node)), --&gt; 474 r) 475 476 for node in new_nodes: </code></pre> <p>Before I was aware of <code>pymc3.BetaBinomial</code> I was fitting trying to achieve the same result using separate <code>Beta</code> and <code>Binomial</code> instances:</p> <pre><code>with pm.Model() as model: C=pm.constant(C0) I=pm.constant(I0) C1=pm.constant(C0 + 1) I1=pm.constant(I0 + 1) N=pm.constant(N0) alpha = pm.Exponential('alpha', 1/(C0.sum()+1)) beta = pm.Exponential('beta', 1/(I0.sum()+1)) p = pm.Beta('P', alpha, beta, shape=K) b = pm.Binomial('B', N, p, observed=C0) </code></pre> <p>This completes successfully but different methods produce rather different results. I thought this could be partly due to the extra level of indirection between the priors and the observations makes the search space larger. When I came across <code>BetaBinomial</code> I figured it would make the search easier as well as being <em>the right thing ^TM</em>. Otherwise I believe the to models should be logically equivalent. Unfortunatelly I cannot figure out how to make <code>batebinomial</code> work and I am unable to find any examples using <code>BetaBinomial</code> on the internet.</p> <ul> <li>How do I make the <code>BetaBinomial</code> modwel work?</li> <li>Are the models really logically equivalent?</li> <li>Does anybody have a better guess at the cause of the numerical problems with the initial hierarchical version? <ul> <li>How I could fix them?</li> </ul></li> </ul>
0
2016-09-08T04:02:05Z
39,384,350
<p>Your model should run, and you can write this </p> <pre><code>with pm.Model() as model: alpha = pm.Exponential('alpha', 1/(C0.sum()+1)) beta = pm.Exponential('beta', 1/(I0.sum()+1)) obs = pm.BetaBinomial('obs', alpha, beta, N0, observed=C0) </code></pre> <p>That is, (C, I C1, I1) were defined in you model but not used. Anyway that was not the problem. The error you are getting is because PyMC3 is expecting a variable <code>P</code> (like in the second model you have) but the variable is not defined. May be you are working with a Jupyter notebook and you delete/comment a theano variable. Try running the Notebook again.</p> <p>Theoretically using a Beta and a Binomial or a BetaBinomial should give the same results. From a practical point of view. Sampling from the BetaBinomial should be faster than from a beta and a binomial, since part of the work has already being done analytically!</p> <p>Assuming a correct sampling both models should provide equivalent results. To check both results are equivalent try increasing the number of samples (and avoid <a href="http://doingbayesiandataanalysis.blogspot.co.at/2011/11/thinning-to-reduce-autocorrelation.html" rel="nofollow">thinning</a>). Also compare the results between and within models (the differences should be about the same). If you don't need to estimate the <code>P</code> variable (the beta distribution), then use the BetaBinomial.</p>
2
2016-09-08T06:52:16Z
[ "python", "bayesian", "pymc", "data-science", "pymc3" ]
crop center portion of a numpy image
39,382,412
<p>Let's say I have a numpy image of some width x and height y. I have to crop the center portion of the image to width cropx and height cropy. Let's assume that cropx and cropy are positive non zero integers and less than the respective image size. What's the best way to apply the slicing for the output image?</p> <p>Thanks, Gert</p>
1
2016-09-08T04:04:33Z
39,382,475
<p>Something along these lines -</p> <pre><code>def crop_center(img,cropx,cropy): y,x = img.shape startx = x//2-(cropx//2) starty = y//2-(cropy//2) return img[starty:starty+cropy,startx:startx+cropx] </code></pre> <p>Sample run -</p> <pre><code>In [45]: img Out[45]: array([[88, 93, 42, 25, 36, 14, 59, 46, 77, 13, 52, 58], [43, 47, 40, 48, 23, 74, 12, 33, 58, 93, 87, 87], [54, 75, 79, 21, 15, 44, 51, 68, 28, 94, 78, 48], [57, 46, 14, 98, 43, 76, 86, 56, 86, 88, 96, 49], [52, 83, 13, 18, 40, 33, 11, 87, 38, 74, 23, 88], [81, 28, 86, 89, 16, 28, 66, 67, 80, 23, 95, 98], [46, 30, 18, 31, 73, 15, 90, 77, 71, 57, 61, 78], [33, 58, 20, 11, 80, 25, 96, 80, 27, 40, 66, 92], [13, 59, 77, 53, 91, 16, 47, 79, 33, 78, 25, 66], [22, 80, 40, 24, 17, 85, 20, 70, 81, 68, 50, 80]]) In [46]: crop_center(img,4,6) Out[46]: array([[15, 44, 51, 68], [43, 76, 86, 56], [40, 33, 11, 87], [16, 28, 66, 67], [73, 15, 90, 77], [80, 25, 96, 80]]) </code></pre>
1
2016-09-08T04:12:43Z
[ "python", "image", "numpy", "crop" ]
crop center portion of a numpy image
39,382,412
<p>Let's say I have a numpy image of some width x and height y. I have to crop the center portion of the image to width cropx and height cropy. Let's assume that cropx and cropy are positive non zero integers and less than the respective image size. What's the best way to apply the slicing for the output image?</p> <p>Thanks, Gert</p>
1
2016-09-08T04:04:33Z
39,383,139
<p>Thanks, Divakar.</p> <p>Your answer got me going the right direction. I came up with this using negative slice offsets to count 'from the end':</p> <pre><code>def cropimread(crop, xcrop, ycrop, fn): "Function to crop center of an image file" img_pre= msc.imread(fn) if crop: ysize, xsize, chan = img_pre.shape xoff = (xsize - xcrop) // 2 yoff = (ysize - ycrop) // 2 img= img_pre[yoff:-yoff,xoff:-xoff] else: img= img_pre return img </code></pre> <p>A few things I am not sure about.</p> <ol> <li>Will this work with odd image sizes and/or crop values?</li> <li>Will the output images always be of same size?</li> </ol> <p>Cheers, Gert</p>
1
2016-09-08T05:24:53Z
[ "python", "image", "numpy", "crop" ]
Pandas timeseries with superimposed lines
39,382,481
<p>I have two data frames in pandas one with four timesseries with second by second data like the following</p> <pre><code>timestamp ID value1 value2 value3 value4 2016/01/01T01:01:01 1234 100 50 50 60 2016/01/01T01:01:02 1234 101 48 48 52 2016/01/01T01:01:02 1234 101 48 48 52 .... </code></pre> <p>and a second with averages from selected intervals</p> <pre><code>ID start_time end_time avg_value1 avg_value2 avg_value3 avg_value4 1234 01:01:01 01:01:15 100.1 50.2 49 55 ... </code></pre> <p>I would like to plot these two as timeseries superimposed over each other with the averages appearing as flat lines starting at start_time and ending at end_time. How would I go about doing this in the latest version of pandas?</p>
0
2016-09-08T04:13:12Z
39,382,982
<p>The easiest way is to put all the data into a single DataFrame and use the built-in <code>.plot()</code> method.</p> <p>Assuming your original DataFrame is called <code>df</code> the the code below should solve your issue (you might need to strip out the "ID" column):</p> <pre><code>means = df.groupby(pd.TimeGrouper('15s')).mean() means.columns = ['avg_'+col for col in df.columns] merged_df = pd.concat([df, means], axis=1).fillna(method='ffill') merged_df.plot() </code></pre> <p>Using some intraday 1s candle stock data, you get something like this:</p> <p><a href="http://i.stack.imgur.com/xGGXl.png" rel="nofollow"><img src="http://i.stack.imgur.com/xGGXl.png" alt="enter image description here"></a></p> <p>If you want to further customize your plots I am afraid you will have to spend a few hours/days studying the basics of matplotlib.</p>
0
2016-09-08T05:09:25Z
[ "python", "pandas" ]
Find the last element (digit) on each line and sum all that are even python 3
39,382,509
<p>Hi there Stack Overflow!</p> <p>I'm trying to solve an assignment we got in my Python class today. I'm not super familiar with python yet so I could really need some tips.</p> <p>The task is to: Find the last element (digit) on each line, if there are any, and sum all that are even.</p> <p>I have started to do something like this:</p> <pre><code>result = 0 counter = 0 handle = open('httpd-access.txt') for line in handle: line = line.strip() #print (line) if line[:-1].isdigit(): print(line[:-1].isdigit()) digitFirst = int(line[counter].isdigit()) if digitFirst % 2 == 0: print("second") result += digitFirst else: print("else") ANSWER = result </code></pre> <p>But this code doesnt work for me, I don't get any data in result. What is it that i'm missing? Think one problem is that I'm not going through the line element by element, just the whole line.</p> <p>Here is an example of how I line in the file can look:</p> <pre><code>37.58.100.166--[02/Jul/2014:16:29:23 +0200]"GET/kod-exempel/source.php?dir=codeigniter/user_guide_src/source/_themes/eldocs/static/asset HTTP/1.1"200867 </code></pre> <p>So the thing I want to retrieve is the 7. And then I want to do a check if the seven is a even or odd number. If it's even, I save it in the a variable.</p>
1
2016-09-08T04:17:12Z
39,382,591
<p><code>isdigit()</code> return <code>True</code> or <code>False</code>, which is assigned to <code>digitFirst</code> (try print it!).<br> <code>True</code> and <code>False</code> are evaluated as 0 and 1 (respectively) in math operations.<br> So, it always pass the <code>if digitFirst % 2 == 0</code> when <code>digitFirst</code> is <code>0</code>, which means <code>0</code> always gets added to <code>result</code>.</p> <p>Also, notice that <code>counter</code> is always 0 during the <code>for</code> loop and gets raised to 1 only after it, which means you are always working with the <strong>first</strong> letter of every line. </p> <p>The purpose of <code>counter</code>is unclear as it only used as "the index of the letter you get" each line.</p>
1
2016-09-08T04:25:27Z
[ "python", "python-3.x" ]
Find the last element (digit) on each line and sum all that are even python 3
39,382,509
<p>Hi there Stack Overflow!</p> <p>I'm trying to solve an assignment we got in my Python class today. I'm not super familiar with python yet so I could really need some tips.</p> <p>The task is to: Find the last element (digit) on each line, if there are any, and sum all that are even.</p> <p>I have started to do something like this:</p> <pre><code>result = 0 counter = 0 handle = open('httpd-access.txt') for line in handle: line = line.strip() #print (line) if line[:-1].isdigit(): print(line[:-1].isdigit()) digitFirst = int(line[counter].isdigit()) if digitFirst % 2 == 0: print("second") result += digitFirst else: print("else") ANSWER = result </code></pre> <p>But this code doesnt work for me, I don't get any data in result. What is it that i'm missing? Think one problem is that I'm not going through the line element by element, just the whole line.</p> <p>Here is an example of how I line in the file can look:</p> <pre><code>37.58.100.166--[02/Jul/2014:16:29:23 +0200]"GET/kod-exempel/source.php?dir=codeigniter/user_guide_src/source/_themes/eldocs/static/asset HTTP/1.1"200867 </code></pre> <p>So the thing I want to retrieve is the 7. And then I want to do a check if the seven is a even or odd number. If it's even, I save it in the a variable.</p>
1
2016-09-08T04:17:12Z
39,382,718
<pre><code>result = [] with open('https-access.txt') as fin: for line in fin: l = line.strip() if l[-1].isdigit(): if int(l[-1]) % 2 == 0: result.append(int(l[-1])) ANSWER = sum(result) </code></pre> <p>How does your file look? You want to calculate the last digit on each line if it's even number. In your code "line[counter]" will catch the first index of each line.</p> <p>For example if data in file is as follows:</p> <pre><code>some_data 2 </code></pre> <p>since counter is set to 0, therefore line['counter'] in your code will always check the first index which will be 's' in the example above.</p> <p>If you can post a few lines from the file that you will be opening, I may be able to suggest something.</p>
1
2016-09-08T04:41:16Z
[ "python", "python-3.x" ]
Find the last element (digit) on each line and sum all that are even python 3
39,382,509
<p>Hi there Stack Overflow!</p> <p>I'm trying to solve an assignment we got in my Python class today. I'm not super familiar with python yet so I could really need some tips.</p> <p>The task is to: Find the last element (digit) on each line, if there are any, and sum all that are even.</p> <p>I have started to do something like this:</p> <pre><code>result = 0 counter = 0 handle = open('httpd-access.txt') for line in handle: line = line.strip() #print (line) if line[:-1].isdigit(): print(line[:-1].isdigit()) digitFirst = int(line[counter].isdigit()) if digitFirst % 2 == 0: print("second") result += digitFirst else: print("else") ANSWER = result </code></pre> <p>But this code doesnt work for me, I don't get any data in result. What is it that i'm missing? Think one problem is that I'm not going through the line element by element, just the whole line.</p> <p>Here is an example of how I line in the file can look:</p> <pre><code>37.58.100.166--[02/Jul/2014:16:29:23 +0200]"GET/kod-exempel/source.php?dir=codeigniter/user_guide_src/source/_themes/eldocs/static/asset HTTP/1.1"200867 </code></pre> <p>So the thing I want to retrieve is the 7. And then I want to do a check if the seven is a even or odd number. If it's even, I save it in the a variable.</p>
1
2016-09-08T04:17:12Z
39,382,913
<p>Don't even bother with the <code>isdigit</code>. Go ahead and try the conversion to <code>int</code> and catch the exception if it fails.</p> <pre><code>result = 0 with open('httpd-access.txt') as f: for line in f: try: i = int(line.strip()[-1:]) if(i % 2 == 0): result += i except ValueError: pass print('result = %d' % result) </code></pre>
3
2016-09-08T05:02:22Z
[ "python", "python-3.x" ]
ipython notebook clear all code
39,382,531
<p>All I want to do is try some new codes in ipython notebook and I don't want to save it every time as its done automatically. Instead what I want is clear all the codes of ipython notebook along with reset of variables.</p> <p>I want to do some coding and clear everything and start coding another set of codes without going to new python portion and without saving the current code.</p> <p>Any shortcuts will be appreciated.</p> <p>Note: I want to clear every cells code one time. All I want is an interface which appears when i create new python file, but I don't want to save my current code.</p>
0
2016-09-08T04:19:22Z
39,382,560
<p>Ok youngster, I will break this down for ya in simple steps:</p> <ol> <li>go to the intended textbox and put your mouse cursor there</li> <li>on keyboard press crtl-a and delete</li> <li>Ta-dah all done </li> </ol> <p>Glad to help </p>
0
2016-09-08T04:22:54Z
[ "python", "jupyter-notebook" ]
ipython notebook clear all code
39,382,531
<p>All I want to do is try some new codes in ipython notebook and I don't want to save it every time as its done automatically. Instead what I want is clear all the codes of ipython notebook along with reset of variables.</p> <p>I want to do some coding and clear everything and start coding another set of codes without going to new python portion and without saving the current code.</p> <p>Any shortcuts will be appreciated.</p> <p>Note: I want to clear every cells code one time. All I want is an interface which appears when i create new python file, but I don't want to save my current code.</p>
0
2016-09-08T04:19:22Z
39,472,132
<p>Well, you could use Shift-M to merge the cells (from top) - at least there's only one left to delete manually. </p>
0
2016-09-13T14:08:19Z
[ "python", "jupyter-notebook" ]
Python: Assigning # values in a list to bins, by rounding up
39,382,594
<p>I want a function that can take a series and a set of bins, and basically round up to the nearest bin. For example:</p> <pre><code>my_series = [ 1, 1.5, 2, 2.3, 2.6, 3] def my_function(my_series, bins): ... my_function(my_series, bins=[1,2,3]) &gt; [1,2,2,3,3,3] </code></pre> <p>This seems to be very close to what <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.digitize.html" rel="nofollow">Numpy's Digitize</a> is intended to do, but it produces the wrong values (asterisks for wrong values):</p> <pre><code>np.digitize(my_series, bins= [1,2,3], right=False) &gt; [1, 1*, 2, 2*, 2*, 3] </code></pre> <p>The reason why it's wrong is clear from the documentation:</p> <blockquote> <p>Each index i returned is such that <strong>bins[i-1] &lt;= x &lt; bins[i]</strong> if bins is monotonically increasing, or <strong>bins[i-1] > x >= bins[i]</strong> if bins is monotonically decreasing. If values in x are beyond the bounds of bins, 0 or len(bins) is returned as appropriate. If right is True, then the right bin is closed so that the index i is such that bins[i-1] &lt; x &lt;= bins[i] or bins[i-1] >= x > bins[i]`` if bins is monotonically increasing or decreasing, respectively.</p> </blockquote> <p>I can kind of get closer to what I want if I enter in the values decreasing and set "right" to True... </p> <pre><code>np.digitize(my_series, bins= [3,2,1], right=True) &gt; [3, 2, 2, 1, 1, 1] </code></pre> <p>but then I'll have to think of a way of basically methodically reversing the lowest number assignment (1) with the highest number assignment (3). It's simple when there are just 3 bins, but will get hairier when the number of bins get longer..there must be a more elegant way of doing all this.</p>
4
2016-09-08T04:25:42Z
39,382,732
<p>I believe <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.searchsorted.html" rel="nofollow"><code>np.searchsorted</code></a> will do what you want:</p> <blockquote> <p>Find the indices into a sorted array <code>a</code> such that, if the corresponding elements in <code>v</code> were inserted before the indices, the order of a would be preserved.</p> </blockquote> <pre><code>In [1]: my_series = [1, 1.5, 2, 2.3, 2.6, 3] In [2]: bins = [1,2,3] In [3]: import numpy as np In [4]: [bins[k] for k in np.searchsorted(bins, my_series)] Out[4]: [1, 2, 2, 3, 3, 3] </code></pre> <p>(As of numpy 1.10.0, <code>digitize</code> is implemented in terms of <code>searchsorted</code>.)</p>
1
2016-09-08T04:42:45Z
[ "python", "numpy", "grouping", "rounding", "bins" ]
Python: Assigning # values in a list to bins, by rounding up
39,382,594
<p>I want a function that can take a series and a set of bins, and basically round up to the nearest bin. For example:</p> <pre><code>my_series = [ 1, 1.5, 2, 2.3, 2.6, 3] def my_function(my_series, bins): ... my_function(my_series, bins=[1,2,3]) &gt; [1,2,2,3,3,3] </code></pre> <p>This seems to be very close to what <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.digitize.html" rel="nofollow">Numpy's Digitize</a> is intended to do, but it produces the wrong values (asterisks for wrong values):</p> <pre><code>np.digitize(my_series, bins= [1,2,3], right=False) &gt; [1, 1*, 2, 2*, 2*, 3] </code></pre> <p>The reason why it's wrong is clear from the documentation:</p> <blockquote> <p>Each index i returned is such that <strong>bins[i-1] &lt;= x &lt; bins[i]</strong> if bins is monotonically increasing, or <strong>bins[i-1] > x >= bins[i]</strong> if bins is monotonically decreasing. If values in x are beyond the bounds of bins, 0 or len(bins) is returned as appropriate. If right is True, then the right bin is closed so that the index i is such that bins[i-1] &lt; x &lt;= bins[i] or bins[i-1] >= x > bins[i]`` if bins is monotonically increasing or decreasing, respectively.</p> </blockquote> <p>I can kind of get closer to what I want if I enter in the values decreasing and set "right" to True... </p> <pre><code>np.digitize(my_series, bins= [3,2,1], right=True) &gt; [3, 2, 2, 1, 1, 1] </code></pre> <p>but then I'll have to think of a way of basically methodically reversing the lowest number assignment (1) with the highest number assignment (3). It's simple when there are just 3 bins, but will get hairier when the number of bins get longer..there must be a more elegant way of doing all this.</p>
4
2016-09-08T04:25:42Z
39,382,758
<p>Another way would be:</p> <pre><code>In [25]: def find_nearest(array,value): ...: idx = (np.abs(array-np.ceil(value))).argmin() ...: return array[idx] ...: In [26]: my_series = np.array([ 1, 1.5, 2, 2.3, 2.6, 3]) In [27]: bins = [1, 2, 3] In [28]: [find_nearest(bins, x) for x in my_series] Out[28]: [1, 2, 2, 3, 3, 3] </code></pre>
1
2016-09-08T04:44:52Z
[ "python", "numpy", "grouping", "rounding", "bins" ]
Python: Assigning # values in a list to bins, by rounding up
39,382,594
<p>I want a function that can take a series and a set of bins, and basically round up to the nearest bin. For example:</p> <pre><code>my_series = [ 1, 1.5, 2, 2.3, 2.6, 3] def my_function(my_series, bins): ... my_function(my_series, bins=[1,2,3]) &gt; [1,2,2,3,3,3] </code></pre> <p>This seems to be very close to what <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.digitize.html" rel="nofollow">Numpy's Digitize</a> is intended to do, but it produces the wrong values (asterisks for wrong values):</p> <pre><code>np.digitize(my_series, bins= [1,2,3], right=False) &gt; [1, 1*, 2, 2*, 2*, 3] </code></pre> <p>The reason why it's wrong is clear from the documentation:</p> <blockquote> <p>Each index i returned is such that <strong>bins[i-1] &lt;= x &lt; bins[i]</strong> if bins is monotonically increasing, or <strong>bins[i-1] > x >= bins[i]</strong> if bins is monotonically decreasing. If values in x are beyond the bounds of bins, 0 or len(bins) is returned as appropriate. If right is True, then the right bin is closed so that the index i is such that bins[i-1] &lt; x &lt;= bins[i] or bins[i-1] >= x > bins[i]`` if bins is monotonically increasing or decreasing, respectively.</p> </blockquote> <p>I can kind of get closer to what I want if I enter in the values decreasing and set "right" to True... </p> <pre><code>np.digitize(my_series, bins= [3,2,1], right=True) &gt; [3, 2, 2, 1, 1, 1] </code></pre> <p>but then I'll have to think of a way of basically methodically reversing the lowest number assignment (1) with the highest number assignment (3). It's simple when there are just 3 bins, but will get hairier when the number of bins get longer..there must be a more elegant way of doing all this.</p>
4
2016-09-08T04:25:42Z
39,397,822
<p>We can simply use <code>np.digitize</code> with its <code>right</code> option set as <code>True</code> to get the indices and then to extract the corresponding elements off <code>bins</code>, bring in <code>np.take</code>, like so -</p> <pre><code>np.take(bins,np.digitize(a,bins,right=True)) </code></pre>
1
2016-09-08T18:25:46Z
[ "python", "numpy", "grouping", "rounding", "bins" ]
Saving Python list containing Tensorflow Sparsetensors to file for later access?
39,382,725
<p>I'm creating a list of Sparsetensors in Tensorflow. I want to access them in later sessions of my program. I've read online that you can store Python lists as json files but how do I save a list of Sparsetensors to a json file and then use that later on?</p> <p>Thanks in advance</p>
0
2016-09-08T04:42:15Z
39,395,872
<p>A Tensor in TensorFlow is a node in the graph which, when run, will produce a tensor. So you can't save the SparseTensor directly because it's not a value (you can serialize the graph). If you do evaluate the sparsetensor, you get a SparseTensorValue object back which can be serialized as it's just a tuple.</p>
1
2016-09-08T16:17:35Z
[ "python", "json", "tensorflow" ]
<urlopen error (-1, 'SSL exception: Differences between the SSL socket behaviour of cpython vs. jython are explained on the wiki
39,382,800
<p>I'm using the following code.</p> <pre><code>import urllib2 #Setting proxy myProxy = {'https':'https://proxy.example.com:8080'} proxy = urllib2.ProxyHandler(myProxy) opener = urllib2.build_opener(proxy) urllib2.install_opener(opener) #Access URL auth_token = "realLy_loNg_AuTheNicaTion_toKen" headers={"Content-Type":"application/json", "charset": "UTF-8", "Authorization": "Bearer %s" %auth_token} url = "https://example.com/something" req = urllib2.Request(url, None, headers) reply = urllib2.urlopen(req) print reply.getcode() </code></pre> <p>I'm running the above as a Jython script in nGrinder. When I run the same script on my system with Jython, it works fine and returns 200(OK status code). When I run it on nGrinder, I get the error</p> <pre><code>(-1, 'SSL exception: Differences between the SSL socket behaviour of cpython vs. jython are explained on the wiki: http://wiki.python.org/jython/NewSocketModule#SSL_Support') </code></pre> <p>Any ideas why this is happening?</p> <p>EDIT: I've been trying and the issue is definitely with the long authentication token. I have a feeling it might be some encoding issue. There was a similar question posted <a href="http://stackoverflow.com/questions/33912074/https-get-using-jython">here</a> before. I read it but it wasn't described properly. But it could be a good reference to think off of.</p>
6
2016-09-08T04:51:17Z
39,558,507
<p>It seems issue of certificate trust. <a href="http://bugs.jython.org/issue1688" rel="nofollow">http://bugs.jython.org/issue1688</a></p> <p>There are these two options that will solve your problem.</p> <blockquote> <p>Jython is not like cpython. Cpython does not verify the chain of trust for server certificates. Jython does verify the chain of trust, and will refuse to open the connection if it cannot verify the server.</p> <p>So you have two options.</p> <ol> <li>Disable certificate checking on jython</li> </ol> <p><a href="http://jython.xhaus.com/installing-an-all-trusting-security-provider-on-java-and-jython/" rel="nofollow">http://jython.xhaus.com/installing-an-all-trusting-security-provider-on-java-and-jython/</a> <a href="http://tech.pedersen-live.com/2010/10/trusting-all-certificates-in-jython/" rel="nofollow">http://tech.pedersen-live.com/2010/10/trusting-all-certificates-in-jython/</a></p> <ol start="2"> <li>Add your (self-signed?) certificate to your local java trust store, so that your client will trust your server.</li> </ol> <p>Google("java install self-signed certificate")</p> </blockquote> <p>Another reason for this can be due to incompactible version of python and java (<a href="https://github.com/geoscript/geoscript-py/issues/32" rel="nofollow">https://github.com/geoscript/geoscript-py/issues/32</a>)</p> <blockquote> <p>I just tried with Jython 2.5.3 and JDK 1.7 on Mac and was able to run ez_setup.py.</p> <p>Java version: [Java HotSpot(TM) 64-Bit Server VM (Oracle Corporation)] on java1.7.0_51</p> <p>Swapping to Oracle JDK 7 did the trick.</p> </blockquote> <p>Please check if this solves the problem, as per implementation of jython and error, issue is due to HTTPS(SSL layer) <a href="https://github.com/int3/jython/blob/master/Lib/socket.py" rel="nofollow">https://github.com/int3/jython/blob/master/Lib/socket.py</a></p> <pre><code># These error codes are currently wrong: getting them correct is going to require # some investigation. Cpython 2.6 introduced extensive SSL support. (javax.net.ssl.SSLException, ALL) : lambda x: sslerror(-1, 'SSL exception'+_ssl_message), </code></pre>
0
2016-09-18T14:07:48Z
[ "python", "ssl", "jython" ]
Two subplots of gridspec, one line plot and the other bar plot, with a time-series on x, are not displaying
39,382,801
<p>I can't figure out what I'm doing wrong in my plotting. Plotting some data vs datetime on two subplots, one is a line plot, the other one should be a bar plot. I have tried several different ways of plotting it but without much success. </p> <p><strong>UPDATE</strong> Minor progress - the first plot is displayed, the second one not.</p> <p>Data looks for example like this:</p> <pre><code> A B C 0 2014-10-23 15:44:00 1 1.5 1 2014-10-30 19:10:00 2 2.0 2 2014-11-05 21:30:00 3 3.3 3 2014-11-07 05:50:00 4 4.0 4 2014-11-12 12:20:00 5 5.8 </code></pre> <p>The latest version of the code:</p> <pre><code>import pandas as pd import numpy as np import matplotlib.pyplot as plt from matplotlib import gridspec import datetime Test = pd.DataFrame({'A':[datetime.datetime(2014,10,23,15,44),datetime.datetime(2014,10,30,19,10), datetime.datetime(2014,11,5,21,30),datetime.datetime(2014,11,7,5,50), datetime.datetime(2014,11,12,12,20)],'B':[1,2,3,4,5],'C':[1.5,2,3.3,4,5.8]}) fig = plt.figure(figsize=(8,8)) gs=gridspec.GridSpec(2,1, hspace=0.1, wspace=0.3, height_ratios=[1,1]) axes1 = plt.subplot(gs[0,0]) ax1 = plt.plot(Test["A"],Test["B"], 'dimgrey', linewidth = 2.5, label = "test") #DepTime = DepTime.set_index("DATETIME") #for l in log_times: # ax1 = plt.bar(l,DepTime.ix[l,"Depth"], width = 1.5, color='b') ax1 = plt.xlim(Test.iloc[0,0],Test.iloc[-1,0]) xticks2 = pd.date_range(start=Test.iloc[0,0],end=Test.iloc[-1,0], freq='D', normalize=True) ax1 = plt.xticks(xticks2,xticks2) ax1 = plt.setp(axes1.get_xticklabels(), visible=False) ax1 = plt.ylim(1,5) ax1 = plt.yticks(np.arange(0,5,1),rotation=0) ax1 = plt.ylabel("B",fontsize = 12) axes2 = plt.subplot(gs[1,0]) ax2 = Test.plot("A","C",kind='bar', ax=axes2) # #ax2 = plt.bar(Test["A"],Test["C"],color='k') #ax2 = plt.xlim(Test.iloc[0,0],Test.iloc[-1,0]) ax2 = plt.xlim(Test.iloc[0,0],Test.iloc[-1,0]) ax2 = plt.xlabel("A",fontsize=12) #ax2 = plt.xaxis_date() #ax2.xaxis.set_major_formatter(mdates.DateFormatter('%d)) ax2 = plt.xticks(xticks2,xticks2, rotation=45) #axes2.xticklabels([x.strftime('%d/%m/%Y %H:%M') for x in xticks2]) #ax2.autofmt_xdate() #ax2 = plt.yticks([0,1]) ax2 = plt.ylim(1,5) ax2 = plt.setp(axes2.get_yticklabels(), visible=False) fig = plt.show() </code></pre> <p>And the resulting figure: <a href="http://i.stack.imgur.com/iPokE.png" rel="nofollow"><img src="http://i.stack.imgur.com/iPokE.png" alt="The incomplete plot"></a></p>
0
2016-09-08T04:51:20Z
39,385,614
<p>I found out what the problem was!!! I don't understand why it worked fine with the line plot and not with the bar plot, but all that needed to be changed in the code is the actual one line for the bar plot. It should go like this:</p> <pre><code>ax2 = plt.bar(Test["A"].values,Test["C"],width=1) </code></pre> <p>So bar plot can't handle datetime? (This <a href="http://stackoverflow.com/a/25234067/5553319">answer</a> helped)</p>
0
2016-09-08T08:02:08Z
[ "python", "python-2.7", "pandas", "matplotlib", "bar-chart" ]
Ubuntu 14.04 LTS: `apt-get install rake` -> “ImportError: No module named rake”
39,382,898
<pre><code>I used 'sudo apt-get install rake'. &gt;&gt;&gt; import rake but Fails with error Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ImportError: No module named rake </code></pre> <p>Why this happened?I'm missing something.</p>
0
2016-09-08T05:00:37Z
39,383,795
<p>Ok, I got answer.</p> <pre><code>$ git clone https://github.com/zelandiya/RAKE-tutorial $ cd RAKE-tutorial/ :~/RAKE-tutorial$ python &gt;&gt;&gt; import rake </code></pre>
0
2016-09-08T06:20:03Z
[ "python", "ubuntu", "rake" ]
mypy spurious error: "module" has no attribute "XPath" with etree
39,382,937
<p>I'm trying to use <code>mypy</code> to do type checking in some code that uses the <a href="http://lxml.de/" rel="nofollow">LXML</a> library to parse XML.</p> <p>On each line where I use <code>etree.XPath</code>, I get a spurious error from <code>mypy</code>. For example, the following trivial script</p> <pre><code>from lxml import etree NameXPath = etree.XPath("Name/text()") </code></pre> <p>generates the error</p> <pre><code>test.py:3: error: "module" has no attribute "XPath" </code></pre> <p>But the script runs fine and my <code>XPath</code>'s work correctly at runtime.</p> <p>I also tried <code>#type:ignore</code> on the import, which I thought might tell <code>mypy</code> not to type-check that library, but that did not suppress the errors.</p> <pre><code>from lxml import etree # type:ignore NameXPath = etree.XPath("Name/text()") </code></pre> <p>I did have some success at suppressing some of the errors by moving the calls to <code>etree.XPath</code> into a separate function which doesn't have any type annotations, but that seemed like a hack and forced me to arrange my code in awkward ways. </p> <p>I would like to know if there's a way to completely suppress these spurious errors, or to possibly hint that the <code>etree.XPath</code> function does exist since it doesn't seem to be able to figure that out on its own.</p> <p>To be clear, I don't actually care that <code>mypy</code> knows the correct types for structures coming out of the <code>lxml</code> library. I'm more concerned about putting the type info on my own classes that I'm shoving the parsed information into, so I want to have type-checked functions which use <code>etree.XPath</code> to do queries, find the data, and then shove them into type-annotated classes that are defined within my script.</p> <p><code>mypy</code> doesn't seem to have difficulty with other functions in <code>etree</code>, for example it's fine with my calls to <code>etree.parse</code></p> <p>I'm currently using <code>mypy</code> 0.4.4</p>
2
2016-09-08T05:04:31Z
39,393,394
<p>It looks like this is a bug in <a href="https://github.com/python/typeshed" rel="nofollow">typeshed</a>, the community-contributed collection of type annotations for the stdlib and various third party libraries.</p> <p>In particular, it looks as if the <a href="https://github.com/python/typeshed/tree/master/third_party/3/lxml" rel="nofollow">stubs for lxml</a> are missing definitions for XPath entirely. This is probably an oversight -- I would try filing a bug on the issue tracker or try submitting a pull request containing a fix.</p> <p>Once this is fixed, and mypy resyncs itself with the latest version of typeshed, you'll need to install mypy from the <a href="https://github.com/python/mypy" rel="nofollow">git repo</a> for the time being (at least, until mypy 0.4.5 comes out sometime in October).</p> <p>In the meantime, you can work around this by doing this:</p> <pre><code>from lxml.etree import XPath # type: ignore NameXPath = XPath("Name/text()") # mypy considers NameXPath to have a type of Any </code></pre> <p>...or, if you'd prefer having a more specific definition of XPath, do this:</p> <pre><code>import typing if typing.TYPE_CHECKING: # typing.TYPE_CHECKING is always False at runtime, so this # branch is parsed by typecheckers only class XPath: # Provide a method header stubs with signatures to fool # mypy into understanding what the interface for XPath is else: # Actually executed at runtime from lxml.etree import XPath # type: ignore NameXPath = XPath("Name/text()") </code></pre>
1
2016-09-08T14:18:54Z
[ "python", "lxml", "mypy" ]
Install OpenStack: ImportError: Could not import settings 'openstack_dashboard.settings' (***?): No module named angular_fileupload
39,383,334
<p>I was trying to build openstack (stack.sh), tried many times, still can't figure out the reason, below is the logs:</p> <pre><code>2016-09-08 05:36:48.424 | Warning: Could not import Horizon dependencies. This is normal during installation. 2016-09-08 05:36:48.425 | WARNING:root:No local_settings file found. 2016-09-08 05:36:48.426 | Traceback (most recent call last): 2016-09-08 05:36:48.426 | File "/opt/stack/horizon/manage.py", line 23, in &lt;module&gt; 2016-09-08 05:36:48.426 | execute_from_command_line(sys.argv) 2016-09-08 05:36:48.426 | File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 385, in execute_from_command_line 2016-09-08 05:36:48.426 | utility.execute() 2016-09-08 05:36:48.426 | File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 345, in execute 2016-09-08 05:36:48.426 | settings.INSTALLED_APPS 2016-09-08 05:36:48.426 | File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 46, in __getattr__ 2016-09-08 05:36:48.426 | self._setup(name) 2016-09-08 05:36:48.426 | File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 42, in _setup 2016-09-08 05:36:48.426 | self._wrapped = Settings(settings_module) 2016-09-08 05:36:48.426 | File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 98, in __init__ 2016-09-08 05:36:48.426 | % (self.SETTINGS_MODULE, e) 2016-09-08 05:36:48.426 | ImportError: Could not import settings 'openstack_dashboard.settings' (Is it on sys.path? Is there an import error in the settings file?): No module named angular_fileupload 2016-09-08 05:36:48.450 | + exit_trap </code></pre>
0
2016-09-08T05:42:18Z
39,571,998
<p>First of all you need to make sure you have <code>pip</code> installed, if you've bootstrapped using Ubuntu <code>sudo apt-get install python-pip -y</code> where the -y flag is simply to accept any packages and prepare them for installation.</p> <p>If you are using CentOS or any other Redhat based system <code>yum install -y python-pip</code></p> <p>Once this is done you need to go to <code>cd horizon/</code> where horizon is the folder you've just downloaded using git.</p> <p>Should look like this:</p> <pre><code>fueladmin@nodename:~/horizon$ ls AUTHORS LICENSE run_tests.sh babel-django.cfg Makefile setup.cfg babel-djangojs.cfg manage.py setup.py build MANIFEST.in static ChangeLog node_modules test-requirements.txt CONTRIBUTING.rst openstack_dashboard test-shim.js doc package.json tools HACKING.rst README.rst tox.ini horizon releasenotes horizon.egg-info requirements.txt </code></pre> <p>If you are familiar with node package management, composer or ruby gems you'll soon understand that requirements.txt is the python equivalent to something like package.json or composer.json i.e. it's where all the packages that needs to be installed are located.</p> <p>Run this command <code>pip install -r requirements.txt</code> in the horizon/ folder and it should install. You may need to run it as sudo.</p> <p>Once this is done you can proceed, firing up the server, configuration etc.</p>
0
2016-09-19T11:22:49Z
[ "python", "openstack" ]
Python Import Error - specific case
39,383,412
<p>I know there has been a ton of questions about this, but mine is pretty specific and i don't really know why the import is not working. I've got the following Folder Structure:</p> <pre><code>importmodule -classes -pluginhelper -- __init__.py -plugins -- plugin_a -- plugin b -- .. -__init__.py -&lt;other py files&gt; </code></pre> <p>In my plugin files i am importing the pluginhelper like this: </p> <pre><code>from importmodule.pluginhelper import function1, function2, ... </code></pre> <p>The functions are defined in the __ init __.py </p> <p>Executing my plugin files works great on my windows machine. When i do it on the server, i get following Exception: </p> <pre><code> ImportError: No module named 'importmodule' </code></pre> <p>The curious thing is, that i do get the error from every plugin, but one. In one of the plugins the import works, while there is no difference in the import statements.</p> <p>I am using python 3.5 on both machines, while on the server my application is within a docker container.</p> <p>Edit: Setting the sys.path didnt work either : </p> <pre><code> print("Indexed Path for Package.") sys.path.index(os.getcwd()) </code></pre> <p>I found the possible problem: <strong>The folder structure in my dockercontainer seems to be different. I will fix it and tell you if it helped.</strong> Still i don't understand why it works with the one plugin using the same statement.</p>
0
2016-09-08T05:50:33Z
39,505,134
<p>I want to share my solution with you, since anybody reading the question seems to have similar problems. </p> <p>The problem occured because the package werent included in pythonpath / syspath. I am calling the plugins in a new thread with a script called execute.py. This is called via cmd from the main.py because i can't multiprocess my classes. And since the plugins are located in ../plugins, python only includes this path. Not the /importmodule path. Somehow it seems that it has been included on windows, i dont really know what has happened there tbh. </p> <p>What i did was, i included the <code>sys.path.append</code> stuff on my execute.py which executes the plugins as follows: <code>from pluginhelper import scrapeHostnames, hostnamesToIps, getSource</code>. My IDE marks the import statement red now, but it is working, since i am appending the package.</p>
0
2016-09-15T07:18:57Z
[ "python", "importerror" ]
Why won't my Angular front-end pass correct $http.get parameters to Django back-end?
39,383,507
<p>I have a Web Application made up of front-end client written in Angular/Javascript and a back-end server written in Python/Django. </p> <p>I'm trying to do a simple http GET request from the client to the server and it is not working. The reason it is failing is because for some unknown reason, the parameters are not being passed correctly.</p> <p>Here is the line of code being called on my client:</p> <pre><code> $http.get(API + '/api/getProfile', {'profileId':5}).then(console.log('A'), console.log('B')); </code></pre> <p>And here are the relevant lines of code on my server:</p> <pre><code>class GetProfileAPI(views.APIView): def get(self, request, *args, **kwargs): logger.info("request.get_full_path() = %s" % request.get_full_path()) profile_id_arg = request.GET.get('profileId') logger.info("profile_id_arg = %s (%s)" % (profile_id_arg, type(profile_id_arg))) # Do something here if profile_id_arg is not None. </code></pre> <p>When I run this code, I expect <code>profile_id_arg</code> on the server side to be the string <code>5</code>. But instead look at the output that I get:</p> <pre><code>request.get_full_path() = /api/getProfile profile_id_arg = None (&lt;type 'NoneType'&gt;) </code></pre> <p>Why isn't <code>profile_id</code> being received properly and how can I fix this? Code example would be helpful.</p>
1
2016-09-08T06:00:19Z
39,383,735
<p>A HTTP GET request can't contain data to be posted to the server. However you can add a query string to the request.</p> <pre><code> $http.get(API + '/api/getProfile', {params:{'profileId':5}}) .then(function (response) { /* */ })... </code></pre> <p>OR</p> <pre><code>$http({ url: API + '/api/getProfile', method: "GET", params: {'profileId':5} }); </code></pre> <p><a href="https://docs.angularjs.org/api/ng/service/$http#get" rel="nofollow">check here1</a> and <a href="https://docs.angularjs.org/api/ng/service/$http#usage" rel="nofollow">check here2</a></p>
2
2016-09-08T06:16:18Z
[ "javascript", "python", "angularjs", "django", "http-get" ]
SQLAlchemy InvalidRequestError when inserting to automap generated ORM
39,383,528
<p>I'm trying to use the SQLAlchemy automap extension to generate an ORM for an existing database, and am getting an InvalidRequestError exception ("Instance cannot be refreshed - it's not persistent and does not contain a full primary key.") whenever I try to insert into a table that uses a composite primary key consisting of a timestamp and a foreign key.</p> <p>Here's some minimal example code that reproduces the problem:</p> <pre><code>from sqlalchemy import create_engine, func, select from sqlalchemy.orm import sessionmaker from sqlalchemy.sql.expression import text from sqlalchemy.ext.automap import automap_base db_schema_cmds = [ '''CREATE TABLE users ( u_id INTEGER NOT NULL, name TEXT NOT NULL, CONSTRAINT Key1 PRIMARY KEY (u_id) );''', '''CREATE TABLE posts ( timestamp TEXT NOT NULL, text TEXT NOT NULL, u_id INTEGER NOT NULL, CONSTRAINT Key2 PRIMARY KEY (timestamp,u_id), CONSTRAINT users_have_posts FOREIGN KEY (u_id) REFERENCES users (u_id) ON DELETE CASCADE );'''] # Create a new in-memory SQLite DB and execute the schema SQL commands. db_engine = create_engine('sqlite://') with db_engine.connect() as db_conn: for cmd in db_schema_cmds: db_conn.execute(text(cmd)) # Use automap to reflect the DB schema and generate ORM classes. Base = automap_base() Base.prepare(db_engine, reflect=True) # Create aliases for the table classes generated. User = Base.classes.users Post = Base.classes.posts session_factory = sessionmaker() session_factory.configure(bind=db_engine) # Add a user and a post to the DB. session = session_factory() new_user = User(name="John") session.add(new_user) session.commit() new_post = Post(users=new_user, text='this is a test', timestamp=func.now()) session.add(new_post) session.commit() # Verify that the insertion worked. new_user_id = session.execute(select([User])).fetchone()['u_id'] new_post_fk_user_id = session.execute(select([Post])).fetchone()['u_id'] assert new_user_id == new_post_fk_user_id session.close() </code></pre> <p>Running this gives the following traceback:</p> <pre><code>Traceback (most recent call last): File "reproduce_InvalidRequestError.py", line 67, in &lt;module&gt; session.commit() File "C:\Python\Python35\lib\site-packages\sqlalchemy\orm\session.py", line 801, in commit self.transaction.commit() File "C:\Python\Python35\lib\site-packages\sqlalchemy\orm\session.py", line 392, in commit self._prepare_impl() File "C:\Python\Python35\lib\site-packages\sqlalchemy\orm\session.py", line 372, in _prepare_impl self.session.flush() File "C:\Python\Python35\lib\site-packages\sqlalchemy\orm\session.py", line 2019, in flush self._flush(objects) File "C:\Python\Python35\lib\site-packages\sqlalchemy\orm\session.py", line 2137, in _flush transaction.rollback(_capture_exception=True) File "C:\Python\Python35\lib\site-packages\sqlalchemy\util\langhelpers.py", line 60, in __exit__ compat.reraise(exc_type, exc_value, exc_tb) File "C:\Python\Python35\lib\site-packages\sqlalchemy\util\compat.py", line 186, in reraise raise value File "C:\Python\Python35\lib\site-packages\sqlalchemy\orm\session.py", line 2107, in _flush flush_context.finalize_flush_changes() File "C:\Python\Python35\lib\site-packages\sqlalchemy\orm\unitofwork.py", line 395, in finalize_flush_changes self.session._register_newly_persistent(other) File "C:\Python\Python35\lib\site-packages\sqlalchemy\orm\session.py", line 1510, in _register_newly_persistent instance_key = mapper._identity_key_from_state(state) File "C:\Python\Python35\lib\site-packages\sqlalchemy\orm\mapper.py", line 2417, in _identity_key_from_state for col in self.primary_key File "C:\Python\Python35\lib\site-packages\sqlalchemy\orm\mapper.py", line 2417, in &lt;listcomp&gt; for col in self.primary_key File "C:\Python\Python35\lib\site-packages\sqlalchemy\orm\attributes.py", line 578, in get value = state._load_expired(state, passive) File "C:\Python\Python35\lib\site-packages\sqlalchemy\orm\state.py", line 474, in _load_expired self.manager.deferred_scalar_loader(self, toload) File "C:\Python\Python35\lib\site-packages\sqlalchemy\orm\loading.py", line 647, in load_scalar_attributes "contain a full primary key." % state_str(state)) sqlalchemy.exc.InvalidRequestError: Instance &lt;posts at 0x45d45f8&gt; cannot be refreshed - it's not persistent and does not contain a full primary key. </code></pre> <p>If I add an <code>echo=True</code> parameter to the <code>create_engine</code> call, I see it is generating the following SQL for the insertion. This SQL works fine when I run it in DB Browser for SQLite.</p> <pre><code>INFO sqlalchemy.engine.base.Engine BEGIN (implicit) INFO sqlalchemy.engine.base.Engine SELECT users.u_id AS users_u_id, users.name AS users_name FROM users WHERE users.u_id = ? INFO sqlalchemy.engine.base.Engine (1,) INFO sqlalchemy.engine.base.Engine INSERT INTO posts (timestamp, text, u_id) VALUES (CURRENT_TIMESTAMP, ?, ?) INFO sqlalchemy.engine.base.Engine ('this is a test', 1) INFO sqlalchemy.engine.base.Engine ROLLBACK </code></pre> <p>I also tried removing the <code>users</code> parameter from <code>Post()</code> and instead adding the line <code>new_user.posts_collection.append(new_post)</code> before calling <code>session.add(new_post)</code>, but that resulted in the same SQL being generated and the same error occurring.</p> <p>If I replace the composite key with a new integer PK column, everything works fine. (Not an ideal solution though, as the reason I'm using <code>automap</code> is to reflect an <em>existing</em> DB, so it's preferable not to have to modify that DB's schema.)</p> <p>I found a similar question, <a href="http://stackoverflow.com/questions/29238260/sqlalchemy-invalidrequesterror-when-using-composite-foreign-keys">SQLAlchemy InvalidRequestError when using composite foreign keys</a>, however that seemed to be related to the use of inheritance in the table ORM classes, and the solution depended on defining the ORM table classes, rather than reflecting a DB to generate them.</p> <p>Edit: I had originally assumed that this problem was related to the fact that my composite primary key contained a foreign key. The accepted answer shows that the foreign key was not actually a contributing factor to the problem.</p>
1
2016-09-08T06:01:49Z
39,384,996
<p>The problem is not actually the composite primary key with the foreign key, but the <code>func.now()</code> passed as <code>timestamp</code>, which is part of the primary key. As the value is not known to SQLAlchemy, since it is generated during insert in the database, it cannot perform the post-fetch; it has no idea what to fetch. If the DB in question supported <code>RETURNING</code> or similar, you'd be able to do this. See the note on <a href="http://docs.sqlalchemy.org/en/latest/core/defaults.html#triggered-columns" rel="nofollow">triggered columns</a>, which describes this exact situation. Pre-executing SQL for primary key values is also covered in <a href="http://docs.sqlalchemy.org/en/latest/core/defaults.html#sql-expressions" rel="nofollow">Defaults / SQL Expressions</a>.</p> <p>The reason why it works with an integer surrogate primary key is that SQLite does have a mechanism for <a href="http://www.sqlite.org/c3ref/last_insert_rowid.html" rel="nofollow">fetching the last inserted row id</a> (an integer primary key column), which SQLAlchemy is able to use.</p> <p>To remedy this you can use a timestamp generated in Python</p> <pre><code>In [8]: new_post = Post(users=new_user, text='this is a test', ...: timestamp=datetime.utcnow()) ...: session.add(new_post) ...: session.commit() ...: </code></pre> <p>The other solution would be to override the <code>timestamp</code> column during reflection and to provide <code>func.now()</code> as the default. This would trigger the pre-execution of <code>func.now()</code>.</p> <pre><code> ...: # Use automap to reflect the DB schema and generate ORM classes. ...: Base = automap_base() ...: ...: # Override timestamp column before reflection ...: class Post(Base): ...: __tablename__ = 'posts' ...: timestamp = Column(Text, nullable=False, primary_key=True, ...: default=func.now()) ...: ...: Base.prepare(db_engine, reflect=True) ...: ...: # Create aliases for the table classes generated. ...: User = Base.classes.users ...: # Post has already been declared ...: #Post = Base.classes.posts </code></pre> <p>With the default in place, you do not need to (and shouldn't) provide <code>timestamp</code> when creating new instances</p> <pre><code>In [6]: new_post = Post(users=new_user, text='this is a test') ...: session.add(new_post) ...: session.commit() ...: </code></pre>
1
2016-09-08T07:30:05Z
[ "python", "sqlalchemy" ]
Is this python pattern for a singleton safe?
39,383,554
<p>I have a module R that handles gets and sets to a redis cluster. It is imported all over a flask api's endpoints. My first thought was to use a Singleton class in R so that we maintain one single connection to the redis cluster, but I'm not entirely I should putting a singleton class pattern into a code base that is only looked at once a year by different developers, I really don't want someone trying to instantiate it multiple times at a later stage. </p> <p>So, instead, in my module <strong>init</strong>.py I set up the connection to the cluster, and import this connection to my redis cluster module, then whereever I use R, the connection is always the same connection without having to use a singleton. </p> <p>e.g.:</p> <p><strong>_init</strong> _.py:</p> <pre><code> try: RedisConnection = ConnectionMaker(...) </code></pre> <p><strong>R</strong>.py:</p> <pre><code>from ...caching import RedisConnection ... def set_cache(): RedisConnection.set(....) </code></pre> <p>some_endpoint.py</p> <pre><code> from ....caching import set_cache, ... </code></pre> <p>some_other_endpoint.py</p> <pre><code> from ....caching import set_cache, ... </code></pre> <p>I think this is safe because '<a href="http://stackoverflow.com/questions/10936709/why-does-a-python-module-act-like-a-singleton">Since Python modules are first-class runtime objects, they effectively become singletons, initialized at the time of first import.</a>'. However, is there anything that I am missing, anything dangerous?</p>
0
2016-09-08T06:03:39Z
39,384,656
<p>It is safe but there are two things I don't think are good practices.</p> <ol> <li>Initializations or class definitions etc should not be there in init.py Init file is use to hide internal structure of the package. A simple <strong>init</strong>.py is a good <strong>init</strong>.py </li> <li>Creating objects in global space is not good. Disadvantage of is that mere importing your package will consume memory since it initializes an object. You should make actual connection inside a class or a function. Whenever you need a connection call this class or function to create a singleton connection.</li> </ol>
1
2016-09-08T07:13:04Z
[ "python", "singleton", "python-module" ]
Multiple python virtual env
39,383,776
<p>Suppose i have normal system python 2.7 packages in system locations</p> <p>Then i do</p> <pre><code>virtualenv env1 </code></pre> <p>I install all requirements there</p> <p>Then i deactivate that and do</p> <pre><code>export PYTHONPATH=$PYTHONPATH:/path/to/env1 </code></pre> <p>Then i do <code>virtualenv env2</code> and then install new requirements there</p> <p>then i do this again </p> <p><code>export PYTHONPATH=$PYTHONPATH:/path/to/env2</code></p> <p>So my questions is</p> <p>All the packagaes which are installed in env1 , will not be installed in env2 or env2 will install new packagaes.</p> <p>I ahve problem where if i <code>pip install packagae1</code> while env2 is activated. it says requirement already met</p> <p>Then i open python shell and do import mymodule. It says module not found. I can see that module was there in <code>env1</code>.</p> <p>I had to remove that module from env1 and then install on env2 and then it work.</p> <p>I want to know whay is that</p>
-1
2016-09-08T06:18:56Z
39,383,877
<p>Have you activated env2 before installing module ?</p> <blockquote> <p>source bin/activate</p> </blockquote> <p>If you want to uninstall any module from virtualenv, then use</p> <blockquote> <p>pip uninstall module_name</p> </blockquote>
1
2016-09-08T06:25:04Z
[ "python", "linux", "virtualenv" ]
Multiple python virtual env
39,383,776
<p>Suppose i have normal system python 2.7 packages in system locations</p> <p>Then i do</p> <pre><code>virtualenv env1 </code></pre> <p>I install all requirements there</p> <p>Then i deactivate that and do</p> <pre><code>export PYTHONPATH=$PYTHONPATH:/path/to/env1 </code></pre> <p>Then i do <code>virtualenv env2</code> and then install new requirements there</p> <p>then i do this again </p> <p><code>export PYTHONPATH=$PYTHONPATH:/path/to/env2</code></p> <p>So my questions is</p> <p>All the packagaes which are installed in env1 , will not be installed in env2 or env2 will install new packagaes.</p> <p>I ahve problem where if i <code>pip install packagae1</code> while env2 is activated. it says requirement already met</p> <p>Then i open python shell and do import mymodule. It says module not found. I can see that module was there in <code>env1</code>.</p> <p>I had to remove that module from env1 and then install on env2 and then it work.</p> <p>I want to know whay is that</p>
-1
2016-09-08T06:18:56Z
39,384,106
<p>Probably you have not activated the virtual environment (lets call it as <code>venv</code>) and installed the package system wide.</p> <p>I suggest you to try activating the venv first and then proceed with installations in either of the venv.</p> <p>You can activate venv using following code : </p> <pre><code> cd ~/venv/ source /bin/activate </code></pre>
0
2016-09-08T06:37:58Z
[ "python", "linux", "virtualenv" ]
Multiple python virtual env
39,383,776
<p>Suppose i have normal system python 2.7 packages in system locations</p> <p>Then i do</p> <pre><code>virtualenv env1 </code></pre> <p>I install all requirements there</p> <p>Then i deactivate that and do</p> <pre><code>export PYTHONPATH=$PYTHONPATH:/path/to/env1 </code></pre> <p>Then i do <code>virtualenv env2</code> and then install new requirements there</p> <p>then i do this again </p> <p><code>export PYTHONPATH=$PYTHONPATH:/path/to/env2</code></p> <p>So my questions is</p> <p>All the packagaes which are installed in env1 , will not be installed in env2 or env2 will install new packagaes.</p> <p>I ahve problem where if i <code>pip install packagae1</code> while env2 is activated. it says requirement already met</p> <p>Then i open python shell and do import mymodule. It says module not found. I can see that module was there in <code>env1</code>.</p> <p>I had to remove that module from env1 and then install on env2 and then it work.</p> <p>I want to know whay is that</p>
-1
2016-09-08T06:18:56Z
39,384,152
<p>Firstly, do not change PYTHONPATH manually. Steps should look something like this:</p> <pre><code>[root@demo src]$ source /usr/local/env1/bin/activate (env1)[root@demo src]$ # pip install blah (env1)[root@demo src]$ source /usr/local/env2/bin/activate (env2)[root@demo src]$ #pip install blah (env2)[root@demo src]$ </code></pre>
1
2016-09-08T06:40:11Z
[ "python", "linux", "virtualenv" ]
Python - speed up pathfinding
39,383,914
<p>This is my pathfinding function:</p> <pre><code>def get_distance(x1,y1,x2,y2): neighbors = [(-1,0),(1,0),(0,-1),(0,1)] old_nodes = [(square_pos[x1,y1],0)] new_nodes = [] for i in range(50): for node in old_nodes: if node[0].x == x2 and node[0].y == y2: return node[1] for neighbor in neighbors: try: square = square_pos[node[0].x+neighbor[0],node[0].y+neighbor[1]] if square.lightcycle == None: new_nodes.append((square,node[1])) except KeyError: pass old_nodes = [] old_nodes = list(new_nodes) new_nodes = [] nodes = [] return 50 </code></pre> <p>The problem is that the AI takes to long to respond( <em>response time &lt;= 100ms</em>) This is just a python way of doing <a href="https://en.wikipedia.org/wiki/Pathfinding#Sample_algorithm" rel="nofollow">https://en.wikipedia.org/wiki/Pathfinding#Sample_algorithm</a></p>
1
2016-09-08T06:27:17Z
39,384,012
<p>You should replace your algorithm with <a href="https://en.wikipedia.org/wiki/A*_search_algorithm" rel="nofollow">A*-search</a> with the Manhattan distance as a heuristic.</p>
3
2016-09-08T06:32:55Z
[ "python", "path-finding" ]
Python - speed up pathfinding
39,383,914
<p>This is my pathfinding function:</p> <pre><code>def get_distance(x1,y1,x2,y2): neighbors = [(-1,0),(1,0),(0,-1),(0,1)] old_nodes = [(square_pos[x1,y1],0)] new_nodes = [] for i in range(50): for node in old_nodes: if node[0].x == x2 and node[0].y == y2: return node[1] for neighbor in neighbors: try: square = square_pos[node[0].x+neighbor[0],node[0].y+neighbor[1]] if square.lightcycle == None: new_nodes.append((square,node[1])) except KeyError: pass old_nodes = [] old_nodes = list(new_nodes) new_nodes = [] nodes = [] return 50 </code></pre> <p>The problem is that the AI takes to long to respond( <em>response time &lt;= 100ms</em>) This is just a python way of doing <a href="https://en.wikipedia.org/wiki/Pathfinding#Sample_algorithm" rel="nofollow">https://en.wikipedia.org/wiki/Pathfinding#Sample_algorithm</a></p>
1
2016-09-08T06:27:17Z
39,385,685
<p>One reasonably fast solution is to implement the Dijkstra algorithm (that I have already implemented in <a href="http://stackoverflow.com/q/39244636/1679629">that question</a>):</p> <p>Build the original map. It's a masked array where the walker cannot walk on masked element:</p> <pre><code>%pylab inline map_size = (20,20) MAP = np.ma.masked_array(np.zeros(map_size), np.random.choice([0,1], size=map_size)) matshow(MAP) </code></pre> <p><a href="http://i.stack.imgur.com/o0BFs.png" rel="nofollow"><img src="http://i.stack.imgur.com/o0BFs.png" alt="MAP"></a></p> <p>Below is the Dijkstra algorithm:</p> <pre><code>def dijkstra(V): mask = V.mask visit_mask = mask.copy() # mask visited cells m = numpy.ones_like(V) * numpy.inf connectivity = [(i,j) for i in [-1, 0, 1] for j in [-1, 0, 1] if (not (i == j == 0))] cc = unravel_index(V.argmin(), m.shape) # current_cell m[cc] = 0 P = {} # dictionary of predecessors #while (~visit_mask).sum() &gt; 0: for _ in range(V.size): #print cc neighbors = [tuple(e) for e in asarray(cc) - connectivity if e[0] &gt; 0 and e[1] &gt; 0 and e[0] &lt; V.shape[0] and e[1] &lt; V.shape[1]] neighbors = [ e for e in neighbors if not visit_mask[e] ] tentative_distance = [(V[e]-V[cc])**2 for e in neighbors] for i,e in enumerate(neighbors): d = tentative_distance[i] + m[cc] if d &lt; m[e]: m[e] = d P[e] = cc visit_mask[cc] = True m_mask = ma.masked_array(m, visit_mask) cc = unravel_index(m_mask.argmin(), m.shape) return m, P def shortestPath(start, end, P): Path = [] step = end while 1: Path.append(step) if step == start: break if P.has_key(step): step = P[step] else: break Path.reverse() return asarray(Path) </code></pre> <p>And the result:</p> <pre><code>start = (2,8) stop = (17,19) D, P = dijkstra(MAP) path = shortestPath(start, stop, P) imshow(MAP, interpolation='nearest') plot(path[:,1], path[:,0], 'ro-', linewidth=2.5) </code></pre> <p><a href="http://i.stack.imgur.com/EWeXl.png" rel="nofollow"><img src="http://i.stack.imgur.com/EWeXl.png" alt="enter image description here"></a></p> <p>Below some timing statistics:</p> <pre><code>%timeit dijkstra(MAP) #10 loops, best of 3: 32.6 ms per loop </code></pre>
1
2016-09-08T08:06:35Z
[ "python", "path-finding" ]
Python - speed up pathfinding
39,383,914
<p>This is my pathfinding function:</p> <pre><code>def get_distance(x1,y1,x2,y2): neighbors = [(-1,0),(1,0),(0,-1),(0,1)] old_nodes = [(square_pos[x1,y1],0)] new_nodes = [] for i in range(50): for node in old_nodes: if node[0].x == x2 and node[0].y == y2: return node[1] for neighbor in neighbors: try: square = square_pos[node[0].x+neighbor[0],node[0].y+neighbor[1]] if square.lightcycle == None: new_nodes.append((square,node[1])) except KeyError: pass old_nodes = [] old_nodes = list(new_nodes) new_nodes = [] nodes = [] return 50 </code></pre> <p>The problem is that the AI takes to long to respond( <em>response time &lt;= 100ms</em>) This is just a python way of doing <a href="https://en.wikipedia.org/wiki/Pathfinding#Sample_algorithm" rel="nofollow">https://en.wikipedia.org/wiki/Pathfinding#Sample_algorithm</a></p>
1
2016-09-08T06:27:17Z
39,387,039
<p>The biggest issue with your code is that you don't do anything to avoid the same coordinates being visited multiple times. This means that the number of nodes you visit is <em>guaranteed</em> to grow exponentially, since it can keep going back and forth over the first few nodes many times.</p> <p>The best way to avoid duplication is to maintain a <code>set</code> of the coordinates we've added to the queue (though if your <code>node</code> values are hashable, you might be able to add them directly to the set instead of coordinate tuples). Since we're doing a breadth-first search, we'll always reach a given coordinate by (one of) the shortest path(s), so we never need to worry about finding a better route later on.</p> <p>Try something like this:</p> <pre><code>def get_distance(x1,y1,x2,y2): neighbors = [(-1,0),(1,0),(0,-1),(0,1)] nodes = [(square_pos[x1,y1],0)] seen = set([(x1, y1)]) for node, path_length in nodes: if path_length == 50: break if node.x == x2 and node.y == y2: return path_length for nx, ny in neighbors: try: square = square_pos[node.x + nx, node.y + ny] if square.lightcycle == None and (square.x, square.y) not in seen: nodes.append((square, path_length + 1)) seen.add((square.x, square.y)) except KeyError: pass return 50 </code></pre> <p>I've also simplified the loop a bit. Rather than switching out the list after each depth, you can just use one loop and add to its end as you're iterating over the earlier values. I still abort if a path hasn't been found with fewer than 50 steps (using the distance stored in the 2-tuple, rather than the number of passes of the outer loop). A further improvement might be to use a <code>collections.dequeue</code> for the queue, since you could efficiently <code>pop</code> from one end while <code>append</code>ing to the other end. It probably won't make a huge difference, but might avoid a little bit of memory usage.</p> <p>I also avoided most of the indexing by one and zero in favor of unpacking into separate variable names in the <code>for</code> loops. I think this is much easier to read, and it avoids confusion since the two different kinds of 2-tuples had had different meanings (one is a <code>node, distance</code> tuple, the other is <code>x, y</code>).</p>
0
2016-09-08T09:17:01Z
[ "python", "path-finding" ]
Django DRF: Default URL always gets trigered first instead of route.url
39,383,926
<p>I have a very simple Django Rest Framework application, my <code>urls.py</code> looks like the following</p> <pre><code>router = routers.DefaultRouter() router.register(r'activity-list', activities.views.ArticleViewSet) urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^api/', include(router.urls, namespace='api')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # Base/default URL, when all else fails urlpatterns += [ url(r'', TemplateView.as_view(template_name='index.html')), ] </code></pre> <p>When I run the url <code>http://127.0.0.1:8000/api/activity-list</code>, the route that comes from the DRF router never gets reached. The server always seems to give precedence to the default URL, and <code>index.html</code> is always rendered.</p> <p>However, if I change the Default URL to:</p> <pre><code># Base/default URL, when all else fails urlpatterns += [ url(r'BLABLABLA', TemplateView.as_view(template_name='index.html')), ] </code></pre> <p>Only then are the DRF routes reachable. This is what makes me think it's a precedence issue. The DRF routes are working, they just always get beaten by the default URL.</p> <p>I've tried variants suggested in the <a href="http://www.django-rest-framework.org/api-guide/routers/#using-include-with-routershttp://" rel="nofollow">DRF docs</a>, without luck, such as :</p> <p>Moreover, <code>/admin</code> works fine, which is why I suspect that it has to do with the DRF router in particular.</p> <p>But the same thing keeps happening. How can I make my DRF routes reachable while maintaining a default route for the server to land on?</p> <p><strong>Update:</strong> So I've found that adding a trailing slash to the api URL causes it to work. This has led me to these two (<a href="http://stackoverflow.com/questions/5948659/when-should-i-use-a-trailing-slash-in-my-url">1</a> and <a href="http://stackoverflow.com/questions/6545741/django-catch-all-url-without-breaking-append-slash">2</a>) questions.</p>
0
2016-09-08T06:27:56Z
39,384,007
<p>You will have to learn <code>url dispatcher</code> in django. Your default url's and DRF route's url's <code>pattern</code> is same, and default url is on top of the <code>urlpatterns</code> thus that url is getting triggered.</p> <p><a href="https://docs.djangoproject.com/en/1.10/topics/http/urls/#how-django-processes-a-request" rel="nofollow">How Django processes a request</a></p>
0
2016-09-08T06:32:37Z
[ "python", "django", "routes", "django-rest-framework" ]
Django DRF: Default URL always gets trigered first instead of route.url
39,383,926
<p>I have a very simple Django Rest Framework application, my <code>urls.py</code> looks like the following</p> <pre><code>router = routers.DefaultRouter() router.register(r'activity-list', activities.views.ArticleViewSet) urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^api/', include(router.urls, namespace='api')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # Base/default URL, when all else fails urlpatterns += [ url(r'', TemplateView.as_view(template_name='index.html')), ] </code></pre> <p>When I run the url <code>http://127.0.0.1:8000/api/activity-list</code>, the route that comes from the DRF router never gets reached. The server always seems to give precedence to the default URL, and <code>index.html</code> is always rendered.</p> <p>However, if I change the Default URL to:</p> <pre><code># Base/default URL, when all else fails urlpatterns += [ url(r'BLABLABLA', TemplateView.as_view(template_name='index.html')), ] </code></pre> <p>Only then are the DRF routes reachable. This is what makes me think it's a precedence issue. The DRF routes are working, they just always get beaten by the default URL.</p> <p>I've tried variants suggested in the <a href="http://www.django-rest-framework.org/api-guide/routers/#using-include-with-routershttp://" rel="nofollow">DRF docs</a>, without luck, such as :</p> <p>Moreover, <code>/admin</code> works fine, which is why I suspect that it has to do with the DRF router in particular.</p> <p>But the same thing keeps happening. How can I make my DRF routes reachable while maintaining a default route for the server to land on?</p> <p><strong>Update:</strong> So I've found that adding a trailing slash to the api URL causes it to work. This has led me to these two (<a href="http://stackoverflow.com/questions/5948659/when-should-i-use-a-trailing-slash-in-my-url">1</a> and <a href="http://stackoverflow.com/questions/6545741/django-catch-all-url-without-breaking-append-slash">2</a>) questions.</p>
0
2016-09-08T06:27:56Z
39,402,663
<p>Finally figured it out. According to the DRF docs:</p> <blockquote> <p>By default the URLs created by <code>SimpleRouter</code> are appended with a trailing slash. This behavior can be modified by setting the <code>trailing_slash</code> argument to <code>False</code> when instantiating the router. For example:</p> <p><code>router = SimpleRouter( trailing_slash = False )</code></p> </blockquote> <p>Having set this as the setting of the router and transformed my route to <code>r'activity-list'</code>, it now works with or without the trailing slash.</p>
1
2016-09-09T01:55:15Z
[ "python", "django", "routes", "django-rest-framework" ]
Bokeh - Link dataframe time series data to Select interaction
39,384,066
<p>I'm trying create a single line chart in Bokeh and linking different charts in one dataframe to a Select interaction. The dataframe structure looks something like this:</p> <p>Date, KPI1, KPI2, KPI3, KPI4 ... ...</p> <p>Date is always x axis, whereas KPI's should be changeable on the y axis.</p> <p>I can't get it to work. Please see my current code below. Explanations are shown as comments</p> <pre><code>from app import app from flask import render_template,request import pandas as pd import numpy as np from bokeh.embed import components from bokeh.plotting import figure from bokeh.resources import CDN from bokeh.embed import file_html from bokeh.plotting import figure, output_file, show from bokeh.io import output_file, show, vform from bokeh.charts import Scatter, output_file, show from bokeh.models import DatetimeTickFormatter from bokeh.models import CustomJS, ColumnDataSource, Select from app import data def createChartHTML(): #Import data from Excel file #Data Structure Looks as follows: Date, KPI 1, KPI 2, KPI 3, KPI 4 ... ... ... allData = pd.read_excel(open('Charts.xlsx', 'rb'), sheetname='DATA') #Get list of column names columnNameList = list(allData.columns.values) #Remove date column from column names columnNameList.pop(0) #Create line chart with markers with initial data p = figure(plot_width=800, plot_height=400,x_axis_type="datetime",title="KPI 1") p.left[0].formatter.use_scientific = False p.line(allData['Date'], allData["KPI 1"], line_width=2) p.circle(allData['Date'], allData["KPI 1"], fill_color="white", size=12) #Create callback source = ColumnDataSource(data=allData) #How do I link this code to the allData dataframe? #I need to pass a parameter from the selection box to this code to select the right data from the dataframe callback = CustomJS(args=dict(source=source), code=""" var data = source.get('data'); var f = cb_obj.get('value') x = data['LINK THIS TO NEWLY SELECTED DATA?????'] y = data['Date'] source.trigger('change'); """) select = Select(title="Option:", value=columnNameList[0], options=columnNameList,callback=callback) layout = vform(select,p) output_file('plot.html', title='Plot') html = file_html(layout, CDN, "my plot") return(html) </code></pre>
0
2016-09-08T06:36:03Z
39,385,405
<p>I found an answer to my question here:</p> <p><a href="https://groups.google.com/a/continuum.io/forum/#!topic/bokeh/2rCCRIyXtk8" rel="nofollow">https://groups.google.com/a/continuum.io/forum/#!topic/bokeh/2rCCRIyXtk8</a></p>
1
2016-09-08T07:51:59Z
[ "python", "pandas", "bokeh" ]
Replacing part of a string in a list in python
39,384,235
<p>For example i have list of a name written diffently </p> <pre><code>list1 = ["jai.kumar","jaikumar","j_kumar","jk","kumar-jai","ja.ku"] for str in l1: if str == “jai” str.replace (“jai”,”firstname”) if str == “ja” str.replace (“ja”,”first 2 character of firstname”) if str == “j” str.replace (“j”,”first character of firstname”) if str == “kumar” str.replace (“kumar”,”lastname”) if str == “ku” str.replace (“ku”,”first 2 character of lasttname”) if str == “k” str.replace (“k”,”first character of lastname”) print(list1) </code></pre> <p>How do i correct the above code or is there an easier way to do it?</p> <p>My expected output is</p> <pre><code> list1 = ["firstname.lastname","firstnamelastname","first character of firstname_lastname",.....] </code></pre>
-1
2016-09-08T06:44:51Z
39,385,061
<p>first of all, you're defining a list "list1" then operating on a list "l1" which is not defined, I'll assume this is a typo. Also you're indentation is fucked up and you're missing tons of colons after your ifs, I'll correct all that, if I shouldn't have and missed the purpose, please tell me.</p> <p>second, you're using == for comparing strings which will only be true for exact matches. What you're looking for is the "in" operator.</p> <p>thirdly, you're using string.replace("str1","str2") incorrectly, string.replace() returns a shallow copy of string where "str1" instances have been replaced by "str2", so what you'd want to do would be more like str = str.replace("1","2").</p> <p>Fourth, </p> <pre><code>for str in list1: </code></pre> <p>creates an str variable that is an alias of the list1 element, and reassigning str breaks the alias, meaning str = something will not modify list1.</p> <p>and lastly, you won't encounter "ja" if you already encountered "jai" I assume, for that reason using elifs is more efficient, rather than testing for "ja" and "j" after already having found "jai"</p> <p>All in all, your code would need to be something like this:</p> <pre><code>list1 = ["jai.kumar","jaikumar","j_kumar","jk","kumar-jai","ja.ku"] for i in range(len(list1)): if “jai” in list1[i]: list1[i] = list1[i].replace (“jai”,”firstname”) elif “ja” in list1[i]: list1[i] = list1[i].replace (“ja”,”first 2 character of firstname”) elif “j” in list1[i]: list1[i] = list1[i].replace (“j”,”first character of firstname”) if “kumar” in list1[i]: list1[i] = list1[i].replace (“kumar”,”lastname”) elif “ku” in list1[i]: str = str.replace (“ku”,”first 2 character of lasttname”) elif "k” in list1[i]: list1[i] = list1[i].replace (“k”,”first character of lastname”) print(list1) </code></pre> <p>Hope this answer your questions, let me know if anything is not clear.</p>
0
2016-09-08T07:33:53Z
[ "python" ]
Replacing part of a string in a list in python
39,384,235
<p>For example i have list of a name written diffently </p> <pre><code>list1 = ["jai.kumar","jaikumar","j_kumar","jk","kumar-jai","ja.ku"] for str in l1: if str == “jai” str.replace (“jai”,”firstname”) if str == “ja” str.replace (“ja”,”first 2 character of firstname”) if str == “j” str.replace (“j”,”first character of firstname”) if str == “kumar” str.replace (“kumar”,”lastname”) if str == “ku” str.replace (“ku”,”first 2 character of lasttname”) if str == “k” str.replace (“k”,”first character of lastname”) print(list1) </code></pre> <p>How do i correct the above code or is there an easier way to do it?</p> <p>My expected output is</p> <pre><code> list1 = ["firstname.lastname","firstnamelastname","first character of firstname_lastname",.....] </code></pre>
-1
2016-09-08T06:44:51Z
39,385,364
<p>I assume you meant sth like this?:</p> <pre><code>if str == “jai”: str.replace (“jai”,”firstname”) if str == “ja”: str.replace (“ja”,”first 2 character of firstname”) if str == “j”: str.replace (“j”,”first character of firstname”) </code></pre> <p>If yes(remeber of semicolon at the end of 'if') then this code won't work as you wish because second and third if is nestled inside previous IFs. So if first condition -> str=="jai" fails then you don't check the next ones. It should be:</p> <pre><code>if str == “jai”: str.replace (“jai”,”firstname”) elif str == “ja”: str.replace (“ja”,”first 2 character of firstname”) elif str == “j”: str.replace (“j”,”first character of firstname”) </code></pre>
0
2016-09-08T07:49:38Z
[ "python" ]
Xlsx Writer: Writing stings with multiple format in a single cell
39,384,236
<p>I have a string with multiple semicolons.</p> <pre><code>'firstline: abc \n secondline: bcd \n thirdline: efg' </code></pre> <p>I want to write this strings in excel cell using Xlsx Writer like below.</p> <p><b>firstline</b>: abc <br> <b>secondline</b>: bcd <br> <b>thirdline</b>: efg <br></p> <p>This is what I did.</p> <pre><code>description_combined = ''' firstline: abc secondline: bcd thirdline: efg ''' spanInserted = [] spanInserted = description_combined.split("\n") result = '' for spans in spanInserted: strr1 = '{}:'.format(spans.split(":")[0]) strr2 = spans.split(":")[1] result += '''bold , "{}" , "{}" ,'''.format(str(strr1),str(strr2)) result = result[:-1] # print result worksheet.write_rich_string('A1', result) </code></pre> <p><br> This is the result I got in excel cell:</p> <blockquote> <p>bold , "firstline:" , "abc" ,bold , "secondline:" , "bcd" ,bold , "thirdline:" , "efg"</p> </blockquote>
2
2016-09-08T06:44:53Z
39,385,849
<p>The jmcnamara's solution works well. I posted a similar possible solution, but dynamic. </p> <pre><code>import xlsxwriter workbook = xlsxwriter.Workbook("&lt;your path&gt;") worksheet = workbook.add_worksheet() # add style for first column cell_format = workbook.add_format({'bold': True}) text_wrap = workbook.add_format({'text_wrap': True, 'valign': 'top'}) data = [] description_combined = 'firstline: abc \n secondline: bcd \n thirdline: efg' # prepare list of list for item in description_combined.split("\n"): data.append(cell_format) data.append(item.split(":")[0].strip() + ":") data.append(item.split(":")[1] + "\n") # write data in one single cell data.append(text_wrap) worksheet.write_rich_string('A1', *data) workbook.close() </code></pre> <p>I hope that will be helpful</p>
2
2016-09-08T08:15:43Z
[ "python", "excel", "python-2.7", "xlsx", "xlsxwriter" ]
Xlsx Writer: Writing stings with multiple format in a single cell
39,384,236
<p>I have a string with multiple semicolons.</p> <pre><code>'firstline: abc \n secondline: bcd \n thirdline: efg' </code></pre> <p>I want to write this strings in excel cell using Xlsx Writer like below.</p> <p><b>firstline</b>: abc <br> <b>secondline</b>: bcd <br> <b>thirdline</b>: efg <br></p> <p>This is what I did.</p> <pre><code>description_combined = ''' firstline: abc secondline: bcd thirdline: efg ''' spanInserted = [] spanInserted = description_combined.split("\n") result = '' for spans in spanInserted: strr1 = '{}:'.format(spans.split(":")[0]) strr2 = spans.split(":")[1] result += '''bold , "{}" , "{}" ,'''.format(str(strr1),str(strr2)) result = result[:-1] # print result worksheet.write_rich_string('A1', result) </code></pre> <p><br> This is the result I got in excel cell:</p> <blockquote> <p>bold , "firstline:" , "abc" ,bold , "secondline:" , "bcd" ,bold , "thirdline:" , "efg"</p> </blockquote>
2
2016-09-08T06:44:53Z
39,389,532
<p>The <a href="http://xlsxwriter.readthedocs.io/worksheet.html#worksheet-write-rich-string" rel="nofollow"><code>write_string()</code></a> method takes a list as an argument but you are passing a string.</p> <p>You should use something like this to pass your list of strings and formats:</p> <pre><code>result = [bold, 'firstline: ', 'abc', bold, 'secondline: ', 'bcd', bold, 'thirdline: ', 'efg'] worksheet.write_rich_string('A1', *result) </code></pre> <p>However, if you also want the text to be wrapped you will need to add a <code>text_wrap</code> cell format at the end of the list and add newlines for where you want the wrap to occur. Something like this:</p> <pre><code>import xlsxwriter workbook = xlsxwriter.Workbook('rich_strings.xlsx') worksheet = workbook.add_worksheet() worksheet.set_column('A:A', 20) worksheet.set_row(0, 60) bold = workbook.add_format({'bold': True}) text_wrap = workbook.add_format({'text_wrap': True, 'valign': 'top'}) result = [bold, 'firstline: ', 'abc\n', bold, 'secondline: ', 'bcd\n', bold, 'thirdline: ', 'efg'] result.append(text_wrap) worksheet.write_rich_string('A1', *result) workbook.close() </code></pre> <p>Output:</p> <p><a href="http://i.stack.imgur.com/tEBXb.png" rel="nofollow"><img src="http://i.stack.imgur.com/tEBXb.png" alt="enter image description here"></a></p>
2
2016-09-08T11:18:07Z
[ "python", "excel", "python-2.7", "xlsx", "xlsxwriter" ]
Copy all files from one FTP directory to another
39,384,246
<p>I have to copy all existing files inside one ftp directory to another ftp directory on another server. I have not had any experience writing scripts - so any help with this would be great.</p> <p>I'm wondering if its possible to write this script so that it happens every day at a specific time?</p> <p>What software/ language should I use for this? Python is a well renowned one, but I want to make sure it suits my requirements.</p> <p>Can someone give me a basic code implementation for how to do it?</p> <p>Thanks in advance</p>
1
2016-09-08T06:45:28Z
39,384,635
<p>In the end you will probably end up downloading the whole directory to a local machine and re-uploading it to the other, as there's generally no way to copy files between directories in FTP.<br> See <a href="http://stackoverflow.com/q/3808799/850848">FTP copy a file to another place in same FTP</a>.</p> <p>You will find plenty of examples for downloading and uploading. You do not even need a scripting language. Simply use some command-line FTP client.</p> <p>For example with <a href="https://winscp.net/" rel="nofollow">WinSCP FTP client</a>, you can use the following batch file (<code>.bat</code>):</p> <pre class="lang-none prettyprint-override"><code>winscp.com /log=copy.log /command ^ "open ftp://username:password@ftp.example.com/" ^ "get /source/remote/path/* C:\temporary\local\path\" ^ "put C:\temporary\local\path\* /destination/remote/path/" ^ "exit" </code></pre> <p>See the guide to <a href="https://winscp.net/eng/docs/guide_automation" rel="nofollow">Automating file transfers to and from FTP server</a>.</p> <p><em>(I'm the author of WinSCP)</em></p>
0
2016-09-08T07:11:44Z
[ "python", "shell", "ftp" ]
It is possible for Django to upload file without FORMS?
39,384,417
<p>Im currently working with a custom html template not using forms on my django app to upload an img in a specific path.</p> <p><strong>app structure</strong></p> <pre><code>src/ media/ app/ img/ app_name/ templates/ app_name/ app_template.html __init__.py admin.py apps.py models.py tests.py urls.py views.py proj_name/ __init__.py settings.py urls.py wsgi.py manage.py </code></pre> <p><strong>settings.py</strong></p> <pre><code>MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' </code></pre> <p><strong>models.py</strong></p> <pre><code>class Document(models.Model): doc_file = models.FileField(upload_to='app/img') </code></pre> <p><strong>views.py</strong></p> <pre><code>def app_save(request): if request.method == 'POST': newdoc = Document(doc_file=request.FILES.get('myfile')) newdoc.save() </code></pre> <p><strong>app_template.html</strong></p> <pre><code>&lt;form id="myform" method="POST" action="{% url 'my_app:save' %}" enctype="multipart/form-data"&gt; &lt;input type="file" name="myfile"&gt; &lt;input type="submit"&gt; &lt;/form&gt; </code></pre> <h1>Result</h1> <p>After submitting the form i dont have any internal server error and no python traceback. But there was no image uploaded in the <code>app/img</code> path and in my database i have blank record inserted because of <code>newdoc.save()</code> query.</p> <p><strong>It is possible to work with file managing without forms?</strong></p> <hr> <h1>UPDATE</h1> <p>i added this on <code>forms.py</code></p> <pre><code>class UploadFileForm(forms.Form): file = forms.FileField() </code></pre> <p>and updated my <strong>app_template.html</strong> to:</p> <pre><code>&lt;form id="myform" method="POST" action="{% url 'my_app:save' %}" enctype="multipart/form-data"&gt; {{ form.file }} &lt;input type="submit"&gt; &lt;/form&gt; </code></pre> <p>then i would like to include the function of loading the <strong>app_template.html</strong> in <code>views.py</code>:</p> <pre><code>def index(request): form = UploadFileForm() return render(request, 'app_name/app_template.html', { 'form': form }) </code></pre> <p>And also updated the <code>app_save()</code> function to:</p> <pre><code> def app_save(request): form = UploadFileForm(request.POST, request.FILES) if request.method == 'POST': if form.is_valid(): newdoc = Document(doc_file=request.FILES.get('file')) # note 'file' is the name of input file of a form. newdoc.save() </code></pre> <p><strong>The problem now is</strong> </p> <p>There is no error found in the application but there is no <code>media/app/img</code> path create with the uploaded image file. Want went wrong? I think i missed something here.</p>
0
2016-09-08T06:57:44Z
39,385,452
<p>Your backend code is fine. The problem is with a frontend. You can't submit file input with jQuery.ajax like other fields. Use <a href="https://developer.mozilla.org/en/docs/Web/API/FormData" rel="nofollow">FormData</a>:</p> <pre><code>$('#myform').submit(function(event) { if(window.FormData !== undefined) { event.preventDefault(); var formData = new FormData(this); var xhr = new XMLHttpRequest(); xhr.open('POST', $(this).attr('action'), true); xhr.setRequestHeader('X-REQUESTED-WITH', 'XMLHttpRequest') xhr.onreadystatechange = function() { if(xhr.readyState == 4) { if(xhr.status == 200) { result = JSON.parse(xhr.responseText); // Code for success upload } else { // Code for error } } }; xhr.send(formData); } }); </code></pre>
1
2016-09-08T07:54:17Z
[ "python", "django", "file", "django-models" ]
It is possible for Django to upload file without FORMS?
39,384,417
<p>Im currently working with a custom html template not using forms on my django app to upload an img in a specific path.</p> <p><strong>app structure</strong></p> <pre><code>src/ media/ app/ img/ app_name/ templates/ app_name/ app_template.html __init__.py admin.py apps.py models.py tests.py urls.py views.py proj_name/ __init__.py settings.py urls.py wsgi.py manage.py </code></pre> <p><strong>settings.py</strong></p> <pre><code>MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' </code></pre> <p><strong>models.py</strong></p> <pre><code>class Document(models.Model): doc_file = models.FileField(upload_to='app/img') </code></pre> <p><strong>views.py</strong></p> <pre><code>def app_save(request): if request.method == 'POST': newdoc = Document(doc_file=request.FILES.get('myfile')) newdoc.save() </code></pre> <p><strong>app_template.html</strong></p> <pre><code>&lt;form id="myform" method="POST" action="{% url 'my_app:save' %}" enctype="multipart/form-data"&gt; &lt;input type="file" name="myfile"&gt; &lt;input type="submit"&gt; &lt;/form&gt; </code></pre> <h1>Result</h1> <p>After submitting the form i dont have any internal server error and no python traceback. But there was no image uploaded in the <code>app/img</code> path and in my database i have blank record inserted because of <code>newdoc.save()</code> query.</p> <p><strong>It is possible to work with file managing without forms?</strong></p> <hr> <h1>UPDATE</h1> <p>i added this on <code>forms.py</code></p> <pre><code>class UploadFileForm(forms.Form): file = forms.FileField() </code></pre> <p>and updated my <strong>app_template.html</strong> to:</p> <pre><code>&lt;form id="myform" method="POST" action="{% url 'my_app:save' %}" enctype="multipart/form-data"&gt; {{ form.file }} &lt;input type="submit"&gt; &lt;/form&gt; </code></pre> <p>then i would like to include the function of loading the <strong>app_template.html</strong> in <code>views.py</code>:</p> <pre><code>def index(request): form = UploadFileForm() return render(request, 'app_name/app_template.html', { 'form': form }) </code></pre> <p>And also updated the <code>app_save()</code> function to:</p> <pre><code> def app_save(request): form = UploadFileForm(request.POST, request.FILES) if request.method == 'POST': if form.is_valid(): newdoc = Document(doc_file=request.FILES.get('file')) # note 'file' is the name of input file of a form. newdoc.save() </code></pre> <p><strong>The problem now is</strong> </p> <p>There is no error found in the application but there is no <code>media/app/img</code> path create with the uploaded image file. Want went wrong? I think i missed something here.</p>
0
2016-09-08T06:57:44Z
39,385,793
<p>I don't understand why you don't want to use a modelform; it'll make things a lot easier.</p> <p>However, if you really do want to do it without one, you'll need to take care of the actual uploading yourself. The <a href="https://docs.djangoproject.com/en/1.10/topics/http/file-uploads/#basic-file-uploads" rel="nofollow">documentation</a> has a good example of what you'll need to do; basically you just take the file from <code>request.FILES</code> and save it to the location you want.</p>
1
2016-09-08T08:12:49Z
[ "python", "django", "file", "django-models" ]
How to read data in chunks in Python dataframe?
39,384,539
<p>I want to read the file f in chunks to a dataframe. Here is part of a code that I used.</p> <pre><code>for i in range(0, maxline, chunksize): df = pandas.read_csv(f,sep=',', nrows=chunksize, skiprows=i) df.to_sql(member, engine, if_exists='append',index= False, index_label=None, chunksize=chunksize) </code></pre> <p>I get the error:</p> <blockquote> <p>pandas.io.common.EmptyDataError: No columns to parse from file</p> </blockquote> <p>The code works only when the chunksize >= maxline (which is total lines in file f). However, in my case, the chunksize&lt;=maxline.</p> <p>Please advise the fix.</p>
1
2016-09-08T07:06:10Z
39,384,706
<p>I think it is better to use the parameter <code>chunksize</code> in <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow"><code>read_csv</code></a>. Also, use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow"><code>concat</code></a> with the parameter <code>ignore_index</code>, because of the need to avoid duplicates in <code>index</code>:</p> <pre><code>chunksize = 5 TextFileReader = pd.read_csv(f, chunksize=chunksize) df = pd.concat(TextFileReader, ignore_index=True) </code></pre> <p>See pandas <a href="http://pandas.pydata.org/pandas-docs/stable/io.html#iterating-through-files-chunk-by-chunk" rel="nofollow">docs</a>.</p>
2
2016-09-08T07:15:36Z
[ "python", "csv", "pandas", "dataframe", "chunks" ]
Can't set an arbitrary attribute in an instance of an object
39,384,634
<p>I'm using the pygame library, it has an object pygame.Surface() that has a bunch of methods. This is what I'm trying to do:</p> <pre><code>my_surface = pygame.Surface((5,5)) #the object requires a size to instantiate my_surface.coords = (10,10) </code></pre> <p>But it throws me this error:</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: 'pygame.Surface' object has no attribute 'coords' </code></pre> <p>same things happen if I use</p> <pre><code>setattr(my_surface, 'coords', (10,10)) </code></pre> <p>instead of </p> <pre><code>my_surface.coords = (10,10) </code></pre> <p>BUT if I make my own class</p> <pre><code>class MyClass(): pass instance = MyClass() instance.coords = (10,10) </code></pre> <p>it works like a charm.</p> <p>I've read that it has something to do with not having a __dict__ on every instance of an object (though it was about the default python object()) which would cause objects to use too much memory, and indeed when I do</p> <pre><code>my_surface.__dict__ #this is a pygame.Surface() object </code></pre> <p>it throws </p> <pre><code>AttributeError: 'pygame.Surface' object has no attribute '__dict__' </code></pre> <p>while</p> <pre><code>instance.__dict__ #this is a MyClass() object </code></pre> <p>returns</p> <pre><code>{} </code></pre> <p>Is there any way I can modify this particular instance to accept arbitrary attributes? Currently the only workaround I can think of is to create a child class for pygame.Surface() and give it a __dict__, but obviously it's rather confusing to have to choose in advance whether or not I'll need to add arbitrary attributes for every instance of a Surface(), and and instantiating every Surface with a __dict__ defeats the whole purpose of it having no __dict__ in the first place.</p>
0
2016-09-08T07:11:42Z
39,385,787
<p>I don't think there's a better way than subclassing <code>Surface</code> if you <em>really</em> need to be able to assign arbitrary attributes to an instance. The subclass can be empty if you don't need to add any other features (the instance <code>__dict__</code> will be created automatically).</p> <pre><code>class MySurface(pygame.Surface): pass </code></pre> <p>However, I'm not sure you really need that ability.</p> <p>A better design is generally to encapsulate the <code>Surface</code> object and whatever other data you have as attributes of some other object type. In Pygame you'll often use a subclass of <code>pygame.sprite.Sprite</code> to bundle a <code>Surface</code> (as the <code>image</code> attribute) with coordinates (as part of the <code>rect</code> attribute). If you have any other data you need to bundle, the <code>Sprite</code> can take it too. <code>Sprite</code> instances have a <code>__dict__</code> by default, even if you don't write your own subclass.</p>
1
2016-09-08T08:12:32Z
[ "python", "python-3.x" ]
groupby pandas : incompatible index of inserted column with frame index
39,384,749
<p>I have performed a groupby on pandas and I want to apply a complex function which needs several inputs and gives as output a pandas Series that I want to burn in my original dataframe. this is a known procedure to me and has worked very well - that is excpet in this last case (of which I forward my apologies for not being able to post the code in its entirety). essentially I get a <code>TypeError: incompatible index of inserted column with frame index</code>. but, as shown below, I shouldn't get one.</p> <p><code>group_by</code> part:</p> <pre><code>all_in_data_risk['weights_of_the_sac'] = all_in_data_risk.groupby(['ptf', 'ac'])['sac', 'unweighted_weights_by_sac', 'instrument_id', 'risk_budgets_sac'].apply(lambda x: wrapper_new_risk_budget(x, temp_fund_all_ret, method_compute_cov)) </code></pre> <p>where the function is:</p> <pre><code>def wrapper_new_risk_budget: print(x.index) ... print(result.index) return result.loc[:, 'res'] </code></pre> <p>which raised this error:</p> <pre><code> raise TypeError('incompatible index of inserted column ' TypeError: incompatible index of inserted column with frame index </code></pre> <p>the problem is this:</p> <pre><code>print(np.array_equal(result.index, x.index)) </code></pre> <p>yields all <code>True</code>. this should be a guarantee of index matching and therefore the problem should not simply be there.</p> <p>now, I understand the information I am providing is scarce to say the least but do you happen to have any insight on where the problem lies?</p> <p>p.s.: I have already tried transforming the result in a dataframe and tried to recast the output as <code>pd.Series(result.loc[:, 'res'].values, index=result.index)</code></p>
0
2016-09-08T07:17:25Z
39,385,558
<p>ok, for reasons beyond my understanding, when I performed a merge inside the code, although their numpy representation was equivalent, they differed for something else before pandas' eyes. I tried a work-around of the merge (longer and more inefficient) and now with more traditional means it works.</p> <p>today I won't be able to post the complete example since I am very pressed for time and I have a deadline looming over but I will complete it as soon as possible both to show respect to those who have answered or tried to do so and to all the other users who might find something beneficial in the resolution of this problem</p>
0
2016-09-08T07:59:12Z
[ "python", "pandas", "indexing", "group-by" ]
Unable to extract unique words from a CSV
39,384,762
<p>I have a <code>csv</code> which looks like below:</p> <pre><code> Description 0 ['boy'] 1 ['boy', 'jumped', 'roof'] 2 ['paris'] 3 ['paris', 'beautiful', 'new', 'york'] 4 ['lets', 'go', 'party'] 5 ['refused', 'come', 'party'] </code></pre> <p>I need to find out unique words from this data. So output would be:</p> <pre><code> Unique Words 0 boy 1 jumped 2 roof 3 paris 4 beautiful 5 new 6 york </code></pre> <p>as so on. I am trying to do this using Pandas and Python and unable to achieve it. My code is:</p> <pre><code>df = pd.read_csv('output.csv') list(set(df.Description)) g = list(df['Description'].unique()) print(g) </code></pre> <p>This throws wrong output, it just throws the original csv dataframe.</p>
1
2016-09-08T07:18:07Z
39,384,964
<p>You can first need convert <code>string</code> column to <code>list</code>, I use <code>ast.literal_eval</code>. Then make flat list of lists by list comprehension, use <code>set</code> and last create new <code>DataFrame</code> by constructor:</p> <pre><code>import ast print (type(df.ix[0, 'Description'])) &lt;class 'str'&gt; df.Description = df.Description.apply(ast.literal_eval) print (type(df.ix[0, 'Description'])) &lt;class 'list'&gt; #http://stackoverflow.com/q/952914/2901002 unique_data = list(set([item for sublist in df.Description.tolist() for item in sublist])) print (unique_data) ['refused', 'jumped', 'go', 'roof', 'come', 'beautiful', 'paris', 'york', 'lets', 'new', 'boy', 'party'] print (pd.DataFrame({'Unique Words': unique_data})) Unique Words 0 refused 1 jumped 2 go 3 roof 4 come 5 beautiful 6 paris 7 york 8 lets 9 new 10 boy 11 party </code></pre> <p>Another solution without <code>ast</code>:</p> <pre><code>df.Description = df.Description.str.strip('[]').str.split(',') print (df) Description 0 ['boy'] 1 ['boy', 'jumped', 'roof'] 2 ['paris'] 3 ['paris', 'beautiful', 'new', 'york'] 4 ['lets', 'go', 'party'] 5 ['refused', 'come', 'party'] unique_data = list(set([item.strip().strip("'") for sublist in df.Description.tolist() for item in sublist])) print (unique_data) ['refused', 'jumped', 'go', 'roof', 'come', 'beautiful', 'paris', 'york', 'lets', 'new', 'boy', 'party'] print (pd.DataFrame({'Unique Words': unique_data})) Unique Words 0 refused 1 jumped 2 go 3 roof 4 come 5 beautiful 6 paris 7 york 8 lets 9 new 10 boy 11 party </code></pre>
3
2016-09-08T07:28:07Z
[ "python", "list", "csv", "pandas", "unique" ]
Unable to extract unique words from a CSV
39,384,762
<p>I have a <code>csv</code> which looks like below:</p> <pre><code> Description 0 ['boy'] 1 ['boy', 'jumped', 'roof'] 2 ['paris'] 3 ['paris', 'beautiful', 'new', 'york'] 4 ['lets', 'go', 'party'] 5 ['refused', 'come', 'party'] </code></pre> <p>I need to find out unique words from this data. So output would be:</p> <pre><code> Unique Words 0 boy 1 jumped 2 roof 3 paris 4 beautiful 5 new 6 york </code></pre> <p>as so on. I am trying to do this using Pandas and Python and unable to achieve it. My code is:</p> <pre><code>df = pd.read_csv('output.csv') list(set(df.Description)) g = list(df['Description'].unique()) print(g) </code></pre> <p>This throws wrong output, it just throws the original csv dataframe.</p>
1
2016-09-08T07:18:07Z
39,385,257
<p>This approach works:</p> <pre><code>import pandas as pd import ast test = {'Description':["['boy']","['boy', 'jumped', 'roof']","['paris']",\ "['paris', 'beautiful', 'new', 'york']","['lets', 'go', 'party']",\ "['refused', 'come', 'party']"]} tt = pd.DataFrame(test) listOfWords = [] for i,row in tt.iterrows(): listOfWords.extend(ast.literal_eval(tt.ix[i,'Description'])) uniqueWords = pd.DataFrame(listOfWords,columns=['Unique Words']).drop_duplicates() </code></pre> <p>If you want it sorted:</p> <pre><code>uniqueWords = uniqueWords.sort_values('Unique Words') </code></pre> <p>You iterate over all rows, convert your strings to lists and gather all those lists into one long list with <code>extend</code>. Then just make a new DataFrame from that list and drop the duplicates.</p> <p>EDIT: Thanks to jezrael for correcting my solution, I borrowed the <code>ast.literal_eval</code> approach from his solution.</p> <p>I tried to compare our solutions using the <code>%timeit</code> command but got <code>ValueError: malformed string</code> on <code>ast.literal_eval</code> in both solutions.</p> <p>EDIT2: jezrael's solution is twice as fast for the small data example we have here.</p> <p>EDIT3: I can't test with a large data example (multiply the given one by some number) because <code>timeit</code> keeps throwing <code>malformed string</code> errors for reasons unclear to me.</p> <p>EDIT4: Made it work somehow. For a larger dataset (6000 rows) jezrael's solution is over 8 times faster. Guess even iterating with <code>iterrows</code> is rather slow compared to list comprehensions. Also I tested jezrael's second solution without <code>ast</code>. It's more than twice as fast as his first solution.</p>
1
2016-09-08T07:43:51Z
[ "python", "list", "csv", "pandas", "unique" ]
Is it OK to replace a method by a plain function?
39,384,922
<p>This works as expected, but I am somehow unsure about this approach. Is it safe? Is it pythonic?</p> <pre><code>class Example: def __init__(self, parameter): if parameter == 0: # trivial case, the result is always zero self.calc = lambda x: 0.0 # &lt;== replacing a method self._parameter = parameter def calc(self, x): # ... long calculation of result ... return result </code></pre> <p>(If there is any difference between Python2 and Python3, I'm using Python3 only.)</p>
1
2016-09-08T07:26:19Z
39,384,999
<p>You'll have a problem should <code>parameter</code> ever changes, so I don't consider it good practice. Instead, I think you should do this:</p> <pre><code>class Example: def __init__(self, parameter): self._parameter = parameter def calc(self, x): if not self._parameter: return 0.0 # ... long calculation of result ... return result </code></pre>
3
2016-09-08T07:30:17Z
[ "python" ]
Is it OK to replace a method by a plain function?
39,384,922
<p>This works as expected, but I am somehow unsure about this approach. Is it safe? Is it pythonic?</p> <pre><code>class Example: def __init__(self, parameter): if parameter == 0: # trivial case, the result is always zero self.calc = lambda x: 0.0 # &lt;== replacing a method self._parameter = parameter def calc(self, x): # ... long calculation of result ... return result </code></pre> <p>(If there is any difference between Python2 and Python3, I'm using Python3 only.)</p>
1
2016-09-08T07:26:19Z
39,385,018
<p>This is very confusing. If someone else reads it, they won't understand what is going on. Just put a <code>if</code> statement at the beginning of your method.</p> <pre><code>def calc(self, x): if self.parameter == 0: return 0 # ... long calculation of result ... return result </code></pre> <p>Also if you change <code>self.parameter</code> after it was initialized with <code>0</code>, your function wouldn't work anymore.</p>
4
2016-09-08T07:31:47Z
[ "python" ]
Is it OK to replace a method by a plain function?
39,384,922
<p>This works as expected, but I am somehow unsure about this approach. Is it safe? Is it pythonic?</p> <pre><code>class Example: def __init__(self, parameter): if parameter == 0: # trivial case, the result is always zero self.calc = lambda x: 0.0 # &lt;== replacing a method self._parameter = parameter def calc(self, x): # ... long calculation of result ... return result </code></pre> <p>(If there is any difference between Python2 and Python3, I'm using Python3 only.)</p>
1
2016-09-08T07:26:19Z
39,385,875
<p><em>I decided to post a summary of several comments and answers. Please do not vote for this summary, but give +1 to the original authors instead</em>.</p> <ul> <li>the approach is safe except for special <code>__methods__</code></li> <li>the approach is deemed unpythonic, undesirable, or unnecessary etc.</li> <li>the parameter determining the function to use must be constant. If it is not the case, this approach makes no sense at all.</li> <li>from several suggestions I prefer the code below for general cases and the obvious <code>if cond: return 0.0</code> for simple cases:</li> </ul> <hr> <pre><code> class Example: def __init__(self, parameter): if parameter == 0: self.calc = self._calc_trivial else: # ... pre-compute data if necessary ... self.calc = self._calc_regular self._parameter = parameter def _calc_regular(self, x): # ... long calculation of result ... return result @staticmethod def _calc_trivial(x): return 0.0 </code></pre>
0
2016-09-08T08:16:48Z
[ "python" ]
Change dtype data_type fields of numpy array
39,384,998
<p>I have a <code>.mat</code> file which I load using <code>scipy</code>:</p> <pre><code>from oct2py import octave import scipy.io as spio matPath = "path/to/file.mat" matFile = spio.loadmat(matPath) </code></pre> <p>I get a numpy array which I want to pass to octave function using <code>oct2py</code>, like that:</p> <pre><code>aMatStruct = matFile["aMatStruct"] result = octave.aMatFunction(aMatStruct) </code></pre> <p>But I get the following error:</p> <pre><code>oct2py.utils.Oct2PyError: Datatype not supported </code></pre> <p>It seems it's due to the array <code>dtype</code>, which looks like: <code>[('x', 'O'), ('y', 'O'), ('z', 'O')]</code></p> <p>So I thought about changing it to <code>'S'</code>, <code>'U'</code>, or something that's supported.</p> <ol> <li>How can it be done?</li> <li>I couldn't find a supported dtype in the <a href="https://blink1073.github.io/oct2py/source/examples.html" rel="nofollow">otc2py documentation</a>. Any help on that?</li> <li>Is there a way to load the <code>.mat</code> file with another (supported) dtype? I looked <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.io.loadmat.html#scipy.io.loadmat" rel="nofollow">here</a> but couldn't find anything useful.</li> </ol> <p>Note that inside <code>aMatFunction</code> it uses <code>aMatStruct</code> like that: <code>x = aMatStruct.x</code>.</p>
0
2016-09-08T07:30:12Z
39,386,846
<p>Found a workaround!</p> <p>I used the <a href="http://stackoverflow.com/questions/7008608/scipy-io-loadmat-nested-structures-i-e-dictionaries">following script</a>, which reconstructs python dictionaries from the loaded struct, which <code>oct2py2</code> in turn interpret as matlab structs.</p>
0
2016-09-08T09:06:20Z
[ "python", "numpy", "scipy", "octave" ]
Change dtype data_type fields of numpy array
39,384,998
<p>I have a <code>.mat</code> file which I load using <code>scipy</code>:</p> <pre><code>from oct2py import octave import scipy.io as spio matPath = "path/to/file.mat" matFile = spio.loadmat(matPath) </code></pre> <p>I get a numpy array which I want to pass to octave function using <code>oct2py</code>, like that:</p> <pre><code>aMatStruct = matFile["aMatStruct"] result = octave.aMatFunction(aMatStruct) </code></pre> <p>But I get the following error:</p> <pre><code>oct2py.utils.Oct2PyError: Datatype not supported </code></pre> <p>It seems it's due to the array <code>dtype</code>, which looks like: <code>[('x', 'O'), ('y', 'O'), ('z', 'O')]</code></p> <p>So I thought about changing it to <code>'S'</code>, <code>'U'</code>, or something that's supported.</p> <ol> <li>How can it be done?</li> <li>I couldn't find a supported dtype in the <a href="https://blink1073.github.io/oct2py/source/examples.html" rel="nofollow">otc2py documentation</a>. Any help on that?</li> <li>Is there a way to load the <code>.mat</code> file with another (supported) dtype? I looked <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.io.loadmat.html#scipy.io.loadmat" rel="nofollow">here</a> but couldn't find anything useful.</li> </ol> <p>Note that inside <code>aMatFunction</code> it uses <code>aMatStruct</code> like that: <code>x = aMatStruct.x</code>.</p>
0
2016-09-08T07:30:12Z
39,387,123
<p>I was going to suggest converting the resulting array to a valid dictionary but you beat me to it so I won't code it :p</p> <p>However, the other, simpler solution I was going to suggest is that, since you're only using the struct within octave, you <em>could</em> just load it into its workspace and evaluate directly. i.e. the following works for me:</p> <pre><code>&gt;&gt;&gt; octave.load("MyFile.mat") &gt;&gt;&gt; octave.eval("fieldnames(S)") ans = { [1,1] = name [2,1] = age } [u'name', u'age'] </code></pre> <p><strong>EDIT</strong> eh screw it, here's the python solution; I'd started it anyway :p</p> <pre><code>&gt;&gt;&gt; from oct2py import octave &gt;&gt;&gt; from scipy.io import loadmat &gt;&gt;&gt; F = loadmat("/home/tasos/Desktop/MyFile.mat") &gt;&gt;&gt; M = F["S"] # the name of the struct variable I saved in the mat file &gt;&gt;&gt; M = M[0][0] &gt;&gt;&gt; D = {M.dtype.names[i]:M[i][0] for i in range(len(M))} &gt;&gt;&gt; out = octave.fieldnames(D); out [u'age', u'name'] </code></pre>
0
2016-09-08T09:21:16Z
[ "python", "numpy", "scipy", "octave" ]
How remove duplicates of tuples in a list, where the tuple elements are in reverse order?
39,385,019
<p>I am working on a assignment where my program shall ask the user about a positive integer <em>n</em> which the prgogram will found the positive integers a and b, satsifying <em>a</em>^3 + <em>b</em>^3 = <em>n</em>.</p> <p>My work and progress thus far is shown below</p> <pre><code>def ramunajan(n): list=[] u = int(n**(1/3)+1) for a in range (0,u): b = (n-a**3)**(1/3) b = round(b) if a**3+b**3 == n: list.append((a,b)) return list while True: try: n = input("För vilket positivt heltal n vill du hitta a och b där a^3 + b^3 = n ?\n") except ValueError or n &lt;= 0: continue else: break list_1 = ramunajan(int(n)) print (list_1) </code></pre> <p>(The input text message is in swedish.)</p> <p>My problem now is that when a user types in, eg 1729, the program gives output accordingly</p> <blockquote> <blockquote> <blockquote> <p>For what postivie integer n would you like to find a and b, satisfying a^3 + b^3 = n ?</p> <p>1729</p> <p>[(1, 12), (9, 10), (10, 9), (12, 1)]</p> </blockquote> </blockquote> </blockquote> <p>How do I get rid of the reverse duplicates, ie (10, 9) and (12, 1), from the list?</p> <p>Thanks!</p>
0
2016-09-08T07:31:47Z
39,385,207
<p>replace <code>u = int(n**(1/3)+1)</code> with <code>u = int((n**(1/3))/2) + 1</code></p> <p>so it checks only the first half of the pool, since the second half are duplicates</p>
2
2016-09-08T07:41:07Z
[ "python", "duplicates", "tuples" ]
How to do List flattening inside the loop with list comprehension?
39,385,026
<p>here i am having list of dictionaries, my goal is to iterate over list and whenever there is 2 or more list available, i want to merge them and append in a output list, and whenever there is only one list it needs to be stored as it as.</p> <pre><code>data = [ [[{'font-weight': '1'},{'font-weight': '1'}],[{'font-weight': '2'},{'font-weight': '2'}]], [{'font-weight': '3'},{'font-weight': '3'},{'font-weight': '3'}], [[{'font-weight': '1'},{'font-weight': '1'}],[{'font-weight': '2'},{'font-weight': '2'}]], [{'font-weight': '3'},{'font-weight': '3'}] ] </code></pre> <p>I can do list flattening for particular element <code>data[0]</code></p> <pre><code>print([item for sublist in data[0] for item in sublist]) [{'font-weight': '1'}, {'font-weight': '1'}, {'font-weight': '2'}, {'font-weight': '2'}] </code></pre> <p>Expected output :</p> <pre><code>data = [ [{'font-weight': '1'},{'font-weight': '1'},{'font-weight': '2'},{'font-weight': '2'}], [{'font-weight': '3'},{'font-weight': '3'},{'font-weight': '3'}], [{'font-weight': '1'},{'font-weight': '1'},{'font-weight': '2'},{'font-weight': '2'}] [{'font-weight': '3'},{'font-weight': '3'}] ] </code></pre>
2
2016-09-08T07:31:54Z
39,385,155
<p>Try this,</p> <pre><code>result = [] for item in data: result.append([i for j in item for i in j]) </code></pre> <p>Single line code with list comprehension,</p> <pre><code>[[i for j in item for i in j] for item in data] </code></pre> <p>Alternative method,</p> <pre><code>import numpy as np [list(np.array(i).flat) for i in data] </code></pre> <p><strong>Result</strong></p> <pre><code>[[{'font-weight': '1'}, {'font-weight': '1'}, {'font-weight': '2'}, {'font-weight': '2'}], [{'font-weight': '3'}, {'font-weight': '3'}, {'font-weight': '3'}], [{'font-weight': '1'}, {'font-weight': '1'}, {'font-weight': '2'}, {'font-weight': '2'}], [{'font-weight': '3'}, {'font-weight': '3'}]] </code></pre>
3
2016-09-08T07:38:31Z
[ "python", "list", "dictionary" ]
How to do List flattening inside the loop with list comprehension?
39,385,026
<p>here i am having list of dictionaries, my goal is to iterate over list and whenever there is 2 or more list available, i want to merge them and append in a output list, and whenever there is only one list it needs to be stored as it as.</p> <pre><code>data = [ [[{'font-weight': '1'},{'font-weight': '1'}],[{'font-weight': '2'},{'font-weight': '2'}]], [{'font-weight': '3'},{'font-weight': '3'},{'font-weight': '3'}], [[{'font-weight': '1'},{'font-weight': '1'}],[{'font-weight': '2'},{'font-weight': '2'}]], [{'font-weight': '3'},{'font-weight': '3'}] ] </code></pre> <p>I can do list flattening for particular element <code>data[0]</code></p> <pre><code>print([item for sublist in data[0] for item in sublist]) [{'font-weight': '1'}, {'font-weight': '1'}, {'font-weight': '2'}, {'font-weight': '2'}] </code></pre> <p>Expected output :</p> <pre><code>data = [ [{'font-weight': '1'},{'font-weight': '1'},{'font-weight': '2'},{'font-weight': '2'}], [{'font-weight': '3'},{'font-weight': '3'},{'font-weight': '3'}], [{'font-weight': '1'},{'font-weight': '1'},{'font-weight': '2'},{'font-weight': '2'}] [{'font-weight': '3'},{'font-weight': '3'}] ] </code></pre>
2
2016-09-08T07:31:54Z
39,385,181
<p>You could use <a href="http://stackoverflow.com/questions/4406389/if-else-in-a-list-comprehension">conditional list comprehension</a> with <a href="http://docs.python.org/2/library/itertools.html#itertools.chain"><code>itertools.chain</code></a> for those elements which need flattening:</p> <pre><code>In [54]: import itertools In [55]: [list(itertools.chain(*l)) if isinstance(l[0], list) else l for l in data] Out[55]: [[{'font-weight': '1'}, {'font-weight': '1'}, {'font-weight': '2'}, {'font-weight': '2'}], [{'font-weight': '3'}, {'font-weight': '3'}, {'font-weight': '3'}], [{'font-weight': '1'}, {'font-weight': '1'}, {'font-weight': '2'}, {'font-weight': '2'}], [{'font-weight': '3'}, {'font-weight': '3'}]] </code></pre>
5
2016-09-08T07:40:04Z
[ "python", "list", "dictionary" ]
How to do List flattening inside the loop with list comprehension?
39,385,026
<p>here i am having list of dictionaries, my goal is to iterate over list and whenever there is 2 or more list available, i want to merge them and append in a output list, and whenever there is only one list it needs to be stored as it as.</p> <pre><code>data = [ [[{'font-weight': '1'},{'font-weight': '1'}],[{'font-weight': '2'},{'font-weight': '2'}]], [{'font-weight': '3'},{'font-weight': '3'},{'font-weight': '3'}], [[{'font-weight': '1'},{'font-weight': '1'}],[{'font-weight': '2'},{'font-weight': '2'}]], [{'font-weight': '3'},{'font-weight': '3'}] ] </code></pre> <p>I can do list flattening for particular element <code>data[0]</code></p> <pre><code>print([item for sublist in data[0] for item in sublist]) [{'font-weight': '1'}, {'font-weight': '1'}, {'font-weight': '2'}, {'font-weight': '2'}] </code></pre> <p>Expected output :</p> <pre><code>data = [ [{'font-weight': '1'},{'font-weight': '1'},{'font-weight': '2'},{'font-weight': '2'}], [{'font-weight': '3'},{'font-weight': '3'},{'font-weight': '3'}], [{'font-weight': '1'},{'font-weight': '1'},{'font-weight': '2'},{'font-weight': '2'}] [{'font-weight': '3'},{'font-weight': '3'}] ] </code></pre>
2
2016-09-08T07:31:54Z
39,385,352
<p>iterate through list and check if each item is lists of list. If so flatten it.</p> <hr> <pre><code>data = [ [[{'font-weight': '1'},{'font-weight': '1'}],[{'font-weight': '2'},{'font-weight': '2'}]], [{'font-weight': '3'},{'font-weight': '3'},{'font-weight': '3'}], [[{'font-weight': '1'},{'font-weight': '1'}],[{'font-weight': '2'},{'font-weight': '2'}]], [{'font-weight': '3'},{'font-weight': '3'}] ] for n, each_item in enumerate(data): if any(isinstance(el, list) for el in each_item): data[n] = sum(each_item, []) print data </code></pre>
0
2016-09-08T07:48:56Z
[ "python", "list", "dictionary" ]
Debug slow ANTLR generating and parsing
39,385,282
<p>I'm using ANTLR4 + Python2 target, </p> <pre><code>time java -jar lib/antlr-4.5-complete.jar -visitor -o build -Dlanguage=Python2 xxx.g4 time ./main.py </code></pre> <p>It takes 10s to generate the visitor/lexer/parser file, and another 4s to execute the visitor.</p> <p>How should I debug its slowness?</p>
0
2016-09-08T07:45:17Z
39,427,608
<p>I write a lot of antlr4 parsers, and I face speed issues all the time. I have a feeling Python target is usually pretty slow. When a parser is really slow, it usually have reduce/reduce issue meaning there are multiple sub rules having the same terminal rule so the parser get confused.</p> <p>When a parser is slow, I turn on the trace mode and display trace messages. When the trace message is always delayed at one same rule, it is the rule you start investigating. You will look at the rule's sub rules and see if there are multiple sub rules that could become the top delay rule. You may want to comment out or modify a rule and see if that makes the parser faster. It is hard when the grammar is large like the C++ grammar. </p> <p>As a rule of thumb of optimizing an antlr parser grammar, one is eliminating left recursion, and the other is eliminating sub rules that has the same starting rule. e.g.</p> <p><code> declaration: declspecifier* what_follows1 | declspecifier* what_follows2 | declspecifier* what_follows3 </code></p> <p>Empirically I find this kind of grammar rules make the parser slow. Change a bit at a time and check if the speed changes, and make sure reduction step isn't broken. </p> <p>I hope all this makes sense.</p>
0
2016-09-10T15:31:30Z
[ "python", "antlr4" ]
Selenium Python Webdriver chrome print src's of all imgs
39,385,460
<p>I want to print all src of imgs in the page, i want to see if it recognize it, cuz when i do </p> <pre><code>driver.find_element_by_xpath("//img[@src='http://images.yad2.co.il/Pic/site_images/yad2/MyYad2/images/myorderbottom/new/jump_ad.png'").click() </code></pre> <p>its says:</p> <pre><code> C:\Users\Bar\AppData\Local\Programs\Python\Python35-32\python.exe C:/Users/Bar/PycharmProjects/yad2/Webdriver.py Traceback (most recent call last): File "C:/Users/Bar/PycharmProjects/yad2/Webdriver.py", line 14, in &lt;module&gt; driver.find_element_by_xpath("//img[@src='http://images.yad2.co.il/Pic/site_images/yad2/MyYad2/images/myorderbottom/new/jump_ad.png'").click() File "C:\Users\Bar\AppData\Local\Programs\Python\Python35-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 293, in find_element_by_xpath return self.find_element(by=By.XPATH, value=xpath) File "C:\Users\Bar\AppData\Local\Programs\Python\Python35-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 752, in find_element 'value': value})['value'] File "C:\Users\Bar\AppData\Local\Programs\Python\Python35-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 236, in execute self.error_handler.check_response(response) File "C:\Users\Bar\AppData\Local\Programs\Python\Python35-32\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 192, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.InvalidSelectorException: Message: invalid selector: Unable to locate an element with the xpath expression //img[@src='http://images.yad2.co.il/Pic/site_images/yad2/MyYad2/images/myorderbottom/new/jump_ad.png' because of the following error: SyntaxError: Failed to execute 'evaluate' on 'Document': The string '//img[@src='http://images.yad2.co.il/Pic/site_images/yad2/MyYad2/images/myorderbottom/new/jump_ad.png'' is not a valid XPath expression. (Session info: chrome=52.0.2743.116) (Driver info: chromedriver=2.23.409699 (49b0fa931cda1caad0ae15b7d1b68004acd05129),platform=Windows NT 6.1.7601 SP1 x86_64) </code></pre> <p>I have tried with <code>css_selector</code> , didn't work , so I want to print all of the srcs of the <code>imgs</code>, how can I do that?</p>
0
2016-09-08T07:54:52Z
39,386,070
<blockquote> <p>selenium.common.exceptions.InvalidSelectorException: Message: invalid selector: Unable to locate an element with the xpath expression //img[@src='<a href="http://images.yad2.co.il/Pic/site_images/yad2/MyYad2/images/myorderbottom/new/jump_ad.png" rel="nofollow">http://images.yad2.co.il/Pic/site_images/yad2/MyYad2/images/myorderbottom/new/jump_ad.png</a>' because of the following error: SyntaxError: Failed to execute 'evaluate' on 'Document': The string '//img[@src='<a href="http://images.yad2.co.il/Pic/site_images/yad2/MyYad2/images/myorderbottom/new/jump_ad.png" rel="nofollow">http://images.yad2.co.il/Pic/site_images/yad2/MyYad2/images/myorderbottom/new/jump_ad.png</a>'' is not a valid XPath expression.</p> </blockquote> <p>Actually your <code>xpath</code> is syntactically incorrect, you are missing to close square bracket <code>]</code>, So you should try as :-</p> <pre><code>driver.find_element_by_xpath(".//img[@src='http://images.yad2.co.il/Pic/site_images/yad2/MyYad2/images/myorderbottom/new/jump_ad.png']").click() </code></pre> <p>Or using <code>css_selector</code> as :-</p> <pre><code>driver.find_element_by_css_selector("img[src='http://images.yad2.co.il/Pic/site_images/yad2/MyYad2/images/myorderbottom/new/jump_ad.png']").click() </code></pre> <p>And if you want to print all <code>img</code> src attribute try as :-</p> <pre><code>images = driver.find_elements_by_tag_name("img") for image in images : print(image.get_attribute("src")) </code></pre>
0
2016-09-08T08:27:25Z
[ "python", "selenium", "selenium-webdriver" ]
Selenium Python Webdriver chrome print src's of all imgs
39,385,460
<p>I want to print all src of imgs in the page, i want to see if it recognize it, cuz when i do </p> <pre><code>driver.find_element_by_xpath("//img[@src='http://images.yad2.co.il/Pic/site_images/yad2/MyYad2/images/myorderbottom/new/jump_ad.png'").click() </code></pre> <p>its says:</p> <pre><code> C:\Users\Bar\AppData\Local\Programs\Python\Python35-32\python.exe C:/Users/Bar/PycharmProjects/yad2/Webdriver.py Traceback (most recent call last): File "C:/Users/Bar/PycharmProjects/yad2/Webdriver.py", line 14, in &lt;module&gt; driver.find_element_by_xpath("//img[@src='http://images.yad2.co.il/Pic/site_images/yad2/MyYad2/images/myorderbottom/new/jump_ad.png'").click() File "C:\Users\Bar\AppData\Local\Programs\Python\Python35-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 293, in find_element_by_xpath return self.find_element(by=By.XPATH, value=xpath) File "C:\Users\Bar\AppData\Local\Programs\Python\Python35-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 752, in find_element 'value': value})['value'] File "C:\Users\Bar\AppData\Local\Programs\Python\Python35-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 236, in execute self.error_handler.check_response(response) File "C:\Users\Bar\AppData\Local\Programs\Python\Python35-32\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 192, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.InvalidSelectorException: Message: invalid selector: Unable to locate an element with the xpath expression //img[@src='http://images.yad2.co.il/Pic/site_images/yad2/MyYad2/images/myorderbottom/new/jump_ad.png' because of the following error: SyntaxError: Failed to execute 'evaluate' on 'Document': The string '//img[@src='http://images.yad2.co.il/Pic/site_images/yad2/MyYad2/images/myorderbottom/new/jump_ad.png'' is not a valid XPath expression. (Session info: chrome=52.0.2743.116) (Driver info: chromedriver=2.23.409699 (49b0fa931cda1caad0ae15b7d1b68004acd05129),platform=Windows NT 6.1.7601 SP1 x86_64) </code></pre> <p>I have tried with <code>css_selector</code> , didn't work , so I want to print all of the srcs of the <code>imgs</code>, how can I do that?</p>
0
2016-09-08T07:54:52Z
39,442,082
<p>Ok propably @Saurabh Gaur were right there is Iframe in the site , Simple solution ,</p> <pre><code>driver.switch_to.frame(driver.find_element_by_id("FrameID")) </code></pre> <p>Thats it from there i could find the button , then i comeback</p> <pre><code>driver.switch_to.default_content() </code></pre> <p>and from here i can continue to the next Frame Thats it! @Saurabh Gaur Thank you So much! , you were Excellent!</p>
0
2016-09-12T00:53:44Z
[ "python", "selenium", "selenium-webdriver" ]
Plot data without interpolation from former x value
39,385,461
<p>I am doing some particle tracking at the moment. Therefore I want to plot the distribution and the cumulative function of the passing particles. </p> <p>When I plot the distribution, my plot always starts one time step to early. Is there a way to just plot the event as a kind of peak, without any interpolation on the x axis? </p> <p>Short example data is attached...</p> <pre><code>time = [ 0.,1.,2.,3.,4.,5.,6.,7.,8.,9.] counts = [0,0,1,0,2,0,0,0,1,0] cum = [ 0.,0.,0.25,0.25,0.75,0.75,0.75,0.75,1.,1.] ax1 = plt.subplot2grid((1,2), (0, 0), colspan=1) ax1.plot(time, counts, "-", label="Density") ax1.set_xlim([0,time[-1]]) ax1.legend(loc = "upper left", frameon = False) ax1.grid() ax2 = plt.subplot2grid((1,2), (0, 1), rowspan=1) ax2.step(time, cum, "r",where='post', label="Sum") ax2.legend(loc = "upper left", frameon = False) ax2.set_ylim([-0.05,1.05]) ax2.set_xlim([0,time[-1]]) ax2.grid() plt.suptitle("Particle distribution \n") plt.show() </code></pre> <p><a href="http://i.stack.imgur.com/ZK7VY.png" rel="nofollow"><img src="http://i.stack.imgur.com/ZK7VY.png" alt="enter image description here"></a></p> <p>Thanks for any help!</p>
1
2016-09-08T07:54:54Z
39,385,649
<p>There is no interpolation; with <code>plot(.., '-')</code>, matplotlib simply <em>"connects the dots"</em> (data coordinates that you provide). Either don't draw the line and use markers, e.g.:</p> <pre><code>ax1.plot(time, counts, "o", label="Density") </code></pre> <p>Or use e.g. <code>bar()</code> to draw "peaks":</p> <pre><code>ax1.bar(time, counts, width=0.001) </code></pre> <p><em>edit</em>: Drawing <code>bar()</code>'s isn't ideal, as you are not drawing individual lines, but very small bars. It turns out that <code>matplotlib</code> actually has a function to draw the peaks: <code>stem()</code>:</p> <pre><code>ax1.stem(time, counts, label="Density") </code></pre> <p>Which results in:</p> <p><a href="http://i.stack.imgur.com/rBW9k.png" rel="nofollow"><img src="http://i.stack.imgur.com/rBW9k.png" alt="enter image description here"></a></p>
1
2016-09-08T08:04:25Z
[ "python", "matplotlib", "plot" ]
what is wrong with this AngularJs code- in browser code editor- Nodejs
39,385,571
<p>Hi am trying to create in browser code editor for free knowledge sharing for high school students from basic level. after long struggle with search i got <a href="https://github.com/scriptnull/compilex" rel="nofollow">this</a> link. i just did some setup and changes as per guidance available in that link.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var express = require('express'); var path = require('path'); var app = express(); var bodyParser = require('body-parser'); //app.use(bodyParser.urlencoded()); app.use(bodyParser.urlencoded({ extended: true })); //compileX var compiler = require('compilex'); var option = {stats : true}; compiler.init(option); app.get('/' , function (req , res ) { res.sendfile( __dirname + "/index.html"); }); //app.post('/compilecode' , function (req , res ) { app.post('/' , function (req , res ) { var code = req.body.code; var input = req.body.input; var inputRadio = req.body.inputRadio; var lang = req.body.lang; if((lang === "C") || (lang === "C++")) { if(inputRadio === "true") { var envData = { OS : "windows" , cmd : "g++"}; compiler.compileCPPWithInput(envData , code ,input , function (data) { if(data.error) { res.send(data.error); } else { res.send(data.output); } }); } else { var envData = { OS : "windows" , cmd : "g++"}; compiler.compileCPP(envData , code , function (data) { if(data.error) { res.send(data.error); } else { res.send(data.output); } }); } } if(lang === "Java") { if(inputRadio === "true") { var envData = { OS : "windows" }; console.log(code); compiler.compileJavaWithInput( envData , code , function(data){ res.send(data); }); } else { var envData = { OS : "windows" }; console.log(code); compiler.compileJavaWithInput( envData , code , input , function(data){ res.send(data); }); } } if( lang === "Python") { if(inputRadio === "true") { var envData = { OS : "windows"}; compiler.compilePythonWithInput(envData , code , input , function(data){ res.send(data); }); } else { var envData = { OS : "windows"}; compiler.compilePython(envData , code , function(data){ res.send(data); }); } } if( lang === "CS") { if(inputRadio === "true") { var envData = { OS : "windows"}; compiler.compileCSWithInput(envData , code , input , function(data){ res.send(data); }); } else { var envData = { OS : "windows"}; compiler.compileCS(envData , code , function(data){ res.send(data); }); } } if( lang === "VB") { if(inputRadio === "true") { var envData = { OS : "windows"}; compiler.compileVBWithInput(envData , code , input , function(data){ res.send(data); }); } else { var envData = { OS : "windows"}; compiler.compileVB(envData , code , function(data){ res.send(data); }); } } }); app.get('/fullStat' , function(req , res ){ compiler.fullStat(function(data){ res.send(data); }); }); app.listen(8080);</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"&gt;&lt;/script&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Compilex&lt;/title&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/PreloadJS/0.6.0/preloadjs.min.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;center&gt; &lt;form id="myform" name="myform" method="post" action="/"&gt; &lt;h3&gt;Your Code&lt;/h3&gt; &lt;textarea rows="13" cols="100" id="code" name="code" &gt;&lt;/textarea&gt; &lt;br/&gt; &lt;div&gt; &lt;input type="submit" value="submit" name="submit" /&gt; &lt;/div&gt; &lt;div&gt; &lt;br/&gt; Language : &lt;select name="lang"&gt; &lt;option value="C"&gt;C&lt;/option&gt; &lt;option value="C++"&gt;C++&lt;/option&gt; &lt;option value="Java"&gt;Java&lt;/option&gt; &lt;option value="Python"&gt;Python&lt;/option&gt; &lt;option value="CS"&gt;C#&lt;/option&gt; &lt;option value="VB"&gt;VB&lt;/option&gt; &lt;/select&gt; Compile With Input : &lt;input type="radio" name="inputRadio" id="inputRadio" value="true"/&gt;yes &lt;input type="radio" name="inputRadio" id="inputRadio" value="false"/&gt;No &lt;/div&gt; &lt;h3&gt;Output&lt;/h3&gt; &lt;textarea rows="10" cols="100" id="input" name="input" &gt;&lt;/textarea&gt; &lt;br /&gt; &lt;/form&gt; &lt;/center&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p> <p>Requirement: 1. how to compile the input for Python (how to configure with this app) 2. how to show the output in second textarea.</p> <p>(note: spend lots of time with codemirror, ace editor examples and demo but couldn't use it efficiently as am new to this platform)</p> <p>helps much appreciated </p> <p>Thank you</p>
-3
2016-09-08T08:00:00Z
39,393,973
<p>Move <code>&lt;script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"&gt;&lt;/script&gt; </code> into the <code>&lt;head&gt;</code>. Not certain that this is your problem, but that'd be the first step in my book in the debugging process. </p>
0
2016-09-08T14:45:42Z
[ "javascript", "python", "angularjs", "node.js", "code-editor" ]
what is wrong with this AngularJs code- in browser code editor- Nodejs
39,385,571
<p>Hi am trying to create in browser code editor for free knowledge sharing for high school students from basic level. after long struggle with search i got <a href="https://github.com/scriptnull/compilex" rel="nofollow">this</a> link. i just did some setup and changes as per guidance available in that link.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var express = require('express'); var path = require('path'); var app = express(); var bodyParser = require('body-parser'); //app.use(bodyParser.urlencoded()); app.use(bodyParser.urlencoded({ extended: true })); //compileX var compiler = require('compilex'); var option = {stats : true}; compiler.init(option); app.get('/' , function (req , res ) { res.sendfile( __dirname + "/index.html"); }); //app.post('/compilecode' , function (req , res ) { app.post('/' , function (req , res ) { var code = req.body.code; var input = req.body.input; var inputRadio = req.body.inputRadio; var lang = req.body.lang; if((lang === "C") || (lang === "C++")) { if(inputRadio === "true") { var envData = { OS : "windows" , cmd : "g++"}; compiler.compileCPPWithInput(envData , code ,input , function (data) { if(data.error) { res.send(data.error); } else { res.send(data.output); } }); } else { var envData = { OS : "windows" , cmd : "g++"}; compiler.compileCPP(envData , code , function (data) { if(data.error) { res.send(data.error); } else { res.send(data.output); } }); } } if(lang === "Java") { if(inputRadio === "true") { var envData = { OS : "windows" }; console.log(code); compiler.compileJavaWithInput( envData , code , function(data){ res.send(data); }); } else { var envData = { OS : "windows" }; console.log(code); compiler.compileJavaWithInput( envData , code , input , function(data){ res.send(data); }); } } if( lang === "Python") { if(inputRadio === "true") { var envData = { OS : "windows"}; compiler.compilePythonWithInput(envData , code , input , function(data){ res.send(data); }); } else { var envData = { OS : "windows"}; compiler.compilePython(envData , code , function(data){ res.send(data); }); } } if( lang === "CS") { if(inputRadio === "true") { var envData = { OS : "windows"}; compiler.compileCSWithInput(envData , code , input , function(data){ res.send(data); }); } else { var envData = { OS : "windows"}; compiler.compileCS(envData , code , function(data){ res.send(data); }); } } if( lang === "VB") { if(inputRadio === "true") { var envData = { OS : "windows"}; compiler.compileVBWithInput(envData , code , input , function(data){ res.send(data); }); } else { var envData = { OS : "windows"}; compiler.compileVB(envData , code , function(data){ res.send(data); }); } } }); app.get('/fullStat' , function(req , res ){ compiler.fullStat(function(data){ res.send(data); }); }); app.listen(8080);</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"&gt;&lt;/script&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Compilex&lt;/title&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/PreloadJS/0.6.0/preloadjs.min.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;center&gt; &lt;form id="myform" name="myform" method="post" action="/"&gt; &lt;h3&gt;Your Code&lt;/h3&gt; &lt;textarea rows="13" cols="100" id="code" name="code" &gt;&lt;/textarea&gt; &lt;br/&gt; &lt;div&gt; &lt;input type="submit" value="submit" name="submit" /&gt; &lt;/div&gt; &lt;div&gt; &lt;br/&gt; Language : &lt;select name="lang"&gt; &lt;option value="C"&gt;C&lt;/option&gt; &lt;option value="C++"&gt;C++&lt;/option&gt; &lt;option value="Java"&gt;Java&lt;/option&gt; &lt;option value="Python"&gt;Python&lt;/option&gt; &lt;option value="CS"&gt;C#&lt;/option&gt; &lt;option value="VB"&gt;VB&lt;/option&gt; &lt;/select&gt; Compile With Input : &lt;input type="radio" name="inputRadio" id="inputRadio" value="true"/&gt;yes &lt;input type="radio" name="inputRadio" id="inputRadio" value="false"/&gt;No &lt;/div&gt; &lt;h3&gt;Output&lt;/h3&gt; &lt;textarea rows="10" cols="100" id="input" name="input" &gt;&lt;/textarea&gt; &lt;br /&gt; &lt;/form&gt; &lt;/center&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p> <p>Requirement: 1. how to compile the input for Python (how to configure with this app) 2. how to show the output in second textarea.</p> <p>(note: spend lots of time with codemirror, ace editor examples and demo but couldn't use it efficiently as am new to this platform)</p> <p>helps much appreciated </p> <p>Thank you</p>
-3
2016-09-08T08:00:00Z
39,403,126
<p>Actually, you have just plain HTML and there is nothing in there that uses angular.</p> <p>Adding a script tag alone does not make something "angular code". BTW, the tag is indeed in the wrong place, and it holds an ancient angular version. By now you should be using version 1.5.8. If you want to learn how to use angulular you should visit the <a href="https://docs.angularjs.org/tutorial" rel="nofollow">tutorial</a> and read through the <a href="https://docs.angularjs.org/guide" rel="nofollow">docs</a> and <a href="https://github.com/johnpapa/angular-styleguide" rel="nofollow">style-guide</a>.</p> <p>If you want to start now with angular its probably a better idea to dirtectly look at <a href="https://angular.io/" rel="nofollow">angular 2</a></p>
2
2016-09-09T02:55:06Z
[ "javascript", "python", "angularjs", "node.js", "code-editor" ]
Python - download file using GET form
39,385,655
<p>I am trying to write a script that downloads a xlsx file and saves it to the computer. This file doesn't have a specific path and it gets generated after filling a <code>GET</code> form. There are two submit buttons. </p> <p>The first one makes a list of results under the form (I can do it). The second one creates a xlsx file and asks where to save it.</p> <pre><code>&lt;form action="/search" method="get" id="frm-detailedSearchForm"&gt; </code></pre> <p>...</p> <pre><code>&lt;input type="text" name="publication_date[from]" class="date" tabindex="1" id="frm-detailedSearchForm-publication_date-from" data-nette-rules='[{"op":":filled","rules":[{"op":":pattern","msg":"Nevalidní formát data (dd.mm.rrrr)","arg":"\\d{1,2}\\.\\d{1,2}.\\d{4}"}],"control":"publication_date[from]"}]'&gt; </code></pre> <p>...</p> <pre><code>&lt;input type="submit" name="search" class="w-button btn ajax" tabindex="27" value="Search"&gt; &lt;input type="submit" name="export" class="w-button btn" tabindex="28" value="Export"&gt; &lt;input type="hidden" name="do" value="detailedSearchForm-submit"&gt;&lt;/form&gt; </code></pre> <hr> <p>EDIT: Solution was easy in the end (using mechanize lib):</p> <pre><code>url = url + ?do=detailedSearchForm-submit&amp;export=Export browser.retrieve(url, file.xlsx) </code></pre> <p>Thank you.</p>
0
2016-09-08T08:04:47Z
39,385,739
<p>if I get you right you're trying to write a script that interacts with an existing website, fills a form, downloads a file and saves it, right? you're not the one writing the website.</p> <p>is so - I highly recommend using <a href="http://selenium-python.readthedocs.io/" rel="nofollow">selenium</a> to automate the task of filling the form <strong>on top of a real browser</strong>. it's a bit hard to start but much much more resilient.</p> <p>while you theoretically could write a script that downloads the file from a url that fakes a form submission, this attitude is often times a source of troubles. if the site is over some level of complexity - the likelihood of this attitude to work is very low.</p>
0
2016-09-08T08:09:57Z
[ "python", "downloadfile" ]
Concatenate Pandas Dataframe
39,385,711
<p>I am trying to concatenate few dataframes which depends on if they are created in the process. So for example I have following master list of many data frame</p> <pre><code> List=['df_facebook','df_LinkedIn','df_Insta','tweet_final','df_Google','df_Slide','df_Youtube'] </code></pre> <p>Now In my process, assume df_google did not get created, so I wont be able to do </p> <pre><code>df_Social = pd.concat([df_facebook,df_LinkedIn,df_Insta,tweet_final,df_Youtube,df_Google,df_Slide]) </code></pre> <p>So to handle this, since I want it to completely automated &amp; Dynamic, I tried to something like this </p> <pre><code>list_a=[col for col in List if col in locals()] df_Social=pd.concat(list_a) </code></pre> <p>Which gives me an error</p> <pre><code>TypeError: cannot concatenate a non-NDFrame object </code></pre> <p>Which is right also, Please help me to fix this, or some alternate solution, which can help me to just concatenate the already created dataframes dynamically. I will appreciate every help!</p>
0
2016-09-08T08:08:34Z
39,385,872
<p>it is not a good idea to look variables in locals. however, you can try:</p> <pre><code>list_a=[locals()[col] for col in List if col in locals()] # for example List = ['df_google', 'df_facebook', 'df_linkedin'] # the frames should have the same column name if you want to concat vertically df_google = pd.DataFrame(np.random.randn(20,3)) df_facebook = pd.DataFrame(np.random.randn(40, 3)) list_a=[locals()[col] for col in List if col in locals()] pd.concat(list_a) </code></pre>
1
2016-09-08T08:16:45Z
[ "python", "pandas", "for-loop", "dataframe" ]
Regex in django models
39,385,914
<p>I've got a problem with regex in django models, the file name must start with letter or numer and the rest of work can caontains letters, numbers and two special signs: - and _. My code looks like:</p> <pre><code>file_validator = validators.RegexValidator( regex='^[a-zA-Z0-9]*[a-zA-Z0-9\_\-]*$', message=(u'Name must start from letter or number, it can contains big and small letters, numbers and special signs: - _'), code='invalid_file', ) </code></pre> <p>But when I test it in my project, when I write file name: "mike", there is an error message. What I do wrong?</p>
0
2016-09-08T08:18:51Z
39,386,681
<p>I believe you do not need the <code>+</code> as <a href="http://stackoverflow.com/questions/39385914/regex-in-django-models#comment66098698_39385914">Avinash suggests</a>, you just need to drop the first <code>*</code> quantifier that means <em>zero or more occurrences</em>. Since it allows 0 occurrences the <em>must start with letter or number</em> rule does not work.</p> <p>Use</p> <pre><code>r'^[a-zA-Z0-9][\w-]*$' </code></pre> <p>See the <a href="https://regex101.com/r/fL2oW2/1" rel="nofollow">regex demo</a></p> <p><strong>Pattern details</strong>:</p> <ul> <li><code>^</code> - start of string</li> <li><code>[a-zA-Z0-9]</code> - 1 occurrence of an ASCII letter or digit</li> <li><code>[\w-]*</code> - 0+ digits, letters, <code>_</code> or <code>-</code> sybmols up to</li> <li><code>$</code> - the end of string.</li> </ul> <p>Note that <code>\w</code> matches ASCII letters and digits in this case since <code>re.UNICODE</code> flag is not used.</p> <p>Also note that <code>-</code> at the end of the character class does not have to be escaped, <strong>but</strong> if you plan to add more chars to the class later, it is a good idea to keep it escaped.</p>
0
2016-09-08T08:58:59Z
[ "python", "regex", "django", "django-models" ]
How to replace a pattern start with {| to end of string (multi line), if there is no |} inside
39,385,967
<p>What I need is to manipulate bad-formated wiki code. I have:</p> <pre><code>s = ''' whatever... {| line1 |} whatever... {| lineXXX ''' </code></pre> <p>Now I want to delete from {| to end, if no |} inside.</p> <p>The result I want is:</p> <pre><code>''' whatever... {| line1 |} whatever... ''' </code></pre> <p>I tried:</p> <pre><code>re.sub('{|[^(\|\})]*$', '\n',s) </code></pre> <p>but failed.</p> <p>How to do this?</p>
1
2016-09-08T08:22:17Z
39,386,160
<p>First of all, your pattern contains an unescaped <code>|</code> that becomes an alternation operator. Then, <code>[^(\|\})]*</code> does not negate a <em>sequence</em> of <code>|}</code>, it just matches 0+ chars other than <code>(</code>, <code>|</code>, <code>}</code> and <code>)</code>.</p> <p>You may use a <a href="http://www.rexegg.com/regex-quantifiers.html#tempered_greed" rel="nofollow"><strong>tempered greedy token</strong></a> (requiring a <code>re.DOTALL</code> modifier):</p> <pre><code>{\|(?:(?!\|}).)*$ </code></pre> <p>or its unroll-the-loop variant (not requiring the <code>re.DOTALL</code> modifier):</p> <pre><code>{\|[^|]*(?:\|(?!})[^|]*)*$ </code></pre> <p>See <a href="https://regex101.com/r/zY3bC5/3" rel="nofollow">the regex demo</a> or <a href="https://regex101.com/r/zY3bC5/4" rel="nofollow">this one</a>.</p> <p><strong>Pattern details</strong>:</p> <ul> <li><code>{\|</code> - a literal <code>{|</code> text</li> <li><code>(?:(?!\|}).)*</code> - a tempered greedy token that matches any character (<code>.</code>) that does not start a <code>|}</code> sequence (OR the unrolled variant is <code>[^|]*(?:\|(?!})[^|]*)*</code> - 0+ non-<code>|</code>s followed with 0+ sequences of <code>|</code> not followed with <code>}</code> and then 0+ non-<code>|</code>s)</li> <li><code>$</code> - end of string.</li> </ul> <p>See the <a href="https://ideone.com/Ai3C9v" rel="nofollow">Python demo</a>:</p> <pre><code>import re s = ''' whatever... {| line1 |} whatever... {| lineXXX ''' res = re.sub(r'{\|(?:(?!\|}).)*$', '', s, flags=re.S) print(res) </code></pre>
2
2016-09-08T08:31:30Z
[ "python", "regex" ]
Python copy, cut and paste detection
39,385,996
<p>I am new to python, I am currently designing a program that runs in the background and i want it to detect if any copy, cut or paste operation is performed on a PC. Or is there a way i can detect when control c, control v or control x is pressed by a user Thanks</p>
-1
2016-09-08T08:23:41Z
39,386,065
<p>You can try a key logger to detect key stroke like <a href="https://github.com/ajinabraham/Xenotix-Python-Keylogger/blob/master/xenotix_python_logger.py" rel="nofollow">this</a> one. Other than that you can use key hooking using system calls.</p>
0
2016-09-08T08:27:06Z
[ "python", "copy", "paste", "cut" ]
Python copy, cut and paste detection
39,385,996
<p>I am new to python, I am currently designing a program that runs in the background and i want it to detect if any copy, cut or paste operation is performed on a PC. Or is there a way i can detect when control c, control v or control x is pressed by a user Thanks</p>
-1
2016-09-08T08:23:41Z
39,386,820
<p>You could try to register changes to clipboard to trigger your event.</p> <p>Take a look at this stack overflow question: <a href="http://stackoverflow.com/questions/14685999/trigger-an-event-when-clipboard-content-changes">link</a></p>
0
2016-09-08T09:04:58Z
[ "python", "copy", "paste", "cut" ]
Python Indentation Error Issue
39,386,080
<p>I'm getting this problem on a simple test on a Python file,</p> <pre><code>class Prueba(object): def __init__(self): self.position = 0 def build_message(self, signal): message = self.position message = message | (0b1&lt;&lt;signal) s = bin(message) s = s[2:len(s)] s = (16-len(s))*'0' + s s0 = s[0:len(s)/2] s1 = s[len(s)/2:len(s)] s0 = s0[::-1] s1 = s1[::-1] s_final = int(s0 + s1, 2) return s_final def motor_activation(self): rospy.logwarn("Preparing motor to start...") if(self.drive_status[MC] == False and self.drive_status[READY] == False and self.drive_status[BRAKE] == False and self.drive_status[ERROR] == False): rospy.sleep(1) ####### Avtivate FG_R ####### message = self.build_message(FG_R) self.setBrModbusValue(2, message) ##Wait a little rospy.sleep(1) ####### Avtivate FG_E ####### message = self.build_message(FG_E) self.setBrModbusValue(2, message) </code></pre> <p>Im getting this message when trying to execute it with ipython:</p> <pre><code>message = self.position ^ IdentationError:expected an indented block </code></pre>
0
2016-09-08T08:28:02Z
39,386,166
<p>This must be an issue of tabs mixed with spaces.</p> <p>You can convert all the tabs into spaces by changing some settings in editor you are using.</p> <p>In case of sublime text : Preferences -> settings-User</p> <p>Try saving this as Packages/User/Preferences.sublime-settings</p> <pre><code>{ "tab_size": 4, "translate_tabs_to_spaces": true } </code></pre>
0
2016-09-08T08:31:49Z
[ "python" ]
How to save results for each while loop in python?
39,386,134
<p>as you can see from my code there will be 150 dx value like dx(1) for j=50, dx(2) for j=51---dx(150) for j=149. I want to write all dx (upto 149) value in one column of "foobar.xls" file. Presently, I found in xls file, only the value of dx(150). so that is my problem. Sorry for improper questioning. (I`m new here). </p> <pre><code>import matplotlib.pyplot as plt import numpy as np import xlrd import xlwt wb = xlrd.open_workbook('Scatter plot.xlsx') sh1 = wb.sheet_by_name('T180') sh2=wb.sheet_by_name("T181") sh3=wb.sheet_by_name("Sheet1") x= np.array([sh1.col_values(1,start_rowx=50, end_rowx=299)]) x1= np.array([sh2.col_values(1, start_rowx=48, end_rowx=200)]) print x1 j=50 while j&lt;200: y=np.array([sh1.cell_value(j,1)]) condition = [(x1&lt;=(sh1.cell_value(j,1)+100)) &amp; (x1&gt;=(sh1.cell_value(j,1)-200)) ] dx=y-x1[condition] j+=1 print dx workbook = xlwt.Workbook() sheet = workbook.add_sheet("Sheet1") i=1 for n in dx: sheet.write(i, 0,n) i=i+1 workbook.save("foobar.xls") </code></pre>
-3
2016-09-08T08:29:57Z
39,407,180
<pre><code>Its working like this way. Thanks for our nice comments and helpful mind. j=50 i=1 while j&lt;300: x=np.array([sh1.cell_value(j,1)]) condition = [(x1&lt;=(sh1.cell_value(j,1)+100)) &amp; (x1&gt;= (sh1.cell_value(j,1)-200)) ] dx=x-x1[condition] j+=1 for n in dx: sheet.write(i, 0,n) i+=1 print dx </code></pre>
0
2016-09-09T08:30:59Z
[ "python", "excel", "while-loop", "saving-data" ]
How to open a mat file in python
39,386,264
<p>I was trying to open a mat file in python but my attempts did fail. Here is my code</p> <pre><code>from scipy import * from pylab import * save('rfdata.mat') import scipy.io as sio mat = scipy.io.loadmat('rfdata.mat'); </code></pre> <p>python says that : </p> <pre><code>Traceback (most recent call last): File "C:\Users\Ali\.spyder2-py3\template.py", line 14, in &lt;module&gt; mat = scipy.io.loadmat('rfdata.mat'); NameError: name 'scipy' is not defined </code></pre> <p>EDIT: I removed all code above and wrote </p> <pre><code>import scipy.io as sio mat = sio.io.loadmat('rfdata.mat'); </code></pre> <p>still does not work</p> <p>I appreciate your help</p> <p>Thanks</p>
0
2016-09-08T08:37:38Z
39,386,312
<p>As you did:</p> <pre><code>import scipy.io as sio </code></pre> <p>You loaded <code>scipy.io</code> into <code>sio</code>. So, when you call:</p> <pre><code>mat = scipy.io.loadmat('rfdata.mat'); </code></pre> <p><code>scipy</code> is not defined, but <code>sio</code> is:</p> <pre><code>mat = sio.loadmat('rfdata.mat') </code></pre> <p>Moreover:</p> <ul> <li>try to place all imports at the begining of the file;</li> <li>do not use <code>;</code> at the end of a line, it is not needed in Python.</li> </ul>
0
2016-09-08T08:39:58Z
[ "python" ]
Python/Django unittest, how to handle outside calls?
39,386,340
<p>I read multiple times that one should use <code>mock</code> to mimic outside calls and there should be no calls made to any outside service because your tests need to run regardless of outside services. </p> <p>This totally makes sense....BUT</p> <p>What about outside services changing? What good is a test, testing that my code works like it should if I will never know when it breaks because of the outside service being modified/updated/removed/deprecated/etc...</p> <p>How can I reconcile this? The pseudocode is below</p> <pre><code>function post_tweet: data = {"tweet":"tweetcontent"} send request to twitter receive response return response </code></pre> <p>If I mock this there is no way I will be notified that twitter changed their API and now I have to update my test...</p>
1
2016-09-08T08:41:30Z
39,386,569
<p>There are different levels of testing.</p> <p><strong>Unit tests</strong> are testing, as you might guess from the name, a unit. Which is for example a function or a method, maybe a class. If you interpret it wider it might include a view to be tested with Djangos test client. Unittests never test external stuff like libraries, dependencies or interfaces to other Systems. Theses thing will be mocked.</p> <p><strong>Integration tests</strong> are testing if your interfaces and usage of outside libraries, systems and APIs is implemented properly. If the dependency changes, you will notice have to change your code and unit tests.</p> <p>There are other levels of tests as well, like behavior tests, UI tests, usability tests. You should make sure to separate theses tests classes in your project.</p>
3
2016-09-08T08:53:41Z
[ "python", "django", "unit-testing", "testing", "call" ]
Search and replace specific line which starts with specific string in a file
39,386,384
<p>My requirement is to open a properties file and update the file, for update purpose i need to search for a specific string which stores the url information. For this purpose i have written the below code in python:</p> <pre><code>import os owsURL="https://XXXXXXXXXXXXXX/" reowsURL = "gStrOwsEnv = " + owsURL + "/" + "OWS_WS_51" + "/" fileName='C:/Users/XXXXXXXXXXX/tempconf.properties' if not os.path.isfile(fileName): print("!!! Message : Configuraiton.properties file is not present ") else: print("+++ Message : Located the configuration.properties file") with open(fileName) as f: data = f.readlines() for m in data: if m.startswith("gStrOwsEnv"): print("ok11") m = m.replace(m,reowsURL) </code></pre> <p>after executing the program i am not able to update the properties file.</p> <p>Any help is highly appreciated</p> <p>Sample Content of file:</p> <pre><code># *********************************************** # Test Environment Details # *********************************************** # Application URL pointing to test execution #gStrApplicationURL =XXXXXXXXXXXXXXXX/webservices/person #gStrApplicationURL = XXXXXXXXXXXXXX/GuestAPIService/ProxyServices/ # FOR JSON #gStrApplicationURL = XXXXXXXXXXXXXX #SOAP_gStrApplicationURL =XXXXXXXXXXXXXXXXXXXXXXX #(FOR WSDL PARSING) version = 5 #v9 #SOAP_gStrApplicationURL = XXXXXXXXXXX/XXXXXXXXX/XXXXXXXXX/ #v5 SOAP_gStrApplicationURL = XXXXXXXXXXXXXXX/OWS_WS_51/ gStrApplicationXAIServerPath= gStrEnvironmentName=XXXXXXXXX gStrOwsEnv = XXXXXXXXXXXXXXXXXXXX/OWS_WS_51/ gStrConnectEnv = XXXXXXXXXXXXXXXXX/OWSServices/Proxy/ gStrSubscriptionKey =XXXXXXXXXXXXXXXXXXXXXX </code></pre>
0
2016-09-08T08:44:08Z
39,386,679
<p>I'm pretty sure that this is not the best way of doing that, but this is still one way:</p> <pre><code>with open(input_file_name, 'r') as f_in, open(output_file_name, 'w') as f_out: for line in f_in: if line.startswith("gStrOwsEnv"): f_out.write(reowsURL) else: f_out.write(line) </code></pre> <p>That script copy every line of <code>input_file_name</code> into <code>output_file_name</code> except the lines that you want to change.</p>
1
2016-09-08T08:58:56Z
[ "python", "file", "search", "replace" ]
Why doesn't the numpy-C api warn me about failed allocations?
39,386,450
<p>I've been writing a python extension that writes into a numpy array from C. During testing, I noticed that certain very large arrays would generate a segfault when I tried to access some of their elements. Specifically, the last line of the following code segment fails with a SEGFAULT:</p> <pre><code> // Size of buffer we will write to npy_intp buffer_len_alt = BUFFER_LENGTH; // PyArray_Descr * dtype; dtype = PyArray_DescrFromType(NPY_BYTE); PyObject* column = PyArray_Zeros(1, &amp;buffer_len_alt, dtype, 0); //Check that array creation succeeds if (column == NULL){ // This exit point is not reached, so it looks like everything is OK return (PyObject *) NULL; } // Get the array's internal buffer so we can write to it output_buffer = PyArray_BYTES((PyArrayObject *)column); // Try writing to the buffer output_buffer[0] = 'x'; //No segfault output_buffer[((int) buffer_len_alt) - 1] = 'x'; //Segfault here </code></pre> <p>I checked and found that the error occurs only when I try to allocate an array of about 3GB (i.e. BUFFER_LENGTH is about 3*2^30). It's <a href="https://en.wikipedia.org/wiki/3_GB_barrier" rel="nofollow">not surprising</a> that an allocation of this size would fail, even if python is using it's custom allocator. What really concerns me is that <strong>numpy did not raise an error or otherwise indicate that the array creation did not go as planned</strong>.</p> <p>I have already tried checking PyArray_ISCONTIGUOUS on the returned array, and using PyArray_GETCONTIGUOUS to ensure it is a single memory segment, but the SEGFAULT would still occur. NPY_ARRAY_DEFAULT creates contiguous arrays, so this shouldn't be necessary anyways.</p> <p><strong>Is there some error flag I should be checking? How can I detect/prevent this situation in the future?</strong> Setting BUFFER_LENGTH to a smaller value obviously works, but this value is determined at runtime and I would like to know the exact bounds.</p> <p><strong>EDIT</strong>:</p> <p>As @DavidW pointed out, the error stems from casting buffer_len_alt to an int, since npy_intp can be a 64-bit number. Replacing the cast to int with a cast to 'unsigned long' fixes the problem for me</p>
3
2016-09-08T08:47:19Z
39,392,253
<p>The issue (diagnosed in the comments) was actually with the array lookup rather than the allocation of the array. Your code contained the line</p> <pre><code>output_buffer[((int) buffer_len_alt) - 1] = 'x' </code></pre> <p>When <code>buffer_len_alt</code> (approx value 3000000000) was cast to an (32 bit) int (maximum value 2147483647) you ended up with an invalid address, probably a large negative number.</p> <p>The solution is just to use</p> <pre><code>output_buffer[buffer_len_alt - 1] = 'x' </code></pre> <p>(i.e. I don't see why you should need a cast at all).</p>
2
2016-09-08T13:27:03Z
[ "python", "c", "numpy", "python-c-api" ]
How to read data in Python dataframe without concatenating?
39,386,458
<p>I want to read the file f (file size:85GB) in chunks to a dataframe. Following code is suggested.</p> <pre><code>chunksize = 5 TextFileReader = pd.read_csv(f, chunksize=chunksize) </code></pre> <p>However, this code gives me TextFileReader, not dataframe. Also, I don't want to concatenate these chunks to convert TextFileReader to dataframe because of the memory limit. Please advise.</p>
0
2016-09-08T08:47:44Z
39,386,767
<p>As you are trying to process 85GB CSV file, if you will try to read all the data by breaking it into chunks and converting it into dataframe then it will hit memory limit for sure. You can try to solve this problem by using different approach. In this case, you can use filtering operations on your data. For example, if there are 600 columns in your dataset and you are interested only in 50 columns. Try to read only 50 columns from the file. This way you will save lot of memory. Process your rows as you read them. If you need to filter the data first, use a generator function. <code>yield</code> makes a function a generator function, which means it won't do any work until you start looping over it.</p> <p>For more information regarding generator function: <a href="http://stackoverflow.com/questions/17444679/reading-a-huge-csv-in-python">Reading a huge .csv in python</a></p> <p>For efficient filtering refer: <a href="http://codereview.stackexchange.com/questions/88885/efficiently-filter-a-large-100gb-csv-file-v3">http://codereview.stackexchange.com/questions/88885/efficiently-filter-a-large-100gb-csv-file-v3</a> </p> <p>For processing smaller dataset:</p> <p><strong>Approach 1: To convert reader object to dataframe directly:</strong></p> <pre><code>full_data = pd.concat(TextFileReader, ignore_index=True) </code></pre> <p>It is necessary to add parameter <a href="http://pandas.pydata.org/pandas-docs/stable/merging.html#ignoring-indexes-on-the-concatenation-axis" rel="nofollow">ignore index</a> to function concat, because avoiding duplicity of indexes.</p> <p><strong>Approach 2:</strong> <strong>Use Iterator or get_chunk to convert it into dataframe.</strong> </p> <p>By specifying a chunksize to read_csv,return value will be an iterable object of type TextFileReader. </p> <pre><code>df=TextFileReader.get_chunk(3) for chunk in TextFileReader: print(chunk) </code></pre> <p>Source : <a href="http://pandas.pydata.org/pandas-docs/stable/io.html#io-chunking" rel="nofollow">http://pandas.pydata.org/pandas-docs/stable/io.html#io-chunking</a></p> <p><code>df= pd.DataFrame(TextFileReader.get_chunk(1))</code> </p> <p>This will convert one chunk to dataframe. </p> <p><strong>Checking total number of chunks in TextFileReader</strong></p> <pre><code>number_of_chunks=0 for chunk in TextFileReader: number_of_chunks=number_of_chunks+1 print(number_of_chunks) </code></pre> <p>If file size is bigger,I won't recommend second approach. For example, if csv file consist of 100000 records then chunksize=5 will create 20,000 chunks. </p>
0
2016-09-08T09:02:30Z
[ "python", "csv", "pandas", "dataframe", "chunks" ]
How to print the query of .get queryset in django
39,386,513
<p>How can I know the query when doing a .get queryset in django</p> <p>I have this model:</p> <pre><code>class Artist(EsIndexable, models.Model): name = models.CharField(max_length=50) birth_date = models.DateField() </code></pre> <p>And I did this in the shell:</p> <pre><code>x = Artist.objects.get(name="Eminem") print x.query </code></pre> <p>Then I got the error:</p> <pre><code>AttributeError: 'Artist' object has no attribute 'query' </code></pre>
1
2016-09-08T08:50:47Z
39,386,591
<pre><code>from django.db import connection x = Artist.objects.get(name="Eminem") print connection.queries[-1] </code></pre>
3
2016-09-08T08:55:21Z
[ "python", "django" ]
How to print the query of .get queryset in django
39,386,513
<p>How can I know the query when doing a .get queryset in django</p> <p>I have this model:</p> <pre><code>class Artist(EsIndexable, models.Model): name = models.CharField(max_length=50) birth_date = models.DateField() </code></pre> <p>And I did this in the shell:</p> <pre><code>x = Artist.objects.get(name="Eminem") print x.query </code></pre> <p>Then I got the error:</p> <pre><code>AttributeError: 'Artist' object has no attribute 'query' </code></pre>
1
2016-09-08T08:50:47Z
39,386,611
<p><code>.get</code> returns an instance, not a queryset.</p> <p>To see the query that is done, do the same thing but with <code>.filter</code>, which does return a queryset:</p> <pre><code>queryset = Artist.objects.filter(name="Eminem") print queryset.query x = queryset.get() </code></pre>
2
2016-09-08T08:56:10Z
[ "python", "django" ]
Python 'except' clauses not working
39,386,618
<p>Hello Stack Overflow community.</p> <p>I'm currently trying to learn how to program in Python (3.5) and I've had a problem with a conversion program. Summarised, it seems like Python is ignoring the except clauses in the source code.</p> <pre><code>try: print("Welcome to CONVERSION. Choose an option.") print("1. Convert CELSIUS to FAHRENHEIT.") print("2. Convert FAHRENHEIT to CELSIUS.") Option = int(input("OPTION: ")) except NameError: print(Option, " is not a valid input.") except ValueError: print(Option, " is not a valid input.") except KeyboardInterrupt: print("Don't do that!") else: if (Option != 1) or (Option != 2): print("Please input a valid option!") elif (Option == 1): try: Celsius = float(input("Enter value in Celsius: ")) except ValueError: print(Celsius, " is not a valid input.") except KeyboardInterrupt: print("Don't do that!") else: Fahrenheit = Celsius * 1.8 + 32 print(Celsius, "C = ", Fahrenheit, "F.") elif (Option == 2): try: Fahrenheit = float(input("Enter value in Fahrenheit: ")) except ValueError: print(Celsius, " is not a valid input.") except KeyboardInterrupt: print("Don't do that!") Celsius = (Fahrenheit - 32) * ( 5 / 9 ) print(Fahrenheit, "F = ", Celsius, "C.") else: print("That value is invalid. Try again.") </code></pre> <p>The full traceback, when inputting the value "wad" in the first screen:</p> <pre><code>Traceback (most recent call last): File "C:\Users\user\Documents\Visual Studio 2015\Projects\TempConversion\TempConversion\TempConversion.py", line 7, in &lt;module&gt; Option = int(input("OPTION: ")) ValueError: invalid literal for int() with base 10: 'wad' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\user\Documents\Visual Studio 2015\Projects\TempConversion\TempConversion\TempConversion.py", line 11, in &lt;module&gt; print(Option, " is not a valid input.") NameError: name 'Option' is not defined </code></pre>
0
2016-09-08T08:56:29Z
39,386,699
<p>The exception is thrown after you caught an exception. This basically puts it outside the try catch scenario.</p> <p>If you add <code>Option = None</code> before <code>try</code> the code should execute properly.</p> <p>The reason for this is because <code>int(input(...))</code> raises an exception before Option is defined. So that the code that handles the initial exception is throwing a new exception.</p> <p>You would also need to change the print statement inside the exception handling to properly handle a potential <code>None</code> value from <code>Options</code>. You could achieve this by something similar to this.</p> <pre><code>Option = None try: Option = int(input("OPTION: ")) except (NameError, ValueError): if Option: print(Option, " is not a valid input.") else: print("No valid input.") except KeyboardInterrupt: print("Don't do that!") else: ..... </code></pre> <p>This also applies to the similar code you have for Celsius and Fahrenheit.</p> <p>[Edit] Not sure what is wrong for you now, ideally you should create a new question, as your new question is beyond the scope of your original question, but I prepared a quick, more slightly structured example based on your code.</p> <pre><code>import sys def get_input(text, convert_to='int'): result = None try: if convert_to == 'int': result = int(input(text)) else: result = float(input(text)) except (NameError, ValueError): if result: print(result, " is not a valid input.") else: print("No valid input.") sys.exit(1) return result def handle_celsius_to_fahrenheit(): celsius = get_input('Enter value in Celsius: ', convert_to='float') fahrenheit = celsius * 1.8 + 32 print("C = %s, F %s." % (celsius, fahrenheit)) def handle_fahrenheit_to_celsius(): fahrenheit = get_input('Enter value in Fahrenheit: ', convert_to='float') celsius = (fahrenheit - 32) * (5 / 9) print('F = %s , C %s.' % (fahrenheit, celsius)) def get_option(): option = get_input('OPTION: ') if option == 1: handle_celsius_to_fahrenheit() elif option == 2: handle_fahrenheit_to_celsius() else: print("Please input a valid option!") sys.exit(1) if __name__ == '__main__': print("Welcome to CONVERSION. Choose an option.") print("1. Convert CELSIUS to FAHRENHEIT.") print("2. Convert FAHRENHEIT to CELSIUS.") get_option() </code></pre>
4
2016-09-08T08:59:41Z
[ "python", "nameerror", "except" ]
Python 'except' clauses not working
39,386,618
<p>Hello Stack Overflow community.</p> <p>I'm currently trying to learn how to program in Python (3.5) and I've had a problem with a conversion program. Summarised, it seems like Python is ignoring the except clauses in the source code.</p> <pre><code>try: print("Welcome to CONVERSION. Choose an option.") print("1. Convert CELSIUS to FAHRENHEIT.") print("2. Convert FAHRENHEIT to CELSIUS.") Option = int(input("OPTION: ")) except NameError: print(Option, " is not a valid input.") except ValueError: print(Option, " is not a valid input.") except KeyboardInterrupt: print("Don't do that!") else: if (Option != 1) or (Option != 2): print("Please input a valid option!") elif (Option == 1): try: Celsius = float(input("Enter value in Celsius: ")) except ValueError: print(Celsius, " is not a valid input.") except KeyboardInterrupt: print("Don't do that!") else: Fahrenheit = Celsius * 1.8 + 32 print(Celsius, "C = ", Fahrenheit, "F.") elif (Option == 2): try: Fahrenheit = float(input("Enter value in Fahrenheit: ")) except ValueError: print(Celsius, " is not a valid input.") except KeyboardInterrupt: print("Don't do that!") Celsius = (Fahrenheit - 32) * ( 5 / 9 ) print(Fahrenheit, "F = ", Celsius, "C.") else: print("That value is invalid. Try again.") </code></pre> <p>The full traceback, when inputting the value "wad" in the first screen:</p> <pre><code>Traceback (most recent call last): File "C:\Users\user\Documents\Visual Studio 2015\Projects\TempConversion\TempConversion\TempConversion.py", line 7, in &lt;module&gt; Option = int(input("OPTION: ")) ValueError: invalid literal for int() with base 10: 'wad' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\user\Documents\Visual Studio 2015\Projects\TempConversion\TempConversion\TempConversion.py", line 11, in &lt;module&gt; print(Option, " is not a valid input.") NameError: name 'Option' is not defined </code></pre>
0
2016-09-08T08:56:29Z
39,386,724
<p>You are trying to use variable <code>Option</code> in your string with error, but that variable doesn't exist, as it's the reason of the error. Try initiating <code>Option = input()</code> before the <code>try</code> and convert it to int in <code>try</code></p>
2
2016-09-08T09:00:52Z
[ "python", "nameerror", "except" ]
Python 'except' clauses not working
39,386,618
<p>Hello Stack Overflow community.</p> <p>I'm currently trying to learn how to program in Python (3.5) and I've had a problem with a conversion program. Summarised, it seems like Python is ignoring the except clauses in the source code.</p> <pre><code>try: print("Welcome to CONVERSION. Choose an option.") print("1. Convert CELSIUS to FAHRENHEIT.") print("2. Convert FAHRENHEIT to CELSIUS.") Option = int(input("OPTION: ")) except NameError: print(Option, " is not a valid input.") except ValueError: print(Option, " is not a valid input.") except KeyboardInterrupt: print("Don't do that!") else: if (Option != 1) or (Option != 2): print("Please input a valid option!") elif (Option == 1): try: Celsius = float(input("Enter value in Celsius: ")) except ValueError: print(Celsius, " is not a valid input.") except KeyboardInterrupt: print("Don't do that!") else: Fahrenheit = Celsius * 1.8 + 32 print(Celsius, "C = ", Fahrenheit, "F.") elif (Option == 2): try: Fahrenheit = float(input("Enter value in Fahrenheit: ")) except ValueError: print(Celsius, " is not a valid input.") except KeyboardInterrupt: print("Don't do that!") Celsius = (Fahrenheit - 32) * ( 5 / 9 ) print(Fahrenheit, "F = ", Celsius, "C.") else: print("That value is invalid. Try again.") </code></pre> <p>The full traceback, when inputting the value "wad" in the first screen:</p> <pre><code>Traceback (most recent call last): File "C:\Users\user\Documents\Visual Studio 2015\Projects\TempConversion\TempConversion\TempConversion.py", line 7, in &lt;module&gt; Option = int(input("OPTION: ")) ValueError: invalid literal for int() with base 10: 'wad' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\user\Documents\Visual Studio 2015\Projects\TempConversion\TempConversion\TempConversion.py", line 11, in &lt;module&gt; print(Option, " is not a valid input.") NameError: name 'Option' is not defined </code></pre>
0
2016-09-08T08:56:29Z
39,386,735
<p>It works as it should. When you're handling the <code>ValueError</code> exception, you try to read <code>Option</code>, which is not set yet. This results in another exception. which you don't catch anymore.</p>
0
2016-09-08T09:01:29Z
[ "python", "nameerror", "except" ]
How do you set a default value for a variable in Python3?
39,386,729
<p>For an assignment I have to write a program that can create directories and files, we have to write a DirectoryEntry class to help do this, and for part of it we have to create a name for the file or directory. If a name is entered then we just use the name but if no name is entered we just use 9 spaces. </p> <p>I don't know how to do this using the <code>__init__</code> method because Python3 doesn't allow you to have more then one constructor method.</p> <p>Right now it just looks like:</p> <pre><code>def __init__(self, name): self.type = "f:" self.name = name self.length = "0000" self.colon = ":" self.blocks = ["000", "000", "000", "000", "000", "000", "000", "000", "000", "000", "000", "000"]` </code></pre>
0
2016-09-08T09:01:09Z
39,386,805
<p>You can use:</p> <pre><code>def __init__(self, name='your_default_name'): </code></pre> <p>Then you can either create an object of that class with <code>my_object()</code> and it will use the default value, or use <code>my_object('its_name')</code> and it will use the input value.</p>
3
2016-09-08T09:04:11Z
[ "python", "default-value", "default-constructor" ]
How do you set a default value for a variable in Python3?
39,386,729
<p>For an assignment I have to write a program that can create directories and files, we have to write a DirectoryEntry class to help do this, and for part of it we have to create a name for the file or directory. If a name is entered then we just use the name but if no name is entered we just use 9 spaces. </p> <p>I don't know how to do this using the <code>__init__</code> method because Python3 doesn't allow you to have more then one constructor method.</p> <p>Right now it just looks like:</p> <pre><code>def __init__(self, name): self.type = "f:" self.name = name self.length = "0000" self.colon = ":" self.blocks = ["000", "000", "000", "000", "000", "000", "000", "000", "000", "000", "000", "000"]` </code></pre>
0
2016-09-08T09:01:09Z
39,386,807
<p>You can use default arguments:</p> <pre><code>def __init__(self, name=' '): </code></pre>
0
2016-09-08T09:04:18Z
[ "python", "default-value", "default-constructor" ]
How do you set a default value for a variable in Python3?
39,386,729
<p>For an assignment I have to write a program that can create directories and files, we have to write a DirectoryEntry class to help do this, and for part of it we have to create a name for the file or directory. If a name is entered then we just use the name but if no name is entered we just use 9 spaces. </p> <p>I don't know how to do this using the <code>__init__</code> method because Python3 doesn't allow you to have more then one constructor method.</p> <p>Right now it just looks like:</p> <pre><code>def __init__(self, name): self.type = "f:" self.name = name self.length = "0000" self.colon = ":" self.blocks = ["000", "000", "000", "000", "000", "000", "000", "000", "000", "000", "000", "000"]` </code></pre>
0
2016-09-08T09:01:09Z
39,386,809
<p>Just set it like this, so for default will use 9 spaces</p> <pre><code>def __init__(self, name=' '): self.type = "f:" self.name = name self.length = "0000" self.colon = ":" self.blocks = ["000", "000", "000", "000", "000", "000", "000", "000", "000", "000", "000", "000"] </code></pre> <p><a href="http://blog.thedigitalcatonline.com/blog/2015/02/11/default-arguments-in-python/#.V9EpHE2LQdU" rel="nofollow">More information</a></p>
1
2016-09-08T09:04:27Z
[ "python", "default-value", "default-constructor" ]
How do you set a default value for a variable in Python3?
39,386,729
<p>For an assignment I have to write a program that can create directories and files, we have to write a DirectoryEntry class to help do this, and for part of it we have to create a name for the file or directory. If a name is entered then we just use the name but if no name is entered we just use 9 spaces. </p> <p>I don't know how to do this using the <code>__init__</code> method because Python3 doesn't allow you to have more then one constructor method.</p> <p>Right now it just looks like:</p> <pre><code>def __init__(self, name): self.type = "f:" self.name = name self.length = "0000" self.colon = ":" self.blocks = ["000", "000", "000", "000", "000", "000", "000", "000", "000", "000", "000", "000"]` </code></pre>
0
2016-09-08T09:01:09Z
39,386,848
<p>Specify it as a default variable as shown below</p> <pre><code>def __init__(self, name=' '*9): self.type = "f:" self.name = name self.length = "0000" self.colon = ":" self.blocks = ["000", "000", "000", "000", "000", "000", "000","000","000","000", "000", "000"] </code></pre>
1
2016-09-08T09:06:28Z
[ "python", "default-value", "default-constructor" ]
Opening file from a Fileshare-system with python
39,386,825
<p>im trying to open a file from a Filesharing-System of our company. Here is the Code of the script:</p> <pre><code>import sys import xlrd from tkinter import * import pandas as pd import time from os import * #hvl_file_path = filedialog.askopenfilename() save_path = filedialog.asksaveasfilename(initialdir="C:/", defaultextension=".xlsx") t1 = time.clock() hvl = pd.read_csv('\\Q4DEE1SYVFS.ffm.t-systems.com\pasm$\Berichte_SQL\HVL.csv', sep='|', encoding='latin1', low_memory=False) hvl.to_excel(save_path, index=False) t2 = time.clock() t_ges = t2 - t1 print(t_ges) </code></pre> <p>You can see the file_path is: \Q4DEE1SYVFS.ffm.t-systems.com\pasm$\Berichte_SQL\HVL.csv</p> <p>When i start the script i get the following error:</p> <pre><code>Traceback (most recent call last): File "C:/Users/A52113242/Desktop/PROJEKTE/[INPROGRESS] AUSWERTUNG COIN + HVL/hvl_convert.py", line 13, in &lt;module&gt; hvl = pd.read_csv('Q4DEE1SYVFS.ffm.t-systems.com\pasm$\Berichte_SQL\HVL.csv', sep='|', encoding='latin1', low_memory=False) File "C:\Users\A52113242\AppData\Local\Downloaded Apps\Winpython\python-3.4.3\lib\site-packages\pandas\io\parsers.py", line 474, in parser_f return _read(filepath_or_buffer, kwds) File "C:\Users\A52113242\AppData\Local\Downloaded Apps\Winpython\python-3.4.3\lib\site-packages\pandas\io\parsers.py", line 250, in _read parser = TextFileReader(filepath_or_buffer, **kwds) File "C:\Users\A52113242\AppData\Local\Downloaded Apps\Winpython\python-3.4.3\lib\site-packages\pandas\io\parsers.py", line 566, in __init__ self._make_engine(self.engine) File "C:\Users\A52113242\AppData\Local\Downloaded Apps\Winpython\python-3.4.3\lib\site-packages\pandas\io\parsers.py", line 705, in _make_engine self._engine = CParserWrapper(self.f, **self.options) File "C:\Users\A52113242\AppData\Local\Downloaded Apps\Winpython\python-3.4.3\lib\site-packages\pandas\io\parsers.py", line 1072, in __init__ self._reader = _parser.TextReader(src, **kwds) File "pandas\parser.pyx", line 350, in pandas.parser.TextReader.__cinit__ (pandas\parser.c:3187) File "pandas\parser.pyx", line 594, in pandas.parser.TextReader._setup_parser_source (pandas\parser.c:5930) OSError: File b'Q4DEE1SYVFS.ffm.t-systems.com\\pasm$\\Berichte_SQL\\HVL.csv' does not exist </code></pre> <p>So my question is if there is a problem with the path or its a point of missing permissions. Do you have any ideas?</p> <p>Thank you!</p> <p>EDIT:</p> <p>Now i tried to open the file: </p> <pre><code>f = open('\\Q4DEE1SYVFS.ffm.t-systems.com\pasm$\RFM\Berichte_SQL\HVL.csv','w') </code></pre> <p>After trying to open the file with open i get this error: </p> <pre><code>Traceback (most recent call last): File "C:/Users/A52113242/Desktop/PROJEKTE/[INPROGRESS] AUSWERTUNG COIN + HVL/hvl_convert.py", line 13, in &lt;module&gt; f = open('\\Q4DEE1SYVFS.ffm.t-systems.com\pasm$\Berichte_SQL\HVL.csv','w') TypeError: an integer is required (got type str) </code></pre>
0
2016-09-08T09:05:11Z
39,390,146
<p>When dealing with UNC strings or Windows strings in general it is better to declare constant strings with the <code>r</code> (raw) prefix:</p> <pre><code>pd.read_csv(r'\\Q4DEE1SYVFS.ffm ...') </code></pre> <p>not doing that result in some chars to be interpreted:</p> <pre><code>print("foo\test") </code></pre> <p>yields:</p> <pre><code>foo est (tabulation has been inserted) </code></pre> <p>Same goes for many lowercase chars (`\t,\n,\v,\b,\x ...).</p> <p>Double antislashes means "escape the antislash" and is converted a single backslash.</p> <pre><code>print('\\ddd') </code></pre> <p>yields:</p> <pre><code>\ddd </code></pre> <p>thus your path is incorrect.</p> <p>But there's more here. You shouldn't get <code>expected int found str</code> errors. So I found out the problem in one of your comments: there are some invisible chars causing trouble. I pasted the path from your comments in pyscripter and assigned it to a variable and go this:</p> <pre><code>&gt;&gt;&gt; z=r"\\Q4DEE1SYVFS.ffm.t-systems.com\pasm$\Berichte_SQL\HVL‌​.csv" &gt;&gt;&gt; z '\\\\Q4DEE1SYVFS.ffm.t-systems.com\\pasm$\\Berichte_SQL\\HVL\xe2\x80\x8c\xe2\x80\x8b.csv' </code></pre> <p>Just rewrite the last part of your string and it will work.</p> <p>PS: notepad++ was unable to see the weird chars. I heard that SciTe had a tendency to let those pass too. Pyscripter sees them.</p>
1
2016-09-08T11:49:58Z
[ "python", "pandas" ]
PySpark - How to output JSON with specific fields?
39,386,832
<p>The JSON format looks like:</p> <pre><code>{ "name": "aaa", "address": { "street": "blv abc", "street_num": "122" } } </code></pre> <p>I would read the data from parquet files and execute a sql query on them, like finding all those living at street <code>blv abc</code>. But I just want to output the <code>name</code> and <code>address.street</code> as:</p> <pre><code>{ "name": "aaa", "address": { "street": "blv abc" } } </code></pre> <p>How can I output only <code>name</code> and <code>address.street</code>?</p> <p>The DataFrameReader schema might not work for me since I need to execute some SQL query before output which might need to filter on <code>street_num</code>.</p>
1
2016-09-08T09:05:37Z
39,406,696
<p>My last resort for this kind of unusual data transformation is</p> <pre><code>from pyspark.sql.types import Row def transform(row): d = row.asDict() # now in python data types del d['address']['street_num'] return Row(**d) new = dataframe.rdd.map(transform) </code></pre> <p>I suppose you want to remove a lot of fields to keep the records slim, otherwise it doesn't really worth it.</p>
1
2016-09-09T08:02:25Z
[ "python", "json", "apache-spark", "pyspark" ]
How to define a temporary variable in python?
39,386,837
<p>Does python have a "temporary" or "very local" variable facility? I am looking for a one-liner and I want to keep my variable space tidy.</p> <p>I would like to do something like this:</p> <pre><code>...a, b, and c populated as lists earlier in code... using ix=getindex(): print(a[ix],b[ix],c[ix]) ...now ix is no longer defined... </code></pre> <p>The variable ix would be undefined outside of the one line.</p> <p>Perhaps this pseudo-code is more clear:</p> <pre><code>...a and b are populated lists earlier in code... {ix=getindex(); answer = f(a[ix]) + g(b[ix])} </code></pre> <p>where ix does not exist outside of the bracket.</p>
1
2016-09-08T09:05:47Z
39,386,999
<p>Comprehensions and generator expressions have their own scope, so you can put it in one of those:</p> <pre><code>&gt;&gt;&gt; def getindex(): ... return 1 ... &gt;&gt;&gt; a,b,c = range(2), range(3,5), 'abc' &gt;&gt;&gt; next(print(a[x], b[x], c[x]) for x in [getindex()]) 1 4 b &gt;&gt;&gt; x Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; NameError: name 'x' is not defined </code></pre> <p>But you really don't have to worry about that sort of thing. That's one of Python's selling points.</p> <p>For those using Python 2:</p> <pre><code>&gt;&gt;&gt; print next(' '.join(map(str, [a[x], b[x], c[x]])) for x in [getindex()]) 1 4 b </code></pre> <p>Consider using Python 3, so you don't have to deal with <code>print</code> as a statement.</p>
1
2016-09-08T09:14:19Z
[ "python" ]