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
Parse text position vector to floats
39,939,185
<p>I have a .txt file that contains lines in this format:</p> <pre><code>{"Position":[81.2305,4.05698,9.14912]} </code></pre> <p>Because I have lots of other lines that start with an open bracket and a name enclosed in quotes followed by a semi-colon, I have split the line into two like this:</p> <pre><code>[ '{"Position":', '[81.2305,4.05698,9.14912]}' ] </code></pre> <p>I would like to parse the second string into a list of 3 floats. What is the best way to do this? </p>
0
2016-10-09T01:53:52Z
39,939,247
<p>Your data looks like JSON, so you can use the built-in JSON module:</p> <pre><code>import json pos = [] # list of (x,y,z) with open('t.txt') as infile: for line in infile: # skip blank lines (add other cases as needed) if not line.strip(): continue item = json.loads(line) if "Position" in item: pos.append(item["Position"]) print(pos) </code></pre>
3
2016-10-09T02:06:01Z
[ "python", "regex", "python-3.x" ]
Parse text position vector to floats
39,939,185
<p>I have a .txt file that contains lines in this format:</p> <pre><code>{"Position":[81.2305,4.05698,9.14912]} </code></pre> <p>Because I have lots of other lines that start with an open bracket and a name enclosed in quotes followed by a semi-colon, I have split the line into two like this:</p> <pre><code>[ '{"Position":', '[81.2305,4.05698,9.14912]}' ] </code></pre> <p>I would like to parse the second string into a list of 3 floats. What is the best way to do this? </p>
0
2016-10-09T01:53:52Z
39,939,611
<pre><code>import re re.sub(r':',':#',s).split('#') </code></pre>
0
2016-10-09T03:08:05Z
[ "python", "regex", "python-3.x" ]
How do I put a string in a list at every nth index?
39,939,197
<p>I'm working on a function that gets the suit and value as a string in a list from another function:</p> <pre><code>def getCard(n): deckListSuit = [] grabSuit = getSuit(n) n = (n-1) % 13 + 1 if n == 1: deckListSuit.append("Ace") return deckListSuit + grabSuit if 2 &lt;= n &lt;= 10: deckListSuit.append(str(n)) return deckListSuit + grabSuit if n == 11: deckListSuit.append("Jack") return deckListSuit + grabSuit if n == 12: deckListSuit.append("Queen") return deckListSuit + grabSuit if n == 13: deckListSuit.append("King") return deckListSuit + grabSuit </code></pre> <p>With the new function it is to take the information from the above function and return it in a list with a certain structure "VALUE of SUIT".</p> <p>So say if you had "3", "Spades" it would return "3 of Spades" instead.</p> <p>This is my code so far on the new function.</p> <pre><code>def getHand(myList): hand = [] for n in myList: hand += getCard(n) return [(" of ".join(hand[:2]))] + [(" of ".join(hand[2:4]))] + [(" of ".join(hand[4:6]))] + [(" of ".join(hand[6:8]))] + [(" of ".join(hand[8:10]))] </code></pre> <p>My question is, is how do I insert "of" between the value and suit without having to do .join a million times?</p>
0
2016-10-09T01:56:46Z
39,939,275
<p>You can do it in your <code>for</code> loop</p> <pre><code>for n in myList: hand += [" of ".join(getCard(n))] return hand </code></pre> <p>You can also do it in <code>getCard</code> and return <code>'3 of Spades'</code></p> <hr> <p>BTW: you could keep it as tuples on list </p> <pre><code>hand = [ ("3", "Spades"), ("Queen", "Spades"), ... ] </code></pre> <p>then you can use <code>for</code> loop instead of slices <code>[:2]</code>, <code>[2:4]</code></p> <pre><code>new_list = [] for card in hand: # in `card` you have ("3", "Spades") new_list.append(' of '.join(card)) return new_list </code></pre>
2
2016-10-09T02:11:36Z
[ "python", "list", "python-3.x", "join" ]
How do I put a string in a list at every nth index?
39,939,197
<p>I'm working on a function that gets the suit and value as a string in a list from another function:</p> <pre><code>def getCard(n): deckListSuit = [] grabSuit = getSuit(n) n = (n-1) % 13 + 1 if n == 1: deckListSuit.append("Ace") return deckListSuit + grabSuit if 2 &lt;= n &lt;= 10: deckListSuit.append(str(n)) return deckListSuit + grabSuit if n == 11: deckListSuit.append("Jack") return deckListSuit + grabSuit if n == 12: deckListSuit.append("Queen") return deckListSuit + grabSuit if n == 13: deckListSuit.append("King") return deckListSuit + grabSuit </code></pre> <p>With the new function it is to take the information from the above function and return it in a list with a certain structure "VALUE of SUIT".</p> <p>So say if you had "3", "Spades" it would return "3 of Spades" instead.</p> <p>This is my code so far on the new function.</p> <pre><code>def getHand(myList): hand = [] for n in myList: hand += getCard(n) return [(" of ".join(hand[:2]))] + [(" of ".join(hand[2:4]))] + [(" of ".join(hand[4:6]))] + [(" of ".join(hand[6:8]))] + [(" of ".join(hand[8:10]))] </code></pre> <p>My question is, is how do I insert "of" between the value and suit without having to do .join a million times?</p>
0
2016-10-09T01:56:46Z
39,939,361
<p>If you use a list of tuple you can do with format and list comprehension</p> <pre><code>test_hand = [("3","space"),("4","old")] return ["{} of {}".format(i,z) for i,z in (test_hand)] </code></pre> <p>output:</p> <pre><code> ['3 of space', '4 of old'] </code></pre>
0
2016-10-09T02:25:29Z
[ "python", "list", "python-3.x", "join" ]
TypeError: YN_prompt() missing 1 required positional argument: 'self'
39,939,253
<p>I'm new to python and I'm kind of stuck. When I run my program, I get this </p> <pre><code>"Traceback (most recent call last): File "C:/Users/Dell/Documents/Code/junk.py", line 1, in &lt;module&gt; class E: File "C:/Users/Dell/Documents/Code/junk.py", line 27, in E YN_prompt() TypeError: YN_prompt() missing 1 required positional argument: 'self' </code></pre> <p>I don't understand what I am doing wrong, can someone please explain to me what that error message means? Thanks.</p> <pre><code>class E: import random import time thing = 1 cookie = random.randrange(4) def YN_prompt(self): ugly = 1 while ugly == 1: yn = input("\n Go again? y/n \n") if yn == ("y"): continue elif yn == ("n"): quit() else: print("ILLEGAL VALUE, CHOOSING ANOTER") time.sleep(0.2) continue while thing == 1: if cookie == 0: print("hi") YN_prompt() elif cookie == 1: print("no") YN_prompt() elif cookie == 2: print("why") YN_prompt() elif cookie == 3: print("when") YN_prompt() elif cookie == 4: print("who") YN_prompt() </code></pre>
0
2016-10-09T02:07:20Z
39,939,334
<p>You need to instantiate a class instance first. For example: </p> <pre><code>Example_class = E() </code></pre> <p>and then you can call your function like this</p> <pre><code> Example_class.YN_prompt() </code></pre> <p>Check this older post for more infos <a href="http://stackoverflow.com/questions/17534345/typeerror-missing-1-required-positional-argument-self">link</a></p>
-1
2016-10-09T02:20:35Z
[ "python" ]
TypeError: YN_prompt() missing 1 required positional argument: 'self'
39,939,253
<p>I'm new to python and I'm kind of stuck. When I run my program, I get this </p> <pre><code>"Traceback (most recent call last): File "C:/Users/Dell/Documents/Code/junk.py", line 1, in &lt;module&gt; class E: File "C:/Users/Dell/Documents/Code/junk.py", line 27, in E YN_prompt() TypeError: YN_prompt() missing 1 required positional argument: 'self' </code></pre> <p>I don't understand what I am doing wrong, can someone please explain to me what that error message means? Thanks.</p> <pre><code>class E: import random import time thing = 1 cookie = random.randrange(4) def YN_prompt(self): ugly = 1 while ugly == 1: yn = input("\n Go again? y/n \n") if yn == ("y"): continue elif yn == ("n"): quit() else: print("ILLEGAL VALUE, CHOOSING ANOTER") time.sleep(0.2) continue while thing == 1: if cookie == 0: print("hi") YN_prompt() elif cookie == 1: print("no") YN_prompt() elif cookie == 2: print("why") YN_prompt() elif cookie == 3: print("when") YN_prompt() elif cookie == 4: print("who") YN_prompt() </code></pre>
0
2016-10-09T02:07:20Z
39,939,514
<p>Looks like you wanted to keep your while loop inside your class :</p> <pre><code>class E: import random import time thing = 1 cookie = random.randrange(4) def YN_prompt(self): ugly = 1 while ugly == 1: yn = input("\n Go again? y/n \n") if yn == ("y"): continue elif yn == ("n"): quit() else: print("ILLEGAL VALUE, CHOOSING ANOTER") time.sleep(0.2) continue while thing == 1: if cookie == 0: print("hi") YN_prompt() elif cookie == 1: print("no") YN_prompt() elif cookie == 2: print("why") YN_prompt() elif cookie == 3: print("when") YN_prompt() elif cookie == 4: print("who") YN_prompt() </code></pre>
0
2016-10-09T02:51:11Z
[ "python" ]
Get right timezone information when using datetime.datetime.now()?
39,939,286
<p>I'm trying to get the date in datetime.datetime.now() format but for MT time in Python 2.7.</p> <p>If you suggest using a library please explain how to install it. Thanks.</p>
0
2016-10-09T02:13:54Z
39,939,464
<pre><code>from pytz import timezone from datetime import datetime datetime.now(timezone('US/Mountain')) </code></pre> <p>That's what you probably need. As for installing the library, just <code>pip install pytz</code></p>
2
2016-10-09T02:41:35Z
[ "python", "python-2.7" ]
Script runs strangely in interpreter. What is the effect of the -i flag?
39,939,517
<p>I recently made a program which prints a word diagonally. Whenever I go to the console/python interpreter and type </p> <p><code>python3 "xxx.py"</code>, it will just continue onto the next line and won't do anything.</p> <p>However, if I do: <code>python3 -i "xxx.py"</code> it enters python and lets me enter inputs for my program</p> <p>Why is this happening?</p> <p>My code (copied from comment below):</p> <pre><code>def diagonal(text, right_to_left = False): #Code for diagonal diagonal() </code></pre> <p>I got this error:</p> <pre><code>Traceback (most recent call last): File "question1.py", line 17, in &lt;module&gt; diagonal() TypeError: diagonal() missing 1 required positional argument: 'text' </code></pre>
0
2016-10-09T02:51:30Z
39,941,758
<p>The flag <code>-i</code> tells python to process the script, and then enter interactive mode. Without the <code>-i</code> python will just process the script and then exit.</p> <p>A script might define functions, classes etc, but not call them. If you want the script to do something, you must have at least one line in your script that calls a function.</p> <p>The usual pattern is:</p> <pre><code>#class and function definitions def print_diagonal(x): #code for diagonal def main(): #code for running the program word = input() print_diagonal(word) #run the program main() </code></pre> <p>The error you get is because the diagonal function has one required argument, the text. You need to supply this argument in some way. You could use an <code>input</code> function in the code (as in my example), or you could use the command line by <code>import sys</code>, and reading <code>sys.argv[]</code>. The <a href="https://docs.python.org/3/library/sys.html?highlight=sys.argv#sys.argv" rel="nofollow">python documentation</a> has examples of this</p>
2
2016-10-09T08:57:40Z
[ "python" ]
Securing android application made by kivy
39,939,523
<p>I've made an app using the Kivy cross-platform tool and I built the <code>apk</code> file using <code>python-for-android</code>. I want to store a secret-key locally in the application but since the <code>apk</code> file can be disassembled, How can I make sure my secret-key is safe?</p>
0
2016-10-09T02:52:18Z
40,034,392
<p>After dissembling my <code>apk</code> file, I figured out that <code>python-for-android</code> stores all of its stuff including the python installation and the project itself in a binary file named <code>private.mp3</code> so the source is not fully open and I might be good to go.</p>
0
2016-10-14T03:17:53Z
[ "android", "python", "security", "kivy" ]
ImportError: No module named yaml
39,939,541
<p>I am very new to PyDev and Python, though I have used Eclipse but I did't do much with it. So I am having some trouble with importing yaml in my Flask project. </p> <p>I install yaml and I can import it from the terminal. But I can't import it when I try to run the project in the eclipse</p> <pre><code>import yaml ImportError: No module named yaml </code></pre> <p>What is the way of importing or setting yaml library to my eclipse flask project ? </p>
-2
2016-10-09T02:55:16Z
40,055,486
<p>Run this from both eclipse and the commandline: </p> <pre><code>import sys; print(sys.executable) </code></pre> <p>Do you get the same result for both?</p> <p>using this statements help me to understand I was using different interpreters which are located in my system. thank you @shuttle87</p>
0
2016-10-15T05:49:15Z
[ "python", "eclipse", "flask", "yaml", "pydev" ]
Python generator doesn't iterate
39,939,547
<p>I am trying to do a tree traversal but the problem is the yield returns a generator object but I am not able to iterate the generator object. I am very new to python, so any help will be appreciated.</p> <pre><code>def inorder_keys(self): try: if self.flag: self.head = self.root self.head_key = self.root_key self.flag = False if self.head.left is not None: self.head_key = self.head.left self.head = self.dict_of_keys[self.head_key] BinarySearchTreeDict.inorder_keys(self) else: yield self.head_key yield self.head.parent #print(self.head_key) #print(self.head.parent) temp = self.head.parent self.head = self.dict_of_keys[temp] self.head = self.dict_of_keys[self.head.right] BinarySearchTreeDict.inorder_keys(self) except KeyError: self.flag = True pass try: x = object01.inorder_keys() print(''.join(x)) except Exception as e: print(str(e)) </code></pre> <p>Output:</p> <pre><code>C:\Python34\python.exe "...\output.py" Process finished with exit code 0 </code></pre>
0
2016-10-09T02:57:00Z
39,940,156
<p>So, your data structure seems awfully weird to me, but here is the general pattern that you want to use:</p> <pre><code>def inorder_keys(self): if self.head.left is not None: yield from self.head.left.inorder_keys() yield self.head_key if self.head.right is not None: yield from self.head.right.inorder_keys() </code></pre> <p>And that’s it if I am understanding your data structure correctly.</p>
0
2016-10-09T04:55:19Z
[ "python", "python-3.x" ]
How to get last OPTION from SELECT list using XPath - Scrapy
39,939,553
<p>I am using this selector but it is giving error</p> <p><code>//*[@id="quantity"]/option/[last()-1]</code></p> <p>How do I select last OPTION?</p> <p>I am using Scrapy Framework.</p>
0
2016-10-09T02:58:21Z
39,939,583
<p>You have an extra <code>/</code> before the <code>[</code> making the XPath expression <em>invalid</em>. Remove it:</p> <pre><code>//*[@id="quantity"]/option[last()-1] </code></pre> <p>Note that you can also solve it using Python/Scrapy:</p> <pre><code>response.xpath('//*[@id="quantity"]/option')[-1].extract() </code></pre> <p>Or, in a <em>CSS selector</em> form:</p> <pre><code>response.css('#quantity option:last-child').extract_first() response.css('#quantity option')[-1].extract() </code></pre>
2
2016-10-09T03:03:40Z
[ "python", "scrapy" ]
find a substring in a string python
39,939,564
<p>This might be a beginner question but I can't seem to find the answer anywhere</p> <p>How do I search and return a substring from another string in which the charachers are in a different order ?</p> <p>When I check with the code below it seems to give the right answer but I'm trying to print it rather getting True or False and also, when I submit it, it says "Incorrect. Your submission did not return the correct result for the input ('UdaciousUdacitee', 'Udacity'). Your submission passed 3 out of 4 test cases:" .... I'm confused..and I've been wrapping my brain around for 3 hours or so.</p> <p>Thank you</p> <pre><code>Test case 1: False Test case 2: True Test case 3: True Test case 4: True </code></pre> <p>More precisely:</p> <pre><code>def fix_machine(debris, product): if debris.find(product): return product else: print("Give me something that's not useless next time.") print "Test case 1: ", fix_machine('UdaciousUdacitee', 'Udacity') == "Give me something that's not useless next time." print "Test case 2: ", fix_machine('buy me dat Unicorn', 'Udacity') == 'Udacity' print "Test case 3: ", fix_machine('AEIOU and sometimes y... c', 'Udacity') == 'Udacity' print "Test case 4: ", fix_machine('wsx0-=mttrhix', 't-shirt') == 't-shirt' </code></pre>
-3
2016-10-09T03:00:12Z
39,939,586
<p>You're <code>print()</code>ing the <code>else</code> case. I think you meant to return that string. (at least according to your assertion code)</p>
0
2016-10-09T03:04:02Z
[ "python", "string", "substring" ]
find a substring in a string python
39,939,564
<p>This might be a beginner question but I can't seem to find the answer anywhere</p> <p>How do I search and return a substring from another string in which the charachers are in a different order ?</p> <p>When I check with the code below it seems to give the right answer but I'm trying to print it rather getting True or False and also, when I submit it, it says "Incorrect. Your submission did not return the correct result for the input ('UdaciousUdacitee', 'Udacity'). Your submission passed 3 out of 4 test cases:" .... I'm confused..and I've been wrapping my brain around for 3 hours or so.</p> <p>Thank you</p> <pre><code>Test case 1: False Test case 2: True Test case 3: True Test case 4: True </code></pre> <p>More precisely:</p> <pre><code>def fix_machine(debris, product): if debris.find(product): return product else: print("Give me something that's not useless next time.") print "Test case 1: ", fix_machine('UdaciousUdacitee', 'Udacity') == "Give me something that's not useless next time." print "Test case 2: ", fix_machine('buy me dat Unicorn', 'Udacity') == 'Udacity' print "Test case 3: ", fix_machine('AEIOU and sometimes y... c', 'Udacity') == 'Udacity' print "Test case 4: ", fix_machine('wsx0-=mttrhix', 't-shirt') == 't-shirt' </code></pre>
-3
2016-10-09T03:00:12Z
39,939,669
<p>You used <code>str.find()</code> wrong.</p> <pre><code>"It determines if string str occurs in string, or in a substring of string if starting index beg and ending index end are given." </code></pre> <p>It will consider the order, which is not what you want. Change your <code>fix_machine</code> to:</p> <pre><code>def fix_machine(debris, product): charNumInDebris = dict() charNumInProduct = dict() for c in debris: if c in charNumInDebris: charNumInDebris[c] += 1 else: charNumInDebris[c] = 1 for c in product: if c in charNumInProduct: charNumInProduct[c] += 1 else: charNumInProduct[c] = 1 for c in charNumInProduct: if not (c in charNumInDebris and charNumInDebris[c] &gt;= charNumInProduct[c]): return "Give me something that's not useless next time." return product </code></pre>
0
2016-10-09T03:20:20Z
[ "python", "string", "substring" ]
Pandas DataFrame (TypeError: Empty 'DataFrame': no numeric data to plot)
39,939,589
<p>I'm trying to learn how to use pandas and im trying to display a plot showing the total births by sex &amp; year.</p> <p>[1] [<a href="http://i.stack.imgur.com/R7Vz7.png]" rel="nofollow">http://i.stack.imgur.com/R7Vz7.png]</a> (Cant figure out why there's another column called sex</p> <p>but this image above the data im trying to plot</p> <p>and keep getting TypeError: Empty 'DataFrame': no numeric data to plot)</p> <p>This is what my code looks like</p> <p>[2] <a href="http://i.stack.imgur.com/FbZmM.png" rel="nofollow">http://i.stack.imgur.com/FbZmM.png</a></p>
0
2016-10-09T03:04:21Z
39,939,746
<p>This is happening because during the pivot the dataFrame becomes multi-indexed. There are no columns with values to plot against eachother. You can use <code>df.reset_index()</code> to set the multiple indexes as columns, and then plot their values.</p>
0
2016-10-09T03:32:08Z
[ "python", "csv", "plot", "dataframe" ]
Save Different Channels of Ycbcr as seperate images | Python
39,939,595
<p>I need to apply some transformations to the individual channels of the Ycbcr color space.</p> <p>I have an tiff format image as the source and I need to convert it to ycbcr color space. I have not been able to successfully save the different channels as separate images. I have been only able to extract the luminescence channel using this code:</p> <pre><code>import numpy import Image as im image = im.open('1.tiff') ycbcr = image.convert('YCbCr') B = numpy.ndarray((image.size[1], image.size[0], 3), 'u1', ycbcr.tobytes()) im.fromarray(B[:,:,0], "L").show() </code></pre> <p>Can someone pls help.</p> <p>Thank you </p>
0
2016-10-09T03:05:06Z
39,940,287
<p>Here is my code:</p> <pre><code>import numpy import Image as im image = im.open('1.tiff') ycbcr = image.convert('YCbCr') # output of ycbcr.getbands() put in order Y = 0 Cb = 1 Cr = 2 YCbCr=list(ycbcr.getdata()) # flat list of tuples # reshape imYCbCr = numpy.reshape(YCbCr, (image.size[1], image.size[0], 3)) # Convert 32-bit elements to 8-bit imYCbCr = imYCbCr.astype(numpy.uint8) # now, display the 3 channels im.fromarray(imYCbCr[:,:,Y], "L").show() im.fromarray(imYCbCr[:,:,Cb], "L").show() im.fromarray(imYCbCr[:,:,Cr], "L").show() </code></pre>
0
2016-10-09T05:18:43Z
[ "python", "python-imaging-library", "color-space" ]
Save Different Channels of Ycbcr as seperate images | Python
39,939,595
<p>I need to apply some transformations to the individual channels of the Ycbcr color space.</p> <p>I have an tiff format image as the source and I need to convert it to ycbcr color space. I have not been able to successfully save the different channels as separate images. I have been only able to extract the luminescence channel using this code:</p> <pre><code>import numpy import Image as im image = im.open('1.tiff') ycbcr = image.convert('YCbCr') B = numpy.ndarray((image.size[1], image.size[0], 3), 'u1', ycbcr.tobytes()) im.fromarray(B[:,:,0], "L").show() </code></pre> <p>Can someone pls help.</p> <p>Thank you </p>
0
2016-10-09T03:05:06Z
39,940,615
<p>Simply use the <a href="http://pillow.readthedocs.io/en/3.4.x/reference/Image.html#PIL.Image.Image.split" rel="nofollow"><code>.split()</code></a> method to split the image into different channels (called <em>bands</em> in PIL). No need to use numpy.</p> <pre><code>(y, cb, cr) = ycbcr.split() # y, cb and cr are all in "L" mode. </code></pre> <p>After you have done the transformations, use <a href="http://pillow.readthedocs.io/en/3.4.x/reference/Image.html#PIL.Image.merge" rel="nofollow"><code>PIL.Image.merge()</code></a> to combine them again.</p> <pre><code>ycbcr2 = im.merge('YCbCr', (y, cb, cr)) </code></pre>
0
2016-10-09T06:17:29Z
[ "python", "python-imaging-library", "color-space" ]
How to split this string to dict with python?
39,939,610
<p><strong>String</strong> </p> <pre><code>string1 = '"{ABCD-1234-3E3F},MEANING1","{ABCD-1B34-3X5F},MEANING2","{XLMN-2345-KFDE},WHITE"' </code></pre> <p><strong>Expected Result</strong> </p> <pre><code>dict1 = {'{ABCD-1234-3E3F}' : 'MEANING1', '{ABCD-1B34-3X5F}' : 'MEANING2', '{XLMN-2345-KFDE}' : 'WHITE'} </code></pre> <p>Perhaps it is simple question,<br> Is there any easy method to split <code>string1</code> to <code>dict1</code>?</p>
0
2016-10-09T03:07:59Z
39,939,655
<pre><code>string1 = '"{ABCD-1234-3E3F},MEANING1","{ABCD-1B34-3X5F},MEANING2","{XLMN-2345-KFDE},WHITE"' elements = string1.replace('"','').split(',') dict(zip(elements[::2],elements[1::2])) </code></pre> <p>You can first split the original string and extract elements from it. Now you can pair element in odd and even positions and turn them into a dict.</p>
1
2016-10-09T03:15:56Z
[ "python", "split" ]
How to split this string to dict with python?
39,939,610
<p><strong>String</strong> </p> <pre><code>string1 = '"{ABCD-1234-3E3F},MEANING1","{ABCD-1B34-3X5F},MEANING2","{XLMN-2345-KFDE},WHITE"' </code></pre> <p><strong>Expected Result</strong> </p> <pre><code>dict1 = {'{ABCD-1234-3E3F}' : 'MEANING1', '{ABCD-1B34-3X5F}' : 'MEANING2', '{XLMN-2345-KFDE}' : 'WHITE'} </code></pre> <p>Perhaps it is simple question,<br> Is there any easy method to split <code>string1</code> to <code>dict1</code>?</p>
0
2016-10-09T03:07:59Z
39,939,666
<p>If you are looking for a one-liner, this will work:</p> <pre><code>&gt;&gt;&gt; dict(tuple(x.split(',')) for x in string1[1:-1].split('","')) {'{ABCD-1B34-3X5F}': 'MEANING2', '{XLMN-2345-KFDE}': 'WHITE', '{ABCD-1234-3E3F}': 'MEANING1'} </code></pre>
5
2016-10-09T03:19:11Z
[ "python", "split" ]
How to split this string to dict with python?
39,939,610
<p><strong>String</strong> </p> <pre><code>string1 = '"{ABCD-1234-3E3F},MEANING1","{ABCD-1B34-3X5F},MEANING2","{XLMN-2345-KFDE},WHITE"' </code></pre> <p><strong>Expected Result</strong> </p> <pre><code>dict1 = {'{ABCD-1234-3E3F}' : 'MEANING1', '{ABCD-1B34-3X5F}' : 'MEANING2', '{XLMN-2345-KFDE}' : 'WHITE'} </code></pre> <p>Perhaps it is simple question,<br> Is there any easy method to split <code>string1</code> to <code>dict1</code>?</p>
0
2016-10-09T03:07:59Z
39,940,011
<p>And here another one-liner alternative:</p> <pre><code>&gt;&gt;&gt; string1 = '"{ABCD-1234-3E3F},MEANING1","{ABCD-1B34-3X5F},MEANING2","{XLMN-2345-KFDE},WHITE"' &gt;&gt;&gt; dict((nm, v) for nm,v in [pair.split(',') for pair in eval(string1)]) &gt;&gt;&gt; {'{ABCD-1234-3E3F}': 'MEANING1', '{ABCD-1B34-3X5F}': 'MEANING2', '{XLMN-2345-KFDE}': 'WHITE'} </code></pre>
0
2016-10-09T04:25:31Z
[ "python", "split" ]
Filter one array according to data in another array
39,939,627
<p>I have two arrays of random numbers, <code>X</code> and <code>Y</code>. X represents x-coordinates and <code>Y</code> represents y-coordinates. I want to filter <code>X</code> such that I only keep indices <code>i</code> of <code>X</code> where:</p> <pre><code>X[i]^2 + Y[i]^2 &lt; 1 </code></pre> <p>I know how to filter with values in 1 array but since I need to use 2, I am not sure what to do. I am not allowed to use loops of any kind.</p>
0
2016-10-09T03:12:17Z
39,939,675
<p>This will do:</p> <pre><code>X_filtered = X[X**2 + Y**2 &lt; 1] </code></pre> <p><code>X**2 + Y**2 &lt; 1</code> returns a boolean array and accessing <code>X</code> on this array returns <code>X</code> only at the indices equal to <code>True</code>.</p>
0
2016-10-09T03:21:49Z
[ "python", "arrays", "numpy" ]
Filter one array according to data in another array
39,939,627
<p>I have two arrays of random numbers, <code>X</code> and <code>Y</code>. X represents x-coordinates and <code>Y</code> represents y-coordinates. I want to filter <code>X</code> such that I only keep indices <code>i</code> of <code>X</code> where:</p> <pre><code>X[i]^2 + Y[i]^2 &lt; 1 </code></pre> <p>I know how to filter with values in 1 array but since I need to use 2, I am not sure what to do. I am not allowed to use loops of any kind.</p>
0
2016-10-09T03:12:17Z
39,939,692
<pre><code>for ind,(a,b) in enumerate(zip(x,y)) : if (a**2 + b**2) &lt; 1 : print ind </code></pre>
-1
2016-10-09T03:24:58Z
[ "python", "arrays", "numpy" ]
Filter one array according to data in another array
39,939,627
<p>I have two arrays of random numbers, <code>X</code> and <code>Y</code>. X represents x-coordinates and <code>Y</code> represents y-coordinates. I want to filter <code>X</code> such that I only keep indices <code>i</code> of <code>X</code> where:</p> <pre><code>X[i]^2 + Y[i]^2 &lt; 1 </code></pre> <p>I know how to filter with values in 1 array but since I need to use 2, I am not sure what to do. I am not allowed to use loops of any kind.</p>
0
2016-10-09T03:12:17Z
39,939,750
<p><code>X = [X[i] for i in range(len(X)) if X[i]**2 + Y[i]**2 &lt; 1]</code></p> <p>this will filter X so that X only contains those that match your filtering criteria. </p> <p>Note that this does use looping via comprehension, so I am not quite sure how this is to be done without looping. </p>
-1
2016-10-09T03:33:12Z
[ "python", "arrays", "numpy" ]
Filter one array according to data in another array
39,939,627
<p>I have two arrays of random numbers, <code>X</code> and <code>Y</code>. X represents x-coordinates and <code>Y</code> represents y-coordinates. I want to filter <code>X</code> such that I only keep indices <code>i</code> of <code>X</code> where:</p> <pre><code>X[i]^2 + Y[i]^2 &lt; 1 </code></pre> <p>I know how to filter with values in 1 array but since I need to use 2, I am not sure what to do. I am not allowed to use loops of any kind.</p>
0
2016-10-09T03:12:17Z
39,939,761
<p>So I think these arrays are too large to loop? If you only want to <strong>keep</strong> the indices for later, try <a href="https://wiki.python.org/moin/Generators" rel="nofollow">Generators</a>:</p> <pre><code>def X_indices_filterd(X, Y): for i in enumerate(X): if (X[i] ** 2 + Y[i] ** 2 &lt; 1) yield i </code></pre>
-1
2016-10-09T03:35:13Z
[ "python", "arrays", "numpy" ]
Writing a Pandas Dataframe to MySQL
39,939,716
<p>I'm trying to write a Python Pandas Dataframe to a MySQL database. I realize that it's possible to use sqlalchemy <a href="http://stackoverflow.com/questions/37627520/insert-pandas-dataframe-to-mysql-using-sqlalchemy">for this</a>, but I'm wondering if there is another way that may be easier, preferably already built into Pandas. I've spent quite some time trying to do it with a For loop, but it's not realiable. </p> <p>If anyone knows of a better way, it would be greatly appreciated.</p> <p>Thanks a lot!</p>
1
2016-10-09T03:27:52Z
39,947,371
<p>The other option to <strong>sqlalchemy</strong> can be used <strong>to_sql</strong> but in future released will be deprecated but now in version <strong>pandas 0.18.1 documentation</strong> is still active. </p> <p>According to pandas documentation <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_sql.html" rel="nofollow">pandas.DataFrame.to_sql</a> you can use following syntax:</p> <pre><code>DataFrame.to_sql(name, con, flavor='sqlite', schema=None, if_exists='fail', index=True, index_label=None, chunksize=None, dtype=None) </code></pre> <p>you specify the con <strong>type/mode</strong> and flavor <strong>‘mysql’</strong>, here is some description:</p> <blockquote> <p>con : SQLAlchemy engine or DBAPI2 connection (legacy mode) Using SQLAlchemy makes it possible to use any DB supported by that library. If a DBAPI2 object, only sqlite3 is supported.</p> <p>flavor : {‘sqlite’, ‘mysql’}, default ‘sqlite’ The flavor of SQL to use. Ignored when using SQLAlchemy engine. ‘mysql’ is deprecated and will be removed in future versions, but it will be further supported through SQLAlchemy engines.</p> </blockquote>
0
2016-10-09T19:00:07Z
[ "python", "mysql", "dataframe" ]
Sum data points from individual pandas dataframes in a summary dataframe based on custom (and possibly overlapping) bins
39,939,723
<p>I have many dataframes with individual counts (e.g. <code>df_boston</code> below). Each row defines a data point that is uniquely identified by its <code>marker</code> and its <code>point</code>. I have a summary dataframe (<code>df_inventory_master</code>) that has custom bins (the <code>point</code>s above map to the <code>Begin</code>-<code>End</code> coordinates in the master). I want to add a column to this dataframe for each individual city that sums the counts from that city in a new column. An example is shown.</p> <p>Two quirks are that the the bins in the master frame can be overlapping (the count should be added to both) and that some counts may not fall in the master (the count should be ignored).</p> <p>I can do this in pure Python but since the data are in dataframes it would be helpful and likely faster to do the manipulations in <code>pandas</code>. I'd appreciate any tips here!</p> <p>This is the master frame:</p> <pre><code>&gt;&gt;&gt; df_inventory_master = pd.DataFrame({'Marker': [1, 1, 1, 2], ... 'Begin': [100, 300, 500, 100], ... 'End': [200, 600, 900, 250]}) &gt;&gt;&gt; df_inventory_master Begin End Marker 0 100 200 1 1 300 600 1 2 500 900 1 3 100 250 2 </code></pre> <p>This is data for one city:</p> <pre><code>&gt;&gt;&gt; df_boston = pd.DataFrame({'Marker': [1, 1, 1, 1], ... 'Point': [140, 180, 250, 500], ... 'Count': [14, 600, 1000, 700]}) &gt;&gt;&gt; df_boston Count Marker Point 0 14 1 140 1 600 1 180 2 1000 1 250 3 700 1 500 </code></pre> <p>This is the desired output.<br> - Note that the count of 700 (Marker 1, Point 500) falls in 2 master bins and is counted for both.<br> - Note that the count of 1000 (Marker 1, Point 250) does not fall in a master bin and is not counted.<br> - Note that nothing maps to Marker 2 because <code>df_boston</code> does not have any Marker 2 data. </p> <pre><code>&gt;&gt;&gt; desired_frame Begin End Marker boston 0 100 200 1 614 1 300 600 1 700 2 500 900 1 700 3 100 250 2 0 </code></pre> <p>What I've tried: I looked at the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.cut.html" rel="nofollow">pd.cut()</a> function, but with the nature of the bins overlapping, and in some cases absent, this does not seem to fit. I can add the column filled with 0 values to get part of the way there but then will need to find a way to sum the data in each frame, using bins defined in the master.</p> <pre><code>&gt;&gt;&gt; df_inventory_master['boston'] = pd.Series([0 for x in range(len(df_inventory_master.index))], index=df_inventory_master.index) &gt;&gt;&gt; df_inventory_master Begin End Marker boston 0 100 200 1 0 1 300 600 1 0 2 500 900 1 0 3 100 250 2 0 </code></pre>
0
2016-10-09T03:29:34Z
39,943,965
<p>Here is how I approached it, basically a *sql style left join * using the pandas merge operation, then apply() across the row axis, with a lambda to decide if the individual records are in the band or not, finally groupby and sum: </p> <pre><code>df_merged = df_inventory_master.merge(df_boston, on=['Marker'],how='left') # logical overwrite of count df_merged['Count'] = df_merged.apply(lambda x: x['Count'] if x['Begin'] &lt;= x['Point'] &lt;= x['End'] else 0 , axis=1 ) df_agged = df_merged[['Begin','End','Marker','Count']].groupby(['Begin','End','Marker']).sum() df_agged_resorted = df_agged.sort_index(level = ['Marker','Begin','End']) df_agged_resorted = df_agged_resorted.astype(np.int) df_agged_resorted.columns =['boston'] # rename the count column to boston. print df_agged_resorted </code></pre> <p>And the result is</p> <pre><code> boston Begin End Marker 100 200 1 614 300 600 1 700 500 900 1 700 100 250 2 0 </code></pre>
1
2016-10-09T13:06:57Z
[ "python", "python-3.x", "pandas", "dataframe" ]
WAV files being saved in wrong order
39,939,724
<p>I have a program that loops over a for loop, and saves sine waves as wav files to create a range of tones for a keyboard. The loop goes from -int to +int, and saves these WAV files in each iteration. The only problem is that when it gets to around x = 2, the file order is messed up. I don't know why this happens or how to fix it.</p> <pre><code>out_int = 0 for x in xrange(-43, 47, 1): CFreq = CFreq * 2**(x/12.) out_int += 1 . . . wavdata = np.zeros(len(data), np.int16) wavdata[:] = data / max(data) * 2**15 wavfile = wave.open("WavFiles/Modes_%02d_.wav" % (out_int), "wb") </code></pre> <p>Theres a lot of data going into these files, which is why I'm guessing it takes longer to produce some notes and save it before saving the previous samples. The output frequency for each sample is correct but they sound off.</p> <p>Is there anyway to make sure the code writes and saves each file first before going to the next? I tried changing the order for the loop to go from positive to negative values, but then the samples at the negative iteration were being messed up.</p>
1
2016-10-09T03:30:00Z
39,979,197
<p>There is not enough code to replicate, However, here is an example using enumerate that will put the subsequent xrange elements in order. Perhaps this will aid in keeping your wavefiles in sequence. </p> <pre><code>for i, x in enumerate(xrange(-43, 47, 1)): file_name = "file{0}-{1}.wav".format(i, x) print file_name </code></pre> <p>Output:</p> <pre><code>Python 2.7.9 (default, Dec 10 2014, 12:24:55) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. &gt;&gt;&gt; ================================ RESTART ================================ &gt;&gt;&gt; file0--43.wav file1--42.wav file2--41.wav file3--40.wav | | file86-43.wav file87-44.wav file88-45.wav file89-46.wav </code></pre>
0
2016-10-11T14:09:17Z
[ "python", "for-loop", "audio", "wav" ]
Why aren't all the base classes constructors being called?
39,939,737
<p>In Python 2.7.10</p> <pre><code>class OneMixin(object): def __init__(self): # super(OneMixin, self).__init__() print "one mixin" class TwoMixin(object): def __init__(self): # super(TwoMixin, self).__init__() print "two mixin" class Account(OneMixin, TwoMixin): def __init__(self): super(Account, self).__init__() print "account" </code></pre> <p>The Account.mro() is: <code>[&lt;class 'Account'&gt;, &lt;class 'OneMixin'&gt;, &lt;class 'TwoMixin'&gt;, &lt;type 'object'&gt;]</code></p> <p>Although every class is listed in the MRO, "two mixin" is not printed.</p> <p>If I uncomment the super calls in OneMixin and TwoMixin, the MRO is exactly the same, but the "two mixin" IS printed.</p> <p>Why the difference? I would expect every thing in the MRO to be called.</p>
1
2016-10-09T03:31:24Z
39,939,819
<p>This is because <code>super</code> is used to delegate the calls to either parent or sibling class of a type. <a href="https://docs.python.org/2.7/library/functions.html#super" rel="nofollow">Python documentation</a> has following description of the second use case:</p> <blockquote> <p>The second use case is to support cooperative multiple inheritance in a dynamic execution environment. This use case is unique to Python and is not found in statically compiled languages or languages that only support single inheritance. This makes it possible to implement “diamond diagrams” where multiple base classes implement the same method. Good design dictates that this method have the same calling signature in every case (because the order of calls is determined at runtime, because that order adapts to changes in the class hierarchy, and because that order can include sibling classes that are unknown prior to runtime).</p> </blockquote> <p>If you remove the <code>super</code> call from <code>OneMixin</code> there's nothing delegating the call to the next type in MRO.</p>
1
2016-10-09T03:46:21Z
[ "python", "python-2.7" ]
Why aren't all the base classes constructors being called?
39,939,737
<p>In Python 2.7.10</p> <pre><code>class OneMixin(object): def __init__(self): # super(OneMixin, self).__init__() print "one mixin" class TwoMixin(object): def __init__(self): # super(TwoMixin, self).__init__() print "two mixin" class Account(OneMixin, TwoMixin): def __init__(self): super(Account, self).__init__() print "account" </code></pre> <p>The Account.mro() is: <code>[&lt;class 'Account'&gt;, &lt;class 'OneMixin'&gt;, &lt;class 'TwoMixin'&gt;, &lt;type 'object'&gt;]</code></p> <p>Although every class is listed in the MRO, "two mixin" is not printed.</p> <p>If I uncomment the super calls in OneMixin and TwoMixin, the MRO is exactly the same, but the "two mixin" IS printed.</p> <p>Why the difference? I would expect every thing in the MRO to be called.</p>
1
2016-10-09T03:31:24Z
39,939,825
<p>The reason is that you're overriding the <code>__init__</code> method of the parent class. The method resolution order will be the same, regardless of what is in your <code>__init__</code> method.</p> <p>The way <code>super</code> works is that it will pass it down to the next class down the line in the method resolution order. By commenting out that line in <code>OneMixin</code>, you break the chain. <code>super</code> is designed for <strong>cooperative</strong> inheritance. </p> <p>Also, <code>__init__</code> is not truly a class constructor, either. This may trip you up if you think of it as you would a constructor in other languages.</p>
1
2016-10-09T03:47:51Z
[ "python", "python-2.7" ]
How do you print a function that returns a request in Python?
39,939,741
<p>I have a function that gets the profile data of an user:</p> <p><strong>API.py</strong></p> <pre><code>def getProfileData(self): data = json.dumps({ '_uuid' : self.uuid, '_uid' : self.username_id, '_csrftoken' : self.token }) return self.SendRequest('accounts/current_user/?edit=true', self.generateSignature(data)) </code></pre> <p>I want to print the returned request in the terminal, so I did this:</p> <p><strong>test.py</strong></p> <pre><code>from API import API API = API("username", "password") API.login() # login print(API.getProfileData()) </code></pre> <p>But nothing is logged in the console.</p> <p>Maybe I'm doing it the JavaScript way, since that's my background.</p> <p>What's the correct way to do it?</p> <p><strong>EDIT:</strong></p> <p>This is what's inside <code>SendRequest</code>:</p> <pre><code>def SendRequest(self, endpoint, post = None, login = False): if (not self.isLoggedIn and not login): raise Exception("Not logged in!\n") return; self.s.headers.update ({'Connection' : 'close', 'Accept' : '*/*', 'Content-type' : 'application/x-www-form-urlencoded; charset=UTF-8', 'Cookie2' : '$Version=1', 'Accept-Language' : 'en-US', 'User-Agent' : self.USER_AGENT}) if (post != None): # POST response = self.s.post(self.API_URL + endpoint, data=post) # , verify=False else: # GET response = self.s.get(self.API_URL + endpoint) # , verify=False if response.status_code == 200: self.LastResponse = response self.LastJson = json.loads(response.text) return True else: print ("Request return " + str(response.status_code) + " error!") # for debugging try: self.LastResponse = response self.LastJson = json.loads(response.text) except: pass return False def getTotalFollowers(self,usernameId): followers = [] next_max_id = '' while 1: self.getUserFollowers(usernameId,next_max_id) temp = self.LastJson for item in temp["users"]: followers.append(item) if temp["big_list"] == False: return followers next_max_id = temp["next_max_id"] def getTotalFollowings(self,usernameId): followers = [] next_max_id = '' while 1: self.getUserFollowings(usernameId,next_max_id) temp = self.LastJson for item in temp["users"]: followers.append(item) if temp["big_list"] == False: return followers next_max_id = temp["next_max_id"] def getTotalUserFeed(self, usernameId, minTimestamp = None): user_feed = [] next_max_id = '' while 1: self.getUserFeed(usernameId, next_max_id, minTimestamp) temp = self.LastJson for item in temp["items"]: user_feed.append(item) if temp["more_available"] == False: return user_feed next_max_id = temp["next_max_id"] </code></pre>
4
2016-10-09T03:31:45Z
39,940,117
<p>If all you want to do is print the response that you get back, you can do that in <code>SendRequest</code>, but I suspect tha tyour real problem is that you are self-serializing your post data when <code>requests</code> does that for you. In any case, since your question is about printing:</p> <pre><code> if response.status_code == 200: print('Yay, my response was: %s' % response.content) self.LastResponse = response self.LastJson = json.loads(response.text) return True else: print ("Request return " + str(response.status_code) + " error!") # for debugging try: self.LastResponse = response self.LastJson = json.loads(response.text) except: pass return False </code></pre>
1
2016-10-09T04:46:35Z
[ "python" ]
How to get a numpy ndarray of integers from a file with header?
39,939,773
<p>I have a plain text file (.txt) with the following content.</p> <pre><code>Matrix Header. 6 11 0 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 0 1 1 1 1 1 1 1 1 0 0 1 1 1 1 1 0 0 0 0 1 1 1 0 0 0 0 1 1 1 0 0 1 1 1 1 1 1 1 0 0 1 1 1 1 0 1 1 0 6 rows, 11 columns </code></pre> <p>I need obtain a numpy ndarray of integers as below:</p> <pre><code>[[0 1 1 1 1 1 1 1 1 1 1] [1 0 1 1 1 1 0 1 1 1 1] [1 1 1 1 0 0 1 1 1 1 1] [0 0 0 0 1 1 1 0 0 0 0] [1 1 1 0 0 1 1 1 1 1 1] [1 0 0 1 1 1 1 0 1 1 0]] </code></pre> <p>I tried the following strategy</p> <pre><code>import pandas import numpy data = pandas.read_table(path, skiprows= 2) data = data.values print(data) </code></pre> <p>But the resulting ndarray isn't in the correct format.</p> <pre><code>[['0 1 1 1 1 1 1 1 1 1 1 '] ['1 0 1 1 1 1 0 1 1 1 1 '] ['1 1 1 1 0 0 1 1 1 1 1 '] ['0 0 0 0 1 1 1 0 0 0 0 '] ['1 1 1 0 0 1 1 1 1 1 1 '] ['1 0 0 1 1 1 1 0 1 1 0 ']] </code></pre> <p>Can anybody help me?</p>
2
2016-10-09T03:37:29Z
39,939,861
<p>A simple solution is to explicitly ignore the lines you don't need:</p> <pre><code>with open(path) as infile: lines = infile.readlines() np.loadtxt(lines[2:-2]) del lines # if you want to immediately release the memory </code></pre> <p>This directly gives you what you want, assuming the header and footer are always two lines each.</p>
1
2016-10-09T03:53:47Z
[ "python", "numpy", "multidimensional-array" ]
How to get a numpy ndarray of integers from a file with header?
39,939,773
<p>I have a plain text file (.txt) with the following content.</p> <pre><code>Matrix Header. 6 11 0 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 0 1 1 1 1 1 1 1 1 0 0 1 1 1 1 1 0 0 0 0 1 1 1 0 0 0 0 1 1 1 0 0 1 1 1 1 1 1 1 0 0 1 1 1 1 0 1 1 0 6 rows, 11 columns </code></pre> <p>I need obtain a numpy ndarray of integers as below:</p> <pre><code>[[0 1 1 1 1 1 1 1 1 1 1] [1 0 1 1 1 1 0 1 1 1 1] [1 1 1 1 0 0 1 1 1 1 1] [0 0 0 0 1 1 1 0 0 0 0] [1 1 1 0 0 1 1 1 1 1 1] [1 0 0 1 1 1 1 0 1 1 0]] </code></pre> <p>I tried the following strategy</p> <pre><code>import pandas import numpy data = pandas.read_table(path, skiprows= 2) data = data.values print(data) </code></pre> <p>But the resulting ndarray isn't in the correct format.</p> <pre><code>[['0 1 1 1 1 1 1 1 1 1 1 '] ['1 0 1 1 1 1 0 1 1 1 1 '] ['1 1 1 1 0 0 1 1 1 1 1 '] ['0 0 0 0 1 1 1 0 0 0 0 '] ['1 1 1 0 0 1 1 1 1 1 1 '] ['1 0 0 1 1 1 1 0 1 1 0 ']] </code></pre> <p>Can anybody help me?</p>
2
2016-10-09T03:37:29Z
39,940,289
<p>To avoid the error that might occur because of the text at the end, you can use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.genfromtxt.html" rel="nofollow"><code>numpy.genfromtxt</code></a> with the <code>max_rows</code> argument. For example,</p> <pre><code>In [26]: with open(filename, 'rb') as f: ...: f.readline() # skip the header ...: nrows, ncols = [int(field) for field in f.readline().split()] ...: data = np.genfromtxt(f, dtype=int, max_rows=nrows) ...: In [27]: data Out[27]: array([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1], [1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1], [0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0], [1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1], [1, 0, 0, 1, 1, 1, 1, 0, 1, 1, 0]]) </code></pre> <p>(I opened the file in binary mode to avoid a bytes/str problem that <code>genfromtxt</code> has in Python 3.)</p>
1
2016-10-09T05:19:37Z
[ "python", "numpy", "multidimensional-array" ]
How do I create an animated gif in Python using Wand?
39,939,780
<p>The instructions are simple enough in the <a href="http://docs.wand-py.org/en/0.4.1/guide/sequence.html" rel="nofollow">Wand docs</a> for <em>reading</em> a sequenced image (e.g. animated gif, icon file, etc.):</p> <pre><code>&gt;&gt;&gt; from wand.image import Image &gt;&gt;&gt; with Image(filename='sequence-animation.gif') as image: ... len(image.sequence) </code></pre> <p>...but I'm not sure how to <em>create</em> one. </p> <p>In Ruby this is easy using <strong>RMagick</strong>, since you have <code>ImageList</code>s. (see <a href="https://gist.github.com/dguzzo/99bbca3df827df475f768383a1b04102" rel="nofollow">my gist</a> for an example.)</p> <p>I tried creating an <code>Image</code> (as the "container") and instantiating each <code>SingleImage</code> with an image path, but I'm pretty sure that's wrong, especially since the constructor documentation for <code>SingleImage</code> doesn't look for use by the end-user.</p> <p>I also tried creating a <code>wand.sequence.Sequence</code> and going from that angle, but hit a dead-end as well. I feel very lost.</p>
3
2016-10-09T03:38:37Z
40,088,327
<p>The best examples are located in the unit-tests shipped with the code. <a href="https://github.com/dahlia/wand/blob/master/tests/sequence_test.py" rel="nofollow"><code>wand/tests/sequence_test.py</code></a> for example.</p> <p>For creating an animated gif with wand, remember to load the image into the sequence, and then set the additional delay/optimize handling after all frames are loaded.</p> <pre class="lang-py prettyprint-override"><code>from wand.image import Image with Image() as wand: # Add new frames into sequance with Image(filename='1.png') as one: wand.sequence.append(one) with Image(filename='2.png') as two: wand.sequence.append(two) with Image(filename='3.png') as three: wand.sequence.append(three) # Create progressive delay for each frame for cursor in range(3): with wand.sequence[cursor] as frame: frame.delay = 10 * (cursor + 1) # Set layer type wand.type = 'optimize' wand.save(filename='animated.gif') </code></pre> <p><a href="https://i.stack.imgur.com/do522.gif" rel="nofollow"><img src="https://i.stack.imgur.com/do522.gif" alt="output animated.gif"></a></p>
2
2016-10-17T13:55:56Z
[ "python", "imagemagick", "animated-gif", "wand" ]
Sorting parallel lists in python - first item descending, second item ascending
39,939,813
<p>I have two lists - one for a team name and the second for points </p> <p>I wanted to sort them based on the points without losing track of the corresponding team. I found something on SO that works great for doing this - and it sorts teams by points in descending order (most to least).</p> <p>There doesn't appear to be a sort on the second list.</p> <blockquote> <p><strong>EDIT - Original Data</strong></p> </blockquote> <pre><code>Teams Pts D Clark 0 D Dupuis 2 T Leach 2 J Schutz 0 C Hearder 2 R Pagani 0 M Cameron 2 B Hunter 0 </code></pre> <p><strong>This is what I'm using:</strong></p> <pre><code>pts, teams = zip(*sorted(zip(pts, teams), reverse=True)) i = 1 for team, num_pts in zip(teams, pts): standings = str(i) + '. ' + team + " (" + num_pts + ")" print standings i += 1 </code></pre> <p><strong>And it results in this:</strong> </p> <pre><code>1. T Leach (2) 2. M Cameron (2) 3. D Dupuis (2) 4. C Hearder (2) 5. R Pagani (0) 6. J Schutz (0) 7. D Clark (0) 8. B Hunter (0) </code></pre> <p>What I'm trying to do is to add an additional sort on team name - so if there's a tie, then it will <em>sort by names in ascending</em> order, </p> <p><strong>Like This:</strong> </p> <pre><code>1. C Hearder (2) 2. D Dupuis (2) 3. M Cameron (2) 4. T Leach (2) 5. B Hunter (0) 6. D Clark (0) 7. J Schutz (0) 8. R Pagani (0) </code></pre>
1
2016-10-09T03:45:02Z
39,939,850
<p>You have two options here. You could use <code>cmp</code> or <code>key</code> as a parameter to <code>sorted</code>.</p> <p>With a <code>cmp</code> you're defining a function which takes two arguments, the two values being compared. If the first argument is smaller than the second, return a negative number. If it is larger than the second, return a positive number. If they are equal, return 0.</p> <p>First example using <code>cmp</code>:</p> <pre><code>pts = ['2', '2', '2', '2', '2', '0', '0', '0', '0'] teams = ['T Leach', 'M Cameron', 'D Dupuis', 'C Hearder', 'R Pagani', 'J Schutz', 'D Clark', 'B Hunter'] def custom_cmp(x,y): return cmp(x[0], y[0]) or cmp(y[1], x[1]) pts, teams = zip(*sorted(zip(pts, teams), cmp=custom_cmp, reverse=True)) </code></pre> <p>The python <code>or</code> operator will return the left hand side if it evaluates to <code>True</code> (not <code>0</code> as described above), otherwise it will return the right hand side. Therefore this <code>custom_cmp</code> returns the comparison of the points from <code>x</code> to <code>y</code> if the points are not equivalent. Otherwise it compares the teams from <code>y</code> to <code>x</code> (the opposite order).</p> <p>With <code>key</code> on the other hand you are just considering how to view an element individually in order that python will naturally understand how to sort it how you want. We know the first item is being compared properly, so now we just need to flip the second. Numbers would be easy, we could just take the negative. But how do you flip a string? </p> <p>One approach is to take the <code>ord</code> (which should be an ascii value integer for your strings) of each character in the string. Then you can take the negative of <strong>these</strong> values and package them into a <code>tuple</code>. This is what one of these would look like:</p> <pre><code>&gt;&gt;&gt; tuple(-ord(c) for c in 'C Hearder') (-67, -32, -72, -101, -97, -114, -100, -101, -114) </code></pre> <p>Second example using <code>key</code>:</p> <pre><code>def custom_key(pair): pts, team = pair return (pts, tuple(-ord(c) for c in team)) pts, teams = zip(*sorted(zip(pts, teams), key=custom_key, reverse=True)) </code></pre> <p><strong>Restrospective edit:</strong></p> <p>If we're defining a custom <code>key</code> we may as well invert the <code>key</code> itself and remove the <code>reverse</code> argument:</p> <pre><code>def custom_key(pair): pts, team = pair return (-int(pts), team) pts, teams = zip(*sorted(zip(pts, teams), key=custom_key)) </code></pre>
1
2016-10-09T03:52:57Z
[ "python", "list", "python-2.7", "sorting" ]
Sorting parallel lists in python - first item descending, second item ascending
39,939,813
<p>I have two lists - one for a team name and the second for points </p> <p>I wanted to sort them based on the points without losing track of the corresponding team. I found something on SO that works great for doing this - and it sorts teams by points in descending order (most to least).</p> <p>There doesn't appear to be a sort on the second list.</p> <blockquote> <p><strong>EDIT - Original Data</strong></p> </blockquote> <pre><code>Teams Pts D Clark 0 D Dupuis 2 T Leach 2 J Schutz 0 C Hearder 2 R Pagani 0 M Cameron 2 B Hunter 0 </code></pre> <p><strong>This is what I'm using:</strong></p> <pre><code>pts, teams = zip(*sorted(zip(pts, teams), reverse=True)) i = 1 for team, num_pts in zip(teams, pts): standings = str(i) + '. ' + team + " (" + num_pts + ")" print standings i += 1 </code></pre> <p><strong>And it results in this:</strong> </p> <pre><code>1. T Leach (2) 2. M Cameron (2) 3. D Dupuis (2) 4. C Hearder (2) 5. R Pagani (0) 6. J Schutz (0) 7. D Clark (0) 8. B Hunter (0) </code></pre> <p>What I'm trying to do is to add an additional sort on team name - so if there's a tie, then it will <em>sort by names in ascending</em> order, </p> <p><strong>Like This:</strong> </p> <pre><code>1. C Hearder (2) 2. D Dupuis (2) 3. M Cameron (2) 4. T Leach (2) 5. B Hunter (0) 6. D Clark (0) 7. J Schutz (0) 8. R Pagani (0) </code></pre>
1
2016-10-09T03:45:02Z
39,939,940
<p>You can specify how <code>sorted</code> will sort by passing in the <code>key</code> kwarg. One handy way to use <code>key</code> is with <code>itemgetter</code> from the <code>operator</code> module.</p> <p>For example, if you have a list of tuples (such as by zipping two lists) and you want to sort by the second item, then the first, the key would be <code>itemgetter(1,0)</code> so you might do something like this:</p> <pre><code>from operator import itemgetter teams_and_points = zip(teams, pts) for team, points in sorted(points_and_teams, key=itemgetter(1, 0)): print(team, points) </code></pre>
1
2016-10-09T04:06:17Z
[ "python", "list", "python-2.7", "sorting" ]
Issue with my word score function
39,939,909
<p>So here is my code:</p> <pre><code>def word_score(string1, string2): '''Returns the word score for two strings''' if len(string1) == 0 or len(string2) == 0: return 0 else: if string1[0] in string2: return 1 + word_score(string1[1:], string2) else: return word_score(string1[1:], string2) </code></pre> <p>Basically for every letter that is shared between each string the score should increase by one. However there should not be repeats but my code repeats letters sometimes depending on the output. I have to use recursion for this and can't using anything like map or key because we haven't learned that yet in class. This lab assignment is really tricky and I tried debugging and all my classmates are stumped and its due on Tuesday. </p> <p>Heres some outputs that don't work and what they should be returning: </p> <p><code>word_score('always', 'walking')</code> returns 4 but should return 3 because of the repeat there is one extra</p> <p><code>word_score('recursion', 'excursion')</code> returns 9 but should return 8 again because of the repeat</p> <p>Correct outputs:</p> <p><code>word_score('diner', 'syrup')</code> correctly returns 1</p> <p><code>word_score('always', 'bananas')</code> correctly returns 3</p>
0
2016-10-09T04:00:46Z
39,939,986
<p>You can convert the str in a list, then in a set for eliminate duplicates and check the intersection len.</p> <pre><code>def word_score(string1, string2): '''Returns the word score for two strings''' string1=list(string1) string2=list(string2) string1=set(string1) string2=set(string2) if len(string1) == 0 or len(string2) == 0: return 0 else: return len((string1.intersection(string2))) </code></pre> <p><strong>EDIT:</strong> you cant use intersection,but <em>list</em> and <em>while</em> you can use?</p> <pre><code>def word_score2(string1, string2): '''Returns the word score for two strings''' string_temp1=list(string1) string_temp2=list(string2) if len(string_temp1) == 0 or len(string_temp2) == 0: return 0 else: if string_temp1[0] in string_temp2: while string1[0] in string_temp1: string_temp1.remove(string1[0]) return 1 + word_score2(string_temp1, string_temp2) else: return word_score2(string_temp1[1:], string_temp2) </code></pre>
0
2016-10-09T04:18:12Z
[ "python", "recursion" ]
Issue with my word score function
39,939,909
<p>So here is my code:</p> <pre><code>def word_score(string1, string2): '''Returns the word score for two strings''' if len(string1) == 0 or len(string2) == 0: return 0 else: if string1[0] in string2: return 1 + word_score(string1[1:], string2) else: return word_score(string1[1:], string2) </code></pre> <p>Basically for every letter that is shared between each string the score should increase by one. However there should not be repeats but my code repeats letters sometimes depending on the output. I have to use recursion for this and can't using anything like map or key because we haven't learned that yet in class. This lab assignment is really tricky and I tried debugging and all my classmates are stumped and its due on Tuesday. </p> <p>Heres some outputs that don't work and what they should be returning: </p> <p><code>word_score('always', 'walking')</code> returns 4 but should return 3 because of the repeat there is one extra</p> <p><code>word_score('recursion', 'excursion')</code> returns 9 but should return 8 again because of the repeat</p> <p>Correct outputs:</p> <p><code>word_score('diner', 'syrup')</code> correctly returns 1</p> <p><code>word_score('always', 'bananas')</code> correctly returns 3</p>
0
2016-10-09T04:00:46Z
39,939,989
<p>You can try to "erase" the letters from the second word, when a "positive match" occurs. This way, your duplicate issues will disappear. </p>
0
2016-10-09T04:18:53Z
[ "python", "recursion" ]
Issue with my word score function
39,939,909
<p>So here is my code:</p> <pre><code>def word_score(string1, string2): '''Returns the word score for two strings''' if len(string1) == 0 or len(string2) == 0: return 0 else: if string1[0] in string2: return 1 + word_score(string1[1:], string2) else: return word_score(string1[1:], string2) </code></pre> <p>Basically for every letter that is shared between each string the score should increase by one. However there should not be repeats but my code repeats letters sometimes depending on the output. I have to use recursion for this and can't using anything like map or key because we haven't learned that yet in class. This lab assignment is really tricky and I tried debugging and all my classmates are stumped and its due on Tuesday. </p> <p>Heres some outputs that don't work and what they should be returning: </p> <p><code>word_score('always', 'walking')</code> returns 4 but should return 3 because of the repeat there is one extra</p> <p><code>word_score('recursion', 'excursion')</code> returns 9 but should return 8 again because of the repeat</p> <p>Correct outputs:</p> <p><code>word_score('diner', 'syrup')</code> correctly returns 1</p> <p><code>word_score('always', 'bananas')</code> correctly returns 3</p>
0
2016-10-09T04:00:46Z
39,940,044
<p>Assuming that you can't use <code>set</code>, <code>dict</code> or <code>Counter</code> one way would be to iterate the characters in <code>string1</code> one by one and use <a href="https://docs.python.org/3.5/library/stdtypes.html#str.find" rel="nofollow"><code>str.find</code></a> to check if it can be found from <code>string2</code>. If character is found then add <code>1</code> to result and construct new <code>string2</code> by combining the slices before and after the match index:</p> <pre><code>def word_score(string1, string2): if not string1 or not string2: return 0 index = string2.find(string1[0]) if index != -1: return 1 + word_score(string1[1:], string2[:index] + string2[index+1:]) else: return word_score(string1[1:], string2) TEST_CASES = [ ['always', 'walking'], ['recursion', 'excursion'], ['diner', 'syrup'], ['always', 'bananas'] ] for s1, s2 in TEST_CASES: print('word_score({}, {}) -&gt; {}'.format(s1, s2, word_score(s1, s2))) </code></pre> <p>Output:</p> <pre><code>word_score(always, walking) -&gt; 3 word_score(recursion, excursion) -&gt; 8 word_score(diner, syrup) -&gt; 1 word_score(always, bananas) -&gt; 3 </code></pre> <p><strong>Update</strong></p> <p>Assuming that <code>str</code> methods are not available either you can easily implement the search yourself assuming <a href="https://docs.python.org/3/library/functions.html#func-range" rel="nofollow"><code>range</code></a> and <a href="https://docs.python.org/3/library/functions.html#len" rel="nofollow"><code>len</code></a> are allowed:</p> <pre><code>def word_score(string1, string2): if not string1 or not string2: return 0 for i in range(len(string2)): if string1[0] == string2[i]: return 1 + word_score(string1[1:], string2[:i] + string2[i+1:]) return word_score(string1[1:], string2) </code></pre>
1
2016-10-09T04:32:58Z
[ "python", "recursion" ]
What is the best way to fetch huge data from mysql with sqlalchemy?
39,939,970
<p>I want to process over 10 millions data stored in MySQL. So I wrote this to slice the sql to several parts then concatenate the data for latter process. It works well if <code>count &lt; 2 millions</code>. However when the <code>count</code> rise, the time sqlalchemy consumes goes much longer.</p> <pre><code>def fetch_from_sql(_sql_pat, count): """ :param _sql_pat: SELECT id, data FROM a.b LIMIT {},{}; :param count: how many data you want to fetch from mysql :return: generator """ def gen_connect(sql): __engine = create_engine(db_config['SQLALCHEMY_DATABASE_URI']) with __engine.connect() as c: for row in c.execute(sql) yield row def gen_range(limit, step): if step &gt; limit: yield 0, limit else: R = range(0, limit + 1, step) for idx, v in enumerate(R): if idx == 0: yield v, step elif limit - v &gt;= step: yield v + 1, step else: yield v + 1, limit - v sqls = [_sql_pat.format(start, step) for start, step in gen_range(count, 100000)] sources = (gen_connect(sql) for sql in sqls) for s in sources: for item in s: yield item gc.collect() </code></pre> <p>The <strong>question</strong> is why the sqlalchemy take more and more time (I logged time and post below), and what is the best way to deal with this situation?</p> <pre><code>Dumped 10000 items, at 2016-10-08 11:55:33 Dumped 1000000 items, at 2016-10-08 11:59:23 Dumped 2000000 items, at 2016-10-08 12:05:07 Dumped 3000000 items, at 2016-10-08 13:54:05 </code></pre>
1
2016-10-09T04:14:43Z
39,947,245
<p>This is because you're using <code>LIMIT</code>/<code>OFFSET</code>, so when you specify offset 3000000, for example, the database has to skip over 3000000 records.</p> <p>The correct way to do this is to <code>ORDER BY</code> some indexed column, like the primary key <code>id</code> column, for example, then do a <code>WHERE id &gt; :last_fetched_id</code>.</p>
1
2016-10-09T18:47:11Z
[ "python", "sqlalchemy" ]
Issues clicking an element using selenium
39,939,995
<p>Im using this code to explore tripadvisor (Portuguese comments)</p> <pre><code>from selenium import webdriver from bs4 import BeautifulSoup driver=webdriver.Firefox() driver.get("https://www.tripadvisor.com/Airline_Review-d8729164-Reviews-Cheap-Flights-TAP-Portugal#review_425811350") driver.set_window_size(1920, 1080) </code></pre> <p>Then Im trying to click the google-translate link</p> <pre><code>driver.find_element_by_class_name("googleTranslation").click() </code></pre> <p>But getting this error :-</p> <pre><code>WebDriverException: Message: Element is not clickable at point (854.5, 10.100006103515625). Other element would receive the click: &lt;div class="inner easyClear"&gt;&lt;/div&gt; </code></pre> <p>So the <code>div class="inner easyClear"</code> is getting the click. I tried exploring it </p> <pre><code>from bs4 import BeautifulSoup page=driver.page_source for i in page.findAll("div","easyClear"): print i print "=================" </code></pre> <p>But was unable to get any intuition from this as in what changes to incorporate now to make the "Google Translate" clickable. Please help</p> <p>===============================EDIT===============================</p> <p>Ive also tried these </p> <pre><code>driver.execute_script("window.scrollTo(0, 1200);") driver.find_element_by_class_name("googleTranslation").click() </code></pre> <p>Resizing the browser to full screen etc..</p>
1
2016-10-09T04:20:01Z
39,940,106
<p>What worked for me was to use an Explicit Wait and the <code>element_to_be_clickable</code> Expected Condition and get to the inner <code>span</code> element:</p> <pre><code>from selenium import webdriver from selenium.webdriver import ActionChains from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC driver = webdriver.Chrome() driver.get("https://www.tripadvisor.com.br/ShowUserReviews-g1-d8729164-r425802060-TAP_Portugal-World.html") wait = WebDriverWait(driver, 10) google_translate = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, ".googleTranslation .link"))) actions = ActionChains(driver) actions.move_to_element(google_translate).click().perform() </code></pre> <p>You may also be getting into a "survey" or "promotion" popup - make sure to account for those.</p>
3
2016-10-09T04:44:30Z
[ "python", "selenium", "selenium-webdriver", "web-scraping" ]
Python Regex for ignoring a sentence with two consecutive upper case letters
39,940,000
<p>I have a simple problem at hand to ignore the sentences that contain two or more consecutive capital letters and many more grammar rules .</p> <p><strong>Issue:</strong> By the definition the regex should not match the string <code>'This is something with two CAPS.'</code> , but it does match.</p> <p><strong>Code:</strong> </p> <pre><code>''' Check if a given sentence conforms to given grammar rules $ Rules * Sentence must start with a Uppercase character (e.g. Noun/ I/ We/ He etc.) * Then lowercase character follows. * There must be spaces between words. * Then the sentence must end with a full stop(.) after a word. * Two continuous spaces are not allowed. * Two continuous upper case characters are not allowed. * However the sentence can end after an upper case character. ''' import re # Returns true if sentence follows these rules else returns false def check_sentence(sentence): checker = re.compile(r"^((^(?![A-Z][A-Z]+))([A-Z][a-z]+)(\s\w+)+\.$)") return checker.match(sentence) print(check_sentence('This is something with two CAPS.')) </code></pre> <p><strong>Output:</strong></p> <pre><code>&lt;_sre.SRE_Match object; span=(0, 32), match='This is something with two CAPS.'&gt; </code></pre>
1
2016-10-09T04:21:03Z
39,940,080
<p>It’s probably easier to write your regex in the negative (find all sentences that are bad sentences) than it is in the positive. </p> <pre><code>checker = re.compile(r'([A-Z][A-Z]|[ ][ ]|^[a-z])') check2 = re.compile(r'^[A-Z][a-z].* .*\.$') return not checker.findall(sentence) and check2.findall(sentence) </code></pre>
0
2016-10-09T04:39:01Z
[ "python", "regex", "python-3.x" ]
Python Regex for ignoring a sentence with two consecutive upper case letters
39,940,000
<p>I have a simple problem at hand to ignore the sentences that contain two or more consecutive capital letters and many more grammar rules .</p> <p><strong>Issue:</strong> By the definition the regex should not match the string <code>'This is something with two CAPS.'</code> , but it does match.</p> <p><strong>Code:</strong> </p> <pre><code>''' Check if a given sentence conforms to given grammar rules $ Rules * Sentence must start with a Uppercase character (e.g. Noun/ I/ We/ He etc.) * Then lowercase character follows. * There must be spaces between words. * Then the sentence must end with a full stop(.) after a word. * Two continuous spaces are not allowed. * Two continuous upper case characters are not allowed. * However the sentence can end after an upper case character. ''' import re # Returns true if sentence follows these rules else returns false def check_sentence(sentence): checker = re.compile(r"^((^(?![A-Z][A-Z]+))([A-Z][a-z]+)(\s\w+)+\.$)") return checker.match(sentence) print(check_sentence('This is something with two CAPS.')) </code></pre> <p><strong>Output:</strong></p> <pre><code>&lt;_sre.SRE_Match object; span=(0, 32), match='This is something with two CAPS.'&gt; </code></pre>
1
2016-10-09T04:21:03Z
39,940,122
<p>Your negative lookahead is only applying to the beginning of the string being tested. </p> <p>2nd Capturing Group <code>(^(?![A-Z][A-Z]+))</code></p> <p><code>^</code> asserts position at start of the string</p> <p>Negative Lookahead <code>(?![A-Z][A-Z]+)</code></p> <p><code>"This will NOT fail."</code></p> <p><code>"THIS will fail."</code></p>
0
2016-10-09T04:47:06Z
[ "python", "regex", "python-3.x" ]
How to save crawl page link into item using scrapy?
39,940,017
<p>This is my spider page:</p> <pre><code>rules = ( Rule(LinkExtractor(allow=r'torrents-details\.php\?id=\d*'), callback='parse_item', follow=True), ) def parse_item(self, response): item = MovieNotifyItem() item['title'] = response.xpath('//h5[@class="col s12 light center teal darken-3 white-text"]/text()').extract_first() item['size'] = response.xpath('//*[@class="torrent-info"]//tr[1]/td[2]/text()').extract_first() item['catagory'] = response.xpath('//*[@class="torrent-info"]//tr[2]/td[2]/text()').extract_first() yield item </code></pre> <p>Now I want to save the page link into a item say item['page_link'] which crawled by this code:</p> <pre><code>rules = ( Rule(LinkExtractor(allow=r'torrents-details\.php\?id=\d*'), callback='parse_item', follow=True), ) </code></pre> <p>How can I do that ? Thanks in advance</p>
1
2016-10-09T04:26:26Z
39,940,118
<p>If I understand correctly, you are looking for the <code>response.url</code>:</p> <pre><code>def parse_item(self, response): item = MovieNotifyItem() item['url'] = response.url # "url" field should be defined for "MovieNotifyItem" Item class # ... yield item </code></pre>
0
2016-10-09T04:46:38Z
[ "python", "python-3.x", "scrapy" ]
apply gaussian filtering on numpy array with nan value and then plot the image
39,940,065
<p>I have a numpy 2d array (image) with values >=0.0 but there are some indices with value 'nan'. When I try to plot this figure it looks like the below image. The 0 in the image array becomes black and nan becomes white.</p> <p><a href="http://i.stack.imgur.com/S5JHF.png" rel="nofollow"><img src="http://i.stack.imgur.com/S5JHF.png" alt="enter image description here"></a></p> <p>Now I want to apply gaussian smoothing on this array such that the after smoothing when I try to plot smoothed array, the nan values from the previous array appears white only.</p>
0
2016-10-09T04:36:36Z
39,942,576
<p>When doing a gaussian filter of an image, any pixel close to a <code>nan</code> pixel will also turn into a <code>nan</code>, since its new value is the weighted sum over all neighboring pixels covered by the convolution kernel.</p> <p>Therefore, smoothing this particular image using, for example, <code>scipy.ndimage.filters.gaussian_filter()</code> will turn a lot of your zero values into <code>nan</code>s and you'll lose a lot of information.</p> <p>To smooth this (apparently binary) data, I would replace the <code>nan</code>s by some other value, of course maintaining contrast to the non-<code>nan</code> pixels. For example, turn the zeros into ones, and the <code>nan</code>s into zeros, then apply the filter.</p>
0
2016-10-09T10:31:19Z
[ "python", "matplotlib" ]
How to pass argument implicitly in Python Class function
39,940,089
<p>I was writing a python class and related functions. Suppose following is a class having a function that adds up all values of a numeric list and returns the sum</p> <pre><code> alist = [2,3,7,4,7] MyClasss(object): def __init__(self): print("Roses are red") def add_list(self,thelist): j = 0 for i in the list: j = j+i return j a = MyClasss() print("sum is ",a.add_list(alist)) </code></pre> <p>The above query will return the sum of the list just fine.</p> <p>MY QUESTION IS: Is it possible write this query or create a data object in which we do not have to pass the data object in the brackets instead write it something like this</p> <pre><code> alist.add_list() </code></pre> <p>and get the same results. Like we see different functions are available for different data types. Any insights on this will be highly appreciated. Thanks </p>
0
2016-10-09T04:41:31Z
39,940,172
<p>You can add it to <code>__init__</code> on construction</p> <pre><code>class MyClasss(object): def __init__(self, theList): self.theList = theList def add_list(self): return sum(self.theList) &gt;&gt;&gt; a = MyClasss([2,3,7,4,7]) &gt;&gt;&gt; print("sum is ", a.add_list()) 23 &gt;&gt;&gt; print("sum is ", a.add_list()) 23 </code></pre> <p>Another way to do this is create a partial function from <code>functools.partial</code> and call that:</p> <pre><code>&gt;&gt;&gt; import functools as ft &gt;&gt;&gt; a = MyClasss() &gt;&gt;&gt; a.add_list = ft.partial(a.add_list, [2,3,7,4,7]) &gt;&gt;&gt; a.add_list() 23 </code></pre>
2
2016-10-09T04:57:44Z
[ "python", "function", "class" ]
Django Form request.POST.get() always returns empty
39,940,182
<p>Sorry if this is a noob question. I'm creating a login form for a Django app, but I'm having trouble getting it to work. request.POST.get() doesn't return anything, so the authentication always fails. Am I missing something obvious?</p> <p>login.html:</p> <pre><code>{% extends "base.html" %} {% block content%} &lt;h2&gt;Welcome! Please login to continue.&lt;/h2&gt; &lt;br&gt; &lt;form action="{% url 'account:authenticate' %}" method="post"&gt; {% csrf_token %} &lt;div &gt; &lt;label for='username'&gt; Username: &lt;/label&gt; &lt;input type='text' name='Username' id='username'&gt; &lt;br&gt;&lt;br&gt; &lt;label for='password'&gt;Password: &lt;/label&gt; &lt;input type='password' name='Password' id='password'&gt;&lt;br&gt;&lt;br&gt; &lt;input type='submit' value='Login'&gt; &lt;/div&gt; &lt;/form&gt; </code></pre> <p>relevant part of views.py:</p> <pre><code>from django.shortcuts import render, get_object_or_404 from datetime import datetime from django.http import HttpResponse, Http404, HttpResponseRedirect from django.template import loader from random import randrange from django.contrib.auth import authenticate def login(request): return render (request, 'login.html') def authenticate(request): usern = request.POST.get('username', '') passw = request.POST.get('password', '') user = authenticate(username = usern, password = passw) if user is not None: authenticate.login(request, user) return HttpResponseRedirect('/voters/instructions') else: return HttpResponseRedirect('/account/loginfail') def loginfail(request): return render (request, 'loginfail.html') </code></pre> <p>I'm using Django 1.10. Thanks!</p>
0
2016-10-09T04:58:34Z
39,940,202
<p>Check out the names in the form input fields they are case sensitive. in Django do this</p> <pre><code> usern = request.POST.get('Username', '') passw = request.POST.get('Password', '') </code></pre> <p>or in html form make them lowercase the input name field</p>
1
2016-10-09T05:03:18Z
[ "python", "django" ]
How do I view errors my Flask App is returning?
39,940,204
<p>I've started to make an app using Python 3 with the Flask framework. I mostly followed this <a href="https://pythonprogramming.net/creating-first-flask-web-app/" rel="nofollow">tutorial</a>. I'm currently using a free-tier AWS Ubuntu-16.04 server to host the app on while trying to develop it.</p> <p>How am I meant to see the errors that my Flask App is returning? - as most of the time I receive a 500 Internal Server Error in my browser. Also is there an easier setup I should be using to develop and debug the app.</p> <p>Thanks</p> <p>Edit 1:</p> <pre><code>#!/usr/bin/python from flask import Flask, render_template, request app = Flask(__name__) app.debug = True @app.route('/table') def current_return(): data = ['one', 'two', 'three'] return render_template("current.html",data = data) if __name__ == "__main__": app.run() </code></pre>
0
2016-10-09T05:03:38Z
39,940,222
<p>You should enable debugging for your app.</p> <pre><code>app = Flask(__name__) app.debug = True </code></pre> <p>That will output the traceback on the error pages, instead of just a generic 'Server error' page. </p>
1
2016-10-09T05:06:53Z
[ "python", "python-3.x", "flask" ]
Python Regex match 2nd or 3rd word in line
39,940,205
<p>I'm trying to separate lines into 3 sections using regex, with a typical line fitting into this kind of pattern: <code>-30.345 150.930 112.356</code></p> <p>I'm extracting the first section of data fine using <code>lat = float(re.match('[^\s]+', line).group(0))</code>, but have been unable to correctly target the 2nd and 3rd numbers. </p> <p>I've tried/am trying <code>long = float(re.match('.*?\s(\S+)\s.*?', line).group(0))</code> but this is returning the entire string up until the 2nd whitespace. How can I target just the 2nd number and 3rd number in these strings?</p>
1
2016-10-09T05:03:54Z
39,940,254
<p>If you cannot do <code>split</code> then you can just match the numbers with optional <code>-</code> or <code>+</code> at the start:</p> <pre><code>&gt;&gt;&gt; s = '-30.345 foo 150.930 abc 112.356 another .123' &gt;&gt;&gt; re.findall(r'([+-]?\d*\.?\d+)', s) ['-30.345', '150.930', '112.356', '.123'] </code></pre> <p><a href="https://regex101.com/r/DXv0ep/7" rel="nofollow">RegEx Demo</a></p>
1
2016-10-09T05:12:51Z
[ "python", "regex" ]
How do I remove commas and quotations from my list output
39,940,447
<p>Having a hard time stripping these quotation marks and commas from my list, </p> <p><code>**SHOWN BELOW IN THE SECOND PART OF MY CODE OUTPUT**</code>I need all of the (' ',) to be stripped from the output and I keep trying the <code>rstrip()</code> on my <code>team variable</code>but it is giving me this ERROR.</p> <pre><code>TypeError: Can't convert 'int' object to str implicitly </code></pre> <p><strong>I think I may have built my code wrong....but this is a last ditch effort to stop myself from trashing it and starting over</strong></p> <pre><code>#list of teams Champs = ['Boston Americans', 'New York Giants', 'Chicago White Sox', 'Chicago Cubs', 'Chicago Cubs', 'Pittsburgh Pirates', 'Philadelphia Athletics', 'Philadelphia Athletics', 'Boston Red Sox', 'Philadelphia Athletics', 'Boston Braves', 'Boston Red Sox', 'Boston Red Sox', 'Chicago White Sox', 'Boston Red Sox', 'Cincinnati Reds', 'Cleveland Indians', 'New York Giants', 'New York Giants', 'New York Yankees', 'Washington Senators', 'Pittsburgh Pirates', 'St. Louis Cardinals', 'New York Yankees', 'New York Yankees', 'Philadelphia Athletics', 'Philadelphia Athletics', 'St. Louis Cardinals', 'New York Yankees', 'New York Giants', 'St. Louis Cardinals', 'Detroit Tigers', 'New York Yankees', 'New York Yankees', 'New York Yankees', 'New York Yankees', 'Cincinnati Reds', 'New York Yankees', 'St. Louis Cardinals', 'New York Yankees', 'St. Louis Cardinals', 'Detroit Tigers', 'St. Louis Cardinals', 'New York Yankees', 'Cleveland Indians', 'New York Yankees', 'New York Yankees', 'New York Yankees', 'New York Yankees', 'New York Yankees', 'New York Giants', 'Brooklyn Dodgers', 'New York Yankees', 'Milwaukee Braves', 'New York Yankees', 'Los Angeles Dodgers', 'Pittsburgh Pirates', 'New York Yankees', 'New York Yankees', 'Los Angeles Dodgers', 'St. Louis Cardinals', 'Los Angeles Dodgers', 'Baltimore Orioles', 'St. Louis Cardinals', 'Detroit Tigers', 'New York Mets', 'Baltimore Orioles', 'Pittsburgh Pirates', 'Oakland Athletics', 'Oakland Athletics', 'Oakland Athletics', 'Cincinnati Reds', 'Cincinnati Reds', 'New York Yankees', 'New York Yankees', 'Pittsburgh Pirates', 'Philadelphia Phillies', 'Los Angeles Dodgers', 'St. Louis Cardinals', 'Baltimore Orioles', 'Detroit Tigers', 'Kansas City Royals', 'New York Mets', 'Minnesota Twins', 'Los Angeles Dodgers', 'Oakland Athletics', 'Cincinnati Reds', 'Minnesota Twins', 'Toronto Blue Jays', 'Toronto Blue Jays', 'Atlanta Braves', 'New York Yankees', 'Florida Marlins', 'New York Yankees', 'New York Yankees', 'New York Yankees', 'Arizona Diamondbacks', 'Anaheim Angels', 'Florida Marlins', 'Boston Red Sox', 'Chicago White Sox', 'St. Louis Cardinals', 'Boston Red Sox', 'Philadelphia Phillies', 'New York Yankees', 'San Francisco Giants', 'St. Louis Cardinals', 'San Francisco Giants', 'Boston Red Sox'] #sort list alphabetically Champs.sort() for team in [ele for ind, ele in enumerate(Champs,1) if ele not in Champs[ind:]]: count = 0 for ele in Champs: if team == ele: count += 1 print((team.strip(),count.strip())) count = 0 </code></pre> <p>--------My Output follows-----------</p> <pre><code>Welcome to the world series team count report generator. Choose an option from the following list. 1: Find out the count of wins for a single team. 2: Run a report showing all teams with their count of wins. 3: Exit the program. Enter your choice: 2 Team Count of Wins ------------------------------ Team Name Wins ('Anaheim Angels', 1) ('Arizona Diamondbacks', 1) ('Atlanta Braves', 1) ('Baltimore Orioles', 3) ('Boston Americans', 1) ('Boston Braves', 1) ('Boston Red Sox', 7) ('Brooklyn Dodgers', 1) ('Chicago Cubs', 2) ('Chicago White Sox', 3) ('Cincinnati Reds', 5) ('Cleveland Indians', 2) ('Detroit Tigers', 4) ('Florida Marlins', 2) ('Kansas City Royals', 1) ('Los Angeles Dodgers', 5) ('Milwaukee Braves', 1) ('Minnesota Twins', 2) ('New York Giants', 5) ('New York Mets', 2) ('New York Yankees', 27) ('Oakland Athletics', 4) ('Philadelphia Athletics', 5) ('Philadelphia Phillies', 2) ('Pittsburgh Pirates', 5) ('San Francisco Giants', 2) ('St. Louis Cardinals', 11) ('Toronto Blue Jays', 2) ('Washington Senators', 1) </code></pre>
-2
2016-10-09T05:47:16Z
39,940,472
<p>Remove the parenthesis and <code>strip</code></p> <pre><code>print(team.strip(), count) </code></pre>
1
2016-10-09T05:51:32Z
[ "python", "list", "output", "strip" ]
How do I remove commas and quotations from my list output
39,940,447
<p>Having a hard time stripping these quotation marks and commas from my list, </p> <p><code>**SHOWN BELOW IN THE SECOND PART OF MY CODE OUTPUT**</code>I need all of the (' ',) to be stripped from the output and I keep trying the <code>rstrip()</code> on my <code>team variable</code>but it is giving me this ERROR.</p> <pre><code>TypeError: Can't convert 'int' object to str implicitly </code></pre> <p><strong>I think I may have built my code wrong....but this is a last ditch effort to stop myself from trashing it and starting over</strong></p> <pre><code>#list of teams Champs = ['Boston Americans', 'New York Giants', 'Chicago White Sox', 'Chicago Cubs', 'Chicago Cubs', 'Pittsburgh Pirates', 'Philadelphia Athletics', 'Philadelphia Athletics', 'Boston Red Sox', 'Philadelphia Athletics', 'Boston Braves', 'Boston Red Sox', 'Boston Red Sox', 'Chicago White Sox', 'Boston Red Sox', 'Cincinnati Reds', 'Cleveland Indians', 'New York Giants', 'New York Giants', 'New York Yankees', 'Washington Senators', 'Pittsburgh Pirates', 'St. Louis Cardinals', 'New York Yankees', 'New York Yankees', 'Philadelphia Athletics', 'Philadelphia Athletics', 'St. Louis Cardinals', 'New York Yankees', 'New York Giants', 'St. Louis Cardinals', 'Detroit Tigers', 'New York Yankees', 'New York Yankees', 'New York Yankees', 'New York Yankees', 'Cincinnati Reds', 'New York Yankees', 'St. Louis Cardinals', 'New York Yankees', 'St. Louis Cardinals', 'Detroit Tigers', 'St. Louis Cardinals', 'New York Yankees', 'Cleveland Indians', 'New York Yankees', 'New York Yankees', 'New York Yankees', 'New York Yankees', 'New York Yankees', 'New York Giants', 'Brooklyn Dodgers', 'New York Yankees', 'Milwaukee Braves', 'New York Yankees', 'Los Angeles Dodgers', 'Pittsburgh Pirates', 'New York Yankees', 'New York Yankees', 'Los Angeles Dodgers', 'St. Louis Cardinals', 'Los Angeles Dodgers', 'Baltimore Orioles', 'St. Louis Cardinals', 'Detroit Tigers', 'New York Mets', 'Baltimore Orioles', 'Pittsburgh Pirates', 'Oakland Athletics', 'Oakland Athletics', 'Oakland Athletics', 'Cincinnati Reds', 'Cincinnati Reds', 'New York Yankees', 'New York Yankees', 'Pittsburgh Pirates', 'Philadelphia Phillies', 'Los Angeles Dodgers', 'St. Louis Cardinals', 'Baltimore Orioles', 'Detroit Tigers', 'Kansas City Royals', 'New York Mets', 'Minnesota Twins', 'Los Angeles Dodgers', 'Oakland Athletics', 'Cincinnati Reds', 'Minnesota Twins', 'Toronto Blue Jays', 'Toronto Blue Jays', 'Atlanta Braves', 'New York Yankees', 'Florida Marlins', 'New York Yankees', 'New York Yankees', 'New York Yankees', 'Arizona Diamondbacks', 'Anaheim Angels', 'Florida Marlins', 'Boston Red Sox', 'Chicago White Sox', 'St. Louis Cardinals', 'Boston Red Sox', 'Philadelphia Phillies', 'New York Yankees', 'San Francisco Giants', 'St. Louis Cardinals', 'San Francisco Giants', 'Boston Red Sox'] #sort list alphabetically Champs.sort() for team in [ele for ind, ele in enumerate(Champs,1) if ele not in Champs[ind:]]: count = 0 for ele in Champs: if team == ele: count += 1 print((team.strip(),count.strip())) count = 0 </code></pre> <p>--------My Output follows-----------</p> <pre><code>Welcome to the world series team count report generator. Choose an option from the following list. 1: Find out the count of wins for a single team. 2: Run a report showing all teams with their count of wins. 3: Exit the program. Enter your choice: 2 Team Count of Wins ------------------------------ Team Name Wins ('Anaheim Angels', 1) ('Arizona Diamondbacks', 1) ('Atlanta Braves', 1) ('Baltimore Orioles', 3) ('Boston Americans', 1) ('Boston Braves', 1) ('Boston Red Sox', 7) ('Brooklyn Dodgers', 1) ('Chicago Cubs', 2) ('Chicago White Sox', 3) ('Cincinnati Reds', 5) ('Cleveland Indians', 2) ('Detroit Tigers', 4) ('Florida Marlins', 2) ('Kansas City Royals', 1) ('Los Angeles Dodgers', 5) ('Milwaukee Braves', 1) ('Minnesota Twins', 2) ('New York Giants', 5) ('New York Mets', 2) ('New York Yankees', 27) ('Oakland Athletics', 4) ('Philadelphia Athletics', 5) ('Philadelphia Phillies', 2) ('Pittsburgh Pirates', 5) ('San Francisco Giants', 2) ('St. Louis Cardinals', 11) ('Toronto Blue Jays', 2) ('Washington Senators', 1) </code></pre>
-2
2016-10-09T05:47:16Z
39,940,474
<p>remove <code>strip()</code> from the count</p> <pre><code>print(team.strip(), count) </code></pre>
1
2016-10-09T05:51:52Z
[ "python", "list", "output", "strip" ]
How do I remove commas and quotations from my list output
39,940,447
<p>Having a hard time stripping these quotation marks and commas from my list, </p> <p><code>**SHOWN BELOW IN THE SECOND PART OF MY CODE OUTPUT**</code>I need all of the (' ',) to be stripped from the output and I keep trying the <code>rstrip()</code> on my <code>team variable</code>but it is giving me this ERROR.</p> <pre><code>TypeError: Can't convert 'int' object to str implicitly </code></pre> <p><strong>I think I may have built my code wrong....but this is a last ditch effort to stop myself from trashing it and starting over</strong></p> <pre><code>#list of teams Champs = ['Boston Americans', 'New York Giants', 'Chicago White Sox', 'Chicago Cubs', 'Chicago Cubs', 'Pittsburgh Pirates', 'Philadelphia Athletics', 'Philadelphia Athletics', 'Boston Red Sox', 'Philadelphia Athletics', 'Boston Braves', 'Boston Red Sox', 'Boston Red Sox', 'Chicago White Sox', 'Boston Red Sox', 'Cincinnati Reds', 'Cleveland Indians', 'New York Giants', 'New York Giants', 'New York Yankees', 'Washington Senators', 'Pittsburgh Pirates', 'St. Louis Cardinals', 'New York Yankees', 'New York Yankees', 'Philadelphia Athletics', 'Philadelphia Athletics', 'St. Louis Cardinals', 'New York Yankees', 'New York Giants', 'St. Louis Cardinals', 'Detroit Tigers', 'New York Yankees', 'New York Yankees', 'New York Yankees', 'New York Yankees', 'Cincinnati Reds', 'New York Yankees', 'St. Louis Cardinals', 'New York Yankees', 'St. Louis Cardinals', 'Detroit Tigers', 'St. Louis Cardinals', 'New York Yankees', 'Cleveland Indians', 'New York Yankees', 'New York Yankees', 'New York Yankees', 'New York Yankees', 'New York Yankees', 'New York Giants', 'Brooklyn Dodgers', 'New York Yankees', 'Milwaukee Braves', 'New York Yankees', 'Los Angeles Dodgers', 'Pittsburgh Pirates', 'New York Yankees', 'New York Yankees', 'Los Angeles Dodgers', 'St. Louis Cardinals', 'Los Angeles Dodgers', 'Baltimore Orioles', 'St. Louis Cardinals', 'Detroit Tigers', 'New York Mets', 'Baltimore Orioles', 'Pittsburgh Pirates', 'Oakland Athletics', 'Oakland Athletics', 'Oakland Athletics', 'Cincinnati Reds', 'Cincinnati Reds', 'New York Yankees', 'New York Yankees', 'Pittsburgh Pirates', 'Philadelphia Phillies', 'Los Angeles Dodgers', 'St. Louis Cardinals', 'Baltimore Orioles', 'Detroit Tigers', 'Kansas City Royals', 'New York Mets', 'Minnesota Twins', 'Los Angeles Dodgers', 'Oakland Athletics', 'Cincinnati Reds', 'Minnesota Twins', 'Toronto Blue Jays', 'Toronto Blue Jays', 'Atlanta Braves', 'New York Yankees', 'Florida Marlins', 'New York Yankees', 'New York Yankees', 'New York Yankees', 'Arizona Diamondbacks', 'Anaheim Angels', 'Florida Marlins', 'Boston Red Sox', 'Chicago White Sox', 'St. Louis Cardinals', 'Boston Red Sox', 'Philadelphia Phillies', 'New York Yankees', 'San Francisco Giants', 'St. Louis Cardinals', 'San Francisco Giants', 'Boston Red Sox'] #sort list alphabetically Champs.sort() for team in [ele for ind, ele in enumerate(Champs,1) if ele not in Champs[ind:]]: count = 0 for ele in Champs: if team == ele: count += 1 print((team.strip(),count.strip())) count = 0 </code></pre> <p>--------My Output follows-----------</p> <pre><code>Welcome to the world series team count report generator. Choose an option from the following list. 1: Find out the count of wins for a single team. 2: Run a report showing all teams with their count of wins. 3: Exit the program. Enter your choice: 2 Team Count of Wins ------------------------------ Team Name Wins ('Anaheim Angels', 1) ('Arizona Diamondbacks', 1) ('Atlanta Braves', 1) ('Baltimore Orioles', 3) ('Boston Americans', 1) ('Boston Braves', 1) ('Boston Red Sox', 7) ('Brooklyn Dodgers', 1) ('Chicago Cubs', 2) ('Chicago White Sox', 3) ('Cincinnati Reds', 5) ('Cleveland Indians', 2) ('Detroit Tigers', 4) ('Florida Marlins', 2) ('Kansas City Royals', 1) ('Los Angeles Dodgers', 5) ('Milwaukee Braves', 1) ('Minnesota Twins', 2) ('New York Giants', 5) ('New York Mets', 2) ('New York Yankees', 27) ('Oakland Athletics', 4) ('Philadelphia Athletics', 5) ('Philadelphia Phillies', 2) ('Pittsburgh Pirates', 5) ('San Francisco Giants', 2) ('St. Louis Cardinals', 11) ('Toronto Blue Jays', 2) ('Washington Senators', 1) </code></pre>
-2
2016-10-09T05:47:16Z
39,940,480
<p>Wrapping the items with <code>( )</code> makes it a tuple; you should remove the extra parenthesis in your call to <code>print</code>. And you don't need <a href="https://docs.python.org/2/library/string.html#string.strip" rel="nofollow"><code>strip</code></a> for <code>int</code> type. You also don't to <code>strip</code> the string either (in this case):</p> <pre><code>print(team, count) </code></pre> <p>More so, <a href="https://docs.python.org/3/library/collections.html#collections.Counter" rel="nofollow"><code>collections.Counter</code></a> already does what you're trying to do:</p> <pre><code>from collections import Counter for k, v in Counter(Champs).items(): print(k, v) </code></pre>
4
2016-10-09T05:52:25Z
[ "python", "list", "output", "strip" ]
How do I remove commas and quotations from my list output
39,940,447
<p>Having a hard time stripping these quotation marks and commas from my list, </p> <p><code>**SHOWN BELOW IN THE SECOND PART OF MY CODE OUTPUT**</code>I need all of the (' ',) to be stripped from the output and I keep trying the <code>rstrip()</code> on my <code>team variable</code>but it is giving me this ERROR.</p> <pre><code>TypeError: Can't convert 'int' object to str implicitly </code></pre> <p><strong>I think I may have built my code wrong....but this is a last ditch effort to stop myself from trashing it and starting over</strong></p> <pre><code>#list of teams Champs = ['Boston Americans', 'New York Giants', 'Chicago White Sox', 'Chicago Cubs', 'Chicago Cubs', 'Pittsburgh Pirates', 'Philadelphia Athletics', 'Philadelphia Athletics', 'Boston Red Sox', 'Philadelphia Athletics', 'Boston Braves', 'Boston Red Sox', 'Boston Red Sox', 'Chicago White Sox', 'Boston Red Sox', 'Cincinnati Reds', 'Cleveland Indians', 'New York Giants', 'New York Giants', 'New York Yankees', 'Washington Senators', 'Pittsburgh Pirates', 'St. Louis Cardinals', 'New York Yankees', 'New York Yankees', 'Philadelphia Athletics', 'Philadelphia Athletics', 'St. Louis Cardinals', 'New York Yankees', 'New York Giants', 'St. Louis Cardinals', 'Detroit Tigers', 'New York Yankees', 'New York Yankees', 'New York Yankees', 'New York Yankees', 'Cincinnati Reds', 'New York Yankees', 'St. Louis Cardinals', 'New York Yankees', 'St. Louis Cardinals', 'Detroit Tigers', 'St. Louis Cardinals', 'New York Yankees', 'Cleveland Indians', 'New York Yankees', 'New York Yankees', 'New York Yankees', 'New York Yankees', 'New York Yankees', 'New York Giants', 'Brooklyn Dodgers', 'New York Yankees', 'Milwaukee Braves', 'New York Yankees', 'Los Angeles Dodgers', 'Pittsburgh Pirates', 'New York Yankees', 'New York Yankees', 'Los Angeles Dodgers', 'St. Louis Cardinals', 'Los Angeles Dodgers', 'Baltimore Orioles', 'St. Louis Cardinals', 'Detroit Tigers', 'New York Mets', 'Baltimore Orioles', 'Pittsburgh Pirates', 'Oakland Athletics', 'Oakland Athletics', 'Oakland Athletics', 'Cincinnati Reds', 'Cincinnati Reds', 'New York Yankees', 'New York Yankees', 'Pittsburgh Pirates', 'Philadelphia Phillies', 'Los Angeles Dodgers', 'St. Louis Cardinals', 'Baltimore Orioles', 'Detroit Tigers', 'Kansas City Royals', 'New York Mets', 'Minnesota Twins', 'Los Angeles Dodgers', 'Oakland Athletics', 'Cincinnati Reds', 'Minnesota Twins', 'Toronto Blue Jays', 'Toronto Blue Jays', 'Atlanta Braves', 'New York Yankees', 'Florida Marlins', 'New York Yankees', 'New York Yankees', 'New York Yankees', 'Arizona Diamondbacks', 'Anaheim Angels', 'Florida Marlins', 'Boston Red Sox', 'Chicago White Sox', 'St. Louis Cardinals', 'Boston Red Sox', 'Philadelphia Phillies', 'New York Yankees', 'San Francisco Giants', 'St. Louis Cardinals', 'San Francisco Giants', 'Boston Red Sox'] #sort list alphabetically Champs.sort() for team in [ele for ind, ele in enumerate(Champs,1) if ele not in Champs[ind:]]: count = 0 for ele in Champs: if team == ele: count += 1 print((team.strip(),count.strip())) count = 0 </code></pre> <p>--------My Output follows-----------</p> <pre><code>Welcome to the world series team count report generator. Choose an option from the following list. 1: Find out the count of wins for a single team. 2: Run a report showing all teams with their count of wins. 3: Exit the program. Enter your choice: 2 Team Count of Wins ------------------------------ Team Name Wins ('Anaheim Angels', 1) ('Arizona Diamondbacks', 1) ('Atlanta Braves', 1) ('Baltimore Orioles', 3) ('Boston Americans', 1) ('Boston Braves', 1) ('Boston Red Sox', 7) ('Brooklyn Dodgers', 1) ('Chicago Cubs', 2) ('Chicago White Sox', 3) ('Cincinnati Reds', 5) ('Cleveland Indians', 2) ('Detroit Tigers', 4) ('Florida Marlins', 2) ('Kansas City Royals', 1) ('Los Angeles Dodgers', 5) ('Milwaukee Braves', 1) ('Minnesota Twins', 2) ('New York Giants', 5) ('New York Mets', 2) ('New York Yankees', 27) ('Oakland Athletics', 4) ('Philadelphia Athletics', 5) ('Philadelphia Phillies', 2) ('Pittsburgh Pirates', 5) ('San Francisco Giants', 2) ('St. Louis Cardinals', 11) ('Toronto Blue Jays', 2) ('Washington Senators', 1) </code></pre>
-2
2016-10-09T05:47:16Z
39,940,507
<p>it is not part of your element . <code>print()</code> adds this when it display list, tuple, dict. And you see it because you used too many <code>()</code> and created tuple.</p> <p>You have </p> <pre><code>print( (team.strip(), count.strip()) ) </code></pre> <p>where <code>(team.strip(), count.strip())</code> means tuple. </p> <p>You need </p> <pre><code>print( team.strip(), count ) </code></pre>
2
2016-10-09T05:56:54Z
[ "python", "list", "output", "strip" ]
How do you create a gtk window in python and also have code running in the background?
39,940,463
<p>I am trying to create a GUI window with a web address inside (a video stream in this case) while also having some additional code running in the background that communicate with the GPIO ports on a Raspberry Pi. I can get the window to work but the background code only starts when the window is closed. Or if I reverse the order of the code the GPIO code stops working when the window is open. Here is some example code. </p> <pre><code>import gtk import webkit import gobject import RPi.GPIO as GPIO from time import sleep import os ip = raw_input("Enter the last 3 digits of IP address: ") awesome = "http://192.168.0." + ip + ":9090/stream" print awesome os.system("sudo uv4l -nopreview --auto-video_nr --driver raspicam --encoding mjpeg --width 640 --height 480 --framerate 30 --server-option '--port=9090' --server-option '--max-queued-connections=30' --server-option '--max-streams=25' --server-option '--max-threads=29'") gobject.threads_init() win = gtk.Window() win.connect('destroy', lambda w: gtk.main_quit()) bro = webkit.WebView() bro.open(awesome) win.add(bro) win.show_all() gtk.main() GPIO.setmode(GPIO.BOARD) GPIO.setup(38, GPIO.OUT) GPIO.setup(40, GPIO.OUT) GPIO.setup(37, GPIO.OUT) GPIO.setup(35, GPIO.OUT) GPIO.output(38, GPIO.HIGH) GPIO.output(40, GPIO.LOW) GPIO.output(37, GPIO.LOW) GPIO.output(35, GPIO.HIGH) sleep(2) </code></pre>
0
2016-10-09T05:50:04Z
39,940,602
<p><code>gtk.main()</code> runs till you close window (it is call "main loop" or "event loop" and it does everything in GUI program - get key/mouse event, send it to widgets, redraw widgets, run functions when ypu press button, etc.). </p> <p>You have to use <code>Threading</code> to run (long-running) code at the same time or use some <code>Timer</code> class in GUI to execute some code periodically.</p>
1
2016-10-09T06:14:41Z
[ "python", "raspberry-pi", "gtk" ]
stuck in implementing search in django
39,940,520
<p>I want to implement search in django. I don't use any search technique like solar etc. I am using simple filter query of django. Now the problem is this: I have a model <strong><code>Product</code></strong> with five field <code>name</code>, <code>cost</code>, <code>brand</code>, <code>expiry_date</code>, <code>weight</code> I want to implement a advanced search feature with all fields, by:</p> <pre><code>name = request.GET.get('name') </code></pre> <p>I get a value on which basis I search all product. What I want is that when <strong><code>name = None</code></strong>, it has to search for all names. <strong>So problem is this: if values are not coming by user side, how can i search for all names?</strong></p>
1
2016-10-09T05:59:42Z
39,940,558
<p>if you want when the name is None, you have to search all names in Product Model try this logic</p> <pre><code>if name == None: result = Product.objects.all() else: result = Product.objects.filter(name = name) </code></pre>
0
2016-10-09T06:06:15Z
[ "python", "django" ]
stuck in implementing search in django
39,940,520
<p>I want to implement search in django. I don't use any search technique like solar etc. I am using simple filter query of django. Now the problem is this: I have a model <strong><code>Product</code></strong> with five field <code>name</code>, <code>cost</code>, <code>brand</code>, <code>expiry_date</code>, <code>weight</code> I want to implement a advanced search feature with all fields, by:</p> <pre><code>name = request.GET.get('name') </code></pre> <p>I get a value on which basis I search all product. What I want is that when <strong><code>name = None</code></strong>, it has to search for all names. <strong>So problem is this: if values are not coming by user side, how can i search for all names?</strong></p>
1
2016-10-09T05:59:42Z
39,940,590
<p>You didn't show your search query. However, I think using <a href="https://docs.djangoproject.com/en/1.10/ref/models/querysets/#contains" rel="nofollow"><code>contains</code></a> (or <a href="https://docs.djangoproject.com/en/1.10/ref/models/querysets/#icontains" rel="nofollow"><code>icontains</code></a> for case insensitive match) will help you solve the problem, with the benefit of being able to search for say first names, last names and names containing a matching text.</p> <p>You would do:</p> <pre><code>name = request.GET.get('name', '') search_result = Product.objects.filter(name__icontains=name) </code></pre> <p>Notice the <code>get</code> method has been instructed to return a <code>''</code> instead of the default <code>None</code>. And keep in mind that all strings in Python contain the empty string <code>''</code>. So when no <code>name</code> is sent via the <code>request</code>, every <code>Product</code> in the DB (with a not <em>NULL</em> name) is returned, as their names all contain the empty string <code>''</code>.</p>
2
2016-10-09T06:13:32Z
[ "python", "django" ]
stuck in implementing search in django
39,940,520
<p>I want to implement search in django. I don't use any search technique like solar etc. I am using simple filter query of django. Now the problem is this: I have a model <strong><code>Product</code></strong> with five field <code>name</code>, <code>cost</code>, <code>brand</code>, <code>expiry_date</code>, <code>weight</code> I want to implement a advanced search feature with all fields, by:</p> <pre><code>name = request.GET.get('name') </code></pre> <p>I get a value on which basis I search all product. What I want is that when <strong><code>name = None</code></strong>, it has to search for all names. <strong>So problem is this: if values are not coming by user side, how can i search for all names?</strong></p>
1
2016-10-09T05:59:42Z
39,940,926
<p>Try this:</p> <pre><code>result = Product.objects.all() name = request.GET.get('name', None) if name: result = result.objects.filter(name__icontains=name) </code></pre>
0
2016-10-09T07:03:27Z
[ "python", "django" ]
install storm on windows 10
39,940,644
<p>I'm new here and I've tried a lot of my own effort before calling you, guys.</p> <p>I'm trying to install apache storm on windows 10. I have installed ZooKeeper successfully, and set the Java_Home and Storm_Home. Python is C:/Python27. What I don't understand is those instructions:</p> <p>PATH Add:</p> <pre><code>%STORM_HOME%\bin;%JAVA_HOME%\bin;C:\Python27;C:\Python27\Lib\site-packages\;C:\Python27\Scripts\; </code></pre> <p>PATHEXT Add:</p> <pre><code>.PY </code></pre> <p>I've tried to add .PY to PATHTEXT and the &amp;STORM_HOME%bin;... to the Path on System Variables but when I open the cmd and go to the Storm_Home, and run Storm nimbus, I get "storm is not recognized as an internal or external command"</p> <p>Any help would be appreciated</p> <p>TNX Meron</p>
1
2016-10-09T06:21:58Z
39,940,839
<pre><code>Download this storm setup from below link: https://dl.dropboxusercontent.com/s/iglqz73chkul1tu/storm-0.9.1-incubating-SNAPSHOT-12182013.zip Extract that file to the location of your choice. i choose 'C:\' **Configure Environment Variables**: On Windows Storm requires the STORM_HOME and JAVA_HOME environment variables to be set, as well as some additions to the PATH variable: </code></pre>
0
2016-10-09T06:49:19Z
[ "java", "python", "apache" ]
BFMatcher match in OpenCV throwing error
39,940,766
<p>I am using SURF descriptors for image matching. I am planning to match a given image to a database of images.</p> <pre><code>import cv2 import numpy as np surf = cv2.xfeatures2d.SURF_create(400) img1 = cv2.imread('box.png',0) img2 = cv2.imread('box_in_scene.png',0) kp1,des1 = surf.detectAndCompute(img1,None) kp2,des2 = surf.detectAndCompute(img2,None) bf = cv2.BFMatcher(cv2.NORM_L1,crossCheck=True) #I am planning to add more descriptors bf.add(des1) bf.train() #This is my test descriptor bf.match(des2) </code></pre> <p>The issue is with <code>bf.match</code> is that I am getting the following error:</p> <pre><code>OpenCV Error: Assertion failed (type == src2.type() &amp;&amp; src1.cols == src2.cols &amp;&amp; (type == CV_32F || type == CV_8U)) in batchDistance, file /build/opencv/src/opencv-3.1.0/modules/core/src/stat.cpp, line 3749 Traceback (most recent call last): File "image_match4.py", line 16, in &lt;module&gt; bf.match(des2) cv2.error: /build/opencv/src/opencv-3.1.0/modules/core/src/stat.cpp:3749: error: (-215) type == src2.type() &amp;&amp; src1.cols == src2.cols &amp;&amp; (type == CV_32F || type == CV_8U) in function batchDistance </code></pre> <p>The error is similar to <a href="http://stackoverflow.com/questions/24224846/opencv-bfmatcher-match-always-return-error">this</a> post. The explanation given is incomplete and inadequate.I want to know how to resolve this issue. I have used ORB descriptors as well with BFMatcher having <code>NORM_HAMMING</code> distance. The error resurfaces. Any help will be appreciated.</p> <p>The two images that I have used for this are:</p> <p><a href="http://i.stack.imgur.com/Er7vx.png" rel="nofollow"><img src="http://i.stack.imgur.com/Er7vx.png" alt="box.png"></a></p> <p>box.png </p> <p><a href="http://i.stack.imgur.com/gAz96.png" rel="nofollow"><img src="http://i.stack.imgur.com/gAz96.png" alt="box_in_scene.png"></a></p> <p>box_in_scene.png</p> <p>I am using Python 3.5.2 and OpenCV 3.1.x in linux.</p>
1
2016-10-09T06:38:34Z
39,946,169
<p><strong>To search between descriptors of two images</strong> use:</p> <pre><code>img1 = cv2.imread('box.png',0) img2 = cv2.imread('box_in_scene.png',0) kp1,des1 = surf.detectAndCompute(img1,None) kp2,des2 = surf.detectAndCompute(img2,None) bf = cv2.BFMatcher(cv2.NORM_L1,crossCheck=False) matches = bf.match(des1,des2) </code></pre> <p><strong>To search among multiple images</strong></p> <p>The <code>add</code> method is used to add descriptor of multiple test images. Once, all descriptors are indexed, you run <code>train</code> method to build an underlying Data Structure(example: KdTree which will be used for searching in case of FlannBasedMatcher). You can then run <code>match</code> to find if which test image is a closer match to which query image. You can check <a href="https://en.wikipedia.org/wiki/K-d_tree" rel="nofollow">K-d_tree</a> and see how it can be used to search for multidimensional vectors(Surf gives 64-dimensional vector).</p> <p><strong>Note:-</strong> BruteForceMatcher, as name implies, has no internal search optimizing data structure and thus has empty train method.</p> <p><strong>Code Sample for Multiple Image search</strong></p> <pre><code>import cv2 import numpy as np surf = cv2.xfeatures2d.SURF_create(400) # Read Images train = cv2.imread('box.png',0) test = cv2.imread('box_in_scene.png',0) # Find Descriptors kp1,trainDes1 = surf.detectAndCompute(train, None) kp2,testDes2 = surf.detectAndCompute(test, None) # Create BFMatcher and add cluster of training images. One for now. bf = cv2.BFMatcher(cv2.NORM_L1,crossCheck=False) # crossCheck not supported by BFMatcher clusters = np.array([trainDes1]) bf.add(clusters) # Train: Does nothing for BruteForceMatcher though. bf.train() matches = bf.match(testDes2) matches = sorted(matches, key = lambda x:x.distance) # Since, we have index of only one training image, # all matches will have imgIdx set to 0. for i in range(len(matches)): print matches[i].imgIdx </code></pre> <p>For DMatch output of bf.match, see <a href="http://docs.opencv.org/2.4/modules/features2d/doc/common_interfaces_of_descriptor_matchers.html#dmatch" rel="nofollow">docs</a>.</p> <p>See full example for this here: <a href="http://docs.opencv.org/3.0-beta/doc/py_tutorials/py_feature2d/py_matcher/py_matcher.html" rel="nofollow">Opencv3.0 docs</a>.</p> <p><strong>Other Info</strong></p> <p>OS: Mac.<br> Python: 2.7.10.<br> Opencv: 3.0.0-dev [If remember correctly, installed using brew]. </p>
1
2016-10-09T17:02:52Z
[ "python", "opencv", "surf", "orb" ]
How do I use a webscraper in python if I have a minimal OS?
39,940,786
<p>I am trying to make my raspberry pi interact with my wifi router using python. Since my router doesn't have an API, I need to use a webscraper or something similar in python to enter password, go to links, etc... I have tried using selenium and Beautifulsoup, but those both require web browsers that I cant get on raspbian minimal.</p> <pre><code>from selenium import webdriver driver = webdriver.Firefox </code></pre> <p>and the result...</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: 'module' object has no attribute 'firefox' </code></pre>
1
2016-10-09T06:41:24Z
39,940,850
<p>Most routers use basic authentication. You can supply the username and password in the request URL by the following scheme: <code>https://USERNAME:PASSWORD@webaddress.com</code></p> <p>You don't need Selenium to make HTTP requests. Selenium is for browser automation. BeautifulSoup is for parsing HTML and has nothing to do with making HTTP requests.</p> <p>You can use a library like <code>requests</code> to make HTTP requests without the need for any browser.</p>
0
2016-10-09T06:50:38Z
[ "python", "web-scraping", "raspberry-pi", "raspbian" ]
Counting seed values from first sequence in second sequence
39,940,809
<p>If a function is given a sequence <code>seeds</code> of seed values, it needs to count for every single seed value the number of times they show up in the 2nd sequence <code>xs</code>. Then it should return the counts as a list of integers, in the same order of the seed values. If <code>seeds</code> includes duplicated values, keep duplicated counts in the returned list. For example, <code>count_each([10,20],[10,20,50,20,40,20])</code> should return <code>[1,3]</code> and <code>count_each('aeiou','encyclopedia') should return [1,2,1,1,0]</code>.</p> <p>I'm stuck on how to program this function. This is what I have so far but I can't figure out how exactly I would count the number of seed values in the second sequence and not just check if the values exist. Any help on this would be appreciated. </p> <pre><code>def count_each(seeds,xs): if seeds in xs: if seeds == True return seeds elif seeds == False return None </code></pre>
0
2016-10-09T06:45:02Z
39,940,876
<blockquote> <p>I can't figure out how exactly I would count the number of seed values in the second sequence and not just check if the values exist.</p> </blockquote> <p>Python sequences have a handy <code>.count</code> method.</p> <pre><code>&gt;&gt;&gt; [1,1,1,2,3,4,5].count(1) 3 &gt;&gt;&gt; "ababababcdefg".count("b") 4 </code></pre>
2
2016-10-09T06:56:07Z
[ "python", "sequence", "counting", "seed" ]
Counting seed values from first sequence in second sequence
39,940,809
<p>If a function is given a sequence <code>seeds</code> of seed values, it needs to count for every single seed value the number of times they show up in the 2nd sequence <code>xs</code>. Then it should return the counts as a list of integers, in the same order of the seed values. If <code>seeds</code> includes duplicated values, keep duplicated counts in the returned list. For example, <code>count_each([10,20],[10,20,50,20,40,20])</code> should return <code>[1,3]</code> and <code>count_each('aeiou','encyclopedia') should return [1,2,1,1,0]</code>.</p> <p>I'm stuck on how to program this function. This is what I have so far but I can't figure out how exactly I would count the number of seed values in the second sequence and not just check if the values exist. Any help on this would be appreciated. </p> <pre><code>def count_each(seeds,xs): if seeds in xs: if seeds == True return seeds elif seeds == False return None </code></pre>
0
2016-10-09T06:45:02Z
39,940,911
<p>Check out <code>collections.Counter()</code></p> <pre><code>import collections def count_each(seeds,xs): c = collections.Counter(xs) return [c[seed] for seed in seeds] </code></pre>
2
2016-10-09T07:01:53Z
[ "python", "sequence", "counting", "seed" ]
Counting seed values from first sequence in second sequence
39,940,809
<p>If a function is given a sequence <code>seeds</code> of seed values, it needs to count for every single seed value the number of times they show up in the 2nd sequence <code>xs</code>. Then it should return the counts as a list of integers, in the same order of the seed values. If <code>seeds</code> includes duplicated values, keep duplicated counts in the returned list. For example, <code>count_each([10,20],[10,20,50,20,40,20])</code> should return <code>[1,3]</code> and <code>count_each('aeiou','encyclopedia') should return [1,2,1,1,0]</code>.</p> <p>I'm stuck on how to program this function. This is what I have so far but I can't figure out how exactly I would count the number of seed values in the second sequence and not just check if the values exist. Any help on this would be appreciated. </p> <pre><code>def count_each(seeds,xs): if seeds in xs: if seeds == True return seeds elif seeds == False return None </code></pre>
0
2016-10-09T06:45:02Z
39,941,178
<pre><code>def count_letter(seeds,xs): for c in seeds: count=0 for d in xs: if c==d: count=count+1 print (c,"Occured ",count,"times") count_letter([10,20],[10,20,30,10]) count_letter('aeiou','encyclopedia') </code></pre>
0
2016-10-09T07:39:07Z
[ "python", "sequence", "counting", "seed" ]
How to select a single JSON object out of several and navigate its hierarchy in python
39,940,873
<p>I have a webpage that contains several javascript elements. I only want to access one, named <code>SOURCE.pdp.propertyJSON</code>, and access the attributes in a PYTHONIC manner.</p> <p>An edited (for the sake of readability) version of the HTML sourcecode is below; following is my python code.</p> <p>Any pointers would be greatly appreciated!</p> <pre class="lang-js prettyprint-override"><code>&lt;script type="text/javascript"&gt; SOURCE = SOURCE || {}; SOURCE.pdp = SOURCE.pdp || {}; SOURCE.pdp.propertyJSON = { "neighborhood": "Westwood", "neighborhoodId": 7187, "zipCode": "90024", "city": "Los Angeles", "county": "Los Angeles", "countyFIPS": "06037", "stateCode": "CA", "stateName": "California", "type": "CONDO", "typeDisplay": "Condo", "numBedrooms": "2", "numBathrooms": 2, "numFullBathrooms": 2, "numBeds": 2, "indexSource": "Assessor", "isForeclosure": false, "isOpaqueBAL": false, "foreclosureStatus": "", "isSrpFeatured": false, "price": null, "sqft": 1321, "formattedBedAndBath": "2bd, 2 full ba", "formattedSqft": "1,321 sqft" } pdp_location_data = { "neighborhood": { "locationId": "87308", "name": "Westwood", "locationType": "neighborhood", "altId": "7187" }, "state": { "locationId": "5", "name": "California", "locationType": "state", "altId": "CA" }, "county": { "locationId": "57", "name": "Los Angeles County", "locationType": "county", "altId": "06037" }, "city": { "locationId": "22637", "name": "Los Angeles", "locationType": "city", "altId": "4396" }, "zipCode": { "locationId": "76090", "name": "90024", "locationType": "zipCode", "altName": "90024", "altId": "90024" } }; SOURCE.pdp.isCountySupportsValuation = true; SOURCE.pdp.isInHighDemandRegion = false; var _SPANLONG = pdp_location_data.longitude; var _SPANLAT = pdp_location_data.latitude; var _CENLONG = pdp_location_data.longitude; var _CENLAT = pdp_location_data.latitude; &lt;/script&gt; </code></pre> <p>Beware the ugly python!</p> <pre><code> from bs4 import BeautifulSoup as bsoup import requests as rq url = 'https://www.SOURCE.com' source_code = rq.get(url).text soupcon = bsoup(source_code,"html.parser") souper = soupcon.find_all('script', {'type': 'text/javascript'}) for line in souper: if format(line).find('SOURCE.pdp.propertyJSON') != -1: parts = format(line).split(',') for var in parts: if var.find('zipCode') != -1: zipCode = var.split(':')[1].strip('"') elif var.find('numBathrooms') != -1: numBathrooms = var.split(':')[1].strip('"') </code></pre> <p>As you can see, I am currently accessing the JS object I want by finding all script elements that are of the type text/javascript, iterating through them to find the script that contains the object that I want, then splitting the entire script by the JS separator <code>','</code>, and identifying elements of the JS object by searching through them for my key words. Not an ideal solution.</p>
0
2016-10-09T06:55:11Z
39,943,498
<p>You can load the data as a dict using json.loads:</p> <pre><code>from bs4 import BeautifulSoup as bsoup import re from json import loads source = """&lt;script type="text/javascript"&gt; SOURCE = SOURCE || {}; SOURCE.pdp = SOURCE.pdp || {}; SOURCE.pdp.propertyJSON = { "neighborhood": "Westwood", "neighborhoodId": 7187, "zipCode": "90024", "city": "Los Angeles", "county": "Los Angeles", "countyFIPS": "06037", "stateCode": "CA", "stateName": "California", "type": "CONDO", "typeDisplay": "Condo", "numBedrooms": "2", "numBathrooms": 2, "numFullBathrooms": 2, "numBeds": 2, "indexSource": "Assessor", "isForeclosure": false, "isOpaqueBAL": false, "foreclosureStatus": "", "isSrpFeatured": false, "price": null, "sqft": 1321, "formattedBedAndBath": "2bd, 2 full ba", "formattedSqft": "1,321 sqft" } pdp_location_data = { "neighborhood": { "locationId": "87308", "name": "Westwood", "locationType": "neighborhood", "altId": "7187" }, "state": { "locationId": "5", "name": "California", "locationType": "state", "altId": "CA" }, "county": { "locationId": "57", "name": "Los Angeles County", "locationType": "county", "altId": "06037" }, "city": { "locationId": "22637", "name": "Los Angeles", "locationType": "city", "altId": "4396" }, "zipCode": { "locationId": "76090", "name": "90024", "locationType": "zipCode", "altName": "90024", "altId": "90024" } }; SOURCE.pdp.isCountySupportsValuation = true; SOURCE.pdp.isInHighDemandRegion = false; var _SPANLONG = pdp_location_data.longitude; var _SPANLAT = pdp_location_data.latitude; var _CENLONG = pdp_location_data.longitude; var _CENLAT = pdp_location_data.latitude; &lt;/script&gt;""" soup = bsoup(source,"html.parser") json_re = re.compile("SOURCE\.pdp\.propertyJSON\s+=\s+(\{.*\})\s+pdp_location_data") scr = soup.find("script", text=re.compile("SOURCE.pdp.propertyJSON")).text js_raw = json_re.search(scr).group(1) json_dict = loads(js_raw) </code></pre> <p>Which would give you:</p> <pre><code>{u'numBeds': 2, u'neighborhood': u'Westwood', u'stateName': u'California', u'numFullBathrooms': 2, u'indexSource': u'Assessor', u'countyFIPS': u'06037', u'city': u'Los Angeles', u'isSrpFeatured': False, u'type': u'CONDO', u'formattedSqft': u'1,321 sqft', u'isOpaqueBAL': False, u'price': None, u'zipCode': u'90024', u'numBedrooms': u'2', u'neighborhoodId': 7187, u'county': u'Los Angeles', u'formattedBedAndBath': u'2bd, 2 full ba', u'sqft': 1321, u'numBathrooms': 2, u'stateCode': u'CA', u'isForeclosure': False, u'typeDisplay': u'Condo', u'foreclosureStatus': u''} </code></pre> <p>If you want the <code>pdp_location_data</code> json just apply the exact same logic.</p>
0
2016-10-09T12:14:36Z
[ "javascript", "python", "json", "beautifulsoup" ]
Plotting over groups of values in Python
39,940,958
<p>I have a dataframe that looks like this. </p> <pre><code> country age new_user 298408 UK 32 1 193010 US 37 0 164494 UK 17 0 28149 US 34 0 297080 China 29 1 </code></pre> <p>I want to plot the count of new_users for the age groups (20-30, 30-40 and so on) for each country in a single graph in Python. </p> <p>Basically, I need to plot new_user(value 0) for all the age groups and new_user(value 1) for all the age groups for all the countries.</p> <p>I am finding it hard to group the ages into 20-30,30-40 and so on. Can someone please help me plot this using either seaborn or ggplot or matplotlib in python? ggplot is preferrable!</p> <p>Thank you.</p>
0
2016-10-09T07:07:41Z
39,947,623
<pre><code>import seaborn as sns from pandas import DataFrame from matplotlib.pyplot import show, legend d = {"country": ['UK','US','US','UK','PRC'], "age": [32, 37, 17, 34, 29], "new_user": [1, 0, 0, 0,1]} df = DataFrame(d) bins = range(0, 100, 10) ax = sns.distplot(df.age[df.new_user==1], color='red', kde=False, bins=bins, label='New') sns.distplot(df.age[df.new_user==0], ax=ax, # Overplots on first plot color='blue', kde=False, bins=bins, label='Existing') legend() show() </code></pre> <p><a href="http://i.stack.imgur.com/W0WHV.png" rel="nofollow"><img src="http://i.stack.imgur.com/W0WHV.png" alt="enter image description here"></a></p>
0
2016-10-09T19:25:12Z
[ "python", "matplotlib", "plot", "seaborn", "python-ggplot" ]
Create sparse matrix for two columns in a Pandas Dataframe
39,941,060
<p>I am trying to create a sparse matrix out of a Pandas Dataset (>10Gb)</p> <p>Assume I have a dataset of the type</p> <p>Table: Class</p> <pre><code> student |teacher --------------------- 0 | abc | a 1 | def | g </code></pre> <p>And I have a list of students </p> <pre><code>students = [ "abc", "def", "ghi", "jkl","mno"] </code></pre> <p>and list of teachers </p> <pre><code>teachers = ["a","b","c","d","e","f","g"] </code></pre> <p>My goal is to create a sparse matrix out of them such that there is a boolean 1 if there is a corresponding relationship between student-teacher in table Class.</p> <p>The dense matrix should look like this:</p> <pre><code> a b c d e f g abc 1 0 0 0 0 0 0 def 0 0 0 0 0 0 1 ghi 0 0 0 0 0 0 0 jkl 0 0 0 0 0 0 0 mno 0 0 0 0 0 0 0 </code></pre> <p>Now in my real dataset I have 700K values of students and another 100K values of teachers. </p> <p>Initially I tried to construct a simple dense matrix and then convert it to a sparse matrix using scipy. However, 700k*100k bytes = ~70GB and as you can realize it didn't work.</p> <p>So I tried to assign unique values to both students and teachers and then append those values to rows and columns and tried to create a sparse matrix in Coordinate format.</p> <p>Code:</p> <pre><code># Get unique value for each student and teacher dictstudent = {} count = 0 for i in rows: dictstudent[i] = count count +=1 dictteacher ={} count = 0 for i in cols: dictteacher[i] = count count +=1 </code></pre> <p>Now that each teacher and student has a numeric number associated with it. Store numeric value of student if it appears in the table class and numeric value of teacher in r and c.</p> <pre><code>r = [] c = [] for row,col in zip(student,teacher): r.append(dictstudent[row]) c.append(dictteacher[col]) values = [1] * class["student"].size #From the pandas dataframe class </code></pre> <p>Then load it to make a sparse matrix</p> <pre><code>a = sparse.coo_matrix((values,(r,c)),shape=(len(students),len(teachers))) </code></pre> <p>This worked fine for my small test dataset. However for my actual large dataset it crashed.</p> <p>Is there a better way to do this?</p>
1
2016-10-09T07:22:52Z
39,942,704
<p>You can convert the columns to category type and then use the <code>codes</code> to create the <code>coo_matrix</code> object:</p> <pre><code>import numpy as np import string import random import pandas as pd from scipy import sparse lowercase = list(string.ascii_lowercase) students = np.random.choice(lowercase, size=[20, 3]).view("&lt;U3").ravel().tolist() teachers = np.random.choice(lowercase, 8).tolist() df = pd.DataFrame({"student": [random.choice(students) for _ in range(30)], "teacher": [random.choice(teachers) for _ in range(30)]}) df = df.apply(lambda s:s.astype("category")) arr = sparse.coo_matrix((np.ones(df.shape[0]), (df.student.cat.codes, df.teacher.cat.codes))) </code></pre> <p>You can get the labels by <code>df.student.cat.categories</code> and <code>df.teacher.cat.categories</code>.</p>
1
2016-10-09T10:44:17Z
[ "python", "pandas", "matrix", "scipy", "sparse-matrix" ]
pycharm can't complete remote interpreter setup for Docker
39,941,116
<p>I'm new to Docker. I'm using Docker &amp; docker-compose, going through a flask tutorial. The base docker image is python 2.7 slim. It's running on Linux. docker 1.11.2 The application is working fine. I want to get pycharm pro connecting to the remote interpreter, something I have never done before. </p> <p>I followed the instructions for docker-compose. Initially it was failing because it could not connect to port 2376. I added this port to docker-compose.yml and the error went away. However, trying to save the configuration now stalls/hangs with a dialog 'Getting Remote Interpreter Version'. This never completes. Also, I can't quit pycharm. This happens in Pycharm 2016.2 and 2016.3 EAP (2nd). </p> <p>The help say "SFTP support is required for copying helpers to the server". Does this mean I need to do something? </p>
0
2016-10-09T07:30:37Z
39,960,909
<p><strong>I - docker-compose up</strong></p> <p>I think PyCharm will run <code>docker-compose up</code>, have you try to run this command first in your terminal (from where your <code>docker-compose.yml</code> is) ?</p> <p>Maybe if some errors occur, you will get more info in your terminal.</p> <p><strong>II - pycharm docker configuration</strong></p> <p>Otherwise it could be due to your docker machine configuration in PyCharm.</p> <p>What I do to configure my machine and to be sure this one is correctly configured:</p> <p>1 - run <code>docker-machine ls</code> in your shell</p> <p><a href="http://i.stack.imgur.com/J8Lca.png" rel="nofollow"><img src="http://i.stack.imgur.com/J8Lca.png" alt="enter image description here"></a></p> <p>2 - copy paste the url without <code>tcp://</code></p> <p>3 - go to pycharm preferences -> <code>Build, Execution, Deployement</code> -> <code>Docker</code> -> <code>+</code> to create a new server, fill the server <code>name</code> field</p> <p><a href="http://i.stack.imgur.com/jd8KW.png" rel="nofollow"><img src="http://i.stack.imgur.com/jd8KW.png" alt="enter image description here"></a></p> <p>4 - paste previously copied url keeping <code>https://</code></p> <p>5 - fill the path of your machine certificates folder</p> <p>6 - tick <code>Import credentials from Docker Machine</code></p> <p>7 - click <code>Detect</code> -> your machine should appear in the selection list</p> <p>8 - save this server</p> <p>9 - select this server when configuring your remote interpreter, from PyCharm Preferences -> <code>Project</code> -> <code>Project Interpreter</code> -> <code>wheel</code> -> <code>add remote</code> -> <code>Docker</code> or <code>Docker Compose</code></p> <p><a href="http://i.stack.imgur.com/CIzKN.png" rel="nofollow"><img src="http://i.stack.imgur.com/CIzKN.png" alt="enter image description here"></a></p> <p>10 - you should be able to select a service name</p> <p>11 - save your new interpreter</p> <p>11 - try run your test twice, sometimes it could take time to initialize</p>
0
2016-10-10T14:43:34Z
[ "python", "docker", "pycharm" ]
pycharm can't complete remote interpreter setup for Docker
39,941,116
<p>I'm new to Docker. I'm using Docker &amp; docker-compose, going through a flask tutorial. The base docker image is python 2.7 slim. It's running on Linux. docker 1.11.2 The application is working fine. I want to get pycharm pro connecting to the remote interpreter, something I have never done before. </p> <p>I followed the instructions for docker-compose. Initially it was failing because it could not connect to port 2376. I added this port to docker-compose.yml and the error went away. However, trying to save the configuration now stalls/hangs with a dialog 'Getting Remote Interpreter Version'. This never completes. Also, I can't quit pycharm. This happens in Pycharm 2016.2 and 2016.3 EAP (2nd). </p> <p>The help say "SFTP support is required for copying helpers to the server". Does this mean I need to do something? </p>
0
2016-10-09T07:30:37Z
39,971,120
<p>I'm not using docker-machine The problem was that TCP access to the docker API is not established by default under ubuntu 16.04. </p> <p>There are suggestions to enable TCP/IP access.</p> <p>However, JetBrains gave me the simplest solution:</p> <blockquote> <p>If you are using Linux it is most likely that Docker installed with its default setup and Docker is expecting to be used through UNIX domain file socket /var/run/docker.sock. And you should specify unix:///var/run/docker.sock in the API URL field. Please comment whether it helps!</p> </blockquote> <p>This suggestion worked with my Ubuntu 16.04 -derived distribution.</p> <p>This goes into the Docker entry in PyCharm preferences under Build, Execution, Deployment.</p> <p>You can also edit this while setting up a remote interpreter, but only by making a new Docker entry.</p> <p><strong>TCP/IP Method</strong> </p> <p>This method works if you want TCP/IP access, but this is a security risk. The socket approach is better, which is probably why it is the default.</p> <p><a href="https://coreos.com/os/docs/latest/customizing-docker.html" rel="nofollow">https://coreos.com/os/docs/latest/customizing-docker.html</a></p> <blockquote> <p>Customizing docker</p> <p>The Docker systemd unit can be customized by overriding the unit that ships with the default CoreOS settings. Common use-cases for doing this are covered below.</p> <p>Enable the remote API on a new socket</p> <p>Create a file called /etc/systemd/system/docker-tcp.socket to make Docker available on a TCP socket on port 2375.</p> <pre><code>[Unit] Description=Docker Socket for the API [Socket] ListenStream=2375 BindIPv6Only=both Service=docker.service [Install] WantedBy=sockets.target </code></pre> <p>Then enable this new socket:</p> <pre><code>systemctl enable docker-tcp.socket systemctl stop docker systemctl start docker-tcp.socket systemctl start docker </code></pre> <p>Test that it’s working:</p> <pre><code>docker -H tcp://127.0.0.1:2375 ps </code></pre> </blockquote> <p>Once I thought to search for ubuntu 16.04 I came across simpler solutions, but I did not test them. </p> <p>For instance:</p> <p><a href="https://www.ivankrizsan.se/2016/05/18/enabling-docker-remote-api-on-ubuntu-16-04/" rel="nofollow">https://www.ivankrizsan.se/2016/05/18/enabling-docker-remote-api-on-ubuntu-16-04/</a></p> <blockquote> <p>Edit the file /lib/systemd/system/docker.service</p> <p>Modify the line that starts with ExecStart to look like this:</p> <pre><code>ExecStart=/usr/bin/docker daemon -H fd:// -H tcp://0.0.0.0:2375 </code></pre> <p>Where my addition is the “-H tcp://0.0.0.0:2375” part. Save the modified file. Restart the Docker service:</p> <pre><code>sudo service docker restart </code></pre> <p>Test that the Docker API is indeed accessible:</p> <pre><code>curl http://localhost:2375/version </code></pre> </blockquote>
0
2016-10-11T05:44:41Z
[ "python", "docker", "pycharm" ]
Don't show zero values on 2D heat map
39,941,128
<p>I want to plot a 2D map of a sillicon wafer dies. Hence only the center portion have values and corners have the value 0. I'm using matplotlib's plt.imshow to obtain a simple map as follows:</p> <pre><code>data = np.array([[ 0. , 0. , 1. , 1. , 0. , 0. ], [ 0. , 1. , 1. , 1. , 1. , 0. ], [ 1. , 2. , 0.1, 2. , 2. , 1. ], [ 1. , 2. , 2. , 0.1, 2. , 1. ], [ 0. , 1. , 1. , 1. , 1. , 0. ], [ 0. , 0. , 1. , 1. , 0. , 0. ]]) plt.figure(1) plt.imshow(data ,interpolation='none') plt.colorbar() </code></pre> <p>And I obtain the following map: <a href="http://i.stack.imgur.com/NdOB3.png" rel="nofollow"><img src="http://i.stack.imgur.com/NdOB3.png" alt="enter image description here"></a></p> <p>Is there any way to remove the dark blue areas where the values are zeros while retaining the shape of the 'wafer' (the green, red and lighter blue areas)? Meaning the corners would be whitespaces while the remainder retains the color configuration. </p> <p>Or is there a better function I could use to obtain this?</p>
4
2016-10-09T07:31:56Z
39,941,795
<p>There are two ways to get rid of the dark blue corners:</p> <p>You can flag the data with zero values:</p> <pre><code>data[data == 0] = np.nan plt.imshow(data, interpolation = 'none', vmin = 0) </code></pre> <p>Or you can create a masked array for <code>imshow</code>:</p> <pre><code>data_masked = np.ma.masked_where(data == 0, data) plt.imshow(data_masked, interpolation = 'none', vmin = 0) </code></pre> <p>The two solutions above both solve your problem, although the use of masks is a bit more general.</p> <p>If you want to retain the exact color configuration you need to manually set the <code>vmin</code>/<code>vmax</code> arguments for plotting the image. Passing <code>vmin = 0</code> to <code>plt.imshow</code> above makes sure that the discarded zeros still show up on the color bar. <a href="http://i.stack.imgur.com/iIjpF.png" rel="nofollow"><img src="http://i.stack.imgur.com/iIjpF.png" alt="masked-imshow"></a></p>
3
2016-10-09T09:01:10Z
[ "python", "matplotlib" ]
Issue while running "lektor server" command on windows
39,941,130
<p>Python version : 2.7</p> <p>Showing the following error on lektor server command</p> <pre><code>Traceback (most recent call last): File "/Users/item4/Projects/lektor/lektor/devserver.py", line 49, in build builder.prune() File "/Users/item4/Projects/lektor/lektor/builder.py", line 1062, in prune for aft in build_state.iter_unreferenced_artifacts(all=all): File "/Users/item4/Projects/lektor/lektor/builder.py", line 371, in iter_unreferenced_artifacts and is_primary_source''', [artifact_name]) ProgrammingError: You must not use 8-bit bytestrings unless you use a text_factory that can interpret 8-bit bytestrings (like text_factory = str). It is highly recommended that you instead just switch your application to Unicode strings. </code></pre>
1
2016-10-09T07:32:09Z
39,941,457
<p>Finally I got the answer. It may helpful</p> <p>I have edited /Users/item4/Projects/lektor/lektor/builder.py and added a single line</p> <pre><code>con.text_factory = lambda x: unicode(x, 'utf-8', 'ignore') </code></pre> <p>after the following line</p> <pre><code>con = sqlite3.connect(self.buildstate_database_filename, timeout=10, check_same_thread=False) </code></pre> <p>Ref Link : <a href="http://hakanu.net/sql/2015/08/25/sqlite-unicode-string-problem/" rel="nofollow">http://hakanu.net/sql/2015/08/25/sqlite-unicode-string-problem/</a></p>
1
2016-10-09T08:14:58Z
[ "python", "lektor" ]
fast Python IPv6 compaction
39,941,174
<p>I'm trying to write some code that can quickly return a properly compacted IPv6 address. I've tried...</p> <pre><code>socket.inet_pton(socket.AF_INET6,socket.inet_PTON(socket.AF_INET6,address)) ipaddress.IPv6Address(address) IPy.IP(address) </code></pre> <p>...listed from faster to slower in their speed of handling IPv6 compaction. The first is the fastest (~3.6 seconds per 65,565 IP addresses), the second is less than half as fast as the first (~8.4 seconds per 65,565 IP addresses), the last one is almost twice as slow as the second (~14.4 seconds per 65,565 IP addresses).</p> <p>So, I set out to create my own...</p> <pre><code>import re from ipaddress import IPv6Address IPaddlist = [ '2001:db8:00:0:0:0:cafe:1111', '2001:db8::a:1:2:3:4', '2001:0DB8:AAAA:0000:0000:0000:0000:000C', '2001:db8::1:0:0:0:4', '2001:4958:5555::4b3:ffff', ] for addr in IPaddlist: address = ":".join('' if i=='0000' else i.lstrip('0') for i in addr.split(':')) address2 = (re.sub(r'(:)\1+', r'\1\1', address).lower()) print(address2) print(IPv6Address(addr)) print('\n') </code></pre> <p>It returns:</p> <pre><code>2001:db8::cafe:1111 2001:db8::cafe:1111 2001:db8::a:1:2:3:4 2001:db8:0:a:1:2:3:4 2001:db8:aaaa::c 2001:db8:aaaa::c 2001:db8::1::4 2001:db8:0:1::4 2001:4958:5555::4b3:ffff 2001:4958:5555::4b3:ffff </code></pre> <p>The first line of each entry is my code, the second is the correct compaction, using ipaddress.IPv6Address.</p> <p>As you can see, I'm close, but you know what they say about 'close'...</p> <p>Anyone have any pointers? I seem to have hit a roadblock.</p>
2
2016-10-09T07:38:30Z
39,943,161
<p>Just use <code>socket</code> functions. The first line of code in your question is almost 10 times faster than your string manipulations:</p> <pre><code>from socket import inet_ntop, inet_pton, AF_INET6 def compact1(addr, inet_ntop=inet_ntop, inet_pton=inet_pton, AF_INET6=AF_INET6): return inet_ntop(AF_INET6, inet_pton(AF_INET6, addr)) from ipaddress import IPv6Address def compact2(addr, IPv6Address=IPv6Address): return IPv6Address(addr) import re def compact3(addr, sub=re.sub): address = ":".join('' if i=='0000' else i.lstrip('0') for i in addr.split(':')) return sub(r'(:)\1+', r'\1\1', address).lower() </code></pre> <p>And now let's <code>%timeit</code>:</p> <pre><code>In[9]: ips = [':'.join('{:x}'.format(random.randint(0, 2**16 - 1)) for i in range(8)) for _ in range(65565)] In[10]: %timeit for ip in ips: compact1(ip) 10 loops, best of 3: 52.9 ms per loop In[11]: %timeit for ip in ips: compact2(ip) 1 loop, best of 3: 715 ms per loop In[12]: %timeit for ip in ips: compact3(ip) 1 loop, best of 3: 411 ms per loop </code></pre>
0
2016-10-09T11:39:12Z
[ "python", "python-3.x" ]
How is the .pop() method able to redefine a variable by only being the value of another?
39,941,196
<p>So in python if you create your <code>list</code>, then a new variable, <code>reject_list</code> and assign it the <code>.pop()</code> method, it changes the value in the previous <code>list</code> variable. </p> <pre><code>list = ['item', 'thing', 'piece'] reject_list = list.pop() print(list) ['item', 'thing'] </code></pre> <p>I understand this effect, but not how it's possible. How does assigning the method of one variable as the value of another retroactively change the value of the original variable without first being defined, like this: </p> <pre><code>list = ['item', 'thing', 'piece'] list = list.pop() print(list) ['item', 'thing'] </code></pre> <p>For instance, this doesn't work with the <code>.title()</code> method: </p> <pre><code>name = mike new_name = name.title() print(name) mike #the original name did not capitalize </code></pre> <p>so how is the .pop() method able to redefine a variable by only being the value of another?</p>
-1
2016-10-09T07:41:33Z
39,941,252
<p>Your explanation of what you're seeing is not correct. The change in the value of <code>list</code> has nothing to do with you assigning the result of <code>list.pop()</code> to <code>reject_list</code>.</p> <p>Python is an object-based language which means the basic element of data in it are <em>objects</em>, which are a collection of data (or <em>state</em>) and functions (called <em>methods</em>). Methods can access the state contained in the object they are called on and they can modify it. In the case of list, its elements are its state. The behaviour of <code>pop()</code> is to modify this state by removing the last element of the list it was called on and returning it. Therefore, after calling it, the original list is shorter by one element.</p> <p>Have a look at this example:</p> <pre><code>&gt;&gt;&gt; a = [1, 2, 3] &gt;&gt;&gt; b = a # the name "b" refers to the same list as the name "a" &gt;&gt;&gt; a.pop() # we pop off a value but don't assign it anywhere 3 &gt;&gt;&gt; a [1, 2] &gt;&gt;&gt; b [1, 2] </code></pre> <p>Note that the result of <code>a.pop()</code> isn't assigned to anything but <code>a</code> is still changed. You can think of the meaning of <code>a.pop()</code> as "remove the last element of the list a (while also returning it as a result)".</p> <p>Also note that it is not a good idea to use the name <code>list</code> since it is a builtin identifier referring to the list type itself and you are redefining it.</p>
1
2016-10-09T07:48:22Z
[ "python", "methods" ]
How is the .pop() method able to redefine a variable by only being the value of another?
39,941,196
<p>So in python if you create your <code>list</code>, then a new variable, <code>reject_list</code> and assign it the <code>.pop()</code> method, it changes the value in the previous <code>list</code> variable. </p> <pre><code>list = ['item', 'thing', 'piece'] reject_list = list.pop() print(list) ['item', 'thing'] </code></pre> <p>I understand this effect, but not how it's possible. How does assigning the method of one variable as the value of another retroactively change the value of the original variable without first being defined, like this: </p> <pre><code>list = ['item', 'thing', 'piece'] list = list.pop() print(list) ['item', 'thing'] </code></pre> <p>For instance, this doesn't work with the <code>.title()</code> method: </p> <pre><code>name = mike new_name = name.title() print(name) mike #the original name did not capitalize </code></pre> <p>so how is the .pop() method able to redefine a variable by only being the value of another?</p>
-1
2016-10-09T07:41:33Z
39,941,606
<p>The answer is that the <code>list.pop()</code> method specifically modifies the object; <strong>removes</strong> and returns an item from the list. <code>str.title()</code> returns a <em>version</em> of the string in title case, but does not modify the string itself.</p> <p>It's also noteworthy that strings are immutable in Python.</p> <pre><code>my_list = ["a", "b", "c"] popped_element = my_list.pop() print(my_list) #['a', 'b'] print(popped_element) #'c' </code></pre>
0
2016-10-09T08:35:56Z
[ "python", "methods" ]
Why my subprocess generated by pool.apply_async() always run as MainProcess?
39,941,272
<p>My env is Python2.7.I am very fuzzed,I run my apply_async(test_func),and I let the test_func print the current process_name.As like:</p> <pre><code>q = Queue(maxsize=20) #multiprocessing.Queue def test_func(queue): print 'Process' print multiprocessing.current_process() if __name__ == '__main__': pool = Pool(processes=3) for i in xrange(3): pool.apply_async(test_func(q,)) while True: time.sleep(1) if q.empty(): break print 'Main Process Monitoring' print multiprocessing.current_process() </code></pre> <p>The code has no syntax error,and the terminal always print <code>&lt;MainProcess&gt;</code> </p> <p>If I change <code>pool.apply_async(test_func,(q,))(add a comma)</code>,it couldn't get into the <code>test_func</code>,just like simply finish for loop,and it just print <code>'Main Process Monitoring' &lt;MainProcess&gt;</code>..</p> <p>So I can't understand why <code>apply_async()</code> can't work normally and when it work,it runs as <code>MainProcess</code>,and I have tried <code>pool.close(),pool.join()</code>.Nothing change. If anyone can help.Thanks a lot!</p>
0
2016-10-09T07:49:51Z
39,941,754
<p>Occasionally,I know that I should use <code>apply_async(test_func, (i,))</code>,and this is a mistake for me.</p> <p>But what very odd is that,when I usse <code>apply_async(test_func, (q,))</code>,it will not work.the <code>q</code> is multiprocessing.Queue().If I remove it or substitute for any other except Queue object,it will work(print subprocess normally)</p> <p>I don't know whether the Queue has some errors or something else raise...</p> <p>Does any one knows that?Thanks a lot!</p>
0
2016-10-09T08:57:24Z
[ "python" ]
Why my subprocess generated by pool.apply_async() always run as MainProcess?
39,941,272
<p>My env is Python2.7.I am very fuzzed,I run my apply_async(test_func),and I let the test_func print the current process_name.As like:</p> <pre><code>q = Queue(maxsize=20) #multiprocessing.Queue def test_func(queue): print 'Process' print multiprocessing.current_process() if __name__ == '__main__': pool = Pool(processes=3) for i in xrange(3): pool.apply_async(test_func(q,)) while True: time.sleep(1) if q.empty(): break print 'Main Process Monitoring' print multiprocessing.current_process() </code></pre> <p>The code has no syntax error,and the terminal always print <code>&lt;MainProcess&gt;</code> </p> <p>If I change <code>pool.apply_async(test_func,(q,))(add a comma)</code>,it couldn't get into the <code>test_func</code>,just like simply finish for loop,and it just print <code>'Main Process Monitoring' &lt;MainProcess&gt;</code>..</p> <p>So I can't understand why <code>apply_async()</code> can't work normally and when it work,it runs as <code>MainProcess</code>,and I have tried <code>pool.close(),pool.join()</code>.Nothing change. If anyone can help.Thanks a lot!</p>
0
2016-10-09T07:49:51Z
39,941,771
<p>First, your <code>test_func</code> function has no <code>return</code> statement, so it returns <code>None</code>:</p> <pre><code>def test_func(queue): print 'Process' print multiprocessing.current_process() </code></pre> <p>Inserting this into an interactive Python:</p> <pre><code>&gt;&gt;&gt; import multiprocessing &gt;&gt;&gt; x = test_func(None) Process &lt;_MainProcess(MainProcess, started)&gt; &gt;&gt;&gt; print x None </code></pre> <p>This means that:</p> <pre><code> pool.apply_async(test_func(q,)) </code></pre> <p>calls <code>test_func</code> with argument <code>(q,)</code>, which returns <code>None</code>; then you pass <code>None</code> to <code>pool.apply_async</code>.</p> <p><a href="https://docs.python.org/2/library/multiprocessing.html" rel="nofollow">The <code>multiprocessing</code> documentation</a> describes <code>apply_async</code> as invoking its first argument a la <code>apply</code>, but asynchronously, i.e., without waiting for its result. Let's try <code>apply(None)</code> interactively, just to see what that does:</p> <pre><code>&gt;&gt;&gt; apply(none) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: 'NoneType' object is not callable </code></pre> <p>So we might expect <code>apply_async</code> to raise a TypeError—and in fact, that <em>is</em> what it does, but the error is deferred until we try to get the result:</p> <pre><code>&gt;&gt;&gt; pool = multiprocessing.Pool(processes=3) &gt;&gt;&gt; pool.apply_async(None) &lt;multiprocessing.pool.ApplyResult object at 0x801b27510&gt; </code></pre> <p>Let's grab this ApplyResult object so we can use and inspect it (the special name <code>_</code> holds the most recent value returned during the interaction):</p> <pre><code>&gt;&gt;&gt; x = _ </code></pre> <p>Now we can see if the asynchronous apply has a result for us:</p> <pre><code>&gt;&gt;&gt; x.ready() True </code></pre> <p>It does! (We can call <code>x.wait()</code> to wait for it if not, but since it's ready now, let's press on.) Is the result a regular value, or an exception?</p> <pre><code>&gt;&gt;&gt; x.successful() False </code></pre> <p>Ah, the result is an exception. Let's get the exception:</p> <pre><code>&gt;&gt;&gt; x.get() Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/local/lib/python2.7/multiprocessing/pool.py", line 567, in get raise self._value TypeError: 'NoneType' object is not callable </code></pre> <p>And there we have the answer: passing <code>None</code> to <code>apply_async</code> spins off the execution of the function <code>None</code> (which is not a function after all), and once we collect the final result, that result is the exception we would expect.</p> <blockquote> <p>If I change <code>pool.apply_async(test_func,(q,))</code> (add a comma), it couldn't get into the <code>test_func</code> ...</p> </blockquote> <p>Let's try something like that in the interactive interpreter. I don't have a <code>q</code> but since <code>test_func</code> does not actually use its arguments, we're OK here with passing None:</p> <pre><code>&gt;&gt;&gt; x = pool.apply_async(test_func, (None,)) &gt;&gt;&gt; Process &lt;Process(PoolWorker-2, started daemon)&gt; </code></pre> <p>This output is a bit messy but it sure looks like it worked. Let's see if <code>x</code> has a result, and whether it's successful, and what its result is:</p> <pre><code>x.ready() True &gt;&gt;&gt; x.successful() True &gt;&gt;&gt; x.get() &gt;&gt;&gt; </code></pre> <p>(the first <code>&gt;&gt;&gt;</code> prompt seems to be missing, but it's really just been printed-over by the things printed in <code>test_func</code>). There is a successful value, but since it's None, the interpreter did not print anything here—we'd have to have done <code>print x.get()</code> to see it.</p> <p>In other words, if you're going to use <code>apply_async</code> you must (1) save the spun-off "pending result" somewhere, and then (2) use <code>.get()</code> to actually <em>retrieve</em> that result. You also need to return something from your function.</p> <p>Meanwhile this loop:</p> <pre><code>while True: time.sleep(1) if q.empty(): break print 'Main Process Monitoring' print multiprocessing.current_process() </code></pre> <p>never runs all the way through once, because your queue object <code>q</code> <em>is</em> empty at the time you test it, so you immediately <code>break</code> out of it.</p>
1
2016-10-09T08:59:07Z
[ "python" ]
pycairo: justify text-align
39,941,286
<p>I use python bindings to Cairo to render text.</p> <p>My question is: Is it possible to render a string using something like <code>text-align: justify</code>? Suppose I have fixed width and I want to print a paragraph.</p>
1
2016-10-09T07:51:47Z
39,942,325
<p>Solved [using pangocairo]:</p> <pre><code>import pygtk import cairo import pango import pangocairo ... layout = pangocairo_context.create_layout() ... layout.set_width(...) layout.set_wrap(pango.WRAP_WORD) layout.set_justify(True) layout.set_text(text) </code></pre>
1
2016-10-09T10:05:46Z
[ "python", "text", "alignment", "cairo", "justify" ]
Create DataFrame from multiple Series
39,941,321
<p>I have 2 <code>Series</code>, given by:</p> <pre><code>import pandas as pd r = pd.Series() for i in range(0, 10): r = r.set_value(i,i*3) r.name = 'rrr' s = pd.Series() for i in range(0, 10): s = s.set_value(i,i*5) s.name = 'sss' </code></pre> <p>How to I create a <code>DataFrame</code> from them?</p>
0
2016-10-09T07:55:08Z
39,941,338
<p>You can use pd.concat:</p> <pre><code>pd.concat([r, s], axis=1) Out: rrr sss 0 0 0 1 3 5 2 6 10 3 9 15 4 12 20 5 15 25 6 18 30 7 21 35 8 24 40 9 27 45 </code></pre> <p>Or the DataFrame constructor:</p> <pre><code>pd.DataFrame({'r': r, 's': s}) Out: r s 0 0 0 1 3 5 2 6 10 3 9 15 4 12 20 5 15 25 6 18 30 7 21 35 8 24 40 9 27 45 </code></pre>
0
2016-10-09T07:57:48Z
[ "python", "python-2.7", "pandas", "dataframe" ]
python: loop a list of list and assign value inside the loop
39,941,393
<p>I have the following code, why the first one doesn't change <code>alist</code> while the second changes it?</p> <pre><code>alist = [[1,2], [3,4], [5,6]] for item in alist: item = 1 print(alist) alist = [[1,2], [3,4], [5,6]] for item in alist: item = item.append(10) print(alist) </code></pre>
5
2016-10-09T08:04:49Z
39,941,425
<p>Referencing <a href="https://docs.python.org/3/reference/compound_stmts.html#the-for-statement" rel="nofollow">the document</a>: </p> <blockquote> <p>The for-loop makes assignments to the variables(s) in the target list. This overwrites all previous assignments to those variables including those made in the suite of the for-loop:</p> <pre><code>for i in range(10): print(i) i = 5 # this will not affect the for-loop # because i will be overwritten with the next # index in the range </code></pre> </blockquote> <p>So your second example is identical to:</p> <pre><code>alist = [[1,2], [3,4], [5,6]] for item in alist: item.append(10) # this statement modifies each item in alist # , which is what item the variable "points to" print(alist) </code></pre> <p>That is to say, <code>item</code> is a new variable <strong>in every iteration</strong>. As a result, assigning values to it in any specific iteration is pointless, because its value will be overridden by the reference to the next item in <code>alist</code> at the very beginning of the next iteration.</p>
1
2016-10-09T08:11:30Z
[ "python" ]
python: loop a list of list and assign value inside the loop
39,941,393
<p>I have the following code, why the first one doesn't change <code>alist</code> while the second changes it?</p> <pre><code>alist = [[1,2], [3,4], [5,6]] for item in alist: item = 1 print(alist) alist = [[1,2], [3,4], [5,6]] for item in alist: item = item.append(10) print(alist) </code></pre>
5
2016-10-09T08:04:49Z
39,941,443
<p>Are you forgetting that <code>list.append()</code> does not return the list itself but actually modifies the list in place?</p> <p><code>item = 1</code> does as expected. For the rest of the for-loop, item is now <code>1</code>, and not the list it originally was. It won't reassign what <code>item</code> is, that's not what for-loops do.</p> <p>However, in your second loop, you're now assigning <code>item = None</code>, because the append function does not return anything but it appends the item to the list in place:</p> <pre><code>&gt;&gt;&gt; L = [1, 2, 3] &gt;&gt;&gt; L.append(4) &gt;&gt;&gt; L [1, 2, 3, 4] </code></pre> <p>Thus, your code is basically saying "go through each sublist in my main list and append <code>10</code> to it".</p>
2
2016-10-09T08:13:29Z
[ "python" ]
python: loop a list of list and assign value inside the loop
39,941,393
<p>I have the following code, why the first one doesn't change <code>alist</code> while the second changes it?</p> <pre><code>alist = [[1,2], [3,4], [5,6]] for item in alist: item = 1 print(alist) alist = [[1,2], [3,4], [5,6]] for item in alist: item = item.append(10) print(alist) </code></pre>
5
2016-10-09T08:04:49Z
39,941,451
<p>When you write</p> <pre><code>for item in alist: </code></pre> <p>You are actually creating a copy of each item in <code>liast</code> in the <code>item</code> variable, and you are <em>not</em> getting a reference to <code>item</code>.</p> <p>However, <code>append</code> changes the list in-place and doesn't return a value, and that's why you're getting the values changed to <code>None</code> (due to the assignment - if you remove it you'll get the appending working fine).</p>
0
2016-10-09T08:14:22Z
[ "python" ]
python: loop a list of list and assign value inside the loop
39,941,393
<p>I have the following code, why the first one doesn't change <code>alist</code> while the second changes it?</p> <pre><code>alist = [[1,2], [3,4], [5,6]] for item in alist: item = 1 print(alist) alist = [[1,2], [3,4], [5,6]] for item in alist: item = item.append(10) print(alist) </code></pre>
5
2016-10-09T08:04:49Z
39,941,454
<p>The <code>=</code> operator does not make any change in the second code, using <code>.append</code> causes changes in <code>alist</code>. Use following line as the third line in the second code. You will see the same result:</p> <pre><code>item.append(10) </code></pre> <p>In the first code <code>item</code> point to another object by <code>item=1</code>, so <code>alist</code> does not change. In the second code you make change on <code>alist</code> by calling <code>append</code> method of it.</p>
2
2016-10-09T08:14:37Z
[ "python" ]
python: loop a list of list and assign value inside the loop
39,941,393
<p>I have the following code, why the first one doesn't change <code>alist</code> while the second changes it?</p> <pre><code>alist = [[1,2], [3,4], [5,6]] for item in alist: item = 1 print(alist) alist = [[1,2], [3,4], [5,6]] for item in alist: item = item.append(10) print(alist) </code></pre>
5
2016-10-09T08:04:49Z
39,941,472
<p>In the first example <code>item</code> is bound to each element in list <code>alist</code>, and then <code>item</code> is <em>rebound</em> to the integer <code>1</code>. This does not change the element of the list - it merely <em>rebinds</em> the name <code>item</code> to the <code>int</code> object <code>1</code>.</p> <p>In the second example the list element (itself a list) is mutated by <code>append()</code>. <code>item</code> is still bound to the sub-list so <code>item.append()</code> mutates the sub-list.</p>
4
2016-10-09T08:16:19Z
[ "python" ]
python: loop a list of list and assign value inside the loop
39,941,393
<p>I have the following code, why the first one doesn't change <code>alist</code> while the second changes it?</p> <pre><code>alist = [[1,2], [3,4], [5,6]] for item in alist: item = 1 print(alist) alist = [[1,2], [3,4], [5,6]] for item in alist: item = item.append(10) print(alist) </code></pre>
5
2016-10-09T08:04:49Z
39,941,492
<p>It's pointer variable in python.</p> <p>The first example:</p> <pre><code>for item in alist: item = 1 </code></pre> <p>each item is pointing to each _item in alist but suddenly you change the item value, not the of the value of the _item in alist, as a result nothing change to alist</p> <p>The second example: </p> <pre><code>for item in alist: item = item.append(10) </code></pre> <p>each item is pointing to each _item in alist and then you append something to the item sharing the same memory location of _item, as a result value of _item in alist are changed and alist is changed too.</p>
2
2016-10-09T08:20:06Z
[ "python" ]
python: loop a list of list and assign value inside the loop
39,941,393
<p>I have the following code, why the first one doesn't change <code>alist</code> while the second changes it?</p> <pre><code>alist = [[1,2], [3,4], [5,6]] for item in alist: item = 1 print(alist) alist = [[1,2], [3,4], [5,6]] for item in alist: item = item.append(10) print(alist) </code></pre>
5
2016-10-09T08:04:49Z
39,942,033
<p>This is a somewhat unintuitive behavor of variables. It happens because, in Python, variables are always references to values.</p> <h1>Boxes and tags</h1> <p>In some languages, we tend to think about variables as "boxes" where we put values; in Python, however, they are references, and behave more like tags or "nicknames" to values. So, when you attribute 1 to <code>item</code>, you are changing only the variable reference, not the list it is pointing to.</p> <p>A graphic representation can help. The image below represents the list created by <code>alist = [[1,2], [3,4], [5,6]]</code></p> <p><a href="http://i.stack.imgur.com/KpcjH.png"><img src="http://i.stack.imgur.com/KpcjH.png" alt="A list with three sublists"></a></p> <p>Given that, let's see what happens when we execute your first loop.</p> <h1>The first loop</h1> <p>When you execute <code>for item in alist</code>, you are asking the interpreter to take each value from the list, one per time, put it on the variable <code>item</code> and do some operation in it. In the first operation, for example, we have this new schema:</p> <p><a href="http://i.stack.imgur.com/wPXKX.png"><img src="http://i.stack.imgur.com/wPXKX.png" alt="Now a variable points to a sublist"></a></p> <p>Note that we do not copy the sublist to <code>item</code>; instead, we <em>point</em> to it through <code>item</code>. Then, we execute <code>item = 1</code> — but what does it mean? It mean that we are making <code>item</code> point to the value <code>1</code>, instead of pointing to the sublist:</p> <p><a href="http://i.stack.imgur.com/snmRy.png"><img src="http://i.stack.imgur.com/snmRy.png" alt="item points to other value now"></a></p> <p>Note that the old reference is lost (it is the red arrow) and now we have a new. But we just changed a variable pointing to a list — we did not alter the list itself.</p> <p>Then, we enter to the second iteration of the loop, and now <code>item</code> points to the second sublist:</p> <p><a href="http://i.stack.imgur.com/ERT2X.png"><img src="http://i.stack.imgur.com/ERT2X.png" alt="item pointing to the second sublist"></a></p> <p>When we execute <code>item = 1</code>, again, we just make the variable point to aonther value, without changing the list:</p> <p><a href="http://i.stack.imgur.com/7jxHt.png"><img src="http://i.stack.imgur.com/7jxHt.png" alt="enter image description here"></a></p> <p>Now, what happens when we execute the second loop?</p> <h1>The second loop</h1> <p>The second loop starts as the first one: we make <code>item</code> refer to the first sublist:</p> <p><a href="http://i.stack.imgur.com/wPXKX.png"><img src="http://i.stack.imgur.com/wPXKX.png" alt="Now a variable points to a sublist"></a></p> <p>The first difference, however, is that we call <code>item.append()</code>. <code>append()</code> is a <em>method</em>, so it can change the value of the object it is calling. As we use to say, we are sending a <em>message</em> to the object pointed by <code>item</code> to append the value 10. In this case, the operation is <em>not</em> being made in the variable <code>item</code>, but directly in the object it refers! So here is the result of calling <code>item.append()</code>:</p> <p><a href="http://i.stack.imgur.com/XXcfr.png"><img src="http://i.stack.imgur.com/XXcfr.png" alt="A list has grown"></a></p> <p>However, we do not only append a value to the list! We also assign the value returned by <code>item.append()</code>. This will sever the <code>item</code> reference to the sublist, but here is a catch: <code>append()</code> returns <code>None</code>.</p> <p><a href="http://i.stack.imgur.com/7T77S.png"><img src="http://i.stack.imgur.com/7T77S.png" alt="enter image description here"></a></p> <h1>The <code>None</code> value</h1> <p><code>None</code> is a value that represents, basically, the unavailability of a relevant value. When a function returns <code>None</code>, it is saying, most of the time, "I have nothing relevant to give you back." <code>append()</code> does change its list directly, so there is nothing it needs to return.</p> <p>It is important because you probably believed <code>item</code> would point to the appended list <code>[1, 2, 10]</code>, right? No, now it points to <code>None</code>. So, you would expect the code below...</p> <pre><code>alist = [[1,2], [3,4], [5,6]] for item in alist: item = item.append(10) print(item) </code></pre> <p>To print something like this:</p> <pre><code>[1, 2, 10] [3, 4, 10] [5, 6, 10] </code></pre> <p>But this <em>does not</em> happen. <em>This</em> is what happens:</p> <pre><code>&gt;&gt;&gt; alist = [[1,2], [3,4], [5,6]] &gt;&gt;&gt; for item in alist: ... item = item.append(10) ... print(item) ... None None None </code></pre> <p>Yet, as we commented, the <code>append()</code> method changed the lists themselves. So, while the <code>item</code> variable was useless after the assignment, the final list is modified!</p> <pre><code>&gt;&gt;&gt; print alist [[1, 2, 10], [3, 4, 10], [5, 6, 10]] </code></pre> <p>If you want to use the appended list inside the loop, just do not assign the method returned value to <code>item</code>. Do this:</p> <pre><code>&gt;&gt;&gt; alist = [[1,2], [3,4], [5,6]] &gt;&gt;&gt; for item in alist: ... item.append(10) ... print item ... [1, 2, 10] [3, 4, 10] [5, 6, 10] </code></pre> <p>This works because <code>item</code> will still point to the list.</p> <h1>Conclusion</h1> <p>References are somewhat complex to understand at first, let alone master. Yet, they are really powerful and can be learned if you follow examples etc. Your example is a bit complicated because there is more happening here.</p> <p>The <a href="http://www.pythontutor.com/">Python Tutor</a> can help you understand what is going on, because it executes each step graphically. <a href="http://www.pythontutor.com/visualize.html#code=alist%20%3D%20%5B%5B1,2%5D,%20%5B3,4%5D,%20%5B5,6%5D%5D%0Afor%20item%20in%20alist%3A%0A%20%20%20%20item%20%3D%201%0Aprint(alist%29%0A%0Aalist%20%3D%20%5B%5B1,2%5D,%20%5B3,4%5D,%20%5B5,6%5D%5D%0Afor%20item%20in%20alist%3A%0A%20%20%20%20item%20%3D%20item.append(10%29%0Aprint(alist%29&amp;cumulative=false&amp;curInstr=0&amp;heapPrimitives=false&amp;mode=display&amp;origin=opt-frontend.js&amp;py=2&amp;rawInputLstJSON=%5B%5D&amp;textReferences=false">Check your own code running there!</a></p>
5
2016-10-09T09:28:59Z
[ "python" ]
ImageView or VideoView, which should I display my streaming "video" in android?
39,941,465
<p>I have an android App (native) which streaming video from other camera. </p> <p>I created a simple server with <code>python</code>, <code>flask</code>, and <code>opencv</code> (to process the video)</p> <pre><code>from mockCamera import VideoCamera; import time import argparse from flask import Flask, render_template, Response, jsonify, url_for, send_file # Gallery folder name STATIC_FOLDER = 'gallery' # Init Flask app &amp; Camera object app = Flask(__name__, static_folder=STATIC_FOLDER) def gen(camera): """Video streaming generator function.""" while True: frame = camera.get_frame() yield(b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n') @app.route('/video_feed') def video_feed(): """Video streaming route.""" return Response(gen(VideoCamera()), mimetype='multipart/x-mixed-replace; boundary=frame') if __name__ == '__main__': # Construct the argument parser and parse the arguments ap = argparse.ArgumentParser() ap.add_argument("-c", "--camera", help="URL of IP Camera") args = vars(ap.parse_args()) # If the camera argument is not None, # then we set it to CAMERA_URL variable # otherwise we use default value if args.get('camera', None) is not None: CAMERA_URL = args['camera'] # Run the app app.run(host='0.0.0.0', debug=True) </code></pre> <p><code>camera.get_frame()</code> will return a frame which processed by opencv</p> <p>So now, I think my Android App will access <code>/video_feed</code> route, and display video in a <code>ImageView</code>.</p> <p>But I don't know if it is right or wrong. And how can I do that?</p> <p>Thanks in advance.</p>
0
2016-10-09T08:15:50Z
39,955,287
<p>You would usually use a VideoView to show a video, setting it up with the URL to the video on your server.</p> <p>For example:</p> <pre class="lang-js prettyprint-override"><code> //Create the video player and set the video path videoPlayerView = (VideoView) rootView.findViewById(R.id.video_area); if (videoPlayerView == null) { Log.d("VideoPlayer Activity","onCreateView: videoPlayerView is null"); return null; } //Set the video URI to the the URL of the video on the server videoPlayerView.setVideoURI(yourVideoURL); </code></pre>
0
2016-10-10T09:32:30Z
[ "android", "python", "opencv", "video", "streaming" ]
Python: Cross Connecting a loop within a loop
39,941,515
<p>Just for practice, I am trying to write a function in python which contains a loop within a loop. However I get an <code>IndexError: list index out of range</code></p> <p>Here's the function</p> <pre><code>def merge(A,B): c = [] k = 0 i = 0 j = 0 while i &lt; len(A): while j &lt; len(B): if A[i] &lt;= B[j]: c.append(A[i]) i+=1 print c print i print k k=j else: c.append(B[j]) j+=1 c.extend(A[i:]) return c c.extend(B[k:]) return c </code></pre> <p>Here's the error</p> <pre><code>merge([1,8,9],[2,3,4,11]) [1] 1 0 [1, 2, 3, 4, 8] 2 0 [1, 2, 3, 4, 8, 9] 3 3 Traceback (most recent call last): File "&lt;pyshell#51&gt;", line 1, in &lt;module&gt; merge([1,8,9],[2,3,4,11]) File "&lt;pyshell#49&gt;", line 8, in merge if A[i] &lt;= B[j]: IndexError: list index out of range </code></pre>
0
2016-10-09T08:22:57Z
39,941,574
<p>You are incrementing i or j in the if statement in the middle - with your sample data, if i is already <code>len(A)-1</code>, i.e. 2 and is incremented when j &lt; <code>len(B)-1</code>, because the <code>while j &lt; len(B)</code> will continue to execute, and on the next time round the loop of course <code>i</code> is out of bounds to index into A. You can see in your console output that i is 3 when the error happens. If you had put "i=" and "j=" before the value in the print statement and also print len(A) and len(B), it would be more obvious, but all the information to diagnose the bug in your code is already in your console output.</p> <p>I leave you the exercise of working out how to make your code not cause the error.</p>
3
2016-10-09T08:32:15Z
[ "python", "python-2.7", "python-3.x" ]
Django and requirements
39,941,604
<p>Im a bit stuck. I can't get this configuration to work and I don't know why. The code I site below is from <a href="https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-apache-and-mod_wsgi-on-ubuntu-14-04" rel="nofollow">https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-apache-and-mod_wsgi-on-ubuntu-14-04</a>. The reason I get stuck on it is because he named his project directory and his project the same thing. If I am right, then where he is locating files like the settings.py and wsgi.py should be /home/user/myproject/myproject/myproject but I'm not sure anymore because I can't even get it right myself. Earlier in the document he cd's into the directory he created, which would put him in /home/user/myproject. He then proceeds to create a virtual environment, enter it, and run <code>django-admin startproject myproject</code>. So, if all this holds true, at least what I see on my own server tells me that when you start a django project it actually creates two folders with the same name, nested. Am I wrong? Can someone help me straighten the below code out to make more sense?</p> <p> . . .</p> <pre><code> Alias /static /home/user/myproject/static &lt;Directory /home/user/myproject/static&gt; Require all granted &lt;/Directory&gt; &lt;Directory /home/user/myproject/myproject&gt; &lt;Files wsgi.py&gt; Require all granted &lt;/Files&gt; &lt;/Directory&gt; WSGIDaemonProcess myproject python-path=/home/user/myproject:/home/user/myproject/myprojectenv/lib/python2.7/site-packages WSGIProcessGroup myproject WSGIScriptAlias / /home/user/myproject/myproject/wsgi.py &lt;/VirtualHost&gt; </code></pre> <p>This is what I consistently see in my apache log:</p> <pre><code>[Sun Oct 09 11:48:15.875313 2016] [wsgi:warn] [pid 47964] mod_wsgi: Compiled for Python/3.5.1+. [Sun Oct 09 11:48:15.875353 2016] [wsgi:warn] [pid 47964] mod_wsgi: Runtime using Python/3.5.2. [Sun Oct 09 11:48:15.877537 2016] [mpm_prefork:notice] [pid 47964] AH00163: Apache/2.4.18 (Ubuntu) mod_wsgi/4.3.0 Python/3.5.2 configured -- resuming normal operations [Sun Oct 09 11:48:15.877568 2016] [core:notice] [pid 47964] AH00094: Command line: '/usr/sbin/apache2' [Sun Oct 09 11:48:18.767800 2016] [wsgi:error] [pid 47967] [remote 192.168.2.249:22662] mod_wsgi (pid=47967): Target WSGI script '/home/addohm/projects/rtservice/servicesite/servicesite/wsgi.py' cannot be loaded as Python module. [Sun Oct 09 11:48:18.767851 2016] [wsgi:error] [pid 47967] [remote 192.168.2.249:22662] mod_wsgi (pid=47967): Exception occurred processing WSGI script '/home/addohm/projects/rtservice/servicesite/servicesite/wsgi.py'. [Sun Oct 09 11:48:18.768339 2016] [wsgi:error] [pid 47967] [remote 192.168.2.249:22662] Traceback (most recent call last): [Sun Oct 09 11:48:18.768385 2016] [wsgi:error] [pid 47967] [remote 192.168.2.249:22662] File "/home/addohm/projects/rtservice/servicesite/servicesite/wsgi.py", line 16, in &lt;module&gt; [Sun Oct 09 11:48:18.768389 2016] [wsgi:error] [pid 47967] [remote 192.168.2.249:22662] application = get_wsgi_application() [Sun Oct 09 11:48:18.768395 2016] [wsgi:error] [pid 47967] [remote 192.168.2.249:22662] File "/usr/lib/python3/dist-packages/django/core/wsgi.py", line 14, in get_wsgi_application [Sun Oct 09 11:48:18.768398 2016] [wsgi:error] [pid 47967] [remote 192.168.2.249:22662] django.setup() [Sun Oct 09 11:48:18.768405 2016] [wsgi:error] [pid 47967] [remote 192.168.2.249:22662] File "/usr/lib/python3/dist-packages/django/__init__.py", line 17, in setup [Sun Oct 09 11:48:18.768408 2016] [wsgi:error] [pid 47967] [remote 192.168.2.249:22662] configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) [Sun Oct 09 11:48:18.768413 2016] [wsgi:error] [pid 47967] [remote 192.168.2.249:22662] File "/usr/lib/python3/dist-packages/django/conf/__init__.py", line 48, in __getattr__ [Sun Oct 09 11:48:18.768423 2016] [wsgi:error] [pid 47967] [remote 192.168.2.249:22662] self._setup(name) [Sun Oct 09 11:48:18.768430 2016] [wsgi:error] [pid 47967] [remote 192.168.2.249:22662] File "/usr/lib/python3/dist-packages/django/conf/__init__.py", line 44, in _setup [Sun Oct 09 11:48:18.768433 2016] [wsgi:error] [pid 47967] [remote 192.168.2.249:22662] self._wrapped = Settings(settings_module) [Sun Oct 09 11:48:18.768438 2016] [wsgi:error] [pid 47967] [remote 192.168.2.249:22662] File "/usr/lib/python3/dist-packages/django/conf/__init__.py", line 92, in __init__ [Sun Oct 09 11:48:18.768441 2016] [wsgi:error] [pid 47967] [remote 192.168.2.249:22662] mod = importlib.import_module(self.SETTINGS_MODULE) [Sun Oct 09 11:48:18.768446 2016] [wsgi:error] [pid 47967] [remote 192.168.2.249:22662] File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module [Sun Oct 09 11:48:18.768449 2016] [wsgi:error] [pid 47967] [remote 192.168.2.249:22662] return _bootstrap._gcd_import(name[level:], package, level) [Sun Oct 09 11:48:18.768454 2016] [wsgi:error] [pid 47967] [remote 192.168.2.249:22662] File "&lt;frozen importlib._bootstrap&gt;", line 986, in _gcd_import [Sun Oct 09 11:48:18.768460 2016] [wsgi:error] [pid 47967] [remote 192.168.2.249:22662] File "&lt;frozen importlib._bootstrap&gt;", line 969, in _find_and_load [Sun Oct 09 11:48:18.768466 2016] [wsgi:error] [pid 47967] [remote 192.168.2.249:22662] File "&lt;frozen importlib._bootstrap&gt;", line 944, in _find_and_load_unlocked [Sun Oct 09 11:48:18.768471 2016] [wsgi:error] [pid 47967] [remote 192.168.2.249:22662] File "&lt;frozen importlib._bootstrap&gt;", line 222, in _call_with_frames_removed [Sun Oct 09 11:48:18.768477 2016] [wsgi:error] [pid 47967] [remote 192.168.2.249:22662] File "&lt;frozen importlib._bootstrap&gt;", line 986, in _gcd_import [Sun Oct 09 11:48:18.768483 2016] [wsgi:error] [pid 47967] [remote 192.168.2.249:22662] File "&lt;frozen importlib._bootstrap&gt;", line 969, in _find_and_load [Sun Oct 09 11:48:18.768488 2016] [wsgi:error] [pid 47967] [remote 192.168.2.249:22662] File "&lt;frozen importlib._bootstrap&gt;", line 956, in _find_and_load_unlocked [Sun Oct 09 11:48:18.768505 2016] [wsgi:error] [pid 47967] [remote 192.168.2.249:22662] ImportError: No module named 'servicesite' </code></pre>
0
2016-10-09T08:35:39Z
39,941,911
<p>in your /etc/apache2/apache2.conf file add </p> <pre><code>&lt;Directory /home/dimitris/mysite&gt; AllowOverride All Require all granted &lt;/Directory&gt; </code></pre> <p>your site.conf file in the example i load mysite with virtualenv</p> <pre><code>WSGIDaemonProcess myp user=dimitris group=dimitris threads=5 python-path=/home/dimitris/myenv/lib/python2.7/site-packages &lt;VirtualHost *:80&gt; #ServerName mysite #ServerAlias mysite ServerAdmin webmaster@localhost WSGIProcessGroup myp WSGIScriptAlias / /home/dimitris/mysite/mysite/wsgi.py Alias /favicon.ico /home/dimitris/mysite/favicon.ico Alias /media/ /home/dimitris/mysite/media/ Alias /static/ /home/dimitris/mysite/project-static/ DocumentRoot /home/dimitris/mysite &lt;Directory /home/dimitris/mysite/&gt; Order allow,deny allow from all &lt;/Directory&gt; LogFormat "%h %l %u %t \"%r\" %&gt;s %b \"%{Referer}i\" \"%{User-agent}i\"" combined ErrorLog /var/log/mysite-error.log # Possible values include: debug, info, notice, warn, error, crit, # alert, emerg. LogLevel warn CustomLog /var/log/mysite-access.log combined &lt;/VirtualHost&gt; </code></pre> <p>in django wsgi.py file add</p> <pre><code>import os DJANGO_PATH = os.path.join(os.path.abspath(os.path.dirname(__file__)), '..') sys.path.append(DJANGO_PATH) </code></pre> <p>in the above code replace dimitris with your username</p>
0
2016-10-09T09:13:50Z
[ "python", "django", "apache", "mod-wsgi" ]
Django and requirements
39,941,604
<p>Im a bit stuck. I can't get this configuration to work and I don't know why. The code I site below is from <a href="https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-apache-and-mod_wsgi-on-ubuntu-14-04" rel="nofollow">https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-apache-and-mod_wsgi-on-ubuntu-14-04</a>. The reason I get stuck on it is because he named his project directory and his project the same thing. If I am right, then where he is locating files like the settings.py and wsgi.py should be /home/user/myproject/myproject/myproject but I'm not sure anymore because I can't even get it right myself. Earlier in the document he cd's into the directory he created, which would put him in /home/user/myproject. He then proceeds to create a virtual environment, enter it, and run <code>django-admin startproject myproject</code>. So, if all this holds true, at least what I see on my own server tells me that when you start a django project it actually creates two folders with the same name, nested. Am I wrong? Can someone help me straighten the below code out to make more sense?</p> <p> . . .</p> <pre><code> Alias /static /home/user/myproject/static &lt;Directory /home/user/myproject/static&gt; Require all granted &lt;/Directory&gt; &lt;Directory /home/user/myproject/myproject&gt; &lt;Files wsgi.py&gt; Require all granted &lt;/Files&gt; &lt;/Directory&gt; WSGIDaemonProcess myproject python-path=/home/user/myproject:/home/user/myproject/myprojectenv/lib/python2.7/site-packages WSGIProcessGroup myproject WSGIScriptAlias / /home/user/myproject/myproject/wsgi.py &lt;/VirtualHost&gt; </code></pre> <p>This is what I consistently see in my apache log:</p> <pre><code>[Sun Oct 09 11:48:15.875313 2016] [wsgi:warn] [pid 47964] mod_wsgi: Compiled for Python/3.5.1+. [Sun Oct 09 11:48:15.875353 2016] [wsgi:warn] [pid 47964] mod_wsgi: Runtime using Python/3.5.2. [Sun Oct 09 11:48:15.877537 2016] [mpm_prefork:notice] [pid 47964] AH00163: Apache/2.4.18 (Ubuntu) mod_wsgi/4.3.0 Python/3.5.2 configured -- resuming normal operations [Sun Oct 09 11:48:15.877568 2016] [core:notice] [pid 47964] AH00094: Command line: '/usr/sbin/apache2' [Sun Oct 09 11:48:18.767800 2016] [wsgi:error] [pid 47967] [remote 192.168.2.249:22662] mod_wsgi (pid=47967): Target WSGI script '/home/addohm/projects/rtservice/servicesite/servicesite/wsgi.py' cannot be loaded as Python module. [Sun Oct 09 11:48:18.767851 2016] [wsgi:error] [pid 47967] [remote 192.168.2.249:22662] mod_wsgi (pid=47967): Exception occurred processing WSGI script '/home/addohm/projects/rtservice/servicesite/servicesite/wsgi.py'. [Sun Oct 09 11:48:18.768339 2016] [wsgi:error] [pid 47967] [remote 192.168.2.249:22662] Traceback (most recent call last): [Sun Oct 09 11:48:18.768385 2016] [wsgi:error] [pid 47967] [remote 192.168.2.249:22662] File "/home/addohm/projects/rtservice/servicesite/servicesite/wsgi.py", line 16, in &lt;module&gt; [Sun Oct 09 11:48:18.768389 2016] [wsgi:error] [pid 47967] [remote 192.168.2.249:22662] application = get_wsgi_application() [Sun Oct 09 11:48:18.768395 2016] [wsgi:error] [pid 47967] [remote 192.168.2.249:22662] File "/usr/lib/python3/dist-packages/django/core/wsgi.py", line 14, in get_wsgi_application [Sun Oct 09 11:48:18.768398 2016] [wsgi:error] [pid 47967] [remote 192.168.2.249:22662] django.setup() [Sun Oct 09 11:48:18.768405 2016] [wsgi:error] [pid 47967] [remote 192.168.2.249:22662] File "/usr/lib/python3/dist-packages/django/__init__.py", line 17, in setup [Sun Oct 09 11:48:18.768408 2016] [wsgi:error] [pid 47967] [remote 192.168.2.249:22662] configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) [Sun Oct 09 11:48:18.768413 2016] [wsgi:error] [pid 47967] [remote 192.168.2.249:22662] File "/usr/lib/python3/dist-packages/django/conf/__init__.py", line 48, in __getattr__ [Sun Oct 09 11:48:18.768423 2016] [wsgi:error] [pid 47967] [remote 192.168.2.249:22662] self._setup(name) [Sun Oct 09 11:48:18.768430 2016] [wsgi:error] [pid 47967] [remote 192.168.2.249:22662] File "/usr/lib/python3/dist-packages/django/conf/__init__.py", line 44, in _setup [Sun Oct 09 11:48:18.768433 2016] [wsgi:error] [pid 47967] [remote 192.168.2.249:22662] self._wrapped = Settings(settings_module) [Sun Oct 09 11:48:18.768438 2016] [wsgi:error] [pid 47967] [remote 192.168.2.249:22662] File "/usr/lib/python3/dist-packages/django/conf/__init__.py", line 92, in __init__ [Sun Oct 09 11:48:18.768441 2016] [wsgi:error] [pid 47967] [remote 192.168.2.249:22662] mod = importlib.import_module(self.SETTINGS_MODULE) [Sun Oct 09 11:48:18.768446 2016] [wsgi:error] [pid 47967] [remote 192.168.2.249:22662] File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module [Sun Oct 09 11:48:18.768449 2016] [wsgi:error] [pid 47967] [remote 192.168.2.249:22662] return _bootstrap._gcd_import(name[level:], package, level) [Sun Oct 09 11:48:18.768454 2016] [wsgi:error] [pid 47967] [remote 192.168.2.249:22662] File "&lt;frozen importlib._bootstrap&gt;", line 986, in _gcd_import [Sun Oct 09 11:48:18.768460 2016] [wsgi:error] [pid 47967] [remote 192.168.2.249:22662] File "&lt;frozen importlib._bootstrap&gt;", line 969, in _find_and_load [Sun Oct 09 11:48:18.768466 2016] [wsgi:error] [pid 47967] [remote 192.168.2.249:22662] File "&lt;frozen importlib._bootstrap&gt;", line 944, in _find_and_load_unlocked [Sun Oct 09 11:48:18.768471 2016] [wsgi:error] [pid 47967] [remote 192.168.2.249:22662] File "&lt;frozen importlib._bootstrap&gt;", line 222, in _call_with_frames_removed [Sun Oct 09 11:48:18.768477 2016] [wsgi:error] [pid 47967] [remote 192.168.2.249:22662] File "&lt;frozen importlib._bootstrap&gt;", line 986, in _gcd_import [Sun Oct 09 11:48:18.768483 2016] [wsgi:error] [pid 47967] [remote 192.168.2.249:22662] File "&lt;frozen importlib._bootstrap&gt;", line 969, in _find_and_load [Sun Oct 09 11:48:18.768488 2016] [wsgi:error] [pid 47967] [remote 192.168.2.249:22662] File "&lt;frozen importlib._bootstrap&gt;", line 956, in _find_and_load_unlocked [Sun Oct 09 11:48:18.768505 2016] [wsgi:error] [pid 47967] [remote 192.168.2.249:22662] ImportError: No module named 'servicesite' </code></pre>
0
2016-10-09T08:35:39Z
39,942,763
<p>Either you create your project at /home/user or change the apache conf file by appending an extra /myproject wherever you are specifying the path as below:</p> <pre><code>Alias /static /home/user/myproject/myproject/static &lt;Directory /home/user/myproject/myproject/static&gt; Require all granted &lt;/Directory&gt; &lt;Directory /home/user/myproject/myproject/myproject&gt; &lt;Files wsgi.py&gt; Require all granted &lt;/Files&gt; &lt;/Directory&gt; WSGIDaemonProcess myproject python-path=/home/user/myproject/myproject:/home/user/myproject/myproject/myprojectenv/lib/python2.7/site-packages WSGIProcessGroup myproject WSGIScriptAlias / /home/user/myproject/myproject/myproject/wsgi.py </code></pre> <p>It was confusing because you created your project inside a myproject folder(same as your project name), rather than creating it somewhere else.</p>
0
2016-10-09T10:52:53Z
[ "python", "django", "apache", "mod-wsgi" ]
Python classes and objects, How to display contents of a list
39,941,609
<p>So below is my coding and whenever I click on the button "Show average mark" it gives me an error </p> <pre><code>"Exception in Tkinter callback Traceback (most recent call last): File "C:\Users\Mohammed\AppData\Local\Programs\Python\Python35-32\lib\tkinter\__init__.py", line 1550, in __call__ return self.func(*args) File "C:\Users\Mohammed\Downloads\homework5_201599618.py", line 67, in showAverage for s in self.studentList: AttributeError: 'student' object has no attribute 'studentList' </code></pre> <p>Here is my code:</p> <pre><code>from tkinter import * from tkinter import ttk class student : name = '' number = 0 homework = 0 average = 0 def __init__(self, master): self.master = master master.title("student markList") studentList = [] self.label_1 = Label(master, text = "Add student name:") self.label_2 = Label(master, text = "Add student number:") self.label_3 = Label(master, text = "Add homework mark:") self.label_4 = Label(master, textvariable=self.average) self.label_1.grid(column=1, row=1, sticky = (W,E)) self.label_2.grid(column=1, row=2, sticky = (W,E)) self.label_3.grid(column=1, row=3, sticky = (W,E)) self.label_4.grid(columnspan=3, row=8, sticky = (N,W,E,S)) self.name = StringVar() self.number = StringVar() self.homework = StringVar() self.average = StringVar() self.name_input = ttk.Entry(master, textvariable=self.name).grid(column=2, row=1, sticky = (W,E)) self.number_input = ttk.Entry(master, textvariable=self.number).grid(column=2, row=2, sticky = (W,E)) self.homework_input = ttk.Entry(master, textvariable=self.homework).grid(column=2, row=3, sticky = (W,E)) self.button_1 = Button(master, text = "Add Student Information", command=self.addStudent) self.button_2 = Button(master, text = "List All Students", command=self.listAll) self.button_3 = Button(master, text = "Show Average Mark", command=self.showAverage) self.button_1.grid(column=2, row=4, sticky = (W,E)) self.button_2.grid(column=2, row=5, sticky = (W,E)) self.button_3.grid(column=2, row=6, sticky = (W,E)) self.lb1 = Listbox(master) self.lb1.grid(columnspan=3,row=7, sticky = (W,E)) def addStudent(self, *args): self.n = self.name.get() self.num = self.number.get() self.hw = self.homework.get() self.studentList.append([self.n, self.num, self.hw]) def listAll(self): self.lb1.delete(0, END) for s in self.studentList: self.lb1.insert(END,s[0] + " " + s[1] + " = " + s[2]) def showAverage(self): self.total = 0 for s in self.studentList: self.total += int(s[2]) self.average.set(int(self.total/len(self.studentList))) root = Tk() gui_markList = student(root) root.mainloop() </code></pre> <p>I think the problem is in the def(showAverage) piece of coding. Could someone please help?</p>
-2
2016-10-09T08:36:12Z
39,941,637
<p>In your <code>__init__</code> method, you need to change <code>studentList = []</code> to <code>self.studentList = []</code></p>
1
2016-10-09T08:40:38Z
[ "python", "list" ]
Python classes and objects, How to display contents of a list
39,941,609
<p>So below is my coding and whenever I click on the button "Show average mark" it gives me an error </p> <pre><code>"Exception in Tkinter callback Traceback (most recent call last): File "C:\Users\Mohammed\AppData\Local\Programs\Python\Python35-32\lib\tkinter\__init__.py", line 1550, in __call__ return self.func(*args) File "C:\Users\Mohammed\Downloads\homework5_201599618.py", line 67, in showAverage for s in self.studentList: AttributeError: 'student' object has no attribute 'studentList' </code></pre> <p>Here is my code:</p> <pre><code>from tkinter import * from tkinter import ttk class student : name = '' number = 0 homework = 0 average = 0 def __init__(self, master): self.master = master master.title("student markList") studentList = [] self.label_1 = Label(master, text = "Add student name:") self.label_2 = Label(master, text = "Add student number:") self.label_3 = Label(master, text = "Add homework mark:") self.label_4 = Label(master, textvariable=self.average) self.label_1.grid(column=1, row=1, sticky = (W,E)) self.label_2.grid(column=1, row=2, sticky = (W,E)) self.label_3.grid(column=1, row=3, sticky = (W,E)) self.label_4.grid(columnspan=3, row=8, sticky = (N,W,E,S)) self.name = StringVar() self.number = StringVar() self.homework = StringVar() self.average = StringVar() self.name_input = ttk.Entry(master, textvariable=self.name).grid(column=2, row=1, sticky = (W,E)) self.number_input = ttk.Entry(master, textvariable=self.number).grid(column=2, row=2, sticky = (W,E)) self.homework_input = ttk.Entry(master, textvariable=self.homework).grid(column=2, row=3, sticky = (W,E)) self.button_1 = Button(master, text = "Add Student Information", command=self.addStudent) self.button_2 = Button(master, text = "List All Students", command=self.listAll) self.button_3 = Button(master, text = "Show Average Mark", command=self.showAverage) self.button_1.grid(column=2, row=4, sticky = (W,E)) self.button_2.grid(column=2, row=5, sticky = (W,E)) self.button_3.grid(column=2, row=6, sticky = (W,E)) self.lb1 = Listbox(master) self.lb1.grid(columnspan=3,row=7, sticky = (W,E)) def addStudent(self, *args): self.n = self.name.get() self.num = self.number.get() self.hw = self.homework.get() self.studentList.append([self.n, self.num, self.hw]) def listAll(self): self.lb1.delete(0, END) for s in self.studentList: self.lb1.insert(END,s[0] + " " + s[1] + " = " + s[2]) def showAverage(self): self.total = 0 for s in self.studentList: self.total += int(s[2]) self.average.set(int(self.total/len(self.studentList))) root = Tk() gui_markList = student(root) root.mainloop() </code></pre> <p>I think the problem is in the def(showAverage) piece of coding. Could someone please help?</p>
-2
2016-10-09T08:36:12Z
39,941,646
<p>When you do:</p> <pre><code>self.studentList.append([self.n, self.num, self.hw]) </code></pre> <p>studentList must be defined/assigned value before.</p> <p>In your code, what you did is:</p> <pre><code>def __init__(self, master): self.master = master master.title("student markList") studentList = [] </code></pre> <p>So studentList is not assigned to self/the object as a result self.studentList is not defined.</p> <p>You can solve the modify it as:</p> <pre><code>def __init__(self, master): self.master = master master.title("student markList") self.studentList = [] </code></pre>
1
2016-10-09T08:41:22Z
[ "python", "list" ]
Expanding function based on array length
39,941,644
<p>I have the following code, which I would like to make responsive to the initial array that is passed to it (letters). Currently it can handle letters &lt;= 3, however I would like to make it expandable to n.</p> <p>In this example, if the array only contains two entries ["a", " b"], it would trigger the second if statement. </p> <p>How can I change this to have effectively infinite if statements, allowing an array of any size?</p> <pre><code>import itertools import numpy as np #variable length letters = ["a", " b", " c"] increment = .1 d = 3 e = 3 #Calculate total possible combinations and create array x=0 for p in itertools.product(range(d), repeat=e): x = x+1 variable = np.arange(x) variable_s = [str(x) for x in variable] x=0 #run loop based on array length. for p in itertools.product(range(d), repeat=e): if len(letters) == 1: variable_s[x] = letters[0]+str(format(p[0]/(increment)**(-1.0),'.2f')).replace("0.", "") elif len(letters) == 2: variable_s[x] = ( letters[0]+str(format(p[0]/(increment)**(-1.0),'.2f')).replace("0.", "") +letters[1]+str(format(p[1]/(increment)**(-1.0),'.2f')).replace("0.", "") ) elif len(letters) == 3: variable_s[x] = ( letters[0]+str(format(p[0]/(increment)**(-1.0),'.2f')).replace("0.", "") +letters[1]+str(format(p[1]/(increment)**(-1.0),'.2f')).replace("0.", "") +letters[2]+str(format(p[2]/(increment)**(-1.0),'.2f')).replace("0.", "") ) x = x+1 variable_s </code></pre> <p>The output from the code above would be: ['a00 b00 c00', 'a00 b00 c10', 'a00 b00 c20', 'a00 b10 c00', 'a00 b10 c10', 'a00 b10 c20', 'a00 b20 c00', 'a00 b20 c10', 'a00 b20 c20', 'a10 b00 c00', 'a10 b00 c10', 'a10 b00 c20', 'a10 b10 c00', 'a10 b10 c10', 'a10 b10 c20', 'a10 b20 c00', 'a10 b20 c10', 'a10 b20 c20', 'a20 b00 c00', 'a20 b00 c10', 'a20 b00 c20', 'a20 b10 c00', 'a20 b10 c10', 'a20 b10 c20', 'a20 b20 c00', 'a20 b20 c10', 'a20 b20 c20']</p> <p>If letters = ["a", "b"] the output would be : ['a00 b00', 'a00 b00', 'a00 b00', 'a00 b10', 'a00 b10', 'a00 b10', 'a00 b20', 'a00 b20', 'a00 b20', 'a10 b00', 'a10 b00', 'a10 b00', 'a10 b10', 'a10 b10', 'a10 b10', 'a10 b20', 'a10 b20', 'a10 b20', 'a20 b00', 'a20 b00', 'a20 b00', 'a20 b10', 'a20 b10', 'a20 b10', 'a20 b20', 'a20 b20', 'a20 b20']</p> <p>If letters ["a", "b", "c", "d", "e", "f", "g"] the output would be: ['a00 b00 c00 d00 e00 f00 g00', 'a00 b00 c00 d00 e00 f00 g10',... etc.</p>
0
2016-10-09T08:41:13Z
39,942,027
<p>Maybe try something like this?</p> <pre><code>import itertools import numpy as np #variable length letters = ["a", "b", "c", "d", "e", "f", "g"] n = len(letters) # Max limit for each element, ie. limit of 2 from [a, b], for k = 2 is ['a00 b00', 'a00 b10', 'a10 b00', 'a10 b10'] k = 3 # Number of elements we want to pick. variable_s = [] #run loop based on array length. for x, p in enumerate(itertools.product(range(n), repeat=k)): variable_s.append(' '.join([letter + str(q).zfill(2)[::-1] for letter, q in zip(letters, p)])) </code></pre>
1
2016-10-09T09:28:00Z
[ "python", "arrays", "itertools" ]
Expanding function based on array length
39,941,644
<p>I have the following code, which I would like to make responsive to the initial array that is passed to it (letters). Currently it can handle letters &lt;= 3, however I would like to make it expandable to n.</p> <p>In this example, if the array only contains two entries ["a", " b"], it would trigger the second if statement. </p> <p>How can I change this to have effectively infinite if statements, allowing an array of any size?</p> <pre><code>import itertools import numpy as np #variable length letters = ["a", " b", " c"] increment = .1 d = 3 e = 3 #Calculate total possible combinations and create array x=0 for p in itertools.product(range(d), repeat=e): x = x+1 variable = np.arange(x) variable_s = [str(x) for x in variable] x=0 #run loop based on array length. for p in itertools.product(range(d), repeat=e): if len(letters) == 1: variable_s[x] = letters[0]+str(format(p[0]/(increment)**(-1.0),'.2f')).replace("0.", "") elif len(letters) == 2: variable_s[x] = ( letters[0]+str(format(p[0]/(increment)**(-1.0),'.2f')).replace("0.", "") +letters[1]+str(format(p[1]/(increment)**(-1.0),'.2f')).replace("0.", "") ) elif len(letters) == 3: variable_s[x] = ( letters[0]+str(format(p[0]/(increment)**(-1.0),'.2f')).replace("0.", "") +letters[1]+str(format(p[1]/(increment)**(-1.0),'.2f')).replace("0.", "") +letters[2]+str(format(p[2]/(increment)**(-1.0),'.2f')).replace("0.", "") ) x = x+1 variable_s </code></pre> <p>The output from the code above would be: ['a00 b00 c00', 'a00 b00 c10', 'a00 b00 c20', 'a00 b10 c00', 'a00 b10 c10', 'a00 b10 c20', 'a00 b20 c00', 'a00 b20 c10', 'a00 b20 c20', 'a10 b00 c00', 'a10 b00 c10', 'a10 b00 c20', 'a10 b10 c00', 'a10 b10 c10', 'a10 b10 c20', 'a10 b20 c00', 'a10 b20 c10', 'a10 b20 c20', 'a20 b00 c00', 'a20 b00 c10', 'a20 b00 c20', 'a20 b10 c00', 'a20 b10 c10', 'a20 b10 c20', 'a20 b20 c00', 'a20 b20 c10', 'a20 b20 c20']</p> <p>If letters = ["a", "b"] the output would be : ['a00 b00', 'a00 b00', 'a00 b00', 'a00 b10', 'a00 b10', 'a00 b10', 'a00 b20', 'a00 b20', 'a00 b20', 'a10 b00', 'a10 b00', 'a10 b00', 'a10 b10', 'a10 b10', 'a10 b10', 'a10 b20', 'a10 b20', 'a10 b20', 'a20 b00', 'a20 b00', 'a20 b00', 'a20 b10', 'a20 b10', 'a20 b10', 'a20 b20', 'a20 b20', 'a20 b20']</p> <p>If letters ["a", "b", "c", "d", "e", "f", "g"] the output would be: ['a00 b00 c00 d00 e00 f00 g00', 'a00 b00 c00 d00 e00 f00 g10',... etc.</p>
0
2016-10-09T08:41:13Z
39,943,143
<p>Here's the smallest change you could make - replace your <code>if</code> statement with:</p> <pre><code>variable_s[x] = ''.join( letter+str(format(p_i/(increment)**(-1.0),'.2f')).replace("0.", "") for letter, p_i in zip(letters, p) ) </code></pre> <p>Other notes:</p> <ul> <li><code>p[1]/(increment)**(-1.0)</code> is better spelt <code>p[1] * increment</code></li> <li><code>x=0; for p in itertools.product(range(d), repeat=e): x = x+1</code> is better spelt <code>x = d**e</code></li> </ul>
1
2016-10-09T11:37:17Z
[ "python", "arrays", "itertools" ]
Numpy Sum Performance
39,941,716
<p>I made a plot of the time required for numpy.sum() to sum elements of an array. Here is my plot:</p> <p><a href="http://i.stack.imgur.com/MSSpd.png" rel="nofollow"><img src="http://i.stack.imgur.com/MSSpd.png" alt="Numpy sum performance"></a></p> <p>The x axis denotes the number of entries that have been summed. The y axis denotes the time used to sum those entries (in seconds).</p> <p>For the entries, I used an array of 10<sup>7</sup> random values. The same array is used every time.</p> <p>I can't understand why the time used by the computer to sum 10<sup>1</sup> entries is larger than the time required for 10<sup>2</sup> entries. Why is it that the first part of the curve is decreasing?</p> <p><b> EDIT </b> Here is the code used for measuring the performance:</p> <pre><code>def numpy_sum(vector, n): new_vector = vector[:n] start_time = time.perf_counter() np.sum(new_vector) return time.perf_counter() - start_time </code></pre>
-1
2016-10-09T08:51:07Z
39,942,707
<p>When you measure performance of some code, it is advisable to run it multiple times and take the average to avoid skewed results.</p> <p>By default, timeit module execute the code for 1 million times. I am not seeing the issue you mentioned even if I run it only for 100 times. Here is an equivalent version of your code using timeit module:</p> <pre><code>from timeit import Timer import numpy as np import random #generate random list random_list =[random.randint(1,100) for x in range(1000000)] np_sum_time= Timer("np.sum(new_list)", "from __main__ import new_list,np") for n in (10**x for x in range(1,7)): new_list = random_list[:n] print "{0} Entries Sum Time: {1} Seconds".format(n,np_sum_time.timeit(number=100)) </code></pre> <p>And the results:</p> <pre><code>10 Entries Sum Time: 0.000567059064269 Seconds 100 Entries Sum Time: 0.00100197540542 Seconds 1000 Entries Sum Time: 0.00490724190233 Seconds 10000 Entries Sum Time: 0.0441321414402 Seconds 100000 Entries Sum Time: 0.430979001174 Seconds 1000000 Entries Sum Time: 4.46029030987 Seconds </code></pre>
-1
2016-10-09T10:44:36Z
[ "python", "performance", "numpy", "sum" ]
TypeError for definied variable in python
39,942,031
<p>I'm trying to make a music player that allows a song to be put into the shell and is then played however, I'm having an issue with a type error in <code>class Notes():</code> and I can't figure out why.</p> <pre><code>import winsound import time length = 125 class Notes(): def processNote(note): if(note == 'C'):return Notes.processNote(262) if(note == 'D'):return Notes.processNote(294) if(note == 'D5'):return Notes.processNote(587) if(note == 'A'):return Notes.processNote(440) if(note == 'Ab'):return Notes.processNote(415) if(note == 'G'):return Notes.processNote(392) if(note == 'F'):return Notes.processNote(349) if(note == 'B'):return Notes.processNote(247) if(note == 'Bb'):return Notes.processNote(233) song = "CCCCCCCCCCCD" noteList = list(song) print(noteList) for note in noteList: print("Doing ", note) frequency = Notes.processNote(note) winsound.Beep(frequency, length) </code></pre> <p>The error: </p> <pre><code>Traceback (most recent call last): File "C:\Python\Tester.py", line 27, in &lt;module&gt; winsound.Beep(frequency, length) TypeError: an integer is required (got type NoneType) </code></pre>
1
2016-10-09T09:28:27Z
39,942,086
<p>And if I can say something, instead of</p> <pre><code>class Notes(): def processNote(note): if(note == 'C'):return Notes.processNote(262) if(note == 'D'):return Notes.processNote(294) if(note == 'D5'):return Notes.processNote(587) (thousands IFs) </code></pre> <p>You could use the python dictionary and create mapping:</p> <pre><code>class Notes(): def processNote(note): signature_to_freq = {'C': 262, 'D': 294, 'D5': 587, 'B': 247} return signature_to_freq[note] </code></pre>
1
2016-10-09T09:36:14Z
[ "python", "music", "typeerror" ]
TypeError for definied variable in python
39,942,031
<p>I'm trying to make a music player that allows a song to be put into the shell and is then played however, I'm having an issue with a type error in <code>class Notes():</code> and I can't figure out why.</p> <pre><code>import winsound import time length = 125 class Notes(): def processNote(note): if(note == 'C'):return Notes.processNote(262) if(note == 'D'):return Notes.processNote(294) if(note == 'D5'):return Notes.processNote(587) if(note == 'A'):return Notes.processNote(440) if(note == 'Ab'):return Notes.processNote(415) if(note == 'G'):return Notes.processNote(392) if(note == 'F'):return Notes.processNote(349) if(note == 'B'):return Notes.processNote(247) if(note == 'Bb'):return Notes.processNote(233) song = "CCCCCCCCCCCD" noteList = list(song) print(noteList) for note in noteList: print("Doing ", note) frequency = Notes.processNote(note) winsound.Beep(frequency, length) </code></pre> <p>The error: </p> <pre><code>Traceback (most recent call last): File "C:\Python\Tester.py", line 27, in &lt;module&gt; winsound.Beep(frequency, length) TypeError: an integer is required (got type NoneType) </code></pre>
1
2016-10-09T09:28:27Z
39,942,097
<p>Currently, the function <code>processNote()</code> returns <code>None</code> for any valid input, because you are calling it twice instead of just returning the value. It may be helpful to look at how your code will be processed to understand why this happens:</p> <p>Imagine <code>processNote()</code> is called with the note value <code>"C"</code>. That will match the first <code>if</code> statement and it will return <strong>the result of calling <code>processNote()</code> with the value 262</strong>. Since there's no if statement that catches 262 in the <code>processNote()</code> function, it returns <code>None</code> (because this is the default for Python functions), so the <code>frequency</code> variable ends up being <code>None</code>.</p> <p>You can solve this rather simply, by just returning the literal value:</p> <pre><code>def processNote(note): if note == 'C': return 262 ... </code></pre>
0
2016-10-09T09:37:36Z
[ "python", "music", "typeerror" ]
python: adding data as string in mysql gives weird error
39,942,061
<p>I'm having a weird problem with a piece of python code.</p> <p>The idea how it should work: 1. a barcode is entered (now hardcode for the moment); 2. barcode is looked up in local mysqldb, if not found, the barcode is looked up via api from datakick, if it's not found there either, step 3 3. i want to add the barcode to my local mysqldatabase and request some input.</p> <p>Now the problem: it works! als long as you fill in numbers for the <code>naamProduct</code>. If you use letters (eg. I filled in Bla as productname), I get a weird SQL-error <code>(_mysql_exceptions.OperationalError: (1054, "Unknown column 'Bla' in 'field.list'")</code></p> <p>I have checked the tables in mysql and the types are all ok. The table where name should end up in is text. I have also tried a hardcoded string which works fine. Using the sql-query from the mysql console also works perfectly. My guess is something is going wrong with the inputpart, but I can't figure out what.</p> <p>(code is still not really tidy with the exceptions, I know ;) Working on it step by step)</p> <p>`</p> <pre><code>def barcodeFunctie(sql): con = mdb.connect ('localhost', 'python', 'python', 'stock') cur = con.cursor() cur.execute(sql) ver = cur.fetchone(); con.commit() con.close() return ver #barcode = '8710624957278' #barcode = '2147483647' barcode = '123' #zoeken op barcode. Barcode is ook de sleutel in de tabel. sql = "select * from Voorraad where Id=%s" % barcode if barcodeFunctie(sql) == "None": print "geen output" else: try: url='https://www.datakick.org/api/items/'+barcode data = json.load(urllib2.urlopen(url)) print data['brand_name'], data['name'] except: #barcode komt niet voor in eigen db en niet in db van datakick, in beide toevoegen print barcode, " barcode als input" naamProduct = str(raw_input("Wat is de naam van het product? ")) hoeveelheidProduct = raw_input("Hoeveel inhoud heeft het product? ") sql = "insert into Voorraad (Id, NaamProduct,HoeveelHeidProduct) values (%s,%s,%s)" % (barcode, naamProduct, hoeveelheidProduct) barcodeFunctie(sql) print "meuktoegevoegd! :D" </code></pre> <p>`</p>
0
2016-10-09T09:32:08Z
39,942,218
<pre><code>sql = "select * from Voorraad where Id=%s" % barcode </code></pre> <p>Your problem is that you are missing quotes for your ID. Change that line above to this:</p> <pre><code>sql = "select * from Voorraad where Id='%s'" % barcode </code></pre>
0
2016-10-09T09:52:26Z
[ "python", "mysql" ]
python: adding data as string in mysql gives weird error
39,942,061
<p>I'm having a weird problem with a piece of python code.</p> <p>The idea how it should work: 1. a barcode is entered (now hardcode for the moment); 2. barcode is looked up in local mysqldb, if not found, the barcode is looked up via api from datakick, if it's not found there either, step 3 3. i want to add the barcode to my local mysqldatabase and request some input.</p> <p>Now the problem: it works! als long as you fill in numbers for the <code>naamProduct</code>. If you use letters (eg. I filled in Bla as productname), I get a weird SQL-error <code>(_mysql_exceptions.OperationalError: (1054, "Unknown column 'Bla' in 'field.list'")</code></p> <p>I have checked the tables in mysql and the types are all ok. The table where name should end up in is text. I have also tried a hardcoded string which works fine. Using the sql-query from the mysql console also works perfectly. My guess is something is going wrong with the inputpart, but I can't figure out what.</p> <p>(code is still not really tidy with the exceptions, I know ;) Working on it step by step)</p> <p>`</p> <pre><code>def barcodeFunctie(sql): con = mdb.connect ('localhost', 'python', 'python', 'stock') cur = con.cursor() cur.execute(sql) ver = cur.fetchone(); con.commit() con.close() return ver #barcode = '8710624957278' #barcode = '2147483647' barcode = '123' #zoeken op barcode. Barcode is ook de sleutel in de tabel. sql = "select * from Voorraad where Id=%s" % barcode if barcodeFunctie(sql) == "None": print "geen output" else: try: url='https://www.datakick.org/api/items/'+barcode data = json.load(urllib2.urlopen(url)) print data['brand_name'], data['name'] except: #barcode komt niet voor in eigen db en niet in db van datakick, in beide toevoegen print barcode, " barcode als input" naamProduct = str(raw_input("Wat is de naam van het product? ")) hoeveelheidProduct = raw_input("Hoeveel inhoud heeft het product? ") sql = "insert into Voorraad (Id, NaamProduct,HoeveelHeidProduct) values (%s,%s,%s)" % (barcode, naamProduct, hoeveelheidProduct) barcodeFunctie(sql) print "meuktoegevoegd! :D" </code></pre> <p>`</p>
0
2016-10-09T09:32:08Z
39,942,224
<p>I believe that you miss the single quotation mark for all your string placeholders. That would explain why it works with numbers but not with strings.</p> <p>I didn't tested it, but in my opinion your SQL statement should look like:</p> <pre><code>sql = "insert into Voorraad (Id, NaamProduct,HoeveelHeidProduct) values ('%s','%s','%s')" % (barcode, naamProduct, hoeveelheidProduct) </code></pre>
0
2016-10-09T09:53:17Z
[ "python", "mysql" ]
Strange merging - list of words
39,942,069
<p>I have a list of lists of words like this:</p> <pre><code>texts=[['word1', 'word2', 'word3']['word4', 'word5', 'word6']] </code></pre> <p>My desired output would be:</p> <pre><code>texts=[['word1 word2 word3']['word4 word5 word6'] </code></pre> <p>This is what I tried:</p> <p>for item in texts:</p> <pre><code>item=[" ".join([word for word in item])] </code></pre> <p>But it doesn't work. Why?</p>
0
2016-10-09T09:33:16Z
39,942,081
<p>Just pass the sub lists to <code>join</code>:</p> <pre><code>In [62]: [[' '.join(sub_list)] for sub_list in texts] Out[62]: [['word1 word2 word3'], ['word4 word5 word6']] </code></pre>
2
2016-10-09T09:34:58Z
[ "python", "list" ]
Np.concatenate ValueError: all the input arrays must have same number of dimensions
39,942,117
<p>I am trying to concatenate but ended up with the mentioned error. Am also new to python. </p> <pre><code>def cving(x1, x2, x3, x4, x5, y1, y2, y3, y4, y5, ind1, ind2, ind3, ind4, ind5, num): if num == 0: xwhole = np.concatenate((x2, x3, x4, x5), axis=0) yhol = np.concatenate((y2, y3, y4, y5), axis=0) return x1, y1, ind1, xwhole, yhol elif num == 1: xwhole = np.concatenate((x1, x3, x4, x5), axis=0) yhol = np.concatenate((y1, y3, y4, y5), axis=0) return x2, y2, ind2, xwhole, yhol elif num == 2: xwhole = np.concatenate((x1, x2, x4, x5), axis=0) yhol = np.concatenate((y1, y2, y4, y5), axis=0) return x3, y3, ind3, xwhole, yhol elif num == 3: xwhole = np.concatenate((x1, x2, x3, x5), axis=0) yhol = np.concatenate((y1, y2, y3, y5), axis=0) return x4, y4, ind4, xwhole, yhol else: xwhole = np.concatenate((x1, x2, x3, x4), axis=0) yhol = np.concatenate((y1, y2, y3, y4), axis=0) return x5, y5, ind5, xwhole, yhol </code></pre> <p>Here are some of the output of x1,x2,x3 and x4 *To show some of the output which is used for np.concantate</p> <pre><code>x1 = [[ 1.21537030e+07 5.73132800e+06 1.39127063e-01 ..., 0.00000000e+00 0.00000000e+00 0.00000000e+00] [ 2.19181650e+07 6.31495600e+06 1.58992826e-01 ..., 0.00000000e+00 0.00000000e+00 0.00000000e+00] [ 9.35311000e+05 5.93920000e+05 1.40974499e-01 ..., 0.00000000e+00 0.00000000e+00 0.00000000e+00]] x2= [] x3= [] x4 = [ 1.11088300e+06 1.23238400e+06 1.32048109e-01 1.05878525e-01 9.01409788e-01 1.24716612e+00 7.22766415e-01 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 1.15544472e-01 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 1.54537898e-02 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 7.82815688e-01 1.13352981e-04 1.13352981e-04 0.00000000e+00 0.00000000e+00 8.52792262e-02 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 6.80117887e-04 0.00000000e+00 0.00000000e+00] </code></pre>
0
2016-10-09T09:39:47Z
39,942,604
<p>The error message says it all: <code>x1</code> is 2D while <code>x4</code> is 1D. Concatenating these makes no sense. You need to make sure all concatenated arrays are of same dimension, e.g. by adding a dimension to all 1D arrays</p> <pre><code>x4 = x4[:, np.newaxis] </code></pre>
2
2016-10-09T10:34:05Z
[ "python", "np" ]
How can I make an organized file into dictionary in python3?
39,942,189
<p>I'm trying to make the file:</p> <pre><code>c;f b;d a;c c;e d;g a;b e;d f;g f;d </code></pre> <p>Into a dict like</p> <pre><code>{'e': {'d'}, 'a': {'b', 'c'}, 'd': {'g'}, 'b': {'d'}, 'c': {'f', 'e'}, 'f': {'g', 'd'}}. </code></pre> <p>The code I'm using now is like below</p> <pre><code>def read_file(file : open) -&gt; {str:{str}}: f = file.read().rstrip('\n').split() answer = {} for line in f: k, v = line.split(';') answer[k] = v return answer </code></pre> <p>But it gives me <code>{'f': 'g', 'a': 'c', 'b': 'd', 'e': 'd', 'c': 'e', 'd': 'g'}</code> How can I fix it?</p>
3
2016-10-09T09:48:54Z
39,942,230
<p>Dictionaries overwrite the previous key, Use a <a href="https://docs.python.org/3/library/collections.html#collections.defaultdict" rel="nofollow">defaultdict here</a> </p> <pre><code>&gt;&gt;&gt; import collections &gt;&gt;&gt; answer = collections.defaultdict(set) &gt;&gt;&gt; for line in f: ... k, v = line.split(";") ... answer[k].add(v) ... &gt;&gt;&gt; answer defaultdict(&lt;class 'set'&gt;, {'b': {'d'}, 'd': {'g'}, 'f': {'d', 'g'}, 'e': {'d'}, 'a': {'c', 'b'}, 'c': {'f', 'e'}}) </code></pre> <p>If you prefer the traditional approach, then you can add a <code>if</code> condition </p> <pre><code>&gt;&gt;&gt; answer = {} &gt;&gt;&gt; for line in f: ... k,v = line.split(";") ... if k in answer: ... answer[k].add(v) ... else: ... answer[k] = {v} ... &gt;&gt;&gt; answer {'b': {'d'}, 'd': {'g'}, 'f': {'d', 'g'}, 'e': {'d'}, 'a': {'c', 'b'}, 'c': {'f', 'e'}} </code></pre>
3
2016-10-09T09:53:36Z
[ "python", "string", "python-3.x", "dictionary", "set" ]
Problems resampling pandas time series with time gap between indices
39,942,269
<p>I want to resample the pandas series </p> <pre><code>import pandas as pd index_1 = pd.date_range('1/1/2000', periods=4, freq='T') index_2 = pd.date_range('1/2/2000', periods=3, freq='T') series = pd.Series(range(4), index=index_1) series=series.append(pd.Series(range(3), index=index_2)) print series &gt;&gt;&gt;2000-01-01 00:00:00 0 2000-01-01 00:01:00 1 2000-01-01 00:02:00 2 2000-01-01 00:03:00 3 2000-01-02 00:00:00 0 2000-01-02 00:01:00 1 2000-01-02 00:02:00 2 </code></pre> <p>such that the resulting DataSeries only contains every second entry, i.e </p> <pre><code> &gt;&gt;&gt;2000-01-01 00:00:00 0 2000-01-01 00:02:00 2 2000-01-02 00:00:00 0 2000-01-02 00:02:00 2 </code></pre> <p>using the (poorly documented) resample method of pandas in the following way:</p> <pre><code>resampled_series = series.resample('2T', closed='right') print resampled_series </code></pre> <p>I get </p> <pre><code>&gt;&gt;&gt;1999-12-31 23:58:00 0.0 2000-01-01 00:00:00 1.5 2000-01-01 00:02:00 3.0 2000-01-01 00:04:00 NaN 2000-01-01 00:56:00 NaN ... 2000-01-01 23:54:00 NaN 2000-01-01 23:56:00 NaN 2000-01-01 23:58:00 0.0 2000-01-02 00:00:00 1.5 2000-01-02 00:02:00 3.0 </code></pre> <p>Why does it start 2 minutes earlier than the original series? why does it contain all the time steps inbetween, which are not contained in the original series? How can I get my desired result?</p>
0
2016-10-09T09:59:00Z
39,942,544
<p><code>resample()</code> is not the right function for your purpose.</p> <p>try this:</p> <pre><code>series[series.index.minute % 2 == 0] </code></pre>
1
2016-10-09T10:27:56Z
[ "python", "pandas" ]