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
Extracting a set from a list of composite elements in python
39,546,200
<p>I'm maintaining <code>message_id</code> and <code>message_writer_id</code> together in a python list like so:</p> <pre><code>composite_items = ['1:2', '2:2', '3:2', '4:1', '5:19', '20:2', '45:1', ...] </code></pre> <p>Where each element is <code>message_id:message_poster_id</code>. </p> <p>From the above list, I want to extract the <code>set</code> of all <code>message_writer_ids</code>. I.e. I want to extract a <code>set</code> containing all unique numbers <em>after</em> <code>:</code> so that I end up with: </p> <pre><code>item_set = ['2', '1', '19'] </code></pre> <p>What's the most efficient way to do that in python?</p> <hr> <p>Currently, I'm thinking I'll do something like:</p> <pre><code>new_list = [] for item in composite_items: element = item.split(":")[1] new_list.append(element) new_set = set(new_list) </code></pre> <p>Was wondering if there's a faster way to achieve this. </p>
0
2016-09-17T11:18:10Z
39,546,755
<pre><code>composite_items = ['1:2', '2:2', '3:2', '4:1', '5:19', '20:2', '45:1', ...] posters = dict() for element in composite_items: poster_id = element.split(":")[1] posters[poster_id] = posters.get(poster_id, 0) + 1 </code></pre> <p>You can use dictionaries and also count how many messages sent by <code>message_poster_id</code>. <code>posters.get(poster_id,0) + 1</code> checks that a poster exists or not. If exists it gets its value (number of messages) and increment it by 1.</p> <p>If doesn't exist its add the poster_id to dictionary and sets it to 0.</p>
0
2016-09-17T12:21:16Z
[ "python" ]
Extracting a set from a list of composite elements in python
39,546,200
<p>I'm maintaining <code>message_id</code> and <code>message_writer_id</code> together in a python list like so:</p> <pre><code>composite_items = ['1:2', '2:2', '3:2', '4:1', '5:19', '20:2', '45:1', ...] </code></pre> <p>Where each element is <code>message_id:message_poster_id</code>. </p> <p>From the above list, I want to extract the <code>set</code> of all <code>message_writer_ids</code>. I.e. I want to extract a <code>set</code> containing all unique numbers <em>after</em> <code>:</code> so that I end up with: </p> <pre><code>item_set = ['2', '1', '19'] </code></pre> <p>What's the most efficient way to do that in python?</p> <hr> <p>Currently, I'm thinking I'll do something like:</p> <pre><code>new_list = [] for item in composite_items: element = item.split(":")[1] new_list.append(element) new_set = set(new_list) </code></pre> <p>Was wondering if there's a faster way to achieve this. </p>
0
2016-09-17T11:18:10Z
39,546,888
<p>You may use set comprehension like so:</p> <pre><code>new_set = {item.partition(":")[2] for item in composite_items} </code></pre> <p>Set comprehension is fast, and unlike <code>str.split()</code>, <code>str.partition()</code> splits only once and stops looking for more colons. Quite the same as with <code>str.split(maxsplit=1)</code>.</p>
2
2016-09-17T12:36:07Z
[ "python" ]
Python start all Threads from doulbe FOR LOOP
39,546,286
<p>I have this kind of scenario:</p> <pre><code>threads = [] for wordToScan in wordsList: dictionaryFileOpen = open(dictionaryFile, "r") for i in range(10): threads.append(Thread(target=words_Scan_Start, args=(dictionaryFileOpen, wordToScan))) for thread in threads: thread.start() for thread in threads: thread.join() def words_Scan_Start(dictionaryFile, wordToScan): while True: sub_word = dictionaryFile.readline() if not sub_word: break #... Here is some actions. </code></pre> <p>Now I need to start all these threads at once(10 threads each for every <code>wordToScan in wordsList</code>).</p> <p>Every <code>wordToScan in wordsList:</code> should use <code>dictionaryFileOpen</code> in 10 threads but without moving <code>.readline()</code> for the other <code>wordToScan in wordsList:</code> that working at the same time. Also, I can't understand where is to close the <code>dictionaryFileOpen</code>.</p>
0
2016-09-17T11:26:20Z
39,546,587
<p>Here is how I have it done:</p> <pre><code>threads = [] for wordToScan in wordsList: wordThread = [] dictionaryFileOpen = open(dictionaryFile, "r") for i in range(10): wordThread.append(Thread(target=words_Scan_Start, args=(dictionaryFileOpen, wordToScan))) threads.append(wordThread) for thread in threads: for wordThread in thread: wordThread.start() for thread in threads: for wordThread in thread: wordThread.join() dictionaryFileOpen.close() def words_Scan_Start(dictionaryFile, wordToScan): while True: sub_word = dictionaryFile.readline() if not sub_word: break #... Here is some actions. </code></pre> <p>Am I doing it right?</p>
0
2016-09-17T12:02:59Z
[ "python", "multithreading", "readline" ]
Python start all Threads from doulbe FOR LOOP
39,546,286
<p>I have this kind of scenario:</p> <pre><code>threads = [] for wordToScan in wordsList: dictionaryFileOpen = open(dictionaryFile, "r") for i in range(10): threads.append(Thread(target=words_Scan_Start, args=(dictionaryFileOpen, wordToScan))) for thread in threads: thread.start() for thread in threads: thread.join() def words_Scan_Start(dictionaryFile, wordToScan): while True: sub_word = dictionaryFile.readline() if not sub_word: break #... Here is some actions. </code></pre> <p>Now I need to start all these threads at once(10 threads each for every <code>wordToScan in wordsList</code>).</p> <p>Every <code>wordToScan in wordsList:</code> should use <code>dictionaryFileOpen</code> in 10 threads but without moving <code>.readline()</code> for the other <code>wordToScan in wordsList:</code> that working at the same time. Also, I can't understand where is to close the <code>dictionaryFileOpen</code>.</p>
0
2016-09-17T11:26:20Z
39,546,667
<p>You should not read file from several threads. This involves following considerations:</p> <ol> <li>Objects which are accessed from several threads must be thread safe. File is not thread safe. So you must guard all places where you use it with mutex.</li> <li>Reading from the disk is quite a slow process. A single thread can handle it with great margin.</li> <li>Linear read is much faster than random read. So it is effective to read it from a single thread.</li> </ol> <p>So general approach is to read the file from one thread and then dispatch the processing fork for other threads. And if you can do the work in one thread it is better just to do it so, because it is much simpler. Make multithreaded applications only when you really need them.</p>
0
2016-09-17T12:13:34Z
[ "python", "multithreading", "readline" ]
Unable to send mail using python with multiple attachment and multiple recipients [to,cc,bcc]
39,546,398
<p>Below is my code. It is unable to send mail somewhere at parsing level. Not able to understand the actual issue. OS is Ubuntu 14.04 Server provided by AWS. It has to send email with two attachments.</p> <pre><code>import smtplib import sys from email.MIMEMultipart import MIMEMultipart from email.MIMEText import MIMEText from email.MIMEBase import MIMEBase from email import encoders fromaddr = "user@comany.com" toaddr = str(sys.argv[1]).split(",") ccaddr = str(sys.argv[2]).split(",") bccaddr = str(sys.argv[3]).split(",") subject = None body = None print sys.argv with open("subject.txt") as f1: subject = f1.read() with open("body.txt") as f2: body = f2.read() msg = MIMEMultipart() msg['From'] = fromaddr msg['To'] = toaddr msg['Cc'] = ccaddr msg['Bcc'] = bccaddr msg['Subject'] = subject.replace("DD",str(sys.argv[4])[6:2]).replace("MM",str(sys.argv[4])[4:2]).replace("YYYY",str(sys.argv[4])[0:4]) body = body.replace("DD",str(sys.argv[4])[6:2]).replace("MM",str(sys.argv[4])[4:2]).replace("YYYY",str(sys.argv[4])[0:4]) msg.attach(MIMEText(body, 'plain')) for filename in str(sys.argv[5]).split(";"): attachment = open(filename, "rb") part = MIMEBase('application', 'octet-stream') part.set_payload((attachment).read()) encoders.encode_base64(part) part.add_header('Content-Disposition', "attachment; filename= %s" % filename) msg.attach(part) server = smtplib.SMTP('smtp.gmail.com', 587) server.ehlo() server.starttls() server.ehlo() server.login(fromaddr, "password") server.sendmail(fromaddr, toaddr, msg.as_string()) server.quit() </code></pre> <p>Here is the error:</p> <pre><code> File "send_mail.py", line 49, in &lt;module&gt; server.sendmail(fromaddr, toaddr, msg.as_string()) File "/usr/lib/python2.7/email/message.py", line 137, in as_string g.flatten(self, unixfrom=unixfrom) File "/usr/lib/python2.7/email/generator.py", line 83, in flatten self._write(msg) File "/usr/lib/python2.7/email/generator.py", line 115, in _write self._write_headers(msg) File "/usr/lib/python2.7/email/generator.py", line 164, in _write_headers v, maxlinelen=self._maxheaderlen, header_name=h).encode() File "/usr/lib/python2.7/email/header.py", line 410, in encode value = self._encode_chunks(newchunks, maxlinelen) File "/usr/lib/python2.7/email/header.py", line 370, in _encode_chunks _max_append(chunks, s, maxlinelen, extra) File "/usr/lib/python2.7/email/quoprimime.py", line 97, in _max_append L.append(s.lstrip()) AttributeError: 'list' object has no attribute 'lstrip' </code></pre>
1
2016-09-17T11:39:05Z
39,546,521
<p>Try it with <a href="https://github.com/kootenpv/yagmail" rel="nofollow">yagmail</a>. Disclaimer: I'm the developer of yagmail.</p> <pre><code>import yagmail yag = yagmail.SMTP("user@comany.com", "password") yag.send(toaddrs, subject, body, str(sys.argv[5]).split(";"), ccaddrs, bccaddrs) # ^ to ^subject ^ body ^ attachments ^ cc ^ bcc </code></pre> <p>It's pretty much "Do What I Want", you can provide lists of strings or a single string, even omit any arguments, and it will be sensible. Another cool thing is that the attachments here is a list of strings; where each will be tried to be loaded as file (with correct mimetype).</p> <p>Use <code>pip install yagmail</code> to install</p>
1
2016-09-17T11:54:34Z
[ "python", "python-2.7", "gmail", "sendmail" ]
Unable to send mail using python with multiple attachment and multiple recipients [to,cc,bcc]
39,546,398
<p>Below is my code. It is unable to send mail somewhere at parsing level. Not able to understand the actual issue. OS is Ubuntu 14.04 Server provided by AWS. It has to send email with two attachments.</p> <pre><code>import smtplib import sys from email.MIMEMultipart import MIMEMultipart from email.MIMEText import MIMEText from email.MIMEBase import MIMEBase from email import encoders fromaddr = "user@comany.com" toaddr = str(sys.argv[1]).split(",") ccaddr = str(sys.argv[2]).split(",") bccaddr = str(sys.argv[3]).split(",") subject = None body = None print sys.argv with open("subject.txt") as f1: subject = f1.read() with open("body.txt") as f2: body = f2.read() msg = MIMEMultipart() msg['From'] = fromaddr msg['To'] = toaddr msg['Cc'] = ccaddr msg['Bcc'] = bccaddr msg['Subject'] = subject.replace("DD",str(sys.argv[4])[6:2]).replace("MM",str(sys.argv[4])[4:2]).replace("YYYY",str(sys.argv[4])[0:4]) body = body.replace("DD",str(sys.argv[4])[6:2]).replace("MM",str(sys.argv[4])[4:2]).replace("YYYY",str(sys.argv[4])[0:4]) msg.attach(MIMEText(body, 'plain')) for filename in str(sys.argv[5]).split(";"): attachment = open(filename, "rb") part = MIMEBase('application', 'octet-stream') part.set_payload((attachment).read()) encoders.encode_base64(part) part.add_header('Content-Disposition', "attachment; filename= %s" % filename) msg.attach(part) server = smtplib.SMTP('smtp.gmail.com', 587) server.ehlo() server.starttls() server.ehlo() server.login(fromaddr, "password") server.sendmail(fromaddr, toaddr, msg.as_string()) server.quit() </code></pre> <p>Here is the error:</p> <pre><code> File "send_mail.py", line 49, in &lt;module&gt; server.sendmail(fromaddr, toaddr, msg.as_string()) File "/usr/lib/python2.7/email/message.py", line 137, in as_string g.flatten(self, unixfrom=unixfrom) File "/usr/lib/python2.7/email/generator.py", line 83, in flatten self._write(msg) File "/usr/lib/python2.7/email/generator.py", line 115, in _write self._write_headers(msg) File "/usr/lib/python2.7/email/generator.py", line 164, in _write_headers v, maxlinelen=self._maxheaderlen, header_name=h).encode() File "/usr/lib/python2.7/email/header.py", line 410, in encode value = self._encode_chunks(newchunks, maxlinelen) File "/usr/lib/python2.7/email/header.py", line 370, in _encode_chunks _max_append(chunks, s, maxlinelen, extra) File "/usr/lib/python2.7/email/quoprimime.py", line 97, in _max_append L.append(s.lstrip()) AttributeError: 'list' object has no attribute 'lstrip' </code></pre>
1
2016-09-17T11:39:05Z
39,552,374
<p>I had the same problem when I tried to feed a list in to msg['To']. I changed the list to string and I got rid of the problem. ['test@my.com', 'another@my.com'] => 'test@my.com, another@my.com' </p>
0
2016-09-17T22:39:13Z
[ "python", "python-2.7", "gmail", "sendmail" ]
Python: Save element by element from input
39,546,524
<p>I have an input file as follow</p> <pre><code>0.1 #real number 0.2 #real number Hello #string 10000 #integer number </code></pre> <p>I want to read it and use each line, before the '#' symbol, in my code. For the second part I did</p> <pre><code>with open('input.dat') as f: for line in f: line = line.split('#', 1)[0] line = line.rstrip() print(line) #test print f.close() </code></pre> <p>In this case I can read and print the number/string before the '#' symbol, but what about save them? For instance if I want to save 'Hello' in a string called 'name', '0.1' as a real called 'min' and so on. The simplest way I found, to read the input.dat file and save the elements as I want is </p> <pre><code>with open('input.dat') as f: lines = f.readlines() f.close() min=lines[2] # it print me: "0.1 #real number" </code></pre> <p>But what about only <code>min=0.1</code>, how can I obtain both the reading and saving procedure ? I am noob in python so maybe I lack of basics.</p> <p>Many thanks</p>
0
2016-09-17T11:55:00Z
39,546,620
<p>One way to do it is to store the results in an array. What to do next will depend on how your input is structured: will it always contain just four values of those types and in that order?</p> <pre><code>values = [] with open('input.dat') as f: for line in f: value = line.split('#', 1)[0] if value.isdigit(): values.append(int(value)) else: try: values.append(float(value)) except ValueError: values.append(value) </code></pre> <p>If the values always appear in that order, you can then do something like this:</p> <pre><code>n_min, n_max, name, big_number = values </code></pre> <p>(note: try to avoid naming variables <code>min</code>, <code>max</code> or other built-in keywords since that might cause problems later on!)</p>
1
2016-09-17T12:06:53Z
[ "python", "string", "file", "input" ]
Python: Save element by element from input
39,546,524
<p>I have an input file as follow</p> <pre><code>0.1 #real number 0.2 #real number Hello #string 10000 #integer number </code></pre> <p>I want to read it and use each line, before the '#' symbol, in my code. For the second part I did</p> <pre><code>with open('input.dat') as f: for line in f: line = line.split('#', 1)[0] line = line.rstrip() print(line) #test print f.close() </code></pre> <p>In this case I can read and print the number/string before the '#' symbol, but what about save them? For instance if I want to save 'Hello' in a string called 'name', '0.1' as a real called 'min' and so on. The simplest way I found, to read the input.dat file and save the elements as I want is </p> <pre><code>with open('input.dat') as f: lines = f.readlines() f.close() min=lines[2] # it print me: "0.1 #real number" </code></pre> <p>But what about only <code>min=0.1</code>, how can I obtain both the reading and saving procedure ? I am noob in python so maybe I lack of basics.</p> <p>Many thanks</p>
0
2016-09-17T11:55:00Z
39,546,631
<p>You already have all the pieces, you just need to put them in the right places:</p> <pre><code>def remove_comment(line): line = line.split('#', 1)[0] line = line.rstrip() return line with open('input.dat') as f: lines = [remove_comment(line) for line in f] # no need for this: "with" takes care of it: # f.close() min=lines[2] </code></pre>
1
2016-09-17T12:08:39Z
[ "python", "string", "file", "input" ]
Same Origin Policy violated on localhost with falcon webserver
39,546,536
<p>I am running an elm frontend via elm-reactor on <code>localhost:8000</code>. It is supposed to load json files from a <strong>falcon backend</strong> running via gunicorn on <code>localhost:8010</code>. This fails.</p> <p>The frontend is able to load static dummy files served by elm-reactor (<code>:8000</code>) but when I try to replace the dummies by the actual backend (<code>:8010</code>) it fails due to a missing header:</p> <blockquote> <p>Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at <a href="http://localhost:8010/api/sheets" rel="nofollow">http://localhost:8010/api/sheets</a>. (Reason: CORS header 'Access-Control-Allow-Origin' missing).</p> </blockquote> <p>The error message from the Firefox Inspector seems reasonably clear, but I'm at a loss how to fix that. I already installed a CORS middleware in falcon, but that didn't improve the situation at all.</p> <pre><code>from falcon_cors import CORS cors = CORS(allow_origins_list=['*']) api = falcon.API(middleware=[cors.middleware]) </code></pre> <p>I did also try to use the origins <code>'localhost:8000'</code> and <code>'localhost'</code> but neither works.</p> <p>Any idea how to fix this?</p>
0
2016-09-17T11:56:58Z
39,546,695
<p>It turns out that falcon_cors offers <code>allow_all_origins=True</code> as a parameter. This fixes my problem, but isn't a perfect solution.</p> <p>When using POST requests as well <code>allow_all_methods=True</code> should be set as well.</p>
0
2016-09-17T12:15:56Z
[ "python", "web-services", "cross-domain", "elm", "falconframework" ]
IndexError: invalid index to scalar variable for double and if 'for' statement
39,546,560
<p>My main aim is to print out the values of one variable which is in a double <code>for loop</code> and under an <code>if-statement</code>but however I tend to get an error <code>IndexError: invalid index to scalar variable.</code> Here is my codes</p> <pre><code>import numpy as np nR = 133 nP = 255 Pmin = 0.09 Pmax = 20.0 dTime = 0.005 g = np.zeros((nR+1, nP+1), dtype=np.float64) E01 = np.zeros(nR+1) LnP = np.zeros(nP+1) n = nR - 1 l = nP - 1 LnPmax = np.log(Pmax) LnPmin = np.log(Pmin) dLnP = (LnPmax - LnPmin)/(l-1) odt = 1/dTime for i in range(1, n): T1 = E01[i]*dTime for k in range(1, l): LnPa = T1 + LnP[k] ka = int((LnPa - LnPmin)/dLnP + 1) if LnPa &lt;= LnPmin: ha = 0.0 elif LnPa &gt;= LnPmax: ha = 0.0 else: ha = g[i][ka] + (g[i][ka+1] - g[i][ka])*(LnPa - LnPa[ka])/dLnP print ha </code></pre> <p>whenever i try to <code>print ha</code> I get an error <code>IndexError: invalid index to scalar variable</code>, I have looked up to other solution on <code>stackoverflow</code> and <code>google</code> but it was to no avail perhaps anyone could help me, I will appreciate <code>:)</code></p>
0
2016-09-17T11:59:42Z
39,547,432
<p>In your next-to-last line, you have the sub-expression</p> <pre><code>LnPa - LnPa[ka] </code></pre> <p>That first reference to <code>LnPa</code> is fine, since that is a float variable, but the second is not. You are trying to treat that float variable as a list or some-such with <code>LnPa[ka]</code>, by indexing it with <code>ka</code>. I do not know what you intend (you really need to add comments and make your variable names more descriptive), so I can't recommend a particular correction. But somehow get rid of <code>LnPa[ka]</code>.</p> <p>Also, the last line <code>print ha</code> does not work in python 3.x. If you replace it with</p> <pre><code>print(ha) </code></pre> <p>it will work in any version of python.</p>
0
2016-09-17T13:34:50Z
[ "python", "numpy", "if-statement", "for-loop" ]
Copy a flat numpy array to an given attribute of an np.array of objects
39,546,562
<p>Can I copy a 1D numpy array to an given attribute of an np.array of objects without using a for loop? For filling the "percentage" property of all PlotInputGridData objects in objarray with the "dist" array, i use something like this:</p> <pre><code>import numpy as np class PlotInputGridData(object): def __init__(self): self.rangemin = 0 self.rangemax = 0 self.rangelabel = '' self.percentage = 0 self.number = 0 objarray = np.arange(6, dtype=PlotInputGridData) for i in range(objarray.size): t = PlotInputGridData() objarray[i] = t dist = np.array([52, 26, 12, 6, 3, 1], dtype=np.int) for i in range(dist.size): objarray[i].percentage = dist[i] </code></pre> <p>i need to do</p> <ul> <li>objarray[0].percentage= dist[0] </li> <li>objarray[1].percentage= dist[1] </li> <li>... and so on</li> </ul> <p>is there any way of copying dist[] to objarray[].percentage in a more concise way without the for loop on the last 2 lines? </p>
0
2016-09-17T11:59:57Z
39,547,521
<p>I don't think there is a way to do that assignment without a for-loop.</p> <p>You could do it if you used a <a href="http://docs.scipy.org/doc/numpy/user/basics.rec.html" rel="nofollow">structured array</a> instead of an array of objects. The class <code>PlotInputGridData</code> is just a few fields, so the data it holds is easily represented as a structured data type instead of a Python class.</p> <p>For example,</p> <pre><code>In [15]: grid_data_type = np.dtype([('rangemin', float), ...: ('rangemax', float), ...: ('rangelabel', 'S16'), ...: ('percentage', float), ...: ('number', int)]) </code></pre> <p><code>grid_data_type</code> is a structured data type with five fields. (Change the types of the individual fields as needed.) This data type can be used as the <code>dtype</code> of a numpy array:</p> <pre><code>In [16]: a = np.zeros(6, dtype=grid_data_dtype) In [17]: dist = np.array([52, 26, 12, 6, 3, 1]) </code></pre> <p>The following assigns the array <code>dist</code> to the <code>'percentage'</code> field:</p> <pre><code>In [18]: a['percentage'] = dist </code></pre> <p>Take a look at <code>a</code>:</p> <pre><code>In [19]: a Out[19]: array([(0.0, 0.0, b'', 52.0, 0), (0.0, 0.0, b'', 26.0, 0), (0.0, 0.0, b'', 12.0, 0), (0.0, 0.0, b'', 6.0, 0), (0.0, 0.0, b'', 3.0, 0), (0.0, 0.0, b'', 1.0, 0)], dtype=[('rangemin', '&lt;f8'), ('rangemax', '&lt;f8'), ('rangelabel', 'S16'), ('percentage', '&lt;f8'), ('number', '&lt;i8')]) In [20]: a[0] Out[20]: (0.0, 0.0, b'', 52.0, 0) In [21]: a['percentage'] Out[21]: array([ 52., 26., 12., 6., 3., 1.]) </code></pre>
3
2016-09-17T13:44:24Z
[ "python", "arrays", "numpy" ]
run pygame with phycharm
39,546,646
<p>I try to run pygame in Pycharm. The editor show the library. But if I run the program I get an error that it can't find the module: pygame.</p> <p>I am running python 3.5</p> <p>I added a picutre: <a href="http://i.stack.imgur.com/brTCS.png" rel="nofollow"><img src="http://i.stack.imgur.com/brTCS.png" alt="enter image description here"></a></p> <p>I try it like this:</p> <p><a href="http://i.stack.imgur.com/466Yc.png" rel="nofollow"><img src="http://i.stack.imgur.com/466Yc.png" alt="enter image description here"></a></p> <p>Thank you</p> <p>oke, I have done that.See:</p> <p><a href="http://i.stack.imgur.com/w0KjO.png" rel="nofollow"><img src="http://i.stack.imgur.com/w0KjO.png" alt="enter image description here"></a></p> <p>So I run again the program:</p> <p>see image: <a href="http://i.stack.imgur.com/JV1Nx.png" rel="nofollow"><img src="http://i.stack.imgur.com/JV1Nx.png" alt="enter image description here"></a></p> <p>ok. I am using python: Python 3.4.4.</p> <p>but if I do this:</p> <p>pip3 install pygame. I get this warning:</p> <p><a href="http://i.stack.imgur.com/rS2j3.png" rel="nofollow"><img src="http://i.stack.imgur.com/rS2j3.png" alt="enter image description here"></a></p> <p>see image: <a href="http://i.stack.imgur.com/vAUmi.png" rel="nofollow"><img src="http://i.stack.imgur.com/vAUmi.png" alt="enter image description here"></a></p>
0
2016-09-17T12:10:44Z
39,546,688
<p>then install <code>pygame</code>:</p> <pre><code>pip install pygame </code></pre> <p>or:</p> <pre><code>python -m pip install pygame </code></pre> <p>or from code:</p> <pre><code>import pip pip.main(['install', 'pygame']) </code></pre>
1
2016-09-17T12:15:24Z
[ "python", "python-3.x" ]
run pygame with phycharm
39,546,646
<p>I try to run pygame in Pycharm. The editor show the library. But if I run the program I get an error that it can't find the module: pygame.</p> <p>I am running python 3.5</p> <p>I added a picutre: <a href="http://i.stack.imgur.com/brTCS.png" rel="nofollow"><img src="http://i.stack.imgur.com/brTCS.png" alt="enter image description here"></a></p> <p>I try it like this:</p> <p><a href="http://i.stack.imgur.com/466Yc.png" rel="nofollow"><img src="http://i.stack.imgur.com/466Yc.png" alt="enter image description here"></a></p> <p>Thank you</p> <p>oke, I have done that.See:</p> <p><a href="http://i.stack.imgur.com/w0KjO.png" rel="nofollow"><img src="http://i.stack.imgur.com/w0KjO.png" alt="enter image description here"></a></p> <p>So I run again the program:</p> <p>see image: <a href="http://i.stack.imgur.com/JV1Nx.png" rel="nofollow"><img src="http://i.stack.imgur.com/JV1Nx.png" alt="enter image description here"></a></p> <p>ok. I am using python: Python 3.4.4.</p> <p>but if I do this:</p> <p>pip3 install pygame. I get this warning:</p> <p><a href="http://i.stack.imgur.com/rS2j3.png" rel="nofollow"><img src="http://i.stack.imgur.com/rS2j3.png" alt="enter image description here"></a></p> <p>see image: <a href="http://i.stack.imgur.com/vAUmi.png" rel="nofollow"><img src="http://i.stack.imgur.com/vAUmi.png" alt="enter image description here"></a></p>
0
2016-09-17T12:10:44Z
39,546,877
<ol> <li><p>You do not have the PyGame module and even PyCharm suggests it for you.</p></li> <li><p>You do not run pip inside the python IDE. In order to do install a module with pip you have to open the command line and directly run</p> <p><code>Pip install PyGame</code></p></li> </ol> <p>Or</p> <pre><code>Python -m pip install pygame </code></pre> <ol start="3"> <li><p>Based on previous answer on a question like yours: Are you sure you have got pygame for Python 3.5? The version for 3.5 wont work and produce this error msg, because the pyd file wont find the python 3.5 dll.</p> <p>EDIT: since you are installing for python2.7 USE PIP3 to install</p> <p><code>pip3 install pygame</code></p></li> <li><p>Since pygame's pip page is rarely downloaded I suggest you download the module from BitBucket avaivable <a href="https://bitbucket.org/pygame/pygame/downloads" rel="nofollow">here</a>.</p></li> </ol>
0
2016-09-17T12:35:14Z
[ "python", "python-3.x" ]
Django models, adding new value, migrations
39,546,734
<p>I worked with django 1.9 and added a new field (creation_date) to myapp/models.py. After that I run "python manage.py makemigrations". I got: </p> <blockquote> <p>Please select a fix:</p> <ol> <li>Provide a one-off default now (will be set on all existing rows)</li> <li>Quit, and let me add a default in models.py."</li> </ol> </blockquote> <p>I choose 1-st option and added value in wrong format '10.07.2016'. After this mistake I couldn't run "python manage.py migrate".</p> <p>So I decided to change models.py and add a default value "datetime.now". But after that I still have problems with "python manage.py makemigrations". I see such things like that:</p> <blockquote> <p>django.core.exceptions.ValidationError: [u"'10.07.2016' value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."]</p> </blockquote> <p>How to solve this problem?</p>
1
2016-09-17T12:18:54Z
39,547,167
<p>As long as your migration isn't applied to the database you can manually update your migration file located in <code>myapp/migrations/*.py</code>. Find the string '10.07.2016' and update it to a supported format.</p> <p>A less attractive solution would be to delete the old migration file (as long as it isn't apllied to the database) and create a new migrations file with <code>python manage.py makemigrations</code>. Because you've updated the model to use a default value it won't ask for a one-off default this time.</p> <p>To check whether a migration is applied to the database run: <code>python manage.py showmigrations</code>.</p>
1
2016-09-17T13:05:51Z
[ "python", "django", "django-models", "django-migrations" ]
pandas: error on DataFrame.unstack
39,546,975
<p>I wrote the following function to convert several columns of a dataframe into numeric values:</p> <pre><code>def factorizeMany(data, columns): """ Factorize a bunch of columns in a data frame""" data[columns] = data[columns].stack().rank(method='dense').unstack() return data </code></pre> <p>Calling it like this</p> <pre><code>trainDataPre = factorizeMany(trainDataMerged.fillna(0), columns=["char_{0}".format(i) for i in range(1,10)]) </code></pre> <p>gives me an error. I don't know where to look for the cause, possibly wrong input?</p> <pre><code>--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) &lt;ipython-input-14-357f8a4b2ef8&gt; in &lt;module&gt;() 1 #trainDataPre = trainDataMerged.drop(["people_id", "activity_id", "date"], axis=1) 2 #trainDataPre = trainDataMerged.fillna(0) ----&gt; 3 trainDataPre = mininggear.factorizeMany(trainDataMerged.fillna(0), columns=["char_{0}".format(i) for i in range(1,10)]) /Users/cls/Dropbox/Datengräber/Kaggle/RedHat/mininggear.py in factorizeMany(data, columns) 15 def factorizeMany(data, columns): 16 """ Factorize a bunch of columns in a data frame""" ---&gt; 17 data[columns] = data[columns].stack().rank(method='dense').unstack() 18 return data 19 /usr/local/lib/python3.5/site-packages/pandas/core/series.py in unstack(self, level, fill_value) 2041 """ 2042 from pandas.core.reshape import unstack -&gt; 2043 return unstack(self, level, fill_value) 2044 2045 # ---------------------------------------------------------------------- /usr/local/lib/python3.5/site-packages/pandas/core/reshape.py in unstack(obj, level, fill_value) 405 else: 406 unstacker = _Unstacker(obj.values, obj.index, level=level, --&gt; 407 fill_value=fill_value) 408 return unstacker.get_result() 409 /usr/local/lib/python3.5/site-packages/pandas/core/reshape.py in __init__(self, values, index, level, value_columns, fill_value) 90 91 # when index includes `nan`, need to lift levels/strides by 1 ---&gt; 92 self.lift = 1 if -1 in self.index.labels[self.level] else 0 93 94 self.new_index_levels = list(index.levels) AttributeError: 'Index' object has no attribute 'labels' </code></pre>
2
2016-09-17T12:45:15Z
39,548,611
<p>The error is due to the fact that you are trying to perform the <code>rank</code> operation on the subset of the dataframe containing both numerical and categorical/string values by filling the <code>NaN's</code> in the dataframe with 0 and calling that function.</p> <p>Consider this case:</p> <pre><code>df = pd.DataFrame({'char_1': ['cat', 'dog', 'buffalo', 'cat'], 'char_2': ['mouse', 'tiger', 'lion', 'mouse'], 'char_3': ['giraffe', np.NaN, 'cat', np.NaN]}) df </code></pre> <p><a href="http://i.stack.imgur.com/R1OPY.png" rel="nofollow"><img src="http://i.stack.imgur.com/R1OPY.png" alt="Image"></a></p> <pre><code>df = df.fillna(0) df[['char_3']].stack().rank() Series([], dtype: float64) </code></pre> <p>So, you are basically performing the <code>unstack</code> operation on an empty series which is not what you wanted to do after all.</p> <p>Better is to do this way to avoid further complications:</p> <pre><code>def factorizeMany(data, columns): """ Factorize a bunch of columns in a data frame""" stacked = data[columns].stack(dropna=False) data[columns] = pandas.Series(stacked.factorize()[0], index=stacked.index).unstack() return data </code></pre>
1
2016-09-17T15:35:36Z
[ "python", "pandas", "dataframe" ]
Python parse string containing functions, lists and dicts
39,547,056
<p>I'm trying to find way to parse string that can contain variable, function, list, or dict written in python syntax separated with ",". Whitespace should be usable anywhere, so split with "," when its not inside (), [] or {}.</p> <p>Example string: <code>"variable, function1(1,3), function2([1,3],2), ['list_item_1','list_item_2'],{'dict_key_1': "dict_item_1"}"</code></p> <p>Another example string: <code>"variable,function1(1, 3) , function2( [1,3],2), ['list_item_1','list_item_2'],{'dict_key_1': "dict_item_1"}"</code></p> <p>Example output <code>["variable", "function1(1,3)", "function2([1,3],2)", "['list_item_1','list_item_2']", "{'dict_key_1': "dict_item_1"}"]</code></p> <p>edit: Reason for the code is to parse string an then run it with <code>exec("var = &amp;s" % list[x])</code>. (yes i know this might not be recommended way to do stuff)</p>
3
2016-09-17T12:54:49Z
39,547,094
<p>Have you tried using split?</p> <pre><code>&gt;&gt;&gt; teststring = "variable, function1(1,3), function2([1,3],2), ['list_item_1','list_item_2'],{'dict_key_1': 'dict_item_1'}" &gt;&gt;&gt; teststring.split(", ") ['variable', 'function1(1,3)', 'function2([1,3],2)', "['list_item_1','list_item_2'],{'dict_key_1': 'dict_item_1'}"] </code></pre>
0
2016-09-17T12:57:46Z
[ "python", "regex", "string-parsing" ]
Python parse string containing functions, lists and dicts
39,547,056
<p>I'm trying to find way to parse string that can contain variable, function, list, or dict written in python syntax separated with ",". Whitespace should be usable anywhere, so split with "," when its not inside (), [] or {}.</p> <p>Example string: <code>"variable, function1(1,3), function2([1,3],2), ['list_item_1','list_item_2'],{'dict_key_1': "dict_item_1"}"</code></p> <p>Another example string: <code>"variable,function1(1, 3) , function2( [1,3],2), ['list_item_1','list_item_2'],{'dict_key_1': "dict_item_1"}"</code></p> <p>Example output <code>["variable", "function1(1,3)", "function2([1,3],2)", "['list_item_1','list_item_2']", "{'dict_key_1': "dict_item_1"}"]</code></p> <p>edit: Reason for the code is to parse string an then run it with <code>exec("var = &amp;s" % list[x])</code>. (yes i know this might not be recommended way to do stuff)</p>
3
2016-09-17T12:54:49Z
39,547,196
<p>Regular expressions aren't very good for parsing the complexity of arbitrary code. What exactly are you trying to accomplish? You can (unsafely) use <code>eval</code> to just evaluate the string as code. Or if you're trying to understand it without <code>eval</code>ing it, you can use <a href="https://docs.python.org/3/library/ast.html" rel="nofollow">the <code>ast</code></a> or <a href="https://docs.python.org/3/library/dis.html" rel="nofollow"><code>dis</code> modules</a> for various forms of inspection.</p>
0
2016-09-17T13:08:50Z
[ "python", "regex", "string-parsing" ]
Python parse string containing functions, lists and dicts
39,547,056
<p>I'm trying to find way to parse string that can contain variable, function, list, or dict written in python syntax separated with ",". Whitespace should be usable anywhere, so split with "," when its not inside (), [] or {}.</p> <p>Example string: <code>"variable, function1(1,3), function2([1,3],2), ['list_item_1','list_item_2'],{'dict_key_1': "dict_item_1"}"</code></p> <p>Another example string: <code>"variable,function1(1, 3) , function2( [1,3],2), ['list_item_1','list_item_2'],{'dict_key_1': "dict_item_1"}"</code></p> <p>Example output <code>["variable", "function1(1,3)", "function2([1,3],2)", "['list_item_1','list_item_2']", "{'dict_key_1': "dict_item_1"}"]</code></p> <p>edit: Reason for the code is to parse string an then run it with <code>exec("var = &amp;s" % list[x])</code>. (yes i know this might not be recommended way to do stuff)</p>
3
2016-09-17T12:54:49Z
39,547,420
<p>I guess the main problem here is that the arrays and dicts also have commas in them, so just using <code>str.split(",")</code> wouldn't work. One way of doing it is to parse the string one character at a time, and keep track of whether all brackets are closed. If they are, we can append the current result to an array when we come across a comma. Here's my attempt:</p> <pre><code>s = "variable, function1(1,3),function2([1,3],2),['list_item_1','list_item_2'],{'dict_key_1': 'dict_item_1'}" tokens = [] current = "" open_brackets = 0 for char in s: current += char if char in "({[": open_brackets += 1 elif char in ")}]": open_brackets -= 1 elif (char == ",") and (open_brackets == 0): tokens.append(current[:-1].strip()) current = "" tokens.append(current) for t in tokens: print(t) """ variable function1(1,3) function2([1,3],2) ['list_item_1','list_item_2'] {'dict_key_1': 'dict_item_1'} """ </code></pre>
2
2016-09-17T13:33:26Z
[ "python", "regex", "string-parsing" ]
Can variables in a function for later use?
39,547,150
<p>Can Python store variables in a function for later use?</p> <p>This is a stat calculator below (unfinished):</p> <pre><code>#Statistics Calculator import random def main(mod): print '' if (mod == '1'): print 'Mode 1 activated' dat_entry = dat() elif (mod == '2'): print 'Mode 2 activated' array = rndom(dat_entry) elif (mod == '3'): print 'Mode 3 activated' array = user_input(dat_entry) elif (mod == '4'): disp(array) elif (mod == '5'): mean = mean(array) elif (mod == '6'): var = var(array) elif (mod == '7'): sd = sd(array, var) elif (mod == '8'): rang(array) elif (mod == '9'): median(array) elif (mod == '10'): mode(array) elif (mod == '11'): trim(array) print '' def dat(): dat = input('Please enter the number of data entries. ') return dat def rndom(dat_entry): print 'This mode allows the computer to generate the data entries.' print 'It ranges from 1 to 100.' cntr = 0 for cntr in range(cntr): array[cntr] = random.randint(1,100) print 'Generating Data Entry', cntr + 1 def rndom(dat_entry): print 'This mode allows you to enter the data.' cntr = 0 for cntr in range(cntr): array[cntr] = input('Please input the value of Data Entry ', cntr + 1, ': ') run = 0 #Number of runs mod = '' #Mode cont = 'T' while (cont == 'T'): print 'Statistics Calculator' print 'This app can:' print '1. Set the number of data entries.' print '2. Randomly generate numbers from 1 to 100.' print '3. Ask input from you, the user.' print '4. Display array.' print '5. Compute mean.' print '6. Compute variance.' print '7. Compute standard deviation.' print '8. Compute range.' print '9. Compute median.' print '10. Compute mode.' print '11. Compute trimmed mean.' print '' if (run == 0): print 'You need to use Mode 1 first.' mod = '1' elif (run == 1): while (mod != '2' or mod != '3'): print 'Please enter Mode 2 or 3 only.' mod = raw_input('Please enter the mode to use (2 or 3): ') if (mod == '2' or mod == '3'): break elif (run &gt; 1): mod = raw_input('Please enter the mode to use (1-11): ') # Error line main(mod) cont = raw_input("Please enter 'T' if and only if you want to continue" " using this app. ") run += 1 print '' </code></pre> <p>This line here is the output (trimmed): Mode 2 activated</p> <pre class="lang-none prettyprint-override"><code>Traceback (most recent call last): File "F:\Com SciActivities\Statistics.py", line 81, in &lt;module&gt; main(mod) File "F:\Com Sci Activities\Statistics.py", line 10, in main array = rndom(dat_entry) UnboundLocalError: local variable 'dat_entry' referenced before assignment </code></pre> <p>Please tell me the reason why...</p>
0
2016-09-17T13:03:56Z
39,547,253
<p>There's a problem with the logic. If you go straight to mode 2 this is what will cause this error because "dat_entry" would be undefined.</p> <p>You've selected mode 2, at this point it doesn't know what dat_entry is:</p> <pre><code>elif (mod == '2'): print 'Mode 2 activated' array = rndom(dat_entry) </code></pre> <p>You should declare dat_entry somewhere in your main loop or somewhere here once the user has selected option 2:</p> <pre><code> if (mod == '2' or mod == '3'): break </code></pre>
0
2016-09-17T13:15:41Z
[ "python" ]
Can variables in a function for later use?
39,547,150
<p>Can Python store variables in a function for later use?</p> <p>This is a stat calculator below (unfinished):</p> <pre><code>#Statistics Calculator import random def main(mod): print '' if (mod == '1'): print 'Mode 1 activated' dat_entry = dat() elif (mod == '2'): print 'Mode 2 activated' array = rndom(dat_entry) elif (mod == '3'): print 'Mode 3 activated' array = user_input(dat_entry) elif (mod == '4'): disp(array) elif (mod == '5'): mean = mean(array) elif (mod == '6'): var = var(array) elif (mod == '7'): sd = sd(array, var) elif (mod == '8'): rang(array) elif (mod == '9'): median(array) elif (mod == '10'): mode(array) elif (mod == '11'): trim(array) print '' def dat(): dat = input('Please enter the number of data entries. ') return dat def rndom(dat_entry): print 'This mode allows the computer to generate the data entries.' print 'It ranges from 1 to 100.' cntr = 0 for cntr in range(cntr): array[cntr] = random.randint(1,100) print 'Generating Data Entry', cntr + 1 def rndom(dat_entry): print 'This mode allows you to enter the data.' cntr = 0 for cntr in range(cntr): array[cntr] = input('Please input the value of Data Entry ', cntr + 1, ': ') run = 0 #Number of runs mod = '' #Mode cont = 'T' while (cont == 'T'): print 'Statistics Calculator' print 'This app can:' print '1. Set the number of data entries.' print '2. Randomly generate numbers from 1 to 100.' print '3. Ask input from you, the user.' print '4. Display array.' print '5. Compute mean.' print '6. Compute variance.' print '7. Compute standard deviation.' print '8. Compute range.' print '9. Compute median.' print '10. Compute mode.' print '11. Compute trimmed mean.' print '' if (run == 0): print 'You need to use Mode 1 first.' mod = '1' elif (run == 1): while (mod != '2' or mod != '3'): print 'Please enter Mode 2 or 3 only.' mod = raw_input('Please enter the mode to use (2 or 3): ') if (mod == '2' or mod == '3'): break elif (run &gt; 1): mod = raw_input('Please enter the mode to use (1-11): ') # Error line main(mod) cont = raw_input("Please enter 'T' if and only if you want to continue" " using this app. ") run += 1 print '' </code></pre> <p>This line here is the output (trimmed): Mode 2 activated</p> <pre class="lang-none prettyprint-override"><code>Traceback (most recent call last): File "F:\Com SciActivities\Statistics.py", line 81, in &lt;module&gt; main(mod) File "F:\Com Sci Activities\Statistics.py", line 10, in main array = rndom(dat_entry) UnboundLocalError: local variable 'dat_entry' referenced before assignment </code></pre> <p>Please tell me the reason why...</p>
0
2016-09-17T13:03:56Z
39,547,645
<p>This part of the code is problematic. <code> elif (mod == '2'): print 'Mode 2 activated' array = rndom(dat_entry) </code> </p> <p>Python does not know what 'dat_entry' is in rndom(dat_entry) because it has not yet been assigned previously in the function, that's why it's throwing an error.</p> <p>I checked your rndom(dat_entry) function, but I see that 'dat_entry' is not used anywhere within it. So this is what I suggest. You can replace <code> def rndom(dat_entry): </code> with: <code> def rndom(): </code> Maybe that would fix that part of code.</p>
0
2016-09-17T13:58:04Z
[ "python" ]
Can variables in a function for later use?
39,547,150
<p>Can Python store variables in a function for later use?</p> <p>This is a stat calculator below (unfinished):</p> <pre><code>#Statistics Calculator import random def main(mod): print '' if (mod == '1'): print 'Mode 1 activated' dat_entry = dat() elif (mod == '2'): print 'Mode 2 activated' array = rndom(dat_entry) elif (mod == '3'): print 'Mode 3 activated' array = user_input(dat_entry) elif (mod == '4'): disp(array) elif (mod == '5'): mean = mean(array) elif (mod == '6'): var = var(array) elif (mod == '7'): sd = sd(array, var) elif (mod == '8'): rang(array) elif (mod == '9'): median(array) elif (mod == '10'): mode(array) elif (mod == '11'): trim(array) print '' def dat(): dat = input('Please enter the number of data entries. ') return dat def rndom(dat_entry): print 'This mode allows the computer to generate the data entries.' print 'It ranges from 1 to 100.' cntr = 0 for cntr in range(cntr): array[cntr] = random.randint(1,100) print 'Generating Data Entry', cntr + 1 def rndom(dat_entry): print 'This mode allows you to enter the data.' cntr = 0 for cntr in range(cntr): array[cntr] = input('Please input the value of Data Entry ', cntr + 1, ': ') run = 0 #Number of runs mod = '' #Mode cont = 'T' while (cont == 'T'): print 'Statistics Calculator' print 'This app can:' print '1. Set the number of data entries.' print '2. Randomly generate numbers from 1 to 100.' print '3. Ask input from you, the user.' print '4. Display array.' print '5. Compute mean.' print '6. Compute variance.' print '7. Compute standard deviation.' print '8. Compute range.' print '9. Compute median.' print '10. Compute mode.' print '11. Compute trimmed mean.' print '' if (run == 0): print 'You need to use Mode 1 first.' mod = '1' elif (run == 1): while (mod != '2' or mod != '3'): print 'Please enter Mode 2 or 3 only.' mod = raw_input('Please enter the mode to use (2 or 3): ') if (mod == '2' or mod == '3'): break elif (run &gt; 1): mod = raw_input('Please enter the mode to use (1-11): ') # Error line main(mod) cont = raw_input("Please enter 'T' if and only if you want to continue" " using this app. ") run += 1 print '' </code></pre> <p>This line here is the output (trimmed): Mode 2 activated</p> <pre class="lang-none prettyprint-override"><code>Traceback (most recent call last): File "F:\Com SciActivities\Statistics.py", line 81, in &lt;module&gt; main(mod) File "F:\Com Sci Activities\Statistics.py", line 10, in main array = rndom(dat_entry) UnboundLocalError: local variable 'dat_entry' referenced before assignment </code></pre> <p>Please tell me the reason why...</p>
0
2016-09-17T13:03:56Z
39,547,725
<p>If the first <code>if</code> condition is not satisfied, it wont execute the block of codes associated with it. Since the first <code>if</code> condition is not satisfied, the assignment <code>dat_entry = dat()</code> will not execute.</p> <p>So, in your case you can do the do it as follows:</p> <pre><code>elif (mod == '2'): print 'Mode 2 activated' array = rndom(dat()) elif (mod == '3'): print 'Mode 3 activated' array = user_input(dat()) </code></pre> <p>Kindly let me know if you need any other clarifications.</p>
0
2016-09-17T14:06:01Z
[ "python" ]
Avoid extra line for attribute check?
39,547,201
<p>I am developing this Python project where I encounter a situation many times and I wondered if there is a better way.</p> <p>There is a list of class instances. Some part of lists are empty(filled with <code>None</code>). Here is an example list.</p> <pre><code>ins_list = [ins_1, ins_2, None, ins_3, None] </code></pre> <p>I have to do some confirmations throughout the program flow. There are points where I need the control an attribute of these instances. But only indexes are given for choosing an instance from the list and it may be one of the empty elements. Which would give an error when the attribute is called. Here is an example program flow.</p> <pre><code>ind = 2 if ins_list[ind].some_attribute == "thing": # This would give error when empty element is selected. </code></pre> <p>I deal with this by using,</p> <pre><code>if ins_list[ind]: if ins_list[ind].some_attribute == "thing": # This works </code></pre> <p>I am okay with using this. However the program is a long one, I apply this hundreds of times. Is there an easier, better way of doing this, it means I am producing reduntant code and increasing indentation level for no reason. I wish to know if there is such a solution.</p>
0
2016-09-17T13:09:17Z
39,547,331
<p>There are these two options:</p> <blockquote> <p>Using a dictionary:</p> </blockquote> <p>Another way would be to use a <code>dictionary</code> instead. So you could create your dictionary once the list is filled up with elements. The dictionary's keys would be the values of your list and as values you could use the attributes of the elements that are not None and "No_attr" for those that are None. (<strong>Note:</strong> Have in mind that python dictionaries don't support duplicate keys and that's why I propose below to store as keys your list indexes else you will have to find a way to make keys be different)</p> <p>For example for a list like:</p> <pre><code>l = [item1,item2,None,item4] </code></pre> <p>You could create a dictionary:</p> <pre><code>d = {item1:"thing1", item2:"thing2", None:"No_attr", item3:"thing3"} </code></pre> <p>So in this way every time you would need to make a check, you wouldn't have to check two conditions, but you could check only the value, such as:</p> <pre><code>if d.values()[your_index]=="thing": </code></pre> <p>The only <strong>cons</strong> of this method is that standard python dictionaries are <strong>inherently unordered</strong>, which makes accessing dictionary values by index a bit dangerous sometimes - you have to be careful not to change the form-arrangement of the dictionary. </p> <p>Now, if you want to make sure that the <strong>index stays stable</strong>, then you would have to store it some way, for example select as <strong>keys</strong> of your dictionary the indexes, as you will have already stored the attributes of the items - <strong>But</strong> that is something that you will have to decide and depends strongly on the architecture of your project.</p> <blockquote> <p>Using a list:</p> </blockquote> <p>In using <code>list</code>s way I don't think there is a way to avoid your if statement - and is not bad actually. Maybe use an <code>and</code> operator as it is mentioned already in another answer but I don't think that makes any difference anyway.</p> <p><strong>Also</strong>, if you want to use your first approach: <code>if ins_list[ind].some_attribute == "thing":</code></p> <p>You could try using and exception catcher like this:</p> <pre><code>try: if ins_list[ind].some_attribute == "thing": #do something except: #an error occured pass </code></pre>
0
2016-09-17T13:24:28Z
[ "python", "attributes" ]
Avoid extra line for attribute check?
39,547,201
<p>I am developing this Python project where I encounter a situation many times and I wondered if there is a better way.</p> <p>There is a list of class instances. Some part of lists are empty(filled with <code>None</code>). Here is an example list.</p> <pre><code>ins_list = [ins_1, ins_2, None, ins_3, None] </code></pre> <p>I have to do some confirmations throughout the program flow. There are points where I need the control an attribute of these instances. But only indexes are given for choosing an instance from the list and it may be one of the empty elements. Which would give an error when the attribute is called. Here is an example program flow.</p> <pre><code>ind = 2 if ins_list[ind].some_attribute == "thing": # This would give error when empty element is selected. </code></pre> <p>I deal with this by using,</p> <pre><code>if ins_list[ind]: if ins_list[ind].some_attribute == "thing": # This works </code></pre> <p>I am okay with using this. However the program is a long one, I apply this hundreds of times. Is there an easier, better way of doing this, it means I am producing reduntant code and increasing indentation level for no reason. I wish to know if there is such a solution.</p>
0
2016-09-17T13:09:17Z
39,547,333
<p>Use a boolean operator <a href="https://docs.python.org/3.5/reference/expressions.html#and" rel="nofollow"><code>and</code></a>.</p> <pre><code>if ins_list[ind] and ins_list[ind].some_attribute == "thing": # Code </code></pre>
0
2016-09-17T13:24:35Z
[ "python", "attributes" ]
Avoid extra line for attribute check?
39,547,201
<p>I am developing this Python project where I encounter a situation many times and I wondered if there is a better way.</p> <p>There is a list of class instances. Some part of lists are empty(filled with <code>None</code>). Here is an example list.</p> <pre><code>ins_list = [ins_1, ins_2, None, ins_3, None] </code></pre> <p>I have to do some confirmations throughout the program flow. There are points where I need the control an attribute of these instances. But only indexes are given for choosing an instance from the list and it may be one of the empty elements. Which would give an error when the attribute is called. Here is an example program flow.</p> <pre><code>ind = 2 if ins_list[ind].some_attribute == "thing": # This would give error when empty element is selected. </code></pre> <p>I deal with this by using,</p> <pre><code>if ins_list[ind]: if ins_list[ind].some_attribute == "thing": # This works </code></pre> <p>I am okay with using this. However the program is a long one, I apply this hundreds of times. Is there an easier, better way of doing this, it means I am producing reduntant code and increasing indentation level for no reason. I wish to know if there is such a solution.</p>
0
2016-09-17T13:09:17Z
39,547,395
<p>As coder proposed, you can remove None from your list, or use dictionaries instead, to avoid to have to create an entry for each index.</p> <p>I want to propose another way: you can create a dummyclass and replace None by it. This way there will be no error if you set an attribute:</p> <pre><code>class dummy: def __nonzero__(self): return False def __setattr__(self, k, v): return mydummy = dummy() mylist = [ins_1, ins_2, mydummy, ins_3, mydummy] </code></pre> <p>nothing will be stored to the dummyinstances when setting an attribute</p> <p><strong>edit:</strong></p> <p>If the content of the original list cannot be chosen, then this class could help:</p> <pre><code>class PickyList(list): def __init__(self, iterable, dummyval): self.dummy = dummyval return super(PickyList, self).__init__(iterable) def __getitem__(self, k): v = super(PickyList, self).__getitem__(k) return (self.dummy if v is None else v) mylist = PickyList(ins_list, mydummy) </code></pre>
0
2016-09-17T13:30:51Z
[ "python", "attributes" ]
Avoid extra line for attribute check?
39,547,201
<p>I am developing this Python project where I encounter a situation many times and I wondered if there is a better way.</p> <p>There is a list of class instances. Some part of lists are empty(filled with <code>None</code>). Here is an example list.</p> <pre><code>ins_list = [ins_1, ins_2, None, ins_3, None] </code></pre> <p>I have to do some confirmations throughout the program flow. There are points where I need the control an attribute of these instances. But only indexes are given for choosing an instance from the list and it may be one of the empty elements. Which would give an error when the attribute is called. Here is an example program flow.</p> <pre><code>ind = 2 if ins_list[ind].some_attribute == "thing": # This would give error when empty element is selected. </code></pre> <p>I deal with this by using,</p> <pre><code>if ins_list[ind]: if ins_list[ind].some_attribute == "thing": # This works </code></pre> <p>I am okay with using this. However the program is a long one, I apply this hundreds of times. Is there an easier, better way of doing this, it means I am producing reduntant code and increasing indentation level for no reason. I wish to know if there is such a solution.</p>
0
2016-09-17T13:09:17Z
39,548,821
<p>In this case I would use an try-except statement because of <a href="https://docs.python.org/2/glossary.html" rel="nofollow">EAFP</a> <em>(easier to ask for forgivness than permission)</em>. It won't shorten yout code but it's a more Pythonic way to code when checking for valid attributes. This way you won't break against DRY <em>(Don't Repat Yourself)</em> either.</p> <pre><code>try: if ins_list[ind].some_attribute == "thing": # do_something() except AttributeError: # do_something_else() </code></pre>
0
2016-09-17T15:57:05Z
[ "python", "attributes" ]
Django REST Framework Swagger - Authentication Error
39,547,208
<p>I followed the instructions <a href="http://django-rest-swagger.readthedocs.io/en/latest/" rel="nofollow">in the docs</a>. So here's my view:</p> <pre><code>from rest_framework.decorators import api_view, renderer_classes from rest_framework import response, schemas from rest_framework_swagger.renderers import OpenAPIRenderer, SwaggerUIRenderer @api_view() @renderer_classes([OpenAPIRenderer, SwaggerUIRenderer]) def schema_view(request): generator = schemas.SchemaGenerator(title='Bookings API') return response.Response(generator.get_schema(request=request)) </code></pre> <p>And I added the following to my <code>urls.py</code>:</p> <pre><code>url(r'^docs/', views.schema_view), </code></pre> <p>When I went to the <code>/docs/</code> page of my project, I got the following error:</p> <pre><code>401 : {"detail": "Authentication credentials were not provided."} http://127.0.0.1:8000/docs/?format=openapi </code></pre> <p>In the browser console I got this message:</p> <pre><code>Unable to Load SwaggerUI init.js (line 57) </code></pre> <p>When I set the <code>permission_classes</code> of my <code>schema_view</code> to <code>AllowAny</code>, I was able to view my api docs. However, I'm not sure if this is the right way of doing this. Isn't there a way to login as an admin, or any other user to view the docs. Also, how do I provide the auth tokens when viewing this in the browser? Maybe I missed something in the docs.</p>
1
2016-09-17T13:10:39Z
39,547,632
<blockquote> <p>Isn't there a way to login as an admin, or any other user to view the docs.</p> </blockquote> <p>If your only use token authentication, first <a href="http://www.django-rest-framework.org/api-guide/authentication/#tokenauthentication" rel="nofollow">create tokens for your users</a>, then access the resources by setting the header</p> <pre><code>curl -X GET http://127.0.0.1:8000/api/example/ -H 'Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b' </code></pre>
1
2016-09-17T13:57:03Z
[ "python", "django", "django-rest-framework", "swagger", "swagger-ui" ]
Django REST Framework Swagger - Authentication Error
39,547,208
<p>I followed the instructions <a href="http://django-rest-swagger.readthedocs.io/en/latest/" rel="nofollow">in the docs</a>. So here's my view:</p> <pre><code>from rest_framework.decorators import api_view, renderer_classes from rest_framework import response, schemas from rest_framework_swagger.renderers import OpenAPIRenderer, SwaggerUIRenderer @api_view() @renderer_classes([OpenAPIRenderer, SwaggerUIRenderer]) def schema_view(request): generator = schemas.SchemaGenerator(title='Bookings API') return response.Response(generator.get_schema(request=request)) </code></pre> <p>And I added the following to my <code>urls.py</code>:</p> <pre><code>url(r'^docs/', views.schema_view), </code></pre> <p>When I went to the <code>/docs/</code> page of my project, I got the following error:</p> <pre><code>401 : {"detail": "Authentication credentials were not provided."} http://127.0.0.1:8000/docs/?format=openapi </code></pre> <p>In the browser console I got this message:</p> <pre><code>Unable to Load SwaggerUI init.js (line 57) </code></pre> <p>When I set the <code>permission_classes</code> of my <code>schema_view</code> to <code>AllowAny</code>, I was able to view my api docs. However, I'm not sure if this is the right way of doing this. Isn't there a way to login as an admin, or any other user to view the docs. Also, how do I provide the auth tokens when viewing this in the browser? Maybe I missed something in the docs.</p>
1
2016-09-17T13:10:39Z
39,554,754
<p>I think I've found the solution.</p> <p>In the <code>settings.py</code>, I added the following settings:</p> <pre><code>SWAGGER_SETTINGS = { 'SECURITY_DEFINITIONS': { 'api_key': { 'type': 'apiKey', 'in': 'header', 'name': 'Authorization' } }, } </code></pre> <p>Then when I load the page, I just click on the <em>Authorize</em> button at the upper right and enter this value in the <em>value</em> text field:</p> <pre><code>Token &lt;valid-token-string&gt; </code></pre> <p>However, I still needed to set the permission class of the <code>schema view</code> to <code>AllowAny</code>. The auth token just let me switch from different users, allowing me to view different set of endpoints.</p>
1
2016-09-18T06:20:02Z
[ "python", "django", "django-rest-framework", "swagger", "swagger-ui" ]
How can I continuously replace an element of an array?
39,547,219
<p>At each time step, I am trying to replace one element of my <code>list</code> with the sum of the other 2 plus 1. This is my code:</p> <pre><code>def replace(x, y, z): for i in range(3): rep_x = [y+z+1, y, z] rep_y = [x, x+z+1, z] rep_z = [x, y, x+y+1] ini_x = rep_x ini_y = rep_y ini_z = rep_z return ini_x, ini_y, ini_z print replace(2, 4, 6) </code></pre> <p>This gives me a single line - a one-time replacement. I would like the code to keep doing the replacements on the newly-obtained arrays every time, for example:</p> <p>([11, 4, 6], [2, 9, 6], [2, 4, 7]) ((11, 4, 6], [11, 18, 6], [11, 4, 16]), ([19, 9, 6], [2, 9, 6], [2, 9, 12]), ([12, 4, 7], [2, 10, 7], [2, 4, 7]))</p> <p>How can I do this?</p>
1
2016-09-17T13:11:54Z
39,547,468
<blockquote> <p>at each time step, replace one element of my array with the sum of the other 2 plus 1</p> </blockquote> <pre><code>from __future__ import print_function def business(array): # Can't give a proper name without knowing what the function does total = sum(array) return [total + 1 - x for x in array] arr = [2,4,6] steps = 10 print(arr) for step in range(steps): arr = business(arr) print(arr) </code></pre>
0
2016-09-17T13:38:15Z
[ "python", "arrays", "python-2.7" ]
How can I continuously replace an element of an array?
39,547,219
<p>At each time step, I am trying to replace one element of my <code>list</code> with the sum of the other 2 plus 1. This is my code:</p> <pre><code>def replace(x, y, z): for i in range(3): rep_x = [y+z+1, y, z] rep_y = [x, x+z+1, z] rep_z = [x, y, x+y+1] ini_x = rep_x ini_y = rep_y ini_z = rep_z return ini_x, ini_y, ini_z print replace(2, 4, 6) </code></pre> <p>This gives me a single line - a one-time replacement. I would like the code to keep doing the replacements on the newly-obtained arrays every time, for example:</p> <p>([11, 4, 6], [2, 9, 6], [2, 4, 7]) ((11, 4, 6], [11, 18, 6], [11, 4, 16]), ([19, 9, 6], [2, 9, 6], [2, 9, 12]), ([12, 4, 7], [2, 10, 7], [2, 4, 7]))</p> <p>How can I do this?</p>
1
2016-09-17T13:11:54Z
39,547,884
<p>Is this helpful:</p> <pre><code>def replace(x, y, z): ini_x = [y+z+1, y, z] ini_y = [x, x+z+1, z] ini_z = [x, y, x+y+1] return ini_x, ini_y, ini_z s = replace(2, 4, 6) print s for i in s: print replace(i[0], i[1], i[2]) </code></pre> <p>output:</p> <pre><code>([11, 4, 6], [2, 9, 6], [2, 4, 7]) ([11, 4, 6], [11, 18, 6], [11, 4, 16]) ([16, 9, 6], [2, 9, 6], [2, 9, 12]) ([12, 4, 7], [2, 10, 7], [2, 4, 7]) </code></pre>
0
2016-09-17T14:24:10Z
[ "python", "arrays", "python-2.7" ]
python django run bash script in server
39,547,220
<p>I would like to create a website-app to run a bash script located in a server. Basically I want this website for:</p> <ul> <li>Upload a file</li> <li>select some parameters</li> <li>Run a bash script taking the input file and the parameters</li> <li>Download the results</li> </ul> <p>I know you can do this with php, javascript... but I have never program in these languages. However I can program in python. I have used pyQT library in python for similar purposes. </p> <p>Can this be done with django? or should I start learning php &amp; javascript? I cannot find any tutorial for this specific task in Django.</p>
0
2016-09-17T13:11:54Z
39,548,033
<p>This can be done in Python using the Django framework. </p> <p>First create a form including a <code>FileField</code> and the fields for the other parameters:</p> <pre><code>from django import forms class UploadFileForm(forms.Form): my_parameter = forms.CharField(max_length=50) file = forms.FileField() </code></pre> <p>Include the <code>UploadFileForm</code> in your view and call your function for handling the uploaded file:</p> <pre><code>from django.http import HttpResponseRedirect from django.shortcuts import render from .forms import UploadFileForm # Imaginary function to handle an uploaded file. from somewhere import handle_uploaded_file def upload_file(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): my_parameter = form.cleaned_data['my_parameter'] # Handle the uploaded file results = handle_uploaded_file(request.FILES['file'], title) # Clear the form and parse the results form = UploadFileForm() return render(request, 'upload.html', {'form': form, 'results': results}) else: form = UploadFileForm() return render(request, 'upload.html', {'form': form}) </code></pre> <p>Create the function to handle the uploaded file and call your bash script:</p> <pre><code>import subprocess import os def handle_uploaded_file(f, my_parameter): file_path = os.path.join('/path/to/destination/', f.name) # Save the file with open(file_path, 'wb+') as destination: for chunk in f.chunks(): destination.write(chunk) # Call your bash script with the output = subprocess.check_output(['./my_script.sh',str(file_path),str(my_parameter)], shell=True) return output </code></pre> <p>Check out <a href="https://docs.djangoproject.com/en/1.10/topics/http/file-uploads/" rel="nofollow">https://docs.djangoproject.com/en/1.10/topics/http/file-uploads/</a> for more examples and instructions on how the handle file uploads in Django.</p>
0
2016-09-17T14:39:48Z
[ "python", "django" ]
Validating the value of several variables
39,547,275
<p><strong>What I am after:</strong> The user is allowed to input only 0 or 1 (for a total of 4 variables). If the user inputs for example 2, 1, 1, 0 it should throw an error saying <code>Only 0 and 1 allowed</code>.</p> <p><strong>What I've tried so far:</strong></p> <pre><code>if (firstBinary != 0 or firstBinary != 1 and secondBinary != 0 or secondBinary != 1 and thirdBinary != 0 or thirdBinary != 1 and forthBinary != 0 or forthBinary != 1): print('Only 0 and 1 allowed') else: print('binary to base 10: result) </code></pre> <p><strong>Problem:</strong> When I use such a statement, I get either the result even when I input for example 5, or I get 'only 0 and 1 allowed' even though I wrote all 1 or 0.</p> <hr> <p>I found this which seemed to be what I was after, but it is still not working like I want it to:</p> <pre><code>if 0 in {firstBinary, secondBinary, thirdBinary, forthBinary} or 1 in \ {firstBinary, secondBinary, thirdBinary, forthBinary}: print("Your result for binary to Base 10: ", allBinaries) else: print('Only 0 and 1 allowed') </code></pre> <p>This code basically gives me the same result as what I get with the first code sample.</p>
3
2016-09-17T13:17:15Z
39,547,326
<p>Use <code>any</code>:</p> <pre><code>v1, v2, v3, v4 = 0, 1, 1, 2 if any(x not in [0, 1] for x in [v1, v2, v3, v4]): print "bad" </code></pre> <p>of course, if you use a list it will look even better</p> <pre><code>inputs = [1, 1, 0 , 2] if any(x not in [0, 1] for x in inputs): print "bad" </code></pre>
6
2016-09-17T13:23:20Z
[ "python" ]
Validating the value of several variables
39,547,275
<p><strong>What I am after:</strong> The user is allowed to input only 0 or 1 (for a total of 4 variables). If the user inputs for example 2, 1, 1, 0 it should throw an error saying <code>Only 0 and 1 allowed</code>.</p> <p><strong>What I've tried so far:</strong></p> <pre><code>if (firstBinary != 0 or firstBinary != 1 and secondBinary != 0 or secondBinary != 1 and thirdBinary != 0 or thirdBinary != 1 and forthBinary != 0 or forthBinary != 1): print('Only 0 and 1 allowed') else: print('binary to base 10: result) </code></pre> <p><strong>Problem:</strong> When I use such a statement, I get either the result even when I input for example 5, or I get 'only 0 and 1 allowed' even though I wrote all 1 or 0.</p> <hr> <p>I found this which seemed to be what I was after, but it is still not working like I want it to:</p> <pre><code>if 0 in {firstBinary, secondBinary, thirdBinary, forthBinary} or 1 in \ {firstBinary, secondBinary, thirdBinary, forthBinary}: print("Your result for binary to Base 10: ", allBinaries) else: print('Only 0 and 1 allowed') </code></pre> <p>This code basically gives me the same result as what I get with the first code sample.</p>
3
2016-09-17T13:17:15Z
39,547,363
<p>I'd break it down into the two parts that you're trying to solve: </p> <p>Is a particular piece of input valid? Are all the pieces of input taken together valid? </p> <pre><code>&gt;&gt;&gt; okay = [0,1,1,0] &gt;&gt;&gt; bad = [0,1,2,3] &gt;&gt;&gt; def validateBit(b): ... return b in (0, 1) &gt;&gt;&gt; def checkInput(vals): ... return all(validateBit(b) for b in vals) ... &gt;&gt;&gt; checkInput(okay) True &gt;&gt;&gt; checkInput(bad) False &gt;&gt;&gt; </code></pre>
1
2016-09-17T13:27:45Z
[ "python" ]
Validating the value of several variables
39,547,275
<p><strong>What I am after:</strong> The user is allowed to input only 0 or 1 (for a total of 4 variables). If the user inputs for example 2, 1, 1, 0 it should throw an error saying <code>Only 0 and 1 allowed</code>.</p> <p><strong>What I've tried so far:</strong></p> <pre><code>if (firstBinary != 0 or firstBinary != 1 and secondBinary != 0 or secondBinary != 1 and thirdBinary != 0 or thirdBinary != 1 and forthBinary != 0 or forthBinary != 1): print('Only 0 and 1 allowed') else: print('binary to base 10: result) </code></pre> <p><strong>Problem:</strong> When I use such a statement, I get either the result even when I input for example 5, or I get 'only 0 and 1 allowed' even though I wrote all 1 or 0.</p> <hr> <p>I found this which seemed to be what I was after, but it is still not working like I want it to:</p> <pre><code>if 0 in {firstBinary, secondBinary, thirdBinary, forthBinary} or 1 in \ {firstBinary, secondBinary, thirdBinary, forthBinary}: print("Your result for binary to Base 10: ", allBinaries) else: print('Only 0 and 1 allowed') </code></pre> <p>This code basically gives me the same result as what I get with the first code sample.</p>
3
2016-09-17T13:17:15Z
39,547,380
<p>This is due to the operator precedence in python. The <code>or</code> operator is of higher precedence than the <code>and</code> operator, the list looks like this:</p> <ol> <li><code>or</code></li> <li><code>and</code></li> <li><code>not</code></li> <li><code>!=</code>, <code>==</code></li> </ol> <p>(Source: <a href="https://docs.python.org/3/reference/expressions.html#operator-precedence" rel="nofollow">https://docs.python.org/3/reference/expressions.html#operator-precedence</a>)</p> <p>So, python interprets your expression like this (the brackets are to clarify what is going on):</p> <pre><code>if (firstBinary != 0 or (firstBinary != 1 and secondBinary != 0 or (secondBinary != 1 and \ thirdBinary != 0 or (thirdBinary != 1 and forthBinary != 0 or (forthBinary != 1))))) </code></pre> <p>Which results in a different logic than what you want. There are 2 possible solutions to this, the first one is to add brackets to make the expression unambiguous. This is quite tedious and long-winded:</p> <pre><code>if ((firstBinary != 0 or firstBinary != 1) and (secondBinary != 0 or secondBinary != 1) and \ (thirdBinary != 0 or thirdBinary != 1) and (forthBinary != 0 or forthBinary != 1)) </code></pre> <p>The other approach is to use the in-built <code>all</code> function:</p> <pre><code>vars = [firstBinary, secondBinary, thirdBinary, fourthBinary] if not all(0 &lt;= x &lt;= 1 for x in vars): print("Only 0 or 1 allowed") </code></pre>
3
2016-09-17T13:29:35Z
[ "python" ]
Validating the value of several variables
39,547,275
<p><strong>What I am after:</strong> The user is allowed to input only 0 or 1 (for a total of 4 variables). If the user inputs for example 2, 1, 1, 0 it should throw an error saying <code>Only 0 and 1 allowed</code>.</p> <p><strong>What I've tried so far:</strong></p> <pre><code>if (firstBinary != 0 or firstBinary != 1 and secondBinary != 0 or secondBinary != 1 and thirdBinary != 0 or thirdBinary != 1 and forthBinary != 0 or forthBinary != 1): print('Only 0 and 1 allowed') else: print('binary to base 10: result) </code></pre> <p><strong>Problem:</strong> When I use such a statement, I get either the result even when I input for example 5, or I get 'only 0 and 1 allowed' even though I wrote all 1 or 0.</p> <hr> <p>I found this which seemed to be what I was after, but it is still not working like I want it to:</p> <pre><code>if 0 in {firstBinary, secondBinary, thirdBinary, forthBinary} or 1 in \ {firstBinary, secondBinary, thirdBinary, forthBinary}: print("Your result for binary to Base 10: ", allBinaries) else: print('Only 0 and 1 allowed') </code></pre> <p>This code basically gives me the same result as what I get with the first code sample.</p>
3
2016-09-17T13:17:15Z
39,547,526
<pre><code>values = [firstBinary, secondBinary, thirdBinary] if set(values) - set([0, 1]): print "Only 0 or 1, please" </code></pre>
0
2016-09-17T13:45:01Z
[ "python" ]
Sending an image through UDP communication
39,547,386
<p>I am trying to make a video-streaming application, in which i'll be able to both stream my webcam and my desktop. Up until now I've done so with TCP communication in order to make sure everything works, and it does, but very slowly. I know that usually in live streams like these you would use UDP, but I can't get it to work. I have created a basic UDP client and a server, and it works with sending shorts string, but when it comes to sending a whole image i can't find a solution to that. I have also looked it up online but found only posts about sending images through sockets in general, and they used TCP. I'm using Python 2.7, pygame to show the images, PIL + VideoCapture to save them, and StringIO + base64 in order to send them as string.</p>
0
2016-09-17T13:29:52Z
39,556,790
<p>My psychic powers tell me that are hitting the size limit for a UDP packet, which is just under 64KB. You will likely need to split your image bytes up into multiple packets when sending and have some logic to put them back together on the receiving end. You will likely need to roll out your own header format.</p> <p>Not sure why you would need to base64 encode your image bytes, that just add 33% of network overhead for no reason.</p> <p>While UDP has less network overhead than TCP, it generally relies on you, the developer, to come up with your own mechanisms for flow control, fragmentation handling, lost packets, etc...</p>
0
2016-09-18T10:46:14Z
[ "python", "image", "sockets", "stream", "udp" ]
Convert numpy array of integers to 12 bit binary
39,547,397
<p>I neeed to convert a np array of integers to 12 bit binary numbers, in an array format. What would be the best way to go about doing so? </p> <p>I've been a bit stuck so any help would be appreciated. Thanks!</p> <p>Here is what I have to convert an integer to binary:</p> <pre><code>def dec_to_binary(my_int): """ Format a number as binary with leading zeros""" if my_int &lt; 4096: x= "{0:12b}".format(my_int) return int(x) else: return 111111111111 </code></pre>
1
2016-09-17T13:31:08Z
39,547,500
<p>Slight correction (replace <code>12b</code> with <code>012b</code>):</p> <pre><code>def dec_to_binary(my_int): """ Format a number as binary with leading zeros """ if my_int &lt; 4096: return "{0:012b}".format(my_int) else: return "111111111111" </code></pre> <p>Example: </p> <pre><code>In [10]: n_array = np.array([123,234,234,345, 4097]) In [11]: map(dec_to_binary, n_array) Out[11]: ['000001111011', '000011101010', '000011101010', '000101011001', '111111111111'] </code></pre>
1
2016-09-17T13:42:36Z
[ "python", "arrays", "python-3.x", "numpy" ]
Determine program was installed using "setup.py develop"
39,547,411
<p>I am developing a Gtk application and would like to use a system-wide, installed version and run a different development version at the same time.</p> <p>The application cannot be started twice because <code>Gtk.Application</code> will try to connect to same DBus bus and refuse to be started twice. Therefore my idea is to determine whether I am in "development mode", i. e. the program has been installed using <code>./setup.py develop</code>, or not. </p> <p>How can I achieve this? Or is there another, more general way to differ between development and installed versions of the program? I would prefer to avoid a special <code>--develop</code> option or the like which would be useless outside of development scope.</p>
0
2016-09-17T13:32:22Z
39,547,684
<p>Due to how <code>setuptools</code> is designed the development mode is simply a transparent <code>.egg-link</code> object away, so internally it is effectively impossible to determine whether or not the package is loaded as an <code>egg-link</code> (i.e. development mode; relevant <a href="https://github.com/pypa/setuptools/blob/v27.2.0/pkg_resources/__init__.py#L1996" rel="nofollow">code here</a> and see how it just recursively invoke <code>find_distributions</code> which would in turn call this method again (through the internal import finder framework) before <a href="https://github.com/pypa/setuptools/blob/v27.2.0/pkg_resources/__init__.py#L1982" rel="nofollow">generating the metadata object</a>).</p> <p>So what you can do instead is to create a distinct DBus bus per version of your application. Typically for development your version number is different, and it is possible to pick up the version number through <a href="https://setuptools.readthedocs.io/en/latest/pkg_resources.html" rel="nofollow"><code>pkg_resources</code> API</a>.</p> <pre><code>&gt;&gt;&gt; pkg_resources.get_distribution('setuptools').version '18.2' </code></pre> <p>You can also use it to generate custom metadata which is written to your package's egg-info, and through that it is possible for your package to declare custom items that could say customize the bus name of the Dbus bus to be used, but this will take a bit more work to set up. At the very least, you can declare a <code>setup.cfg</code> that tag a build</p> <pre><code>[egg_info] tag_build = dev </code></pre> <p>Rerun <code>setup.py develop</code> again and the version number will include a <code>dev</code> suffix which will show up in the version string returned by <code>pkg_resources.get_distribution</code> on your package's name. This is not quite what you are looking for, but it might allow multiple versions of your application to be executed at the same time regardless of where they are installed or how they are installed. Consider users that might use virtualenvs to have multiple local installations of your applications and want to run them at the same time, and in that case you might want to base it on the hash of the install location instead:</p> <pre><code>&gt;&gt;&gt; pkg_resources.get_distribution('setuptools').location '/tmp/.env3/lib/python3.5/site-packages' </code></pre> <p>Of course, if the package is found within <code>site-packages</code> it is probably done as a proper <code>install</code>, but there is nothing in the API that will tell you this.</p>
1
2016-09-17T14:01:33Z
[ "python", "setuptools", "gtk3" ]
Reportlab Error after page break
39,547,528
<p>I am designing a two page form to be printed duplex. After I add a pagebreak, I get the following error:</p> <pre><code> File "f:\Dropbox\pms\pms_reports.py", line 450, in &lt;module&gt; a = Key_card1() File "f:\Dropbox\pms\pms_reports.py", line 441, in __init__ doc.build(elements) File "c:\Python34\Lib\site-packages\reportlab\platypus\doctemplate.py", line 1171, in build BaseDocTemplate.build(self,flowables, canvasmaker=canvasmaker) File "c:\Python34\Lib\site-packages\reportlab\platypus\doctemplate.py", line 927, in build self.handle_flowable(flowables) File "c:\Python34\Lib\site-packages\reportlab\platypus\doctemplate.py", line 775, in handle_flowable self.handle_keepWithNext(flowables) File "c:\Python34\Lib\site-packages\reportlab\platypus\doctemplate.py", line 742, in handle_keepWithNext while i&lt;n and flowables[i].getKeepWithNext(): i += 1 builtins.TypeError: getKeepWithNext() missing 1 required positional argument: 'self' </code></pre> <p>Here is my code:</p> <pre><code>from reportlab.lib.pagesizes import A4, landscape from reportlab.platypus import SimpleDocTemplate, Table, TableStyle, Paragraph, PageBreak from reportlab.lib.styles import getSampleStyleSheet class Key_card1(): def __init__(self, start_date=datetime.now(), room="1", end_date=datetime.now()+timedelta(days=1), password = "999999"): stylesheet = getSampleStyleSheet() doc = SimpleDocTemplate("key_card.pdf", pagesize=A4) if password == "999999": password = str(random.randint(10000,99999)) roomno = "Room" + room w_text = [] w_text.append(Paragraph("To use the wireless broadband…:",stylesheet["BodyText"])) w_text.append(Paragraph("User id: &lt;b&gt;" + roomno + "&lt;/b&gt;", stylesheet["BodyText"])) w_text.append(Paragraph("Password: &lt;b&gt;" + password + "&lt;/b&gt;", stylesheet["BodyText"])) message_text = [] message_text.append(Paragraph("Our current menus ...", stylesheet["BodyText"])) message_text.append(Paragraph("Our restaurant can get very busy ...",stylesheet["BodyText"])) message_text.append(Paragraph("Your shower has a safety device to...", stylesheet["BodyText"])) message_text .append(Paragraph("Please do not hesitate to call...",stylesheet["BodyText"])) elements=[] table_data = [(w_text, message_text)] the_table = Table(table_data) the_table.setStyle(TableStyle([('VALIGN',(0,0),(-1,-1),'MIDDLE')])) elements.append(the_table) elements.append(PageBreak) #Cover page logo= "y:\marketing\priory_master_logo bw.jpg" im = Image(logo, 3*cm, 1.258*cm) cover_data = [] cover_data.append(im) cover_data.append(Paragraph("Room number : " + room, stylesheet["BodyText"])) left_cell =[] left_cell.append(Paragraph(" ", stylesheet["BodyText"])) table_data1 = [(left_cell, cover_data)] the_table1 = Table(table_data1) the_table1.setStyle(TableStyle([('VALIGN',(0,0),(-1,-1),'MIDDLE')])) elements.append(the_table1) doc.build(elements) </code></pre> <p>I tried modifying the Reportlab modules but I was not successful. Anybody have any ideas?</p>
1
2016-09-17T13:45:21Z
39,547,653
<p>I have tried to understand the error and i guess there is problem in <code>doc = SimpleDocTemplate("key_card.pdf", pagesize=A4)</code>.The problem may be the argument "key_card.pdf". I'm not sure</p> <p>Edit: Maybe, <code>BaseDocTemplate.build(self,flowables, canvasmaker=canvasmaker)</code> problem is about "flowables" argument which is connected to elements in doc.build(elements)</p> <p>SOLUTION -> elements.append(PageBreak) should be elements.append(PageBreak())</p>
1
2016-09-17T13:59:02Z
[ "python", "reportlab" ]
How do i draw a line and change colors in pygame?
39,547,587
<p>I am trying to make a draw program in pygame for a school project. In this module, i am intending for the user to press down on the mouse and draw a line on the surface. If a person presses down on a rect, the color that the person selected is the color that the drawn line will be. For some reason, the variable can change but even if i press down the mouse, no line is drawn. Here's the code:</p> <pre><code>def painting_module(): running = True while running: #clock for timingn processes Clock.tick(FPS) # Process input (event) for event in pygame.event.get(): Mouse_location = pygame.mouse.get_pos() click = pygame.mouse.get_pressed() displacement_val = pygame.mouse.get_rel() color_to_paint_with = (0,0,0) if event.type == pygame.QUIT: running = False if click[0] == 1: # Intended to select colors if pressed, draw a line if the mouse is not on the rect if red_rect.collidepoint(Mouse_location): color_to_paint_with = RED print "Red" print color_to_paint_with if green_rect.collidepoint(Mouse_location): color_to_paint_with = GREEN print "red" print color_to_paint_with if blue_rect.collidepoint(Mouse_location): color_to_paint_with = BLUE print "red" print color_to_paint_with if gray_rect.collidepoint(Mouse_location): color_to_paint_with = GRAY print "red" print color_to_paint_with if eraser_ivory_rect.collidepoint(Mouse_location): color_to_paint_with = IVORY print "red" print color_to_paint_with #draws the line pygame.draw.line(Screen, color_to_paint_with, Mouse_location, (Mouse_location[0] + displacement_val[0], Mouse_location[1] + displacement_val[1])) </code></pre>
2
2016-09-17T13:51:38Z
39,547,896
<p>What I would do is</p> <pre><code>painting_module() def painting_module(): running = True while running: #clock for timingn processes Clock.tick(FPS) # Process input (event) for event in pygame.event.get(): Mouse_location = pygame.mouse.get_pos() click = pygame.mouse.get_pressed() displacement_val = pygame.mouse.get_rel() color_to_paint_with = (0,0,0) if event.type == pygame.QUIT: running = False if click[0] == 1: # Intended to select colors if pressed, draw a line if the mouse is not on the rect if red_rect.collidepoint(Mouse_location): color_to_paint_with = RED print "Red" print color_to_paint_with // Call drawloop here if green_rect.collidepoint(Mouse_location): color_to_paint_with = GREEN print "red" print color_to_paint_with if blue_rect.collidepoint(Mouse_location): color_to_paint_with = BLUE print "red" print color_to_paint_with if gray_rect.collidepoint(Mouse_location): color_to_paint_with = GRAY print "red" print color_to_paint_with if eraser_ivory_rect.collidepoint(Mouse_location): color_to_paint_with = IVORY print "red" print color_to_paint_with def drawline(color_to_paint_with, Mouse_location, displacement_val): for event in pygame.event.get(): while pygame.mouse.get_pressed()[0] == 1: pygame.draw.line(Screen, color_to_paint_with, Mouse_location, (Mouse_location[0] + displacement_val[0], Mouse_location[1] + displacement_val[1])) pygame.display.flip() </code></pre> <p>I would replace the "if pygame.mouse.get_pressed():" code block with this.</p>
0
2016-09-17T14:26:10Z
[ "python", "python-2.7", "pygame", "pygame-surface" ]
Filerenaming loop not functioning
39,547,750
<p>I'm having trouble understanding why my code doesn't work. I want to rename each file in a particular folder in an order like this: Foldername_1 Foldername_2 Foldername_3 etc...</p> <p>The code I wrote should increase the 'num' variable by 1 every time it reloops the for loop.</p> <pre><code>path = os.getcwd() filenames = os.listdir(path) for filename in filenames: num = 0 num = num + 1 name = "Foldername_{}".format(num) os.rename(filename, "{}".format(name)) </code></pre> <p>However I'm getting this Error:</p> <blockquote> <p>FileExistsError: [WinError 183] Cannot create a file when that file already exists: '90' -> 'Foldername_1'</p> </blockquote>
0
2016-09-17T14:09:58Z
39,547,761
<p>You are setting <code>num</code> to 0 <em>for each iteration</em>. Move the <code>num = 0</code> <em>out</em> of the loop:</p> <pre><code>num = 0 for filename in filenames: num = num + 1 name = "Foldername_{}".format(num) os.rename(filename, "{}".format(name)) </code></pre> <p>You don't need to format the <code>name</code> variable again; <code>"{}".format(name)</code> produces the same string as what is already in <code>name</code>. And rather than manually increment a number, you could use the <a href="https://docs.python.org/3/library/functions.html#enumerate" rel="nofollow"><code>enumerate()</code> function</a> to produce the number for you:</p> <pre><code>for num, filename in enumerate(filenames, 1): name = "Foldername_{}".format(num) os.rename(filename, name) </code></pre> <p>Take into account that <code>os.listdir()</code> doesn't list names in alphabetical order; rather, you'll get an order that is based on the on-disk directory structure, which depends on the order files where created and the exact filesystem implementation. You may want to sort manually:</p> <pre><code>for num, filename in enumerate(sorted(filenames), 1): </code></pre>
1
2016-09-17T14:11:10Z
[ "python", "python-3.x", "file-rename" ]
How do I get an entry widget to save what I input? Python Tkinter
39,547,768
<p>I want to make an entry widget that inputs personal details, however I want to save those details as variables, so I can write them in a txt file. </p> <pre><code>from tkinter import * root = Tk() Label(root, text = "Childs First name").grid(row = 0, sticky = W) Label(root, text = "Childs Surname").grid(row = 1, sticky = W) Label(root, text = "Childs Year of Birth").grid(row = 2, sticky = W) Label(root, text = "Childs Month of Birth").grid(row = 3, sticky = W) Label(root, text = "Childs Day of Birth").grid(row = 4, sticky = W) Fname = Entry(root) Sname = Entry(root) x = Entry(root) y = Entry(root) z = Entry(root) Fname.grid(row = 0, column = 1) Sname.grid(row = 1, column = 1) x.grid(row = 3, column = 1) y.grid(row = 2, column = 1) z.grid(row = 4, column = 1) Fname = Fname.get Sname = Sname.get x = x.get y = y.get z = z.get mainloop() </code></pre> <p>My code works absolutely fine, however it doesn't save what I inputted, let alone save it within a variable. I'm obviously missing chunks of code, but I don't know what code. Please help!? Thanks!!</p> <p>P.S: Also, if its not too much, how would I make a button to continue on to the next lines of code? Thank you again. </p>
0
2016-09-17T14:12:12Z
39,548,068
<p>Entry widgets have a <code>get</code> method which can be used to get the values when you need them. Your "save" function simply needs to call this function before writing to a file.</p> <p>For example:</p> <pre><code>def save(): x_value = x.get() y_value = y.get() z_value = z.get() ... </code></pre>
0
2016-09-17T14:43:38Z
[ "python", "button", "tkinter", "widget", "entry" ]
How to read the string and long features in tensorflow
39,547,815
<p>The tensorflow, I can't read string,long, only short float allowed? Why? </p> <pre><code>import tensorflow as tf import numpy as np # Data sets IRIS_TRAINING = "seRelFeatures.csv" IRIS_TEST = "seRelFeatures.csv" # Load datasets. training_set = tf.contrib.learn.datasets.base.load_csv(filename=IRIS_TRAINING, target_dtype=np.int) test_set = tf.contrib.learn.datasets.base.load_csv(filename=IRIS_TEST, target_dtype=np.int) </code></pre> <p>here is the error</p> <pre><code>/home/xuejiao/anaconda2/bin/python /home/xuejiao/Desktop/HDSO_DirectAnswer/training_testing/dnn_semiSuper.py Traceback (most recent call last): File "/home/xuejiao/Desktop/HDSO_DirectAnswer/training_testing/dnn_semiSuper.py", line 9, in &lt;module&gt; training_set = tf.contrib.learn.datasets.base.load_csv(filename=IRIS_TRAINING, target_dtype=np.int) File "/home/xuejiao/anaconda2/lib/python2.7/site-packages/tensorflow/contrib/learn/python/learn/datasets/base.py", line 47, in load_csv target[i] = np.asarray(ir.pop(target_column), dtype=target_dtype) File "/home/xuejiao/anaconda2/lib/python2.7/site-packages/numpy/core/numeric.py", line 482, in asarray return array(a, dtype, copy=False, order=order) ValueError: invalid literal for long() with base 10: '' Process finished with exit code 1 </code></pre>
2
2016-09-17T14:16:50Z
39,549,160
<p>Your error is <code>ValueError: invalid literal for long() with base 10: ''</code>. It simply that you are entering empty string instead of an integer (or string presentation of an integer). I'd check data in CSV files. </p>
0
2016-09-17T16:33:17Z
[ "python", "csv", "tensorflow" ]
How to read the string and long features in tensorflow
39,547,815
<p>The tensorflow, I can't read string,long, only short float allowed? Why? </p> <pre><code>import tensorflow as tf import numpy as np # Data sets IRIS_TRAINING = "seRelFeatures.csv" IRIS_TEST = "seRelFeatures.csv" # Load datasets. training_set = tf.contrib.learn.datasets.base.load_csv(filename=IRIS_TRAINING, target_dtype=np.int) test_set = tf.contrib.learn.datasets.base.load_csv(filename=IRIS_TEST, target_dtype=np.int) </code></pre> <p>here is the error</p> <pre><code>/home/xuejiao/anaconda2/bin/python /home/xuejiao/Desktop/HDSO_DirectAnswer/training_testing/dnn_semiSuper.py Traceback (most recent call last): File "/home/xuejiao/Desktop/HDSO_DirectAnswer/training_testing/dnn_semiSuper.py", line 9, in &lt;module&gt; training_set = tf.contrib.learn.datasets.base.load_csv(filename=IRIS_TRAINING, target_dtype=np.int) File "/home/xuejiao/anaconda2/lib/python2.7/site-packages/tensorflow/contrib/learn/python/learn/datasets/base.py", line 47, in load_csv target[i] = np.asarray(ir.pop(target_column), dtype=target_dtype) File "/home/xuejiao/anaconda2/lib/python2.7/site-packages/numpy/core/numeric.py", line 482, in asarray return array(a, dtype, copy=False, order=order) ValueError: invalid literal for long() with base 10: '' Process finished with exit code 1 </code></pre>
2
2016-09-17T14:16:50Z
39,873,129
<p>Actually I solved this problem by myself, this mistake mean</p> <pre><code>ValueError: invalid literal for long() with base 10: '' </code></pre> <p>I have some empty cell, but actually I don't have on the view. After I check it, it cased by I delete the last column but I just delete the content didn't delete the cells, so from view can't find any empty </p>
0
2016-10-05T11:47:09Z
[ "python", "csv", "tensorflow" ]
Counting the number of vowels
39,547,818
<p>Trying to print no. of vowels. When I run this code I get <code>1,2,3,4</code> I intend to print only 4. Where is my mistake and how would I correct it?</p> <pre><code>vowels='a','e','i','o','u' s= 'hellohello' count = 0 for letters in s: if letters in vowels: count+=1 print (count) </code></pre>
0
2016-09-17T14:17:07Z
39,547,849
<p>You're mostly right, but you're printing in the loop rather than at the end.</p> <pre><code>for letters in s: if letters in vowels: count+=1 # de indent to close the loop print (count) </code></pre>
0
2016-09-17T14:20:17Z
[ "python", "python-3.x" ]
Counting the number of vowels
39,547,818
<p>Trying to print no. of vowels. When I run this code I get <code>1,2,3,4</code> I intend to print only 4. Where is my mistake and how would I correct it?</p> <pre><code>vowels='a','e','i','o','u' s= 'hellohello' count = 0 for letters in s: if letters in vowels: count+=1 print (count) </code></pre>
0
2016-09-17T14:17:07Z
39,547,875
<p><code>count</code> should be out of <code>for</code> loop.So that it prints only once.</p> <pre><code>vowels='a','e','i','o','u' s= 'hellohello' count = 0 for letters in s: if letters in vowels: count+=1 print (count) </code></pre>
0
2016-09-17T14:22:29Z
[ "python", "python-3.x" ]
Doing something after popen is finished
39,547,820
<p>I want to make a background process that displays a <code>file</code> with an external <code>viewer</code>. When the process is stopped, it should delete the file. The following piece of code does what I want to do, but it is ugly and I guess there is a more idiomatic way. It would be perfect, if it is even OS independent.</p> <pre><code> subprocess.Popen(viewer + ' ' + file + ' &amp;&amp; rm ' + file, shell=True) </code></pre>
1
2016-09-17T14:17:20Z
39,547,855
<p>Using <code>subprocess.call()</code> to open the viewer and view the file will exactly do that. Subsequently, run the command to delete the file.</p> <p>If you want the script to continue while the process is running, use <code>threading</code></p> <p>An example:</p> <pre><code>from threading import Thread import subprocess import os def test(): file = "/path/to/somefile.jpg" subprocess.call(["eog", file]) os.remove(file) Thread(target = test).start() # the print command runs, no matter if the process above is finished or not print("Banana") </code></pre> <p>This will do exactly what you describe:</p> <ul> <li>open the file with <code>eog</code> (viewer), wait for it to finish (close<code>eog</code>) and remove the file. </li> <li>In the meantime continue the script and print "Banana".</li> </ul>
1
2016-09-17T14:20:44Z
[ "python", "python-3.x", "subprocess", "popen" ]
Pandas group by chunks not single values
39,547,873
<p>Now I'm kinda confused about grouping stuff using pandas.</p> <p>I have set of data (over 60k rows) with 3 columns:</p> <pre><code>2015/12/18 11:12:49 +0300 d1 b1 2015/12/18 11:12:50 +0300 d2 b2 2015/12/18 11:13:08 +0300 d1 b3 2015/12/18 11:13:36 +0300 d2 b4 2015/12/18 11:13:43 +0300 d2 b5 2015/12/18 11:14:21 +0300 d2 c0 2015/12/18 11:14:42 +0300 d2 c1 2015/12/18 11:15:13 +0300 d1 c2 2015/12/18 11:15:19 +0300 d3 c3 </code></pre> <p>And I need to get count of rows grouped by time periods (let's say 0-4, 4-8, 8-12 etc. by 4 hours) and weekdays and then get a single set for periods within a week.</p> <p>I can get sum for every hour in a week (time is the name of 1st column):</p> <pre><code>dind = pd.DatetimeIndex(df.time) gr = df.groupby([dind.weekday, dind.hour]) gr.size() </code></pre> <p>But I can't figure out how to group by chunks and then merge resulting <code>MultiIndex</code> into single index column.</p> <p>I hope it was clear description of the problem.</p>
1
2016-09-17T14:22:29Z
39,548,003
<p>The first part of you question, how to group by 4 hour chunks is easy and is addressed in both options below. <code>df.index.hour // 4</code></p> <p>The second part was vague as there are several ways to interpret "merge into a single column". I provided you two alternatives.</p> <p><strong><em>Option 1</em></strong></p> <pre><code>gpd = df.groupby([df.index.weekday, df.index.hour // 4]).size() gpd.index = gpd.index.to_series() gpd (4, 2) 9 dtype: int64 </code></pre> <p><strong><em>Option 2</em></strong></p> <pre><code>gpd = df.groupby([df.index.weekday, df.index.hour // 4]).size() gpd.index = ['{}_{}'.format(*i) for i in gpd.index] gpd 4_2 9 dtype: int64 </code></pre>
1
2016-09-17T14:37:01Z
[ "python", "pandas", "dataframe", "grouping" ]
Setting a plain checkbox with robobrowser
39,547,879
<p>I am struggling to check a simple checkbox with <code>robobrowser</code> to discard all messages in mailman.</p> <pre><code>form['discardalldefersp'].options </code></pre> <p>returns <code>['0']</code>, neither </p> <pre><code>form['discardalldefersp'].value= True </code></pre> <p>nor </p> <pre><code>form['discardalldefersp'].value = '1' </code></pre> <p>delivers a result. I only get 'ValueError: Option 1 not found in field '</p> <p>How can I set the checkbox?</p> <p>My code for the whole thing is as following:</p> <pre><code>import robobrowser pw = '&lt;password&gt;' browser = RoboBrowser(history=True) browser.open('&lt;mailmanlist&gt;') form = browser.get_form(action='/mailman/admindb/&lt;listname&gt;') form['adminpw'].value = pw browser.submit_form(form) form = browser.get_form(action='&lt;listurl&gt;') form['discardalldefersp'].value = '1' </code></pre> <p>The HTML is the following (in German):</p> <pre><code>&lt;HTML&gt; &lt;HEAD&gt; &lt;LINK REL="SHORTCUT ICON" HREF="/images/mailman/mm-icon.png"&gt; &lt;META http-equiv="Content-Type" content="text/html; charset=iso-8859-1"&gt; &lt;TITLE&gt;Administrative Datenbank&lt;/TITLE&gt; &lt;/HEAD&gt; &lt;BODY bgcolor="white" dir="ltr"&gt; &lt;h2&gt;Administrative Anfragen für Liste: &lt;em&gt;foobar&lt;/em&gt;&lt;/h2&gt;&lt;!-- based on en 2.0 / StD--&gt; Diese Seite zeigt eine &amp;Uuml;bersicht der gegenw&amp;auml;rtigen administrativen Anfragen f&amp;uuml;r die &lt;a href="https://lists.server.de/mailman/admin/foobar"&gt;&lt;em&gt;foobar&lt;/em&gt; Mailingliste&lt;/a&gt;, die auf Ihre Genehmigung warten. Als erstes sehen Sie eine Liste allf&amp;auml;lliger Abonnement- und K&amp;uuml;ndigungsanfragen, gefolgt von eventuellen Nachrichten, die Ihre Genehmigung erfordern, und daher gestoppt wurden. &lt;p&gt;Bitte w&amp;auml;hlen Sie f&amp;uuml;r jede Anfrage die zu treffende Ma&amp;szlig;nahme aus, und klicken Sie auf den &lt;b&gt;Alle Daten senden&lt;/b&gt; Knopf, wenn sie fertig sind. Eine &lt;a href="https://lists.server.de/mailman/admindb/foobar?details=instructions"&gt;detaillierte Anleitung&lt;/a&gt; ist ebenfalls verf&amp;uuml;gbar. &lt;p&gt;Sie k&amp;ouml;nnen sich auch &lt;a href="https://lists.server.de/mailman/admindb/foobar?details=all"&gt;Details&lt;/a&gt; zu allen gestoppten Nachrichten anzeigen lassen. &lt;FORM action="https://lists.server.de/mailman/admindb/foobar" method="POST" &gt; &lt;center&gt; &lt;INPUT name="submit" type="SUBMIT" value="Alle Daten senden" &gt;&lt;/center&gt; &lt;center&gt; &lt;INPUT name="discardalldefersp" type="CHECKBOX" value="0" &gt;&amp;nbsp;Alle mit &lt;em&gt;Verschieben&lt;/em&gt; markierten Nachrichten verwerfen. &lt;/center&gt; &lt;hr&gt; &lt;center&gt; &lt;h2&gt;Zurückgehaltene Nachrichten&lt;/h2&gt;&lt;/center&gt; ... &lt;/FORM&gt; </code></pre> <p><a href="http://i.stack.imgur.com/Qere7.png" rel="nofollow"><img src="http://i.stack.imgur.com/Qere7.png" alt="enter image description here"></a></p>
1
2016-09-17T14:22:59Z
39,897,976
<p>I had a similar error message with a radio button. Try to add the option of '1' or True to the Robobrowser field <strong>discardalldefersp</strong> and see if it solves the problem:</p> <pre><code>form['discardalldefersp'].options = ['1'] form['discardalldefersp'].value = '1' </code></pre> <p>Or with the True option:</p> <pre><code>form['discardalldefersp'].options = [True] form['discardalldefersp'].value = True </code></pre> <p>That solved me of getting the error message but the form didn't work well, but I think it was the web site that wasn't working good.</p>
1
2016-10-06T13:57:41Z
[ "python", "beautifulsoup", "robobrowser" ]
Python - print name shows None
39,547,942
<pre><code>import re import time import sys def main(): name = getName() getOption() nameForTicket, done = getTraveling(name) price, destination = getWay() fare = getFare() seat = getSeat() age = getAge() totalcost = getTotalCost(price, fare, seat, age) print("\n" + "Thank you " + name + " for flying us!" + "\n" + "The ticket price is: $" + str(totalcost) + "\n" + "The destination is: " + str(destination) + "\n" + "Ticket is for: " + str(nameForTicket).title()) main2(name, done) def getName(): name = input("Welcome to Tropical Airlines! Please enter your name &gt;&gt;&gt; ") if not re.match("^[a-zA-Z ]*$", name): print("Error, only letters allowed!") getName() elif len(name) &gt; 15: print("Error, Only 15 characters allowed!") getName() else: print ("Welcome " + name.title()) return name def getOption(): print("(I) Information" + "\n" + "(O) Order" + "\n" + "(E) Exit") user_choice = input("Choose one of the following option &gt;&gt;&gt; ") if user_choice.upper() == "I": displayInfo() else: if user_choice.upper() == "O": return else: if user_choice.upper() == "E": print("Thank you for visiting Tropical Airlines") exit() else: print("Error") getOption() def displayInfo(): print("Thank you for choosing Tropical Airlines for your air travel needs." + "\n" + "You will be asked questions regarding what type of ticket you would like to purchase as well as destination information." + "\n" + "We also offer 50% discounted fares for children.") getOption() def getTraveling(name): option = input("Who is the traveling person?" + "\n" + "(Y) You" + "\n" + "(S) Someone else") if option.upper() == "Y": nameForTicket = name done = True return nameForTicket, done elif option.upper() == "S": nameForTicket = getName2() done = False return nameForTicket, done else: print("Error") getTraveling(name) def getName2(): name2 = input("What is the travelling person name?") if not re.match("^[a-zA-Z ]*$", name2): print("Error, only letters allowed!") getName2() elif len(name2) &gt; 15: print("Error, Only 15 characters allowed!") getName2() else: return name2 def getWay(): option = input("What kind of trip?" + "\n" + "(1) One way" + "\n" + "(2) Round trip") if option == "1": cost, destination = getDest1() return cost, destination elif option == "2": cost, destination = getDest2() return cost, destination else: print("Error") getWay() def getDest1(): option = input("Choose one of the following destination: " + "\n" + "(C) Cairns -- $200" + "\n" + "(P) Perth -- $250" + "\n" + "(S) Sydney -- $300") if option.upper() == "C": initialCost = 200 dest = "Cairns" return initialCost, dest elif option.upper() == "P": initialCost = 250 dest = "Perth" return initialCost, dest elif option.upper() == "S": initialCost = 300 dest = "Sydney" return initialCost, dest else: print("Error") getDest1() def getDest2(): option = input("Choose one of the following destination: " + "\n" + "(C) Cairns -- $300" + "\n" + "(P) Perth -- $400" + "\n" + "(S) Sydney -- $500") if option.upper() == "C": initialCost = 300 dest = "Cairns" return initialCost, dest elif option.upper() == "P": initialCost = 400 dest = "Perth" return initialCost, dest elif option.upper() == "S": initialCost = 500 dest = "Sydney" return initialCost, dest else: print("Error") getDest2() def getFare(): option = input("Choose one of the following type of fare: " + "\n" + "(B) Business -- Extra $200" + "\n" + "(E) Economy -- Extra $50" + "\n" + "(F) Frugal -- Free") if option.upper() == "B": fare = 200 return fare elif option.upper() == "E": fare = 50 return fare elif option.upper() == "F": fare = 0 return fare else: print("Error") getFare() def getSeat(): option = input("Choose one of the following type of seat: " + "\n" + "(W) Window -- $20" + "\n" + "(A) Aisle -- $15" + "\n" + "(M)Middle -- $10") if option.upper() == "W": seat = 20 return seat elif option.upper() == "A": seat = 15 return seat elif option.upper() == "M": seat = 10 return seat else: print("Error") getSeat() def getAge(): age = int(input("Enter the age, if the age is bellow 17, you will get 50% discount &gt;&gt;&gt; ")) while age &lt; 6 or age &gt; 100: print("Invalid age") age= int(input("Enter the valid age &gt;&gt;&gt;")) return age def getTotalCost(price, fare, seat, age): if age &lt;18: finalCost = (price + fare + seat)/2 else: finalCost = price + fare + seat return finalCost def loading(): for i in range(101): time.sleep(0.02) sys.stdout.write("\r%d%%" % i) sys.stdout.flush() def main2(name, done): getOption() nameForTicket = getTraveling2(name, done) price, destination = getWay() fare = getFare() seat = getSeat() age = getAge() totalcost = getTotalCost(price, fare, seat, age) print("\n" + "Thank you " + name + " for flying us!" + "\n" + "The ticket price is: $" + str(totalcost) + "\n" + "The destination is: " + str(destination) + "\n" + "Ticket is for: " + str(nameForTicket2).title()) main2(name, done) def getTraveling2(name, done): option = input("Who is the traveling person?" + "\n" + "(Y) You" + "\n" + "(S) Someone else") if option.upper() == "Y": if done == True: print("You have already ordered ticket for you!") getTraveling2(name, done) elif done == False: nameForTicket = name done = True return nameForTicket, done elif option.upper() == "S": nameForTicket = getName2() return nameForTicket else: print("Error") getTraveling2(name, done) main() </code></pre> <p>Short story I was writing these long codes.</p> <p>If from <code>def main()</code> in <code>nameForTicket, done = getTraveling(name)</code> I choose Y, the code shows the name in<code>str(nameForTicket).title()</code> for the <code>def main()</code> just fine.</p> <p>but in <code>def main2():</code> for the function getTraveling2(name, done) if I choose S, the <code>str(nameForTicket2).title()</code> in <code>def main2():</code> will show None.</p> <p>And the same happens if from <code>main()</code> I choose S, the <code>main2()</code> if I choose S will show none, and if I choose Y, it will display (Name, True)</p> <p>how to fix it so the name will show based on the input for S?</p>
0
2016-09-17T14:31:20Z
39,548,081
<p>In <code>main2</code>, change </p> <p><code>nameForTicket = getTraveling2(name, done)</code> </p> <p>to </p> <p><code>nameForTicket2 = getTraveling2(name, done)</code> </p> <p>because your print statement in <code>main2</code> addresses <code>str(nameForTicket2).title()</code>, which is trying to print the title of <code>nameForTicket2</code> when you set the result of the <code>getTraveling2</code> method to <code>nameForTicket</code> instead. Therefore, the print statement gives you <code>None</code> since <code>nameForTicket2</code> was never really defined.</p>
0
2016-09-17T14:44:47Z
[ "python", "function" ]
Neural Network predictions are always the same while testing an fMRI dataset with pyBrain. Why?
39,547,947
<p>I am quite new to fMRI analysis. I am trying to determine which object (out of 9 objects) a person is thinking about just by looking at their Brain Images. I am using the dataset on <a href="https://openfmri.org/dataset/ds000105/" rel="nofollow">https://openfmri.org/dataset/ds000105/</a> . So, I am using a neural network by inputting 2D slices of brain images to get the output as 1 of the 9 objects. There are details about every step and the images in the code below.</p> <pre><code>import os, mvpa2, pyBrain import numpy as np from os.path import join as opj from mvpa2.datasets.sources import OpenFMRIDataset from pybrain.datasets import SupervisedDataSet,classification path = opj(os.getcwd() , 'datasets','ds105') of = OpenFMRIDataset(path) #12th run of the 1st subject ds = of.get_model_bold_dataset(model_id=1, subj_id=1,run_ids=[12]) #Get the unique list of 8 objects (sicissors, ...) and 'None'. target_list = np.unique(ds.sa.targets).tolist() #Returns Nibabel Image instance img = of.get_bold_run_image(subj=1,task=1,run=12) # Getting the actual image from the proxy image img_data = img.get_data() #Get the middle voxelds of the brain samples mid_brain_slices = [x/2 for x in img_data.shape] # Each image in the img_data is a 3D image of 40 x 64 x 64 voxels, # and there are 121 such samples taken periodically every 2.5 seconds. # Thus, a single person's brain is scanned for about 300 seconds (121 x 2.5). # This is a 4D array of 3 dimensions of space and 1 dimension of time, # which forms a matrix of (40 x 64 x 64 x 121) # I only want to extract the slice of the 2D images brain in it's top view # i.e. a series of 2D images 40 x 64 # So, i take the middle slice of the brain, hence compute the middle_brain_slices DS = classification.ClassificationDataSet(40*64, class_labels=target_list) # Loop over every brain image for i in range(0,121): #Image of brain at i th time interval brain_instance = img_data[:,:,:,i] # We will slice the brain to create 2D plots and use those 'pixels' # as the features slice_0 = img_data[mid_brain_slices[0],:,:,i] #64 x 64 slice_1 = img_data[:,mid_brain_slices[1],:,i] #40 x 64 slice_2 = img_data[:,:,mid_brain_slices[2],i] #40 x 64 #Note : we may actually only need one of these slices (the one with top view) X = slice_2 #Possibly top view # Reshape X from 40 x 64 to 1D vector 2560 x 1 X = np.reshape(X,40*64) #Get the target at this intance (y) y = ds.sa.targets[i] y = target_list.index(y) DS.appendLinked(X,y) print DS.calculateStatistics() print DS.classHist print DS.nClasses print DS.getClass(1) # Generate y as a 9 x 1 matrix with eight 0's and only one 1 (in this training set) DS._convertToOneOfMany(bounds=[0, 1]) #Split into Train and Test sets test_data, train_data = DS.splitWithProportion( 0.25 ) #Note : I think splitWithProportion will also internally shuffle the data #Build neural network from pybrain.tools.shortcuts import buildNetwork from pybrain.structure.modules import SoftmaxLayer nn = buildNetwork(train_data.indim, 64, train_data.outdim, outclass=SoftmaxLayer) from pybrain.supervised.trainers import BackpropTrainer trainer = BackpropTrainer(nn, dataset=train_data, momentum=0.1, learningrate=0.01 , verbose=True, weightdecay=0.01) trainer.trainUntilConvergence(maxEpochs = 20) </code></pre> <p>The line <code>nn.activate(X_test[i])</code> should take the 2560 inputs and generate a probability output, right? in the predicted y vector (shape 9 x 1 ) </p> <p>So, I assume the highest of the 9 values should be assigned answer. But it is not the case when I verify it with y_test[i]. Furthermore, I get similar values for X_test for every test sample. Why is this so?</p> <pre><code> #Just splitting the test and trainset X_train = train_data.getField('input') y_train = train_data.getField('target') X_test = test_data.getField('input') y_test = test_data.getField('target') #Testing the network for i in range(0,len(X_test)): print nn.activate(X_test[i]) print y_test[i] </code></pre> <p>When I include the code above, here are some values of X_test :</p> <pre><code>. . . nn.activated = [ 0.44403205 0.06144328 0.04070154 0.09399672 0.08741378 0.05695479 0.08178353 0.0623408 0.07133351] y_test [0 1 0 0 0 0 0 0 0] nn.activated = [ 0.44403205 0.06144328 0.04070154 0.09399672 0.08741378 0.05695479 0.08178353 0.0623408 0.07133351] y_test [1 0 0 0 0 0 0 0 0] nn.activated = [ 0.44403205 0.06144328 0.04070154 0.09399672 0.08741378 0.05695479 0.08178353 0.0623408 0.07133351] y_test [0 0 0 0 0 0 1 0 0] . . . </code></pre> <p>So the probability of the test sample being index 0 in every case id 44.4% irrespective of the sample value. The actual values keep varying though. </p> <pre><code>print 'print predictions: ' , trainer.testOnClassData (dataset=test_data) x = [] for item in y_test: x.extend(np.where(item == 1)[0]) print 'print actual: ' , x </code></pre> <p>Here, the output comparison is :</p> <pre><code>print predictions: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] print actual: [7, 0, 4, 8, 2, 0, 2, 1, 0, 6, 1, 4] </code></pre> <p>All the predictions are for the first item. I don't know what the problem is. The total error seems to be decreasing, which is a good sign though :</p> <pre><code>Total error: 0.0598287764931 Total error: 0.0512272330797 Total error: 0.0503835076374 Total error: 0.0486402801867 Total error: 0.0498354140541 Total error: 0.0495447833038 Total error: 0.0494208449895 Total error: 0.0491162599037 Total error: 0.0486775862084 Total error: 0.0486638648161 Total error: 0.0491337891419 Total error: 0.0486965691406 Total error: 0.0490016912735 Total error: 0.0489939195858 Total error: 0.0483910986235 Total error: 0.0487459940103 Total error: 0.0485516142106 Total error: 0.0477407360102 Total error: 0.0490661144891 Total error: 0.0483103097669 Total error: 0.0487965594586 </code></pre>
1
2016-09-17T14:31:54Z
39,548,287
<p>I can't be sure -- because I haven't used all of these tools together before, or worked specifically in this kind of project -- but I would look at the documentation and be sure that your <code>nn</code> is being created as you expect it to.</p> <p>Specifically, it mentions here:</p> <p><a href="http://pybrain.org/docs/api/tools.html?highlight=buildnetwork#pybrain.tools.shortcuts.buildNetwork" rel="nofollow">http://pybrain.org/docs/api/tools.html?highlight=buildnetwork#pybrain.tools.shortcuts.buildNetwork</a></p> <p>that "If the recurrent flag is set, a RecurrentNetwork will be created, otherwise a FeedForwardNetwork.", and you can read here:</p> <p><a href="http://pybrain.org/docs/api/structure/networks.html?highlight=feedforwardnetwork" rel="nofollow">http://pybrain.org/docs/api/structure/networks.html?highlight=feedforwardnetwork</a></p> <p>that "FeedForwardNetworks are networks that do not work for sequential data. Every input is treated as independent of any previous or following inputs.".</p> <p>Did you mean to create a "FeedForward" network object?</p> <p>You're testing by looping over an index and activating each <code>"input"</code> field that's based off the instantiation of a <code>FeedForwardNetwork</code> object, which the documentation suggests are treated as independent of other inputs. This may be why you're getting such similar results each time, when you are expecting better convergences.</p> <p>You initialize your dataset <code>ds</code> object with the parameters <code>model_id=1, subj_id=1,run_ids=[12]</code>, suggesting that you're only looking at a single subject and model, but 12 "runs" from that subject under that model, right?</p> <p>Most likely there's nothing semantically or grammatically wrong with your code, but a general confusion from the PyBrain library's presumed and assumed models, parameters, and algorithms. So don't tear your hair out looking for code "errors"; this is definitely a common difficulty with under-documented libraries.</p> <p>Again, I may be off base, but in my experience with similar tools and libraries, it's most often that the benefit of taking an extremely complicated process and simplifying it to just a couple dozen lines of code, comes with a TON of completely opaque and fixed assumptions.</p> <p>My guess is that you're essentially re-running "new" tests on "new" or independent training data, without all the actual information and parameters that you thought you had setup in the previous code lines. You are exactly correct that the highest value (read: largest probability) is the "most likely" (that's exactly what each value is, a "likeliness") answer, especially if your probability array represents a <a href="https://en.wikipedia.org/wiki/Multimodal_distribution#Unimodal_vs._bimodal_distribution" rel="nofollow">unimodal distribution</a>.</p> <p>Because there are no obvious code syntax errors -- like accidentally looping over a range iterator equivalent to the list <code>[0,0,0,0,0,0]</code>; which you can verify because you reuse the <code>i</code> index integer in printing <code>y_test</code> which varies and the result of <code>nn.activate(X_test[i])</code> which isn't varying -- then most likely what's happening is that you're basically restarting your test every time and that's why you're getting an identical result, not just similar but identical for every printout of that <code>nn.activate(...)</code> method's results.</p> <p>This is a complex, but very well written and well illustrated question, but unfortunately I don't think there will be a simple or blatantly obvious solution.</p> <p>Again, you're getting the benefits of PyBrain's simplificaiton of neural networks, data training, heuristics, data reading, sampling, statistical modelling, classification, and so on and so forth, all reduced into single line or two line commands. There <em>are</em> assumptions being made, TONS of them. That's what the documentation <em>needs</em> to be illuminating, and we have to be very very careful when we use tools like these that it's not just a matter of correct syntax, but an actually correct (read: expected) algorithm, assumptions and all.</p> <p>Good luck!</p> <p>(P.S. -- Open source libraries also, despite a lack of documentation, give you the benefit of checking the source code to see [assumptions and all] what they're actually doing: <a href="https://github.com/pybrain/pybrain" rel="nofollow">https://github.com/pybrain/pybrain</a> )</p>
1
2016-09-17T15:03:17Z
[ "python", "neural-network", "pybrain" ]
Why does SymPy not work properly with real numbers?
39,547,952
<p>I am trying to evaluate an infinite sum in SymPy. While the first expression is calculated the way I expect it, SymPy seems to have trouble with the second expression.</p> <pre><code>from sympy import * n = symbols('n') print Sum((2)**(-n), (n, 1, oo)).doit() print Sum((0.5)**(n), (n, 1, oo)).doit() </code></pre> <p>Results in:</p> <pre><code>1 Sum(0.5**n, (n, 1, oo)) </code></pre> <p>I assume that the reason is that I am using a float number instead of an integer value.</p> <p>Is there a way to approximate the sum instead?</p>
1
2016-09-17T14:32:13Z
39,548,327
<p>From the <a href="http://docs.sympy.org/latest/modules/concrete.html#concrete-functions-reference" rel="nofollow">docs:</a></p> <blockquote> <p>If it cannot compute the sum, it returns an unevaluated Sum object.</p> </blockquote> <p>Another way to do this would be:</p> <pre><code>In [40]: Sum((Rational(1,2))**(n), (n, 1, oo)).doit() Out[40]: 1 </code></pre> <p>Yet another way to do this:</p> <pre><code>In [43]: Sum((0.5)**(n), (n, 1, float('inf'))).doit() Out[43]: 1.00000000000000 </code></pre> <p>To approximate, you can take a sufficiently large number instead of infinity:</p> <pre><code>In [51]: import sys In [52]: Sum((0.5)**(n), (n, 1, sys.maxint)).doit() Out[52]: 1.00000000000000 </code></pre>
3
2016-09-17T15:06:42Z
[ "python", "sympy" ]
Why does SymPy not work properly with real numbers?
39,547,952
<p>I am trying to evaluate an infinite sum in SymPy. While the first expression is calculated the way I expect it, SymPy seems to have trouble with the second expression.</p> <pre><code>from sympy import * n = symbols('n') print Sum((2)**(-n), (n, 1, oo)).doit() print Sum((0.5)**(n), (n, 1, oo)).doit() </code></pre> <p>Results in:</p> <pre><code>1 Sum(0.5**n, (n, 1, oo)) </code></pre> <p>I assume that the reason is that I am using a float number instead of an integer value.</p> <p>Is there a way to approximate the sum instead?</p>
1
2016-09-17T14:32:13Z
39,622,450
<p>That's <a href="https://github.com/sympy/sympy/issues/11642" rel="nofollow">a bug</a>. It ought to work. In general, however, it's best to prefer exact rational numbers over floats in SymPy, wherever possible. If you replace <code>0.5</code> with <code>Rational(1, 2)</code> it works. </p>
2
2016-09-21T16:59:49Z
[ "python", "sympy" ]
the Georgian language in tkinter. Python
39,547,969
<p>I can not write on a standard Georgian language in the Text widget. instead of letters writes question marks . when no tkinter, ie, when writing code, Georgian font recognized without problems. Plus, if I copy the word written in Georgian and inserted in the text widget, it is displayed correctly.</p> <p>this is elementary code that displays the text box on the screen, where I want to write a word in Georgian.</p> <pre><code>import tkinter root = tkinter.Tk() txt = tkinter.Text(root) txt.pack() root.mainloop() </code></pre> <p><a href="http://i.stack.imgur.com/ibC3E.png" rel="nofollow">the first image shows how the word is displayed when the selected Georgian language.</a></p> <p><a href="http://i.stack.imgur.com/Xyf5U.png" rel="nofollow">the second shot, when I write in the code in Georgian, and define in advance the value of text field. in this case, the text in the field is displayed normally.</a></p>
0
2016-09-17T14:33:03Z
39,548,453
<p>Okay, so here is how I achieved it:<br/> First, make sure you have a Georgian font installed in your computer; if there is no any, then go download one (I downloaded mine from <a href="http://fonts.ge/en/font/2/AcadNusx" rel="nofollow">here</a>);<br/> Now, go to your tkinter program, and add your font to your <code>Text</code> widget:<br/></p> <pre><code>txt = tkinter.Text(root, font=("AcadNusx", 16)) </code></pre> <p><b>NOTE 1:</b> My font name that supports Georgian is AcadNusx, but yours can be different;<br/> <b>NOTE 2:</b> If you have not imported Font, then import it at the beginning of your program;<br/> <b>NOTE 3:</b> Do not change your computer's font to Georgian, because you have already changed it inside the program, so make sure it is set to English.</p>
0
2016-09-17T15:20:30Z
[ "python", "tkinter", "georgian" ]
the Georgian language in tkinter. Python
39,547,969
<p>I can not write on a standard Georgian language in the Text widget. instead of letters writes question marks . when no tkinter, ie, when writing code, Georgian font recognized without problems. Plus, if I copy the word written in Georgian and inserted in the text widget, it is displayed correctly.</p> <p>this is elementary code that displays the text box on the screen, where I want to write a word in Georgian.</p> <pre><code>import tkinter root = tkinter.Tk() txt = tkinter.Text(root) txt.pack() root.mainloop() </code></pre> <p><a href="http://i.stack.imgur.com/ibC3E.png" rel="nofollow">the first image shows how the word is displayed when the selected Georgian language.</a></p> <p><a href="http://i.stack.imgur.com/Xyf5U.png" rel="nofollow">the second shot, when I write in the code in Georgian, and define in advance the value of text field. in this case, the text in the field is displayed normally.</a></p>
0
2016-09-17T14:33:03Z
39,563,799
<p>The best answer I can determine so far is that there is something about Georgian and keyboard entry that tk does not like, at least not on Windows. </p> <p>Character 'translation' is usually called 'transliteration'.</p> <p>Tk text uses the Basic Multilingual Plane (the BMP, the first 2**16 codepoints) of Unicode. This includes the Georgian alphabet. The second image shows that the default Text widget font on your system is quite capable of displaying Georgian characters <em>once</em> the characters are in the widget. So a new display font does not seem to be the solution to your problem. ('ქართული ენა' is visible on Firefox because FF is unicode based and can display most if not all of the BMP.)</p> <p>It looks like the problem is getting the proper codes to tk without going through your editor. What OS and editor are your using. How did you enter the mixed-alphabet line similar to</p> <pre><code>txt.insert('1.0', 'ქართული ენა') # ? (I cannot copy the image string.) </code></pre> <p>How are you running the Python code? If you cut the question marks from the first image and insert into</p> <pre><code>for c in '&lt;insert here&gt;': print(ord(c)) </code></pre> <p>what do you see?</p> <p>You need a 'Georgian keyboard entry' or 'input method' program (Google shows several) for your OS that will let you switch back and forth between sending ascii and Geargian codes to any program reading the keyboard.</p> <p>Windows now comes with this, with languages activated on a case-by-case basis. I already had Spanish entry, and with it I can enter á and ñ both here and into IDLE and a fresh Text box. However, when I add Georgian, I can type (randomly ;-) ჰჯჰფგეუგსკფ here (in FireFox, also MS Edge) but only get ?????? in tk Text boxes. And these are actual ascii question marks, ord('?') = 63, rather that replacements for codes that cannot be represented. Japanese also works with tk-Text based IDLE. So the problem with Georgian is not generic to all non-latin alphabets.</p>
0
2016-09-19T00:13:17Z
[ "python", "tkinter", "georgian" ]
Pandas dataframe slicing
39,547,985
<p>I have the following dataframe:</p> <pre><code> 2012 2013 2014 2015 2016 2017 2018 Kategorie 0 5.31 5.27 5.61 4.34 4.54 5.02 7.07 Gewinn pro Aktie in EUR 1 13.39 14.70 12.45 16.29 15.67 14.17 10.08 KGV 2 -21.21 -0.75 6.45 -22.63 -7.75 9.76 47.52 Gewinnwachstum 3 -17.78 2.27 -0.55 3.39 1.48 0.34 NaN PEG </code></pre> <p>Now, I am selecting only the <code>KGV</code> row with:</p> <pre><code>df[df["Kategorie"] == "KGV"] </code></pre> <p>Which outputs:</p> <pre><code> 2012 2013 2014 2015 2016 2017 2018 Kategorie 1 13.39 14.7 12.45 16.29 15.67 14.17 10.08 KGV </code></pre> <p>How do I calculate the <code>mean()</code> of the last five years (2016,15,14,13,12 in this example)?<br> I tried</p> <pre><code>df[df["Kategorie"] == "KGV"]["2016":"2012"].mean() </code></pre> <p>but this throws a <code>TypeError</code>. Why can I not slice the columns here?</p>
1
2016-09-17T14:34:50Z
39,548,058
<p>Not sure why the last five years are 2012-2016 (they seem to be the <em>first</em> five years). Notwithstanding, to find the mean for 2012-2016 for <code>'KGV'</code>, you can use</p> <pre><code>df[df['Kategorie'] == 'KGV'][[c for c in df.columns if c != 'Kategorie' and 2012 &lt;= int(c) &lt;= 2016]].mean(axis=1) </code></pre>
2
2016-09-17T14:42:17Z
[ "python", "pandas", "dataframe" ]
Pandas dataframe slicing
39,547,985
<p>I have the following dataframe:</p> <pre><code> 2012 2013 2014 2015 2016 2017 2018 Kategorie 0 5.31 5.27 5.61 4.34 4.54 5.02 7.07 Gewinn pro Aktie in EUR 1 13.39 14.70 12.45 16.29 15.67 14.17 10.08 KGV 2 -21.21 -0.75 6.45 -22.63 -7.75 9.76 47.52 Gewinnwachstum 3 -17.78 2.27 -0.55 3.39 1.48 0.34 NaN PEG </code></pre> <p>Now, I am selecting only the <code>KGV</code> row with:</p> <pre><code>df[df["Kategorie"] == "KGV"] </code></pre> <p>Which outputs:</p> <pre><code> 2012 2013 2014 2015 2016 2017 2018 Kategorie 1 13.39 14.7 12.45 16.29 15.67 14.17 10.08 KGV </code></pre> <p>How do I calculate the <code>mean()</code> of the last five years (2016,15,14,13,12 in this example)?<br> I tried</p> <pre><code>df[df["Kategorie"] == "KGV"]["2016":"2012"].mean() </code></pre> <p>but this throws a <code>TypeError</code>. Why can I not slice the columns here?</p>
1
2016-09-17T14:34:50Z
39,548,073
<p>I used <code>filter</code> and <code>iloc</code></p> <pre><code>row = df[df.Kategorie == 'KGV'] row.filter(regex='\d{4}').sort_index(1).iloc[:, -5:].mean(1) 1 13.732 dtype: float64 </code></pre>
2
2016-09-17T14:43:53Z
[ "python", "pandas", "dataframe" ]
Pandas dataframe slicing
39,547,985
<p>I have the following dataframe:</p> <pre><code> 2012 2013 2014 2015 2016 2017 2018 Kategorie 0 5.31 5.27 5.61 4.34 4.54 5.02 7.07 Gewinn pro Aktie in EUR 1 13.39 14.70 12.45 16.29 15.67 14.17 10.08 KGV 2 -21.21 -0.75 6.45 -22.63 -7.75 9.76 47.52 Gewinnwachstum 3 -17.78 2.27 -0.55 3.39 1.48 0.34 NaN PEG </code></pre> <p>Now, I am selecting only the <code>KGV</code> row with:</p> <pre><code>df[df["Kategorie"] == "KGV"] </code></pre> <p>Which outputs:</p> <pre><code> 2012 2013 2014 2015 2016 2017 2018 Kategorie 1 13.39 14.7 12.45 16.29 15.67 14.17 10.08 KGV </code></pre> <p>How do I calculate the <code>mean()</code> of the last five years (2016,15,14,13,12 in this example)?<br> I tried</p> <pre><code>df[df["Kategorie"] == "KGV"]["2016":"2012"].mean() </code></pre> <p>but this throws a <code>TypeError</code>. Why can I not slice the columns here?</p>
1
2016-09-17T14:34:50Z
39,548,150
<p><code>loc</code> supports that type of slicing (from left to right):</p> <pre><code>df.loc[df["Kategorie"] == "KGV", "2012":"2016"].mean(axis=1) Out: 1 14.5 dtype: float64 </code></pre> <p>Note that this does not necessarily mean 2012, 2013, 2014, 2015 and 2016. These are strings so it means all columns between <code>df['2012']</code> and <code>df['2016']</code>. There could be a column named <code>foo</code> in between and it would be selected.</p>
4
2016-09-17T14:50:39Z
[ "python", "pandas", "dataframe" ]
Printing Simple Diamond Pattern in Python
39,548,099
<p>I would like to print the following pattern in Python 3.5 (I'm new to coding): </p> <pre><code> * *** ***** ******* ********* ******* ***** *** * </code></pre> <p>But I only know how to print the following using the code below, but not sure how to invert it to make it a complete diamond:</p> <pre><code>n = 5 print("Pattern 1") for a1 in range (0,n): for a2 in range (a1): print("*", end="") print() for a1 in range (n,0,-1): for a2 in range (a1): print("*", end="") print() * ** *** **** ***** **** *** ** * </code></pre> <p>Any help would be appreciated!</p>
0
2016-09-17T14:46:00Z
39,548,404
<p>Since the middle and largest row of stars has 9 stars, you should make <code>n</code> equal to 9. You were able to print out half of the diamond, but now you have to try to make a function that prints a specific number of spaces, then a specific number of stars. So try to develop a pattern with the number of spaces and stars in each row,</p> <pre><code>Row1: 4 spaces, 1 star, 4 spaces Row2: 3 spaces, 3 stars, 3 spaces Row3: 2 spaces, 5 stars, 2 spaces Row4: 1 space, 7 stars, 1 space Row5: 0 spaces, 9 stars, 0 spaces Row6: 1 space, 7 stars, 1 space Row7: 2 spaces, 5 stars, 2 spaces Row8: 3 spaces, 3 stars, 3 spaces Row9: 4 spaces, 1 star, 4 spaces </code></pre> <p>So what can you deduce? From row 1 to (n+1)/2, the number of spaces decreases as the number of stars increase. So from 1 to 5, the <code># of stars</code> = (<code>row number</code> * 2) - 1, while <code># of spaces before stars</code> = 5 - <code>row number</code>. </p> <p>Now from row (n+1)/2 + 1 to row 9, the number of spaces increase while the number of stars decrease. So from 6 to n, the <code># of stars</code> = ((n+1 - <code>row number</code>) * 2) - 1, while <code># of spaces before stars</code> = <code>row number</code> - 5.</p> <p>From this information, you should be able to make a program that looks like this,</p> <pre><code>n = 9 print("Pattern 1") for a1 in range(1, (n+1)//2 + 1): #from row 1 to 5 for a2 in range((n+1)//2 - a1): print(" ", end = "") for a3 in range((a1*2)-1): print("*", end = "") print() for a1 in range((n+1)//2 + 1, n + 1): #from row 6 to 9 for a2 in range(a1 - (n+1)//2): print(" ", end = "") for a3 in range((n+1 - a1)*2 - 1): print("*", end = "") print() </code></pre> <p>Note that you can replace n with any odd number to create a perfect diamond of that many lines.</p>
0
2016-09-17T15:15:01Z
[ "python" ]
Printing Simple Diamond Pattern in Python
39,548,099
<p>I would like to print the following pattern in Python 3.5 (I'm new to coding): </p> <pre><code> * *** ***** ******* ********* ******* ***** *** * </code></pre> <p>But I only know how to print the following using the code below, but not sure how to invert it to make it a complete diamond:</p> <pre><code>n = 5 print("Pattern 1") for a1 in range (0,n): for a2 in range (a1): print("*", end="") print() for a1 in range (n,0,-1): for a2 in range (a1): print("*", end="") print() * ** *** **** ***** **** *** ** * </code></pre> <p>Any help would be appreciated!</p>
0
2016-09-17T14:46:00Z
39,548,445
<p>As pointed out by Martin Evans in his post: <a href="http://stackoverflow.com/a/32613884/4779556">http://stackoverflow.com/a/32613884/4779556</a> a possible solution to the diamond pattern could be: </p> <blockquote> <pre><code>side = int(input("Please input side length of diamond: ")) for x in list(range(side)) + list(reversed(range(side-1))): print('{: &lt;{w1}}{:*&lt;{w2}}'.format('', '', w1=side-x-1, w2=x*2+1)) </code></pre> </blockquote>
1
2016-09-17T15:19:34Z
[ "python" ]
My code skips the IF block and goes to ELSE
39,548,134
<p>Just started python a few hours ago and stumbles across a problem. The blow snippet shows that initially I store a userInput as 1 or 2 then execute a if block. Issue is that the code jumps straight to else (even if i type 1 in the console window). I know Im making a simple mistake but any help will be appreciated.</p> <p>using Python 3.5 === running in Visual Studio 2015 === specifically cPython </p> <pre><code>userInput = float(input("Choose 1 (calculator) or 2 (area check)\n")) if(userInput =='1') : shape = input("Please enter name of shape you would like to calculate the area for\n") if(shape == 'triangle') : base = int(input("Please enter length of BASE\n")) height = int(input("Please enter HEIGHT\n")) print("The area of the triangle is %f" % ((base * height)*0.5)) elif (shape == 'circle') : radius = int(input("Please enter RADIUS\n")) print("The Area of the circle is %f" % ((radius**2)*22/7)) elif (shape == 'square') : length = int(input("Please Enter LENGTH\n")) print("The area of the square is %f" % ((length**2)*4)) else : initial1 = float(input("Please enter a number\n")) sign1 = input("please enter either +,-,*,/ \nwhen you wish to exit please type exit\n") initial2 = float(input("Please enter number 2\n")) if(sign1 == '+') : answer = float(initial1) + float(initial2) print(answer) elif(sign1 == '*') : answer = float(initial1) * float(initial2) print(answer) elif(sign1 == '-') : answer = float(initial1) - float(initial2) print(answer) elif(sign1 == '/') : answer = float(initial1) / float(initial2) print(answer) </code></pre> <p>PS. if [possible] could you keep the help as basic as possible as I wanna make sure i understand the basics perfectly.</p> <p>Thanks for all the help!! :D</p>
1
2016-09-17T14:49:09Z
39,548,199
<p>You are converting your input to float but checking for the string of the number. Change it to:</p> <pre><code>If userInput == 1.0: </code></pre> <p>Or better yet, keep it the way it is and just don't convert your user input to float in the first place. It is only necessary to convert the input to <code>float</code> or <code>int</code> if you want to do math on it. In your case you are just using it as an option, so you can keep it as a string:</p> <pre><code>userInput = input("Choose 1 (calculator) or 2 (area check)\n") </code></pre> <p>P.S. make sure to be very careful with indentation in Python. I assume your indentation is correct in your code editor, but also take care when pasting into this site. You have everything on the same level here, but some of your <code>if</code> blocks will need to be indented further in order for your program to work properly. </p>
0
2016-09-17T14:56:17Z
[ "python" ]
Faster way of converting Date column to weekday name in Pandas
39,548,139
<p>Here is my input csv file that i read via pd.read_csv()</p> <pre><code>ProductCode,Date,Receipt,Total x1,07/29/15,101790,17.35 x2,07/29/15,103601,8.89 x3,07/29/15,103601,8.58 x4,07/30/15,101425,11.95 x5,07/29/15,101422,1.09 x6,07/29/15,101422,0.99 x7,07/29/15,101422,3 y7,08/05/15,100358,7.29 x8,08/05/15,100358,2.6 z3,08/05/15,100358,2.99 import pandas as pd df = pd.read_csv('product.csv') #I have to add some columns to the data: df['Receipt_Count'] = df.groupby(['Date','Receipt'])['Receipt'].transform('count') df['Day_of_Week'] = pd.to_datetime(df['Date']).dt.weekday_name </code></pre> <p>I have around 800K of lines in my csv file. When I run the line of code for the conversion of date to weekday_name, it takes me around 2 minutes. I know that Im converting my 'Date' column to datetime first because it is treated as a string from the csv then it gets converted to its weekday equivalent. Is there any way I can shorten the conversion time?</p> <p>I'm fairly new to Pandas/Python, so I'm not sure if i missed something here. </p>
0
2016-09-17T14:49:57Z
39,548,416
<p>Specifying the format of your date strings will speed up the conversion considerably:</p> <pre><code>df['Day_of_Week'] = pd.to_datetime(df['Date'], format='%m/%d/%y').dt.weekday_name </code></pre> <p>Here are some benchmarks:</p> <pre><code>import io import pandas as pd data = io.StringIO('''\ ProductCode,Date,Receipt,Total x1,07/29/15,101790,17.35 x2,07/29/15,103601,8.89 x3,07/29/15,103601,8.58 x4,07/30/15,101425,11.95 x5,07/29/15,101422,1.09 x6,07/29/15,101422,0.99 x7,07/29/15,101422,3 y7,08/05/15,100358,7.29 x8,08/05/15,100358,2.6 z3,08/05/15,100358,2.99 ''') df = pd.read_csv(data) %timeit pd.to_datetime(df['Date']).dt.weekday_name # =&gt; 100 loops, best of 3: 2.48 ms per loop %timeit pd.to_datetime(df['Date'], format='%m/%d/%y').dt.weekday_name # =&gt; 1000 loops, best of 3: 507 µs per loop large_df = pd.concat([df] * 1000) %timeit pd.to_datetime(large_df['Date']).dt.weekday_name # =&gt; 1 loop, best of 3: 1.62 s per loop %timeit pd.to_datetime(large_df['Date'], format='%m/%d/%y').dt.weekday_name # =&gt; 10 loops, best of 3: 45.9 ms per loop </code></pre> <p>Even for the small sample you provided in the OP, performance improves by a factor of 5 &mdash; for a larger dataframe it gets much, much better.</p>
3
2016-09-17T15:16:19Z
[ "python", "pandas" ]
inside the function "bigger()", it has returned a value--a or b. so, why do still need "return"s before "bigger()"s in the function "median()"?
39,548,157
<p>inside the function "bigger()", it has returned a value--a or b. so, why do still need "return"s before "bigger()"s in the function "median()"? Here is the code:</p> <pre><code>def bigger(a,b): if a &gt; b: return a else: return b def biggest(a,b,c): return bigger(a,bigger(b,c)) def median(a,b,c): if a == biggest(a,b,c): return bigger(b,c) #the function "bigger()" above has returned a value, #so, why still need a 'return' before bigger(b,c)? elif b == biggest(a,b,c): return bigger(a,c) else: return bigger(a,b) </code></pre>
-2
2016-09-17T14:51:22Z
39,548,229
<p>A function call is an expression. Consider the following:</p> <pre><code>def add(a, b): a + b x = add(3, 5) </code></pre> <p>Would you expect <code>x</code> to now have the value <code>8</code>? You shouldn't because <code>add</code> did not return the value of the expression <code>a+b</code>. The correct definition would be</p> <pre><code>def add(a, b): return a+b </code></pre> <p>Now consider this function:</p> <pre><code>def backwards_add(a, b): add(b, a) x = backwards_add(3, 5) </code></pre> <p>Again, would you expect that <code>x</code> has the value <code>8</code>? Once again, you shouldn't because <code>backwards_add</code> did not return the value of the expression <code>add(b, a)</code>. The correct definition is</p> <pre><code>def backwards_add(a, b): return add(b, a) </code></pre> <p>There are some languages that implicitly return the value of the last expression executed in a function (cf. Perl</p> <pre><code>sub add { $1 + $2; } my $x = add(3, 5); # x has the value 8 </code></pre> <p>), but Python is not one of those languages. You must explicitly return a value, or it will return <code>None</code> for you.</p>
0
2016-09-17T14:58:29Z
[ "python", "return" ]
inside the function "bigger()", it has returned a value--a or b. so, why do still need "return"s before "bigger()"s in the function "median()"?
39,548,157
<p>inside the function "bigger()", it has returned a value--a or b. so, why do still need "return"s before "bigger()"s in the function "median()"? Here is the code:</p> <pre><code>def bigger(a,b): if a &gt; b: return a else: return b def biggest(a,b,c): return bigger(a,bigger(b,c)) def median(a,b,c): if a == biggest(a,b,c): return bigger(b,c) #the function "bigger()" above has returned a value, #so, why still need a 'return' before bigger(b,c)? elif b == biggest(a,b,c): return bigger(a,c) else: return bigger(a,b) </code></pre>
-2
2016-09-17T14:51:22Z
39,548,246
<p>I'll try to explain with examples, maybe it is simpler. </p> <p>You have defined your <code>bigger</code> function, that returns a value, right?</p> <pre><code>def bigger(a,b): if a &gt; b: return a else: return b </code></pre> <p>Now, you have defined a <code>biggest</code> function, and you are calling <code>bigger</code> from that function.</p> <pre><code>def biggest(a,b,c): return bigger(a,bigger(b,c)) </code></pre> <p>Now imagine the thousands of stuff that you could do with the value returned from <code>bigger</code>.</p> <p>You could use the <strong>returned value</strong> from <code>bigger</code> anywhere within <code>biggest</code> function. For example:</p> <pre><code>def biggest(a,b,c): some_var = bigger(a,bigger(b,c)) return some_var + 10 </code></pre> <p>Or</p> <pre><code>def biggest(a,b,c): list_of_values = [] list_of_values.append(bigger(a,bigger(b,c))) </code></pre> <p>But as you wish to use the value returned from <code>bigger</code> in the function that calls <code>biggest</code> , you should return that again so that the caller of <code>biggest</code> gets this value. Otherwise, it would get <code>None</code> which basically tells the caller "No value returned."</p>
0
2016-09-17T14:59:43Z
[ "python", "return" ]
How to use a function to change a list when passed by reference?
39,548,189
<p>The code is passed an array. My understanding is this passing is done by reference. I want the function to recursively divide the last remaining half of the list in two and set each value that it was split at to zero. The change to zero is happens in the array but when I call print a at the end I get the original array.</p> <p>What am i doing wrong?</p> <pre><code>a = range(10) def listreduction(array): if len(array) == 1: array[0] = 0 return split = len(array)/2 array[split] = 0 return listreduction(array[split:]) listreduction(a) print a </code></pre> <p>The current output is </p> <pre><code>[0, 1, 2, 3, 4, 0, 6, 7, 8, 9] </code></pre> <p>The should be more zeros to the right of the second one</p>
0
2016-09-17T14:55:25Z
39,548,211
<p>Since you use recursion, the slice operation in the argument will create new list instance which is different than you instance. That's the reason.</p> <p>You can change your code as following:</p> <pre><code>a = range(10) def list_reduction(array, position=0): if len(array) -1 &lt;= position: return split = position + (len(array) - position) / 2 array[split] = 0 return list_reduction(array, split) list_reduction(a) print a </code></pre> <p>The output is:</p> <pre><code>[0, 1, 2, 3, 4, 0, 6, 0, 0, 0] </code></pre>
1
2016-09-17T14:57:20Z
[ "python", "list" ]
How to use a function to change a list when passed by reference?
39,548,189
<p>The code is passed an array. My understanding is this passing is done by reference. I want the function to recursively divide the last remaining half of the list in two and set each value that it was split at to zero. The change to zero is happens in the array but when I call print a at the end I get the original array.</p> <p>What am i doing wrong?</p> <pre><code>a = range(10) def listreduction(array): if len(array) == 1: array[0] = 0 return split = len(array)/2 array[split] = 0 return listreduction(array[split:]) listreduction(a) print a </code></pre> <p>The current output is </p> <pre><code>[0, 1, 2, 3, 4, 0, 6, 7, 8, 9] </code></pre> <p>The should be more zeros to the right of the second one</p>
0
2016-09-17T14:55:25Z
39,548,525
<p>A slice creates a new list. If you want to do this recursively, you'll have to pass the index where the function is supposed to work on the list, not the actual slice.</p>
2
2016-09-17T15:27:44Z
[ "python", "list" ]
How to use a function to change a list when passed by reference?
39,548,189
<p>The code is passed an array. My understanding is this passing is done by reference. I want the function to recursively divide the last remaining half of the list in two and set each value that it was split at to zero. The change to zero is happens in the array but when I call print a at the end I get the original array.</p> <p>What am i doing wrong?</p> <pre><code>a = range(10) def listreduction(array): if len(array) == 1: array[0] = 0 return split = len(array)/2 array[split] = 0 return listreduction(array[split:]) listreduction(a) print a </code></pre> <p>The current output is </p> <pre><code>[0, 1, 2, 3, 4, 0, 6, 7, 8, 9] </code></pre> <p>The should be more zeros to the right of the second one</p>
0
2016-09-17T14:55:25Z
39,548,562
<p>This is probably what you want.</p> <pre><code>a = range(1, 10) def list_reduction(l, prev_split_pos=None): split_pos = (len(l) + prev_split_pos) / 2 if prev_split_pos else len(l) / 2 if split_pos == prev_split_pos: return l[split_pos] = 0 return list_reduction(l, split_pos) list_reduction(a) print a </code></pre> <p>So, to your code. Everytime you do a list slice, you actually generate a new list, which is not at all connected to the old one. This is why you don't see any mutations to it except the first one.</p>
1
2016-09-17T15:30:48Z
[ "python", "list" ]
How to use a function to change a list when passed by reference?
39,548,189
<p>The code is passed an array. My understanding is this passing is done by reference. I want the function to recursively divide the last remaining half of the list in two and set each value that it was split at to zero. The change to zero is happens in the array but when I call print a at the end I get the original array.</p> <p>What am i doing wrong?</p> <pre><code>a = range(10) def listreduction(array): if len(array) == 1: array[0] = 0 return split = len(array)/2 array[split] = 0 return listreduction(array[split:]) listreduction(a) print a </code></pre> <p>The current output is </p> <pre><code>[0, 1, 2, 3, 4, 0, 6, 7, 8, 9] </code></pre> <p>The should be more zeros to the right of the second one</p>
0
2016-09-17T14:55:25Z
39,548,618
<p>In Python argumnet passing is different from other conventional programming language. arguments are passed by object reference. And the whether the referred object will be modifed or not it depends on two things</p> <ul> <li>Whether the variable is mutable or immutable. In your case <code>range</code> will create a list so its a mutable object. That implies that if you update <code>array</code> it should also update <code>a</code>. </li> <li>Operation. <code>=</code> operation will always create new object reference. So even in your case <code>array</code> is mutable but since you are doing assignment operation It will create a new object reference. </li> </ul> <p>Following example should clear up the things for you. </p> <p><strong>Example 1</strong></p> <pre><code> &gt;&gt;&gt; a = [1,2] def fun1(array): array= array + [3] print "var array = %s" %array fun1(a) print "var a = %s" %a </code></pre> <p><strong>Output</strong></p> <pre><code>var array = [1, 2, 3] var a = [1, 2] </code></pre> <p><strong>Example 2</strong></p> <pre><code>a = [1,2] def fun1(array): array.append(3) print "var array = %s" %array fun1(a) print "var a = %s" %a </code></pre> <p><strong>Output</strong></p> <pre><code>var array = [1, 2, 3] var a = [1, 2,3] </code></pre>
1
2016-09-17T15:36:48Z
[ "python", "list" ]
Faster method of looping through pixels
39,548,328
<p>I'm looping through every pixel of some photos and storing the RGB numbers, plus the location of the pixel.</p> <p>This is my current loop which looks like it might be a very slow version of what is actually possible - I have some familiarity with pandas hence I've used a dataframe to store the data inside the loop.</p> <p>What avenues should I explore to make this more efficient? Scrap the df idea and use a vanilla list instead?</p> <pre><code>import os import pandas as pd import numpy as np from PIL import ImageColor from PIL import Image IMAGE_PATH = 'P:/image_files/' def loopThroughPixels(): im = Image.open(IMAGE_PATH + 'small_orange_white.png') w,h = im.size df = pd.DataFrame({ 'pixLocation' : [(0,0)], 'pixRGB' : [im.getpixel((0,0))] }) i = 0 for x in range(w): for y in range(h): i = i + 1 new_record = pd.DataFrame({ 'pixLocation' : [(x,y)], 'pixRGB' : [im.getpixel((x,y))] }) df = pd.concat([df,new_record]) del new_record df.reset_index(inplace = True) df.drop("index", axis = 1, inplace = True) </code></pre> <hr> <p>note</p> <p>Nehal's answer is quick put producing the wrong answer. Let me illustrate:</p> <pre><code>import pandas as pd import itertools from PIL import ImageColor from PIL import Image # create very small image to illustrate i = Image.new('RGB',(2,2)) i.putpixel((0,0), (1,1,1)) i.putpixel((1,0), (2,2,2)) i.putpixel((0,1), (3,3,3)) i.putpixel((1,1), (4,4,4)) # run the algorithm: def loopThroughPixels(): im = i w,h = im.size pixLocation = list(itertools.product(range(h), range(w))) pixRGB = list(im.getdata()) df = pd.DataFrame({'pixLocation': pixLocation, 'pixRGB': pixRGB}) return df </code></pre> <h1>the result:</h1> <p><a href="http://i.stack.imgur.com/xfAT3.png" rel="nofollow"><img src="http://i.stack.imgur.com/xfAT3.png" alt="enter image description here"></a></p> <p>COMPARE THE RESULT TO THE INITIAL putpixel STATEMENTS - THE ALGOITHM IS SAYING COORDINATE (0,1) IS (2,2,2) BUT IT SHOULD BE (3,3,3).</p>
1
2016-09-17T15:06:47Z
39,548,510
<p>A faster way would be:</p> <pre><code>import pandas as pd from PIL import ImageColor from PIL import Image IMAGE_PATH = 'P:/image_files/' def loopThroughPixels(): im = Image.open(IMAGE_PATH + 'small_orange_white.png') w,h = im.size pixLocation = [(y, x) for x in range(h) for y in range(w)] pixRGB = list(im.getdata()) df = pd.DataFrame({'pixLocation': pixLocation, 'pixRGB': pixRGB}) return df loopThroughPixels() </code></pre> <p>On a file of description...</p> <pre><code>PNG image data, 1399 x 835, 8-bit/color RGBA, non-interlaced </code></pre> <p>...it took:</p> <pre><code>In [1]: %timeit loopThroughPixels() 1 loop, best of 3: 324 ms per loop </code></pre> <p>Update (comparison with options from comments):</p> <pre><code>In [14]: w = 1399 In [15]: h = 835 In [16]: [(y, x) for x in range(h) for y in range(w)] == list(zip(list(range(w))*h, sorted(list(range(h))*w))) Out[16]: True In [17]: %timeit [(y, x) for x in range(h) for y in range(w)] 10 loops, best of 3: 107 ms per loop In [18]: %timeit list(zip(list(range(w))*h, sorted(list(range(h))*w))) 1 loop, best of 3: 207 ms per loop </code></pre>
3
2016-09-17T15:26:08Z
[ "python", "pandas" ]
Python 3: pass filename variable from Gtk.FileChooser to __init__ function
39,548,356
<p>I'm writing a Gtk program that does stuff with images. I got app window with menu and connected one of the buttons to Gtk.FileChooser that gets a filename (i can open it with Gtk.Image() but cant do much with such object afaik). The problem is I don't know how to pass the filename to my <strong>init</strong> function so I can open image from that filename using opencv (need to be able to draw with mouse on that image thats why opencv3). Here's the code structure Im using:</p> <pre><code>class main_win(Gtk.Window): def __init__(self): '''menu stuff and box with widgets, few labels''' def FileChooser(self): dialog = Gtk.FileChooserDialog("Open a File Image", self, Gtk.FileChooserAction.OPEN, (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, Gtk.STOCK_OPEN, Gtk.ResponseType.OK)) response = dialog.run() if response == Gtk.ResponseType.OK: path = dialog.get_filename() elif response == Gtk.ResponseType.CANCEL: pass dialog.destroy() </code></pre> <p>Ideally I would prefere to put this inside init:</p> <pre><code>img = cv2.imread(path,0) cv2.imshow('image',img) </code></pre> <p>Then afaik i could do stuff with the image in opencv window like for example getting pixel (from a drawn area with mouse or just a single pixel by mouse click) statistics into gtk.label or drawing plots.</p> <p>Im fairly new to python, so maybe I'm asking sth super easy or super stupid;p Thanks in advance ;).</p>
0
2016-09-17T15:09:31Z
39,550,748
<p>Well, maybe you have a legitimate reason for using OpenCV to simply display an image (because for example you use that library elsewhere in your code) but you can use GTK+ 3 facilities for that.</p> <pre><code>import os, re import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk class main_win(Gtk.Window): def __init__(self): '''menu stuff and box with widgets, few labels''' super().__init__(title="Image show") main_column = Gtk.Box(spacing=6, orientation=Gtk.Orientation.VERTICAL) self.add(main_column) button1 = Gtk.Button(label="Get Image") button1.connect("clicked", self.FileChooser) main_column.pack_start(button1, True, True, 0) self.embedded_image = Gtk.Image() main_column.pack_start(self.embedded_image, True, True, 0) def FileChooser(self, widget): dialog = Gtk.FileChooserDialog("Open a File Image", self, Gtk.FileChooserAction.OPEN, (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, Gtk.STOCK_OPEN, Gtk.ResponseType.OK)) response = dialog.run() if response == Gtk.ResponseType.OK: path = dialog.get_filename() self.embedded_image.set_from_file(path) self.show_all() dialog.destroy() main_windows = main_win() main_windows.connect("delete-event", Gtk.main_quit) main_windows.show_all() Gtk.main() </code></pre> <p>You can use a <a href="https://lazka.github.io/pgi-docs/Gtk-3.0/classes/Image.html" rel="nofollow"><code>Gtk.Image()</code></a> to put an image anywhere in your interface. You can update it using <a href="https://lazka.github.io/pgi-docs/Gtk-3.0/classes/Image.html#Gtk.Image.set_from_file" rel="nofollow"><code>.set_from_file()</code></a>.</p>
0
2016-09-17T19:13:43Z
[ "python", "variables", "scope", "gtk3", "opencv3.0" ]
Python 3: pass filename variable from Gtk.FileChooser to __init__ function
39,548,356
<p>I'm writing a Gtk program that does stuff with images. I got app window with menu and connected one of the buttons to Gtk.FileChooser that gets a filename (i can open it with Gtk.Image() but cant do much with such object afaik). The problem is I don't know how to pass the filename to my <strong>init</strong> function so I can open image from that filename using opencv (need to be able to draw with mouse on that image thats why opencv3). Here's the code structure Im using:</p> <pre><code>class main_win(Gtk.Window): def __init__(self): '''menu stuff and box with widgets, few labels''' def FileChooser(self): dialog = Gtk.FileChooserDialog("Open a File Image", self, Gtk.FileChooserAction.OPEN, (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, Gtk.STOCK_OPEN, Gtk.ResponseType.OK)) response = dialog.run() if response == Gtk.ResponseType.OK: path = dialog.get_filename() elif response == Gtk.ResponseType.CANCEL: pass dialog.destroy() </code></pre> <p>Ideally I would prefere to put this inside init:</p> <pre><code>img = cv2.imread(path,0) cv2.imshow('image',img) </code></pre> <p>Then afaik i could do stuff with the image in opencv window like for example getting pixel (from a drawn area with mouse or just a single pixel by mouse click) statistics into gtk.label or drawing plots.</p> <p>Im fairly new to python, so maybe I'm asking sth super easy or super stupid;p Thanks in advance ;).</p>
0
2016-09-17T15:09:31Z
39,563,468
<p>Moved to pyqt4, not only opencv but also matplotlib works there smoothly ;)</p>
0
2016-09-18T23:06:59Z
[ "python", "variables", "scope", "gtk3", "opencv3.0" ]
How does threading.join() detect a timeout?
39,548,357
<p>We are running quit a large Python code to randomly scan the parameter space of some physics models (So, it is very difficult to give a minimal example, sorry). Evaluating one parameter point takes about 300ms, but sometimes (I don't know why) the evaluation suddenly takes several hours which kills the CPU budget we have on a computing cluster.</p> <p>So, my idea was to use threading to give each evaluation of a parameter point a maximal time for running. If the evaluation takes longer, then I can ignore this point as being unphysical. Now, this does not seem to work. I start the calculation in a new thread, join it to the main thread with a timeout set to, say, 1 second, but the main thread still keeps on waiting for the calculation to terminate (which takes significantly longer than 1 second).</p> <p>How is this possible? How does threading measure the time the new thread is already running? I have to say that during the evaluation of one parameter point I heavily use nlopt, numpy and scipy. Most of which is, as I assume, written not directly in python but rather some binaries are used to speed up the calculation. Does this affect threading (since the functions are "black boxes" to it)?</p> <p>Thanks! </p>
-1
2016-09-17T15:09:32Z
39,549,124
<p>Short answer:</p> <p>I don't think <code>threading.join</code> checks timeout. You have to check if it has timed out.</p> <ul> <li><a href="http://stackoverflow.com/questions/13821156/timeout-function-using-threading-in-python-does-not-work">Timeout function using threading in python does not work</a></li> <li><a href="http://stackoverflow.com/questions/323972/is-there-any-way-to-kill-a-thread-in-python">Is there any way to kill a Thread in Python?</a></li> </ul> <p>In either case to get a working solution, a minimal code snippet would help. This is mostly a guess, but if the main process isn't checking the timeout then it will just keep on keeping on.</p> <p>Longer answer:</p> <p>Let's see where the <code>timeout</code> parameter goes:</p> <p><a href="https://github.com/python/cpython/blob/464aaba29700905badb7137e5048f8965833f946/Lib/threading.py#L1060" rel="nofollow">https://github.com/python/cpython/blob/464aaba29700905badb7137e5048f8965833f946/Lib/threading.py#L1060</a></p> <pre><code>self._wait_for_tstate_lock(timeout=max(timeout, 0)) </code></pre> <p><a href="https://github.com/python/cpython/blob/464aaba29700905badb7137e5048f8965833f946/Lib/threading.py#L1062-L1074" rel="nofollow">https://github.com/python/cpython/blob/464aaba29700905badb7137e5048f8965833f946/Lib/threading.py#L1062-L1074</a></p> <pre><code>def _wait_for_tstate_lock(self, block=True, timeout=-1): # Issue #18808: wait for the thread state to be gone. # At the end of the thread's life, after all knowledge of the thread # is removed from C data structures, C code releases our _tstate_lock. # This method passes its arguments to _tstate_lock.acquire(). # If the lock is acquired, the C code is done, and self._stop() is # called. That sets ._is_stopped to True, and ._tstate_lock to None. lock = self._tstate_lock if lock is None: # already determined that the C code is done assert self._is_stopped elif lock.acquire(block, timeout): lock.release() self._stop() </code></pre> <p>If no lock make sure the thread is stopped. Otherwise acquire the lock with given the parameters <code>block</code> and <code>timeout</code>.</p> <p><a href="https://github.com/python/cpython/blob/464aaba29700905badb7137e5048f8965833f946/Lib/threading.py#L117" rel="nofollow">https://github.com/python/cpython/blob/464aaba29700905badb7137e5048f8965833f946/Lib/threading.py#L117</a></p> <pre><code>def acquire(self, blocking=True, timeout=-1): """Acquire a lock, blocking or non-blocking. When invoked without arguments: if this thread already owns the lock, increment the recursion level by one, and return immediately. Otherwise, if another thread owns the lock, block until the lock is unlocked. Once the lock is unlocked (not owned by any thread), then grab ownership, set the recursion level to one, and return. If more than one thread is blocked waiting until the lock is unlocked, only one at a time will be able to grab ownership of the lock. There is no return value in this case. When invoked with the blocking argument set to true, do the same thing as when called without arguments, and return true. When invoked with the blocking argument set to false, do not block. If a call without an argument would block, return false immediately; otherwise, do the same thing as when called without arguments, and return true. When invoked with the floating-point timeout argument set to a positive value, block for at most the number of seconds specified by timeout and as long as the lock cannot be acquired. Return true if the lock has been acquired, false if the timeout has elapsed. """ me = get_ident() if self._owner == me: self._count += 1 return 1 rc = self._block.acquire(blocking, timeout) if rc: self._owner = me self._count = 1 return rc </code></pre> <p>To acquire the lock get the thread identity. Increment a count.</p> <p>Really get the lock.</p> <p><a href="https://github.com/python/cpython/blob/464aaba29700905badb7137e5048f8965833f946/Lib/threading.py#L98" rel="nofollow">https://github.com/python/cpython/blob/464aaba29700905badb7137e5048f8965833f946/Lib/threading.py#L98</a></p> <pre><code>self._block = _allocate_lock() </code></pre> <p><a href="https://github.com/python/cpython/blob/464aaba29700905badb7137e5048f8965833f946/Lib/threading.py#L33" rel="nofollow">https://github.com/python/cpython/blob/464aaba29700905badb7137e5048f8965833f946/Lib/threading.py#L33</a></p> <pre><code>_allocate_lock = _thread.allocate_lock </code></pre> <p><a href="https://github.com/python/cpython/blob/464aaba29700905badb7137e5048f8965833f946/Lib/threading.py#L4" rel="nofollow">https://github.com/python/cpython/blob/464aaba29700905badb7137e5048f8965833f946/Lib/threading.py#L4</a></p> <pre><code>import _thread </code></pre> <p><a href="https://github.com/python/cpython/blob/7b90e3674be86479c51faf872d0b9367c9fc2f96/Modules/_threadmodule.c#L1300-L1301" rel="nofollow">https://github.com/python/cpython/blob/7b90e3674be86479c51faf872d0b9367c9fc2f96/Modules/_threadmodule.c#L1300-L1301</a></p> <pre><code>static PyMethodDef thread_methods[] = { {"start_new_thread", (PyCFunction)thread_PyThread_start_new_thread, METH_VARARGS, start_new_doc}, {"start_new", (PyCFunction)thread_PyThread_start_new_thread, METH_VARARGS, start_new_doc}, {"allocate_lock", (PyCFunction)thread_PyThread_allocate_lock, METH_NOARGS, allocate_doc}, {"allocate", (PyCFunction)thread_PyThread_allocate_lock, METH_NOARGS, allocate_doc}, {"exit_thread", (PyCFunction)thread_PyThread_exit_thread, METH_NOARGS, exit_doc}, {"exit", (PyCFunction)thread_PyThread_exit_thread, METH_NOARGS, exit_doc}, {"interrupt_main", (PyCFunction)thread_PyThread_interrupt_main, METH_NOARGS, interrupt_doc}, {"get_ident", (PyCFunction)thread_get_ident, METH_NOARGS, get_ident_doc}, {"_count", (PyCFunction)thread__count, METH_NOARGS, _count_doc}, {"stack_size", (PyCFunction)thread_stack_size, METH_VARARGS, stack_size_doc}, {"_set_sentinel", (PyCFunction)thread__set_sentinel, METH_NOARGS, _set_sentinel_doc}, {NULL, NULL} /* sentinel */ }; </code></pre> <p>Define the <code>allocated_lock</code> method as with the type <code>PyCFunction</code> and name <code>thread_PyThread_allocate_lock</code></p> <p><a href="https://github.com/python/cpython/blob/7b90e3674be86479c51faf872d0b9367c9fc2f96/Modules/_threadmodule.c#L1128-L1131" rel="nofollow">https://github.com/python/cpython/blob/7b90e3674be86479c51faf872d0b9367c9fc2f96/Modules/_threadmodule.c#L1128-L1131</a></p> <pre><code>static PyObject * thread_PyThread_allocate_lock(PyObject *self) { return (PyObject *) newlockobject(); } </code></pre> <p><a href="https://github.com/python/cpython/blob/7b90e3674be86479c51faf872d0b9367c9fc2f96/Modules/_threadmodule.c#L538-L553" rel="nofollow">https://github.com/python/cpython/blob/7b90e3674be86479c51faf872d0b9367c9fc2f96/Modules/_threadmodule.c#L538-L553</a></p> <pre><code>static lockobject * newlockobject(void) { lockobject *self; self = PyObject_New(lockobject, &amp;Locktype); if (self == NULL) return NULL; self-&gt;lock_lock = PyThread_allocate_lock(); self-&gt;locked = 0; self-&gt;in_weakreflist = NULL; if (self-&gt;lock_lock == NULL) { Py_DECREF(self); PyErr_SetString(ThreadError, "can't allocate lock"); return NULL; } return self; } </code></pre> <p>Allocate a new context and lock</p> <p><a href="https://github.com/python/cpython/blob/2d264235f6e066611b412f7c2e1603866e0f7f1b/Python/thread_pthread.h#L276" rel="nofollow">https://github.com/python/cpython/blob/2d264235f6e066611b412f7c2e1603866e0f7f1b/Python/thread_pthread.h#L276</a></p> <pre><code>PyThread_type_lock PyThread_allocate_lock(void) { sem_t *lock; int status, error = 0; dprintf(("PyThread_allocate_lock called\n")); if (!initialized) PyThread_init_thread(); lock = (sem_t *)PyMem_RawMalloc(sizeof(sem_t)); if (lock) { status = sem_init(lock,0,1); CHECK_STATUS("sem_init"); if (error) { PyMem_RawFree((void *)lock); lock = NULL; } } dprintf(("PyThread_allocate_lock() -&gt; %p\n", lock)); return (PyThread_type_lock)lock; } </code></pre> <p><a href="https://github.com/python/cpython/blob/2d264235f6e066611b412f7c2e1603866e0f7f1b/Python/thread.c#L60-L77" rel="nofollow">https://github.com/python/cpython/blob/2d264235f6e066611b412f7c2e1603866e0f7f1b/Python/thread.c#L60-L77</a></p> <pre><code>void PyThread_init_thread(void) { #ifdef Py_DEBUG char *p = Py_GETENV("PYTHONTHREADDEBUG"); if (p) { if (*p) thread_debug = atoi(p); else thread_debug = 1; } #endif /* Py_DEBUG */ if (initialized) return; initialized = 1; dprintf(("PyThread_init_thread called\n")); PyThread__init_thread(); } </code></pre> <p><a href="https://github.com/python/cpython/blob/2d264235f6e066611b412f7c2e1603866e0f7f1b/Python/thread_pthread.h#L170-L176" rel="nofollow">https://github.com/python/cpython/blob/2d264235f6e066611b412f7c2e1603866e0f7f1b/Python/thread_pthread.h#L170-L176</a></p> <pre><code>static void PyThread__init_thread(void) { #if defined(_AIX) &amp;&amp; defined(__GNUC__) extern void pthread_init(void); pthread_init(); #endif } </code></pre> <p><a href="https://github.com/python/cpython/blob/f243de2bc8d940316ce8da778ec02a7bbe594de1/configure.ac#L3416" rel="nofollow">https://github.com/python/cpython/blob/f243de2bc8d940316ce8da778ec02a7bbe594de1/configure.ac#L3416</a></p> <pre><code>AC_CHECK_FUNCS(alarm accept4 setitimer getitimer bind_textdomain_codeset chown \ clock confstr ctermid dup3 execv faccessat fchmod fchmodat fchown fchownat \ fexecve fdopendir fork fpathconf fstatat ftime ftruncate futimesat \ futimens futimes gai_strerror getentropy \ getgrouplist getgroups getlogin getloadavg getpeername getpgid getpid \ getpriority getresuid getresgid getpwent getspnam getspent getsid getwd \ if_nameindex \ initgroups kill killpg lchmod lchown lockf linkat lstat lutimes mmap \ memrchr mbrtowc mkdirat mkfifo \ mkfifoat mknod mknodat mktime mremap nice openat pathconf pause pipe2 plock poll \ posix_fallocate posix_fadvise pread \ pthread_init pthread_kill putenv pwrite readlink readlinkat readv realpath renameat \ select sem_open sem_timedwait sem_getvalue sem_unlink sendfile setegid seteuid \ setgid sethostname \ setlocale setregid setreuid setresuid setresgid setsid setpgid setpgrp setpriority setuid setvbuf \ sched_get_priority_max sched_setaffinity sched_setscheduler sched_setparam \ sched_rr_get_interval \ sigaction sigaltstack siginterrupt sigpending sigrelse \ sigtimedwait sigwait sigwaitinfo snprintf strftime strlcpy symlinkat sync \ sysconf tcgetpgrp tcsetpgrp tempnam timegm times tmpfile tmpnam tmpnam_r \ truncate uname unlinkat unsetenv utimensat utimes waitid waitpid wait3 wait4 \ wcscoll wcsftime wcsxfrm wmemcmp writev _getpty) </code></pre> <p><a href="http://man7.org/linux/man-pages/man7/pthreads.7.html" rel="nofollow">http://man7.org/linux/man-pages/man7/pthreads.7.html</a></p> <p>All of this to ask two things: is timeout a <code>float</code>? and are you checking if <code>isAlive</code>?:</p> <ul> <li><a href="https://docs.python.org/3/library/threading.html#threading.Thread.join" rel="nofollow">https://docs.python.org/3/library/threading.html#threading.Thread.join</a></li> </ul> <blockquote> <p>When the timeout argument is present and not None, it should be a floating point number specifying a timeout for the operation in seconds (or fractions thereof). As join() always returns None, you must call is_alive() after join() to decide whether a timeout happened – if the thread is still alive, the join() call timed out.</p> </blockquote>
0
2016-09-17T16:29:34Z
[ "python", "multithreading", "numpy", "nlopt" ]
How to integrate python3-flake8 with Atom in Ubuntu 16.04
39,548,524
<p>I installed python3-flake8 on Ubuntu 16.04 with the command <em>sudo apt-get install python3-flake8</em> Then proceeded to install the flake8 linter package on Atom. However on restart it shows the following error <em>Error: spawn flake8 ENOENT</em>.</p> <p>I do not know if atom is able to detect flake8 on my system or if it is some other kind of problem.</p> <p>Error message:</p> <pre><code>Error: spawn flake8 ENOENT at exports._errnoException (util.js:890:11) at Process.ChildProcess._handle.onexit (internal/child_process.js:182:32) at onErrorNT (internal/child_process.js:348:16) at _combinedTickCallback (internal/process/next_tick.js:74:11) at process._tickCallback (internal/process/next_tick.js:98:9) </code></pre>
1
2016-09-17T15:27:44Z
39,549,171
<p>From Ubuntu 16.04, the <code>flake8</code> binary can be found in the <code>flake8</code> package rather than <code>python3-flake8</code> (<a href="http://packages.ubuntu.com/xenial/flake8" rel="nofollow">Xenial/16.04</a> and <a href="http://packages.ubuntu.com/yakkety/flake8" rel="nofollow">Yakkety/16.10</a>). Installing this will allow you to use the <code>flake8</code> command in the terminal, and will also allow Atom to access it and lint your code.</p> <p>You can install <code>flake8</code> correctly with:</p> <pre><code>sudo apt-get install flake8 </code></pre>
1
2016-09-17T16:34:20Z
[ "python", "ubuntu", "atom" ]
Create a a segment with the given number of verts and hook and empty to every verts in the segment
39,548,544
<p>How can I create a segment with for example 30 verices and then connect an empty with an Hook parenting to every veritces in the segment, all this via Python in Blender 3d?</p>
0
2016-09-17T15:29:32Z
39,708,428
<p>I'm going to say that this was frustrating but after trying several different approaches this is the one way that I got to work.</p> <pre><code>import bpy import bmesh num_verts = 30 scn = bpy.context.scene D = bpy.data.objects verts = [] edges = [] for i in range(num_verts): verts += [(i, 0.0, 0.0)] if i &gt; 0: edges += [(i, i-1)] mesh_data = bpy.data.meshes.new("hooked verts") mesh_data.from_pydata(verts, edges, []) mesh_data.update() obj = D.new("Hooked line", mesh_data) obj.select = True scn.objects.link(obj) scn.objects.active = obj bpy.ops.object.mode_set(mode='EDIT') for i in range(len(obj.data.vertices)): bm = bmesh.from_edit_mesh(obj.data) bpy.ops.mesh.select_all(action='DESELECT') bm.verts.ensure_lookup_table() bm.verts[i].select = True bpy.ops.object.hook_add_newob() bpy.context.selected_objects[0].name = 'Hook' bm.free() bpy.ops.object.mode_set(mode='OBJECT') </code></pre> <p>To assign a hook to a vertex, the object needs to be in edit mode with the desired vertex selected. It would seem that the add hook operators make a mess of the edit mesh data so that after the first hook modifier is created the mesh data is no longer valid. The solution - re-create the bmesh data and select a vertex after creating each hook.</p>
0
2016-09-26T17:00:48Z
[ "python", "blender", "segment", "vertices" ]
Read dicom file in python by sample ITK
39,548,551
<p>I use simple ITK for read dicom file but I do not know how to show it into a QLabel.</p> <pre><code>reader = SimpleITK.ImageFileReader() reader.SetFileName("M:\\CT-RT DICOM\ct\\CT111253009007.dcm") image1 = reader.Execute() </code></pre> <p>How can I show image1 in QLabel?</p>
1
2016-09-17T15:29:51Z
39,632,974
<p>Maybe something like this? It should generate a QImage which you can then pass into the QLabel. </p> <p>A few catch-me's will be the 16 bit image data (I assume) from the DICOM which needs passed into the RGB image. Further the scaling of the image. But this should be enough to get you started</p> <pre><code>from PySide import QtGui width,height = img.GetSize() img = QtGui.QImage(width, height, QtGui.QImage.Format_RGB16) for x in xrange(width): for y in xrange(height): img.setPixel(x, y, QtGui.QColor(data[x,y],data[x,y],data[x,y])) pix = QtGui.QPixmap.fromImage(img) QtGui.QLabel label; label.setPixmap(pix); label.setMask(pix.mask()); label.show(); </code></pre>
0
2016-09-22T07:35:21Z
[ "python", "pyqt", "dicom", "itk" ]
python - import namespace
39,548,560
<p>If I have a library like:</p> <p>MyPackage:</p> <ul> <li><p><code>__init__.py</code></p></li> <li><p>SubPackage1</p> <ul> <li><code>__init__.py</code></li> <li>moduleA.py</li> <li>moduleB.py </li> </ul></li> <li>SubPackage2 <ul> <li><code>__init__.py</code></li> <li>moduleC.py</li> <li>moduleD.py</li> </ul></li> </ul> <p>But I want that users can import moduleA like <code>import MyPackage.moduleA</code> directly. Can I implement this by write some rules in <code>MyPackage/__init__.py</code>?</p>
0
2016-09-17T15:30:33Z
39,548,591
<p>In <code>MyPackage/__init__.py</code>, import the modules you want available from the subpackages:</p> <pre><code>from __future__ import absolute_import # Python 3 import behaviour from .SubPackage1 import moduleA from .SubPackage2 import moduleD </code></pre> <p>This makes both <code>moduleA</code> and <code>moduleD</code> globals in <code>MyPackage</code>. You can then use:</p> <pre><code>from MyPackage import moduleA </code></pre> <p>and that'll bind to the same module, or do</p> <pre><code>import MyPackage myPackage.moduleA </code></pre> <p>to directly access that module.</p> <p>However, you <em>can't</em> use</p> <pre><code>from MyPackage.moduleA import somename </code></pre> <p>as that requires <code>moduleA</code> to live directly in MyPackage; a global in the <code>__init__</code> won't cut it there.</p>
3
2016-09-17T15:34:10Z
[ "python", "import", "namespaces", "package" ]
Python: monster list need monster help, how do I fill my list the proper way?
39,548,703
<p>So I started with Python yesterday and for my first project I want to make monsters battle each other.</p> <p>I'm still at the start and I want to fill a list with monsters I created. My monster function asks for how many monsters it should create and gives back a list with all of them.</p> <p>Somehow my code is wrong and only gives back one single monster :(</p> <pre><code>def create_monster(number): monster = [0] * number for i in monster: """monster = [ID,GENDER,NAME,HP,ATK,DEF,SATK,SDEF,AGIL,]""" monster[i] = [monster_identifier(), monster_gender(), None] monster[i][2] = monster_name(monster[i][1]) return monster </code></pre> <p>The output of this code is for number = 3 for example</p> <pre><code>[[3, 'Male', 'Berid'], 0, 0] </code></pre> <p>but should be something like this</p> <pre><code>[[1,'Male','Berid'],[2,'Female','David'],[3,'Male','Holger']] </code></pre>
0
2016-09-17T15:46:06Z
39,548,736
<p>Your loop:</p> <pre><code>for i in monster: </code></pre> <p>iterates over the <em>values</em> in the <code>monster</code> list. You are not getting indices, as Python loops are <a href="https://en.wikipedia.org/wiki/Foreach_loop" rel="nofollow"><em>foreach</em> constructs</a>.</p> <p>Your list only contains the number <code>0</code>:</p> <pre><code>monster = [0] * number </code></pre> <p>so all <code>i</code> is ever set to is <code>0</code>. This in turn is why you only ever alter the element at index 0, everywhere you wrote <code>monster[i]</code> you could have written <code>monster[0]</code> for the same results.</p> <p>Rather than pre-build the list with zeros, just use <a href="https://docs.python.org/3/library/stdtypes.html#mutable-sequence-types" rel="nofollow"><code>list.append()</code></a> to add new elements as you loop, and use <a href="https://docs.python.org/3/library/stdtypes.html#ranges" rel="nofollow"><code>range()</code></a> to count out how many monsters you create:</p> <pre><code>def create_monsters(number): monsters = [] # empty list for i in range(number): # loop number times gender = monster_gender() monster = [monster_identifier(), gender, monster_name(gender)] monsters.append(monster) # add to the list at the end return monsters </code></pre> <p>I renamed the function and list to the plural <code>monsters</code> to indicate this is not just about 1 monster.</p>
3
2016-09-17T15:49:40Z
[ "python", "arrays", "list" ]
Python: monster list need monster help, how do I fill my list the proper way?
39,548,703
<p>So I started with Python yesterday and for my first project I want to make monsters battle each other.</p> <p>I'm still at the start and I want to fill a list with monsters I created. My monster function asks for how many monsters it should create and gives back a list with all of them.</p> <p>Somehow my code is wrong and only gives back one single monster :(</p> <pre><code>def create_monster(number): monster = [0] * number for i in monster: """monster = [ID,GENDER,NAME,HP,ATK,DEF,SATK,SDEF,AGIL,]""" monster[i] = [monster_identifier(), monster_gender(), None] monster[i][2] = monster_name(monster[i][1]) return monster </code></pre> <p>The output of this code is for number = 3 for example</p> <pre><code>[[3, 'Male', 'Berid'], 0, 0] </code></pre> <p>but should be something like this</p> <pre><code>[[1,'Male','Berid'],[2,'Female','David'],[3,'Male','Holger']] </code></pre>
0
2016-09-17T15:46:06Z
39,548,754
<p>simply replace </p> <pre><code>monster = [0] * number </code></pre> <p>with </p> <pre><code>monster = range(number) </code></pre>
1
2016-09-17T15:51:12Z
[ "python", "arrays", "list" ]
How do I get np.where to accept more arguments, so it will filter >, < , and =; not just > and <?
39,548,753
<p>I am using python 3.5 and have the numpy and pandas libraries imported. I have created a DataFrame called df, which has an index starting at zero, and two columns; Percentage of Change (PofChg) and Up, Down, or Flat (U_D_F).</p> <p>For the U_D_F column I want to populate it with the words 'Up', 'Down', 'Flat', based off of the PofChg column. Up means it was greater than zero, Down means it was less than zero, and Flat means it was equal to zero. </p> <p>The np.where function seems to work well except for two things, (1) Why is it displaying "Down" in the U_D_F column when the number in the PofChg column is "Zero" (2) How do I make the np.where function accept more arguments, i.e. instead of saying - if df.PofChg is > 0 , if true display "Up" or if false display "Down", I want to change it to - if df.PofChg is > 0, if true display "Up" or if false display "Down", but if it is equal to zero then Display "Flat"</p> <p>This is the current output when I print df</p> <pre><code> PofChg U_D_F 0 -1 Down 1 0 Down 2 1 Up 3 -2 Down 4 0 Down 5 5 Up 6 3 Up 7 -6 Down Press any key to continue . . . </code></pre> <p>This is my code</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame({'PofChg':[-1,0,1,-2,0,5,3,-6]}) df['U_D_F'] = np.where(df.PofChg &gt; 0 , 'Up','Down');df print(df) </code></pre>
3
2016-09-17T15:51:09Z
39,548,815
<p>I would use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.map.html" rel="nofollow">map()</a> in conjunction with <code>np.sign()</code> in this case:</p> <pre><code>In [133]: mp = {-1:'Down', 0:'Flat', 1:'Up'} In [134]: df['U_D_F'] = np.sign(df.PofChg).map(mp) In [135]: df Out[135]: PofChg U_D_F 0 -1 Down 1 0 Flat 2 1 Up 3 -2 Down 4 0 Flat 5 5 Up 6 3 Up 7 -6 Down </code></pre> <p>np.sign():</p> <pre><code>In [136]: np.sign(df.PofChg) Out[136]: 0 -1 1 0 2 1 3 -1 4 0 5 1 6 1 7 -1 Name: PofChg, dtype: int64 </code></pre> <p>Type of <code>np.sign(df.PofChg)</code>:</p> <pre><code>In [9]: type(np.sign(df.PofChg)) Out[9]: pandas.core.series.Series </code></pre>
4
2016-09-17T15:56:52Z
[ "python", "pandas", "numpy", "dataframe", "where" ]
How do I get np.where to accept more arguments, so it will filter >, < , and =; not just > and <?
39,548,753
<p>I am using python 3.5 and have the numpy and pandas libraries imported. I have created a DataFrame called df, which has an index starting at zero, and two columns; Percentage of Change (PofChg) and Up, Down, or Flat (U_D_F).</p> <p>For the U_D_F column I want to populate it with the words 'Up', 'Down', 'Flat', based off of the PofChg column. Up means it was greater than zero, Down means it was less than zero, and Flat means it was equal to zero. </p> <p>The np.where function seems to work well except for two things, (1) Why is it displaying "Down" in the U_D_F column when the number in the PofChg column is "Zero" (2) How do I make the np.where function accept more arguments, i.e. instead of saying - if df.PofChg is > 0 , if true display "Up" or if false display "Down", I want to change it to - if df.PofChg is > 0, if true display "Up" or if false display "Down", but if it is equal to zero then Display "Flat"</p> <p>This is the current output when I print df</p> <pre><code> PofChg U_D_F 0 -1 Down 1 0 Down 2 1 Up 3 -2 Down 4 0 Down 5 5 Up 6 3 Up 7 -6 Down Press any key to continue . . . </code></pre> <p>This is my code</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame({'PofChg':[-1,0,1,-2,0,5,3,-6]}) df['U_D_F'] = np.where(df.PofChg &gt; 0 , 'Up','Down');df print(df) </code></pre>
3
2016-09-17T15:51:09Z
39,548,816
<blockquote> <p>Why is it displaying "Down" in the U_D_F column when the number in the PofChg column is "Zero" </p> </blockquote> <p>That is because your condition to <code>np.where</code> was > 0, so, if it is 0, the condition fails, and it chooses the alternative.</p> <blockquote> <p>I want to change it to - if df.PofChg is > 0, if true display "Up" or if false display "Down", but if it is equal to zero then Display "Flat"</p> </blockquote> <pre><code>np.where(df.PofChg &gt; 0 , 'Up', np.where(df.PofChg == 0, 'Flat', 'Down')) </code></pre> <p>If <code>df.PofChg &gt; 0</code>, it chooses <code>'Up'</code>; otherwise, if <code>df.PofChg == 0</code>, it choose <code>'Flat'</code>, and otherwise <code>'Down'</code>.</p>
5
2016-09-17T15:56:54Z
[ "python", "pandas", "numpy", "dataframe", "where" ]
AttributeError not generated in case of passing method reference
39,548,864
<p>I have one simple doubt with respect to python 2.7:</p> <p>I have created an abstract base class and a child class:</p> <pre><code>from abc import ABCMeta, abstractmethod class Base: """ Abstract base class for all entities. """ __metaclass__ = ABCMeta def __init__(self, name): self.name = name def send_data(self): self.send_data() class Child (Base): def __init__(self, name): super(Child, self).__init__(name=name) </code></pre> <p>When the object for the child class is created and the send_method is called I get the following error which is the expected behavior:</p> <pre><code>sample = Child('test') sample.send_data() # … RuntimeError: maximum recursion depth exceeded </code></pre> <p>But when the send_method reference is passed in the base class and call is made to send_method by creating the child class object I think the expected behavior is to receive <code>AttributeError</code> but I am surprised to see no error is generated. Please explain.</p> <pre><code>from abc import ABCMeta, abstractmethod class Base: """ Abstract base class for all entities. """ __metaclass__ = ABCMeta def __init__(self, name, parent): self.name = name self.parent = parent def send_data(self): self.send_data sample = Child('test') sample.send_data() # No error </code></pre>
-2
2016-09-17T16:01:37Z
39,548,895
<p>In your first example you simply created a recursive function:</p> <pre><code>def send_data(self): self.send_data() </code></pre> <p>This calls itself, without end, and that's why you end up with a recursion depth exception.</p> <p>Your second example <em>doesn't actually call the method</em>:</p> <pre><code>def send_data(self): self.send_data </code></pre> <p>The <em>only</em> difference here is that you forgot to use <code>()</code>.</p> <p>None of this has anything to do with abstract base classes or inheritance. You didn't mark the <code>send_data</code> function as abstract, and even if you did, all that using <code>abstractmethod</code> does is make it impossible to create an instance of a class without a concrete implementation to replace it.</p> <p>You won't get an <code>AttributeError</code> just because you defined a method on an <code>ABCMeta</code> class. And note that methods are just attributes on a class; they don't live a separate namespace. <code>self.send_data</code> references the bound method, not some other attribute that is separate. Referencing the method without calling it does nothing otherwise.</p>
0
2016-09-17T16:06:03Z
[ "python", "abstract-base-class" ]
Indexing a matrix by a column vector
39,548,914
<p>I have a matrix M of size m x n, and column vector of m x 1. For each of m rows, I need to pickup the index corresponding to the value in the column vector minus 1. Thus, giving me answer m x 1. How can I do this?</p> <pre><code>zb=a1.a3[np.arange(a1.z3.shape[0]),a1.train_labels-1] zb.shape Out[72]: (4000, 4000) a1.z3.shape Out[73]: (4000, 26) a1.train_labels.shape Out[74]: (4000, 1) a1.train_labels.head() Out[75]: 22 1618 25 2330 1 1651 17 133 17 2360 5 #my column vector a1.train_labels is shuffled. I don't want to unshuffle it. </code></pre>
1
2016-09-17T16:08:09Z
39,549,012
<p>If your 2d array is <em>M</em>, and indices are a 1d array <code>v</code>, then you can use</p> <pre><code>M[np.arange(len(v)), v - 1] </code></pre> <p>For example:</p> <pre><code>In [14]: M = np.array([[1, 2], [3, 4]]) In [15]: v = np.array([2, 1]) In [16]: M[np.arange(len(v)), v - 1] Out[16]: array([2, 3]) </code></pre>
1
2016-09-17T16:17:31Z
[ "python", "numpy" ]
New Programmer, How do you use If and Elif and Else statements? Its giving me NameError: name 'No' is not defined
39,548,972
<pre><code>answer = input('Hi! Would you like to say something? (No or Yes)') if answer == No or no: print('Okay then, have a good day!') elif answer == Yes or yes: answertwo = input('What would you like to say?') print(answertwo, 'Hmmmmmm, Intresting.') </code></pre> <p> <pre><code> **if answer == No or no: NameError: name 'No' is not defined** </code></pre>
-4
2016-09-17T16:14:04Z
39,801,058
<p>I would suggest you using <code>.lower()</code> for every input. This ensures that if some types "nO" or "YeS" it takes the lowercase equivalent. Example:</p> <pre><code>ui = input("Type \"Hi\"").lower() </code></pre> <p>Next, you should really add an <code>else</code> option to your code. This is for answers you don't want them to type. This should be held in a <code>while loop</code> Example:</p> <pre><code>while(True): ui = input("Type \"Hi\"").title() if(ui == "Hi"): print("Hello") break else: print("That isn't a choice!") </code></pre>
0
2016-09-30T22:39:00Z
[ "python", "if-statement", "input" ]
While loop does not recognise if statement and variables?
39,549,015
<p>I'm doing a code for a school project and I tried to include a while loop but the if statement that is inside this loop is not recognised and the program does not recognise the variable Correct_Weight under each statement and instead it takes it as 0 which causes a division by zero error. </p> <p>the code is this:</p> <pre><code>Coin_Grams = 0 Correct_Weight = 0 Difference = 0 Total_Coins_Removed = [] Total_Coins_Added = [] Coins_To_Remove = 0 Coins_To_Add = 0 Number_Of_Bags_Checked = 0 Continue = "y" print ("Welcome to our program!") while Continue == "y": Type_Of_Coin = input("Please enter the type of coin in the bag") break if Type_Of_Coin == "1 pence": Coin_Grams = 3.56 Correct_Weight = Coin_Grams * 100 elif Type_Of_Coin == "2 pence": Coin_Grams = 7.12 Correct_Weight = Coin_Grams * 50 elif Type_Of_Coin == "5 pence": Coin_Grams = 3.25 Correct_Weight = Coin_Grams * 100 elif Type_Of_Coin == "10 pence": Coin_Grams = 6.50 Correct_Weight = Coin_Grams * 50 elif Type_Of_Coin == "20 pence": Coin_Grams = 5.00 Correct_Weight = Coin_Grams * 50 elif Type_Of_Coin == "50 pence": Coin_Grams = 8.00 Correct_Weight = Coin_Grams * 20 elif Type_Of_Coin == "1 pound": Coin_Grams = 9.50 Correct_Weight = Coin_Grams * 20 elif Type_Of_Coin == "2 pounds": Coin_Grams = 12.00 Correct_Weight = Coin_Grams * 10 else: print ("Type of coin is wrong please try again") Current_Weight = int(input("How much does the bag weight?")) Difference = Current_Weight - Correct_Weight print ("The difference is" ,Difference, "grams") if Difference &lt;= 0: Coins_To_Add = abs(Difference) / Coin_Grams Total_Coins_Add.append(Coins_To_Add) print ("You need to add" ,round(Coins_To_Add), "coins") elif Difference &gt;= 0: Coins_To_Remove = Difference / Coin_Grams Total_Coins_Removed.append(Coins_To_Remove) print ("You need to remove" ,round(Coins_To_Remove), "coins") else: print ("You don't need to remove or add any coins") Number_Of_Bags_Checked = Number_Of_Bags_Checked + 1 Continue = input("Do you have any more bags to check? please answer as y or n") print ("\n") if Continue == "n": print("\n") print (Number_Of_Bags_Checked,"bags have been checked") print ("\n") print (Total_Coins_Removed,"coins have been removed in total") print ("\n") print (Total_Coins_Added,"coins have been added in total") </code></pre> <p>and the error is this:</p> <p><a href="http://i.stack.imgur.com/mgciU.png" rel="nofollow"><img src="http://i.stack.imgur.com/mgciU.png" alt="enter image description here"></a></p>
-1
2016-09-17T16:17:46Z
39,549,057
<p>At the top, <code>Coin_Grams</code> is set to 0:</p> <pre><code>Coin_Grams = 0 </code></pre> <p>and you never set it to something else, because you <em>break out of the loop</em> immediately:</p> <pre><code>while Continue == "y": Type_Of_Coin = input("Please enter the type of coin in the bag") break </code></pre> <p>It doesn't matter what other code is in the loop past that point, because you told Python to ignore it.</p> <p>So you end up with <code>Coint_Grams</code> still set to <code>0</code> and that gives you a division by zero exception.</p> <p>Put the <code>break</code> at the <em>end</em> of the loop, and use <code>continue</code> in the <code>else:</code> block:</p> <pre><code>while True: Type_Of_Coin = input("Please enter the type of coin in the bag") if Type_Of_Coin == "1 pence": # etc. else: print ("Type of coin is wrong please try again") # when you get here the type of coin was incorrect, start again continue break # when you get here the type of coin was correct, so break out </code></pre> <p>I also replaced the <code>while</code> condition; your <code>==</code> test is always true, and you don't need to change the value of the <code>Continue</code> variable, so you may as well just test for <code>while True</code> here.</p>
0
2016-09-17T16:21:37Z
[ "python", "loops", "while-loop", "project", "division" ]
MIT 6.00 Newton's Method in Python 3
39,549,024
<p>This is part of the second problem set for MIT's OCW 6.00 Intro to Computation and Programming using Python. First, I created a function that evaluates a polynomial for a given x value. Then a function that computes the derivative for a given polynomial. Using those, I created a function that evaluates the first derivative for a given polynomial and x value. </p> <p>Then I tried to create a function to estimate the root of any given polynomial within a tolerance (epsilon). </p> <p>Test case is at bottom with expected output.</p> <p>I am new to programming and new to python, so I have included some comments in the code to explain what I think the code should be doing. </p> <pre><code>def evaluate_poly(poly, x): """ Computes the polynomial function for a given value x. Returns that value.""" answer = poly[0] for i in range (1, len(poly)): answer = answer + poly[i] * x**i return answer def compute_deriv(poly): """ #Computes and returns the derivative of a polynomial function. If the #derivative is 0, returns (0.0,).""" dpoly = () for i in range(1,len(poly)): dpoly = dpoly + (poly[i]*i,) return dpoly def df(poly, x): """Computes and returns the solution as a float to the derivative of a polynomial function """ dx = evaluate_poly(compute_deriv(poly), x) #dpoly = compute_deriv(poly) #dx = evaluate_poly(dpoly, x) return dx def compute_root(poly, x_0, epsilon): """ Uses Newton's method to find and return a root of a polynomial function. Returns a float containing the root""" iteration = 0 fguess = evaluate_poly(poly, x_0) #evaluates poly for first guess print(fguess) x_guess = x_0 #initialize x_guess if fguess &gt; 0 and fguess &lt; epsilon: #if solution for first guess is close enough to root return first guess return x_guess else: while fguess &gt; 0 and fguess &gt; epsilon: iteration+=1 x_guess = x_0 - (evaluate_poly(poly,x_0)/df(poly, x_0)) fguess = evaluate_poly(poly, x_guess) if fguess &gt; 0 and fguess &lt; epsilon: break #fguess where guess is close enough to root, breaks while loop, skips else, return x_guess else: x_0 = x_guess #guess again with most recent guess as x_0 next time through while loop print(iteration) return x_guess #Example: poly = (-13.39, 0.0, 17.5, 3.0, 1.0) #x^4 + 3x^3 + 17.5x^2 - 13.39 x_0 = 0.1 epsilon = .0001 print (compute_root(poly, x_0, epsilon)) #answer should be 0.80679075379635201 </code></pre> <p>The first 3 functions return correct answers, but compute_root (Newton's method) does not seem to enter the <code>while</code> loop because when I run the cell <code>print(iteration)</code> prints 0. I would think that since <code>if fguess &gt; 0 and fguess &lt; epsilon:</code> should return <code>false</code> for the test case (statement <code>print(fguess)</code> prints <code>-13.2119</code>), the interpreter would go to <code>else</code> and enter the <code>while</code> loop until it finds a solution that is within epsilon of 0. </p> <p>I have tried eliminating the first <code>if</code> <code>else</code> conditions so that I only have one <code>return</code> statement and I get the same problem. </p> <p>What could be causing the function to skip the <code>else</code> case / <code>while</code> loop altogether? I'm stumped!</p> <p>Thanks for looking and/or helping!</p>
0
2016-09-17T16:18:52Z
39,549,202
<p>It seems to be just a small oversight. Notice how <code>fguess</code> is printed with a value of -13.2119. In your <code>while</code> condition (in <code>else</code> from <code>compute_root</code>) you require <code>fguess &gt; 0 and fguess &lt; epsilon</code>, which is not met so nothing is done further and you exit without iterations.</p> <p>Instead:</p> <pre><code>while fguess &lt; 0 or fguess &gt; epsilon: </code></pre> <p>Will give you what you need:</p> <pre><code>-13.2119 7 0.806790753796352 </code></pre>
0
2016-09-17T16:37:50Z
[ "python", "python-3.x", "newtons-method" ]
Form validation failing in Django
39,549,053
<p>Im trying to get a form to validate with a Charfield but using the Select widget.</p> <p>Here is my <code>view.py</code> code:</p> <pre><code>def mpld3plot(request): form = PlotlyPlotForm() form.fields['plot_file'].widget.choices = own_funcs.uploaded_files(string=False) if request.method == 'POST': print(form.is_valid()) if form.is_valid(): return HttpResponseRedirect('/mpld3') else: pass else: pass return render(request, 'evert/plot.html', {'plottype': 'MPLD3', 'form': form}) </code></pre> <p>Below is my <code>forms.py</code> code:</p> <pre><code>class Mpld3PlotForm(forms.Form): plot_file = forms.CharField(widget=forms.Select(choices=[('', 'a'), ('', 'b')])) </code></pre> <p>The form does not validate on submit. I update the choices dynamically based on uploaded files. Any help would be appreciated. </p>
1
2016-09-17T16:21:11Z
39,556,281
<p>Turns out I did not pass the <code>request</code> object to the form.</p> <p>The <code>view.py</code> file should look like the following:</p> <pre><code>def mpld3plot(request): form = PlotlyPlotForm(request.POST) form.fields['plot_file'].widget.choices = own_funcs.uploaded_files(string=False) if request.method == 'POST': print(form.is_valid()) if form.is_valid(): return HttpResponseRedirect('/mpld3') else: pass else: pass return render(request, 'evert/plot.html', {'plottype': 'MPLD3', 'form': form}) </code></pre>
0
2016-09-18T09:47:08Z
[ "python", "django", "forms", "validation", "python-3.x" ]
Is it possible to detect the number of local variables declared in a function?
39,549,078
<p>In a Python test fixture, is it possible to count how many local variables a function declares in its body?</p> <pre><code>def foo(): a = 1 b = 2 Test.assertEqual(countLocals(foo), 2) </code></pre> <p>Alternatively, is there a way to see if a function declares any variables at all?</p> <pre><code>def foo(): a = 1 b = 2 def bar(): pass Test.assertEqual(hasLocals(foo), True) Test.assertEqual(hasLocals(bar), False) </code></pre> <p>The use case I'm thinking of has to do with validating user-submitted code.</p>
2
2016-09-17T16:23:26Z
39,549,096
<p>Yes, the associated code object accounts for all local names in the <code>co_nlocals</code> attribute:</p> <pre><code>foo.__code__.co_nlocals </code></pre> <p>Demo:</p> <pre><code>&gt;&gt;&gt; def foo(): ... a = 1 ... b = 2 ... &gt;&gt;&gt; foo.__code__.co_nlocals 2 </code></pre> <p>See the <a href="https://docs.python.org/3/reference/datamodel.html"><em>Datamodel</em> documentation</a>:</p> <blockquote> <p><em>User-defined functions</em></p> <p><em>[...]</em></p> <p><code>__code__</code> The code object representing the compiled function body. </p> <p><em>Code objects</em></p> <p><em>[...]</em></p> <p>Special read-only attributes: <em>[...]</em> <code>co_nlocals</code> is the number of local variables used by the function (including arguments); <em>[...]</em></p> </blockquote>
8
2016-09-17T16:25:35Z
[ "python", "metaprogramming" ]
Is it possible to detect the number of local variables declared in a function?
39,549,078
<p>In a Python test fixture, is it possible to count how many local variables a function declares in its body?</p> <pre><code>def foo(): a = 1 b = 2 Test.assertEqual(countLocals(foo), 2) </code></pre> <p>Alternatively, is there a way to see if a function declares any variables at all?</p> <pre><code>def foo(): a = 1 b = 2 def bar(): pass Test.assertEqual(hasLocals(foo), True) Test.assertEqual(hasLocals(bar), False) </code></pre> <p>The use case I'm thinking of has to do with validating user-submitted code.</p>
2
2016-09-17T16:23:26Z
39,560,200
<p>To elaborate somewhat on @Martijn excellent answer, if you read the documentation for the <a href="https://docs.python.org/3/library/inspect.html" rel="nofollow">inspect — Inspect live objects</a> module, you can see that it allows for introspection of a wealth of data, including (as @Martijn noted) in the <code>code</code> type, the following attributes:</p> <pre><code>co_names tuple of names of local variables co_nlocals number of local variables </code></pre>
1
2016-09-18T16:48:01Z
[ "python", "metaprogramming" ]
Filtering out string in a Panda Dataframe
39,549,097
<p>I have the following formulas that I use to compute data in my Dataframe. The Datframe consists of data downloaded. My Index is made of dates, and the first row contains only strings..</p> <pre><code>cols = df.columns.values.tolist() weight = pd.DataFrame([df[col] / df.sum(axis=1) for col in df], index=cols).T std = pd.DataFrame([df.std(axis=1) for col in df], index=cols).T A B C D E 2006-04-27 00:00:00 'dd' 'de' 'ede' 'wew' 'were' 2006-04-28 00:00:00 69.62 69.62 6.518 65.09 69.62 2006-05-01 00:00:00 71.5 71.5 6.522 65.16 71.5 2006-05-02 00:00:00 72.34 72.34 6.669 66.55 72.34 2006-05-03 00:00:00 70.22 70.22 6.662 66.46 70.22 2006-05-04 00:00:00 68.32 68.32 6.758 67.48 68.32 2006-05-05 00:00:00 68 68 6.805 67.99 68 2006-05-08 00:00:00 67.88 67.88 6.768 67.56 67.88 </code></pre> <p>The Issue I am having is that the formulas I use do not seem to ignore the Index and also the first Indexed row where it's only 'strings'. Thus i get the following error for the weight formula:</p> <blockquote> <p>TypeError: Cannot compare type 'Timestamp' with type 'str'</p> </blockquote> <p>and I get the following error for the std formula:</p> <blockquote> <p>ValueError: No axis named 1 for object type </p> </blockquote>
0
2016-09-17T16:25:40Z
39,549,471
<p>You could filter the rows so as to compute weight and standard deviation as follows:</p> <pre><code>df_string = df.iloc[0] # Assign First row to DF df_numeric = df.iloc[1:].astype(float) # Assign All rows after first row to DF cols = df_numeric.columns.values.tolist() </code></pre> <p>Computing:</p> <pre><code>weight = pd.DataFrame([df_numeric[col] / df_numeric.sum(axis=1) for col in df_numeric], index=cols).T weight </code></pre> <p><a href="http://i.stack.imgur.com/Tx9UY.png" rel="nofollow"><img src="http://i.stack.imgur.com/Tx9UY.png" alt="Image"></a></p> <pre><code>std = pd.DataFrame([df_numeric.std(axis=1) for col in df_numeric],index=cols).T std </code></pre> <p><a href="http://i.stack.imgur.com/7l74w.png" rel="nofollow"><img src="http://i.stack.imgur.com/7l74w.png" alt="Image"></a></p> <p>To reassign, say <code>std</code> values back to the original <code>DF</code>, you could do:</p> <pre><code>df_string_std = df_string.to_frame().T.append(std) df_string_std </code></pre> <p><a href="http://i.stack.imgur.com/xJy7l.png" rel="nofollow"><img src="http://i.stack.imgur.com/xJy7l.png" alt="Image"></a></p> <hr> <p>As the OP had difficulty in reproducing the results, here is the complete summary of the <code>DF</code> used:</p> <pre><code>df.info() &lt;class 'pandas.core.frame.DataFrame'&gt; DatetimeIndex: 8 entries, 2006-04-27 to 2006-05-08 Data columns (total 5 columns): A 8 non-null object B 8 non-null object C 8 non-null object D 8 non-null object E 8 non-null object dtypes: object(5) memory usage: 384.0+ bytes df.index DatetimeIndex(['2006-04-27', '2006-04-28', '2006-05-01', '2006-05-02', '2006-05-03', '2006-05-04', '2006-05-05', '2006-05-08'], dtype='datetime64[ns]', name='Date', freq=None) </code></pre> <p>Starting <code>DF</code>used:</p> <pre><code>df </code></pre> <p><a href="http://i.stack.imgur.com/nKV8A.png" rel="nofollow"><img src="http://i.stack.imgur.com/nKV8A.png" alt="Image"></a></p>
3
2016-09-17T17:00:46Z
[ "python", "pandas", "dataframe", "rows" ]
How to print words that only cointain letters from a list?
39,549,175
<p>Hello I have recently been trying to create a progam in Python 3 which will read a text file wich contains 23005 words, the user will then enter a <strong>string of 9 characters</strong> which the program will use to create words and compare them to the ones in the text file.</p> <p><strong>I want to print words which contains between 4-9 letters and that also contains the letter in the middle of my list</strong>. For example if the user enters the string "anitsksem" then the fifth letter "s" must be present in the word.</p> <p>Here is how far I have gotten on my own:</p> <pre><code># Open selected file &amp; read filen = open("svenskaOrdUTF-8.txt", "r") # Read all rows and store them in a list wordList = filen.readlines() # Close File filen.close() # letterList index i = 0 # List of letters that user will input letterList = [] # List of words that are our correct answers solvedList = [] # User inputs 9 letters that will be stored in our letterList string = input(str("Ange Nio Bokstäver: ")) userInput = False # Checks if user input is correct while userInput == False: # if the string is equal to 9 letters # insert letter into our letterList. # also set userInput to True if len(string) == 9: userInput = True for char in string: letterList.insert(i, char) i += 1 # If string not equal to 9 ask user for a new input elif len(string) != 9: print("Du har inte angivit nio bokstäver") string = input(str("Ange Nio Bokstäver: ")) # For each word in wordList # and for each char within that word # check if said word contains a letter from our letterList # if it does and meets the requirements to be a correct answer # add said word to our solvedList for word in wordList: for char in word: if char in letterList: if len(word) &gt;= 4 and len(word) &lt;= 9 and letterList[4] in word: print("Char:", word) solvedList.append(word) </code></pre> <p>The issue that I run into is that instead of printing words which <strong>only</strong> contain letters from my <code>letterList</code>, it prints out words which contains <strong>at least one</strong> letter from my <code>letterList</code>. This also mean that some words are printed out multiple time, for example if the words contains multiple letters from <code>letterList</code>.</p> <p>I've been trying to solve these problems for a while but I just can't seem to figure it out. I Have also tried using permutations to create all possible combinations of the letters in my list and then comparing them to my <code>wordlist</code>, however I felt that solution was to slow given the number of combinations which must be created.</p> <pre><code> # For each word in wordList # and for each char within that word # check if said word contains a letter from our letterList # if it does and meets the requirements to be a correct answer # add said word to our solvedList for word in wordList: for char in word: if char in letterList: if len(word) &gt;= 4 and len(word) &lt;= 9 and letterList[4] in word: print("Char:", word) solvedList.append(word) </code></pre> <p>Also since I'm kinda to new to python, if you have any general tips to share, I would really appreciate it.</p>
0
2016-09-17T16:34:59Z
39,549,319
<p>You get multiple words mainly because you iterate through each character in a given word and if that character is in the <code>letterList</code> you append and print it.</p> <p>Instead, iterate on a word basis and not on a character basis while also using the <code>with</code> context managers to automatically close files:</p> <pre><code>with open('american-english') as f: for w in f: w = w.strip() cond = all(i in letterList for i in w) and letterList[4] in w if 9 &gt; len(w) &gt;= 4 and cond: print(w) </code></pre> <p>Here <code>cond</code> is used to trim down the <code>if</code> statement, <code>all(..)</code> is used to check if every character in the word is in <code>letterList</code>, <code>w.strip()</code> is to remove any redundant white-space.</p> <p>Additionally, to populate your <code>letterList</code> when the input is <code>9</code> letters, <em>don't use <code>insert</code></em>. Instead, just supply the string to <code>list</code> and the list will be created in a similar, but noticeably faster, fashion:</p> <p>This:</p> <pre><code>if len(string) == 9: userInput = True for char in string: letterList.insert(i, char) i += 1 </code></pre> <p>Can be written as:</p> <pre><code>if len(string) == 9: userInput = True letterList = list(string) </code></pre> <p>With these changes, the initial <code>open</code> and <code>readlines</code> are not needed, neither is the initialization of <code>letterList</code>.</p>
1
2016-09-17T16:47:28Z
[ "python", "python-3.x", "for-loop", "comparison", "iteration" ]
How to print words that only cointain letters from a list?
39,549,175
<p>Hello I have recently been trying to create a progam in Python 3 which will read a text file wich contains 23005 words, the user will then enter a <strong>string of 9 characters</strong> which the program will use to create words and compare them to the ones in the text file.</p> <p><strong>I want to print words which contains between 4-9 letters and that also contains the letter in the middle of my list</strong>. For example if the user enters the string "anitsksem" then the fifth letter "s" must be present in the word.</p> <p>Here is how far I have gotten on my own:</p> <pre><code># Open selected file &amp; read filen = open("svenskaOrdUTF-8.txt", "r") # Read all rows and store them in a list wordList = filen.readlines() # Close File filen.close() # letterList index i = 0 # List of letters that user will input letterList = [] # List of words that are our correct answers solvedList = [] # User inputs 9 letters that will be stored in our letterList string = input(str("Ange Nio Bokstäver: ")) userInput = False # Checks if user input is correct while userInput == False: # if the string is equal to 9 letters # insert letter into our letterList. # also set userInput to True if len(string) == 9: userInput = True for char in string: letterList.insert(i, char) i += 1 # If string not equal to 9 ask user for a new input elif len(string) != 9: print("Du har inte angivit nio bokstäver") string = input(str("Ange Nio Bokstäver: ")) # For each word in wordList # and for each char within that word # check if said word contains a letter from our letterList # if it does and meets the requirements to be a correct answer # add said word to our solvedList for word in wordList: for char in word: if char in letterList: if len(word) &gt;= 4 and len(word) &lt;= 9 and letterList[4] in word: print("Char:", word) solvedList.append(word) </code></pre> <p>The issue that I run into is that instead of printing words which <strong>only</strong> contain letters from my <code>letterList</code>, it prints out words which contains <strong>at least one</strong> letter from my <code>letterList</code>. This also mean that some words are printed out multiple time, for example if the words contains multiple letters from <code>letterList</code>.</p> <p>I've been trying to solve these problems for a while but I just can't seem to figure it out. I Have also tried using permutations to create all possible combinations of the letters in my list and then comparing them to my <code>wordlist</code>, however I felt that solution was to slow given the number of combinations which must be created.</p> <pre><code> # For each word in wordList # and for each char within that word # check if said word contains a letter from our letterList # if it does and meets the requirements to be a correct answer # add said word to our solvedList for word in wordList: for char in word: if char in letterList: if len(word) &gt;= 4 and len(word) &lt;= 9 and letterList[4] in word: print("Char:", word) solvedList.append(word) </code></pre> <p>Also since I'm kinda to new to python, if you have any general tips to share, I would really appreciate it.</p>
0
2016-09-17T16:34:59Z
39,549,352
<p>You can try this logic:</p> <pre><code>for word in wordList: # if not a valid work skip - moving this check out side the inner for-each will improve performance if len(word) &lt; 4 or len(word) &gt; 9 or letterList[4] not in word: continue # find the number of matching words match_count = 0 for char in word: if char in letterList: match_count += 1 # check if total number of match is equal to the word count if match_count == len(word): print("Char:", word) solvedList.append(word) </code></pre>
0
2016-09-17T16:50:27Z
[ "python", "python-3.x", "for-loop", "comparison", "iteration" ]
How to print words that only cointain letters from a list?
39,549,175
<p>Hello I have recently been trying to create a progam in Python 3 which will read a text file wich contains 23005 words, the user will then enter a <strong>string of 9 characters</strong> which the program will use to create words and compare them to the ones in the text file.</p> <p><strong>I want to print words which contains between 4-9 letters and that also contains the letter in the middle of my list</strong>. For example if the user enters the string "anitsksem" then the fifth letter "s" must be present in the word.</p> <p>Here is how far I have gotten on my own:</p> <pre><code># Open selected file &amp; read filen = open("svenskaOrdUTF-8.txt", "r") # Read all rows and store them in a list wordList = filen.readlines() # Close File filen.close() # letterList index i = 0 # List of letters that user will input letterList = [] # List of words that are our correct answers solvedList = [] # User inputs 9 letters that will be stored in our letterList string = input(str("Ange Nio Bokstäver: ")) userInput = False # Checks if user input is correct while userInput == False: # if the string is equal to 9 letters # insert letter into our letterList. # also set userInput to True if len(string) == 9: userInput = True for char in string: letterList.insert(i, char) i += 1 # If string not equal to 9 ask user for a new input elif len(string) != 9: print("Du har inte angivit nio bokstäver") string = input(str("Ange Nio Bokstäver: ")) # For each word in wordList # and for each char within that word # check if said word contains a letter from our letterList # if it does and meets the requirements to be a correct answer # add said word to our solvedList for word in wordList: for char in word: if char in letterList: if len(word) &gt;= 4 and len(word) &lt;= 9 and letterList[4] in word: print("Char:", word) solvedList.append(word) </code></pre> <p>The issue that I run into is that instead of printing words which <strong>only</strong> contain letters from my <code>letterList</code>, it prints out words which contains <strong>at least one</strong> letter from my <code>letterList</code>. This also mean that some words are printed out multiple time, for example if the words contains multiple letters from <code>letterList</code>.</p> <p>I've been trying to solve these problems for a while but I just can't seem to figure it out. I Have also tried using permutations to create all possible combinations of the letters in my list and then comparing them to my <code>wordlist</code>, however I felt that solution was to slow given the number of combinations which must be created.</p> <pre><code> # For each word in wordList # and for each char within that word # check if said word contains a letter from our letterList # if it does and meets the requirements to be a correct answer # add said word to our solvedList for word in wordList: for char in word: if char in letterList: if len(word) &gt;= 4 and len(word) &lt;= 9 and letterList[4] in word: print("Char:", word) solvedList.append(word) </code></pre> <p>Also since I'm kinda to new to python, if you have any general tips to share, I would really appreciate it.</p>
0
2016-09-17T16:34:59Z
39,549,442
<p>You can use lambda functions to get this done. I am just putting up a POC here leave it to you to convert it into complete solution.</p> <pre><code>filen = open("test.text", "r") word_list = filen.read().split() print("Enter your string") search_letter = raw_input()[4] solved_list = [ word for word in word_list if len(word) &gt;= 4 and len(word) &lt;= 9 and search_letter in word] print solved_list </code></pre>
0
2016-09-17T16:58:21Z
[ "python", "python-3.x", "for-loop", "comparison", "iteration" ]
How to load a pre-trained Word2vec MODEL File and reuse it?
39,549,248
<p>I want to use a pre-trained <code>word2vec</code> model, but I don't know how to load it in python.</p> <p>This file is a MODEL file (703 MB). It can be downloaded here:<br> <a href="http://devmount.github.io/GermanWordEmbeddings/" rel="nofollow">http://devmount.github.io/GermanWordEmbeddings/</a></p>
0
2016-09-17T16:40:54Z
39,662,736
<p>just for loading</p> <pre><code>import gensim # Load pre-trained Word2Vec model. model = gensim.models.Word2Vec.load("modelName.model") </code></pre> <p>now you can train the model as usual. also, if you want to be able to save it and retrain it multiple times, here's what you should do</p> <pre><code>model.train(//insert proper parameters here//) """ If you don't plan to train the model any further, calling init_sims will make the model much more memory-efficient If `replace` is set, forget the original vectors and only keep the normalized ones = saves lots of memory! replace=True if you want to reuse the model """ model.init_sims(replace=True) # save the model for later use # for loading, call Word2Vec.load() model.save("modelName.model") </code></pre>
0
2016-09-23T14:02:09Z
[ "python", "file", "model", "word2vec" ]
Reshape numpy (n,) vector to (n,1) vector
39,549,331
<p>So it is easier for me to think about vectors as column vectors when I need to do some linear algebra. Thus I prefer shapes like (n,1). </p> <p>Is there significant memory usage difference between shapes (n,) and (n,1)? </p> <p>What is preferred way? </p> <p>And how to reshape (n,) vector into (n,1) vector. Somehow b.reshape((n,1)) doesn't do the trick. </p> <pre><code>a = np.random.random((10,1)) b = np.ones((10,)) b.reshape((10,1)) print(a) print(b) [[ 0.76336295] [ 0.71643237] [ 0.37312894] [ 0.33668241] [ 0.55551975] [ 0.20055153] [ 0.01636735] [ 0.5724694 ] [ 0.96887004] [ 0.58609882]] [ 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.] </code></pre>
1
2016-09-17T16:48:45Z
39,549,486
<p><a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html#numpy.reshape" rel="nofollow"><code>ndarray.reshape()</code></a> returns a new view, or a copy (depends on the new shape). It does not modify the array in place.</p> <pre><code>b.reshape((10, 1)) </code></pre> <p>as such is effectively no-operation, since the created view/copy is not assigned to anything. The "fix" is simple:</p> <pre><code>b_new = b.reshape((10, 1)) </code></pre> <p>The amount of memory used should not differ at all between the 2 shapes. Numpy arrays use the concept of <a href="http://www.scipy-lectures.org/advanced/advanced_numpy/#indexing-scheme-strides" rel="nofollow">strides</a> and so the dimensions <code>(10,)</code> and <code>(10, 1)</code> can both use the same buffer; the amounts to jump to next row and column just change.</p>
2
2016-09-17T17:02:43Z
[ "python", "numpy" ]
Group a list of dates by month, year
39,549,338
<pre><code>raw_data = ["2015-12-31", "2015-12-1" , "2015-1-1", "2014-12-31", "2014-12-1" , "2014-1-1", "2013-12-31", "2013-12-1" , "2013-1-1",] expected_grouped_bymonth = [("2015-12", #dates_in_the_list_occured_in_december_2015) , ... ("2013-1", #january2013dates)] </code></pre> <p>OR as a dict</p> <pre><code>expected_grouped_bymonth = { "2015-12": #dates_in_the_list_occured_in_december_2015) , ... "2013-1", #january2013dates)} </code></pre> <p>I have a list of strings that represent dates. What I would like to have is a list of tuples, or a dictionary, that count per year or month the number of occurrences. What I've tried to do is something related to the <code>groupby</code>. I'm not able to understand how to use the the <code>TimeGrouper</code> according to the <code>groupby</code> function.</p> <p>The raised exception is:</p> <pre class="lang-none prettyprint-override"><code>TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'RangeIndex' from itertools import groupby for el in data: if 'Real rates - Real volatilities' in el['scenario']: counter += 1 real_records_dates.append(pd.to_datetime(el['refDate'])) print("Thera are {} real records.".format(counter)) BY_YEAR = 'Y' BY_MONTH = 'M' BY_DAY = 'D' real_records_df = pd.DataFrame(pd.Series(real_records_dates)) real_records_df.groupby(pd.TimeGrouper(freq=BY_MONTH)) </code></pre> <p>(You can also assume to start with a dictionary og <code>{date1:1, date2:2, ...}</code> if it easier. My problem is related only to the <code>groupby</code>.)</p>
0
2016-09-17T16:49:01Z
39,553,026
<p>If you want to get the frequency of how often a date occurs per month and year you can use a <em>defaulftdict</em>:</p> <pre><code>raw_data = ["2015-12-31", "2015-12-1", "2015-1-1", "2014-12-31", "2014-12-1", "2014-1-1", "2013-12-31", "2013-12-1", "2013-1-1", ] from collections import defaultdict dates = defaultdict(lambda:defaultdict(int)) for s in raw_data: k, v = s.rsplit("-", 1) dates[k][v] += 1 print(dates) </code></pre> <p>Or if you just want to <em>Group a list of dates by month, year</em>:</p> <pre><code>dates = defaultdict(list) for s in raw_data: k, v = s.rsplit("-", 1) dates[k].append(v) print(dates) </code></pre>
2
2016-09-18T00:37:39Z
[ "python", "list", "datetime", "pandas", "group-by" ]
Django 1.9 error - 'User' object has no attribute 'profile'
39,549,351
<p>So I recently added an optional user profile model that is linked to a user via a OneToOneField like so:</p> <pre><code>class UserProfile(models.Model): # Creating class user = models.OneToOneField(User, on_delete=models.CASCADE) </code></pre> <p>This worked fine, and my current UserProfile models were intact both before and after I added in this field to link the profile to a user.</p> <p>The problem comes when I log in on the website as a valid user, after submitting the log in form comes an error:</p> <blockquote> <p>AttributeError at /login/</p> <p>'User' object has no attribute 'profile'</p> </blockquote> <p>I have searched through my files for anything along the lines of '<code>User.profile</code>', and similar queries, however I can't seem to find anything that would allow me to properly log in as a user.</p> <p>I wasn't sure what other code to post here, and didn't want to spam this question with potentially unnecessary code so tell me if there's anything more specific (views.py, models.py, forms.py, etc) that will be needed to solve this sort of problem, or if you know of any possible solutions.</p> <p>Thank you</p>
0
2016-09-17T16:50:27Z
39,549,956
<p>You haven't set any related_name attribute on that one-to-one field, so the reverse accessor will be called <code>userprofile</code> not <code>profile</code>.</p>
1
2016-09-17T17:49:28Z
[ "python", "django", "django-models", "django-views" ]
Read multiple lines from a file batch by batch
39,549,426
<p>I would like to know is there a method that can read multiple lines from a file batch by batch. For example:</p> <pre><code>with open(filename, 'rb') as f: for n_lines in f: process(n_lines) </code></pre> <p>In this function, what I would like to do is: for every iteration, next n lines will be read from the file, batch by batch. </p> <p>Because one single file is too big. What I want to do is to read it part by part.</p>
0
2016-09-17T16:57:12Z
39,549,830
<p>You can actually just iterate over lines in a file (see <a href="https://docs.python.org/2/library/stdtypes.html#file.next" rel="nofollow">file.next</a> docs - this also works on Python 3) like</p> <pre><code>with open(filename) as f: for line in f: something(line) </code></pre> <p>so your code can be rewritten to</p> <pre><code>n=5 # your chunk size with open(filename) as f: batch=[] for line in f: chunk.append(line) if len(batch)==n: process(batch) chunk=[] process(batch) #this batch might be smaller or even empty </code></pre> <p>but normally just processing line-by-line is more convenient (first example)</p> <p>If you dont care about how many lines are read exactly for each batch but just that it is not too much memory then use <a href="https://docs.python.org/2/library/stdtypes.html#file.readlines" rel="nofollow">file.readlines</a> with <code>sizehint</code> like</p> <pre><code>size_hint=2&lt;&lt;24 # 16MB with open(filename) as f: while f: # not sure if this check works process(f.readlines(size_hint) </code></pre>
0
2016-09-17T17:36:10Z
[ "python", "python-2.7", "io", "readfile" ]
Read multiple lines from a file batch by batch
39,549,426
<p>I would like to know is there a method that can read multiple lines from a file batch by batch. For example:</p> <pre><code>with open(filename, 'rb') as f: for n_lines in f: process(n_lines) </code></pre> <p>In this function, what I would like to do is: for every iteration, next n lines will be read from the file, batch by batch. </p> <p>Because one single file is too big. What I want to do is to read it part by part.</p>
0
2016-09-17T16:57:12Z
39,549,901
<p><a href="https://docs.python.org/3/library/itertools.html#itertools.islice" rel="nofollow"><code>itertools.islice</code></a> and two arg <code>iter</code> can be used to accomplish this, but it's a little funny:</p> <pre><code>from itertools import islice n = 5 # Or whatever chunk size you want with open(filename, 'rb') as f: for n_lines in iter(lambda: tuple(islice(f, n)), ()): process(n_lines) </code></pre> <p>This will keep <code>islice</code>ing off <code>n</code> lines at a time (using <code>tuple</code> to actually force the whole chunk to be read in) until the <code>f</code> is exhausted, at which point it will stop. The final chunk will be less than <code>n</code> lines if the number of lines in the file isn't an even multiple of <code>n</code>. If you want all the lines to be a single string, change the <code>for</code> loop to be:</p> <pre><code> # The b prefixes are ignored on 2.7, and necessary on 3.x since you opened # the file in binary mode for n_lines in iter(lambda: b''.join(islice(f, n)), b''): </code></pre> <p>Another approach is to use <code>izip_longest</code> for the purpose, which avoids <code>lambda</code> functions:</p> <pre><code>from future_builtins import map # Only on Py2 from itertools import izip_longest # zip_longest on Py3 # gets tuples possibly padded with empty strings at end of file for n_lines in izip_longest(*[f]*n, fillvalue=b''): # Or to combine into a single string: for n_lines in map(b''.join, izip_longest(*[f]*n, fillvalue=b'')): </code></pre>
2
2016-09-17T17:43:00Z
[ "python", "python-2.7", "io", "readfile" ]
Why does loop never exit?
39,549,429
<p>I have been working on a Bisectional Number guessing game and I would like to make it work automatically, but the code appears to be getting stuck in a loop. </p> <p>Any suggestions?</p> <pre><code>x = 75 low = 0 high = 100 guessing = True while guessing: guess = int((high + low) // 2) if guess == x: guessing = False elif guess &lt; x: high = guess else: low = guess print("Your number is ", str(guess)) </code></pre>
0
2016-09-17T16:57:24Z
39,549,554
<p>I think it will work:</p> <pre><code>x = 75 low = 0 high = 100 guessing = True while guessing: guess = (high + low) // 2 print("guess:",guess) if guess == x: guessing = False elif guess &lt; x: low = guess else: high = guess print("Your number is ", guess) </code></pre> <p>output: </p> <pre><code>guess: 50 guess: 75 Your number is 75 </code></pre> <p>You don't need to explicitly convert it to int because you are using integer division here <code>guess = int((high + low) // 2)</code> And reverse the <code>elif ..else</code> logic..</p> <p>Hope this will help you.</p>
0
2016-09-17T17:08:58Z
[ "python", "python-3.x" ]
Why does loop never exit?
39,549,429
<p>I have been working on a Bisectional Number guessing game and I would like to make it work automatically, but the code appears to be getting stuck in a loop. </p> <p>Any suggestions?</p> <pre><code>x = 75 low = 0 high = 100 guessing = True while guessing: guess = int((high + low) // 2) if guess == x: guessing = False elif guess &lt; x: high = guess else: low = guess print("Your number is ", str(guess)) </code></pre>
0
2016-09-17T16:57:24Z
39,549,651
<p>For such things it's better to limit the number of possible iterations. </p> <pre><code>max_iter = 25 x = 42 low , high = 0 , 100 for _ in range(max_iter): guess = (high + low) // 2 if guess == x: break low , high = (guess , high) if x &gt; guess else (low , guess) print("Your number is {}".format(guess)) </code></pre>
0
2016-09-17T17:16:59Z
[ "python", "python-3.x" ]
Finding multiple lines with a regex?
39,549,437
<p>I am trying to complete a "Regex search" project from the book <a href="https://automatetheboringstuff.com/chapter8/" rel="nofollow">Automate boring stuff with python</a>. I tried searching for answer, but I failed to find related thread in python.</p> <p>The task is: "Write a program that opens all .txt files in a folder and searches for any line that matches a user-supplied regular expression. The results should be printed to the screen."</p> <p>With the below compile I manage to find the first match</p> <pre><code>regex = re.compile(r".*(%s).*" % search_str) </code></pre> <p>And I can print it out with </p> <pre><code>print(regex.search(content).group()) </code></pre> <p>But if I try to use </p> <pre><code>print(regex.findall(content)) </code></pre> <p>The output is only the inputted word/words, not the whole line they are on. Why won't <code>findall</code> match the whole line, even though that is how I compiled the regex?</p> <p>My code is as follows.</p> <pre><code># Regex search - Find user given text from a .txt file # and prints the line it is on import re # user input print("\nThis program searches for lines with your string in them\n") search_str = input("Please write the string you are searching for: \n") print("") # file input file = open("/users/viliheikkila/documents/kooditreeni/input_file.txt") content = file.read() file.close() # create regex regex = re.compile(r".*(%s).*" % search_str) # print out the lines with match if regex.search(content) is None: print("No matches was found.") else: print(regex.findall(content)) </code></pre>
1
2016-09-17T16:58:04Z
39,550,854
<p>In python regex, parentheses define a <em>capturing group</em>. (See <a href="https://regex101.com/r/iV8nS1/1" rel="nofollow">here</a> for breakdown and explanation).</p> <p><code>findall</code> will only return the captured group. If you want the entire line, you will have to iterate over the result of <code>finditer</code>.</p>
0
2016-09-17T19:24:51Z
[ "python", "regex", "python-3.x" ]