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
python: Is there anyway to read messages from a tcp port without knowing the sent message size?
39,574,683
<p>I'm trying to do write a python script that should work as a tcp server. I receive messages of different sizes from a client whose message format cannot be changed, so my server script is the one that, somehow, should get adapted to the received messages. Together with this, the server can't send back any kind of ack to the client. The server must just receive the variable size messages and afterwards process them. </p> <p>Is there any way to do so?</p>
-1
2016-09-19T13:40:59Z
39,576,008
<p>TCP is a data stream protocol which means that there are no inherent message boundaries. The concept of a message can only be defined by the application. This is typically done by defining a message boundary or by prefixing the message with its size. Since the message is thus defined at the application level you will not be able to read a message with a TCP level command only (i.e. plain socket read). Instead your application must read and then interpret the data stream to find out where the message starts and ends.</p>
1
2016-09-19T14:46:06Z
[ "python", "tcp" ]
'int' object not subscriptable error
39,574,702
<pre><code>while 1 == 1: import csv from time import sleep import sys bill = 0 with open('list2.txt') as csvfile: readCSV = csv.reader(csvfile, delimiter = ",") GTINs = [] products = [] prices = [] for row in readCSV: GTIN = row[0] product = str(row[1]) price = float(row[2]) GTINs.append(GTIN) products.append(product) prices.append(price) x = 1 print("Welcome to the GTIN shop!") while x == 1: try: sleep(1) print("Please input the 8 digit GTIN code") sleep(0.5) GTIN0 = GTIN[0] GTIN1 = GTIN[1] GTIN2 = GTIN[2] GTIN3 = GTIN[3] GTINx = input("--&gt; ") </code></pre> <p>The error brought up here is that on the lines GTIN0 = GTIN[0] etc, the 'int' object not subscriptable, I can't work out how to fix it, it used to work before.</p> <p>For reference, here is "list2.txt".</p> <pre><code>45112454,Milk,1.29 55555555,Bread,0.49 87595376,Milkshake,1.99 </code></pre> <p>The next error comes up here (continuing from last segment):</p> <pre><code> GTINx = input("--&gt; ") if GTINx == GTIN0: product1 = products[0] price1 = prices[0] x = 2 elif GTINx == GTIN1: product1 = products[1] price1 = prices[1] x = 2 elif GTINx == GTIN2: product1 = products[2] price1 = prices[2] x = 2 elif GTINx == GTIN3: (this one is just here for if another one is added) product1 = products[3] price1 = prices[3] x = 2 else: print("Have another go") except: print("ERROR - Try Again") </code></pre> <p>To retrieve milk, the code is 7. For bread the code is 8, and for milkshake, the code is 9. I have no idea where python got these numbers from...</p> <pre><code>while x == 3: try: sleep(1) print("So you would like", number, product1, "?") sleep(0.5) confirmation = input("Please enter \"YES\" or \"NO\": --&gt; ") if confirmation == ("YES") or ("Yes") or ("yes"): x = 4 elif confirmation == ("NO") or ("No") or ("no"): x = 1 else: sleep(0.5) print("Have another go") except: print("ERROR - Try Again") </code></pre> <p>So, this was supposed to end that loop, and send them back to the start if they said no (relooped via while 1 == 1:) but, it acts as if they said yes, no matter what was typed.</p> <p>Next is a similar issue...</p> <pre><code>while x == 4: try: cost = price1 * number bill = bill + cost print("The cost is", cost) sleep(5) print("Would you like to purchase anything else?") sleep(0.5) anythingelse = input("Please enter \"YES\" or \"NO\": --&gt; ") sleep(1) if anythingelse == ("YES") or ("Yes") or ("yes"): x = 1 elif anythingelse == ("NO") or ("No") or ("no"): x = 5 else: sleep(0.5) print("Have another go") except: print("ERROR - Try Again") </code></pre> <p>Again, it answers yes, no matter what is inputted.</p> <p>Sorry for the spam, thanks for any help that I get.</p>
-1
2016-09-19T13:42:03Z
39,574,835
<p>For your loops <code>if confirmation == ("YES") or ("Yes") or ("yes"):</code></p> <p>That's never going to work in Python because you are basically asking <code>if confirmation is equal to "YES" or if ("Yes") or if ("yes")</code> ; and <code>if ("Yes")</code> is true because it's valid and not None or 0 or empty. You want:</p> <pre><code>if confirmation == ("YES") or confirmation == ("Yes") or confirmation == ("yes"): </code></pre> <p>There are other ways to do your <code>or</code> checking but I'm just going to correct what you have. </p> <p>As the comments and other answers has pointed out, a better way of checking "yes" would be:</p> <pre><code>if confirmation.lower() == "yes" </code></pre> <p>Just turn the input to lower case and check the value. </p> <p>As for your first issue. <code>GTIN0 = GTIN[0]</code> do you mean <code>GTIN0 = GTINs[0]</code>. Because <code>GTIN</code> is an int not something "subscriptable" just like what the error is telling you.</p> <p>As for your second issue with <code>GTIN0</code> and what not, see if the fix fixes it for you since the <code>GTIN0</code> and so on, was never set correctly. Edit your question if it's still wrong after the fixes. </p> <p>Also this line </p> <pre><code>elif GTINx == GTIN3: (this one is just here for if another one is added) </code></pre> <p>is not really correct for commenting (I'm guessing your commenting, use a <code>#</code> in front of comment lines)</p> <pre><code>elif GTINx == GTIN3: #(this one is just here for if another one is added) </code></pre>
4
2016-09-19T13:48:31Z
[ "python", "python-3.x", "csv" ]
'int' object not subscriptable error
39,574,702
<pre><code>while 1 == 1: import csv from time import sleep import sys bill = 0 with open('list2.txt') as csvfile: readCSV = csv.reader(csvfile, delimiter = ",") GTINs = [] products = [] prices = [] for row in readCSV: GTIN = row[0] product = str(row[1]) price = float(row[2]) GTINs.append(GTIN) products.append(product) prices.append(price) x = 1 print("Welcome to the GTIN shop!") while x == 1: try: sleep(1) print("Please input the 8 digit GTIN code") sleep(0.5) GTIN0 = GTIN[0] GTIN1 = GTIN[1] GTIN2 = GTIN[2] GTIN3 = GTIN[3] GTINx = input("--&gt; ") </code></pre> <p>The error brought up here is that on the lines GTIN0 = GTIN[0] etc, the 'int' object not subscriptable, I can't work out how to fix it, it used to work before.</p> <p>For reference, here is "list2.txt".</p> <pre><code>45112454,Milk,1.29 55555555,Bread,0.49 87595376,Milkshake,1.99 </code></pre> <p>The next error comes up here (continuing from last segment):</p> <pre><code> GTINx = input("--&gt; ") if GTINx == GTIN0: product1 = products[0] price1 = prices[0] x = 2 elif GTINx == GTIN1: product1 = products[1] price1 = prices[1] x = 2 elif GTINx == GTIN2: product1 = products[2] price1 = prices[2] x = 2 elif GTINx == GTIN3: (this one is just here for if another one is added) product1 = products[3] price1 = prices[3] x = 2 else: print("Have another go") except: print("ERROR - Try Again") </code></pre> <p>To retrieve milk, the code is 7. For bread the code is 8, and for milkshake, the code is 9. I have no idea where python got these numbers from...</p> <pre><code>while x == 3: try: sleep(1) print("So you would like", number, product1, "?") sleep(0.5) confirmation = input("Please enter \"YES\" or \"NO\": --&gt; ") if confirmation == ("YES") or ("Yes") or ("yes"): x = 4 elif confirmation == ("NO") or ("No") or ("no"): x = 1 else: sleep(0.5) print("Have another go") except: print("ERROR - Try Again") </code></pre> <p>So, this was supposed to end that loop, and send them back to the start if they said no (relooped via while 1 == 1:) but, it acts as if they said yes, no matter what was typed.</p> <p>Next is a similar issue...</p> <pre><code>while x == 4: try: cost = price1 * number bill = bill + cost print("The cost is", cost) sleep(5) print("Would you like to purchase anything else?") sleep(0.5) anythingelse = input("Please enter \"YES\" or \"NO\": --&gt; ") sleep(1) if anythingelse == ("YES") or ("Yes") or ("yes"): x = 1 elif anythingelse == ("NO") or ("No") or ("no"): x = 5 else: sleep(0.5) print("Have another go") except: print("ERROR - Try Again") </code></pre> <p>Again, it answers yes, no matter what is inputted.</p> <p>Sorry for the spam, thanks for any help that I get.</p>
-1
2016-09-19T13:42:03Z
39,574,981
<p>In relation with the 'if' comparison issue, I would recommend you to firstly remove the Upper format from the string and then compare. It would be then more idiomatic and also youre problem would be solved:</p> <pre><code>if anythingelse.lower() == ("yes"): x = 1 elif anythingelse.lower() == ("no"): x = 5 else: sleep(0.5) print("Have another go") </code></pre>
0
2016-09-19T13:55:37Z
[ "python", "python-3.x", "csv" ]
Replace newline in python when reading line for line
39,574,730
<p>I am trying to do a simple parsing on a text in python which I have no issues with in bash using tr '\n' ' '. Basically to get all of the lines on a single line. In python print line is a bit different from what I understand. re.sub cannot find my new line because it doesn't exist even though when I print to an output it does. Can someone explain how I can work around this issue in python?</p> <p>Here is my code so far:</p> <pre><code># -*- iso-8859-1 -*- import re def proc(): f= open('out.txt', 'r') lines=f.readlines() for line in lines: line = line.strip() if '[' in line: line_1 = line line_1_split = line_1.split(' ')[0] line_2 = re.sub(r'\n',r' ', line_1_split) print line_2 proc() </code></pre> <p>Edit: I know that "print line," will print without the newline. The issue is that I need to handle these lines both before and after doing operations line by line. My code in shell uses sed, awk and tr to do this.</p>
0
2016-09-19T13:43:36Z
39,574,815
<p>Use <code>replace()</code> method.</p> <pre><code>file = open('out.txt', 'r') data = file.read() file.close() data.replace('\n', '') </code></pre>
0
2016-09-19T13:47:32Z
[ "python", "regex", "newline", "python-2.x" ]
Replace newline in python when reading line for line
39,574,730
<p>I am trying to do a simple parsing on a text in python which I have no issues with in bash using tr '\n' ' '. Basically to get all of the lines on a single line. In python print line is a bit different from what I understand. re.sub cannot find my new line because it doesn't exist even though when I print to an output it does. Can someone explain how I can work around this issue in python?</p> <p>Here is my code so far:</p> <pre><code># -*- iso-8859-1 -*- import re def proc(): f= open('out.txt', 'r') lines=f.readlines() for line in lines: line = line.strip() if '[' in line: line_1 = line line_1_split = line_1.split(' ')[0] line_2 = re.sub(r'\n',r' ', line_1_split) print line_2 proc() </code></pre> <p>Edit: I know that "print line," will print without the newline. The issue is that I need to handle these lines both before and after doing operations line by line. My code in shell uses sed, awk and tr to do this.</p>
0
2016-09-19T13:43:36Z
39,575,029
<p>You can write directly to stdout to avoid the automatic newline of <code>print</code>:</p> <pre><code>from sys import stdout stdout.write("foo") stdout.write("bar\n") </code></pre> <p>This will print <code>foobar</code> on a single line.</p>
1
2016-09-19T13:57:46Z
[ "python", "regex", "newline", "python-2.x" ]
Replace newline in python when reading line for line
39,574,730
<p>I am trying to do a simple parsing on a text in python which I have no issues with in bash using tr '\n' ' '. Basically to get all of the lines on a single line. In python print line is a bit different from what I understand. re.sub cannot find my new line because it doesn't exist even though when I print to an output it does. Can someone explain how I can work around this issue in python?</p> <p>Here is my code so far:</p> <pre><code># -*- iso-8859-1 -*- import re def proc(): f= open('out.txt', 'r') lines=f.readlines() for line in lines: line = line.strip() if '[' in line: line_1 = line line_1_split = line_1.split(' ')[0] line_2 = re.sub(r'\n',r' ', line_1_split) print line_2 proc() </code></pre> <p>Edit: I know that "print line," will print without the newline. The issue is that I need to handle these lines both before and after doing operations line by line. My code in shell uses sed, awk and tr to do this.</p>
0
2016-09-19T13:43:36Z
39,575,150
<p>When you call the <code>print</code> statement, you automatically add a new line. Just add a comma:</p> <pre><code>print line_2, </code></pre> <p>And it will all print on the same line.</p> <p>Mind you, if you're trying to get all lines of a file, and print them on a single line, there are more efficient ways to do this:</p> <pre><code>with open('out.txt', 'r') as f: lines = f.readlines() for line in lines: line = line.strip() # Some extra line formatting stuff goes here print line, # Note the comma! </code></pre> <p>Alternatively, just join the lines on a string:</p> <pre><code>everything_on_one_line = ''.join(i.strip() for i in f.readlines()) print everything_on_one_line </code></pre>
1
2016-09-19T14:04:12Z
[ "python", "regex", "newline", "python-2.x" ]
Replace newline in python when reading line for line
39,574,730
<p>I am trying to do a simple parsing on a text in python which I have no issues with in bash using tr '\n' ' '. Basically to get all of the lines on a single line. In python print line is a bit different from what I understand. re.sub cannot find my new line because it doesn't exist even though when I print to an output it does. Can someone explain how I can work around this issue in python?</p> <p>Here is my code so far:</p> <pre><code># -*- iso-8859-1 -*- import re def proc(): f= open('out.txt', 'r') lines=f.readlines() for line in lines: line = line.strip() if '[' in line: line_1 = line line_1_split = line_1.split(' ')[0] line_2 = re.sub(r'\n',r' ', line_1_split) print line_2 proc() </code></pre> <p>Edit: I know that "print line," will print without the newline. The issue is that I need to handle these lines both before and after doing operations line by line. My code in shell uses sed, awk and tr to do this.</p>
0
2016-09-19T13:43:36Z
39,575,557
<p>Using <code>with</code> ensures you close the file after iteration.</p> <p>Iterating saves memory and doesn't load the entire file.</p> <p><code>rstrip()</code> removes the newline in the end.</p> <p>Combined:</p> <pre><code>with open('out.txt', 'r') as f: for line in f: print line.rstrip(), </code></pre>
1
2016-09-19T14:24:10Z
[ "python", "regex", "newline", "python-2.x" ]
Using python 2 or 3, matplotlib and tkinter causes an extra empty window to open on calling plt.show()
39,574,732
<p>I am making an interactive data analysis tool that I am having trouble with (in <code>python 2.7</code>, <code>3.4</code> and <code>3.5</code>). The full program makes graphs that the user has to interact with and then close. It also requires the user to input files via a filechooser. </p> <p>The issue is whenever I use <code>plt.show()</code> an additional small window opens (which I don't want) along with the graph. The small window then has to be closed too, to continue the program. Not that big a deal, but there are many graphs to interact with, so it is a bit off a pain always closing two windows.</p> <p>If the <code>Tkinter.Tk().withraw()</code> is uncommented only the plot opens, but now the program just hangs upon closing the graph and I have to kill the process. </p> <p>Any ideas for how I might get around this problem?</p> <p>Thanks in advance. Example code:</p> <pre><code>import matplotlib.pyplot as plt import numpy as np try: import Tkinter except (ImportError): import tkinter as Tkinter try: from tkFileDialog import askopenfilename except (ImportError): from tkinter.filedialog import askopenfilename # Tkinter.Tk().withdraw() print(askopenfilename()) x = np.arange(0,5,0.1) y = np.sin(x) plt.plot(x,y) plt.show() </code></pre>
1
2016-09-19T13:43:41Z
39,575,994
<p>You could try naming the figure as maybe it's getting confused as to what you are referring to when you ask it to show a figure</p> <pre><code>x = np.arange(0,5,0.1) y = np.sin(x) fig1 = plt.figure() plt.plot(x,y) plt.show(fig1) </code></pre>
0
2016-09-19T14:45:33Z
[ "python", "python-3.x", "matplotlib", "tkinter" ]
Using python 2 or 3, matplotlib and tkinter causes an extra empty window to open on calling plt.show()
39,574,732
<p>I am making an interactive data analysis tool that I am having trouble with (in <code>python 2.7</code>, <code>3.4</code> and <code>3.5</code>). The full program makes graphs that the user has to interact with and then close. It also requires the user to input files via a filechooser. </p> <p>The issue is whenever I use <code>plt.show()</code> an additional small window opens (which I don't want) along with the graph. The small window then has to be closed too, to continue the program. Not that big a deal, but there are many graphs to interact with, so it is a bit off a pain always closing two windows.</p> <p>If the <code>Tkinter.Tk().withraw()</code> is uncommented only the plot opens, but now the program just hangs upon closing the graph and I have to kill the process. </p> <p>Any ideas for how I might get around this problem?</p> <p>Thanks in advance. Example code:</p> <pre><code>import matplotlib.pyplot as plt import numpy as np try: import Tkinter except (ImportError): import tkinter as Tkinter try: from tkFileDialog import askopenfilename except (ImportError): from tkinter.filedialog import askopenfilename # Tkinter.Tk().withdraw() print(askopenfilename()) x = np.arange(0,5,0.1) y = np.sin(x) plt.plot(x,y) plt.show() </code></pre>
1
2016-09-19T13:43:41Z
39,599,850
<p>After some more research, it looks like the extra window is a root window. This link explains it:</p> <p><a href="https://bytes.com/topic/python/answers/768419-askopenfilename-tkfiledialog-problem" rel="nofollow">https://bytes.com/topic/python/answers/768419-askopenfilename-tkfiledialog-problem</a></p> <pre><code>from Tkinter import * import tkFileDialog root = Tk() root.withdraw() file = tkFileDialog.askopenfile(parent=root) file_read = file.read() #reads file </code></pre>
0
2016-09-20T16:59:02Z
[ "python", "python-3.x", "matplotlib", "tkinter" ]
Using python 2 or 3, matplotlib and tkinter causes an extra empty window to open on calling plt.show()
39,574,732
<p>I am making an interactive data analysis tool that I am having trouble with (in <code>python 2.7</code>, <code>3.4</code> and <code>3.5</code>). The full program makes graphs that the user has to interact with and then close. It also requires the user to input files via a filechooser. </p> <p>The issue is whenever I use <code>plt.show()</code> an additional small window opens (which I don't want) along with the graph. The small window then has to be closed too, to continue the program. Not that big a deal, but there are many graphs to interact with, so it is a bit off a pain always closing two windows.</p> <p>If the <code>Tkinter.Tk().withraw()</code> is uncommented only the plot opens, but now the program just hangs upon closing the graph and I have to kill the process. </p> <p>Any ideas for how I might get around this problem?</p> <p>Thanks in advance. Example code:</p> <pre><code>import matplotlib.pyplot as plt import numpy as np try: import Tkinter except (ImportError): import tkinter as Tkinter try: from tkFileDialog import askopenfilename except (ImportError): from tkinter.filedialog import askopenfilename # Tkinter.Tk().withdraw() print(askopenfilename()) x = np.arange(0,5,0.1) y = np.sin(x) plt.plot(x,y) plt.show() </code></pre>
1
2016-09-19T13:43:41Z
39,601,718
<p>Ok I think I solved it myself after a bit of poking around in the matplotlib source. I tried changing the matplotlib backend to gtk3cairo. I guess the <code>Tk().withdraw()</code> was also affecting the matplotlib backend. Works on my linux distro but still need to test it on windows. If I find a solution that works on both I will update the answer.</p> <p><strong>EDIT:</strong> <code>matplotlib.use("Qt4agg")</code> worked on my windows version. I alo got it work on linux by installing pyside. Doesn't work with the latest version of python3 unfortunatly</p> <p>Working code:</p> <pre><code>import matplotlib matplotlib.use("gtk3cairo") import matplotlib.pyplot as plt import numpy as np try: import Tkinter except (ImportError): import tkinter as Tkinter try: from tkFileDialog import askopenfilename except (ImportError): from tkinter.filedialog import askopenfilename Tkinter.Tk().withdraw() print(askopenfilename()) x = np.arange(0,5,0.1) y = np.sin(x) fig1 = plt.figure() plt.plot(x,y) plt.show(fig1) </code></pre>
0
2016-09-20T18:52:20Z
[ "python", "python-3.x", "matplotlib", "tkinter" ]
Django filter-save QuerySet
39,574,742
<p>I've a django model:-</p> <pre><code>class ModelA(models.Model): flag = models.BooleanField(default=True) </code></pre> <p>Next, I query it:- </p> <p><code>obj = ModelA.objects.filter(flag=True)</code></p> <p>Now, I change the <code>flag</code> of first object.</p> <pre><code>obj1 = obj[0] obj1.flag = False obj1.save() </code></pre> <p>Now, when I get <code>obj[0]</code> again, it returns me the <code>2nd object</code> of the filtered query. <strong>Why?</strong></p>
0
2016-09-19T13:44:21Z
39,575,287
<p>Because the first object does not match anymore the filtered queryset, you can't find it in the <code>obj</code> pointer. If you want to clone the queryset to another variable you can use <a href="https://docs.djangoproject.com/en/1.10/ref/models/querysets/#values-list" rel="nofollow">values_list</a>.</p>
-1
2016-09-19T14:11:05Z
[ "python", "django", "django-queryset" ]
Django filter-save QuerySet
39,574,742
<p>I've a django model:-</p> <pre><code>class ModelA(models.Model): flag = models.BooleanField(default=True) </code></pre> <p>Next, I query it:- </p> <p><code>obj = ModelA.objects.filter(flag=True)</code></p> <p>Now, I change the <code>flag</code> of first object.</p> <pre><code>obj1 = obj[0] obj1.flag = False obj1.save() </code></pre> <p>Now, when I get <code>obj[0]</code> again, it returns me the <code>2nd object</code> of the filtered query. <strong>Why?</strong></p>
0
2016-09-19T13:44:21Z
39,575,470
<p>I believe that every time you run <code>obj[0]</code>, Django goes back to the database and runs the query. You can see the queries that are executed by using <code>django.db.connection</code>:</p> <pre><code>&gt;&gt;&gt; from django.db import connection &gt;&gt;&gt; obj = ModelA.objects.filter(flag=True) &gt;&gt;&gt; print(connection.queries) [] &gt;&gt;&gt; o = obj[0] &gt;&gt;&gt; print(connection.queries) [{'time': '0.001', 'sql': 'SELECT "myapp_modela"."id", "myapp_modela"."flag" FROM "myapp_modela" WHERE "myapp_modela"."flag" = 1 LIMIT 1'}] &gt;&gt;&gt; o.flag = False &gt;&gt;&gt; o.save() &gt;&gt;&gt; print(connection.queries) [{'time': '0.001', 'sql': 'SELECT "myapp_modela"."id", "myapp_modela"."flag" FROM "myapp_modela" WHERE "myapp_modela"."flag" = 1 LIMIT 1'}, {'time': '0.000', 'sql': 'BEGIN'}, {'time': '0.002', 'sql': 'UPDATE "myapp_modela" SET "flag" = 0 WHERE "myapp_modela"."id" = 1'}] &gt;&gt;&gt; o = obj[0] &gt;&gt;&gt; print(connection.queries) [{'time': '0.001', 'sql': 'SELECT "myapp_modela"."id", "myapp_modela"."flag" FROM "myapp_modela" WHERE "myapp_modela"."flag" = 1 LIMIT 1'}, {'time': '0.000', 'sql': 'BEGIN'}, {'time': '0.002', 'sql': 'UPDATE "myapp_modela" SET "flag" = 0 WHERE "myapp_modela"."id" = 1'}, {'time': '0.000', 'sql': 'SELECT "myapp_modela"."id", "myapp_modela"."flag" FROM "myapp_modela" WHERE "myapp_modela"."flag" = 1 LIMIT 1'}] </code></pre>
0
2016-09-19T14:19:35Z
[ "python", "django", "django-queryset" ]
Django filter-save QuerySet
39,574,742
<p>I've a django model:-</p> <pre><code>class ModelA(models.Model): flag = models.BooleanField(default=True) </code></pre> <p>Next, I query it:- </p> <p><code>obj = ModelA.objects.filter(flag=True)</code></p> <p>Now, I change the <code>flag</code> of first object.</p> <pre><code>obj1 = obj[0] obj1.flag = False obj1.save() </code></pre> <p>Now, when I get <code>obj[0]</code> again, it returns me the <code>2nd object</code> of the filtered query. <strong>Why?</strong></p>
0
2016-09-19T13:44:21Z
39,575,617
<p>If you look at <code>Queryset.__getitem__()</code> (django/db/models/query.py), you'll find this (django 1.10):</p> <pre><code>295 qs = self._clone() 296 qs.query.set_limits(k, k + 1) 297 return list(qs)[0] </code></pre> <p>Note that you only get there if the queryset has not been iterated yet - else it would fetch the instance from it's resultcache, and then you'd get the same instance twice.</p> <p>FWIW, the point of this code is to optimize db access (by not fetching the whole dataset when a single instance is asked for), and yes this behaviour is quite suprising to say the least.</p> <p>If what you want is to keep the modify the first item while still keeping it as part of the dataset AND you're going to use the whole dataset, the simplest solution is to make a <code>list</code> from your queryset before:</p> <pre><code>obj = list(ModelA.objects.filter(flag=True)) obj1 = obj[0] obj1.flag = False obj1.save() </code></pre>
0
2016-09-19T14:27:08Z
[ "python", "django", "django-queryset" ]
Error loading MySQLdb module: No module named 'MySQLdb'
39,574,813
<p>I have tried a lot to solve this issue but I did not solve it. I have searched a lot on google and stackoverflow, no option is working for me. Please help me. Thanks in advance. I am using django 1.10, python 3.4. I have tried :</p> <ol> <li>pip install mysqldb.</li> <li>pip install mysql.</li> <li>pip install mysql-python.</li> <li>pip install MySQL-python.</li> <li>easy_install mysql-python.</li> <li>easy_install MySQL-python.</li> </ol> <p>Anything else left ?</p> <pre><code> C:\Users\benq\Desktop\dimo-develop\Project&gt;python manage.py runserver Unhandled exception in thread started by &lt;function check_errors.&lt;locals&gt;.wrapper at 0x0332D348&gt; Traceback (most recent call last): File "C:\Python34\lib\site-packages\django\db\backends\mysql\base.py", line 25, in &lt;module&gt; import MySQLdb as Database ImportError: No module named 'MySQLdb' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Python34\lib\site-packages\django\utils\autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "C:\Python34\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "C:\Python34\lib\site-packages\django\utils\autoreload.py", line 249, in raise_last_exception six.reraise(*_exception) File "C:\Python34\lib\site-packages\django\utils\six.py", line 685, in reraise raise value.with_traceback(tb) File "C:\Python34\lib\site-packages\django\utils\autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "C:\Python34\lib\site-packages\django\__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Python34\lib\site-packages\django\apps\registry.py", line 108, in populate app_config.import_models(all_models) File "C:\Python34\lib\site-packages\django\apps\config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "C:\Python34\lib\importlib\__init__.py", line 109, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "&lt;frozen importlib._bootstrap&gt;", line 2254, in _gcd_import File "&lt;frozen importlib._bootstrap&gt;", line 2237, in _find_and_load File "&lt;frozen importlib._bootstrap&gt;", line 2226, in _find_and_load_unlocked File "&lt;frozen importlib._bootstrap&gt;", line 1200, in _load_unlocked File "&lt;frozen importlib._bootstrap&gt;", line 1129, in _exec File "&lt;frozen importlib._bootstrap&gt;", line 1471, in exec_module File "&lt;frozen importlib._bootstrap&gt;", line 321, in _call_with_frames_removed File "C:\Python34\lib\site-packages\django\contrib\auth\models.py", line 4, in &lt;module&gt; from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "C:\Python34\lib\site-packages\django\contrib\auth\base_user.py", line 49, in &lt;module&gt; class AbstractBaseUser(models.Model): File "C:\Python34\lib\site-packages\django\db\models\base.py", line 108, in __new__ new_class.add_to_class('_meta', Options(meta, app_label)) File "C:\Python34\lib\site-packages\django\db\models\base.py", line 299, in add_to_class value.contribute_to_class(cls, name) File "C:\Python34\lib\site-packages\django\db\models\options.py", line 263, in contribute_to_class self.db_table = truncate_name(self.db_table, connection.ops.max_name_length()) File "C:\Python34\lib\site-packages\django\db\__init__.py", line 36, in __getattr__ return getattr(connections[DEFAULT_DB_ALIAS], item) File "C:\Python34\lib\site-packages\django\db\utils.py", line 212, in __getitem__ backend = load_backend(db['ENGINE']) File "C:\Python34\lib\site-packages\django\db\utils.py", line 116, in load_backend return import_module('%s.base' % backend_name) File "C:\Python34\lib\importlib\__init__.py", line 109, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "C:\Python34\lib\site-packages\django\db\backends\mysql\base.py", line 28, in &lt;module&gt; raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named 'MySQLdb' </code></pre>
2
2016-09-19T13:47:27Z
39,574,842
<p>MySQLdb is not compatible with Python 3. Use mysql-client or mysql-connect.</p>
1
2016-09-19T13:48:47Z
[ "python", "mysql", "django" ]
Error loading MySQLdb module: No module named 'MySQLdb'
39,574,813
<p>I have tried a lot to solve this issue but I did not solve it. I have searched a lot on google and stackoverflow, no option is working for me. Please help me. Thanks in advance. I am using django 1.10, python 3.4. I have tried :</p> <ol> <li>pip install mysqldb.</li> <li>pip install mysql.</li> <li>pip install mysql-python.</li> <li>pip install MySQL-python.</li> <li>easy_install mysql-python.</li> <li>easy_install MySQL-python.</li> </ol> <p>Anything else left ?</p> <pre><code> C:\Users\benq\Desktop\dimo-develop\Project&gt;python manage.py runserver Unhandled exception in thread started by &lt;function check_errors.&lt;locals&gt;.wrapper at 0x0332D348&gt; Traceback (most recent call last): File "C:\Python34\lib\site-packages\django\db\backends\mysql\base.py", line 25, in &lt;module&gt; import MySQLdb as Database ImportError: No module named 'MySQLdb' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Python34\lib\site-packages\django\utils\autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "C:\Python34\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "C:\Python34\lib\site-packages\django\utils\autoreload.py", line 249, in raise_last_exception six.reraise(*_exception) File "C:\Python34\lib\site-packages\django\utils\six.py", line 685, in reraise raise value.with_traceback(tb) File "C:\Python34\lib\site-packages\django\utils\autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "C:\Python34\lib\site-packages\django\__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Python34\lib\site-packages\django\apps\registry.py", line 108, in populate app_config.import_models(all_models) File "C:\Python34\lib\site-packages\django\apps\config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "C:\Python34\lib\importlib\__init__.py", line 109, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "&lt;frozen importlib._bootstrap&gt;", line 2254, in _gcd_import File "&lt;frozen importlib._bootstrap&gt;", line 2237, in _find_and_load File "&lt;frozen importlib._bootstrap&gt;", line 2226, in _find_and_load_unlocked File "&lt;frozen importlib._bootstrap&gt;", line 1200, in _load_unlocked File "&lt;frozen importlib._bootstrap&gt;", line 1129, in _exec File "&lt;frozen importlib._bootstrap&gt;", line 1471, in exec_module File "&lt;frozen importlib._bootstrap&gt;", line 321, in _call_with_frames_removed File "C:\Python34\lib\site-packages\django\contrib\auth\models.py", line 4, in &lt;module&gt; from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "C:\Python34\lib\site-packages\django\contrib\auth\base_user.py", line 49, in &lt;module&gt; class AbstractBaseUser(models.Model): File "C:\Python34\lib\site-packages\django\db\models\base.py", line 108, in __new__ new_class.add_to_class('_meta', Options(meta, app_label)) File "C:\Python34\lib\site-packages\django\db\models\base.py", line 299, in add_to_class value.contribute_to_class(cls, name) File "C:\Python34\lib\site-packages\django\db\models\options.py", line 263, in contribute_to_class self.db_table = truncate_name(self.db_table, connection.ops.max_name_length()) File "C:\Python34\lib\site-packages\django\db\__init__.py", line 36, in __getattr__ return getattr(connections[DEFAULT_DB_ALIAS], item) File "C:\Python34\lib\site-packages\django\db\utils.py", line 212, in __getitem__ backend = load_backend(db['ENGINE']) File "C:\Python34\lib\site-packages\django\db\utils.py", line 116, in load_backend return import_module('%s.base' % backend_name) File "C:\Python34\lib\importlib\__init__.py", line 109, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "C:\Python34\lib\site-packages\django\db\backends\mysql\base.py", line 28, in &lt;module&gt; raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named 'MySQLdb' </code></pre>
2
2016-09-19T13:47:27Z
39,575,525
<p>You can use <strong>mysqlclient</strong> instead of MySQLdb which is not compatible with Python 3:</p> <pre><code>pip install mysqlclient </code></pre>
1
2016-09-19T14:22:46Z
[ "python", "mysql", "django" ]
Error loading MySQLdb module: No module named 'MySQLdb'
39,574,813
<p>I have tried a lot to solve this issue but I did not solve it. I have searched a lot on google and stackoverflow, no option is working for me. Please help me. Thanks in advance. I am using django 1.10, python 3.4. I have tried :</p> <ol> <li>pip install mysqldb.</li> <li>pip install mysql.</li> <li>pip install mysql-python.</li> <li>pip install MySQL-python.</li> <li>easy_install mysql-python.</li> <li>easy_install MySQL-python.</li> </ol> <p>Anything else left ?</p> <pre><code> C:\Users\benq\Desktop\dimo-develop\Project&gt;python manage.py runserver Unhandled exception in thread started by &lt;function check_errors.&lt;locals&gt;.wrapper at 0x0332D348&gt; Traceback (most recent call last): File "C:\Python34\lib\site-packages\django\db\backends\mysql\base.py", line 25, in &lt;module&gt; import MySQLdb as Database ImportError: No module named 'MySQLdb' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Python34\lib\site-packages\django\utils\autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "C:\Python34\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "C:\Python34\lib\site-packages\django\utils\autoreload.py", line 249, in raise_last_exception six.reraise(*_exception) File "C:\Python34\lib\site-packages\django\utils\six.py", line 685, in reraise raise value.with_traceback(tb) File "C:\Python34\lib\site-packages\django\utils\autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "C:\Python34\lib\site-packages\django\__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Python34\lib\site-packages\django\apps\registry.py", line 108, in populate app_config.import_models(all_models) File "C:\Python34\lib\site-packages\django\apps\config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "C:\Python34\lib\importlib\__init__.py", line 109, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "&lt;frozen importlib._bootstrap&gt;", line 2254, in _gcd_import File "&lt;frozen importlib._bootstrap&gt;", line 2237, in _find_and_load File "&lt;frozen importlib._bootstrap&gt;", line 2226, in _find_and_load_unlocked File "&lt;frozen importlib._bootstrap&gt;", line 1200, in _load_unlocked File "&lt;frozen importlib._bootstrap&gt;", line 1129, in _exec File "&lt;frozen importlib._bootstrap&gt;", line 1471, in exec_module File "&lt;frozen importlib._bootstrap&gt;", line 321, in _call_with_frames_removed File "C:\Python34\lib\site-packages\django\contrib\auth\models.py", line 4, in &lt;module&gt; from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "C:\Python34\lib\site-packages\django\contrib\auth\base_user.py", line 49, in &lt;module&gt; class AbstractBaseUser(models.Model): File "C:\Python34\lib\site-packages\django\db\models\base.py", line 108, in __new__ new_class.add_to_class('_meta', Options(meta, app_label)) File "C:\Python34\lib\site-packages\django\db\models\base.py", line 299, in add_to_class value.contribute_to_class(cls, name) File "C:\Python34\lib\site-packages\django\db\models\options.py", line 263, in contribute_to_class self.db_table = truncate_name(self.db_table, connection.ops.max_name_length()) File "C:\Python34\lib\site-packages\django\db\__init__.py", line 36, in __getattr__ return getattr(connections[DEFAULT_DB_ALIAS], item) File "C:\Python34\lib\site-packages\django\db\utils.py", line 212, in __getitem__ backend = load_backend(db['ENGINE']) File "C:\Python34\lib\site-packages\django\db\utils.py", line 116, in load_backend return import_module('%s.base' % backend_name) File "C:\Python34\lib\importlib\__init__.py", line 109, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "C:\Python34\lib\site-packages\django\db\backends\mysql\base.py", line 28, in &lt;module&gt; raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named 'MySQLdb' </code></pre>
2
2016-09-19T13:47:27Z
39,575,675
<p>MySQLdb is only for Python 2.x. You can't install in Python 3.x versions. Now from your question i can see that you are working with Django. In this case you have three alternatives, from <a href="https://docs.djangoproject.com/en/1.10/ref/databases/#mysql-notes" rel="nofollow">Django mysql notes</a>:</p> <ul> <li>mysqldb </li> <li>mysqlclient</li> <li>mysql-connect-python</li> </ul> <p>This gives to you two alternatives, mysqlclient and mysql-connect-python, The first one requires compilation from extensions for the plugin and, in Windows, this implies VStudio Libraries and a knowhow for compiling native extensions.</p> <p>mysql-connect-python is not compiled (and i don't recommend this for production, maybe only for dev) so you are going to need to install this.</p> <p>You can try:</p> <pre><code>pip3 install mysql-connect-python </code></pre> <p>or</p> <pre><code>pip3 install http://cdn.mysql.com/Downloads/Connector-Python/mysql-connector-python-2.0.4.zip </code></pre> <p>if the first one fails.</p>
1
2016-09-19T14:29:55Z
[ "python", "mysql", "django" ]
How to convert suds object to xml string
39,574,831
<p>This is a duplicate to this question: <a href="http://stackoverflow.com/questions/33303813/how-to-convert-suds-object-to-xml">How to convert suds object to xml</a> <br>But the question has not been answered: "totxt" is not an attribute on the Client class. Unfortunately I lack of reputation to add comments. <br>So I ask again: Is there a way to convert a suds object to its xml?</p> <p>I ask this because I already have a system that consumes wsdl files and sends data to a webservice. But now the customers want to alternatively store the XML as files (to import them later manually). So all I need are 2 methods for writing data: One writes to a webservice (implemented and tested), the other (not implemented yet) writes to files. If only I could make something like this:<br> <code>xml_as_string = My_suds_object.to_xml()</code></p> <p>The following code is just an example and does not run. And it's not elegant. Doesn't matter. I hope you get the idea what I want to achieve: I have the function "write_customer_obj_webservice" that works. Now I want to write the function "write_customer_obj_xml_file".<br></p> <pre><code>import suds def get_customer_obj(): wsdl_url = r'file:C:/somepathhere/Customer.wsdl' service_url = r'http://someiphere/Customer' c = suds.client.Client(wsdl_url, location=service_url) customer = c.factory.create("ns0:CustomerType") return customer def write_customer_obj_webservice(customer): wsdl_url = r'file:C:/somepathhere/Customer.wsdl' service_url = r'http://someiphere/Customer' c = suds.client.Client(wsdl_url, location=service_url) response = c.service.save(someparameters, None, None, customer) return response def write_customer_obj_xml_file(customer): output_filename = r'C\temp\testxml' # The following line is the problem. "to_xml" does not exist and I can't find a way to do it. xml = customer.to_xml() fo = open(output_filename, 'a') try: fo.write(xml) except: raise else: response = 'All ok' finally: fo.close() return response # Get the customer object always from the wsdl. customer = get_customer_obj() # Since customer is an object, setting it's attributes is very easy. There are very complex objects in this system. customer.name = "Doe J." customer.age = 42 # Write the new customer to a webservice or store it in a file for later proccessing if later_processing: response = write_customer_obj_xml_file(customer) else: response = write_customer_obj_webservice(customer) </code></pre>
0
2016-09-19T13:48:21Z
39,589,789
<p>You have some issues in <code>write_customer_obj_xml_file</code> function:</p> <p>Fix bad path:</p> <pre><code>output_filename = r'C:\temp\test.xml' </code></pre> <blockquote> <p>The following line is the problem. "to_xml" does not exist and I can't find a way to do it.</p> </blockquote> <p>What's the type of customer? <code>type(customer)</code>?</p> <pre><code>xml = customer.to_xml() # to be continued... </code></pre> <p>Why mode='a'? ('a' => append, 'w' => create + write)</p> <p>Use a <code>with</code> statement (file context manager).</p> <pre><code>with open(output_filename, 'w') as fo: fo.write(xml) </code></pre> <p>Don't need to return a response string: use an exception manager. The exception to catch can be <a href="https://docs.python.org/2/library/exceptions.html#exceptions.EnvironmentError" rel="nofollow">EnvironmentError</a>.</p> <h2>Analyse</h2> <p>The following call:</p> <pre><code>customer = c.factory.create("ns0:CustomerType") </code></pre> <p>Construct a <code>CustomerType</code> on the fly, and return a <code>CustomerType</code> instance <code>customer</code>.</p> <p>I think you can introspect your <code>customer</code> object, try the following:</p> <pre><code>vars(customer) # display the object attributes help(customer) # display an extensive help about your instance </code></pre> <p>Another way is to try the WSDL URLs by hands, and see the XML results. You may obtain the full description of your <code>CustomerType</code> object.</p> <h2>And then?</h2> <p>Then, with the attributes list, you can create your own XML. Use an XML template and fill it with the object attributes.</p> <p>You may also found the magic function (<code>to_xml</code>) which do the job for you. But, not sure the XML format matches your need.</p>
0
2016-09-20T08:59:04Z
[ "python", "xml", "soap", "suds" ]
How to convert suds object to xml string
39,574,831
<p>This is a duplicate to this question: <a href="http://stackoverflow.com/questions/33303813/how-to-convert-suds-object-to-xml">How to convert suds object to xml</a> <br>But the question has not been answered: "totxt" is not an attribute on the Client class. Unfortunately I lack of reputation to add comments. <br>So I ask again: Is there a way to convert a suds object to its xml?</p> <p>I ask this because I already have a system that consumes wsdl files and sends data to a webservice. But now the customers want to alternatively store the XML as files (to import them later manually). So all I need are 2 methods for writing data: One writes to a webservice (implemented and tested), the other (not implemented yet) writes to files. If only I could make something like this:<br> <code>xml_as_string = My_suds_object.to_xml()</code></p> <p>The following code is just an example and does not run. And it's not elegant. Doesn't matter. I hope you get the idea what I want to achieve: I have the function "write_customer_obj_webservice" that works. Now I want to write the function "write_customer_obj_xml_file".<br></p> <pre><code>import suds def get_customer_obj(): wsdl_url = r'file:C:/somepathhere/Customer.wsdl' service_url = r'http://someiphere/Customer' c = suds.client.Client(wsdl_url, location=service_url) customer = c.factory.create("ns0:CustomerType") return customer def write_customer_obj_webservice(customer): wsdl_url = r'file:C:/somepathhere/Customer.wsdl' service_url = r'http://someiphere/Customer' c = suds.client.Client(wsdl_url, location=service_url) response = c.service.save(someparameters, None, None, customer) return response def write_customer_obj_xml_file(customer): output_filename = r'C\temp\testxml' # The following line is the problem. "to_xml" does not exist and I can't find a way to do it. xml = customer.to_xml() fo = open(output_filename, 'a') try: fo.write(xml) except: raise else: response = 'All ok' finally: fo.close() return response # Get the customer object always from the wsdl. customer = get_customer_obj() # Since customer is an object, setting it's attributes is very easy. There are very complex objects in this system. customer.name = "Doe J." customer.age = 42 # Write the new customer to a webservice or store it in a file for later proccessing if later_processing: response = write_customer_obj_xml_file(customer) else: response = write_customer_obj_webservice(customer) </code></pre>
0
2016-09-19T13:48:21Z
39,614,744
<p>I found a way that works for me. The trick is to create the Client with the option "nosend=True". <br> In the <a href="https://jortel.fedorapeople.org/suds/doc/suds.options.Options-class.html" rel="nofollow">documentation</a> it says:<br></p> <blockquote> <p><strong>nosend</strong> - Create the soap envelope but don't send. When specified, method invocation returns a RequestContext instead of sending it.</p> </blockquote> <p>The RequestContext object has the attribute envelope. This is the XML as string. <br> Some pseudo code to illustrate:<br></p> <pre><code>c = suds.client.Client(url, nosend=True) customer = c.factory.create("ns0:CustomerType") customer.name = "Doe J." customer.age = 42 response = c.service.save(someparameters, None, None, customer) print response.envelope # This prints the XML string that would have been sent. </code></pre>
0
2016-09-21T11:02:32Z
[ "python", "xml", "soap", "suds" ]
filter tags of django-taggit in Django's Queryset
39,574,909
<p>Having the following models:</p> <pre><code>class Post(models.Model): title = models.CharField(max_length=250) tags = TaggableManager() </code></pre> <p>and the data are:</p> <pre><code>**post.title** **post.tags** Django By Example python,django,web Who was Django Reinhardt python,django, Test-Driven Development with Python python,web Python for Data Analysis python,data Learning Python python Programming Python python Automate the Boring Stuff with Python python </code></pre> <p>I try to code below</p> <pre><code>&gt;&gt;&gt; alist=Post.objects.filter(tags__name__in=["data","python"]) &gt;&gt;&gt; for i in alist.annotate(sam_tags=Count('tags')): ... print("\n---",i) ... print("tags of it : ",i.tags.all()) ... print("value of sam_tags : ",i.sam_tags) ... --- Django By Example tags of it : [&lt;Tag: django&gt;, &lt;Tag: python&gt;, &lt;Tag: web&gt;] value of sam_tags : 1 --- Who was Django Reinhardt tags of it : [&lt;Tag: django&gt;, &lt;Tag: python&gt;] value of sam_tags : 1 --- Automate the Boring Stuff with Python tags of it : [&lt;Tag: python&gt;] value of sam_tags : 1 --- Test-Driven Development with Python tags of it : [&lt;Tag: python&gt;, &lt;Tag: web&gt;] value of sam_tags : 1 --- Learning Python tags of it : [&lt;Tag: python&gt;] value of sam_tags : 1 --- Python for Data Analysis tags of it : [&lt;Tag: data&gt;, &lt;Tag: python&gt;] value of sam_tags : 2 --- Programming Python tags of it : [&lt;Tag: python&gt;] value of sam_tags : 1 &gt;&gt;&gt; </code></pre> <p>why is the value of slist[0].sam_tags (post:Django By Example) equal to 1?</p> <p>I think the post object of (post:Django By Example) has three tags [python,django and web] after reading the Django's documentation.</p> <p><a href="https://docs.djangoproject.com/en/1.10/ref/models/querysets/#count" rel="nofollow">https://docs.djangoproject.com/en/1.10/ref/models/querysets/#count</a></p> <p>It said that <strong>Count(expression)</strong> returns the number of objects that are related through the provided expression. so the code </p> <pre><code>&gt;&gt;&gt;alist[0].tags.all() [&lt;Tag: django&gt;, &lt;Tag: python&gt;, &lt;Tag: web&gt;] </code></pre> <p>shows there are three tags in alist[0].tags,</p> <pre><code>&gt;&gt;&gt; slist=alist.annotate(sam_tags=Count('tags')) &gt;&gt;&gt; slist[0].tags.all() [&lt;Tag: django&gt;, &lt;Tag: python&gt;, &lt;Tag: web&gt;] &gt;&gt;&gt; slist[0].sam_tags 1 </code></pre> <p>but here I get the value 1,<br> why?</p> <p>I understand that Django is counting only the "python" and "data" tags which I included in my filter clause - other tags are not counted.</p> <p>The output of "slist[0].tags.all()" shows that slist[0] has three tags related with itself. Because the documentation of django says that Count(expression) returns the number of objects that are related through the provided expression, slist[0].sam_tags should be 3 according to the documentation, but django-taggit make slist[0].sam_tags to be 1. </p> <p>So what I really want to know is how django-taggit lets Count(expression) in the filter clause only calculate the number of tags in the filter condition .</p>
0
2016-09-19T13:52:34Z
39,692,261
<p>Django is counting only the <code>python</code> and <code>data</code> tags which you included in your filter clause - other tags are not counted. (Note that the only example with <code>sam_tags</code> of 2 is the one tagged both <code>data</code> and <code>python</code>.) This is probably unexpected behavior, but makes sense if you consider how the underlying SQL is executed. See this example from a similar schema to yours:</p> <pre><code>&gt;&gt;&gt; a = Article.objects.filter(tags__slug__in=['python']).annotate(num_tags=Count('tags'))[0] &gt;&gt;&gt; a.num_tags 1 &gt;&gt;&gt; a.tags.count() 2 </code></pre> <p>If I change the filter clause to filter on somethign other than tags, it behaves as expected:</p> <pre><code>&gt;&gt;&gt; Article.objects.filter(pk=a.pk).annotate(num_tags=Count('tags'))[0].num_tags 2 &gt;&gt;&gt; Article.objects.filter(pk=a.pk).annotate(num_tags=Count('tags'))[0].tags.count() 2 </code></pre>
1
2016-09-25T22:01:54Z
[ "python", "django", "django-1.9", "django-taggit" ]
Python-Django Response the text of error
39,574,918
<p>How can I response the text of validation error to my template with Ajax?</p> <pre><code>def create_user(request): if request.method == 'POST': is_super = True if request.POST.get('is_super') in 'false': is_super = False if request.POST.get('password') == request.POST.get('confirm'): user = User.objects.create(first_name=request.POST.get('first_name'), last_name=request.POST.get('second_name'), username=request.POST.get('username'), is_superuser=is_super, date_joined=datetime.now()) user.set_password(request.POST.get('password')) user.save() else: raise forms.ValidationError("Passwords doesn't match") return HttpResponse('') </code></pre>
-1
2016-09-19T13:52:54Z
39,748,062
<pre><code>def create_user(request): if request.method == 'POST': is_super = True if request.POST.get('is_super') in 'false': is_super = False if request.POST.get('password') == request.POST.get('confirm'): user = User.objects.create(first_name=request.POST.get('first_name'), last_name=request.POST.get('second_name'), username=request.POST.get('username'), is_superuser=is_super, date_joined=datetime.now()) user.set_password(request.POST.get('password')) user.save() else: return HttpResponse(json.dumps({'error': True, 'message': 'Password and confirm password doesnt match'}))` return HttpResponse('') </code></pre> <p>You need to show the above error message "Password and confirm password doesn't match" in HTML using Jquery.</p>
0
2016-09-28T12:49:30Z
[ "python", "ajax", "django" ]
TensorFlow "tf.image" functions on an image batch
39,574,999
<p>I would like to use this function in TensorFlow, however it operates on 3D tensors rather than 4D tensors: I have an outer dimension of batch_size. </p> <pre><code>tf.image.random_flip_left_right(input_image_data) </code></pre> <p>That said, this function expects a tensor (image) of shape:</p> <pre><code>(width, height, channels) </code></pre> <p>But I have multiple images such as: </p> <pre><code>(batch_size, width, height, channels) </code></pre> <p>How could I map the random flip function to each image in my batch size and get as an output a tensor with the same 4D shape I already have? </p> <p>My guess is that it would need a reshape at the entry of the function and a reshape after the function, but I am not sure whether or not this would break the data's structure and blend together images in the batch when applying the mirror. Moreover, this approach would do a single randomization on the whole batch rather than on a per-image basis. </p> <p>Any suggestion appreciated! </p>
1
2016-09-19T13:56:24Z
39,578,657
<p>You would have to use something like tf.pack and tf.unpack or tf.gather and tf.concatenate to convert from your 4D array to your 3D array.</p> <p>Depending upon how your loading your data you can do the processing in numpy. Another alternative is to process each image before you put it into a batch. </p> <p>Let me know if you need an explanation for how tf.pack or the others work.</p>
0
2016-09-19T17:16:57Z
[ "python", "image-processing", "machine-learning", "computer-vision", "tensorflow" ]
TensorFlow "tf.image" functions on an image batch
39,574,999
<p>I would like to use this function in TensorFlow, however it operates on 3D tensors rather than 4D tensors: I have an outer dimension of batch_size. </p> <pre><code>tf.image.random_flip_left_right(input_image_data) </code></pre> <p>That said, this function expects a tensor (image) of shape:</p> <pre><code>(width, height, channels) </code></pre> <p>But I have multiple images such as: </p> <pre><code>(batch_size, width, height, channels) </code></pre> <p>How could I map the random flip function to each image in my batch size and get as an output a tensor with the same 4D shape I already have? </p> <p>My guess is that it would need a reshape at the entry of the function and a reshape after the function, but I am not sure whether or not this would break the data's structure and blend together images in the batch when applying the mirror. Moreover, this approach would do a single randomization on the whole batch rather than on a per-image basis. </p> <p>Any suggestion appreciated! </p>
1
2016-09-19T13:56:24Z
39,852,683
<p>You can use map_fcn as described in this post <a href="http://stackoverflow.com/questions/38920240/tensorflow-image-operations-for-batches">TensorFlow image operations for batches</a></p> <p>result = tf.map_fn(lambda img: tf.image.random_flip_left_right(img), images)</p>
1
2016-10-04T12:43:57Z
[ "python", "image-processing", "machine-learning", "computer-vision", "tensorflow" ]
Button instance has no _call_ method
39,575,022
<pre><code> #AssessmentGUI from Tkinter import * window=Tk() window.title('Troubleshooting') def start(): wet() def wet(): global wetlabel wetlabel=Label(window, text="Has the phone got wet? Y/N") wetsubmit() def wetsubmit(): wetlabel.pack() wetanswer=(entry.get()) if wetanswer=="Y": print"ADD SOLUTION" else: dropped() def dropped(): global droppedlabel dropwindow.title('Troubleshooting') dropwindow.mainloop() droplabel=Label(dropwindow, text="Has the phone been dropped? Y/N") droplabel.pack() dropButton.pack() dropsubmit() def dropsubmit(): print "test" window.geometry("300x100") global wetsubmit Button=Button(window, text="Submit Answer", activebackground="Green",command= wetsubmit , width=100) dropwindow=Tk() dropButton=Button(dropwindow, text="Submit Answer", activebackground="Green",command= dropsubmit , width=100) entry=Entry(window, text="Test", width=100) start() entry.pack() Button.pack() window.mainloop() </code></pre> <p>Above is my code which isn't working due to the error. Basically what I want to happen is that each window opens another window after it for the next question on the troubleshooting program! If anyone has the task it would be nice if youy could suggest a better method if mine is unfixable. The error message says:</p> <pre><code> Traceback (most recent call last): File "H:\GCSE\Computing\GUI.py", line 36, in &lt;module&gt; dropButton=Button(dropwindow, text="Submit Answer", activebackground="Green",command= dropsubmit , width=100) AttributeError: Button instance has no __call__ method* </code></pre> <p>This is after a little bit of tweaking to the original code but I cannot fix this problem!</p>
0
2016-09-19T13:57:25Z
39,575,120
<p>You have a class, named <code>Button</code>,and then you create a variable named <code>Button</code>. You have now destroyed the class, so the next time you try to create a button, you are calling your variable instead.</p> <p>Lesson: don't use variable names that are the same as classes. </p>
1
2016-09-19T14:02:49Z
[ "python", "user-interface", "tkinter", "label", "call" ]
create multidimensional dictionary to count word occurence
39,575,236
<p>I have a source.txt file consisting of words. Each word is in a new line.</p> <pre><code>apple tree bee go apple see </code></pre> <p>I also have a taget_words.txt file, where the words are also in one line each.</p> <pre><code>apple bee house garden eat </code></pre> <p>Now I have to search for each of the target words in the source file. If a target word is found, e.g. apple, a dictionary entry for the target word and each of the 3 preceding and 3 following words should be made. In the example case, that would be</p> <pre><code>words_dict = {'apple':'tree', 'apple':'bee', 'apple':'go'} </code></pre> <p>How can I tell python by creating and populating the dictionary to consider these 3 words before and after the entry in the source_file? My idea was to use lists but ideally the code should be very efficient and fast as the files consists of some million words. I guess, with lists, the computation is very slow. </p> <pre><code>from collections import defaultdict words_occ = {} defaultdict = defaultdict(words_occ) with open('source.txt') as s_file, open('target_words.txt') as t_file: for line in t_file: keys = [line.split()] lines = s_file.readlines() for line in lines: s_words = line.strip() # if key is found in s_words # look at the 1st, 2nd, 3rd word before and after # create a key, value entry for each of them </code></pre> <p>Later, I have to count the occurrence of each key, value pair and add the number to a separate dictionary, that is why I started with a defaultdict.</p> <p>I would be glad about any suggestion for the above code.</p>
-5
2016-09-19T14:08:09Z
39,689,816
<p>The first issue you will face is your lack of understanding of dicts. Each key can occur only once, so if you ask the interpreter to give you the value of the one you gave you might get a surprise:</p> <pre><code>&gt;&gt;&gt; {'apple':'tree', 'apple':'bee', 'apple':'go'} {'apple': 'go'} </code></pre> <p>The problem is that there can only be one value associated with the key <code>'apple'</code>.</p> <p>You appear to be searching for suitable data structures, but StackOverflow is for improving or fixing problematic code.</p>
0
2016-09-25T17:37:02Z
[ "python", "dictionary", "multidimensional-array", "counter" ]
Function to check a variable and change it
39,575,281
<p>I am making a calculator to turn RGB values into Hexidecimal numbers. as I was coding I realised I had written the same code three times to check user input for red, green, and blue. So I thought, why not use a function to check my variables for me!! Here is my code:</p> <pre><code>invalid_msg = 'Whoops looks like you have entered incorrect information' def check_rgb(var): while var &gt; 255 or var &lt; 0: print invalid_msg var = int(raw_input('Please enter a value between 0 and 255:')) return var def rgb_hex(): red = int(raw_input('Enter your value for red.')) check_rgb(red) green = int(raw_input('Enter your value for green.')) while green &gt; 255 or red &lt; 0: print invalid_msg green = int(raw_input('Enter your value for green.')) blue = int(raw_input('Enter your value for blue.')) while blue &gt; 255 or red &lt; 0: print invalid_msg blue = int(raw_input('Enter your value for blue.')) val = (red &lt;&lt; 16) + (green &lt;&lt; 8) + blue print '%s' % (hex(val)[2:]).upper() rgb_hex() </code></pre> <p>The issue is with redeclaring the variable. Right now this stores the value entered into the function to the variable 'var' not red.</p>
1
2016-09-19T14:10:40Z
39,575,577
<p>You need to do something like something like</p> <pre><code>red = check_rgb(red) </code></pre> <p>When you just do</p> <pre><code>check_rgb(red) </code></pre> <p>The return value is not used.</p>
2
2016-09-19T14:25:25Z
[ "python", "python-2.7" ]
Function to check a variable and change it
39,575,281
<p>I am making a calculator to turn RGB values into Hexidecimal numbers. as I was coding I realised I had written the same code three times to check user input for red, green, and blue. So I thought, why not use a function to check my variables for me!! Here is my code:</p> <pre><code>invalid_msg = 'Whoops looks like you have entered incorrect information' def check_rgb(var): while var &gt; 255 or var &lt; 0: print invalid_msg var = int(raw_input('Please enter a value between 0 and 255:')) return var def rgb_hex(): red = int(raw_input('Enter your value for red.')) check_rgb(red) green = int(raw_input('Enter your value for green.')) while green &gt; 255 or red &lt; 0: print invalid_msg green = int(raw_input('Enter your value for green.')) blue = int(raw_input('Enter your value for blue.')) while blue &gt; 255 or red &lt; 0: print invalid_msg blue = int(raw_input('Enter your value for blue.')) val = (red &lt;&lt; 16) + (green &lt;&lt; 8) + blue print '%s' % (hex(val)[2:]).upper() rgb_hex() </code></pre> <p>The issue is with redeclaring the variable. Right now this stores the value entered into the function to the variable 'var' not red.</p>
1
2016-09-19T14:10:40Z
39,575,680
<p>You can check the condition on the three colors calling separately the function and then compare all them in the same statement:</p> <pre><code>red_ok = check_rgb(red) green_ok = check_rgb(green) blue_ok = check_rgb(blue) if (red_ok and green_ok and blue_ok) : val = (red &lt;&lt; 16) + (green &lt;&lt; 8) + blue print '%s' % (hex(val)[2:]).upper() </code></pre>
0
2016-09-19T14:30:12Z
[ "python", "python-2.7" ]
Function to check a variable and change it
39,575,281
<p>I am making a calculator to turn RGB values into Hexidecimal numbers. as I was coding I realised I had written the same code three times to check user input for red, green, and blue. So I thought, why not use a function to check my variables for me!! Here is my code:</p> <pre><code>invalid_msg = 'Whoops looks like you have entered incorrect information' def check_rgb(var): while var &gt; 255 or var &lt; 0: print invalid_msg var = int(raw_input('Please enter a value between 0 and 255:')) return var def rgb_hex(): red = int(raw_input('Enter your value for red.')) check_rgb(red) green = int(raw_input('Enter your value for green.')) while green &gt; 255 or red &lt; 0: print invalid_msg green = int(raw_input('Enter your value for green.')) blue = int(raw_input('Enter your value for blue.')) while blue &gt; 255 or red &lt; 0: print invalid_msg blue = int(raw_input('Enter your value for blue.')) val = (red &lt;&lt; 16) + (green &lt;&lt; 8) + blue print '%s' % (hex(val)[2:]).upper() rgb_hex() </code></pre> <p>The issue is with redeclaring the variable. Right now this stores the value entered into the function to the variable 'var' not red.</p>
1
2016-09-19T14:10:40Z
39,576,137
<p>As Davis Yoshida mentions, merely doing <code>check_rgb(red)</code> doesn't change the original value of <code>red</code>, since you forgot to save the value that <code>check_rgb</code> returns.</p> <p>I recommend expanding your helper function so that it gets the user input and validates it too. Here's an example that also makes sure that the input is a valid integer in the proper range. This code also shows an easier way to print the hex representation of the RGB value. </p> <pre><code>def get_color_byte(name): while True: s = raw_input('Enter a value from 0 to 255 for %s: ' % name) try: v = int(s) if not 0 &lt;= v &lt;= 255: raise ValueError('Out of range') return v except ValueError as e: print e r, g, b = [get_color_byte(name) for name in ('red', 'green', 'blue')] rgb = (r &lt;&lt; 16) | (g &lt;&lt; 8 ) | b print '%06X' % rgb </code></pre> <p><strong>test</strong></p> <pre class="lang-none prettyprint-override"><code>Enter a value from 0 to 255 for red: hello invalid literal for int() with base 10: 'hello' Enter a value from 0 to 255 for red: 12.5 invalid literal for int() with base 10: '12.5' Enter a value from 0 to 255 for red: -5 Out of range Enter a value from 0 to 255 for red: 300 Out of range Enter a value from 0 to 255 for red: 240 Enter a value from 0 to 255 for green: 13 Enter a value from 0 to 255 for blue: 7 F00D07 </code></pre> <p>As an alternative to <code>print '%06X' % rgb</code> you could use the more modern <code>format</code> function:</p> <pre><code>print format(rgb, '06X') </code></pre> <p>In both of those, the capital <code>X</code> says to use capital letters in the hex string.</p>
0
2016-09-19T14:52:05Z
[ "python", "python-2.7" ]
Code works in Windows, but not on Mac
39,575,564
<p>So I'm new to programming, and recently I got an assignment to create a program that could convert binary to decimal and vice versa, and also decimal to hexadecimal and vice versa. The problem is, I'm not allowed to use available functions such as <code>int()</code> or <code>hex()</code> or <code>bin()</code>.</p> <p>I might have found a way to do the conversion from decimal to binary, and I tried it out on my friends' laptop (which runs on Windows) and it worked. But when I tried to execute it in my own laptop (a MacBook), it won't run even though it's the exact same code. Here's the code:</p> <pre><code>def dectobin(x): temporary_result = "" while x &gt; 0: result = str(x % 2) + temporary_result x = x // 2 return result </code></pre> <p>Instead of the result being the binary number, it just returns the value of <code>x % 2</code>. Does anyone have any idea why it does that on a Mac and not on Windows? And if so, where did I go wrong? How do I fix it?</p>
0
2016-09-19T14:24:42Z
39,575,819
<p>The value of <code>temporary_result</code> never changes, but remains <code>""</code>. Therefore the value of <code>result</code> will always be the <code>str(x % 2)</code> for the most-recently-processed value of <code>x</code>. Given that the loop terminates when <code>x</code> goes to zero, it's likely that the function always returns <code>1</code>.</p> <p>Are you SURE this is the code you executed on Windows? You don't say how you know "it won't even run" but it's possible you are using different Python versions on the two different machines. </p>
1
2016-09-19T14:37:21Z
[ "python", "windows", "osx", "python-3.x" ]
Code works in Windows, but not on Mac
39,575,564
<p>So I'm new to programming, and recently I got an assignment to create a program that could convert binary to decimal and vice versa, and also decimal to hexadecimal and vice versa. The problem is, I'm not allowed to use available functions such as <code>int()</code> or <code>hex()</code> or <code>bin()</code>.</p> <p>I might have found a way to do the conversion from decimal to binary, and I tried it out on my friends' laptop (which runs on Windows) and it worked. But when I tried to execute it in my own laptop (a MacBook), it won't run even though it's the exact same code. Here's the code:</p> <pre><code>def dectobin(x): temporary_result = "" while x &gt; 0: result = str(x % 2) + temporary_result x = x // 2 return result </code></pre> <p>Instead of the result being the binary number, it just returns the value of <code>x % 2</code>. Does anyone have any idea why it does that on a Mac and not on Windows? And if so, where did I go wrong? How do I fix it?</p>
0
2016-09-19T14:24:42Z
39,575,860
<p>Why do you need temporary_result when the value never changes within your loop? </p> <pre><code>def dectobin(x): result = "" while x &gt; 0: result = str(x % 2) + result x = x // 2 return result </code></pre>
0
2016-09-19T14:39:20Z
[ "python", "windows", "osx", "python-3.x" ]
KMeans clustering of textual data
39,575,591
<p>I have a pandas dataframe with the following 2 columns:</p> <pre><code> Database Name Name db1_user Login db1_client Login db_care Login db_control LoginEdit db_technology View db_advanced LoginEdit </code></pre> <p>I have to cluster the Database Name based on the field “Name”. When I convert it to a numpy, using </p> <p>dataset = df2.values</p> <p>When I print the print(dataset.dtype), the type is object. I have just started with Clustering, from what I read, I understand that object is not a type suitable for Kmeans clustering. </p> <p>Any help would be appreicated!! </p>
-2
2016-09-19T14:26:10Z
39,581,534
<p>What is the <strong>mean</strong> of</p> <pre><code>Login LoginEdit View </code></pre> <p>supposed to be?</p> <p>There is a reason why k-means only works on continuous numerical data. Because the <em>mean</em> requires such data to be well defined.</p> <p>I don't think clustering is applicable on your problem <em>at all</em> (rather look into data cleaning). But clearly you need a method that works with arbitrary distances - k-mean does not.</p>
0
2016-09-19T20:26:04Z
[ "python", "dataframe", "cluster-analysis", "k-means" ]
KMeans clustering of textual data
39,575,591
<p>I have a pandas dataframe with the following 2 columns:</p> <pre><code> Database Name Name db1_user Login db1_client Login db_care Login db_control LoginEdit db_technology View db_advanced LoginEdit </code></pre> <p>I have to cluster the Database Name based on the field “Name”. When I convert it to a numpy, using </p> <p>dataset = df2.values</p> <p>When I print the print(dataset.dtype), the type is object. I have just started with Clustering, from what I read, I understand that object is not a type suitable for Kmeans clustering. </p> <p>Any help would be appreicated!! </p>
-2
2016-09-19T14:26:10Z
39,698,930
<p>I don't understand whether you want to develop clusters for each GROUP of "Name" Attributes, or alternatively create n clusters regardless of the value of "Name"; and I don't understand what clustering could achieve here.</p> <p>In any case, just a few days ago there was a similar question on the datascience SE site (from an R user, though), asking for similarity of local-names of email addresses (the part before the "@"), not of database-names. The problem is similar to yours. </p> <p>Check this out:</p> <p><a href="http://datascience.stackexchange.com/questions/14146/text-similarities/14148#14148">http://datascience.stackexchange.com/questions/14146/text-similarities/14148#14148</a></p> <p>The answer was comprehensive with respect to the <strong>different distance measures for strings</strong>. </p> <p>Maybe this is what you should investigate. Then decide on a proper distance measure that is available in python (or one that you can program yourself), and that fits your needs.</p>
1
2016-09-26T09:16:38Z
[ "python", "dataframe", "cluster-analysis", "k-means" ]
OpenCV and Anaconda Python
39,575,666
<p>How can you import <code>OpenCV</code> to run in <code>Python</code>?</p> <p>I ran it on a windows platform. My main problem i ran into was using Python 3.5 (presuming it was the latest) and the latest version of OpenCV but i didn't know that OpenCV sis not compatible with Python 3.5 so online video tutorials on youtube all failed miserably and i couldnt get past the import stage for almost a full day. </p> <p>Here's what I have tried:</p> <ol> <li><p>Python 3.5 (64bit) &amp; (32bit) with OpenCV</p></li> <li><p>Anaconda 3 (64bit) &amp; (32bit) with OpenCV</p></li> </ol> <p>Using <code>Anaconda Python 2.7 (64bit)</code> with <code>OpenCV</code> ended up working. Turns out <code>OpenCV</code> that I downloaded from the site is for <code>Python 2.7</code>.</p>
-3
2016-09-19T14:29:15Z
39,577,324
<pre><code>conda install -c menpo opencv3=3.1.0 </code></pre> <p>or </p> <pre><code>conda install -c anaconda opencv=2.4.10 </code></pre> <p>It's a bit annoying that you need to know which collection a package is in if it isn't the standard one, but a certain search engine will find it.</p>
0
2016-09-19T15:57:58Z
[ "python", "opencv", "anaconda" ]
Create a structured array in python
39,575,721
<p>I would like to create a dictionary in Python using numpy commands. </p> <p>First I tried to define the structure and then to populate the array according to a number/case selected by the user. When I try to request one of the cases I get the following error (for case 1):</p> <pre><code>cannot copy sequence with size 3 to array axis with dimension 1 </code></pre> <p>How can I fix my code in order to be able to store the data I want in my structure? Regardless of the case I select. </p> <p>Here is my code:</p> <pre><code># defining the structure usgStruct = np.zeros(1,dtype = [("satNr",np.int), ("satAzimuth", np.int), ("satElevation", np.int), ("scenarioEnv", np.str), ("scenarioHead", np.int), ("scenarioLen", np.int), ("speed", np.int)]) def case1(): usgStruct["satNr"] = 3 usgStruct["satAzimuth"] = [180, 200, 235] usgStruct["satElevation"] = [35, 25, 25] usgStruct["scenarioEnv"] = ["S", "S", "S", "U", "U"] usgStruct["scenarioHead"] = [45, 280, 45, 120, 200] usgStruct["scenarioLen"] = [2000, 500, 3000, 2000, 500] usgStruct["speed"] = [15, 15, 15, 10, 10] return usgStruct def case2(): usgStruct["satNr"] = 2 usgStruct["satAzimuth"] = [180, 225] usgStruct["satElevation"] = [45, 30] usgStruct["scenarioEnv"] = ["U", "U", "O", "O", "S", "S", "S"] usgStruct["scenarioHead"] = [30, 65, 65, 80, 80, 60, 130] usgStruct["scenarioLen"] = [300, 800, 2000, 1000, 700, 700, 300] usgStruct["speed"] = [10, 10, 15, 15, 15, 15, 15] return usgStruct def case3(): usgStruct["satNr"] = 2 usgStruct["satAzimuth"] = [180, 225] usgStruct["satElevation"] = [35, 30] usgStruct["scenarioEnv"] = ['C', 'C', 'C', 'C', 'O'] usgStruct["scenarioHead"] = [90, 45, 120, 70, 45] usgStruct["scenarioLen"] = [1500, 500, 300, 2000, 3000] usgStruct["speed"] = [15, 15, 15, 15, 20] return usgStruct # set up a dictionary of actions scenarioGenerator = { "1": case1, "2": case2, "3": case3} runscenGen = raw_input("Please enter a number from 1 to 7\n ") scenarioGenerator.get(runscenGen,case3)() # specify a default: case3 print usgStruct </code></pre>
0
2016-09-19T14:32:08Z
39,578,177
<p>print the initial <code>usgStruct</code> array:</p> <pre><code>In [329]: usgStruct Out[329]: array([(0, 0, 0, '', 0, 0, 0)], dtype=[('satNr', '&lt;i4'), ('satAzimuth', '&lt;i4'), ('satElevation', '&lt;i4'), ('scenarioEnv', '&lt;U'), ('scenarioHead', '&lt;i4'), ('scenarioLen', '&lt;i4'), ('speed', '&lt;i4')]) </code></pre> <p>Its data is 6 numbers and one character ('U' on my py3). That's all it can hold. It can't hold lists.</p> <p>Even if you defined it to be size (3,) </p> <pre><code>In [331]: usgStruct Out[331]: array([(0, 0, 0, '', 0, 0, 0), (0, 0, 0, '', 0, 0, 0), (0, 0, 0, '', 0, 0, 0)], dtype=[('satNr', '&lt;i4'), ('satAzimuth', '&lt;i4'), ('satElevation', '&lt;i4'), ('scenarioEnv', '&lt;U'), ('scenarioHead', '&lt;i4'), ('scenarioLen', '&lt;i4'), ('speed', '&lt;i4')]) </code></pre> <p>individual records are still this 7 element tuple. </p> <p>You <code>case</code> data is entirely different. Each case looks like a dictionary with list values. Changing <code>case1</code> to produce and return a dictionary:</p> <pre><code>In [334]: def case1(): ...: usgStruct={} ...: usgStruct["satNr"] = 3 ...: usgStruct["satAzimuth"] = [180, 200, 235] ...: usgStruct["satElevation"] = [35, 25, 25] ...: usgStruct["scenarioEnv"] = ["S", "S", "S", "U", "U"] ...: usgStruct["scenarioHead"] = [45, 280, 45, 120, 200] ...: usgStruct["scenarioLen"] = [2000, 500, 3000, 2000, 500] ...: usgStruct["speed"] = [15, 15, 15, 10, 10] ...: return usgStruct ...: In [335]: case1() Out[335]: {'satAzimuth': [180, 200, 235], 'satElevation': [35, 25, 25], 'satNr': 3, 'scenarioEnv': ['S', 'S', 'S', 'U', 'U'], 'scenarioHead': [45, 280, 45, 120, 200], 'scenarioLen': [2000, 500, 3000, 2000, 500], 'speed': [15, 15, 15, 10, 10]} </code></pre> <p>Now <code>scenarioGenerator</code> would be a dictionary of dictionaries.</p>
0
2016-09-19T16:47:57Z
[ "python", "arrays", "numpy", "structure" ]
OpenCV Select Ink On Scanned Page
39,575,744
<p>Say we have a picture of a page with text on it. However, a threshold is not sufficient. On an example image, the page has a large shadow that covers half the image, such that at some points, there is paper that is darker than the lightest ink.</p> <p>What's the best way to get a mask of the ink on the page? I'm thinking it's something like edge detection, although I wouldn't then know how to select the inner part of the ink.</p> <p>I'm doing this in Python, so answers in that would be most helpful!</p>
0
2016-09-19T14:33:25Z
39,577,889
<p>There are two things you can try:</p> <ul> <li>Convert the image to HSV and check the hue component</li> <li>Use algorithms to remove shadow from the image and then process it. An example of such methods can be found in <a href="http://www.serc.iisc.ernet.in/~venky/SE263/papers/Salvador_CVIU2004.pdf" rel="nofollow">this paper</a> </li> </ul>
0
2016-09-19T16:30:57Z
[ "python", "opencv", "mask", "threshold" ]
How do I get opencv for python3 with anaconda3?
39,575,800
<p>So, initially, I just had python 3.5 from the anaconda installation and all was fine. Then I was following a tutorial that suggested the use of enthought canopy, which used python 2.7. After this I did a 'pip install opencv-python' and that installed the 2.7 version of the library. I should note, I am on Ubunutu 16 desktop for development.</p> <p>I cannot seem to find a way for installing opencv and possibly cv2 for python3, the version installed in my user directory. Maybe I should remove enthought canopy. But I will still need to find the correct versions of opencv, cv2 for anaconda3. Thanks in advance for any help, Bruce</p>
0
2016-09-19T14:35:56Z
39,601,323
<p>Once you have anaconda installed, try the following (as seen in <a href="https://rivercitylabs.org/up-and-running-with-opencv3-and-python-3-anaconda-edition/" rel="nofollow">this tutorial</a>):</p> <pre><code>conda create -n opencv numpy scipy scikit-learn matplotlib python=3 source activate opencv conda install -c https://conda.binstar.org/menpo opencv3 </code></pre> <p>it will first create a virtual environment called <code>opencv</code> with the packages <code>opencv</code>, <code>numpy</code>, <code>scipy</code>, <code>scikit-learn</code> and <code>matplotlib</code>.</p> <p>It works for me on Mac. </p>
1
2016-09-20T18:30:15Z
[ "python", "python-3.x", "opencv" ]
Does the entire scope path need to match for variable reuse in TensorFlow?
39,575,892
<p>Is the variable <code>Test</code> shared in these two scenarios?</p> <pre class="lang-py prettyprint-override"><code>with tf.name_scope("ns1"): with tf.variable_scope("vs1"): var = tf.get_variable("Test", [1,2,3]) with tf.name_scope("ns2"): with tf.variable_scope("vs1", reuse=True): var = tf.get_variable("Test", [1,2,3]) </code></pre> <p>and </p> <pre class="lang-py prettyprint-override"><code>with tf.name_scope("ns1"): with tf.variable_scope("vs1"): var = tf.get_variable("Test", [1,2,3]) with tf.variable_scope("vs1", reuse=True): var = tf.get_variable("Test", [1,2,3]) </code></pre>
0
2016-09-19T14:40:19Z
39,578,326
<p>Yes, the variable is shared. In general, name_scope does <em>not</em> influence variable names, only variable_scope does (but yes, the whole prefix of variable_scopes must match). I think that it is reasonable to try and not use name_scope at all, it can be confusing when mixed with variable_scope. Also note that you set reuse=True -- if the variable were not shared, you'd get an error. That's why it's there, so you can be sure it's shared.</p>
2
2016-09-19T16:56:21Z
[ "python", "tensorflow" ]
password field is showing password in plain text
39,575,910
<p>I have used django allauth for user registration and login system. I could show the form by simplifying the lines of code using for loop. I got the right field type(TextInput and PasswordInput) for each field too. However the password field which has PasswordInput shows password in plain text. How can i resolve this?</p> <p><strong>my signup page(account/signup.html)</strong></p> <pre><code>&lt;form class="signup" id="signup_form" method="post" action="{% url 'account_signup' %}"&gt; {% csrf_token %} {% for field in form.visible_fields %} &lt;div class="form-group"&gt; &lt;label for="{{ field.id_for_label}}"&gt;{{field.label}}&lt;/label&gt; {{ field.errors.0 }} &lt;input type="{{field|input_type}}" name="{{ field.name }}" class="form-control" id="{{ field.id_for_label}}"&gt; &lt;/div&gt; {% endfor %} &lt;/form&gt; </code></pre> <p><strong>filters.py</strong></p> <pre><code>from django import template register = template.Library() @register.filter('input_type') def input_type(field): print('field',field.field.widget.__class__) return field.field.widget.__class__.__name__ </code></pre> <p>How can i show password in dot? </p>
1
2016-09-19T14:41:10Z
39,576,523
<p>You can add class by overriding <code>__init__</code> method in form class</p> <pre><code>def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['password'].widget.attrs['class'] = 'form-control' </code></pre>
2
2016-09-19T15:10:51Z
[ "python", "django", "python-3.x", "django-allauth" ]
password field is showing password in plain text
39,575,910
<p>I have used django allauth for user registration and login system. I could show the form by simplifying the lines of code using for loop. I got the right field type(TextInput and PasswordInput) for each field too. However the password field which has PasswordInput shows password in plain text. How can i resolve this?</p> <p><strong>my signup page(account/signup.html)</strong></p> <pre><code>&lt;form class="signup" id="signup_form" method="post" action="{% url 'account_signup' %}"&gt; {% csrf_token %} {% for field in form.visible_fields %} &lt;div class="form-group"&gt; &lt;label for="{{ field.id_for_label}}"&gt;{{field.label}}&lt;/label&gt; {{ field.errors.0 }} &lt;input type="{{field|input_type}}" name="{{ field.name }}" class="form-control" id="{{ field.id_for_label}}"&gt; &lt;/div&gt; {% endfor %} &lt;/form&gt; </code></pre> <p><strong>filters.py</strong></p> <pre><code>from django import template register = template.Library() @register.filter('input_type') def input_type(field): print('field',field.field.widget.__class__) return field.field.widget.__class__.__name__ </code></pre> <p>How can i show password in dot? </p>
1
2016-09-19T14:41:10Z
39,576,622
<p>The password is showing in plain text because you're assigning <code>&lt;input&gt;</code> types incorrectly, therefore not hiding passwords as <code>&lt;input type="password"&gt;</code> does.</p> <p>From reading the comments, it looks like you're trying to add custom bootstrap classes to the form fields. As <a href="http://stackoverflow.com/users/6663134/anna-vracheva">Anna Vracheva</a> was saying, you can add the class to the fields using the form's <code>__init__</code> method.</p> <pre><code>from django import forms class CustomForm("""Whichever class you're inheriting from, probably ModelForm"""): # If you're using AllAuth, this is already defined on the form password = fields.CharField(widget=forms.PasswordInput) # Or whatever field, for that matter def __init__(self, *args, **kwargs): super(CustomFieldForm, self).__init__(*args, **kwargs) # Option 1 - Assign to only password self.fields['password'].widget['class'] = 'form-control' # Option 2 - Loop over all fields and assign to all for field in self.fields: field.widget['class'] = 'form-control' </code></pre> <p>Then, instead of manually rendering HTML, let Django's Templates do that:</p> <pre class="lang-html prettyprint-override"><code>&lt;!-- This --&gt; {{ field }} &lt;-- --&gt; &lt;!-- Instead of this --&gt; &lt;input type="{{field|input_type}}" name="{{ field.name }}" class="form-control" id="{{ field.id_for_label}}"&gt; </code></pre> <p>That should fix any field rendering problems you're having while preserving your form classes.</p>
1
2016-09-19T15:15:46Z
[ "python", "django", "python-3.x", "django-allauth" ]
password field is showing password in plain text
39,575,910
<p>I have used django allauth for user registration and login system. I could show the form by simplifying the lines of code using for loop. I got the right field type(TextInput and PasswordInput) for each field too. However the password field which has PasswordInput shows password in plain text. How can i resolve this?</p> <p><strong>my signup page(account/signup.html)</strong></p> <pre><code>&lt;form class="signup" id="signup_form" method="post" action="{% url 'account_signup' %}"&gt; {% csrf_token %} {% for field in form.visible_fields %} &lt;div class="form-group"&gt; &lt;label for="{{ field.id_for_label}}"&gt;{{field.label}}&lt;/label&gt; {{ field.errors.0 }} &lt;input type="{{field|input_type}}" name="{{ field.name }}" class="form-control" id="{{ field.id_for_label}}"&gt; &lt;/div&gt; {% endfor %} &lt;/form&gt; </code></pre> <p><strong>filters.py</strong></p> <pre><code>from django import template register = template.Library() @register.filter('input_type') def input_type(field): print('field',field.field.widget.__class__) return field.field.widget.__class__.__name__ </code></pre> <p>How can i show password in dot? </p>
1
2016-09-19T14:41:10Z
39,576,808
<p>You can also try this:</p> <pre><code>&lt;input class="form-control" type="{{ field.field.widget.input_type }}" name="{{ field.name }}" id="id_{{ field.name }}" &gt; </code></pre>
0
2016-09-19T15:28:07Z
[ "python", "django", "python-3.x", "django-allauth" ]
Calling mapPartitions on a class method in python
39,575,917
<p>I'm fairly new to Python and to Spark but let me see if I can explain what I am trying to do.</p> <p>I have a bunch of different types of pages that I want to process. I created a base class for all the common attributes of those pages and then have a page specific class inherit from the base class. The idea being that the spark runner will be able to do the exact thing for all pages by changing just the page type when called.</p> <p>Runner</p> <pre><code>def CreatePage(pageType): if pageType == "Foo": return PageFoo(pageType) elif pageType == "Bar": return PageBar(pageType) def Main(pageType): page = CreatePage(pageType) pageList_rdd = sc.parallelize(page.GetPageList()) return = pageList_rdd.mapPartitions(lambda pageNumber: CreatePage(pageType).ProcessPage(pageNumber)) print Main("Foo") </code></pre> <p>PageBaseClass.py</p> <pre><code>class PageBase(object): def __init__(self, pageType): self.pageType = None self.dbConnection = None def GetDBConnection(self): if self.dbConnection == None: # Set up a db connection so we can share this amongst all nodes. self.dbConnection = DataUtils.MySQL.GetDBConnection() return self.dbConnection def ProcessPage(): raise NotImplementedError() </code></pre> <p>PageFoo.py</p> <pre><code> class PageFoo(PageBase, pageType): def __init__(self, pageType): self.pageType = pageType self.dbConnetion = GetDBConnection() def ProcessPage(): result = self.dbConnection.cursor("SELECT SOMETHING") # other processing </code></pre> <p>There are a lot of other page specific functionality that I am omitting from brevity, but the idea is that I'd like to keep all the logic of how to process that page in the page class. And, be able to share resources like db connection and an s3 bucket.</p> <p>I know that the way that I have it right now, it is creating a new Page object for every item in the rdd. Is there a way to do this so that it is only creating the one object? Is there a better pattern for this? Thanks!</p>
1
2016-09-19T14:41:28Z
39,577,121
<p>A few suggestions:</p> <ul> <li>Don't create connections directly. Use connection pool (since each executor uses separate process setting pool size to one is just fine) and make sure that connections are automatically closed on timeout) instead.</li> <li>Use <a href="http://stackoverflow.com/q/1318406/1560062">Borg pattern</a> to store the pool and adjust your code to use it to retrieve connections.</li> <li>You won't be able to share connections between nodes or even within a single node (see comment about separate processes). The best guarantee you can get is a single connection per partition (or a number of partitions with interpreter reuse).</li> </ul>
0
2016-09-19T15:46:15Z
[ "python", "apache-spark" ]
Get next value from a row that satisfies a condition in pandas
39,575,947
<p>I have a DataFrame that looks something like this:</p> <pre><code> | event_type | object_id ------ | ------ | ------ 0 | A | 1 1 | D | 1 2 | A | 1 3 | D | 1 4 | A | 2 5 | A | 2 6 | D | 2 7 | A | 3 8 | D | 3 9 | A | 3 </code></pre> <p>What I want to do is get the index of the next row where the <code>event_type</code> is A and the <code>object_id</code> is still the same, so as an additional column this would look like this:</p> <pre><code> | event_type | object_id | next_A ------ | ------ | ------ | ------ 0 | A | 1 | 2 1 | D | 1 | 2 2 | A | 1 | NaN 3 | D | 1 | NaN 4 | A | 2 | 5 5 | A | 2 | NaN 6 | D | 2 | NaN 7 | A | 3 | 9 8 | D | 3 | 9 9 | A | 3 | NaN </code></pre> <p>and so on.</p> <p>I want to avoid using <code>.apply()</code> because my DataFrame is quite large, is there a vectorized way to do this?</p> <p>EDIT: for multiple A/D pairs for the same <code>object_id</code>, I'd like it to always use the next index of A, like this:</p> <pre><code> | event_type | object_id | next_A ------ | ------ | ------ | ------ 0 | A | 1 | 2 1 | D | 1 | 2 2 | A | 1 | 4 3 | D | 1 | 4 4 | A | 1 | NaN </code></pre>
0
2016-09-19T14:43:22Z
39,576,338
<p>You can do it with groupby like:</p> <pre><code>def populate_next_a(object_df): object_df['a_index'] = pd.Series(object_df.index, index=object_df.index)[object_df.event_type == 'A'] object_df['a_index'].fillna(method='bfill', inplace=True) object_df['next_A'] = object_df['a_index'].where(object_df.event_type != 'A', object_df['a_index'].shift(-1)) object_df.drop('a_index', axis=1) return object_df result = df.groupby(['object_id']).apply(populate_next_a) print(result) event_type object_id next_A 0 A 1 2.0 1 D 1 2.0 2 A 1 NaN 3 D 1 NaN 4 A 2 5.0 5 A 2 NaN 6 D 2 NaN 7 A 3 9.0 8 D 3 9.0 9 A 3 NaN </code></pre> <p><a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html" rel="nofollow">GroupBy.apply</a> will not have as much overhead as a simple apply.</p> <p>Note you cannot (yet) store integer with NaN: <a href="http://pandas.pydata.org/pandas-docs/stable/gotchas.html#support-for-integer-na" rel="nofollow">http://pandas.pydata.org/pandas-docs/stable/gotchas.html#support-for-integer-na</a> so they end up as float values</p>
2
2016-09-19T15:01:26Z
[ "python", "python-3.x", "pandas" ]
Saving as csv output of applyin a "main" function in python
39,575,972
<p>I've been applying a main function in Python, by saying:</p> <pre><code>def main(): "some code here" if __name__ == '__main__': main() </code></pre> <p>Then I get a result like this:</p> <pre><code>[['This is my car not yours'], ['He answered me sorry'], ['no problem'], ['\nYou are crazy'], ['All cars are the same'], etc...] </code></pre> <p>I Want to save the result in a txt and csv file to manipulate it later preserving the same structure: squared parentheses, words, commas, etc. How can I do that? Thanks in advance.</p>
0
2016-09-19T14:44:34Z
39,576,228
<p>Hope this is what you wanted:</p> <pre><code>def main(): return [['This is my car not yours'], ['He answered me sorry'], ['no problem'], ['\nYou are crazy'], ['All cars are the same']] if __name__ == '__main__': with open('output.txt', 'w') as f: a = ('').join(str(main())) f.write(a) </code></pre>
0
2016-09-19T14:56:44Z
[ "python", "csv" ]
docker-py: how can I check if the build was successful?
39,575,982
<p>I'm trying to build myself a neat pipeline in Python 3. My problem, everything seems to be working nice, Jenkins always gives me a green bubble, but sometimes docker build fails to executed.</p> <p>So <code>client.build</code> doesn't raise an error if the build breaks for some reason:</p> <pre><code>try: self.client.build(path=self.arguments.projectPath, pull=True, rm=False, tag=self.arguments.dockerImageTag) except: print("Error: Docker did not build) raise </code></pre> <p>does not raise an error if the build failed. </p> <p>Can someone please help me finding the right method, how I can be sure my build was done, and if not getting a valid message? I am totally lost.</p> <p>Best regards Mirco</p>
0
2016-09-19T14:45:09Z
39,577,514
<p><code>client.build</code> returns the messages outputted by <code>docker</code> when issuing the <code>docker build</code> command. Your initial mistake is in not capturing the response:</p> <pre><code>response = cl.build(fileobj=f, rm = True, tag='myv/v') </code></pre> <p>and if successful the contents look as they do if executed through the command line:</p> <pre><code>list(response) b'{"stream":" ---\\u003e bb44cb7f2d89\\n"}\r\n', # snipped for brevity b'{"stream":"Successfully built 6bc18019ddb6\\n"}\r\n'] </code></pre> <p>On error cases, for example, using a silly dockerfile:</p> <pre><code># a dockerfile with a type in 'MAINTAINER' f = BytesIO(''' # Shared Volume FROM busybox:buildroot-2014.02 MAINTAIER first last, first.last@yourdomain.com VOLUME /data CMD ["/bin/sh"] '''.encode('utf-8')) </code></pre> <p>The output contained in <code>response</code> looks like:</p> <pre><code>[b'{"stream":"Step 1 : FROM busybox:buildroot-2014.02\\n"}\r\n', b'{"stream":" ---\\u003e 9875fb006e07\\n"}\r\n', b'{"stream":"Step 2 : MAINTAIER \\n"}\r\n', b'{"errorDetail":{"message":"Unknown instruction: MAINTAIER"},"error":"Unknown instruction: MAINTAIER"}\r\n'] </code></pre> <p>As you see, a <code>key</code> of <code>errorDetail</code> is contained containing the error message. </p> <p>So, you can check for that, either with byte string search:</p> <pre><code>class DockerBuildException(BaseException): pass try: responce = self.client.build(path=self.arguments.projectPath, pull=True, rm=False, tag=self.arguments.dockerImageTag) for i in respone: if b'errorDetail' in i: raise DockerBuildException("Build Failed") except DockerBuildException as e: print("Error: " + e.args[0]) raise </code></pre> <p>Or, even better, by transforming each entry to a <code>dict</code> with <code>ast.literal_eval</code> and also using the message supplied to inform the user:</p> <pre><code>from ast import literal_eval try: responce = self.client.build(path=self.arguments.projectPath, pull=True, rm=False, tag=self.arguments.dockerImageTag) for i in respone: if b'errorDetail' in i: d = literal_eval(i.decode('ascii') raise DockerBuildException(d['errorDetail']['message']) except DockerBuildException as e: print("Error: " + e.args[0]) raise </code></pre>
2
2016-09-19T16:07:56Z
[ "python", "python-3.x", "docker", "dockerpy" ]
Django 1.9 using django sessions in two page forms
39,576,016
<p>How can I use Django sessions to have a user be able to start a form on one page, and move to the next page and have them complete the form? </p> <p>I have looked into pagination and wizard forms, but I don't get them at all. </p> <p>When I have one page with a small portion of a model I'm using - in forms - and another page with the rest of the model - <code>forms.py</code> with the rest of the model info - I can use the first form perfectly. </p> <p>But when I move to the next page, I get an error saying <code>(1048, "Column 'user_id' cannot be null")</code>. </p> <p>My best guess is to use Django sessions to fix this issue. I don't want the user to have to put in their username and password a second time to get this to work. Any ideas?</p> <p>my models/forms.py:</p> <pre><code>class Contact(models.Model): user = models.OneToOneField(User) subject = models.CharField(max_length=100, blank=True) sender = models.EmailField(max_length=100, blank=True) message = models.CharField(max_length=100, blank=True) def __str__(self): return self.user.username class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput()) class Meta: model = Contact fields = ('username', 'password', 'email') class ContactForm1(forms.Form): class Meta: model = Contact fields = ('subject', 'sender') class ContactForm2(forms.Form): message = forms.CharField(widget=forms.Textarea) class Meta: model = Contact fields = ('message',) </code></pre> <p>views:</p> <pre><code>def contact(request): registered = False if request.method =='POST': user = UserForm(request.POST) contact = ContactForm1(request.POST) if user.is_valid() and contact.is_valid(): user = user.save() user.set_password(user.password) user.save() contact = contact.save(commit=False) contact.user = user registered = True return render(request, 'mysite/contact.html', {'user': user, 'contact': contact, 'registered': registered}) def contact_second(request): if request.method =='POST': contact = ContactForm2(request.POST) if contact.is_valid(): contact = contact.save(commit=False) contact.save() return render(request, 'mysite/contact_two.html', {'contact': contact} </code></pre>
2
2016-09-19T14:46:28Z
39,578,988
<p>I think it's a good idea to use sessions to store the forms because you don't want on each page to store the user input into the database because what if s/he change mind in the 3rd page and s/he wants to discard the registration or whatever it is?</p> <p>I think is better to store the forms in session until you get in the last page, you ensure that everything is valid and then save the data in the database.</p> <p>So let's say that the bellow code is in one of the view that will serve the first form/page. You retrieve the data from the POST request and you check if the given data are valid using the <code>form.is_valid()</code>, you then store the <code>form.cleaned_data</code> (which contains the user's validated data) to a session variable. </p> <pre><code>form = CustomForm(request.POST) ... if form.is_valid(): request.session['form_data_page_1'] = form.cleaned_data </code></pre> <p>Note here that you may need to add code to redirect the user to the next page <code>if form.is_valid()</code> is true, something like this:</p> <pre><code>if form.is_valid(): request.session['form_data_page_1'] = form.cleaned_data return HttpResponseRedirect(reverse('url-name-of-second-page')) </code></pre> <p>Then in any other view let's say in the view that is going to serve the second page you can retreive the from data from the first page like this:</p> <pre><code>first_page_data = request.session['form_data_page_1'] </code></pre> <p>And you can do whatever you want with them as if it was after you executed the <code>form.is_valid()</code> in the first view.</p>
1
2016-09-19T17:36:12Z
[ "python", "django", "django-forms", "django-sessions", "django-1.9" ]
Excluding a set of indices from an array whilst keeping its original order
39,576,019
<p>I have an HDF5 dataset which I read as a numpy array: </p> <pre><code>my_file = h5py.File(h5filename, 'r') file_image = my_file['/image'] </code></pre> <p>and a list of indices called <code>in</code>. </p> <p>I want to split the <code>image</code> dataset into two separate <code>np.array</code>s: one containing images corresponding to the <code>in</code> indices, and the other containing images whose indices are not in <code>in</code>. The order of images is very important - I want to split the dataset such that the original order of the images is preserved within each subset. How can I achieve this? </p> <p>I tried the following:</p> <pre><code>labeled_image_dataset = list(file_image[in]) </code></pre> <p>However, h5py gave me an error saying that the indices must be in increasing order. I can't change the order of indices, since I need the images to stay in their original order.</p> <p>My code:</p> <pre><code>my_file = h5py.File(h5filename, 'r') file_image = my_file['/imagePatches'] li = dataframe["label"] temporary_list = file_image # select images whose indices exist in "in" labeled_dataset = list(temporary_list[in]) # select images whose indices don't exist in "in" unlabeled_dataset = np.delete(temporary_list, in, 0) </code></pre>
0
2016-09-19T14:46:32Z
39,578,735
<p>I'm not following why or how you are choosing the indexes, but as the error indicates, when you index an array on the h5 file, then indexes have to be sorted. Remember files are serial storage, so it is easier and faster to read straight through rather than go back and forth. Regardless of where the constraint lies, in <code>h5py</code> or the <code>h5</code> back end, <code>idx</code> has to ordered.</p> <p>But if you load the whold array into memory (or some contiguous chunk), that may require a <code>copy</code>, then you can use an unsorted, or even repetitious, <code>idx</code> list.</p> <p>In other words, <code>h5py</code> arrays can be indexed like <code>numpy</code> arrays, but with some limits.</p> <p><a href="http://docs.h5py.org/en/latest/high/dataset.html#fancy-indexing" rel="nofollow">http://docs.h5py.org/en/latest/high/dataset.html#fancy-indexing</a></p>
1
2016-09-19T17:20:44Z
[ "python", "numpy", "indexing", "h5py" ]
Excluding a set of indices from an array whilst keeping its original order
39,576,019
<p>I have an HDF5 dataset which I read as a numpy array: </p> <pre><code>my_file = h5py.File(h5filename, 'r') file_image = my_file['/image'] </code></pre> <p>and a list of indices called <code>in</code>. </p> <p>I want to split the <code>image</code> dataset into two separate <code>np.array</code>s: one containing images corresponding to the <code>in</code> indices, and the other containing images whose indices are not in <code>in</code>. The order of images is very important - I want to split the dataset such that the original order of the images is preserved within each subset. How can I achieve this? </p> <p>I tried the following:</p> <pre><code>labeled_image_dataset = list(file_image[in]) </code></pre> <p>However, h5py gave me an error saying that the indices must be in increasing order. I can't change the order of indices, since I need the images to stay in their original order.</p> <p>My code:</p> <pre><code>my_file = h5py.File(h5filename, 'r') file_image = my_file['/imagePatches'] li = dataframe["label"] temporary_list = file_image # select images whose indices exist in "in" labeled_dataset = list(temporary_list[in]) # select images whose indices don't exist in "in" unlabeled_dataset = np.delete(temporary_list, in, 0) </code></pre>
0
2016-09-19T14:46:32Z
39,579,003
<p>Using <code>in</code> as a variable name is not a good idea, since <code>in</code> is a Python keyword (e.g. see the list comprehensions below). For clarity I've renamed it as <code>idx</code></p> <p>One straightforward solution would be to simply iterate over your set of indices in a standard Python <code>for</code> loop or list comprehension:</p> <pre><code>labelled_dataset = [file_image[ii] for ii in idx] unlabelled_dataset = [file_image[ii] for ii in range(len(file_image)) if ii not in idx] </code></pre> <p>It might be faster to use vectorized indexing, e.g. if you have a very large number of small image patches to load. In that case you could use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.argsort.html" rel="nofollow"><code>np.argsort</code></a> to find the set of indices that will sort <code>idx</code> in ascending order, then index into <code>file_image</code> with the sorted indices. Afterwards you can "undo" the effect of sorting <code>idx</code> by indexing into the resulting array with the same set of indices that were used to sort <code>idx</code>.</p> <p>Here's a simplified example to illustrate:</p> <pre><code>target = np.array(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']) idx = np.array([5, 1, 9, 0, 3]) # find a set of indices that will sort `idx` in ascending order order = np.argsort(idx) ascending_idx = idx[order] # use the sorted indices to index into the target array ascending_result = target[ascending_idx] # "undo" the effect of sorting `idx` by indexing the result with `order` result = ascending_result[order] print(np.all(result == target[idx])) # True </code></pre>
1
2016-09-19T17:37:16Z
[ "python", "numpy", "indexing", "h5py" ]
Install multiple .service files with dh_systemd packaging
39,576,120
<p>I'm currently packaging a python app with dh_virtualenv, to deploy it on Ubuntu 16.04, daemonized with systemd.</p> <p>I use the dh_systemd plugin to automatically install the file my_app.service will install the .deb package, but I'd like to run another process in a different service that schedules tasks for my app, using celery. </p> <p>So, I created another service file, my_app.scheduler.service, but I don't know how to declare this file/app/service in my debian packaging rules, so that while installing the whole package, both services file will be copied and thus will be launched independently.</p> <p>Do you have any idea to do that ? </p> <p>Here are my debian conf files for dpkg-buildpackage command : </p> <p><strong>control</strong></p> <pre><code>Source: my_app Section: python Priority: extra Maintainer: me Build-Depends: debhelper (&gt;= 9), python, dh-virtualenv (&gt;= 0.6), dh-systemd (&gt;= 1.5), adduser Standards-Version: 3.9.5 Package: my_app Architecture: any Pre-Depends: dpkg (&gt;= 1.16.1), python2.7, ${misc:Pre-Depends} Depends: ${python:Depends}, ${misc:Depends} Description: blabla </code></pre> <p><strong>rules</strong></p> <pre><code>#!/usr/bin/make -f %: dh $@ --with python-virtualenv --with=systemd </code></pre> <p><strong>install</strong></p> <pre><code>etc/my_app.config /etc/ </code></pre> <p><strong>dirs</strong></p> <pre><code>/var/lib/my_app /var/log/my_app </code></pre> <p>And of course the .service files :</p> <p><strong>my_app.service</strong></p> <pre><code>[Unit] Description=APP [Service] Type=simple User=app_user EnvironmentFile=/etc/my_app.config ExecStart=/usr/share/python/my_app/bin/gunicorn -w 10 -b 0.0.0.0:6000 -t 600 my_app_python_package:app [Install] WantedBy=multi-user.target </code></pre> <p><strong>my_app.scheduler.service</strong></p> <pre><code>[Unit] Description=APP Scheduler [Service] Type=simple User=app_user EnvironmentFile=/etc/my_app.config ExecStart=/usr/share/python/my_app/bin/celery worker -A my_app_python_package.tasks [Install] WantedBy=multi-user.targetroot </code></pre> <p>Thanks in advance :)</p> <p><strong>EDIT / SOLUTION</strong></p> <p>I finally found an answer. For those who might have the same problem, using <a href="http://unix.stackexchange.com/questions/306234/is-it-possible-to-install-two-services-for-one-package-using-dh-installinit-how">dh_installinit</a> solves the case :)</p>
0
2016-09-19T14:51:16Z
39,795,036
<p>Found the solution <a href="http://%20http://unix.stackexchange.com/questions/306234/is-it-possible-to-install-two-services-for-one-package-using-dh-installinit-how" rel="nofollow">here</a> : </p> <pre><code>override_dh_installinit: dh_installinit --name=service1 dh_installinit --name=service2 </code></pre>
0
2016-09-30T15:27:59Z
[ "python", "virtualenv", "packaging", "systemd", "debhelper" ]
What is the relationship between a python virtual environment and specific system libraries?
39,576,125
<p>We have an application which does some of its work in Python in a python virtual environment setup using virtualenv.</p> <p>We've hit a problem where the version of a system library does not match the version installed in the virtual environment. That is we have <code>NetCDF4</code> installed into the virtual environment and and previously had <code>libnetcdf.so.7</code> installed through <code>yum</code>. The python package appears to be dependent on having <code>libnetcdf.so.7</code> available.</p> <p>Due to a system update <code>libnetcdf.so.7</code> no longer exists and has been replaced by <code>libnetcdf.so.11</code>.</p> <p>So the question is this: Does setting up the virtual environment detect the system library version or is there some other mechanism? Also do we need to re-build the environment to fix this or is there another option?</p>
0
2016-09-19T14:51:24Z
39,576,379
<p>When you use <code>virtualenv</code> to create a virtual environment you have the option of whether or not to include the standard site packages as part of the environment. Since this is now default behaviour (though it can be asserted by using <code>--no-site-packages</code> in the command line) it's possible that you are using an older version of virtualenv that doesn't insist on this.</p> <p>In that case you should be able to re-create the environment fairly easily. First of all capture the currently-installed packages in the existing environment with the commmand</p> <pre><code>pip freeze &gt; /tmp/requirements.txt </code></pre> <p>Then delete the virtual environment, and re-create it with the following commands:</p> <pre><code>virtualenv --no-site-packages envname source envname/bin/activate pip install -r /tmp/requirements.txt </code></pre> <p>However none of this addresses the tricky issue of not having the required support libraries installed. You might try creating a symbolic link to the new library from the old library's position - it may be that<code>NetCDF4</code> can work with multiple versions of <code>libnetCDF</code> and is simply badly configured to use a specific version. If not then solving thsi issue might turn out to be long and painful.</p>
0
2016-09-19T15:03:45Z
[ "python", "linux", "virtualenv" ]
Selecting values from a series in pandas
39,576,156
<p>I have a dataset D with Columns from [A - Z] in total 26 columns. I have done some test and got to know which are the useful columns to me in a series S.</p> <pre><code>D #Dataset with columns from A - Z S B 0.78 C 1.04 H 2.38 </code></pre> <p>S has the columns and a value associated with it, So I now know their importance and would like to keep only those Columns in the Dataset eg(<code>B</code>, <code>C</code>, <code>D</code>) How can I do it? </p>
1
2016-09-19T14:52:53Z
39,576,217
<p>IIUC you can use:</p> <pre><code>cols = ['B','C','D'] df = df[cols] </code></pre> <p>Or if column names are in <code>Series</code> as values:</p> <pre><code>S = pd.Series(['B','C','D']) df = df[S] </code></pre> <p>Sample:</p> <pre><code>df = pd.DataFrame({'A':[1,2,3], 'B':[4,5,6], 'C':[7,8,9], 'D':[1,3,5], 'E':[5,3,6], 'F':[7,4,3]}) print (df) A B C D E F 0 1 4 7 1 5 7 1 2 5 8 3 3 4 2 3 6 9 5 6 3 S = pd.Series(['B','C','D']) print (S) 0 B 1 C 2 D dtype: object print (df[S]) B C D 0 4 7 1 1 5 8 3 2 6 9 5 </code></pre> <p>Or <code>index</code> values:</p> <pre><code>S = pd.Series([1,2,3], index=['B','C','D']) print (S) B 1 C 2 D 3 dtype: int64 print (df[S.index]) B C D 0 4 7 1 1 5 8 3 2 6 9 5 </code></pre>
2
2016-09-19T14:56:06Z
[ "python", "pandas", "select", "dataframe", "multiple-columns" ]
Save base64 image in django file field
39,576,174
<p>I have following input</p> <pre><code>"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAA7YAAAISCAIAAAB3YsSDAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAA5JxJREFUeNrsnQl4FEX6xqcJJEAS7ivhBkMAQTSJ4h0QEQ+I90rAc1cOL3QBXXV1AV1dVwmrsCqQ9VwJ6HoC7oon0T8iEkABwRC5IeE+kkAIkPT/nfmSmprunskk5CDw/p55hu7qOr76api8........" </code></pre> <p>I want to save this file in file field. What can I do?</p> <p><strong>models.py</strong></p> <pre><code>class SomeModel(models.Model): file = models.FileField(upload_to=get_upload_report) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) </code></pre> <p>I'm trying to do this</p> <pre><code>def get_file(data): from django.core.files import File return File(data) </code></pre> <p>and save return file to model instance</p> <pre><code>somemodel.file = get_file(image_base64_data) </code></pre> <p>but it's gives a following error</p> <pre><code>AttributeError at /someurl/ 'File' object has no attribute 'decode' </code></pre>
3
2016-09-19T14:53:31Z
39,577,190
<p>This question looks like it should help: <a href="http://stackoverflow.com/questions/7514964/django-how-to-create-a-file-and-save-it-to-a-models-filefield">Django - how to create a file and save it to a model&#39;s FileField?</a> </p> <p>You should be able to decode the base64 string and supply that as the <code>content</code> argument to <a href="https://docs.djangoproject.com/en/1.9/ref/models/fields/#django.db.models.fields.files.FieldFile.save" rel="nofollow"><code>FieldFile.save</code></a>: </p>
1
2016-09-19T15:50:31Z
[ "python", "django", "image", "filefield" ]
Save base64 image in django file field
39,576,174
<p>I have following input</p> <pre><code>"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAA7YAAAISCAIAAAB3YsSDAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAA5JxJREFUeNrsnQl4FEX6xqcJJEAS7ivhBkMAQTSJ4h0QEQ+I90rAc1cOL3QBXXV1AV1dVwmrsCqQ9VwJ6HoC7oon0T8iEkABwRC5IeE+kkAIkPT/nfmSmprunskk5CDw/p55hu7qOr76api8........" </code></pre> <p>I want to save this file in file field. What can I do?</p> <p><strong>models.py</strong></p> <pre><code>class SomeModel(models.Model): file = models.FileField(upload_to=get_upload_report) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) </code></pre> <p>I'm trying to do this</p> <pre><code>def get_file(data): from django.core.files import File return File(data) </code></pre> <p>and save return file to model instance</p> <pre><code>somemodel.file = get_file(image_base64_data) </code></pre> <p>but it's gives a following error</p> <pre><code>AttributeError at /someurl/ 'File' object has no attribute 'decode' </code></pre>
3
2016-09-19T14:53:31Z
39,587,386
<pre><code>import base64 from django.core.files.base import ContentFile format, imgstr = data.split(';base64,') ext = format.split('/')[-1] data = ContentFile(base64.b64decode(imgstr), name='temp.' + ext) # You can save this as file istance. </code></pre> <p>Use this code snippet to decode the base64 string.</p>
1
2016-09-20T06:45:14Z
[ "python", "django", "image", "filefield" ]
printing UTF-8 in Python 3 using Sublime Text 3
39,576,308
<p>I have this Python3 code to attempt to read and print from a utf-8 encoded file:</p> <pre><code>f = open('mybook.txt', encoding='utf-8') for line in f: print(line) </code></pre> <p>When I build using Sublime Text 3 I get the following error:</p> <pre><code>UnicodeEncodeError: 'ascii' codec can't encode character '\u2019' in position 18: ordinal not in range(128) </code></pre> <p>However, it works file when I just execute my code in the terminal with python3.</p> <p>My build configuration is</p> <pre><code>{ "cmd": ["/usr/local/bin/python3", "$file"] , "selector": "source.python" , "file_regex": "file \"(...*?)\", line ([0-9]+)" } </code></pre> <p>If I change it to:</p> <pre><code>f = open('mybook.txt', encoding='utf-8') for line in f: print(line.encode('utf-8')) </code></pre> <p>Then it does print the utf-8 encoded byte string (I think that's what's happening).</p> <pre><code>b'Hello\n' b'\xc2\xab\xe2\x80\xa2\n' b'Goodbye' </code></pre> <p>But I also don't know how to go from this to printing the unicode characters on the screen...</p> <p>Also, if I try changing this env variable as per <a href="http://stackoverflow.com/questions/34302902/a-python-program-fails-to-execute-in-sublime-text-3-but-success-in-bash">A python program fails to execute in sublime text 3, but success in bash</a> it still doesn't fix it.</p>
2
2016-09-19T15:00:26Z
39,583,630
<p>The answer was actually in the question linked in your question - <code>PYTHONIOENCODING</code> needs to be set to <code>"utf-8"</code>. However, since OS X is silly and doesn't pick up on environment variables set in Terminal or via <code>.bashrc</code> or similar files, this won't work in the way indicated in the answer to the other question. Instead, you need to pass that environment variable to Sublime. </p> <p>Luckily, ST3 build systems (I don't know about ST2) have the <a href="http://docs.sublimetext.info/en/latest/reference/build_systems/exec.html#exec-command-arguments" rel="nofollow"><code>"env"</code></a> option. This is a dictionary of keys and values passed to <code>exec.py</code>, which is responsible for running build systems without the <code>"target"</code> option set. As discussed in our comments above, I indicated that your sample program worked fine on a UTF-8-encoded text file containing non-ASCII characters when run with ST3 (Build 3122) on Linux, but not with the same version run on OS X. All that was necessary to get it to run was to change the build system to enclude this line:</p> <pre><code>"env": {"PYTHONIOENCODING": "utf8"}, </code></pre> <p>I saved the build system, hit <kbd>⌘</kbd><kbd>B</kbd>, and the program ran fine.</p> <p>BTW, if you'd like to read <code>exec.py</code>, or <code>Packages/Python/Python.sublime-build</code>, or any other file packed up in a <code>.sublime-package</code> archive, install <a href="https://packagecontrol.io/packages/PackageResourceViewer" rel="nofollow"><code>PackageResourceViewer</code></a> via Package Control. Use the "Open Resource" option in the Command Palette to pick individual files, or "Extract Package" (both are preceded by "PackageResourceViewer:", or <strong><em><code>prv</code></em></strong> using fuzzy search) to extract an entire package to your <code>Packages</code> folder, which is accessed by selecting <strong><code>Sublime Text → Preferences → Browse Packages…</code></strong> (just <strong><code>Preferences → Browse Packages…</code></strong> on other operating systems). It is located on your hard drive in the following location:</p> <ul> <li>Linux: <code>~/.config/sublime-text-3/Packages</code></li> <li>OS X: <code>~/Library/Application Support/Sublime Text 3/Packages</code></li> <li>Windows Regular Install: <code>C:\Users\<b><i>YourUserName</i></b>\AppData\Roaming\Sublime Text 3\Packages</code></li> <li>Windows Portable Install: <code><b><i>InstallationFolder</i></b>\Sublime Text 3\Data\Packages</code></li> </ul> <p>Once files are saved to your <code>Packages</code> folder (if you just view them via the "Open Resource" option and close without changing or saving them, they won't be), they will override the identically-named file contained within the <code>.sublime-package</code> archive. So, for instance, if you want to edit the default <code>Python.sublime-build</code> file in the <code>Python</code> package, your changes will be saved as <code>Packages/Python/Python.sublime-build</code>, and when you choose the <code>Python</code> build system from the menu, it will only use your version.</p>
3
2016-09-19T23:39:17Z
[ "python", "python-3.x", "utf-8", "sublimetext3", "sublimetext" ]
Validating a users input
39,576,320
<p>I'm fairly new to Python and I'm using a while True loop. Inside that loop I have </p> <pre><code>Sentence= input("please enter a sentence").lower().split() </code></pre> <p>However I want to create validation so an error message appears when the user inputs a number instead of a letter. I was researching and saw the use of .isalpha. Would anyone where this would go in the whie true loop to create and error message for inputting numbers? </p>
0
2016-09-19T15:00:51Z
39,576,406
<pre><code>sentence = input("please enter a sentence").lower().split() for word in sentence: if not word.isalpha(): print("The word %s is not alphabetic." % word) </code></pre>
1
2016-09-19T15:04:54Z
[ "python" ]
Validating a users input
39,576,320
<p>I'm fairly new to Python and I'm using a while True loop. Inside that loop I have </p> <pre><code>Sentence= input("please enter a sentence").lower().split() </code></pre> <p>However I want to create validation so an error message appears when the user inputs a number instead of a letter. I was researching and saw the use of .isalpha. Would anyone where this would go in the whie true loop to create and error message for inputting numbers? </p>
0
2016-09-19T15:00:51Z
39,576,840
<p>Something like this?</p> <pre><code>sentence = input("please enter a sentence: ").lower().split() while False in [word.isalpha() for word in sentence]: sentence = input("Do not use digits. Enter again: ").lower().split() </code></pre>
0
2016-09-19T15:29:21Z
[ "python" ]
rename the pandas Series
39,576,340
<p>I have some wire thing when renaming the pandas Series by the datetime.date</p> <pre><code>import pandas as pd a = pd.Series([1, 2, 3, 4], name='t') </code></pre> <p>I got <code>a</code> is:</p> <pre><code>0 1 1 2 2 3 3 4 Name: t, dtype: int64 </code></pre> <p>Then, I have:</p> <pre><code>ts = pd.Series([pd.Timestamp('2016-05-16'), pd.Timestamp('2016-05-17'), pd.Timestamp('2016-05-18'), pd.Timestamp('2016-05-19')], name='time') </code></pre> <p>with <code>ts</code> as:</p> <pre><code>0 2016-05-16 1 2016-05-17 2 2016-05-18 3 2016-05-19 Name: time, dtype: datetime64[ns] </code></pre> <p>Now, if I do:</p> <pre><code>ts_date = ts.apply(lambda x: x.date()) dates = ts_date.unique() </code></pre> <p>I got <code>dates</code> as:</p> <pre><code>array([datetime.date(2016, 5, 16), datetime.date(2016, 5, 17), datetime.date(2016, 5, 18), datetime.date(2016, 5, 19)], dtype=object) </code></pre> <hr> <p>I have two approaches. The wired thing is, if I do the following renaming (approach 1):</p> <pre><code>for one_date in dates: a.rename(one_date) print one_date, a.name </code></pre> <p>I got:</p> <pre><code>2016-05-16 t 2016-05-17 t 2016-05-18 t 2016-05-19 t </code></pre> <p>But if I do it like this (approach 2):</p> <pre><code>for one_date in dates: a = pd.Series(a, name=one_date) print one_date, a.name 2016-05-16 2016-05-16 2016-05-17 2016-05-17 2016-05-18 2016-05-18 2016-05-19 2016-05-19 </code></pre> <hr> <p>My question is: why the method <code>rename</code> does not work (in approach 1)?</p>
0
2016-09-19T15:01:28Z
39,576,580
<p>Because <code>rename</code> does not change the object unless you set the <code>inplace</code> argument as <code>True</code>, as seen in the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.rename.html" rel="nofollow">docs</a>.</p> <p>Notice that the <code>copy</code> argument can be used so you don't have to create a new series passing the old series as argument, like in your second example.</p>
2
2016-09-19T15:13:54Z
[ "python", "python-2.7", "pandas" ]
IMDb dataset find number of 10 ratings for a movie
39,576,473
<p>I'm trying to sort IMDb movies based on the number of (rated 10) votes they got.<br> Unfortunately, I can't seem to find that piece of information in their public dataset on their FTP servers (It's not in the ratings file).<br> Example of the information I'm trying to extract: <a href="http://www.imdb.com/title/tt0111161/ratings?ref_=tt_ov_rt" rel="nofollow">The Shawshank Redemption</a> has 955769 votes of a 10 rating.<br> Is there any other way this could be done? Can IMDbPy help?</p>
-1
2016-09-19T15:08:15Z
39,577,684
<p>You should be able to get the rating information by using the IMDbPY package.</p> <p>Follow the steps as shown in the link <a href="http://imdbpy.sourceforge.net/support.html#documentation" rel="nofollow">IMDbPY</a>.</p> <p>You can actually do it in two ways,</p> <ol> <li>Use the <strong>api</strong> provided which is a straight forward method (works in cases where the number of api calls are less).</li> <li>But in case you have multiple api calls, you need to create a <strong>local IMDb database</strong>. You can do it by running the python script provided by IMDbPY which automatically creates tables for you in the database (follow the steps as mentioned <a href="http://imdbpy.sourceforge.net/docs/README.sqldb.txt" rel="nofollow">here</a>).</li> </ol> <p>Other way of doing it (not recommended) is by creating a web scraper which is a painful process. Can build one with the help of <em>requests</em>, <em>beautifulsoup</em> packages in python.</p>
0
2016-09-19T16:18:49Z
[ "python", "database", "web-scraping" ]
Why Python and java does not need any header file whereas C and C++ needs them
39,576,478
<p>I am a complete newbie to python transiting from C++. </p> <p>While learning C++, I was explained that header files tells about the working of the function or define them to the compiler so that it understands what means what i.e., iostream contains the definition of cin (nd much more) so that the compiler knows that it is a keyword and understands its function.</p> <p>However, python and java do not need header files. So basically how does the compiler understands the actual meaning/function of 'print' or 'input' in python????? </p>
-1
2016-09-19T15:08:32Z
39,576,524
<p>Java and Python have <code>import</code> which is similar to include.</p> <p>Some inbuilt functions are built in and hence does not require any imports.</p>
-1
2016-09-19T15:10:54Z
[ "python" ]
Why Python and java does not need any header file whereas C and C++ needs them
39,576,478
<p>I am a complete newbie to python transiting from C++. </p> <p>While learning C++, I was explained that header files tells about the working of the function or define them to the compiler so that it understands what means what i.e., iostream contains the definition of cin (nd much more) so that the compiler knows that it is a keyword and understands its function.</p> <p>However, python and java do not need header files. So basically how does the compiler understands the actual meaning/function of 'print' or 'input' in python????? </p>
-1
2016-09-19T15:08:32Z
39,576,570
<p>Header files in C/C++ are a "copy paste" mechanism. The included header file is literally written into the file while preprocessing (copy pasting the source code together). After that is done, the compiler transaltes the source code. The linker then connects the function calls. That is somewhat outdated and error prone -> can be really frustrating as well when sth doesnt work as expected.</p> <p>Newer languages have module systems, which are nicer (import simply does it).</p>
2
2016-09-19T15:13:32Z
[ "python" ]
Why Python and java does not need any header file whereas C and C++ needs them
39,576,478
<p>I am a complete newbie to python transiting from C++. </p> <p>While learning C++, I was explained that header files tells about the working of the function or define them to the compiler so that it understands what means what i.e., iostream contains the definition of cin (nd much more) so that the compiler knows that it is a keyword and understands its function.</p> <p>However, python and java do not need header files. So basically how does the compiler understands the actual meaning/function of 'print' or 'input' in python????? </p>
-1
2016-09-19T15:08:32Z
39,576,943
<p>In Java and Python we use a similar keyword called <strong>import</strong> to add a package and use the methods in it. But in advanced languages like Java and Python few packages are imported by default. <strong>e.g.</strong> in Java <strong>java.lang.*</strong> is imported by default.</p>
0
2016-09-19T15:35:00Z
[ "python" ]
Python Parsing XML - if element == "value" do x
39,576,517
<p>sorry if title isn't that clear, I'm currently parsing a xml file that has lots of nested tags, for example it goes:</p> <pre><code>&lt;Artifacts&gt; &lt;Artifact name="1"&gt; &lt;Fragments&gt; &lt;hits&gt; &lt;hit sequence="1"&gt; &lt;Fragment name="1"&gt;Data&lt;/Fragment&gt; &lt;Fragment name="2"&gt;Data&lt;/Fragment&gt; &lt;/hit&gt; &lt;/hits&gt; &lt;/Fragments&gt; &lt;/Artifact&gt; &lt;Artifact name="2"&gt; </code></pre> <p>(Making layout a bit clearer sorry) and so on. The pain I'm currently having is to be able to get only the data we need. From the example above we require everything under Artifact name=1, and to pull out the fragment name of "1" along with Data. The outcome aimed for would be something like:</p> <p>Artifact = "1", Fragment Name = "1", Fragment Data = "Data".</p> <p>At present I just can't seem to get to grips with it, I've done similar with PHP without issues but this is required to be done in python really. </p> <p>So bit long winded sorry, but does anyone have any ideas how to specify to only grab the data from the artifacts named 1,3,5 for example and ignore everything else? All I can seem to do is grab it from everything in the file (which slows it down and then requires further processing)</p> <p>thanks.</p>
-1
2016-09-19T15:10:35Z
39,578,089
<p>With minidom:</p> <pre><code>from xml.dom import minidom xmlstr = ''' &lt;Artifacts&gt; &lt;Artifact name="1"&gt; &lt;Fragments&gt; &lt;Fragment name="1"&gt;Data&lt;/Fragment&gt; &lt;/Fragments&gt; &lt;/Artifact&gt; &lt;Artifact name="2"&gt; &lt;/Artifact&gt; &lt;/Artifacts&gt; ''' def with_children(tag): if tag.localName: # if not, it's text node print tag.localName, if tag.hasAttributes(): for item in tag.attributes.items(): print "%s=%s" % item, for child in tag.childNodes: with_children(child) else: s = tag.nodeValue.strip() print "data=%s" % s if s else "", xml = minidom.parseString(xmlstr) tags = xml.getElementsByTagName('Artifact') tag = [t for t in tags if t.attributes['name'].value == '1'][0] with_children(tag) </code></pre>
1
2016-09-19T16:42:23Z
[ "python", "xml" ]
Python Parsing XML - if element == "value" do x
39,576,517
<p>sorry if title isn't that clear, I'm currently parsing a xml file that has lots of nested tags, for example it goes:</p> <pre><code>&lt;Artifacts&gt; &lt;Artifact name="1"&gt; &lt;Fragments&gt; &lt;hits&gt; &lt;hit sequence="1"&gt; &lt;Fragment name="1"&gt;Data&lt;/Fragment&gt; &lt;Fragment name="2"&gt;Data&lt;/Fragment&gt; &lt;/hit&gt; &lt;/hits&gt; &lt;/Fragments&gt; &lt;/Artifact&gt; &lt;Artifact name="2"&gt; </code></pre> <p>(Making layout a bit clearer sorry) and so on. The pain I'm currently having is to be able to get only the data we need. From the example above we require everything under Artifact name=1, and to pull out the fragment name of "1" along with Data. The outcome aimed for would be something like:</p> <p>Artifact = "1", Fragment Name = "1", Fragment Data = "Data".</p> <p>At present I just can't seem to get to grips with it, I've done similar with PHP without issues but this is required to be done in python really. </p> <p>So bit long winded sorry, but does anyone have any ideas how to specify to only grab the data from the artifacts named 1,3,5 for example and ignore everything else? All I can seem to do is grab it from everything in the file (which slows it down and then requires further processing)</p> <p>thanks.</p>
-1
2016-09-19T15:10:35Z
39,580,500
<p>Here is a simple example using <code>lxml</code>:</p> <pre><code>from lxml import etree content = '''\ &lt;Artifacts&gt; &lt;Artifact name="1"&gt; &lt;Fragments&gt; &lt;Fragment name="1"&gt;Data&lt;/Fragment&gt; &lt;/Fragments&gt; &lt;/Artifact&gt; &lt;Artifact name="2"&gt; &lt;Fragments&gt; &lt;Fragment name="2"&gt;Data2&lt;/Fragment&gt; &lt;/Fragments&gt; &lt;/Artifact&gt; &lt;Artifact name="3"&gt; &lt;Fragments&gt; &lt;Fragment name="3"&gt;Data3&lt;/Fragment&gt; &lt;/Fragments&gt; &lt;/Artifact&gt; &lt;/Artifacts&gt; ''' tree = etree.XML(content) elts = tree.xpath("/Artifacts/Artifact[@name = '1' or @name = '3' or @name = '5']") for elt in elts: etree.dump(elt) </code></pre> <p>You'll get:</p> <pre><code>&lt;Artifact name="1"&gt; &lt;Fragments&gt; &lt;Fragment name="1"&gt;Data&lt;/Fragment&gt; &lt;/Fragments&gt; &lt;/Artifact&gt; &lt;Artifact name="3"&gt; &lt;Fragments&gt; &lt;Fragment name="3"&gt;Data3&lt;/Fragment&gt; &lt;/Fragments&gt; &lt;/Artifact&gt; </code></pre> <p>If you want to extract each Fragment:</p> <pre><code>artifacts = tree.xpath("/Artifacts/Artifact[@name = '1' or @name = '3' or @name = '5']") fmt = 'Artifact = "{art_name}",' \ 'Fragment Name = "{frag_name}",' \ 'Fragment Data = "{data}".' for artifact in artifacts: for fragments in artifact.iter("Fragments"): for fragment in fragments.iter("Fragment"): print(fmt.format(art_name=artifact.get("name"), frag_name=fragment.get("name"), data=fragment.text)) </code></pre> <p>You'll get:</p> <pre><code>Artifact = "1", Fragment Name = "1", Fragment Data = "Data". Artifact = "3", Fragment Name = "3", Fragment Data = "Data3". </code></pre>
1
2016-09-19T19:16:26Z
[ "python", "xml" ]
using SSL with nginx in a django app
39,576,535
<p>This is my yo_nginx.conf file:</p> <pre><code>upstream django { server unix:///home/ubuntu/test/yo/yo.sock; # for a file socket, check if the path is correct } # Redirect all non-encrypted to encrypted server { server_name 52.89.220.11; listen 80; return 301 https://52.89.220.11$request_uri; } # configuration of the server server { # the port your site will be served on listen 443 default ssl; # the domain name it will serve for server_name 52.89.220.11; # substitute your machine's IP address or FQDN charset utf-8; ssl on; ssl_certificate /etc/ssl/certs/api.ajayvision.com.chain.crt; ssl_certificate_key /etc/ssl/private/api.ajayvision.com.key; # max upload size client_max_body_size 75M; # adjust to taste # Finally, send all non-media requests to the Django server. location / { proxy_set_header X-Forwarded-Proto https; include /home/ubuntu/test/yo/uwsgi_params; uwsgi_param UWSGI_SCHEME https; uwsgi_pass_header X_FORWARDED_PROTO; uwsgi_pass django; } } </code></pre> <p>All I want to do is implement SSL on my django app but when I open the domain, it opens up in normal HTTP port. Also when I open the domain using https, it says check your connection. Am I missing something in my conf file? Also, I don't have a proxy set up.</p>
2
2016-09-19T15:11:24Z
39,576,627
<p>Below is most of the config we use. It ensures the appropriate headers are set. One word of caution, our <code>ssl_ciphers</code> list is probably not ideal as we need to support some clients on older devices.</p> <pre><code>server { listen 443; server_name uidev01; ssl on; ssl_certificate /etc/nginx/ssl/server.crt; ssl_certificate_key /etc/nginx/ssl/server.key; ssl_ciphers "ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA:ECDHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA256:DHE-RSA-AES128-SHA256:DHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA:ECDHE-RSA-DES-CBC3-SHA:EDH-RSA-DES-CBC3-SHA:AES256-GCM-SHA384:AES128-GCM-SHA256:AES256-SHA256:AES128-SHA256:AES256-SHA:AES128-SHA:DES-CBC3-SHA:HIGH:!aNULL:!eNULL:!EXPORT:!DES:!MD5:!PSK:!RC4"; ssl_protocols TLSv1 TLSv1.1 TLSv1.2; ssl_prefer_server_ciphers on; ssl_stapling on; ssl_stapling_verify on; error_page 501 /static/ErrorPages/501.html; error_page 502 /static/ErrorPages/502.html; error_page 503 /static/ErrorPages/503.html; error_page 504 /static/ErrorPages/504.html; server_tokens off; ssl_session_cache shared:SSL:50m; ssl_session_timeout 5m; add_header Strict-Transport-Security "max-age=172800; includeSubdomains;"; add_header X-Frame-Options DENY; add_header X-Content-Type-Options nosniff; add_header Cache-Control "no-cache, no-store"; add_header Pragma no-cache; expires 0s; location / { proxy_pass http://localhost:8000; proxy_pass_header Server; proxy_set_header X-Real-IP $remote_addr; add_header X-Frame-Options sameorigin; add_header X-Content-Type-Options nosniff; add_header Cache-Control "no-cache, no-store"; add_header Pragma no-cache; add_header Strict-Transport-Security "max-age=172800; includeSubdomains;"; expires 0s; proxy_read_timeout 1800; proxy_connect_timeout 1800; client_max_body_size 200M; } } </code></pre> <p>As to redirecting from HTTP to HTTPS, we use this...</p> <pre><code>server { listen 80; return 301 https://$host$request_uri; server_tokens off; } </code></pre>
2
2016-09-19T15:16:03Z
[ "python", "django", "ssl", "nginx" ]
using SSL with nginx in a django app
39,576,535
<p>This is my yo_nginx.conf file:</p> <pre><code>upstream django { server unix:///home/ubuntu/test/yo/yo.sock; # for a file socket, check if the path is correct } # Redirect all non-encrypted to encrypted server { server_name 52.89.220.11; listen 80; return 301 https://52.89.220.11$request_uri; } # configuration of the server server { # the port your site will be served on listen 443 default ssl; # the domain name it will serve for server_name 52.89.220.11; # substitute your machine's IP address or FQDN charset utf-8; ssl on; ssl_certificate /etc/ssl/certs/api.ajayvision.com.chain.crt; ssl_certificate_key /etc/ssl/private/api.ajayvision.com.key; # max upload size client_max_body_size 75M; # adjust to taste # Finally, send all non-media requests to the Django server. location / { proxy_set_header X-Forwarded-Proto https; include /home/ubuntu/test/yo/uwsgi_params; uwsgi_param UWSGI_SCHEME https; uwsgi_pass_header X_FORWARDED_PROTO; uwsgi_pass django; } } </code></pre> <p>All I want to do is implement SSL on my django app but when I open the domain, it opens up in normal HTTP port. Also when I open the domain using https, it says check your connection. Am I missing something in my conf file? Also, I don't have a proxy set up.</p>
2
2016-09-19T15:11:24Z
39,578,138
<p>For redirection from HTTP to HTTPS use:</p> <pre><code>server { listen 80; server_name yourdomain.com; return 301 https://$server_name$request_uri; } </code></pre> <p>But if your website is not working with HTTPS, it means you have invalid certificate. The reasons should be not-signed certificate or your browser should require chained certificate etc. </p>
0
2016-09-19T16:45:19Z
[ "python", "django", "ssl", "nginx" ]
using SSL with nginx in a django app
39,576,535
<p>This is my yo_nginx.conf file:</p> <pre><code>upstream django { server unix:///home/ubuntu/test/yo/yo.sock; # for a file socket, check if the path is correct } # Redirect all non-encrypted to encrypted server { server_name 52.89.220.11; listen 80; return 301 https://52.89.220.11$request_uri; } # configuration of the server server { # the port your site will be served on listen 443 default ssl; # the domain name it will serve for server_name 52.89.220.11; # substitute your machine's IP address or FQDN charset utf-8; ssl on; ssl_certificate /etc/ssl/certs/api.ajayvision.com.chain.crt; ssl_certificate_key /etc/ssl/private/api.ajayvision.com.key; # max upload size client_max_body_size 75M; # adjust to taste # Finally, send all non-media requests to the Django server. location / { proxy_set_header X-Forwarded-Proto https; include /home/ubuntu/test/yo/uwsgi_params; uwsgi_param UWSGI_SCHEME https; uwsgi_pass_header X_FORWARDED_PROTO; uwsgi_pass django; } } </code></pre> <p>All I want to do is implement SSL on my django app but when I open the domain, it opens up in normal HTTP port. Also when I open the domain using https, it says check your connection. Am I missing something in my conf file? Also, I don't have a proxy set up.</p>
2
2016-09-19T15:11:24Z
39,579,594
<p>All I had to do was add default_server and also change the permission of my socket in the uwsgi/sites/sample.ini file from 664 to 666.</p> <pre><code>server { listen 443 default_server ssl; ... } </code></pre>
1
2016-09-19T18:12:57Z
[ "python", "django", "ssl", "nginx" ]
Python Selenium Webdriver.Firefox() hangs at 'about:blank&utm_content=firstrun'
39,576,552
<p>Am using Selenium version 2.53.6 and have tried it with Firefox 44,45,46 and 47...</p> <p>Whenever I run the line </p> <blockquote> <p>driver = webdriver.Firefox()</p> </blockquote> <p>Firefox initializes but hangs at 'about:blank&amp;utm_content=firstrun' and I cannot type additional code on the command line.</p> <p>Been researching on how to solve this and so far the only available solution that did not work for me was to downgrade FF (but I have tried numerous older versions already) (am using Python 2.7 and have also tried and failed using 3.5)</p>
0
2016-09-19T15:12:18Z
39,577,507
<p>I would recommend using chrome. <a href="http://chromedriver.storage.googleapis.com/2.9/chromedriver_win32.zip" rel="nofollow">http://chromedriver.storage.googleapis.com/2.9/chromedriver_win32.zip</a> Download that and extract it to your <code>python27/scripts</code> folder located in the root directory in the <code>C:\\ Drive</code> and then run this script.</p> <pre><code>from selenium import webdriver driver = webdriver.Chrome() driver.get('http://www.google.com') </code></pre> <p>And It should connect you to google.com Hope I helped. :)</p>
0
2016-09-19T16:07:25Z
[ "python", "selenium", "firefox" ]
Implementing CNN with tensorflow
39,576,631
<p>I'm new in convolutional neural networks and in Tensorflow and I need to implement a conv layer with further parameters:</p> <p>Conv. layer1: filter=11, channel=64, stride=4, Relu.</p> <p>The API is following:</p> <pre><code>tf.nn.conv2d(input, filter, strides, padding, use_cudnn_on_gpu=None, data_format=None, name=None) </code></pre> <p>I understand, what is stride and that it should be [1, 4, 4, 1] in my case. But I do not understand, how should I pass a filter parameter and padding. Could someone help with it?</p>
1
2016-09-19T15:16:20Z
39,577,003
<p>At first, you need to create a filter variable:</p> <pre><code>W = tf.truncated_normal(shape = [11, 11, 3, 64], stddev = 0.1) </code></pre> <p>First two fields of shape parameter stand for filter size, third for the number of input channels (I guess your images have 3 channels) and fourth for the number of output channels.</p> <p>Now output of convolutional layer could be computed as follows:</p> <p><code>conv1 = tf.nn.conv2d(input, W, strides = [1, 4, 4, 1], padding = 'SAME')</code>, where <code>padding = 'SAME'</code> stands for zero padding and therefore size of the image remains the same, input should have size [batch, size1, size2, 3].</p> <p>ReLU application is pretty straightforward:</p> <pre><code>conv1 = tf.nn.relu(conv1) </code></pre>
1
2016-09-19T15:38:16Z
[ "python", "neural-network", "tensorflow", "convolution", "conv-neural-network" ]
python lxml - simply get/check class of HTML element
39,576,673
<p>I use <code>tree.xpath</code> to iterate over all interesting HTML elements but I need to be able to tell whether the current element is part of a certain CSS class or not.</p> <pre><code>from lxml import html mypage = """ &lt;div class="otherclass exampleclass"&gt;some&lt;/div&gt; &lt;div class="otherclass"&gt;things&lt;/div&gt; &lt;div class="exampleclass"&gt;are&lt;/div&gt; &lt;div class="otherclass"&gt;better&lt;/div&gt; &lt;div&gt;left&lt;/div&gt;""" tree = html.fromstring(mypage) for item in tree.xpath( "//div" ): print("testing") #if "exampleclass" in item.getListOfClasses(): # print("foo") #else: # print("bar") </code></pre> <p>The overall structure should remain the same.</p> <p>What is a fast way to check whether or not the current <code>div</code> has the <code>exampleclass</code> class or not?</p> <p>In above example, <code>item</code> is of <a href="http://lxml.de/api/lxml.html.HtmlElement-class.html" rel="nofollow"><code>lxml.html.HtmlElement</code></a> class, which has the property <a href="http://lxml.de/api/lxml.html.HtmlMixin-class.html#classes" rel="nofollow"><code>classes</code></a> but I don't understand what this means:</p> <blockquote> <p><strong>classes</strong><br> A set-like wrapper around the 'class' attribute.</p> <p><strong>Get Method:</strong><br> <code>unreachable.classes(self)</code> - A set-like wrapper around the 'class' attribute.</p> <p><strong>Set Method:</strong><br> <code>unreachable.classes(self, classes)</code></p> </blockquote> <p>It returns a <a href="http://lxml.de/api/lxml.html.Classes-class.html" rel="nofollow"><code>lxml.html.Classes</code></a> object, which has a <code>__iter__</code> method and it turns out <code>iter()</code> works. So I construct this code:</p> <pre><code>for item in tree.xpath( "//div" ) match = False for classname in iter(item.classes): if classname == "exampleclass": match = True if match: print("foo") else: print("bar") </code></pre> <p>But I'm hoping there is a more elegant method.</p> <p>I tried searching for similar questions but all I found were various "how do I get all elements of 'classname'", however I need all <code>div</code>s in the loop, I just want to treat some of them differently.</p>
1
2016-09-19T15:18:32Z
39,576,674
<p>You can elegantly use the <a href="https://docs.python.org/3/reference/expressions.html#in" rel="nofollow">membership test operator <code>in</code></a>:</p> <pre><code>for item in tree.xpath( "//div" ): if "exampleclass" in iter(item.classes): print("foo") </code></pre> <blockquote> <p>For user-defined classes which do not define <code>__contains__()</code> but do define <code>__iter__()</code>, <code>x in y</code> is true if some value <code>z</code> with <code>x == z</code> is produced while iterating over <code>y</code>.</p> </blockquote>
0
2016-09-19T15:18:32Z
[ "python", "class", "python-3.x", "lxml" ]
python lxml - simply get/check class of HTML element
39,576,673
<p>I use <code>tree.xpath</code> to iterate over all interesting HTML elements but I need to be able to tell whether the current element is part of a certain CSS class or not.</p> <pre><code>from lxml import html mypage = """ &lt;div class="otherclass exampleclass"&gt;some&lt;/div&gt; &lt;div class="otherclass"&gt;things&lt;/div&gt; &lt;div class="exampleclass"&gt;are&lt;/div&gt; &lt;div class="otherclass"&gt;better&lt;/div&gt; &lt;div&gt;left&lt;/div&gt;""" tree = html.fromstring(mypage) for item in tree.xpath( "//div" ): print("testing") #if "exampleclass" in item.getListOfClasses(): # print("foo") #else: # print("bar") </code></pre> <p>The overall structure should remain the same.</p> <p>What is a fast way to check whether or not the current <code>div</code> has the <code>exampleclass</code> class or not?</p> <p>In above example, <code>item</code> is of <a href="http://lxml.de/api/lxml.html.HtmlElement-class.html" rel="nofollow"><code>lxml.html.HtmlElement</code></a> class, which has the property <a href="http://lxml.de/api/lxml.html.HtmlMixin-class.html#classes" rel="nofollow"><code>classes</code></a> but I don't understand what this means:</p> <blockquote> <p><strong>classes</strong><br> A set-like wrapper around the 'class' attribute.</p> <p><strong>Get Method:</strong><br> <code>unreachable.classes(self)</code> - A set-like wrapper around the 'class' attribute.</p> <p><strong>Set Method:</strong><br> <code>unreachable.classes(self, classes)</code></p> </blockquote> <p>It returns a <a href="http://lxml.de/api/lxml.html.Classes-class.html" rel="nofollow"><code>lxml.html.Classes</code></a> object, which has a <code>__iter__</code> method and it turns out <code>iter()</code> works. So I construct this code:</p> <pre><code>for item in tree.xpath( "//div" ) match = False for classname in iter(item.classes): if classname == "exampleclass": match = True if match: print("foo") else: print("bar") </code></pre> <p>But I'm hoping there is a more elegant method.</p> <p>I tried searching for similar questions but all I found were various "how do I get all elements of 'classname'", however I need all <code>div</code>s in the loop, I just want to treat some of them differently.</p>
1
2016-09-19T15:18:32Z
39,580,476
<p>There is no need for <em>iter</em>, <code>if "exampleclass" in item.classes:</code> does the exact same thing, only more efficiently. </p> <pre><code>from lxml import html mypage = """ &lt;div class="otherclass exampleclass"&gt;some&lt;/div&gt; &lt;div class="otherclass"&gt;things&lt;/div&gt; &lt;div class="exampleclass"&gt;are&lt;/div&gt; &lt;div class="otherclass"&gt;better&lt;/div&gt; &lt;div&gt;left&lt;/div&gt;""" tree = html.fromstring(mypage) for item in tree.xpath("//div"): if "exampleclass" in item.classes: print("foo") </code></pre> <p>The difference is calling <em>iter</em> on a set makes the lookup linear so definitely not an efficient way to search a set, not much difference here but in some cases there would be a monumental diffrence:</p> <pre><code>In [1]: st = set(range(1000000)) In [2]: timeit 100000 in st 10000000 loops, best of 3: 51.4 ns per loop In [3]: timeit 100000 in iter(st) 100 loops, best of 3: 1.82 ms per loop </code></pre> <p>You can also use <a href="https://pythonhosted.org/cssselect/" rel="nofollow">css selectors</a> using lxml:</p> <pre><code>for item in tree.cssselect("div.exampleclass"): print("foo") </code></pre> <p>Depending on the case, you may also be able to use contains:</p> <pre><code>for item in tree.xpath("//div[contains(@class, 'exampleclass')]"): print("foo") </code></pre>
1
2016-09-19T19:13:51Z
[ "python", "class", "python-3.x", "lxml" ]
Python recv multicast returns one byte
39,576,696
<p>recv is not working as expected. I am sending 10 bytes (verified with wireshark) and recv is only getting the first byte and discarding the rest (until the next sendto). Is this a multicast thing? I'm pretty sure I've done this same thing with unicast UDP and had no issues.</p> <p>Here is my example code:</p> <pre><code>import struct, socket, multiprocessing, time MCAST_PORT = 62950 MCAST_GRP = '239.0.0.13' def _Rx(self, RXsock, Queue): print "Receiver started" while True: # State machine goes here to parse header and recv (&lt;msglen&gt;) bytes. print "Waiting Rx char...", RXsock char = RXsock.recv(1) # Blocks here after first byte ("1") ??? print "Rx", hex(ord(char)) TXsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) TXsock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2) RXsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) RXsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) RXsock.bind((MCAST_GRP, MCAST_PORT)) mreq = struct.pack("4sl", socket.inet_aton(MCAST_GRP), socket.INADDR_ANY) RXsock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq) RxQueue = multiprocessing.Queue() receiver = multiprocessing.Process(target=_Rx, args=(None, RXsock, RxQueue)) receiver.daemon = True receiver.start() TXsock.sendto("09123456789", (MCAST_GRP, MCAST_PORT)) time.sleep(3) </code></pre>
1
2016-09-19T15:19:38Z
39,579,879
<p>You are only getting one byte because you set your buffer size to one.</p> <p>From the <a href="https://docs.python.org/2/library/socket.html#socket.socket.recv" rel="nofollow">documentation for <code>socket.recv</code></a>:</p> <blockquote> <p>The maximum amount of data to be received at once is specified by bufsize.</p> </blockquote> <p>Try passing <code>1024</code> or <code>4096</code> to <code>recv</code>.</p> <p>From the <a href="https://linux.die.net/man/2/recv" rel="nofollow">man page for <code>recv</code></a>:</p> <blockquote> <p>If a message is too long to fit in the supplied buffer, excess bytes may be discarded depending on the type of socket the message is received from.</p> </blockquote> <p>Your comment says that you are trying to parse the header one byte at a time. You can always parse the header after you finish receiving the datagram.</p> <p>If you really need to do a partial read of the buffer, try passing the <code>socket.MSG_PEEK</code> flag to <code>recv</code>:</p> <blockquote> <p>MSG_PEEK</p> <p>This flag causes the receive operation to return data from the beginning of the receive queue without removing that data from the queue. Thus, a subsequent receive call will return the same data.</p> </blockquote> <p>However, you still won't be able to read one byte at a time.</p>
1
2016-09-19T18:33:00Z
[ "python", "blocking", "multicast", "recv" ]
Getting data from Google Maps python object
39,576,737
<p>I've gathered some data from Google Maps API but I'm stuck on getting out the LAT/LNG.</p> <p>Creating object:</p> <pre><code>loc = self.google_maps.geocode(location) </code></pre> <p>I cannot traverse down this object:</p> <pre><code>pprint(loc) </code></pre> <p><a href="http://i.stack.imgur.com/J7CVI.png" rel="nofollow"><img src="http://i.stack.imgur.com/J7CVI.png" alt="enter image description here"></a></p> <p>I've tried:</p> <pre><code>loc.address_components loc['address_components'] loc-&gt;address_components loc.geometry loc['geometry'] </code></pre> <p>etc which all fail. This feels like such a simple question but I don't know they all fail to work</p>
0
2016-09-19T15:22:45Z
39,576,765
<p>You should try:</p> <pre><code>loc[0]['address_components'] # ^ index the list </code></pre> <p>That's because your dict is contained in a list.</p> <p>The same applies to other dictionaries that deeply nested:</p> <pre><code>loc[0]['address_components'][0]['long_name'] # or loc[0]['address_components'][1]['long_name'] for second nested dict </code></pre>
3
2016-09-19T15:24:25Z
[ "python" ]
Assign value to a slice of a numpy array
39,576,757
<p>I want to get slices from a numpy array and assign them to a larger array. The slices should be 64 long and should be taken out evenly from the source array. I tried the following:</p> <pre><code>r = np.arange(0,magnitude.shape[0],step) magnitudes[counter:counter+len(r),ch] = magnitude[r:r+64] </code></pre> <p>I get the following error when I tried the above code:</p> <pre><code>TypeError: only integer arrays with one element can be converted to an index </code></pre> <p>What is the most pythonic way to achieve the slicing?</p>
-1
2016-09-19T15:24:01Z
39,578,337
<p><code>magnitude[r:r+64]</code> where <code>r</code> is an array is wrong. The variables in the slice must be scalars, <code>magnitude[3:67]</code>, not <code>magnitude[[1,2,3]:[5,6,7]]</code>.</p> <p>If you want to collect multiple slices you have to do something like</p> <pre><code>In [345]: x=np.arange(10) In [346]: [x[i:i+3] for i in range(4)] Out[346]: [array([0, 1, 2]), array([1, 2, 3]), array([2, 3, 4]), array([3, 4, 5])] In [347]: np.array([x[i:i+3] for i in range(4)]) Out[347]: array([[0, 1, 2], [1, 2, 3], [2, 3, 4], [3, 4, 5]]) </code></pre> <p>Other SO questions have explored variations on this, trying to find the fastest, but it's hard to get around some sort loop or list comprehension.</p> <p>I'd suggest working with this answer, and come back with a new question, and a small working example, if you think you need more speed.</p>
2
2016-09-19T16:57:28Z
[ "python", "arrays", "numpy", "indexing" ]
Transform to normal Data Frame which has row as list. Split rows to column
39,576,800
<p>My Data Frame output from reading a complex json looks like below.</p> <p>Where individual row is a list within a single column.</p> <p>Below is the sample Data Frame(<code>df</code>)</p> <pre><code>col [A,1,3,4,Null] [B,4,5,6,Null] [C,7,8,9,Null] </code></pre> <p>I tried to split to individual column using pandas but it didnt work as individual row itself is a list. I want the data frame to look like below.</p> <pre><code>colA,colB,colC,colD,colE A 1 3 4 Null B 4 5 6 Null C 7 8 9 Null </code></pre> <p>I dont need the column name to specified manually it can be auto-generated.</p>
1
2016-09-19T15:27:35Z
39,576,878
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.from_records.html" rel="nofollow"><code>DataFrame.from_records</code></a>, but first need create nested <code>list</code> from values of column <code>col</code>:</p> <pre><code>df = pd.DataFrame({'col':[['A',1,3,4,'Null'],['B',4,5,6,'Null'],['C',7,8,9,'Null']]}) print (df) col 0 [A, 1, 3, 4, Null] 1 [B, 4, 5, 6, Null] 2 [C, 7, 8, 9, Null] print (df.col.values.tolist()) [['A', 1, 3, 4, 'Null'], ['B', 4, 5, 6, 'Null'], ['C', 7, 8, 9, 'Null']] df1 = pd.DataFrame.from_records(df.col.values.tolist(), columns=['colA','colB','colC','colD','colE']) print(df1) colA colB colC colD colE 0 A 1 3 4 Null 1 B 4 5 6 Null 2 C 7 8 9 Null </code></pre> <hr> <p>If dont need specify column names:</p> <pre><code>df1 = pd.DataFrame.from_records(df.col.values.tolist()) print(df1) 0 1 2 3 4 0 A 1 3 4 Null 1 B 4 5 6 Null 2 C 7 8 9 Null </code></pre> <p><strong>Timings</strong>:</p> <pre><code>#len(df) = 4k df = pd.concat([df]*1000).reset_index(drop=True) In [80]: %timeit pd.DataFrame(df['col'].apply(pd.Series).values, columns=['colA','colB','colC','colD','colE']) 1 loop, best of 3: 753 ms per loop In [81]: %timeit pd.DataFrame.from_records(df.col.values.tolist(), columns=['colA','colB','colC','colD','colE']) 100 loops, best of 3: 3.73 ms per loop </code></pre>
1
2016-09-19T15:31:13Z
[ "python", "list", "pandas", "dataframe", "multiple-columns" ]
Transform to normal Data Frame which has row as list. Split rows to column
39,576,800
<p>My Data Frame output from reading a complex json looks like below.</p> <p>Where individual row is a list within a single column.</p> <p>Below is the sample Data Frame(<code>df</code>)</p> <pre><code>col [A,1,3,4,Null] [B,4,5,6,Null] [C,7,8,9,Null] </code></pre> <p>I tried to split to individual column using pandas but it didnt work as individual row itself is a list. I want the data frame to look like below.</p> <pre><code>colA,colB,colC,colD,colE A 1 3 4 Null B 4 5 6 Null C 7 8 9 Null </code></pre> <p>I dont need the column name to specified manually it can be auto-generated.</p>
1
2016-09-19T15:27:35Z
39,576,919
<p>You can construct a df from the result of using <code>apply</code> and <code>pd.Series</code> ctor on each row:</p> <pre><code>In [99]: pd.DataFrame(df['col'].apply(pd.Series).values, columns=['colA','colB','colC','colD','colE']) Out[99]: colA colB colC colD colE 0 A 1 3 4 Null 1 B 4 5 6 Null 2 C 7 8 9 Null </code></pre>
0
2016-09-19T15:33:40Z
[ "python", "list", "pandas", "dataframe", "multiple-columns" ]
Using django-photologue to assign single image to a model
39,576,870
<p>I'm working on my first project in django, and the first part of it is a blog app. I've installed django-photologue which seems very useful for the intended purposes for later apps. Although this app will be used extensively later for posting galleries in other apps, assigning single photo to a model still eludes me. Namely, what I want is to assign a single image to each post, which will be a featured image to show on generated list of posts. I've tried a couple of different way, always resulting in same error.</p> <p>First attempt:</p> <pre><code>class Post(models.Model): ... image = models.ForeignKey(Photo, related_name='posts') ... </code></pre> <p>Migrating worked and the option appeared in post admin. It showed a drop down list of all images in photologue library. I tried to create a test post in admin and it resulted in a ProgrammingError</p> <pre><code>column posts_post.image_id does not exist LINE 1: ..., "posts_post"."created", "posts_post"."updated", "posts_pos... </code></pre> <p>From what I understand, trying to create a relation falls through because it lacks the image_id column to assign the pk (although I'm not 100% sure that's the problem).</p> <p>I experienced this same error when I tried creating categories for posts, which I solved using <code>ManyToManyField</code> so I gave it a try.</p> <p>Second attempt:</p> <pre><code>class Post(models.Model): ... image = models.ManyToManyField(Photo, blank=False, through='ImageToPost') ... class ImageToPost(models.Model): post = models.ForeignKey(Post) image = models.ForeignKey(Photo) </code></pre> <p>After updating the model, <code>makemigrations</code> went through without errors, but doing <code>migrate</code> yields similar error:</p> <pre><code>psycopg2.ProgrammingError: column "image_id" of relation "posts_post" does not exist </code></pre> <p>Again, the programming error from postgree pops up. Right now my knowledge of django is limited, so trying to go through photologue models confuses me even further. Any suggestion on how to properly set up my model or an example of models using Photo to assign a single image from photologue to it?</p> <p>A couple notes:</p> <p>1) The dropdown list from post admin showed all images stored by photologue. This solution is not very productive, as the site will store extensive amount of images, and very few of those will be related to blog posts. Is there a way to filter this list to a single gallery?</p> <p>2) Second solution with <code>ManyToManyField</code> is also redundant. Namely, it mirrors the category function which allows posts to be related to one or more post categories, and allow categories to related to any amount of blog posts. For featured images this is not necessary, each post must be related to a single image (multiple posts can link to a same image), but images don't need to be related to blog posts, which makes <code>ManyToManyField</code> perhaps a wrong one to use, but I'm not sure weather to use <code>OneToOneField</code> or <code>ManyToOneField</code>? Does OneToOne relation prevents multiple posts to link to a same image?</p>
0
2016-09-19T15:30:39Z
39,602,813
<p>As per Andreas' comment: it looks like your database does not reflect your Post model; it looks like either you have migrations that have not been applied to the database (run <code>python manage.py migrate --list</code> to see them), or else you have not yet created migrations for your Post model - <a href="https://docs.djangoproject.com/en/1.10/topics/migrations/" rel="nofollow">refer to the migrations documentation for more information</a>.</p> <p>About your 'couple notes':</p> <p>1) Is the single gallery going to be hard-coded? If yes, then <a href="https://docs.djangoproject.com/en/1.10/ref/contrib/admin/" rel="nofollow">in the admin you can filter down the list of image instances to be displayed in the list</a> - look for <code>formfield_for_foreignkey()</code> on that page.</p> <p>2) A OneToOne field will enforce one post to one image; this may, or may not, be what you want!</p>
1
2016-09-20T19:59:32Z
[ "python", "django", "postgresql", "photo", "photologue" ]
Updating postgres column using python dataframe
39,576,900
<p>I am generating dataframe (<code>df</code>) for different dates and it will have the following variables</p> <pre><code>date value rowId 2016-05-14 2.5 1 2016-05-14 3.0 2 2016-05-14 3.4 5 </code></pre> <p>I have to update a column (<code>value</code>) in postgres table (<code>Table1</code>). This table already contains a column (<code>value</code>) of type decimal in (<code>Table1</code>) along with unique identifier (<code>rowId</code>)</p> <pre><code>for d in range(0,len(df)): QUERY=""" UPDATE "Table1" SET "value"='%s' WHERE "Table1"."rowId"='%s' """ % (df['value'][d], df['rowId'][d]) cur.execute(QUERY) </code></pre> <p>There is no error. However, the above code is not updating the column in Postgres table. Is there any error in the code?</p>
0
2016-09-19T15:32:26Z
39,577,021
<p>Well, closing transaction with commit should help. I'm not sure if you are using <code>psycopg2</code>, or any other library which has a <code>commit()</code> function. If not, then a simple <code>cur.execute('COMMIT')</code> should be enough. This should be run right after the <code>for</code> loop.</p>
0
2016-09-19T15:39:26Z
[ "python", "sql", "postgresql", "dataframe" ]
Is the below function O(n) time and O(1) space, where n = |A|?
39,576,942
<pre><code>def firstMissingPositive(self, A): least = 1024*1024*1024 # worst case n ops for i in A: if i &lt; least and i &gt; 0: least = i if least &gt; 1: return 1 else: # should be O(n) A_set = set(A) # worst case n ops again while True: least += 1 if least not in A_set: return least </code></pre> <p>I only ask because it seemed too simple for the given problem, which most people here may have seen on Leetcode or someplace similar. Is there something I'm not aware of in Python's implementation of set or dict? Lookup should be O(1) and converting a list to a set should be O(n) from what I understand.</p>
0
2016-09-19T15:34:58Z
39,577,059
<p>It's not <code>O(1)</code> space, it's <code>O(n)</code> space, since you need to build the set. </p> <p>As for the time, according to <a href="https://wiki.python.org/moin/TimeComplexity" rel="nofollow">the Python wiki</a>, set containment takes <code>O(n)</code> worst case. So your algorithm is thus <code>O(n^2)</code>. Note this is worst case - the average time for set containment is <code>O(1)</code> and so the average time complexity for your algorithm is indeed <code>O(n)</code>.</p> <p>You can get the worst-case down to <code>O(n log n)</code> by using an ordered set, but then the average-time will be <code>O(n log n)</code> as well.</p>
2
2016-09-19T15:42:12Z
[ "python", "algorithm", "time-complexity" ]
TypeError: __deepcopy__() takes 1 positional argument but 2 were given error?
39,577,016
<p>I'm doing a deepcopy for a list of objects, but I keep getting following error:</p> <pre><code>deepcopy __deepcopy__() takes 1 positional argument but 2 were given </code></pre> <p>and following traceback:</p> <pre class="lang-none prettyprint-override"><code>TypeError Traceback (most recent call last) &lt;ipython-input-4-66b9ee5521c7&gt; in &lt;module&gt;() 2 3 import copy ----&gt; 4 regions_copy = copy.deepcopy(regions) 5 regions[0].A = 15 6 print(regions[0].A) /home/michal/Bin/anaconda/envs/tensorflow/lib/python3.5/copy.py in deepcopy(x, memo, _nil) 153 copier = _deepcopy_dispatch.get(cls) 154 if copier: --&gt; 155 y = copier(x, memo) 156 else: 157 try: /home/michal/Bin/anaconda/envs/tensorflow/lib/python3.5/copy.py in _deepcopy_list(x, memo) 216 memo[id(x)] = y 217 for a in x: --&gt; 218 y.append(deepcopy(a, memo)) 219 return y 220 d[list] = _deepcopy_list /home/michal/Bin/anaconda/envs/tensorflow/lib/python3.5/copy.py in deepcopy(x, memo, _nil) 180 raise Error( 181 "un(deep)copyable object of type %s" % cls) --&gt; 182 y = _reconstruct(x, rv, 1, memo) 183 184 # If is its own copy, don't memoize. /home/michal/Bin/anaconda/envs/tensorflow/lib/python3.5/copy.py in _reconstruct(x, info, deep, memo) 295 if state is not None: 296 if deep: --&gt; 297 state = deepcopy(state, memo) 298 if hasattr(y, '__setstate__'): 299 y.__setstate__(state) /home/michal/Bin/anaconda/envs/tensorflow/lib/python3.5/copy.py in deepcopy(x, memo, _nil) 153 copier = _deepcopy_dispatch.get(cls) 154 if copier: --&gt; 155 y = copier(x, memo) 156 else: 157 try: /home/michal/Bin/anaconda/envs/tensorflow/lib/python3.5/copy.py in _deepcopy_dict(x, memo) 241 memo[id(x)] = y 242 for key, value in x.items(): --&gt; 243 y[deepcopy(key, memo)] = deepcopy(value, memo) 244 return y 245 d[dict] = _deepcopy_dict /home/michal/Bin/anaconda/envs/tensorflow/lib/python3.5/copy.py in deepcopy(x, memo, _nil) 164 copier = getattr(x, "__deepcopy__", None) 165 if copier: --&gt; 166 y = copier(memo) 167 else: 168 reductor = dispatch_table.get(cls) TypeError: __deepcopy__() takes 1 positional argument but 2 were given </code></pre> <p>The problem seems to be also when I copy a single object. Any idea what could be the cause?</p> <p>I suppose it might be in my class implementation, because deepcopying a list like <code>[object(), object(), object()]</code> is fine. Although that would be very strange...</p>
-1
2016-09-19T15:39:02Z
39,657,547
<p>I found the problem was in fact in the definition of the variable <code>regions</code>. It is a list of classes <code>AreaRegion</code>, which contained assignment into class <code>__dict__</code>:</p> <pre><code>from matplotlib.path import Path ... class AreaRegion: def __init__(self): ... self.path = Path(verts, codes, closed=True) ... ... </code></pre> <p>Apparently it didn't like this, so I've moved Path into a getter instead.</p>
0
2016-09-23T09:40:24Z
[ "python" ]
list indices must be integers, not str
39,577,110
<pre><code>class targil4(object): def plus(): x=list(raw_input('enter 4 digit Num ')) print x for i in x: int(x[i]) x[i]+=1 print x plus() </code></pre> <p>this is my code, I try to get input of 4 digits from user, then to add 1 to each digit, and print it back. When I run this code i get the massage:</p> <pre><code>Traceback (most recent call last): ['1', '2', '3', '4'] File "C:/Users/Maymon/PycharmProjects/untitled4/targil4.py", line 1, in &lt;module&gt; class targil4(object): File "C:/Users/Maymon/PycharmProjects/untitled4/targil4.py", line 10, in targil4 plus() File "C:/Users/Maymon/PycharmProjects/untitled4/targil4.py", line 6, plus int(x[i]) TypeError: list indices must be integers, not str Process finished with exit code 1 </code></pre>
2
2016-09-19T15:45:25Z
39,577,181
<p>You can also use <a href="http://www.secnetix.de/olli/Python/list_comprehensions.hawk" rel="nofollow">list comprehension</a> and do</p> <pre><code>y = [int(i) + 1 for i in x] print y </code></pre>
0
2016-09-19T15:49:53Z
[ "python", "string", "list", "integer", "indices" ]
list indices must be integers, not str
39,577,110
<pre><code>class targil4(object): def plus(): x=list(raw_input('enter 4 digit Num ')) print x for i in x: int(x[i]) x[i]+=1 print x plus() </code></pre> <p>this is my code, I try to get input of 4 digits from user, then to add 1 to each digit, and print it back. When I run this code i get the massage:</p> <pre><code>Traceback (most recent call last): ['1', '2', '3', '4'] File "C:/Users/Maymon/PycharmProjects/untitled4/targil4.py", line 1, in &lt;module&gt; class targil4(object): File "C:/Users/Maymon/PycharmProjects/untitled4/targil4.py", line 10, in targil4 plus() File "C:/Users/Maymon/PycharmProjects/untitled4/targil4.py", line 6, plus int(x[i]) TypeError: list indices must be integers, not str Process finished with exit code 1 </code></pre>
2
2016-09-19T15:45:25Z
39,577,309
<p>I believe you may get more out of an answer here by actually looking at each statement and seeing what is going on. </p> <pre><code># Because the user enters '1234', x is a list ['1', '2', '3', '4'], # each time the loop runs, i gets '1', '2', etc. for i in x: # here, x[i] fails because your i value is a string. # You cannot index an array via a string. int(x[i]) x[i]+=1 </code></pre> <p>So we can "fix" this by adjusting the code by our new understanding.</p> <pre><code># We create a new output variable to hold what we will display to the user output = '' for i in x: output += str(int(i) + 1) print(output) </code></pre>
1
2016-09-19T15:57:19Z
[ "python", "string", "list", "integer", "indices" ]
How to make argparse work in executable program
39,577,267
<p>I have a program command line which uses the argparse module.</p> <pre><code>import argparse def run(): print 'Running' def export(): print 'Exporting' def argument_parser(): parser = argparse.ArgumentParser() parser.add_argument('run', action='store_true') parser.add_argument('export', action='store_true') return parser.parse_args() args = argument_parser() if args.run: run() else: export() </code></pre> <p>Now it works just fine when run from command line <code>&gt; python myfile.py run</code> etc. </p> <p>However using <code>pyinstaller</code> I've made an executable from it and if I open the main.exe file I got <code>too few arguments</code> error which is quite logical. But I want to be able to open (double click) main.exe (which open the comman line tool) and have the command line wait for my command (run or export in this case). Instead it just throws the error and quits.</p>
1
2016-09-19T15:55:10Z
39,577,523
<p>Use the <a href="https://docs.python.org/3/library/cmd.html" rel="nofollow"><code>cmd</code> module</a> to create a shell.</p> <p>You can then use <code>cmd.Cmd()</code> class you create to run single commands through the <a href="https://docs.python.org/3/library/cmd.html#cmd.Cmd.onecmd" rel="nofollow"><code>cmd.Cmd().onecmd()</code> method</a>; pass in the <code>sys.argv</code> command line, joined with spaces:</p> <pre><code>from cmd import Cmd import sys class YourCmdSubclass(Cmd): def do_run(*args): """Help text for run""" print('Running') def do_export(*args): """Help text for export""" print('Exporting') def do_exit(*args): return -1 if __name__ == '__main__': c = YourCmdSubclass() command = ' '.join(sys.argv[1:]) if command: sys.exit(c.onecmd(command)) c.cmdloop() </code></pre> <p>Help is automatically provided by the <code>help</code> command.</p>
1
2016-09-19T16:08:16Z
[ "python", "argparse", "pyinstaller" ]
Asynchronous receiving TCP packets in python
39,577,302
<p>I have an instant messaging app, with client written in python.</p> <p>Code that connects to a server:</p> <pre><code>def connect(self, host, port, name): host = str(host) port = int(port) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((host, port)) s.send('CONNECT:' + name) print s.recv(1024) return s </code></pre> <p>Then s will be stored in a self.socket.</p> <p>Here is function that receives tcp packets from server and prints it to command line. </p> <pre><code>def chat(self): while True: data = self.socket.recv(4096) if not data: pass else: print data </code></pre> <p>So in my mind it should receive everything server sends and prints out, but it isn't happens. Anyone knows how to bring it to life?</p>
0
2016-09-19T15:56:56Z
39,577,818
<p>There is a way with <code>select</code> function to monitor multiple streams, make a list of all the streams you need to handle and use the <code>select</code> function for it, for the user input use <code>sys.stdin</code> and all the sockets that you expect to chat with.<br> check this: <a href="https://docs.python.org/2/library/select.html" rel="nofollow">https://docs.python.org/2/library/select.html</a><br>But still the best way to do asynchronous chat will be with <code>udp</code>, it will work really fine</p>
0
2016-09-19T16:27:14Z
[ "python", "sockets", "tcp" ]
Python Selenium Explicit WebDriverWait function only works with presence_of_element_located
39,577,365
<p>I am trying to use Selenium WebDriverWait in Python to wait for items to load on a webpage , however, using any expected condition apart from <strong>presence_of_element_located</strong> seems to result in the error </p> <blockquote> <p>selenium.common.exceptions.WebDriverException: Message: SyntaxError: missing ) in parenthetical</p> </blockquote> <p>I thought it might be linked to the site I was trying against , however I get the same error on any site - see snippit below where I have replaced <strong>presence_of_element_located</strong> with <strong>visibility_of_element_located</strong> and am trying to confirm visibility of the search box on python.org.</p> <pre><code>from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.keys import Keys driver = webdriver.Firefox() driver.get("http://www.python.org") try: element = WebDriverWait(driver, 5).until(EC.visibility_of_element_located((By.NAME,"q"))) element.send_keys("pycon") element.send_keys(Keys.RETURN) finally: driver.quit() </code></pre> <p>The Full stack trace is as below , Any help would be appreciated !</p> <pre><code>Traceback (most recent call last): File "C:\dev\test.py", line 51, in &lt;module&gt; element = WebDriverWait(driver, 5).until(EC.visibility_of_element_located((By.NAME,"q"))) File "C:\Development\python\python35-32\lib\site-packages\selenium-3.0.0b3-py3.5.egg\selenium\webdriver\support\wait.py", line 71, in until value = method(self._driver) File "C:\Development\python\python35-32\lib\site-packages\selenium-3.0.0b3-py3.5.egg\selenium\webdriver\support\expected_conditions.py", line 78, in __call__ return _element_if_visible(_find_element(driver, self.locator)) File "C:\Development\python\python35-32\lib\site-packages\selenium-3.0.0b3-py3.5.egg\selenium\webdriver\support\expected_conditions.py", line 98, in _element_if_visible return element if element.is_displayed() == visibility else False File "C:\Development\python\python35-32\lib\site-packages\selenium-3.0.0b3-py3.5.egg\selenium\webdriver\remote\webelement.py", line 353, in is_displayed self) File "C:\Development\python\python35-32\lib\site-packages\selenium-3.0.0b3-py3.5.egg\selenium\webdriver\remote\webdriver.py", line 465, in execute_script 'args': converted_args})['value'] File "C:\Development\python\python35-32\lib\site-packages\selenium-3.0.0b3-py3.5.egg\selenium\webdriver\remote\webdriver.py", line 236, in execute self.error_handler.check_response(response) File "C:\Development\python\python35-32\lib\site-packages\selenium-3.0.0b3-py3.5.egg\selenium\webdriver\remote\errorhandler.py", line 192, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.WebDriverException: Message: SyntaxError: missing ) in parenthetical </code></pre> <p><em>Update - > After a few comments below i have done some testing on versions and browsers and this issue seems isolated to Python 3 and Firefox , the script works with Python 2.7 and works on both versions of python for Chrome webdriver .</em> </p>
0
2016-09-19T15:59:55Z
39,577,900
<p>Copy pasted the same code and it works. Dint have enough repo to post comments so had to put it in answer section.</p>
0
2016-09-19T16:31:39Z
[ "python", "selenium" ]
Python Selenium Explicit WebDriverWait function only works with presence_of_element_located
39,577,365
<p>I am trying to use Selenium WebDriverWait in Python to wait for items to load on a webpage , however, using any expected condition apart from <strong>presence_of_element_located</strong> seems to result in the error </p> <blockquote> <p>selenium.common.exceptions.WebDriverException: Message: SyntaxError: missing ) in parenthetical</p> </blockquote> <p>I thought it might be linked to the site I was trying against , however I get the same error on any site - see snippit below where I have replaced <strong>presence_of_element_located</strong> with <strong>visibility_of_element_located</strong> and am trying to confirm visibility of the search box on python.org.</p> <pre><code>from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.keys import Keys driver = webdriver.Firefox() driver.get("http://www.python.org") try: element = WebDriverWait(driver, 5).until(EC.visibility_of_element_located((By.NAME,"q"))) element.send_keys("pycon") element.send_keys(Keys.RETURN) finally: driver.quit() </code></pre> <p>The Full stack trace is as below , Any help would be appreciated !</p> <pre><code>Traceback (most recent call last): File "C:\dev\test.py", line 51, in &lt;module&gt; element = WebDriverWait(driver, 5).until(EC.visibility_of_element_located((By.NAME,"q"))) File "C:\Development\python\python35-32\lib\site-packages\selenium-3.0.0b3-py3.5.egg\selenium\webdriver\support\wait.py", line 71, in until value = method(self._driver) File "C:\Development\python\python35-32\lib\site-packages\selenium-3.0.0b3-py3.5.egg\selenium\webdriver\support\expected_conditions.py", line 78, in __call__ return _element_if_visible(_find_element(driver, self.locator)) File "C:\Development\python\python35-32\lib\site-packages\selenium-3.0.0b3-py3.5.egg\selenium\webdriver\support\expected_conditions.py", line 98, in _element_if_visible return element if element.is_displayed() == visibility else False File "C:\Development\python\python35-32\lib\site-packages\selenium-3.0.0b3-py3.5.egg\selenium\webdriver\remote\webelement.py", line 353, in is_displayed self) File "C:\Development\python\python35-32\lib\site-packages\selenium-3.0.0b3-py3.5.egg\selenium\webdriver\remote\webdriver.py", line 465, in execute_script 'args': converted_args})['value'] File "C:\Development\python\python35-32\lib\site-packages\selenium-3.0.0b3-py3.5.egg\selenium\webdriver\remote\webdriver.py", line 236, in execute self.error_handler.check_response(response) File "C:\Development\python\python35-32\lib\site-packages\selenium-3.0.0b3-py3.5.egg\selenium\webdriver\remote\errorhandler.py", line 192, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.WebDriverException: Message: SyntaxError: missing ) in parenthetical </code></pre> <p><em>Update - > After a few comments below i have done some testing on versions and browsers and this issue seems isolated to Python 3 and Firefox , the script works with Python 2.7 and works on both versions of python for Chrome webdriver .</em> </p>
0
2016-09-19T15:59:55Z
39,578,019
<p>These minor changes work for me.</p> <ol> <li>visibility_of_element_located ===> presence_of_element_located</li> <li>driver.quit() ===> driver.close()</li> </ol> <p>See the following:</p> <pre><code>from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.keys import Keys driver = webdriver.Firefox() driver.get("http://www.python.org") try: element = WebDriverWait(driver, 5).until(EC.presence_of_element_located((By.NAME,"q"))) element.send_keys("pycon") element.send_keys(Keys.RETURN) finally: driver.close() </code></pre>
0
2016-09-19T16:38:21Z
[ "python", "selenium" ]
which averaging should be used when computing the ROC AUC on imbalanced data set?
39,577,408
<p>I am doing a binary classification task on imbalanced data set .. and right now computing the ROC AUC using : <code>sklearn.metrics.roc_auc_score(y_true, y_score, average='macro')</code> <a href="http://scikit-learn.org/stable/modules/generated/sklearn.metrics.roc_auc_score.html" rel="nofollow">source</a> and I have two questions: </p> <ul> <li>I am not sure if the averaging <code>macro</code> is influenced by the class imbalance here and what is the best averaging in this situation (when classifying imbalanced classes)?</li> <li>Is there a reference for the way that shows how scikit-learn calculate the ROC AUC with the different averaging argument ? </li> </ul>
0
2016-09-19T16:02:15Z
39,580,846
<p>The average='weighted' is your choice for the problem of imbalanced classes as it follows from 3.3.2.1 in</p> <blockquote> <p><a href="http://scikit-learn.org/stable/modules/model_evaluation.html" rel="nofollow">http://scikit-learn.org/stable/modules/model_evaluation.html</a></p> </blockquote>
1
2016-09-19T19:40:22Z
[ "python", "machine-learning", "scikit-learn" ]
Why is my Python Tuple only storing first value?
39,577,443
<p>I am storing a mysql query w/in a tuple in my python script. I have a raw_input variable w/in the script which I would like to check if their is a match w/in the tuple.</p> <pre><code>curs.execute("""SELECT username, id FROM employees WHERE gid!=4""") rows=curs.fetchall() db.close() uname = raw_input('Type the username for the new device: ') for row in rows: user = row[0] empid = row[1] if user == uname: print 'User ' + uname + ' found...' else: print 'Not Found' </code></pre> <p>This only works if I type the username of the first employee. Any other employee returns 'Not Found'</p> <p>I noticed that if I remove the raw_input line, and the if statement and add </p> <pre><code>for row in rows: user = row[0] empid = row[1] print user </code></pre> <p>It prints all of the values</p>
1
2016-09-19T16:04:01Z
39,577,751
<p>This may be a better approach based on what I assume you are trying to do.</p> <p>There is no reason for the loop in Python to search for the user when you can simply add that to your <code>WHERE</code> clause.</p> <pre><code># Get the username from input uname = raw_input('Type the username for the new device: ') # Check to see if username in table curs.execute("SELECT username, id FROM employees WHERE gid != 4 AND LOWER(username) = %s", (uname.lower(),)) row = curs.fetchone() # If no records found, should return an empty tuple db.close() # Return the user if found if row: user = row[0] empid = row[1] print 'User ' + user + ' found...' else print 'Not Found' </code></pre> <p>This will return the username, if found. Otherwise 'Not Found'.</p>
0
2016-09-19T16:23:10Z
[ "python", "mysql", "tuples" ]
What is the pythonic way of specifying a minimal module version?
39,577,484
<p>I'm writing a Python script where one of its imported modules needs to be at least version <code>x.y.z</code>.</p> <pre><code>import pandas as pd # Check the pandas version _pdversion = map(lambda x: int(x), pd.__version__.split('.')) if _pdversion[1] &lt; 18: # Not sure the most sensible exception class.. raise Exception("ERROR: you need pandas &gt; version 0.18") </code></pre> <p>Is there a standard way to check for a minimal version at runtime? Or is this discouraged, in favour of specification at the package level and configure-time?</p>
1
2016-09-19T16:06:25Z
39,577,845
<p>I think the most pythonic way would be to specify it in a requirements.txt file, and keep everything in a virtual environment.</p> <p>Or: </p> <pre><code>import pkg_resources pkg_resources.require("requests==2.11.1") import requests </code></pre>
0
2016-09-19T16:28:47Z
[ "python", "dependencies", "packaging" ]
Use DBus daemon to exchange message from C application to python application
39,577,527
<p>Hi I am pretty new to DBus daemon and would like to accomplish simple message exchange between C application and python application, which are running on custom linux-like environment. My understanding is</p> <ol> <li>First, start dbus-daemon from init file </li> <li>Register the C application and the python application to the D-BUS</li> <li>Send message (it's just a simple string) on the bus between these 2 applications.</li> </ol> <p>My questions are regarding (2) and (3) above. How can C application and python application register to the same bus?</p> <p>Also, what APIs need to be invoked to send string messages between these 2 applications?</p>
0
2016-09-19T16:08:31Z
39,578,717
<p><em>[You asked for simple message passing]</em> Do you really need DBus?</p> <p>If you're asking for simple message passing between a C app and Python, why not use a message-passing library like Rabbit/ZeroMQ? Those already solve all the issues related to passing/receiving messages.</p> <p>And, if you want to keep dependencies to a minimum, you could use a UNIX socket or even some simple TCP/UDP datagrams.</p> <p>EDIT: Since I'm trying to convince you to research ZeroMQ as your IPC platform and how simple it is, here's a sample C "Client" sending a complete datagram to the server, which replies back.</p> <p><a href="http://zguide.zeromq.org/c:hwclient" rel="nofollow">ZeroQM Client Example in C</a></p> <p>And the server is just as simple:</p> <p><a href="http://zguide.zeromq.org/c:hwserver" rel="nofollow">ZeroQM Server Example in C</a></p>
0
2016-09-19T17:20:01Z
[ "python", "linux", "dbus" ]
Use DBus daemon to exchange message from C application to python application
39,577,527
<p>Hi I am pretty new to DBus daemon and would like to accomplish simple message exchange between C application and python application, which are running on custom linux-like environment. My understanding is</p> <ol> <li>First, start dbus-daemon from init file </li> <li>Register the C application and the python application to the D-BUS</li> <li>Send message (it's just a simple string) on the bus between these 2 applications.</li> </ol> <p>My questions are regarding (2) and (3) above. How can C application and python application register to the same bus?</p> <p>Also, what APIs need to be invoked to send string messages between these 2 applications?</p>
0
2016-09-19T16:08:31Z
39,591,363
<p>There are two default buses on each Linux system - the system bus (shared for all users, made for system services) and the session bus. All DBus libraries let you trivially connect to one of those buses.</p> <p>Then, in the receiver process, you need to take ownership of a bus name (a string that will let other processes find you), and register an object providing some methods. And then you will be able to call those methods from another process.</p> <p>The best DBus API for C is <a href="https://developer.gnome.org/gio/stable/GDBusConnection.html" rel="nofollow">https://developer.gnome.org/gio/stable/GDBusConnection.html</a> and the best API for Python is <a href="https://github.com/LEW21/pydbus" rel="nofollow">https://github.com/LEW21/pydbus</a></p>
0
2016-09-20T10:10:40Z
[ "python", "linux", "dbus" ]
How to handle concurrent modifications in django?
39,577,548
<p>I am trying to build a project(like e-commerce) using Django and integrate it with android. (I am not building website, I am trying mobile only, so I am using <em>django-rest-framework</em> to create api)</p> <p>So my question is how to handle a case where two or more users can book an item at the same time when there is only a single item. (basically how to handle concurrent modification and access of data) ?</p> <p>Please help. I am stuck on this one.</p>
0
2016-09-19T16:09:43Z
39,584,832
<p><code>django-locking</code> is the way to go.</p>
0
2016-09-20T02:31:09Z
[ "python", "django", "django-models", "django-rest-framework" ]
If item in list does not contain "string", add a "string2" to the item?
39,577,562
<p>In Python I have a list of this sort:</p> <pre><code>list = ["item.1", "sdfhkjdsffs/THIS-STRING", "fsdhfjsdhfsdf/THIS-STRING", item4/THIS-STRING, item5] </code></pre> <p>How do I go about adding <code>"some string"</code> for each item in list that does <em>not</em> contain <code>"THIS-STRING"</code>?</p>
-2
2016-09-19T16:10:33Z
39,577,620
<pre><code>result = [x if x.find("SOME-STRING")&gt;=0 else x+"some string" for x in list] </code></pre>
0
2016-09-19T16:14:47Z
[ "python", "list" ]
Storing user permissions on rows of data
39,577,568
<p>I have a table with rows of data for different experiments.</p> <pre><code>experiment_id data_1 data_2 ------------- ------ ------- 1 2 3 4 .. </code></pre> <p>I have a user database on django, and I would like to store permissions indicating which users can access which rows and then return only the rows the user is authorized for.</p> <p>What format should I use to store the permissions? Simply a table with a row for each user and a column for each experiment with Boolean? And in that case I would have to add a row to this table each time an experiment is added?</p> <pre><code>user experiment_1 experiment_2 experiment_3 .. ---- ------------ ------------ ------------ -- user_1 True False False .. user_2 False True False .. .. </code></pre> <p>Any reference literature on the topic would also be great, preferably related to sqlite3 functionality since that is my current db backend.</p>
0
2016-09-19T16:11:11Z
39,577,734
<p>I'm not 100% sure what all will work best for you but in the past I find using a solution as follows to be the easiest to query against and maintain in the future.</p> <pre><code>Table: Experiment Experiment_Id | data_1 | data_2 ----------------------------------- 1 | ... | ... 2 | ... | ... Table: User User_Name | Password | ... ---------------------------- User1 | ... User2 | ... Table: User_Experiment_Permissions User_Name | Experiment | Can_Read | Can_Edit -------------------------------------------- User1 | 1 | true | false User2 | 1 | false | false User1 | 2 | true | true User2 | 2 | true | false </code></pre> <p>As you can see, in the new table we reference both the user and the experiment. This allows us fine grain control over the relationship between the user and the experiment. Also, if this relationship had a new permission that arose, such as <code>can_delete</code> then you can simply add this to the new cross reference table with a default and the change will be retrofit into your your system :-)</p>
0
2016-09-19T16:22:07Z
[ "python", "mysql", "django", "database", "sqlite3" ]
Storing user permissions on rows of data
39,577,568
<p>I have a table with rows of data for different experiments.</p> <pre><code>experiment_id data_1 data_2 ------------- ------ ------- 1 2 3 4 .. </code></pre> <p>I have a user database on django, and I would like to store permissions indicating which users can access which rows and then return only the rows the user is authorized for.</p> <p>What format should I use to store the permissions? Simply a table with a row for each user and a column for each experiment with Boolean? And in that case I would have to add a row to this table each time an experiment is added?</p> <pre><code>user experiment_1 experiment_2 experiment_3 .. ---- ------------ ------------ ------------ -- user_1 True False False .. user_2 False True False .. .. </code></pre> <p>Any reference literature on the topic would also be great, preferably related to sqlite3 functionality since that is my current db backend.</p>
0
2016-09-19T16:11:11Z
39,578,092
<p>It depends on the way you will use the permissions for.<br> <br> - In case you will use this values inside a query you have two options for example to get the users with specific permiss </p> <ul> <li>Create a <a href="https://en.wikipedia.org/wiki/Mask_(computing)" rel="nofollow">bit masking</a> number fields and every bit will represent permission, and you can use AND/OR to get whatever combinations of permissions you need. <ul> <li>Advantage : small size, very efficient</li> <li>Disadvantage: complex to implement</li> </ul> </li> <li>Create a field for each permission ( your solution ). <ul> <li>Advantage : To easy to add</li> <li>Disadvantage: Have to edit schema with each permission</li> </ul> </li> </ul> <p><br> - In case you will not use it for any query and will process it at the code you can just dump a <strong>JSON</strong> into one column include all the permission the user has like :</p> <pre><code>{"experiment_1": 1, "experiment_2": 0, "experiment_3": 1} </code></pre>
0
2016-09-19T16:42:33Z
[ "python", "mysql", "django", "database", "sqlite3" ]
Getting the last value for each week, with the matching date
39,577,617
<p>So I start out with a <code>pd.Series</code> called <code>jpm</code>, and I would like to group it into weeks and take the last value from each week. This works with the code below, it does get the last value. But it changes corresponding index to the Sunday of the week, and I would like it to <strong>leave it unchaged</strong>.</p> <pre><code>import pandas_datareader.data as web import pandas as pd start = pd.datetime(2015, 11, 1) end = pd.datetime(2015, 11, 17) raw_jpm = web.DataReader("JPM", 'yahoo', start, end)["Adj Close"] jpm = raw_jpm.ix[raw_jpm.index[::2]] </code></pre> <p><code>jpm</code> is now</p> <pre><code>Date 2015-11-02 64.125610 2015-11-04 64.428918 2015-11-06 66.982593 2015-11-10 66.219427 2015-11-12 64.575682 2015-11-16 65.074678 Name: Adj Close, dtype: float64 </code></pre> <p>I want to do some operations to it, such as</p> <pre><code>weekly = jpm.groupby(pd.TimeGrouper('W')).last() </code></pre> <p><code>weekly</code> is now</p> <pre><code>Date 2015-11-08 66.982593 2015-11-15 64.575682 2015-11-22 65.074678 Freq: W-SUN, Name: Adj Close, dtype: float64 </code></pre> <p>which is great, except all my dates got changed. The output I want, is:</p> <pre><code>Date 2015-11-06 66.982593 2015-11-12 64.575682 2015-11-16 65.074678 </code></pre>
2
2016-09-19T16:14:38Z
39,578,315
<p>You could provide a <code>DateOffset</code> by specifying the class name <code>Week</code> and indicating the weekly frequency <code>W-FRI</code>, by setting the <code>dayofweek</code> property as 4 [Monday : 0 → Sunday : 6]</p> <pre><code>jpm.groupby(pd.TimeGrouper(freq=pd.offsets.Week(weekday=4))).last().tail(5) Date 2016-08-19 65.860001 2016-08-26 66.220001 2016-09-02 67.489998 2016-09-09 66.650002 2016-09-16 65.820000 Freq: W-FRI, Name: Adj Close, dtype: float64 </code></pre> <hr> <p>If you want the starting date as the next monday from <code>start</code> date and the previous sunday from the <code>end</code> date, you could do this way:</p> <pre><code>from datetime import datetime, timedelta start = datetime(2015, 11, 1) monday = start + timedelta(days=(7 - start.weekday())) end = datetime(2016, 9, 30) sunday = end - timedelta(days=end.weekday() + 1) print (monday) 2015-11-02 00:00:00 print (sunday) 2016-09-25 00:00:00 </code></pre> <p>Then, use it as:</p> <pre><code>jpm = web.DataReader('JPM', 'yahoo', monday, sunday)["Adj Close"] jpm.groupby(pd.TimeGrouper(freq='7D')).last() </code></pre> <p>To get it all on a Sunday, as you specified the range Monday → Sunday and Sunday being the last day for the date to be considered, you could do a small hack:</p> <pre><code>monday_new = monday - timedelta(days=3) jpm = web.DataReader('JPM', 'yahoo', monday_new, sunday)["Adj Close"] jpm.groupby(pd.TimeGrouper(freq='W')).last().head() Date 2015-11-01 62.863448 2015-11-08 66.982593 2015-11-15 64.145175 2015-11-22 66.082449 2015-11-29 65.720431 Freq: W-SUN, Name: Adj Close, dtype: float64 </code></pre> <hr> <p>Now that you've posted the desired output, you can arrive at the result using <code>transform</code> method instead of taking the aggregated <code>last</code>, so that it returns an object that is indexed the same size as the one being grouped.</p> <pre><code>df = jpm.groupby(pd.TimeGrouper(freq='W')).transform('last').reset_index(name='Last') df </code></pre> <p><a href="http://i.stack.imgur.com/EIDce.png" rel="nofollow"><img src="http://i.stack.imgur.com/EIDce.png" alt="Image"></a></p> <pre><code>df['counter'] = (df['Last'].shift() != df['Last']).astype(int).cumsum() </code></pre> <p><a href="http://i.stack.imgur.com/uTl0L.png" rel="nofollow"><img src="http://i.stack.imgur.com/uTl0L.png" alt="Image"></a></p> <pre><code>df.groupby(['Last','counter'])['Date'].apply(lambda x: np.array(x)[-1]) \ .reset_index().set_index('Date').sort_index()['Last'] Date 2015-11-06 66.982593 2015-11-12 64.575682 2015-11-16 65.074678 Name: Last, dtype: float64 </code></pre> <p>Note: This is capable of handling repeated entries that occur in two separate dates due to the inclusion of the <code>counter</code> column which bins them separately into two buckets.</p>
1
2016-09-19T16:55:33Z
[ "python", "pandas" ]
Getting the last value for each week, with the matching date
39,577,617
<p>So I start out with a <code>pd.Series</code> called <code>jpm</code>, and I would like to group it into weeks and take the last value from each week. This works with the code below, it does get the last value. But it changes corresponding index to the Sunday of the week, and I would like it to <strong>leave it unchaged</strong>.</p> <pre><code>import pandas_datareader.data as web import pandas as pd start = pd.datetime(2015, 11, 1) end = pd.datetime(2015, 11, 17) raw_jpm = web.DataReader("JPM", 'yahoo', start, end)["Adj Close"] jpm = raw_jpm.ix[raw_jpm.index[::2]] </code></pre> <p><code>jpm</code> is now</p> <pre><code>Date 2015-11-02 64.125610 2015-11-04 64.428918 2015-11-06 66.982593 2015-11-10 66.219427 2015-11-12 64.575682 2015-11-16 65.074678 Name: Adj Close, dtype: float64 </code></pre> <p>I want to do some operations to it, such as</p> <pre><code>weekly = jpm.groupby(pd.TimeGrouper('W')).last() </code></pre> <p><code>weekly</code> is now</p> <pre><code>Date 2015-11-08 66.982593 2015-11-15 64.575682 2015-11-22 65.074678 Freq: W-SUN, Name: Adj Close, dtype: float64 </code></pre> <p>which is great, except all my dates got changed. The output I want, is:</p> <pre><code>Date 2015-11-06 66.982593 2015-11-12 64.575682 2015-11-16 65.074678 </code></pre>
2
2016-09-19T16:14:38Z
39,586,375
<p>you can do it this way:</p> <pre><code>In [15]: jpm Out[15]: Date 2015-11-02 64.125610 2015-11-04 64.428918 2015-11-06 66.982593 2015-11-10 66.219427 2015-11-12 64.575682 2015-11-16 65.074678 Name: Adj Close, dtype: float64 In [16]: jpm.groupby(jpm.index.week).transform('last').drop_duplicates(keep='last') Out[16]: Date 2015-11-06 66.982593 2015-11-12 64.575682 2015-11-16 65.074678 dtype: float64 </code></pre> <p>Explanation:</p> <pre><code>In [17]: jpm.groupby(jpm.index.week).transform('last') Out[17]: Date 2015-11-02 66.982593 2015-11-04 66.982593 2015-11-06 66.982593 2015-11-10 64.575682 2015-11-12 64.575682 2015-11-16 65.074678 dtype: float64 </code></pre>
1
2016-09-20T05:32:52Z
[ "python", "pandas" ]
Getting the last value for each week, with the matching date
39,577,617
<p>So I start out with a <code>pd.Series</code> called <code>jpm</code>, and I would like to group it into weeks and take the last value from each week. This works with the code below, it does get the last value. But it changes corresponding index to the Sunday of the week, and I would like it to <strong>leave it unchaged</strong>.</p> <pre><code>import pandas_datareader.data as web import pandas as pd start = pd.datetime(2015, 11, 1) end = pd.datetime(2015, 11, 17) raw_jpm = web.DataReader("JPM", 'yahoo', start, end)["Adj Close"] jpm = raw_jpm.ix[raw_jpm.index[::2]] </code></pre> <p><code>jpm</code> is now</p> <pre><code>Date 2015-11-02 64.125610 2015-11-04 64.428918 2015-11-06 66.982593 2015-11-10 66.219427 2015-11-12 64.575682 2015-11-16 65.074678 Name: Adj Close, dtype: float64 </code></pre> <p>I want to do some operations to it, such as</p> <pre><code>weekly = jpm.groupby(pd.TimeGrouper('W')).last() </code></pre> <p><code>weekly</code> is now</p> <pre><code>Date 2015-11-08 66.982593 2015-11-15 64.575682 2015-11-22 65.074678 Freq: W-SUN, Name: Adj Close, dtype: float64 </code></pre> <p>which is great, except all my dates got changed. The output I want, is:</p> <pre><code>Date 2015-11-06 66.982593 2015-11-12 64.575682 2015-11-16 65.074678 </code></pre>
2
2016-09-19T16:14:38Z
39,598,938
<p>It seems a little tricky to do this in pure pandas, so I used numpy</p> <pre><code>import numpy as np weekly = jpm.groupby(pd.TimeGrouper('W-SUN')).last() weekly.index = jpm.index[np.searchsorted(jpm.index, weekly.index, side="right")-1] </code></pre>
1
2016-09-20T16:06:45Z
[ "python", "pandas" ]
Dynamically setting scrapy request call back
39,577,650
<p>I'm working with scrapy. I want to rotate proxies on a per request basis and get a proxy from an api I have that returns a single proxy. My plan is to make a request to the api, get a proxy, then use it to set the proxy based on :</p> <pre><code>http://stackoverflow.com/questions/39430454/making-request-to-api-from-within-scrapy-function </code></pre> <p>I have the following:</p> <pre><code>class ContactSpider(Spider): name = "contact" def parse(self, response): .... PR = Request( 'my_api' headers=self.headers, meta={'newrequest': Request(url_to_scrape, headers=self.headers),}, callback=self.parse_PR ) yield PR def parse_PR(self, response): newrequest = response.meta['newrequest'] proxy_data = response.body newrequest.meta['proxy'] = 'http://'+proxy_data newrequest.replace(url = 'http://ipinfo.io/ip') #TESTING newrequest.replace(callback= self.form_output) #TESTING yield newrequest def form_output(self, response): open_in_browser(response) </code></pre> <p>but I'm getting:</p> <pre><code> Traceback (most recent call last): File "C:\twisted\internet\defer.py", line 1126, in _inlineCallbacks result = result.throwExceptionIntoGenerator(g) File "C:\twisted\python\failure.py", line 389, in throwExceptionIntoGenerator return g.throw(self.type, self.value, self.tb) File "C:\scrapy\core\downloader\middleware.py", line 43, in process_request defer.returnValue((yield download_func(request=request,spider=spider))) File "C:\scrapy\utils\defer.py", line 45, in mustbe_deferred result = f(*args, **kw) File "C:\scrapy\core\downloader\handlers\__init__.py", line 65, in download_request return handler.download_request(request, spider) File "C:\scrapy\core\downloader\handlers\http11.py", line 60, in download_request return agent.download_request(request) File "C:\scrapy\core\downloader\handlers\http11.py", line 255, in download_request agent = self._get_agent(request, timeout) File "C:\scrapy\core\downloader\handlers\http11.py", line 235, in _get_agent _, _, proxyHost, proxyPort, proxyParams = _parse(proxy) File "C:\scrapy\core\downloader\webclient.py", line 37, in _parse return _parsed_url_args(parsed) File "C:\scrapy\core\downloader\webclient.py", line 20, in _parsed_url_args host = b(parsed.hostname) File "C:\scrapy\core\downloader\webclient.py", line 17, in &lt;lambda&gt; b = lambda s: to_bytes(s, encoding='ascii') File "C:\scrapy\utils\python.py", line 117, in to_bytes 'object, got %s' % type(text).__name__) TypeError: to_bytes must receive a unicode, str or bytes object, got NoneType </code></pre> <p>what am I doing wrong?</p>
1
2016-09-19T16:17:01Z
39,583,110
<p>The stacktrace info suggests Scrapy has encountered a request object whose <code>url</code> is <code>None</code>, which is expected to be of string type.</p> <p>These two lines in your code:</p> <pre><code>newrequest.replace(url = 'http://ipinfo.io/ip') #TESTING newrequest.replace(callback= self.form_output) #TESTING </code></pre> <p>would not work as expected, since method <a href="http://doc.scrapy.org/en/latest/topics/request-response.html#scrapy.http.Request.replace" rel="nofollow"><code>Request.replace</code></a> <em>returns a new instance</em> instead of modifying the original request in-place.</p> <p>You would need something like this:</p> <pre><code>newrequest = newrequest.replace(url = 'http://ipinfo.io/ip') #TESTING newrequest = newrequest.replace(callback= self.form_output) #TESTING </code></pre> <p>or simply:</p> <pre><code>newrequest = newrequest.replace( url='http://ipinfo.io/ip', callback=self.form_output ) </code></pre>
1
2016-09-19T22:37:48Z
[ "python", "scrapy" ]
How to maintain different country versions of same language in Django?
39,577,656
<p>I would like to have a few different versions of the same language in Django, customized for different countries (e.g. <code>locale/en</code>, <code>locale/en_CA</code>, <code>locale/en_US</code>, etc.). If there is no language for specific country I would expect to use the default language version (<code>locale/en</code>)).</p> <p>Then in the settings file for each site I specify <code>LANGUAGE_CODE</code> and <code>LANGUAGES</code>.</p> <p>For some reason, even if I specify the following settings, the <code>locale/en_US</code> translations are still used:</p> <pre><code>LANGUAGE_CODE = 'en' LANGUAGES = ( ('en', ugettext('English')), ) </code></pre> <p>Though I clearly specify that the language code should be <code>en</code> (not <code>en-us</code>).</p> <p>Am I missing something? Already tried to find the answer in multiple places, including Django documentation.</p>
12
2016-09-19T16:17:30Z
39,646,423
<p>may I suggest you to put a breakpoint into the LocaleMiddleware Class? </p> <p>In this way, you might found out a clue which thing was actually getting your way from getting the right Language.</p> <p>Becaue according the <a href="https://docs.djangoproject.com/en/1.10/_modules/django/middleware/locale/#LocaleMiddleware" rel="nofollow">source code</a> of LocaleMiddleware Class and the <a href="https://docs.djangoproject.com/en/1.10/topics/i18n/translation/#how-django-discovers-language-preference" rel="nofollow">How Django discovers language preference</a> , there could be so many things can affect the result.</p>
0
2016-09-22T18:31:18Z
[ "python", "django", "internationalization", "django-i18n" ]
How to maintain different country versions of same language in Django?
39,577,656
<p>I would like to have a few different versions of the same language in Django, customized for different countries (e.g. <code>locale/en</code>, <code>locale/en_CA</code>, <code>locale/en_US</code>, etc.). If there is no language for specific country I would expect to use the default language version (<code>locale/en</code>)).</p> <p>Then in the settings file for each site I specify <code>LANGUAGE_CODE</code> and <code>LANGUAGES</code>.</p> <p>For some reason, even if I specify the following settings, the <code>locale/en_US</code> translations are still used:</p> <pre><code>LANGUAGE_CODE = 'en' LANGUAGES = ( ('en', ugettext('English')), ) </code></pre> <p>Though I clearly specify that the language code should be <code>en</code> (not <code>en-us</code>).</p> <p>Am I missing something? Already tried to find the answer in multiple places, including Django documentation.</p>
12
2016-09-19T16:17:30Z
39,733,169
<p>This is a quirk of Python (not specifically Django) and the gettext module.</p> <p>Ticket <a href="https://code.djangoproject.com/ticket/8626" rel="nofollow">8626</a> was raised on the Django issue tracker around the time of the 1.0 release and after some suggestions and debate, the Django devs deemed it a "won't fix".</p> <p>There are suggestions in the ticket thread to use 'en-en' as the default. My memory is a little rough but if I recall correctly this approach didn't play well with other parts of my i18n tooling (e.g. the pox library). I gave up and settled for using en-US as the default for the project and listing the other variants (e.g. en-au) as alternatives.</p>
3
2016-09-27T19:50:17Z
[ "python", "django", "internationalization", "django-i18n" ]
How to select a name of a new list from existing string?
39,577,863
<p>I'm quite new to python and I'm not able to solve this. In a loop, I have a list with some numbers and a string with the desired name of the list. I want to create a new list identical to the existing list a named it according to the name from the string. </p> <p><code>values = [1,2,3] name='Ehu'</code></p> <p>What I need is a new list named 'Ehu' containing the same items as the list values, but I don't know how to select a name of the new list from existing string. </p> <p>Thanks</p>
1
2016-09-19T16:29:51Z
39,578,137
<p>While you <em>can</em> do what you ask:</p> <pre><code>&gt;&gt;&gt; globals()['Ehu'] = [1,2,3] &gt;&gt;&gt; Ehu [1, 2, 3] </code></pre> <p>or for local variables:</p> <pre><code>&gt;&gt;&gt; def f(): ... f.__dict__['Ehu'] = [1,2,3] ... print(Ehu) ... &gt;&gt;&gt; f() [1, 2, 3] </code></pre> <p>That is a bad practice. A better solution as @Moses commented:</p> <pre><code>&gt;&gt;&gt; list_names = {} &gt;&gt;&gt; list_names['Ehu'] = [1,2,3] &gt;&gt;&gt; print(list_names['Ehu']) [1, 2, 3] </code></pre>
0
2016-09-19T16:45:18Z
[ "python" ]
How to select a name of a new list from existing string?
39,577,863
<p>I'm quite new to python and I'm not able to solve this. In a loop, I have a list with some numbers and a string with the desired name of the list. I want to create a new list identical to the existing list a named it according to the name from the string. </p> <p><code>values = [1,2,3] name='Ehu'</code></p> <p>What I need is a new list named 'Ehu' containing the same items as the list values, but I don't know how to select a name of the new list from existing string. </p> <p>Thanks</p>
1
2016-09-19T16:29:51Z
39,578,484
<p>Can be done using <code>globals</code>:</p> <pre><code>&gt;&gt;&gt; g = globals() &gt;&gt;&gt; name = 'Ehu' &gt;&gt;&gt; g['{}'.format(name)] = [1, 2, 3] &gt;&gt;&gt; Ehu [1, 2, 3] </code></pre> <hr>
1
2016-09-19T17:06:42Z
[ "python" ]