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
Using python thread as a plain object
39,053,520
<p>If i define a python thread extending threading.Thread class and overriding run I can then invoke run() instead of start() and use it in the caller thread instead of a separate one.</p> <p>i.e.</p> <pre><code>class MyThread(threading.thread): def run(self): while condition(): do_something() </code></pre> <p>this code (1) will execute "run" method this in a separate thread</p> <pre><code>t = MyThread() t.start() </code></pre> <p>this code (2) will execute "run" method in the current thread</p> <pre><code>t = MyThread() t.run() </code></pre> <p>Are there any practical disadvantages in using this approach in writing code that can be executed in either way? Could invoking directly the "run" of a Thread object cause memory problems, performance issues or some other unpredictable behavior?</p> <p>In other words, what are the differences (if any notable, i guess some more memory <em>will</em> be allocated but It should be negligible) between invoking the code (2) on MyThread class and another identical class that extends "object" instead of "threading.Tread"</p> <p>I guess that some (if any) of the more low level differences might depend on the interpreter. In case this is relevant i'm mainly interested in CPython 3.*</p>
0
2016-08-20T11:18:19Z
39,053,622
<p>There will be no difference in the behavior of <code>run</code> when you're using the <code>threading.Thread</code> object, or an object of a <code>threading.Thread</code>'s subclass, or an object of any other class that has the <code>run</code> method:</p> <blockquote> <p><code>threading.Thread.start</code> starts a new thread and then runs <code>run</code> in this thread.</p> <p><code>run</code> starts the activity in the <em>calling thread</em>, be it the main thread or another one.</p> </blockquote> <p>If you run <code>run</code> in the main thread, the whole thread will be busy executing the task <code>run</code> is supposed to execute, and you won't be able to do anything until the task finishes.</p> <p>That said, no, there will be no notable differences as the <code>run</code> method behaves just like any other method and is executed in the <em>calling thread</em>.</p>
1
2016-08-20T11:31:10Z
[ "python", "multithreading" ]
Using python thread as a plain object
39,053,520
<p>If i define a python thread extending threading.Thread class and overriding run I can then invoke run() instead of start() and use it in the caller thread instead of a separate one.</p> <p>i.e.</p> <pre><code>class MyThread(threading.thread): def run(self): while condition(): do_something() </code></pre> <p>this code (1) will execute "run" method this in a separate thread</p> <pre><code>t = MyThread() t.start() </code></pre> <p>this code (2) will execute "run" method in the current thread</p> <pre><code>t = MyThread() t.run() </code></pre> <p>Are there any practical disadvantages in using this approach in writing code that can be executed in either way? Could invoking directly the "run" of a Thread object cause memory problems, performance issues or some other unpredictable behavior?</p> <p>In other words, what are the differences (if any notable, i guess some more memory <em>will</em> be allocated but It should be negligible) between invoking the code (2) on MyThread class and another identical class that extends "object" instead of "threading.Tread"</p> <p>I guess that some (if any) of the more low level differences might depend on the interpreter. In case this is relevant i'm mainly interested in CPython 3.*</p>
0
2016-08-20T11:18:19Z
39,112,405
<p>I looked into the <a href="https://hg.python.org/cpython/file/3.5/Lib/threading.py" rel="nofollow">code implementing threading.Thread</a> class in cpython 3. The init method simply assigns some variables and do not do anything that seems related to actually create a new thread. Therefore we can assume that it should be safe use a threading.Thread object in the proposed manner.</p>
0
2016-08-23T23:55:23Z
[ "python", "multithreading" ]
cannot import pandas after conda update, Missing required dependencies ['numpy']
39,053,553
<p>I have been using pandas for a long while now, and wanted to use this functionality. Realizing I was in a prior version I typed <code>conda update pandas</code> into my command line.</p> <p>Now, when I go into python and try to import pandas I see the following:</p> <pre><code>C:\Users\%USER%&gt;python Python 2.7.10 |Continuum Analytics, Inc.| (default, May 28 2015, 17:02:00) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. Anaconda is brought to you by Continuum Analytics. Please check out: http://continuum.io/thanks and https://binstar.org &gt;&gt;&gt; import pandas as pd Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "C:\Users\%USER%\Miniconda\lib\site-packages\pandas\__init__.py", l ine 18, in &lt;module&gt; raise ImportError("Missing required dependencies {0}".format(missing_depende ncies)) ImportError: Missing required dependencies ['numpy'] &gt;&gt;&gt; </code></pre> <p>If I just try to import numpy i see:</p> <pre><code> &gt;&gt;&gt; import numpy Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "C:\Users\%USER%\Miniconda\lib\site-packages\numpy\__init__.py", li ne 180, in &lt;module&gt; from . import add_newdocs File "C:\Users\%USER%\Miniconda\lib\site-packages\numpy\add_newdocs.py", line 13, in &lt;module&gt; from numpy.lib import add_newdoc File "C:\Users\%USER%\Miniconda\lib\site-packages\numpy\lib\__init__.py" , line 8, in &lt;module&gt; from .type_check import * File "C:\Users\%USER%\Miniconda\lib\site-packages\numpy\lib\type_check.p y", line 11, in &lt;module&gt; import numpy.core.numeric as _nx File "C:\Users\%USER%\Miniconda\lib\site-packages\numpy\core\__init__.py ", line 14, in &lt;module&gt; from . import multiarray ImportError: DLL load failed: The specified module could not be found. </code></pre> <p>This was working perfectly until this conda update. Has anyone experienced this?</p>
1
2016-08-20T11:21:58Z
39,054,124
<p>Thankfully conda understands revisions.</p> <pre><code>C:\&gt;conda list --revisions </code></pre> <p>Will give you your list of revisions. Find the one prior to the most recent that broke stuff.</p> <p>For me it was revision 6, so I typed:</p> <pre><code>C:\&gt;conda install --revision 6 </code></pre> <p>I am up and running again!</p>
0
2016-08-20T12:25:31Z
[ "python", "pandas", "numpy", "conda" ]
open selected rows with pandas using "chunksize" and/or "iterator"
39,053,628
<p>I have a large csv file and I open it with pd.read_csv as it follows:</p> <pre><code>df = pd.read_csv(path//fileName.csv, sep = ' ', header = None) </code></pre> <p>As the file is really large I would like to be able to open it in rows</p> <pre><code>from 0 to 511 from 512 to 1023 from 1024 to 1535 ... from 512*n to 512*(n+1) - 1 </code></pre> <p>Where n = 1, 2, 3 ...</p> <p>If I add chunksize = 512 into the arguments of read_csv</p> <pre><code>df = pd.read_csv(path//fileName.csv, sep = ' ', header = None, chunksize = 512) </code></pre> <p>and I type</p> <pre><code>df.get_chunk(5) </code></pre> <p>Than I am able to open rows from 0 to 5 or I may be able to divide the file in parts of 512 rows using a for loop</p> <pre><code>data = [] for chunks in df: data = data + [chunk] </code></pre> <p>But this is quite useless as still the file has to be completelly opened and takes time. How can I read only rows from 512*n to 512*(n+1).</p> <p>Looking around I often saw that "chunksize" is used together with "iterator" as it follows</p> <pre><code> df = pd.read_csv(path//fileName.csv, sep = ' ', header = None, iterator = True, chunksize = 512) </code></pre> <p>But after many attempts I still don't understand which benefits provide me this boolean variable. Could you explain me it, please?</p>
2
2016-08-20T11:31:44Z
39,053,748
<blockquote> <p>How can I read only rows from 512*n to 512*(n+1)?</p> </blockquote> <pre><code>df = pd.read_csv(fn, header=None, skiprows=512*n, nrows=512) </code></pre> <p>You can do it this way (and it's pretty useful):</p> <pre><code>for chunk in pd.read_csv(f, sep = ' ', header = None, chunksize = 512): # process your chunk here </code></pre> <p>Demo:</p> <pre><code>In [61]: fn = 'd:/temp/a.csv' In [62]: pd.DataFrame(np.random.randn(30, 3), columns=list('abc')).to_csv(fn, index=False) In [63]: for chunk in pd.read_csv(fn, chunksize=10): ....: print(chunk) ....: a b c 0 2.229657 -1.040086 1.295774 1 0.358098 -1.080557 -0.396338 2 0.731741 -0.690453 0.126648 3 -0.009388 -1.549381 0.913128 4 -0.256654 -0.073549 -0.171606 5 0.849934 0.305337 2.360101 6 -1.472184 0.641512 -1.301492 7 -2.302152 0.417787 0.485958 8 0.492314 0.603309 0.890524 9 -0.730400 0.835873 1.313114 a b c 0 1.393865 -1.115267 1.194747 1 3.038719 -0.343875 -1.410834 2 -1.510598 0.664154 -0.996762 3 -0.528211 1.269363 0.506728 4 0.043785 -0.786499 -1.073502 5 1.096647 -1.127002 0.918172 6 -0.792251 -0.652996 -1.000921 7 1.582166 -0.819374 0.247077 8 -1.022418 -0.577469 0.097406 9 -0.274233 -0.244890 -0.352108 a b c 0 -0.317418 0.774854 -0.203939 1 0.205443 0.820302 -2.637387 2 0.332696 -0.655431 -0.089120 3 -0.884916 0.274854 1.074991 4 0.412295 -1.561943 -0.850376 5 -1.933529 -1.346236 -1.789500 6 1.652446 -0.800644 -0.126594 7 0.520916 -0.825257 -0.475727 8 -2.261692 2.827894 -0.439698 9 -0.424714 1.862145 1.103926 </code></pre> <blockquote> <p>In which case "iterator" can be useful?</p> </blockquote> <p>when using <code>chunksize</code> - all chunks will have the same length. Using <code>iterator</code> parameter you can define how much data (<code>get_chunk(nrows)</code>) you want to read in each iteration:</p> <pre><code>In [66]: reader = pd.read_csv(fn, iterator=True) </code></pre> <p>let's read first 3 rows</p> <pre><code>In [67]: reader.get_chunk(3) Out[67]: a b c 0 2.229657 -1.040086 1.295774 1 0.358098 -1.080557 -0.396338 2 0.731741 -0.690453 0.126648 </code></pre> <p>now we'll read next 5 rows:</p> <pre><code>In [68]: reader.get_chunk(5) Out[68]: a b c 0 -0.009388 -1.549381 0.913128 1 -0.256654 -0.073549 -0.171606 2 0.849934 0.305337 2.360101 3 -1.472184 0.641512 -1.301492 4 -2.302152 0.417787 0.485958 </code></pre> <p>next 7 rows:</p> <pre><code>In [69]: reader.get_chunk(7) Out[69]: a b c 0 0.492314 0.603309 0.890524 1 -0.730400 0.835873 1.313114 2 1.393865 -1.115267 1.194747 3 3.038719 -0.343875 -1.410834 4 -1.510598 0.664154 -0.996762 5 -0.528211 1.269363 0.506728 6 0.043785 -0.786499 -1.073502 </code></pre>
2
2016-08-20T11:45:37Z
[ "python", "pandas" ]
Python multiprocessing infinite loops
39,053,656
<p>I want to process simultaneously a function three times which contains an infinite loop.</p> <p>My code:</p> <pre><code>import multiprocessing def worker(numbers): while True: print numbers if __name__ == '__main__': nums = ["1","2","3"] for i in nums: p = multiprocessing.Process(target=worker(i)) p.start() </code></pre> <p>The problem is that keep looping only to "1"</p> <pre><code>1 1 1 1 1 1 1 </code></pre>
2
2016-08-20T11:35:01Z
39,055,167
<p>As per rawing's comment, instead of passing the function object to the <code>target</code> keyword argument, you are directly calling it and are passing its return value, which never returns since it's an infinite loop.</p> <p>Try this:</p> <pre><code>import multiprocessing _MAX_ITERATIONS = 10 def worker(numbers): iteration = 0 while True: if iteration &gt;= _MAX_ITERATIONS: break print(numbers) iteration += 1 if __name__ == '__main__': nums = ["1","2","3"] for i in nums: p = multiprocessing.Process(target=worker, args=(i,)) p.start() </code></pre> <p>I only added a <code>_MAX_ITERATIONS</code> guard for the sake of not having to kill the processes otherwise.</p>
2
2016-08-20T14:23:32Z
[ "python", "multithreading", "parallel-processing", "multiprocessing" ]
Something going wrong while making my progress bar in GUI
39,053,666
<p>After I succeeded in making a progress bar in console, I thought about upgrading the program to GUI. </p> <p>This is my code: </p> <pre><code>from tkinter import * class Progress(Frame): def __init__(self, master): Frame.__init__(self, master) self.grid() self.value = 1 self.endvalue = 100 self.bar_length = 20 self.label1 = Label(self) self.label1.grid() self.button1 = Button(self, text = "Start", command = self.startprogress()) self.button.grid() def startprogress(self): while self.value &lt;= self.endvalue: root.after(100, self.updateprogress) def updateprogress(self): percent = float(self.value) / self.endvalue arrow = '|' * int(round(percent * self.bar_length)-1) + '|' spaces = ' ' * (self.bar_length - len(arrow)) self.label1.configure( text = "Percent: [{0}] {1}%".format(arrow + spaces, int(round(percent * 100))) ) self.value+=1 root = Tk() root.title("Progress") app = Progress(root) root.mainloop() </code></pre> <p>When I start the program, It does nothing; no error, no window going up.</p> <p>I started debugging it, trying to understand the problem. If I erase all the code under the <code>__init__</code> function, the window would go up. For that I think maybe the <code>while</code> loop is the problem here.</p> <p>Can someone tell me whats the problem in this program?</p>
0
2016-08-20T11:36:07Z
39,053,874
<p>Look at this code:</p> <pre><code>def startprogress(self): while self.value &lt;= self.endvalue: root.after(100, self.updateprogress) </code></pre> <p>This is an infinite loop. I hope I don't need to explain why.</p> <p>What you probably wanted to do is this:</p> <pre><code>def startprogress(self): # queue ONE call to self.updateprogress root.after(100, self.updateprogress) def updateprogress(self): percent = float(self.value) / self.endvalue arrow = '|' * int(round(percent * self.bar_length)-1) + '|' spaces = ' ' * (self.bar_length - len(arrow)) self.label1.configure( text = "Percent: [{0}] {1}%".format(arrow + spaces, int(round(percent * 100))) ) self.value+=1 # now that self.value has been incremented, queue ANOTHER call if self.value &lt;= self.endvalue: root.after(100, self.updateprogress) </code></pre>
2
2016-08-20T11:58:48Z
[ "python", "tkinter" ]
check the width and height of an image
39,053,681
<p>i am trying to check the width and height of an image in a directory by using python . the directory consist of two folders and each folder there are pictures want to check the width and height to resize them if they are not matched. here is my code:</p> <pre><code>def Resize(imageFolder, factor_1, factor_2): for path, dirs, files in os.walk(imageFolder): for fileName in files: image = Image.open(fileName) image_size = image.size width = image_size[0] height = image_size[1] if ((width and height) == 224): print("the width and height are equals") continue print("the width and height are not equals, so we should resize it") resize_pic(path, fileName, factor_1, factor_2) </code></pre> <p>when I run the code gives me error, i think the loop is not right. any help ? </p> <pre><code> Traceback (most recent call last): File "resize.py", line 62, in &lt;module&gt; Resize(imageFolder, resizeFactor , resizeFactor_h) File "resize.py", line 46, in Resize image = Image.open(fileName) File "/usr/lib/python2.7/dist-packages/PIL/Image.py", line 2028, in open raise IOError("cannot identify image file") IOError: cannot identify image file </code></pre>
-3
2016-08-20T11:37:20Z
39,054,813
<pre><code>for (pth, dirs, files) in os.walk(imageFolder): for fileName in files: image = Image.open(fileName) with Image.open(os.path.join(pth, fileName)) as image: image_size = image.size </code></pre> <p>You need provide the absolute path of the file as well like above.</p> <p>Also check on image file format</p>
1
2016-08-20T13:44:18Z
[ "python", "python-2.7", "image-processing" ]
How to check if the lines in two files are included in each other
39,053,697
<p>I am new to python have got a problem with comparison of two files and get the output in Boolean form. I have seen few recommendations here, but due to less application knowledge I think I couldn't get still. These two permission related text files need to be compared</p> <p>1ST text file :perm.txt</p> <pre><code>ACCESS_COARSE_LOCATION ACCESS_FINE_LOCATION ACCESS_NETWORK_STATE BLUETOOTH CAMERA CHANGE_WIFI_STATE EXPAND_STATUS_BAR GET_ACCOUNTS GET_TASKS MANAGE_DOCUMENTS READ_EXTERNAL_STORAGE READ_LOGS RECORD_AUDIO SET_WALLPAPER USE_CREDENTIALS VIBRATE WRITE_CALENDAR </code></pre> <hr> <p>2ND TEXT FILE file :op3.txt</p> <pre><code>GET_TASKS EXPAND_STATUS_BAR SET_WALLPAPER CAMERA MANAGE_DOCUMENTS READ_EXTERNAL_STORAGE ACCESS_COARSE_LOCATION ACCESS_FINE_LOCATION CHANGE_WIFI_STATE VIBRATE RECORD_AUDIO </code></pre> <p>I need to compare 2nd file permissions with first file and based on comparison if permission is same in two files output should be '1' or 'True' if not it should be '0' or 'False'</p> <p>I tried with the following codes </p> <pre><code>f1 = open('op2.txt', 'r') f2 = open('permissions.txt', 'r') FO = open('out1.txt', 'w') for line1 in sorted(f2): if line1 is f1: FO.write(line1 + "True" + '\n') else: FO.write(line1 + "False" + '\n') FO.close() f1.close() f2.close() </code></pre> <p>another attempt i tried like this intially was able to get the output for two or three permissions i tried in diff ways but couldnt get it finally i struck here at this point </p> <pre><code>fname1 = input("Enter the first filename: ") fname2 = input("Enter the second filename: ") f1 = open(fname1) f2 = open(fname2) print("-----------------------------------") print("Comparing files ", " &gt; " + fname1, " &lt; " + fname2, sep='\n') print("-----------------------------------") f1_line = f1.readline() f2_line = f2.readline() line_no = 1 # Loop if either file1 or file2 has not reached EOF while f1_line != '' or f2_line != '': f1_line = f1_line.rstrip() f2_line = f2_line.rstrip() if f1_line != f2_line: # If a line does not exist on file2 then mark the output with false if f2_line == '' and f1_line != '': print("false", "Line-%d" % line_no, f1_line) # otherwise output the line on file1 and mark it with &gt; sign elif f1_line != '': print("True", "Line-%d" % line_no, f1_line) # Print a blank line print() # Read the next line from the file f1_line = f1.readline() f2_line = f2.readline() line_no += 1 f1.close() f2.close() </code></pre>
1
2016-08-20T11:38:56Z
39,061,382
<p>If you only need a fast and quick string comparison, why don't you use hashing (md5/sha1)?</p> <p>Sort the lines, then use something like this:</p> <pre><code>import md5 m1 = md5.md5(file1_str) m2 = md5.md5(file2_str) if m1.hexdigest() == m2.hexdigest(): .... else: .... </code></pre>
1
2016-08-21T06:18:23Z
[ "python" ]
How to check if the lines in two files are included in each other
39,053,697
<p>I am new to python have got a problem with comparison of two files and get the output in Boolean form. I have seen few recommendations here, but due to less application knowledge I think I couldn't get still. These two permission related text files need to be compared</p> <p>1ST text file :perm.txt</p> <pre><code>ACCESS_COARSE_LOCATION ACCESS_FINE_LOCATION ACCESS_NETWORK_STATE BLUETOOTH CAMERA CHANGE_WIFI_STATE EXPAND_STATUS_BAR GET_ACCOUNTS GET_TASKS MANAGE_DOCUMENTS READ_EXTERNAL_STORAGE READ_LOGS RECORD_AUDIO SET_WALLPAPER USE_CREDENTIALS VIBRATE WRITE_CALENDAR </code></pre> <hr> <p>2ND TEXT FILE file :op3.txt</p> <pre><code>GET_TASKS EXPAND_STATUS_BAR SET_WALLPAPER CAMERA MANAGE_DOCUMENTS READ_EXTERNAL_STORAGE ACCESS_COARSE_LOCATION ACCESS_FINE_LOCATION CHANGE_WIFI_STATE VIBRATE RECORD_AUDIO </code></pre> <p>I need to compare 2nd file permissions with first file and based on comparison if permission is same in two files output should be '1' or 'True' if not it should be '0' or 'False'</p> <p>I tried with the following codes </p> <pre><code>f1 = open('op2.txt', 'r') f2 = open('permissions.txt', 'r') FO = open('out1.txt', 'w') for line1 in sorted(f2): if line1 is f1: FO.write(line1 + "True" + '\n') else: FO.write(line1 + "False" + '\n') FO.close() f1.close() f2.close() </code></pre> <p>another attempt i tried like this intially was able to get the output for two or three permissions i tried in diff ways but couldnt get it finally i struck here at this point </p> <pre><code>fname1 = input("Enter the first filename: ") fname2 = input("Enter the second filename: ") f1 = open(fname1) f2 = open(fname2) print("-----------------------------------") print("Comparing files ", " &gt; " + fname1, " &lt; " + fname2, sep='\n') print("-----------------------------------") f1_line = f1.readline() f2_line = f2.readline() line_no = 1 # Loop if either file1 or file2 has not reached EOF while f1_line != '' or f2_line != '': f1_line = f1_line.rstrip() f2_line = f2_line.rstrip() if f1_line != f2_line: # If a line does not exist on file2 then mark the output with false if f2_line == '' and f1_line != '': print("false", "Line-%d" % line_no, f1_line) # otherwise output the line on file1 and mark it with &gt; sign elif f1_line != '': print("True", "Line-%d" % line_no, f1_line) # Print a blank line print() # Read the next line from the file f1_line = f1.readline() f2_line = f2.readline() line_no += 1 f1.close() f2.close() </code></pre>
1
2016-08-20T11:38:56Z
39,061,684
<p>The function </p> <pre><code>get_line_set = lambda f_name: set([l.strip() for l in open(f_name, 'r')]) </code></pre> <p>Creates a <a href="https://docs.python.org/2/library/sets.html" rel="nofollow"><code>set</code></a> of the lines of <code>f_name</code>.</p> <p>Now you can just use </p> <pre><code>get_line_set('perm.txt') == get_line_set('op3.txt') </code></pre> <p>Moreover, sets allow you to see intersection, difference, symmetric difference, and so forth. E.g., to see the difference from <code>perm.txt</code> to <code>op3.txt</code>, just change this to </p> <pre><code>get_line_set('perm.txt').difference(get_line_set('op3.txt')) </code></pre>
1
2016-08-21T07:04:54Z
[ "python" ]
How to check if the lines in two files are included in each other
39,053,697
<p>I am new to python have got a problem with comparison of two files and get the output in Boolean form. I have seen few recommendations here, but due to less application knowledge I think I couldn't get still. These two permission related text files need to be compared</p> <p>1ST text file :perm.txt</p> <pre><code>ACCESS_COARSE_LOCATION ACCESS_FINE_LOCATION ACCESS_NETWORK_STATE BLUETOOTH CAMERA CHANGE_WIFI_STATE EXPAND_STATUS_BAR GET_ACCOUNTS GET_TASKS MANAGE_DOCUMENTS READ_EXTERNAL_STORAGE READ_LOGS RECORD_AUDIO SET_WALLPAPER USE_CREDENTIALS VIBRATE WRITE_CALENDAR </code></pre> <hr> <p>2ND TEXT FILE file :op3.txt</p> <pre><code>GET_TASKS EXPAND_STATUS_BAR SET_WALLPAPER CAMERA MANAGE_DOCUMENTS READ_EXTERNAL_STORAGE ACCESS_COARSE_LOCATION ACCESS_FINE_LOCATION CHANGE_WIFI_STATE VIBRATE RECORD_AUDIO </code></pre> <p>I need to compare 2nd file permissions with first file and based on comparison if permission is same in two files output should be '1' or 'True' if not it should be '0' or 'False'</p> <p>I tried with the following codes </p> <pre><code>f1 = open('op2.txt', 'r') f2 = open('permissions.txt', 'r') FO = open('out1.txt', 'w') for line1 in sorted(f2): if line1 is f1: FO.write(line1 + "True" + '\n') else: FO.write(line1 + "False" + '\n') FO.close() f1.close() f2.close() </code></pre> <p>another attempt i tried like this intially was able to get the output for two or three permissions i tried in diff ways but couldnt get it finally i struck here at this point </p> <pre><code>fname1 = input("Enter the first filename: ") fname2 = input("Enter the second filename: ") f1 = open(fname1) f2 = open(fname2) print("-----------------------------------") print("Comparing files ", " &gt; " + fname1, " &lt; " + fname2, sep='\n') print("-----------------------------------") f1_line = f1.readline() f2_line = f2.readline() line_no = 1 # Loop if either file1 or file2 has not reached EOF while f1_line != '' or f2_line != '': f1_line = f1_line.rstrip() f2_line = f2_line.rstrip() if f1_line != f2_line: # If a line does not exist on file2 then mark the output with false if f2_line == '' and f1_line != '': print("false", "Line-%d" % line_no, f1_line) # otherwise output the line on file1 and mark it with &gt; sign elif f1_line != '': print("True", "Line-%d" % line_no, f1_line) # Print a blank line print() # Read the next line from the file f1_line = f1.readline() f2_line = f2.readline() line_no += 1 f1.close() f2.close() </code></pre>
1
2016-08-20T11:38:56Z
39,061,934
<p>one way to do this is below:</p> <pre><code>f1 = open('perm.txt', 'rb') f2 = open('op3.txt', 'rb') f1_lines = f1.readlines() f2_lines = f2.readlines() f1.close() f2.close() overall_compare_result = True fo = open('out1.txt', 'w') for each in f1_lines: if each in f2_lines: fo.write(each.strip() + ' True\n') else: fo.write(each.strip() + ' False\n') if overall_compare_result: overall_compare_result = False fo.close() print("overall comparision result: " + str(overall_compare_result)) </code></pre> <p><strong>out.txt will have below:</strong></p> <pre><code>ACCESS_COARSE_LOCATION True ACCESS_FINE_LOCATION True ACCESS_NETWORK_STATE False BLUETOOTH False CAMERA True CHANGE_WIFI_STATE True EXPAND_STATUS_BAR True GET_ACCOUNTS False GET_TASKS True MANAGE_DOCUMENTS True READ_EXTERNAL_STORAGE True READ_LOGS False RECORD_AUDIO False SET_WALLPAPER True USE_CREDENTIALS False VIBRATE True WRITE_CALENDAR False </code></pre>
0
2016-08-21T07:38:25Z
[ "python" ]
Improving the performance of repetitive groupby operations
39,053,734
<p>I have a DataFrame with MultiIndex which is basically a binary matrix:</p> <pre><code>day day01 day02 session session1 session2 session3 session1 session2 session3 0 1 0 0 0 0 0 1 0 0 1 1 1 0 2 1 1 1 0 0 1 3 1 0 0 1 0 0 4 1 0 1 0 0 0 </code></pre> <p>From this DataFrame, I need to calculate daily sums for each row:</p> <pre><code> day01 day02 0 1 0 1 1 2 2 3 1 3 1 1 4 2 0 </code></pre> <p>And get the number of 0s, 1s... (value counts) in this sum:</p> <pre><code>0 2 1 5 2 2 3 1 </code></pre> <p>I need to do this for sessions, too. Session sums for each row:</p> <pre><code> session1 session2 session3 0 1 0 0 1 1 1 1 2 1 1 2 3 2 0 0 4 1 0 1 </code></pre> <p>And get the value counts:</p> <pre><code>0 5 1 8 2 2 </code></pre> <p>As a baseline, this is the result of <code>df.groupby(level='day', axis=1).sum().stack().value_counts()</code> (and <code>df.groupby(level='session', axis=1).sum().stack().value_counts()</code>). The DataFrame changes in each iteration of a simulated annealing algorithm and these counts are recalculated. When I profiled the code I saw that a significant amount of time spent on groupby operations. </p> <p>I tried saving groupby objects and taking sums on those objects in each iteration but the improvement was about 10%. Here's the code to create a larger DataFrame (similar to the one I have):</p> <pre><code>import numpy as np import pandas as pd prng = np.random.RandomState(0) days = ['day{0:02d}'.format(i) for i in range(1, 11)] sessions = ['session{}'.format(i) for i in range(1, 5)] idx = pd.MultiIndex.from_product((days, sessions), names=['day', 'session']) df = pd.DataFrame(prng.binomial(1, 0.25, (1250, 40)), columns=idx) </code></pre> <p>In my computer, the following two methods take 3.8s and 3.38s respectively.</p> <pre><code>def try1(df, num_repeats=1000): for i in range(num_repeats): session_counts = (df.groupby(level='session', axis=1, sort=False) .sum() .stack() .value_counts(sort=False)) daily_counts = (df.groupby(level='day', axis=1, sort=False) .sum() .stack() .value_counts(sort=False)) return session_counts, daily_counts def try2(df, num_repeats=1000): session_groups = df.groupby(level='session', axis=1, sort=False) day_groups = df.groupby(level='day', axis=1, sort=False) for i in range(num_repeats): df.iat[0, 0] = (i + 1) % 2 session_counts = session_groups.sum().stack().value_counts(sort=False) daily_counts = day_groups.sum().stack().value_counts(sort=False) return session_counts, daily_counts %time try1(df) Wall time: 3.8 s %time try2(df) Wall time: 3.38 s </code></pre> <p>Note: The loops in the functions are for timing only. For the second function in order to get correct timings I needed to modify the DataFrame. </p> <p><s>I am currently working on another method to directly reflect the changes in the DataFrame to counts without recalculating the groups but I haven't succeeded yet.</s> Tracking the affected rows and updating saved DataFrames turned out to be slower.</p> <p>Is there a way to improve the performance of these groupby operations? </p>
3
2016-08-20T11:44:15Z
39,054,362
<p>Assuming a regular data format (equal number of days and sessions across each row), here's a NumPy based approach using <code>np.unique</code> with the output having their indexes in sorted order -</p> <pre><code># Extract array a,b = df.columns.levels arr = df.values.reshape(-1,len(a),len(b)) # Get session counts session_sums = arr.sum(1) unq,count = np.unique(session_sums,return_counts=True) session_counts_out = pd.Series(count,index=unq) # Get daily count daily_sums = arr.sum(2) unq,count = np.unique(daily_sums,return_counts=True) daily_counts_out = pd.Series(count,index=unq) </code></pre> <p>If you are only interested in the values without the indexes, here's an alternative with <code>np.bincount</code> that essentially just does the counting, as done by <code>return_counts</code> part with <code>np.unique</code> -</p> <pre><code># Get session counts session_sums = arr.sum(1) count = np.bincount(session_sums.ravel()) session_counts_out = count[count&gt;0] # Get daily count daily_sums = arr.sum(2) count = np.bincount(daily_sums.ravel()) daily_counts_out = count[count&gt;0] </code></pre>
1
2016-08-20T12:50:48Z
[ "python", "pandas", "numpy" ]
Django error SiteProfileNotAvailable
39,053,745
<p>Im installed django-userena with django 1.9.7, <a href="https://github.com/bread-and-pepper/django-userena" rel="nofollow">https://github.com/bread-and-pepper/django-userena</a> step by step ,why I'm I getting this error?</p> <p>Thanks settings.py</p> <pre><code>INSTALLED_APPS = [ 'userena', 'guardian', 'easy_thumbnails', ] ANONYMOUS_USER_ID = -1 </code></pre> <p>error:</p> <pre><code>Traceback (most recent call last): File "manage.py", line 12, in &lt;module&gt; execute_from_command_line(sys.argv) File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 353, in execute_from_command_line utility.execute() File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 327, in execute django.setup() File "C:\Python27\lib\site-packages\django\__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Python27\lib\site-packages\django\apps\registry.py", line 115, in populate app_config.ready() File "C:\Python27\lib\site-packages\django\contrib\admin\apps.py", line 22, in ready self.module.autodiscover() File "C:\Python27\lib\site-packages\django\contrib\admin\__init__.py", line 26, in autodiscover autodiscover_modules('admin', register_to=site) File "C:\Python27\lib\site-packages\django\utils\module_loading.py", line 50, in autodiscover_modules import_module('%s.%s' % (app_config.name, module_to_search)) File "C:\Python27\lib\importlib\__init__.py", line 37, in import_module __import__(name) File "C:\Python27\lib\site-packages\userena\admin.py", line 31, in &lt;module&gt; admin.site.register(get_profile_model(), GuardedModelAdmin) File "C:\Python27\lib\site-packages\userena\utils.py", line 137, in get_profile_model raise SiteProfileNotAvailable userena.compat.SiteProfileNotAvailable </code></pre>
0
2016-08-20T11:45:16Z
39,054,132
<p>As mentioned in the <a href="http://django-userena.readthedocs.io/en/latest/installation.html#id2" rel="nofollow">docs</a> you need to create a Site object (see <a href="https://docs.djangoproject.com/en/1.10/ref/contrib/sites/" rel="nofollow">Sites Framework</a>) either from admin panel or shell or via fixture and define its ID in settings using <code>SITE_ID</code>.</p>
0
2016-08-20T12:26:30Z
[ "python", "django", "django-users" ]
How to set a clicking clock in a pygame window
39,053,817
<pre><code>#!/usr/bin/python # -*- coding: utf-8 -*- import pygame import sys import datetime import time class TextPicture(pygame.sprite.Sprite): def __init__(self, speed, location): pygame.sprite.Sprite.__init__(self) now = datetime.datetime.now() text = now.strftime("%H:%M:%S") font = pygame.font.Font(None, 40) time_text = font.render(text, 1, [0, 0, 0]) # show now time self.image = time_text self.speed = speed self.rect = self.image.get_rect() self.rect.left, self.rect.top = location def move(self): self.rect = self.rect.move(self.speed) if self.rect.left &lt; 0 or self.rect.left &gt; screen.get_width() - self.image.get_width(): self.speed[0] = -self.speed[0] if self.rect.top &lt; 0 or self.rect.top &gt; screen.get_height() - self.image.get_height(): self.speed[1] = -self.speed[1] pygame.init() screen = pygame.display.set_mode([640, 480]) my_time_picture = TextPicture([1, 1], [50, 50]) while 1: screen.fill([255, 255, 255]) my_time_picture.move() screen.blit(my_time_picture.image, my_time_picture.rect) pygame.display.flip() for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() </code></pre> <p>I am designing a clock which can move in the screen. But what my code can do now is to show a invariant time. I want to clicking and count the time. <a href="http://i.stack.imgur.com/Z4bhP.png" rel="nofollow">My invariable clock picture</a></p> <p>And I want to make my clock more beautiful, but don't know how. I will be super grateful if anyone can make any suggestions. </p>
0
2016-08-20T11:52:03Z
39,054,676
<p>You could do it by using <a href="http://www.pygame.org/docs/ref/time.html#pygame.time.set_timer" rel="nofollow"><code>pygame.time.set_timer()</code></a> to make "tick events" be generated which cause the clock's image to be updated when encountered in the event processing loop.</p> <p>To make implementing this easier, an <code>update()</code> method could be added to the <code>DigitalClock</code> class (which is what I renamed your generic <code>TextPicture</code> class) which only updates the image, but leaving the current location alone:</p> <pre><code>import datetime import sys import time import pygame class DigitalClock(pygame.sprite.Sprite): def __init__(self, speed, location): pygame.sprite.Sprite.__init__(self) self.speed = speed self.font = pygame.font.Font(None, 40) self.rect = pygame.Rect(location, (0, 0)) # placeholder self.update() def update(self): location = self.rect.left, self.rect.top # save position time_text = datetime.datetime.now().strftime("%H:%M:%S") self.image = self.font.render(time_text, 1, [0, 0, 0]) self.rect = self.image.get_rect() self.rect.left, self.rect.top = location # restore position def move(self): self.rect = self.rect.move(self.speed) if (self.rect.left &lt; 0 or self.rect.left &gt; screen.get_width()-self.image.get_width()): self.speed[0] = -self.speed[0] if (self.rect.top &lt; 0 or self.rect.top &gt; screen.get_height()-self.image.get_height()): self.speed[1] = -self.speed[1] </code></pre> <p>Following that, you'd need to modify the processing to be something along these lines:</p> <pre><code>pygame.init() framerate_clock = pygame.time.Clock() screen = pygame.display.set_mode([640, 480]) my_digital_clock = DigitalClock([1, 1], [50, 50]) TICK_EVENT = pygame.USEREVENT + 1 pygame.time.set_timer(TICK_EVENT, 1000) # periodically create TICK_EVENT while True: for event in pygame.event.get(): if event.type == TICK_EVENT: my_digital_clock.update() # call new method if event.type == pygame.QUIT: pygame.quit() sys.exit() screen.fill([255, 255, 255]) my_digital_clock.move() screen.blit(my_digital_clock.image, my_digital_clock.rect) framerate_clock.tick(60) # limit framerate pygame.display.flip() </code></pre> <p>You could make it more beautiful by using a different font and color. Generally anything that made it look more realistic would be an improvement. It might be cool to make the colons between the digit characters blink on and off (using a similar technique).</p>
2
2016-08-20T13:27:53Z
[ "python", "python-2.7", "pygame-clock" ]
how to select a radio button in selenium python?
39,053,899
<pre><code>&lt;ul&gt; &lt;li&gt; &lt;label class="checkbox"&gt; &lt;input checked="checked" id="fechapublicacion" name="fechapublicacion" onclick="javascript: filtrarListado(&amp;#39;fechapublicacion&amp;#39;, this);" type="radio" value="0" /&gt; &lt;span&gt;Cualquier fecha&lt;/span&gt; &lt;/label&gt; &lt;input id="fechapublicacionhidden" name="fechapublicacionhidden" type="hidden" value="0" /&gt; &lt;/li&gt; &lt;li&gt; &lt;label class="checkbox"&gt; &lt;input id="fechapublicacion" name="fechapublicacion" onclick="javascript: filtrarListado(&amp;#39;fechapublicacion&amp;#39;, this);" type="radio" value="1" /&gt; &lt;span&gt;&amp;#218;ltimas 24 horas&lt;/span&gt; &lt;/label&gt; &lt;input id="fechapublicacionhidden" name="fechapublicacionhidden" type="hidden" value="0" /&gt; &lt;/li&gt; &lt;li&gt; &lt;label class="checkbox"&gt; &lt;input id="fechapublicacion" name="fechapublicacion" onclick="javascript: filtrarListado(&amp;#39;fechapublicacion&amp;#39;, this);" type="radio" value="7" /&gt; &lt;span&gt;&amp;#218;ltimos 7 d&amp;#237;as&lt;/span&gt; &lt;/label&gt; &lt;input id="fechapublicacionhidden" name="fechapublicacionhidden" type="hidden" value="0" /&gt; &lt;/li&gt; &lt;li&gt; &lt;label class="checkbox"&gt; &lt;input id="fechapublicacion" name="fechapublicacion" onclick="javascript: filtrarListado(&amp;#39;fechapublicacion&amp;#39;, this);" type="radio" value="15" /&gt; &lt;span&gt;&amp;#218;ltimos 15 d&amp;#237;as&lt;/span&gt; &lt;/label&gt; &lt;input id="fechapublicacionhidden" name="fechapublicacionhidden" type="hidden" value="0" /&gt; &lt;/li&gt; &lt;/ul&gt; </code></pre> <p>I am trying to select the last radio button. Since all of them have same id, how can i select the last one.</p> <p>Any help will be appreciated.</p>
0
2016-08-20T12:01:35Z
39,053,988
<p>You are using find_elements.... which returns a list. Use findelement or getelement which returns one element(i got no idea abt python functions). Or else use an index 0 to findelements. it is saying it is trying yo find a click method on a list which it aint got</p>
0
2016-08-20T12:10:40Z
[ "python", "selenium", "selenium-webdriver" ]
how to select a radio button in selenium python?
39,053,899
<pre><code>&lt;ul&gt; &lt;li&gt; &lt;label class="checkbox"&gt; &lt;input checked="checked" id="fechapublicacion" name="fechapublicacion" onclick="javascript: filtrarListado(&amp;#39;fechapublicacion&amp;#39;, this);" type="radio" value="0" /&gt; &lt;span&gt;Cualquier fecha&lt;/span&gt; &lt;/label&gt; &lt;input id="fechapublicacionhidden" name="fechapublicacionhidden" type="hidden" value="0" /&gt; &lt;/li&gt; &lt;li&gt; &lt;label class="checkbox"&gt; &lt;input id="fechapublicacion" name="fechapublicacion" onclick="javascript: filtrarListado(&amp;#39;fechapublicacion&amp;#39;, this);" type="radio" value="1" /&gt; &lt;span&gt;&amp;#218;ltimas 24 horas&lt;/span&gt; &lt;/label&gt; &lt;input id="fechapublicacionhidden" name="fechapublicacionhidden" type="hidden" value="0" /&gt; &lt;/li&gt; &lt;li&gt; &lt;label class="checkbox"&gt; &lt;input id="fechapublicacion" name="fechapublicacion" onclick="javascript: filtrarListado(&amp;#39;fechapublicacion&amp;#39;, this);" type="radio" value="7" /&gt; &lt;span&gt;&amp;#218;ltimos 7 d&amp;#237;as&lt;/span&gt; &lt;/label&gt; &lt;input id="fechapublicacionhidden" name="fechapublicacionhidden" type="hidden" value="0" /&gt; &lt;/li&gt; &lt;li&gt; &lt;label class="checkbox"&gt; &lt;input id="fechapublicacion" name="fechapublicacion" onclick="javascript: filtrarListado(&amp;#39;fechapublicacion&amp;#39;, this);" type="radio" value="15" /&gt; &lt;span&gt;&amp;#218;ltimos 15 d&amp;#237;as&lt;/span&gt; &lt;/label&gt; &lt;input id="fechapublicacionhidden" name="fechapublicacionhidden" type="hidden" value="0" /&gt; &lt;/li&gt; &lt;/ul&gt; </code></pre> <p>I am trying to select the last radio button. Since all of them have same id, how can i select the last one.</p> <p>Any help will be appreciated.</p>
0
2016-08-20T12:01:35Z
39,054,046
<p>Actually <code>find_elements</code> returns list that's why you are in trouble, you should try using <code>find_element</code> instead as below :-</p> <pre><code>browser.find_element_by_id("fechapublicacion").click() </code></pre> <p>Or if you want to use <code>find_elements</code>, You should try using index in returned list as below :-</p> <pre><code>browser.find_elements_by_id("fechapublicacion")[0].click() </code></pre> <p><strong>Edited</strong> :- As I'm seeing in provided HTML, I'd is not unique there and you want to select last element with the id then try using <code>find_elements</code> and select last element by passing last index as <code>-1</code> :</p> <pre><code>browser.find_elements_by_id("fechapublicacion")[-1].click() </code></pre> <p>Or you can also use <code>find_element</code> to point this element using unique <code>css_selector</code> as below :-</p> <pre><code>browser.find_element_by_css_selector("input#fechapublicacion[value='15']").click() </code></pre>
2
2016-08-20T12:17:00Z
[ "python", "selenium", "selenium-webdriver" ]
How to get more usable error messages from ansible-playbook?
39,054,099
<p><code>ansible-playbook</code> gives me errors that look like this:</p> <pre><code>fatal: [test.example.com]: FAILED! =&gt; {"changed": false, "cmd": "./manage.py migrate --noinput --pythonpath=/srv/virtualenv/myapp/bin/python3", "failed": true, "msg": "\n:stderr: Traceback (most recent call last):\n File \"./manage.py\", line 10, in &lt;module&gt;\n execute_from_command_line(sys.argv)\n File \"/srv/virtualenv/myapp/lib/python3.5/site-packages/django/core/management/__init__.py\", line 354, in execute_from_command_line\n utility.execute()\n File \"/srv/virtualenv/myapp/lib/python3.5/site-packages/django/core/management/__init__.py\", line 303, in execute\n settings.INSTALLED_APPS\n File \"/srv/virtualenv/myapp/lib/python3.5/site-packages/django/conf/__init__.py\", line 48, in __getattr__\n self._setup(name)\n File \"/srv/virtualenv/myapp/lib/python3.5/site-packages/django/conf/__init__.py\", line 44, in _setup\n self._wrapped = Settings(settings_module)\n File \"/srv/virtualenv/myapp/lib/python3.5/site-packages/django/conf/__init__.py\", line 92, in __init__\n mod = importlib.import_module(self.SETTINGS_MODULE)\n File \"/srv/virtualenv/myapp/lib/python3.5/importlib/__init__.py\", line 126, in import_module\n return _bootstrap._gcd_import(name[level:], package, level)\n File \"&lt;frozen importlib._bootstrap&gt;\", line 986, in _gcd_import\n File \"&lt;frozen importlib._bootstrap&gt;\", line 969, in _find_and_load\n File \"&lt;frozen importlib._bootstrap&gt;\", line 956, in _find_and_load_unlocked\nImportError: No module named 'myapp.settings'\n", "path": "/srv/virtualenv/myapp/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", "state": "absent", "syspath": ["/tmp/ansible_OoxaWI", "/tmp/ansible_OoxaWI/ansible_modlib.zip", "/usr/lib/python2.7", "/usr/lib/python2.7/plat-x86_64-linux-gnu", "/usr/lib/python2.7/lib-tk", "/usr/lib/python2.7/lib-old", "/usr/lib/python2.7/lib-dynload", "/usr/local/lib/python2.7/dist-packages", "/usr/lib/python2.7/dist-packages"]} </code></pre> <p>Of course I could copy this and paste it into <code>ipython</code> to get a more usable view on things, i.e.</p> <pre><code>fatal: [test.example.com]: FAILED! =&gt; {"changed": false, "cmd": "./manage.py migrate --noinput --pythonpath=/srv/virtualenv/myapp/bin/python3", "failed": true, "msg": " :stderr: Traceback (most recent call last): File "./manage.py", line 10, in &lt;module&gt; execute_from_command_line(sys.argv) File "/srv/virtualenv/myapp/lib/python3.5/site-packages/django/core/management/__init__.py", line 354, in execute_from_command_line utility.execute() File "/srv/virtualenv/myapp/lib/python3.5/site-packages/django/core/management/__init__.py", line 303, in execute settings.INSTALLED_APPS File "/srv/virtualenv/myapp/lib/python3.5/site-packages/django/conf/__init__.py", line 48, in __getattr__ self._setup(name) File "/srv/virtualenv/myapp/lib/python3.5/site-packages/django/conf/__init__.py", line 44, in _setup self._wrapped = Settings(settings_module) File "/srv/virtualenv/myapp/lib/python3.5/site-packages/django/conf/__init__.py", line 92, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/srv/virtualenv/myapp/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "&lt;frozen importlib._bootstrap&gt;", line 986, in _gcd_import File "&lt;frozen importlib._bootstrap&gt;", line 969, in _find_and_load File "&lt;frozen importlib._bootstrap&gt;", line 956, in _find_and_load_unlocked ImportError: No module named 'myapp.settings' ", "path": "/srv/virtualenv/myapp/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", "state": "absent", "syspath": ["/tmp/ansible_OoxaWI", "/tmp/ansible_OoxaWI/ansible_modlib.zip", "/usr/lib/python2.7", "/usr/lib/python2.7/plat-x86_64-linux-gnu", "/usr/lib/python2.7/lib-tk", "/usr/lib/python2.7/lib-old", "/usr/lib/python2.7/lib-dynload", "/usr/local/lib/python2.7/dist-packages", "/usr/lib/python2.7/dist-packages"]} </code></pre> <p>But I'd like <code>ansible</code> to do that for me. How can I do that?</p> <p>This is related but doesn't look like solution to my problem: <a href="http://stackoverflow.com/questions/20563639/ansible-playbook-shell-output">Ansible playbook shell output</a></p>
0
2016-08-20T12:23:15Z
39,055,930
<p>Ansible allows you to control its output by using <a href="http://docs.ansible.com/ansible/developing_plugins.html#callbacks" rel="nofollow">callback plugins</a> and provides a few optional callbacks <a href="https://github.com/ansible/ansible/tree/devel/lib/ansible/plugins/callback" rel="nofollow">out of the box</a>.</p> <p>To configure them simply set the <a href="http://docs.ansible.com/ansible/intro_configuration.html#callback-plugins" rel="nofollow"><code>callback_plugs</code> option</a> in <code>ansible.cfg</code>:</p> <pre><code>callback_plugins = ~/.ansible/plugins/callback:/usr/share/ansible/plugins/callback </code></pre> <p>To get Ansible to print the newlines rather than render them as <code>\n</code>s you could develop your own callback or simply use the <a href="https://gist.github.com/cliffano/9868180" rel="nofollow"><code>human_log</code></a> callback plugin developed by <a href="http://blog.cliffano.com/2014/04/06/human-readable-ansible-playbook-log-output-using-callback-plugin/" rel="nofollow">Cliffano Subagio</a>.</p> <p>For Ansible 2 compatibility (the plugin system was rewritten in the version upgrade from Ansible 1.x) an equivalent was written by <a href="https://github.com/n0ts/ansible-human_log" rel="nofollow">n0ts</a>.</p>
1
2016-08-20T15:42:46Z
[ "python", "ansible" ]
How to get more usable error messages from ansible-playbook?
39,054,099
<p><code>ansible-playbook</code> gives me errors that look like this:</p> <pre><code>fatal: [test.example.com]: FAILED! =&gt; {"changed": false, "cmd": "./manage.py migrate --noinput --pythonpath=/srv/virtualenv/myapp/bin/python3", "failed": true, "msg": "\n:stderr: Traceback (most recent call last):\n File \"./manage.py\", line 10, in &lt;module&gt;\n execute_from_command_line(sys.argv)\n File \"/srv/virtualenv/myapp/lib/python3.5/site-packages/django/core/management/__init__.py\", line 354, in execute_from_command_line\n utility.execute()\n File \"/srv/virtualenv/myapp/lib/python3.5/site-packages/django/core/management/__init__.py\", line 303, in execute\n settings.INSTALLED_APPS\n File \"/srv/virtualenv/myapp/lib/python3.5/site-packages/django/conf/__init__.py\", line 48, in __getattr__\n self._setup(name)\n File \"/srv/virtualenv/myapp/lib/python3.5/site-packages/django/conf/__init__.py\", line 44, in _setup\n self._wrapped = Settings(settings_module)\n File \"/srv/virtualenv/myapp/lib/python3.5/site-packages/django/conf/__init__.py\", line 92, in __init__\n mod = importlib.import_module(self.SETTINGS_MODULE)\n File \"/srv/virtualenv/myapp/lib/python3.5/importlib/__init__.py\", line 126, in import_module\n return _bootstrap._gcd_import(name[level:], package, level)\n File \"&lt;frozen importlib._bootstrap&gt;\", line 986, in _gcd_import\n File \"&lt;frozen importlib._bootstrap&gt;\", line 969, in _find_and_load\n File \"&lt;frozen importlib._bootstrap&gt;\", line 956, in _find_and_load_unlocked\nImportError: No module named 'myapp.settings'\n", "path": "/srv/virtualenv/myapp/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", "state": "absent", "syspath": ["/tmp/ansible_OoxaWI", "/tmp/ansible_OoxaWI/ansible_modlib.zip", "/usr/lib/python2.7", "/usr/lib/python2.7/plat-x86_64-linux-gnu", "/usr/lib/python2.7/lib-tk", "/usr/lib/python2.7/lib-old", "/usr/lib/python2.7/lib-dynload", "/usr/local/lib/python2.7/dist-packages", "/usr/lib/python2.7/dist-packages"]} </code></pre> <p>Of course I could copy this and paste it into <code>ipython</code> to get a more usable view on things, i.e.</p> <pre><code>fatal: [test.example.com]: FAILED! =&gt; {"changed": false, "cmd": "./manage.py migrate --noinput --pythonpath=/srv/virtualenv/myapp/bin/python3", "failed": true, "msg": " :stderr: Traceback (most recent call last): File "./manage.py", line 10, in &lt;module&gt; execute_from_command_line(sys.argv) File "/srv/virtualenv/myapp/lib/python3.5/site-packages/django/core/management/__init__.py", line 354, in execute_from_command_line utility.execute() File "/srv/virtualenv/myapp/lib/python3.5/site-packages/django/core/management/__init__.py", line 303, in execute settings.INSTALLED_APPS File "/srv/virtualenv/myapp/lib/python3.5/site-packages/django/conf/__init__.py", line 48, in __getattr__ self._setup(name) File "/srv/virtualenv/myapp/lib/python3.5/site-packages/django/conf/__init__.py", line 44, in _setup self._wrapped = Settings(settings_module) File "/srv/virtualenv/myapp/lib/python3.5/site-packages/django/conf/__init__.py", line 92, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/srv/virtualenv/myapp/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "&lt;frozen importlib._bootstrap&gt;", line 986, in _gcd_import File "&lt;frozen importlib._bootstrap&gt;", line 969, in _find_and_load File "&lt;frozen importlib._bootstrap&gt;", line 956, in _find_and_load_unlocked ImportError: No module named 'myapp.settings' ", "path": "/srv/virtualenv/myapp/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", "state": "absent", "syspath": ["/tmp/ansible_OoxaWI", "/tmp/ansible_OoxaWI/ansible_modlib.zip", "/usr/lib/python2.7", "/usr/lib/python2.7/plat-x86_64-linux-gnu", "/usr/lib/python2.7/lib-tk", "/usr/lib/python2.7/lib-old", "/usr/lib/python2.7/lib-dynload", "/usr/local/lib/python2.7/dist-packages", "/usr/lib/python2.7/dist-packages"]} </code></pre> <p>But I'd like <code>ansible</code> to do that for me. How can I do that?</p> <p>This is related but doesn't look like solution to my problem: <a href="http://stackoverflow.com/questions/20563639/ansible-playbook-shell-output">Ansible playbook shell output</a></p>
0
2016-08-20T12:23:15Z
39,056,816
<p>Increase the verbosity. Add <code>-vvvv</code> at the end of ansible-playbook command. It will set the verbosity to 4 and that much logs are good enough most of the time.</p>
1
2016-08-20T17:17:23Z
[ "python", "ansible" ]
Level-Wise Sorting of Series in Pandas
39,054,107
<p>I have a dataframe called mydf</p> <pre><code>mydf </code></pre> <p><a href="http://i.stack.imgur.com/atOtv.png" rel="nofollow"><img src="http://i.stack.imgur.com/atOtv.png" alt="enter image description here"></a></p> <p>I performed below operation and it is then converted into a series.</p> <pre><code>mydf.groupby([mydf.type,mydf.name]).size() </code></pre> <p>Now I have a series with two levels of type i.e. actor and actress.</p> <pre><code> type name actor 'Big' Ben Moroz 1 'Ducky' Louie 3 'Fast' Eddie Mahler 1 'King Kong' Kashey 1 'Muddy' Berry 1 actress Zedra Conde 3 Zena Marshall 1 Zinaida Morskaya 1 Zoe Holland 1 Zoia Karabanova 2 </code></pre> <p>Now I want my result to be sorted in descending order in the <strong>level</strong> actor and if actor <strong>"value"</strong> (given in third unnamed say column) is same then the sorting must be done by <strong>"name"</strong> and then same pattern must be followed when sorting is done in other <strong>level</strong> called actress </p> <pre><code>type name actor 'Ducky' Louie 3 'Big' Ben Moroz 1 'Fast' Eddie Mahler 1 'King Kong' Kashey 1 'Muddy' Berry 1 actress Zedra Conde 3 Zoia Karabanova 2 Zena Marshall 1 Zinaida Morskaya 1 Zoe Holland 1 </code></pre> <p>Note:- Please avoid looping. </p>
1
2016-08-20T12:24:00Z
39,056,119
<p>Unfortunately everything I came up with requires double grouping/sorting. Suppose we have a DataFrame</p> <pre><code>import pandas as pd import numpy as np import random d = pd.DataFrame({'type': ['actor']*5+['actress']*5, 'name' : [random.choice(['a', 'b', 'c']) for i in range(10)]}) d name type 0 c actor 1 c actor 2 a actor 3 b actor 4 a actor 5 c actress 6 c actress 7 c actress 8 a actress 9 a actress d.groupby([d.type,d.name]).size() type name actor a 2 b 1 c 2 actress a 2 c 3 dtype: int64 </code></pre> <p>Approach 1:</p> <pre><code>d.groupby([d.type,d.name]).size().groupby(level=[0]).apply(lambda x: x.sort_values(ascending=False)) type type name actor actor c 2 a 2 b 1 actress actress c 3 a 2 dtype: int64 </code></pre> <p>Approach 2:</p> <pre><code>d1 = d.groupby([d.type,d.name]).size() d2 = d1.reset_index() d2.columns = ['type', 'actress', 'sz'] d2.sort_values(by = ['type', 'sz', 'actress'], ascending = [True, False, True]) type actress sz 0 actor a 2 2 actor c 2 1 actor b 1 4 actress c 3 3 actress a 2 </code></pre>
0
2016-08-20T16:01:00Z
[ "python", "python-3.x", "sorting", "pandas", "series" ]
Tkinter custom create buttons
39,054,156
<p>can tkinter custom buttons from a image or icon like this <a href="http://i.stack.imgur.com/pOTbI.png" rel="nofollow"><img src="http://i.stack.imgur.com/pOTbI.png" alt="enter image description here"></a></p> <p><a href="http://i.stack.imgur.com/nqNRA.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/nqNRA.jpg" alt="enter image description here"></a></p> <p>tkinter have normal buttons i dont want add a image buttons i want create a new button or styles<a href="http://i.stack.imgur.com/LBq38.png" rel="nofollow"><img src="http://i.stack.imgur.com/LBq38.png" alt="enter image description here"></a></p>
-2
2016-08-20T12:28:42Z
39,057,406
<p>It's possible!</p> <p>If you check out the <a href="http://effbot.org/tkinterbook/button.htm" rel="nofollow">button documentation</a>, you can use an image to display on the button.</p> <p>For example:</p> <pre><code>from tkinter import * root = Tk() button = Button(root, text="Click me!") img = PhotoImage(file="C:/path to image/example.gif") # make sure to add "/" not "\" button.config(image=img) button.pack() # Displaying the button root.mainloop() </code></pre> <p>This is a simplified example for adding an image to a button widget, you can make many more cool things with the button widget.</p>
1
2016-08-20T18:25:11Z
[ "python", "button", "tkinter", "python-3.5", "ttk" ]
How to override Django-CMS templates
39,054,370
<p>settings.py</p> <pre><code>from .ENV import BASE_DIR, ENV_VAR # SECURITY WARNING: don't run with debug turned on in production! # False if not in os.environ DEBUG = ENV_VAR('DEBUG', default=False) # SECURITY WARNING: keep the secret key used in production secret! # If not found in os.environ will raise ImproperlyConfigured error SECRET_KEY = ENV_VAR('SECRET_KEY') SITE_ID = 1 # Application definition INSTALLED_APPS = [ 'djangocms_admin_style', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.admin', 'django.contrib.sites', 'django.contrib.sitemaps', 'django.contrib.staticfiles', 'django.contrib.messages', 'cms', 'menus', 'sekizai', 'treebeard', 'djangocms_text_ckeditor', 'djangocms_style', 'djangocms_column', 'djangocms_file', 'djangocms_googlemap', 'djangocms_inherit', 'djangocms_link', 'djangocms_picture', 'djangocms_teaser', 'djangocms_video', 'reversion', 'config', ] MIDDLEWARE_CLASSES = [ 'cms.middleware.utils.ApphookReloadMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'cms.middleware.user.CurrentUserMiddleware', 'cms.middleware.page.CurrentPageMiddleware', 'cms.middleware.toolbar.ToolbarMiddleware', 'cms.middleware.language.LanguageCookieMiddleware' ] ROOT_URLCONF = 'urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ BASE_DIR('config/templates'), ], 'OPTIONS': { 'context_processors': [ 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.core.context_processors.i18n', 'django.core.context_processors.debug', 'django.core.context_processors.request', 'django.core.context_processors.media', 'django.core.context_processors.csrf', 'django.core.context_processors.tz', 'sekizai.context_processors.sekizai', 'django.core.context_processors.static', 'cms.context_processors.cms_settings' ], 'loaders': [ 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', 'django.template.loaders.eggs.Loader' ], }, }, ] WSGI_APPLICATION = 'config.wsgi.application' # Database # https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES = { 'default': ENV_VAR.db() } # Password validation # https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/1.8/topics/i18n/ LANGUAGE_CODE = 'en' TIME_ZONE = 'Asia/Kolkata' USE_I18N = True USE_L10N = True USE_TZ = True MEDIA_ROOT = BASE_DIR('media', default='') MEDIA_URL = '/media/' # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.8/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = BASE_DIR('static') STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'django.contrib.staticfiles.finders.FileSystemFinder', ) STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' </code></pre> <p>urls.py</p> <pre><code>from __future__ import absolute_import, print_function, unicode_literals from cms.sitemaps import CMSSitemap from django.conf import settings from django.conf.urls import include, url from django.conf.urls.i18n import i18n_patterns from django.contrib import admin admin.autodiscover() urlpatterns = [ url(r'^sitemap\.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps': {'cmspages': CMSSitemap}}), url(r'^select2/', include('django_select2.urls')), ] urlpatterns += i18n_patterns( '', url(r'^admin/', include(admin.site.urls)), url(r'^', include('cms.urls')), ) </code></pre> <p>DIR Structure</p> <pre><code>. |-- apps | |-- __init__.py |-- config | |-- __init__.py | |-- settings | | |-- base.py | | |-- configurations | | | |-- DJANGOCMS.py | | | |-- DJANGO.py | | | |-- ENV.py | | | |-- GRAPPELLI.py | | | |-- __init__.py | | |-- dev.py | | |-- __init__.py | | `-- pro.py | |-- templates | | |-- base.html | | |-- feature.html | | |-- menu.html | | |-- page.html | |-- wsgi.py |-- manage.py |-- media |-- requirements | |-- base.txt | |-- dev.txt | `-- pro.txt |-- requirements.txt |-- static |-- urls.py </code></pre> <p><a href="http://i.stack.imgur.com/9K8pz.png" rel="nofollow"><img src="http://i.stack.imgur.com/9K8pz.png" alt="enter image description here"></a></p> <p><strong>I am unable to open localhost:8000/ it always redirects me to login page. Then I have created a new project and this time kept the default project layout and now this is what I see if I open localhost:8000/</strong></p> <p><a href="http://i.stack.imgur.com/X1124.png" rel="nofollow"><img src="http://i.stack.imgur.com/X1124.png" alt="enter image description here"></a></p> <p><strong>So if someone can tell me what is wrong ?? How do I use custom templates ???</strong></p>
0
2016-08-20T12:51:35Z
39,099,777
<p>First off, if it redirects you to the login page, that'll most likely be because there isn't any content yet. Based on the question, I'm assuming this is a new installation with no pages, so you'd need to login, create your pages, and then you should get it to load without the admin redirect.</p> <p>In terms of overriding templates, it works the same as for any django or app template.</p> <p>If you want to use a custom template, you simply create your own version following the same path as the original, but in one of your own template directories.</p> <p>For example I've got a directory in my project where I override CMS templates;</p> <p><code>/project/myapp/templates/cms/toolbar/plugin.html</code></p> <p>Which you can see in the CMS app lives in that same template path;</p> <p><a href="https://github.com/divio/django-cms/tree/release/3.3.x/cms/templates/cms/toolbar" rel="nofollow">https://github.com/divio/django-cms/tree/release/3.3.x/cms/templates/cms/toolbar</a></p> <p>If you've got templates that you wish to make available as page templates for the CMS then there is a <code>CMS_TEMPLATES</code> setting which you add like so;</p> <pre><code>CMS_TEMPLATES = ( ('home.html', 'Homepage'), ('article.html', 'Article'), ('blogs/entry_form.html', 'Blogs Competition Entry Form'), ) </code></pre>
1
2016-08-23T11:21:52Z
[ "python", "django", "django-cms" ]
How to find cumulative sum of items in a list of dictionaries in python
39,054,413
<p>I have a list which is like</p> <pre><code>a=[{'time':3},{'time':4},{'time':5}] </code></pre> <p>I want to get the cumulative sum of the values in reversed order like this</p> <pre><code>b=[{'exp':3,'cumsum':12},{'exp':4,'cumsum':9},{'exp':5,'cumsum':5}] </code></pre> <p>What is the most efficient way to get this ? I have read other answer where using <code>numpy</code> gives the solution like </p> <pre><code>a=[1,2,3] b=numpy.cumsum(a) </code></pre> <p>but I need to insert the cumsum in the dictionary as well</p>
2
2016-08-20T12:56:48Z
39,054,460
<pre><code>a=[{'time':3},{'time':4},{'time':5}] b = [] cumsum = 0 for e in a[::-1]: cumsum += e['time'] b.insert(0, {'exp':e['time'], 'cumsum':cumsum}) print(b) </code></pre> <p><strong>Output:</strong></p> <pre><code>[{'exp': 3, 'cumsum': 12}, {'exp': 4, 'cumsum': 9}, {'exp': 5, 'cumsum': 5}] </code></pre> <p><hr> So it turns out that inserting at the start of a list is <a href="http://stackoverflow.com/questions/7776938/python-insert-vs-append">slow</a> (O(n)). Instead, try a <code>deque</code> (O(1)):</p> <pre><code>from collections import deque a=[{'time':3},{'time':4},{'time':5}] b = deque() cumsum = 0 for e in a[::-1]: cumsum += e['time'] b.appendleft({'exp':e['time'], 'cumsum':cumsum}) print(b) print(list(b)) </code></pre> <p><strong>Output:</strong></p> <pre><code>deque([{'cumsum': 12, 'exp': 3}, {'cumsum': 9, 'exp': 4}, {'cumsum': 5, 'exp': 5}]) [{'cumsum': 12, 'exp': 3}, {'cumsum': 9, 'exp': 4}, {'cumsum': 5, 'exp': 5}] </code></pre> <p><hr> Here is a script to test the speed of each of the approaches ITT, as well as a chart with timing results:</p> <p><a href="http://i.stack.imgur.com/ItblP.png" rel="nofollow"><img src="http://i.stack.imgur.com/ItblP.png" alt="enter image description here"></a></p> <pre><code>from collections import deque from copy import deepcopy import numpy as np import pandas as pd from random import randint from time import time def Nehal_pandas(l): df = pd.DataFrame(l) df['cumsum'] = df.ix[::-1, 'time'].cumsum()[::-1] df.columns = ['exp', 'cumsum'] return df.to_json(orient='records') def Merlin_pandas(l): df = pd.DataFrame(l).rename(columns={'time':'exp'}) df["cumsum"] = df['exp'][::-1].cumsum() return df.to_dict(orient='records') def RahulKP_numpy(l): cumsum_list = np.cumsum([i['time'] for i in l][::-1])[::-1] for i,j in zip(l,cumsum_list): i.update({'cumsum':j}) def Divakar_pandas(l): df = pd.DataFrame(l) df.columns = ['exp'] df['cumsum'] = (df[::-1].cumsum())[::-1] return df.T.to_dict().values() def cb_insert_0(l): b = [] cumsum = 0 for e in l[::-1]: cumsum += e['time'] b.insert(0, {'exp':e['time'], 'cumsum':cumsum}) return b def cb_deque(l): b = deque() cumsum = 0 for e in l[::-1]: cumsum += e['time'] b.appendleft({'exp':e['time'], 'cumsum':cumsum}) b = list(b) return b def cb_deque_noconvert(l): b = deque() cumsum = 0 for e in l[::-1]: cumsum += e['time'] b.appendleft({'exp':e['time'], 'cumsum':cumsum}) return b def hpaulj_gen(l, var='value'): cum=0 for i in l: j=i[var] cum += j yield {var:j, 'sum':cum} def hpaulj_inplace(l, var='time'): cum = 0 for i in l: cum += i[var] i['sum'] = cum def test(number_of_lists, min_list_length, max_list_length): test_lists = [] for _ in range(number_of_lists): test_list = [] number_of_dicts = randint(min_list_length,max_list_length) for __ in range(number_of_dicts): random_value = randint(0,50) test_list.append({'time':random_value}) test_lists.append(test_list) lists = deepcopy(test_lists) start_time = time() for l in lists: res = list(hpaulj_gen(l[::-1], 'time'))[::-1] elapsed_time = time() - start_time print('hpaulj generator:'.ljust(25), '%.2f' % (number_of_lists / elapsed_time), 'lists per second') lists = deepcopy(test_lists) start_time = time() for l in lists: hpaulj_inplace(l[::-1]) elapsed_time = time() - start_time print('hpaulj in place:'.ljust(25), '%.2f' % (number_of_lists / elapsed_time), 'lists per second') lists = deepcopy(test_lists) start_time = time() for l in lists: res = cb_insert_0(l) elapsed_time = time() - start_time print('craig insert list at 0:'.ljust(25), '%.2f' % (number_of_lists / elapsed_time), 'lists per second') lists = deepcopy(test_lists) start_time = time() for l in lists: res = cb_deque(l) elapsed_time = time() - start_time print('craig deque:'.ljust(25), '%.2f' % (number_of_lists / elapsed_time), 'lists per second') lists = deepcopy(test_lists) start_time = time() for l in lists: res = cb_deque_noconvert(l) elapsed_time = time() - start_time print('craig deque no convert:'.ljust(25), '%.2f' % (number_of_lists / elapsed_time), 'lists per second') lists = deepcopy(test_lists) start_time = time() for l in lists: RahulKP_numpy(l) # l changed in place elapsed_time = time() - start_time print('Rahul K P numpy:'.ljust(25), '%.2f' % (number_of_lists / elapsed_time), 'lists per second') lists = deepcopy(test_lists) start_time = time() for l in lists: res = Divakar_pandas(l) elapsed_time = time() - start_time print('Divakar pandas:'.ljust(25), '%.2f' % (number_of_lists / elapsed_time), 'lists per second') lists = deepcopy(test_lists) start_time = time() for l in lists: res = Nehal_pandas(l) elapsed_time = time() - start_time print('Nehal pandas:'.ljust(25), '%.2f' % (number_of_lists / elapsed_time), 'lists per second') lists = deepcopy(test_lists) start_time = time() for l in lists: res = Merlin_pandas(l) elapsed_time = time() - start_time print('Merlin pandas:'.ljust(25), '%.2f' % (number_of_lists / elapsed_time), 'lists per second') </code></pre>
6
2016-08-20T13:04:33Z
[ "python", "pandas", "numpy", "dictionary", "deque" ]
How to find cumulative sum of items in a list of dictionaries in python
39,054,413
<p>I have a list which is like</p> <pre><code>a=[{'time':3},{'time':4},{'time':5}] </code></pre> <p>I want to get the cumulative sum of the values in reversed order like this</p> <pre><code>b=[{'exp':3,'cumsum':12},{'exp':4,'cumsum':9},{'exp':5,'cumsum':5}] </code></pre> <p>What is the most efficient way to get this ? I have read other answer where using <code>numpy</code> gives the solution like </p> <pre><code>a=[1,2,3] b=numpy.cumsum(a) </code></pre> <p>but I need to insert the cumsum in the dictionary as well</p>
2
2016-08-20T12:56:48Z
39,054,556
<p>Try this,</p> <pre><code>cumsum_list = np.cumsum([i['time'] for i in a][::-1])[::-1] for i,j in zip(a,cumsum_list): i.update({'cumsum':j}) </code></pre> <p><strong>Result</strong></p> <pre><code>[{'cumsum': 12, 'time': 3}, {'cumsum': 9, 'time': 4}, {'cumsum': 5, 'time': 5}] </code></pre> <p><strong>Efficiency</strong></p> <p>Change into a function,</p> <pre><code>In [49]: def convert_dict(a): ....: cumsum_list = np.cumsum([i['time'] for i in a][::-1])[::-1] ....: for i,j in zip(a,cumsum_list): ....: i.update({'cumsum':j}) ....: return a </code></pre> <p>And then the result,</p> <pre><code>In [51]: convert_dict(a) Out[51]: [{'cumsum': 12, 'time': 3}, {'cumsum': 9, 'time': 4}, {'cumsum': 5, 'time': 5}] </code></pre> <p>Finally efficiency,</p> <pre><code>In [52]: %timeit convert_dict(a) The slowest run took 12.84 times longer than the fastest. This could mean that an intermediate result is being cached. 100000 loops, best of 3: 12.1 µs per loop </code></pre>
1
2016-08-20T13:15:27Z
[ "python", "pandas", "numpy", "dictionary", "deque" ]
How to find cumulative sum of items in a list of dictionaries in python
39,054,413
<p>I have a list which is like</p> <pre><code>a=[{'time':3},{'time':4},{'time':5}] </code></pre> <p>I want to get the cumulative sum of the values in reversed order like this</p> <pre><code>b=[{'exp':3,'cumsum':12},{'exp':4,'cumsum':9},{'exp':5,'cumsum':5}] </code></pre> <p>What is the most efficient way to get this ? I have read other answer where using <code>numpy</code> gives the solution like </p> <pre><code>a=[1,2,3] b=numpy.cumsum(a) </code></pre> <p>but I need to insert the cumsum in the dictionary as well</p>
2
2016-08-20T12:56:48Z
39,054,557
<p>Using <code>pandas</code>:</p> <pre><code>In [4]: df = pd.DataFrame([{'time':3},{'time':4},{'time':5}]) In [5]: df Out[5]: time 0 3 1 4 2 5 In [6]: df['cumsum'] = df.ix[::-1, 'time'].cumsum()[::-1] In [7]: df Out[7]: time cumsum 0 3 12 1 4 9 2 5 5 In [8]: df.columns = ['exp', 'cumsum'] In [9]: df Out[9]: exp cumsum 0 3 12 1 4 9 2 5 5 In [10]: df.to_json(orient='records') Out[10]: '[{"exp":3,"cumsum":12},{"exp":4,"cumsum":9},{"exp":5,"cumsum":5}]' </code></pre>
0
2016-08-20T13:15:40Z
[ "python", "pandas", "numpy", "dictionary", "deque" ]
How to find cumulative sum of items in a list of dictionaries in python
39,054,413
<p>I have a list which is like</p> <pre><code>a=[{'time':3},{'time':4},{'time':5}] </code></pre> <p>I want to get the cumulative sum of the values in reversed order like this</p> <pre><code>b=[{'exp':3,'cumsum':12},{'exp':4,'cumsum':9},{'exp':5,'cumsum':5}] </code></pre> <p>What is the most efficient way to get this ? I have read other answer where using <code>numpy</code> gives the solution like </p> <pre><code>a=[1,2,3] b=numpy.cumsum(a) </code></pre> <p>but I need to insert the cumsum in the dictionary as well</p>
2
2016-08-20T12:56:48Z
39,054,593
<p>Here's another approach using <code>pandas</code> -</p> <pre><code>df = pd.DataFrame(a) df.columns = ['exp'] df['cumsum'] = (df[::-1].cumsum())[::-1] out = df.T.to_dict().values() </code></pre> <p>Sample input, output -</p> <pre><code>In [396]: a Out[396]: [{'time': 3}, {'time': 4}, {'time': 5}] In [397]: out Out[397]: [{'cumsum': 12, 'exp': 3}, {'cumsum': 9, 'exp': 4}, {'cumsum': 5, 'exp': 5} </code></pre>
0
2016-08-20T13:18:59Z
[ "python", "pandas", "numpy", "dictionary", "deque" ]
How to find cumulative sum of items in a list of dictionaries in python
39,054,413
<p>I have a list which is like</p> <pre><code>a=[{'time':3},{'time':4},{'time':5}] </code></pre> <p>I want to get the cumulative sum of the values in reversed order like this</p> <pre><code>b=[{'exp':3,'cumsum':12},{'exp':4,'cumsum':9},{'exp':5,'cumsum':5}] </code></pre> <p>What is the most efficient way to get this ? I have read other answer where using <code>numpy</code> gives the solution like </p> <pre><code>a=[1,2,3] b=numpy.cumsum(a) </code></pre> <p>but I need to insert the cumsum in the dictionary as well</p>
2
2016-08-20T12:56:48Z
39,054,943
<p>Try this:</p> <pre><code>a = [{'time':3},{'time':4},{'time':5}] df = pd.DataFrame(a).rename(columns={'time':'exp'}) df["cumsum"] = df['exp'][::-1].cumsum() df.to_dict(orient='records') </code></pre> <p>Dicts are not ordered.</p> <pre><code> [{'cumsum': 12, 'exp': 3}, {'cumsum': 9, 'exp': 4}, {'cumsum': 5, 'exp': 5}] </code></pre>
1
2016-08-20T13:58:21Z
[ "python", "pandas", "numpy", "dictionary", "deque" ]
How to find cumulative sum of items in a list of dictionaries in python
39,054,413
<p>I have a list which is like</p> <pre><code>a=[{'time':3},{'time':4},{'time':5}] </code></pre> <p>I want to get the cumulative sum of the values in reversed order like this</p> <pre><code>b=[{'exp':3,'cumsum':12},{'exp':4,'cumsum':9},{'exp':5,'cumsum':5}] </code></pre> <p>What is the most efficient way to get this ? I have read other answer where using <code>numpy</code> gives the solution like </p> <pre><code>a=[1,2,3] b=numpy.cumsum(a) </code></pre> <p>but I need to insert the cumsum in the dictionary as well</p>
2
2016-08-20T12:56:48Z
39,056,177
<p>A generator based solution:</p> <pre><code>def foo(a, var='value'): cum=0 for i in a: j=i[var] cum += j yield {var:j, 'sum':cum} In [79]: a=[{'time':i} for i in range(5)] In [80]: list(foo(a[::-1], var='time'))[::-1] Out[80]: [{'sum': 10, 'time': 0}, {'sum': 10, 'time': 1}, {'sum': 9, 'time': 2}, {'sum': 7, 'time': 3}, {'sum': 4, 'time': 4}] </code></pre> <p>In quick time tests this is competitive with <code>cb_insert_0</code></p> <p>The in-place version does even better:</p> <pre><code>def foo2(a, var='time'): cum = 0 for i in a: cum += i[var] i['sum'] = cum foo2(a[::-1]) </code></pre>
2
2016-08-20T16:05:33Z
[ "python", "pandas", "numpy", "dictionary", "deque" ]
Tensorflow: Using tf.slice to split the input
39,054,414
<p>I'm trying to split my input layer into different sized parts. I'm trying to use tf.slice to do that but it's not working.</p> <p>Some sample code:</p> <pre><code>import tensorflow as tf import numpy as np ph = tf.placeholder(shape=[None,3], dtype=tf.int32) x = tf.slice(ph, [0, 0], [3, 2]) input_ = np.array([[1,2,3], [3,4,5], [5,6,7]]) with tf.Session() as sess: sess.run(tf.initialize_all_variables()) print sess.run(x, feed_dict={ph: input_}) </code></pre> <p>Output:</p> <pre><code>[[1 2] [3 4] [5 6]] </code></pre> <p>This works and is roughly what I want to happen, but I have to specify the first dimension (<code>3</code> in this case). I can't know though how many vectors I'll be inputting, that's why I'm using a <code>placeholder</code> with <code>None</code> in the first place!</p> <p>Is it possible to use <code>slice</code> in such a way that it will work when a dimension is unknown until runtime?</p> <p>I've tried using a <code>placeholder</code> that takes its value from <code>ph.get_shape()[0]</code> like so: <code>x = tf.slice(ph, [0, 0], [num_input, 2])</code>. but that didn't work either.</p>
0
2016-08-20T12:57:00Z
39,054,738
<p>You can specify one negative dimension in the <code>size</code> parameter of <code>tf.slice</code>. The negative dimension tells Tensorflow to dynamically determine the right value basing its decision on the other dimensions.</p> <pre><code>import tensorflow as tf import numpy as np ph = tf.placeholder(shape=[None,3], dtype=tf.int32) # look the -1 in the first position x = tf.slice(ph, [0, 0], [-1, 2]) input_ = np.array([[1,2,3], [3,4,5], [5,6,7]]) with tf.Session() as sess: sess.run(tf.initialize_all_variables()) print(sess.run(x, feed_dict={ph: input_}) </code></pre>
1
2016-08-20T13:35:05Z
[ "python", "tensorflow" ]
How to split output from a list of urls in scrapy
39,054,475
<p>I am trying to generate a csv file for each scraped url from a list of urls in scrapy. I do understand I shall modify pipeline.py, however all my attempts have failed so far. I do not understand how I can pass the url being scraped to the pipeline and use this as name for the output and split the output accordingly.</p> <p>Any help?</p> <p>Thanks</p> <p>Here the spider and the pipeline</p> <pre><code>from scrapy import Spider from scrapy.selector import Selector from vApp.items import fItem class VappSpider(Spider): name = "vApp" allowed_domains = ["google.co.uk"] start_urls = [l.strip() for l in open('data/listOfUrls.txt').readlines()] def parse(self, response): trs = Selector(response).xpath('//[@id="incdiv"]/table/tbody/tr') for tr in trs: item = fItem() try: item['item'] = tr.xpath('td/text()').extract()[0] except IndexError: item['item'] = 'null' yield item </code></pre> <p>Pipeline:</p> <pre><code>from scrapy import signals from scrapy.contrib.exporter import CsvItemExporter class VappPipeline(object): def __init__(self): self.files = {} @classmethod def from_crawler(cls, crawler): pipeline = cls() crawler.signals.connect(pipeline.spider_opened, signals.spider_opened) crawler.signals.connect(pipeline.spider_closed, signals.spider_closed) return pipeline def spider_opened(self, spider): file = open('results/%s.csv' % spider.name, 'w+b') self.files[spider] = file self.exporter = CsvItemExporter(file) self.exporter.fields_to_export = ['item'] self.exporter.start_exporting() def spider_closed(self, spider): self.exporter.finish_exporting() file = self.files.pop(spider) file.close() def process_item(self, item, spider): self.exporter.export_item(item) return item </code></pre>
1
2016-08-20T13:06:20Z
39,064,519
<p>I think you should be doing all those things in batch as a post-processing step when your crawl finishes instead of per-item but here's a draft on how you could do what you want:</p> <pre><code>from scrapy import Spider from scrapy.selector import Selector from vApp.items import fItem class VappSpider(Spider): name = "vApp" allowed_domains = ["google.co.uk"] start_urls = [l.strip() for l in open('data/listOfUrls.txt').readlines()] def parse(self, response): trs = Selector(response).xpath('//[@id="incdiv"]/table/tbody/tr') for tr in trs: item = fItem() try: item['item'] = tr.xpath('td/text()').extract()[0] except IndexError: item['item'] = 'null' item['url'] = response.url yield item from scrapy import signals from scrapy.contrib.exporter import CsvItemExporter from urlparse import urlparse class VappPipeline(object): def __init__(self): self.files = {} self.exporter = {} @classmethod def from_crawler(cls, crawler): pipeline = cls() crawler.signals.connect(pipeline.spider_closed, signals.spider_closed) return pipeline def process_item(self, item, spider): url = item['url'] parsed_uri = urlparse(url) domain = parsed_uri.netloc if domain not in self.exporter: file = open('results/%s.csv' % domain, 'w+b') self.files[domain] = file self.exporter[domain] = CsvItemExporter(file) self.exporter[domain].fields_to_export = ['item'] self.exporter[domain].start_exporting() assert domain in self.exporter self.exporter[domain].export_item(item) return item def spider_closed(self, spider): for domain, exporter in self.exporter.iteritems(): exporter.finish_exporting() self.files[domain].close() </code></pre>
0
2016-08-21T13:06:08Z
[ "python", "scrapy" ]
Pyspark reduceByKey on nested tuples
39,054,489
<p>My question is similar to <a href="http://stackoverflow.com/questions/30831530/pyspark-reducebykey-on-multiple-values">PySpark reduceByKey on multiple values</a> but with a somehow critical difference. I am new to PySpark, so I am for sure missing something obvious.</p> <p>I have an RDD with the following structure:</p> <pre><code>(K0, ((k01,v01), (k02,v02), ...)) .... (Kn, ((kn1,vn1), (kn2,vn2), ...)) </code></pre> <p>What I want as an output is something like</p> <pre><code>(K0, v01+v02+...) ... (Kn, vn1+vn2+...) </code></pre> <p>This seems like the perfect case to use <code>reduceByKey</code> and at first I thought of something like</p> <pre><code>rdd.reduceByKey(lambda x,y: x[1]+y[1]) </code></pre> <p>Which gives me exactly the RDD I began with. I suppose there is something wrong with my indexing, as there are nested tuples, but I have tried every possible index combination I could think of and it keeps on giving me back the initial RDD.</p> <p>Is there maybe a reason why it shouldn't work with nested tuples or am I doing something wrong?</p> <p>Thank you</p>
0
2016-08-20T13:07:15Z
39,056,158
<p>You shouldn't use <code>reduceByKey</code> here at all. It takes an associative and commutative function with signature. <code>(T, T) =&gt; T</code>. It should be obvious that it is not applicable when you have <code>List[Tuple[U, T]]</code> as an input and you expect <code>T</code> as an output.</p> <p>Since it is not exactly clear if keys or unique or not lets consider general example when we have to aggregate both locally and globally. Lets assume that <code>v01</code>, <code>v02</code>, ... <code>vm</code> are simple numerics:</p> <pre><code>from functools import reduce from operator import add def agg_(xs): # For numeric values sum would be more idiomatic # but lets make it more generic return reduce(add, (x[1] for x in xs), zero_value) zero_value = 0 merge_op = add def seq_op(acc, xs): return acc + agg_(xs) rdd = sc.parallelize([ ("K0", (("k01", 3), ("k02", 2))), ("K0", (("k03", 5), ("k04", 6))), ("K1", (("k11", 0), ("k12", -1)))]) rdd.aggregateByKey(0, seq_op, merge_op).take(2) ## [('K0', 16), ('K1', -1)] </code></pre> <p>If keys are already unique simple <code>mapValues</code> will suffice:</p> <pre><code>from itertools import chain unique_keys = rdd.groupByKey().mapValues(lambda x: tuple(chain(*x))) unique_keys.mapValues(agg_).take(2) ## [('K0', 16), ('K1', -1)] </code></pre>
0
2016-08-20T16:03:52Z
[ "python", "apache-spark", "pyspark" ]
How to create a list containing names of functions?
39,054,533
<p>I am completely new to python and programming but I am trying to learn it using more practical approach.</p> <p>What I am trying to do is an exercise for converting different units, e.g. pounds -> kilograms, foot -> meter etc.</p> <p>I have defined all the functions for different unit pairs:</p> <pre><code>def kg_to_g(value): return round(value*1000.0,2) def g_to_kg(value): return round(value/1000.0,2) def inch_to_cm(value): return round(value*2.54,2) def cm_to_inch(value): return round(value/2.54,2) def ft_to_cm(value): return round(value*30.48,2) </code></pre> <p>etc.</p> <p>and created a list with names of these functions: </p> <pre><code>unit_list = ['kg_to_g','g_to_kg','inch_to_cm','cm_to_inch', 'ft_to_cm','cm_to_ft','yard_to_m','m_to_yard', 'mile_to_km','km_to_mile','oz_to_g','g_to_oz', 'pound_to_kg','kg_to_pound','stone_to_kg','kg_to_stone', 'pint_to_l','l_to_pint','quart_to_l','l_to_quart', 'gal_to_l','l_to_gal','bar_to_l','l_to_bar'] </code></pre> <p>The program should randomly choose a unit pair(e.g. kg->pounds) and value (e.g. 134.23), and the user will be asked to convert those values.</p> <pre><code>random_unit = random.choice(unit_list) lower = 0.1001 upper = 2000.1001 range_width = upper - lower ranval = round(random.random() * range_width + lower, 2) </code></pre> <p>When user enters answer, the program should compare answer with the calculations defined by function and tell user if it is a correct answer or wrong answer:</p> <pre><code>def input_handler(answer): if answer == random_unit(ranval): label2.set_text("Correct!") else: label2.set_text("Wrong!") </code></pre> <p>Unfortunately, that way program doesn't work, and codesculptor(codesculptor.org) returns with an error </p> <pre><code>TypeError: 'str' object is not callable </code></pre> <p>Could someone please explain to me what is wrong with the code and suggest something to solve the problem.</p>
0
2016-08-20T13:12:03Z
39,054,797
<p>Because you've enclosed the function names (in the list) in quotes, they have become strings.</p> <p>Change your list to:</p> <pre><code>unit_list = [kg_to_g, g_to_kg, inch_to_cm, cm_to_inch, ft_to_cm, cm_to_ft, yard_to_m, m_to_yard, mile_to_km, km_to_mile, oz_to_g, g_to_oz, pound_to_kg, kg_to_pound, stone_to_kg, kg_to_stone, pint_to_l, l_to_pint, quart_to_l, l_to_quart, gal_to_l, l_to_gal, bar_to_l, l_to_bar] </code></pre> <p>And now it is a list of functions, which can be called like this: <code>unit_list[0](34)</code>, for example.</p> <p>So now <code>random_unit(ranval)</code> should not throw an exception.</p> <p>Note also that comparing floats (<code>if answer == random_unit(ranval)</code>) will most likely cause you problems. See <a href="http://stackoverflow.com/questions/588004/is-floating-point-math-brokenfor">Is floating point math broken?</a> for some detailed explanations of why this is.</p> <p>As you are rounding you may get away with it, but it's good to be aware of this and understand that you need to deal with it in your code.</p>
0
2016-08-20T13:42:05Z
[ "python", "list", "function" ]
How to create a list containing names of functions?
39,054,533
<p>I am completely new to python and programming but I am trying to learn it using more practical approach.</p> <p>What I am trying to do is an exercise for converting different units, e.g. pounds -> kilograms, foot -> meter etc.</p> <p>I have defined all the functions for different unit pairs:</p> <pre><code>def kg_to_g(value): return round(value*1000.0,2) def g_to_kg(value): return round(value/1000.0,2) def inch_to_cm(value): return round(value*2.54,2) def cm_to_inch(value): return round(value/2.54,2) def ft_to_cm(value): return round(value*30.48,2) </code></pre> <p>etc.</p> <p>and created a list with names of these functions: </p> <pre><code>unit_list = ['kg_to_g','g_to_kg','inch_to_cm','cm_to_inch', 'ft_to_cm','cm_to_ft','yard_to_m','m_to_yard', 'mile_to_km','km_to_mile','oz_to_g','g_to_oz', 'pound_to_kg','kg_to_pound','stone_to_kg','kg_to_stone', 'pint_to_l','l_to_pint','quart_to_l','l_to_quart', 'gal_to_l','l_to_gal','bar_to_l','l_to_bar'] </code></pre> <p>The program should randomly choose a unit pair(e.g. kg->pounds) and value (e.g. 134.23), and the user will be asked to convert those values.</p> <pre><code>random_unit = random.choice(unit_list) lower = 0.1001 upper = 2000.1001 range_width = upper - lower ranval = round(random.random() * range_width + lower, 2) </code></pre> <p>When user enters answer, the program should compare answer with the calculations defined by function and tell user if it is a correct answer or wrong answer:</p> <pre><code>def input_handler(answer): if answer == random_unit(ranval): label2.set_text("Correct!") else: label2.set_text("Wrong!") </code></pre> <p>Unfortunately, that way program doesn't work, and codesculptor(codesculptor.org) returns with an error </p> <pre><code>TypeError: 'str' object is not callable </code></pre> <p>Could someone please explain to me what is wrong with the code and suggest something to solve the problem.</p>
0
2016-08-20T13:12:03Z
39,054,850
<p>I think this is what you are asking about. You should be able to store the functions in a list like this</p> <pre><code>unit_list = [kg_to_g, g_to_kg, inch_to_cm, cm_to_inch, ft_to_cm] </code></pre> <p>You can then call each item in the list and give it a parameter and it should execute the function for example like this:</p> <pre><code>unit_list[0](value) </code></pre>
-1
2016-08-20T13:48:31Z
[ "python", "list", "function" ]
Performance between C-contiguous and Fortran-contiguous array operations
39,054,539
<p>Below, I compared performance when dealing with sum operations between C-contiguous and Fortran-contiguous arrays (<a href="http://www.visitusers.org/index.php?title=C_vs_Fortran_memory_order" rel="nofollow">C vs FORTRAN memory order</a>). I set <code>axis=0</code> to ensure numbers are added up column wise. I was surprised that Fortran-contiguous array is actually slower than its C counterpart. Isn't that Fortran-contiguous array has contiguous memory allocation in columns and hence is better at column-wise operation?</p> <pre><code>import numpy as np a = np.random.standard_normal((10000, 10000)) c = np.array(a, order='C') f = np.array(a, order='F') </code></pre> <p>In Jupyter notebook, run</p> <pre><code>%timeit c.sum(axis=0) 10 loops, best of 3: 84.6 ms per loop </code></pre> <pre><code>%timeit f.sum(axis=0) 10 loops, best of 3: 137 ms per loop </code></pre>
10
2016-08-20T13:12:51Z
39,055,449
<p>That's expected. If you check the result of </p> <pre><code>%timeit f.sum(axis=1) </code></pre> <p>it also gives similar result with the timing of <code>c</code>. Similarly, </p> <pre><code>%timeit c.sum(axis=1) </code></pre> <p>is slower. </p> <hr> <p>Some explanation: suppose you have the following structure</p> <pre><code>|1| |6| |2| |7| |3| |8| |4| |9| |5| |10| </code></pre> <p>As Eric mentioned, these operations work with <code>reduce</code>. Let's say we are asking for column sum. So intuitive mechanism is not at play such that each column is accessed once, summed, and recorded. In fact it is the opposite such that each row is accessed and the function (here summing) is performed in essence similar to having two arrays <code>a,b</code> and executing</p> <pre><code>a += b </code></pre> <p>That's a very informal way of repeating what is mentioned super-cryptically in the <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.ufunc.reduce.html" rel="nofollow">documentation of reduce</a>. This requires rows to be accessed contiguously although we are performing a column sum [1,6] + [2,7] + [3,8]... Hence, the implementation direction matters depending on the operation but not the array. </p>
1
2016-08-20T14:53:43Z
[ "python", "numpy", "multidimensional-array", "scipy" ]
Performance between C-contiguous and Fortran-contiguous array operations
39,054,539
<p>Below, I compared performance when dealing with sum operations between C-contiguous and Fortran-contiguous arrays (<a href="http://www.visitusers.org/index.php?title=C_vs_Fortran_memory_order" rel="nofollow">C vs FORTRAN memory order</a>). I set <code>axis=0</code> to ensure numbers are added up column wise. I was surprised that Fortran-contiguous array is actually slower than its C counterpart. Isn't that Fortran-contiguous array has contiguous memory allocation in columns and hence is better at column-wise operation?</p> <pre><code>import numpy as np a = np.random.standard_normal((10000, 10000)) c = np.array(a, order='C') f = np.array(a, order='F') </code></pre> <p>In Jupyter notebook, run</p> <pre><code>%timeit c.sum(axis=0) 10 loops, best of 3: 84.6 ms per loop </code></pre> <pre><code>%timeit f.sum(axis=0) 10 loops, best of 3: 137 ms per loop </code></pre>
10
2016-08-20T13:12:51Z
39,058,941
<p>I think it's in the implementation of the np.sum(). For example:</p> <pre><code>import numpy as np A = np.random.standard_normal((10000,10000)) C = np.array(A, order='C') F = np.array(A, order='F') </code></pre> <p>Benchmarking with Ipython:</p> <pre><code>In [7]: %timeit C.sum(axis=0) 10 loops, best of 3: 101 ms per loop In [8]: %timeit C.sum(axis=1) 10 loops, best of 3: 149 ms per loop In [9]: %timeit F.sum(axis=0) 10 loops, best of 3: 149 ms per loop In [10]: %timeit F.sum(axis=1) 10 loops, best of 3: 102 ms per loop </code></pre> <p>So it's behaving exactly the opposite as expected. But let's try out some other function:</p> <pre><code>In [17]: %timeit np.amax(C, axis=0) 1 loop, best of 3: 173 ms per loop In [18]: %timeit np.amax(C, axis=1) 10 loops, best of 3: 70.4 ms per loop In [13]: %timeit np.amax(F,axis=0) 10 loops, best of 3: 72 ms per loop In [14]: %timeit np.amax(F,axis=1) 10 loops, best of 3: 168 ms per loop </code></pre> <p>Sure, it's apples to oranges. But np.amax() works along the axis as does sum and returns a vector with one element for each row/column. And behaves as one would expect.</p> <pre><code>In [25]: C.strides Out[25]: (80000, 8) In [26]: F.strides Out[26]: (8, 80000) </code></pre> <p>Tells us that the arrays are in fact packed in row-order and column-order and looping in that direction should be a lot faster. Unless for example the sum sums each row by row as it travels along the columns for providing the column sum (axis=0). But without a mean of peeking inside the .pyd I'm just speculating.</p> <p>EDIT:</p> <p>From percusse 's link: <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.ufunc.reduce.html" rel="nofollow">http://docs.scipy.org/doc/numpy/reference/generated/numpy.ufunc.reduce.html</a></p> <blockquote> <p>Reduces a‘s dimension by one, by applying ufunc along one axis.</p> <p>Let a.shape = (N_0, ..., N_i, ..., N_{M-1}). Then ufunc.reduce(a, axis=i)[k_0, ..,k_{i-1}, k_{i+1}, .., k_{M-1}] = the result of iterating j over range(N_i), cumulatively applying ufunc to each a[k_0, ..,k_{i-1}, j, k_{i+1}, .., k_{M-1}]</p> </blockquote> <p>So in pseudocode, when calling F.sum(axis=0):</p> <pre><code>for j=cols #axis=0 for i=rows #axis=1 sum(j,i)=F(j,i)+sum(j-1,i) </code></pre> <p>So it would actually iterate over the row when calculating the column sum, slowing down considerably when in column-major order. Behaviour such as this would explain the difference.</p> <p>eric's link provides us with the implementation, for somebody curious enough to go through large amounts of code for the reason. </p>
2
2016-08-20T21:40:51Z
[ "python", "numpy", "multidimensional-array", "scipy" ]
Python BeautifulSoup extracting text from result
39,054,666
<p>I am trying to get the text from contents but when i try beautiful soup functions on the result variable it results in errors.</p> <pre><code>from bs4 import BeautifulSoup as bs import requests webpage = 'http://www.dictionary.com/browse/coypu' r = requests.get(webpage) page_text = r.text soup = bs(page_text, 'html.parser') result = soup.find_all('meta', attrs={'name':'description'}) print (result.get['contents']) </code></pre> <p>I am trying to get the result to read;</p> <p>"Coypu definition, a large, South American, aquatic rodent, Myocastor (or Myopotamus) coypus, yielding the fur nutria. See more."</p>
1
2016-08-20T13:26:34Z
39,054,750
<p><code>soup.find_all()</code> returns a list. Since in your case, it returns only one element in the list, you can do:</p> <pre><code>&gt;&gt;&gt; type(result) &lt;class 'bs4.element.ResultSet'&gt; &gt;&gt;&gt; type(result[0]) &lt;class 'bs4.element.ResultSet'&gt; &gt;&gt;&gt; result[0].get('content') Coypu definition, a large, South American, aquatic rodent, Myocastor (or Myopotamus) coypus, yielding the fur nutria. See more. </code></pre>
1
2016-08-20T13:36:14Z
[ "python", "regex", "beautifulsoup" ]
Python BeautifulSoup extracting text from result
39,054,666
<p>I am trying to get the text from contents but when i try beautiful soup functions on the result variable it results in errors.</p> <pre><code>from bs4 import BeautifulSoup as bs import requests webpage = 'http://www.dictionary.com/browse/coypu' r = requests.get(webpage) page_text = r.text soup = bs(page_text, 'html.parser') result = soup.find_all('meta', attrs={'name':'description'}) print (result.get['contents']) </code></pre> <p>I am trying to get the result to read;</p> <p>"Coypu definition, a large, South American, aquatic rodent, Myocastor (or Myopotamus) coypus, yielding the fur nutria. See more."</p>
1
2016-08-20T13:26:34Z
39,054,965
<p>When you only want the first or a single tag use <em>find</em>, find_all returns a <em>list/resultSet</em>:</p> <pre><code>result = soup.find('meta', attrs={'name':'description'})["contents"] </code></pre> <p>You can also use a <em>css selector</em> with <em>select_one</em>:</p> <pre><code>result = soup.select_one('meta[name=description]')["contents"] </code></pre>
1
2016-08-20T14:00:19Z
[ "python", "regex", "beautifulsoup" ]
Python BeautifulSoup extracting text from result
39,054,666
<p>I am trying to get the text from contents but when i try beautiful soup functions on the result variable it results in errors.</p> <pre><code>from bs4 import BeautifulSoup as bs import requests webpage = 'http://www.dictionary.com/browse/coypu' r = requests.get(webpage) page_text = r.text soup = bs(page_text, 'html.parser') result = soup.find_all('meta', attrs={'name':'description'}) print (result.get['contents']) </code></pre> <p>I am trying to get the result to read;</p> <p>"Coypu definition, a large, South American, aquatic rodent, Myocastor (or Myopotamus) coypus, yielding the fur nutria. See more."</p>
1
2016-08-20T13:26:34Z
39,064,389
<p>you need not to use findall as only by using find you can get desired output'</p> <pre><code>from bs4 import BeautifulSoup as bs import requests webpage = 'http://www.dictionary.com/browse/coypu' r = requests.get(webpage) page_text = r.text soup = bs(page_text, 'html.parser') result = soup.find('meta', {'name':'description'}) print result.get('content') </code></pre> <p>it will print:</p> <pre><code>Coypu definition, a large, South American, aquatic rodent, Myocastor (or Myopotamus) coypus, yielding the fur nutria. See more. </code></pre>
0
2016-08-21T12:50:39Z
[ "python", "regex", "beautifulsoup" ]
pyqt dialog not showing a second time
39,054,690
<p>I have a pyqt app where I want a dialog to display when I click a menu item. If the dialog loses focus and the menu item is clicked again, it brings the dialog to the front. This is working fine so far.</p> <p>The problem is that when the dialog is opened and then closed, clicking the menu item doesnt create/display a new dialog. I think I know why, but can't figure out a solution</p> <p>Heres the code:</p> <pre><code>from ui import mainWindow, aboutDialog class ReadingList(QtGui.QMainWindow, mainWindow.Ui_MainWindow): def __init__(self): super(self.__class__, self).__init__() self.setupUi(self) self.about = None self.actionAbout.triggered.connect(self.showAbout) def showAbout(self): # If the about dialog does not exist, create one if self.about is None: self.about = AboutDialog(self) self.about.show() # If about dialog exists, bring it to the front else: self.about.activateWindow() self.about.raise_() class AboutDialog(QtGui.QDialog, aboutDialog.Ui_Dialog): def __init__(self, parent=None): super(self.__class__, self).__init__() self.setupUi(self) def main(): app = QtGui.QApplication(sys.argv) readingList = ReadingList() readingList.show() sys.exit(app.exec_()) if __name__ == '__main__': main() </code></pre> <p>The problem lies in the fact that when the dialog is created the first time, <code>self.about</code> is no longer <code>None</code>. This is good because the conditional in <code>showAbout()</code> allows me to bring the dialog to the front instead of creating a new one (the else condition)</p> <p>However, when the dialog is closed, <code>self.about</code> is no longer <code>None</code> due to the previous dialog creation, which means it doesn't create a new one and just jumps to the else condition</p> <p>How can I make it so that dialogs can be created after the first?</p> <p>I thought about overriding the <code>closeEvent</code> method in the <code>AboutDialog</code> class but I'm not sure how to get a reference to <code>readingList</code> to send a message back saying the dialog has been closed. Or maybe I'm overthinking it, maybe the return from <code>self.about.show()</code> can be used somehow?</p> <p>(I know I can probably avoid all of this using modal dialogs but want to try to figure this out)</p>
1
2016-08-20T13:29:26Z
39,056,473
<p>There are probably several ways to do this, but here's one possibility:</p> <pre><code>class ReadingList(QtGui.QMainWindow, mainWindow.Ui_MainWindow): def __init__(self): super(ReadingList, self).__init__() self.setupUi(self) self.actionAbout.triggered.connect(self.showAbout) self.about = None def showAbout(self): if self.about is None: self.about = AboutDialog(self) self.about.show() self.about.finished.connect( lambda: setattr(self, 'about', None)) else: self.about.activateWindow() self.about.raise_() class AboutDialog(QtGui.QDialog): def __init__(self, parent=None): super(AboutDialog, self).__init__(parent) self.setAttribute(QtCore.Qt.WA_DeleteOnClose) </code></pre> <p>(NB: you should never use <code>self.__class__</code> with <code>super</code> as it can lead to an infinite recursion under certain circumstances. Always pass in the subclass as the first argument - unless you're using Python 3, in which case you can omit all the arguments).</p>
0
2016-08-20T16:41:00Z
[ "python", "qt", "pyqt", "pyqt4" ]
Getting key of unique values in a nested dict within lists
39,054,836
<p>I have a dict, which contains of elements with the following structure</p> <pre><code>{'task0': {'id': 0, 'successor':[&lt;other elements&gt;]} </code></pre> <p>Every element contains a unique id and a successor list of the mentioned elements. The can be also empty, which means, this element has no successors. </p> <p><strong>Example</strong> </p> <pre><code>a = {'task0': {'node_id': 0, 'successor': [{'task1': {'node_id': 1, 'successor': [{'task2': {'node_id': 2, 'successor': [{'task4': {'node_id': 4, 'successor': []}}, {'task5': {'node_id': 5, 'successor': []}}]}}, {'task3': {'node_id': 3, 'successor': []}}]}}]}} </code></pre> <p><strong>What I want</strong></p> <pre><code>def get_node_name_by_id(obj, id_search) </code></pre> <p>Example: def get_node_name_by_id(a, 3) == 'task3'</p> <pre><code>def get_parent_id_by_child_id(obj, id_search) </code></pre> <p>Example: def get_parent_id_by_child_id(a, 3) == 1 </p> <p><strong>What I have so far</strong></p> <pre><code>def get_node_name_by_id(obj, id_search): for k,v in obj.iteritems(): if isinstance(v,dict): if v['node_id'] is id_search: return k elif v['successor']: for e in v['successor']: return get_node_name_by_id(e, id_search) </code></pre> <p>-> Problem: If the id, which I am searching for, is not on place 1 of the list, I get <code>None</code> as a result. </p> <p>-> For the second function, I have no clue how to implement it</p> <p><strong>Question</strong></p> <ul> <li>How can I fix my problems, respectively, is there a smarter way to implement the first function?</li> <li>What would be a good implementation for the second function?</li> </ul> <p>Thanks for any help.</p>
2
2016-08-20T13:46:33Z
39,056,695
<p>The obvious issue that we did not see earlier was unconditional <code>return</code> statement in your inner loop.</p> <p>You have to return something only if it is not <code>None</code>, else other items of the list other than the first one are ignored.</p> <p>(note I have changed <code>iteritems</code> to <code>items</code> because it is python 3 compatible and also works with latest python 2.7 versions)</p> <pre><code>a = {'task0': {'node_id': 0, 'successor': [{'task1': {'node_id': 1, 'successor': [{'task2': {'node_id': 2, 'successor': [{'task4': {'node_id': 4, 'successor': []}}, {'task5': {'node_id': 5, 'successor': []}}]}}, {'task3': {'node_id': 3, 'successor': []}}]}}]}} def get_node_name_by_id(obj, id_search): for k,v in obj.items(): if isinstance(v,dict): if v['node_id'] is id_search: return k elif v['successor']: for e in v['successor']: r = get_node_name_by_id(e, id_search) if r: return r print(get_node_name_by_id(a, 3)) </code></pre> <p>output:</p> <pre><code>task3 </code></pre>
0
2016-08-20T17:03:22Z
[ "python", "dictionary", "nested", "iteration" ]
Getting key of unique values in a nested dict within lists
39,054,836
<p>I have a dict, which contains of elements with the following structure</p> <pre><code>{'task0': {'id': 0, 'successor':[&lt;other elements&gt;]} </code></pre> <p>Every element contains a unique id and a successor list of the mentioned elements. The can be also empty, which means, this element has no successors. </p> <p><strong>Example</strong> </p> <pre><code>a = {'task0': {'node_id': 0, 'successor': [{'task1': {'node_id': 1, 'successor': [{'task2': {'node_id': 2, 'successor': [{'task4': {'node_id': 4, 'successor': []}}, {'task5': {'node_id': 5, 'successor': []}}]}}, {'task3': {'node_id': 3, 'successor': []}}]}}]}} </code></pre> <p><strong>What I want</strong></p> <pre><code>def get_node_name_by_id(obj, id_search) </code></pre> <p>Example: def get_node_name_by_id(a, 3) == 'task3'</p> <pre><code>def get_parent_id_by_child_id(obj, id_search) </code></pre> <p>Example: def get_parent_id_by_child_id(a, 3) == 1 </p> <p><strong>What I have so far</strong></p> <pre><code>def get_node_name_by_id(obj, id_search): for k,v in obj.iteritems(): if isinstance(v,dict): if v['node_id'] is id_search: return k elif v['successor']: for e in v['successor']: return get_node_name_by_id(e, id_search) </code></pre> <p>-> Problem: If the id, which I am searching for, is not on place 1 of the list, I get <code>None</code> as a result. </p> <p>-> For the second function, I have no clue how to implement it</p> <p><strong>Question</strong></p> <ul> <li>How can I fix my problems, respectively, is there a smarter way to implement the first function?</li> <li>What would be a good implementation for the second function?</li> </ul> <p>Thanks for any help.</p>
2
2016-08-20T13:46:33Z
39,077,423
<p>Based on tobias_k comment, I found an easier way to store the information. Because every node object has a unique ID, it is enough to store these IDs only. The index of each sublist is the index of the node, for which the successors are defined.</p> <pre><code>successor_list = [[successors_node0], [successors_node1], [successors_node2], ..., [successors_nodeN]] </code></pre> <p>With the help of the ID, I can access to the node object (all node objects are stored in a list) to access on the object attributes.</p>
0
2016-08-22T10:40:21Z
[ "python", "dictionary", "nested", "iteration" ]
Need help using regex to extract strings from json string from text (python)
39,054,914
<p>Hi so I'm trying to extract moderator names from a simple piece of code like this:</p> <pre><code>{ "_links": {}, "chatter_count": 2, "chatters": { "moderators": [ "nightbot", "vivbot" ], "staff": [], "admins": [], "global_mods": [], "viewers": [] } } </code></pre> <p>I've been trying to grab the moderators using \"moderators\":\s*[(\s*\"\w*\"\,<em>)</em>\s*] but to no success. <strong>I'm using regex over json parsing mostly for the challenge.</strong></p>
1
2016-08-20T13:55:36Z
39,055,469
<pre><code>moderators = list() first = re.compile(r'moderators.*?\[([^\]]*)', re.I) second = re.compile(r'"(.*?)"') strings = first.findall(string) for strings2 in strings: moderators = moderators + second.findall(strings2) </code></pre> <p>This should do the trick</p> <p>The first regular expression extracts everything between 2 square braces. The second regular expression extracts the string from it.</p> <p>I broke it up into 2 regex expressions for readability and ease of writing</p> <p>NOW, using the json module, you could do something much easier:</p> <pre><code>import json a = json.loads(string) moderators = a['chatters']['moderators'] </code></pre>
1
2016-08-20T14:55:52Z
[ "python", "json", "regex" ]
How to change fields label to a specific language in django admin panel?
39,054,923
<p>I am using Python 3 and django 1.10. <br> i have a model named <code>Comapny</code>. It has a field called title , i am trying to save the company title in two languages but dont wanna separate them to <code>title_en</code> and <code>title_fa</code>. i am want to save both of them using <code>Json</code> in the Company field. How can i make this changes before saving ? Also i added this model to the admin panel so i can see the fields in that page. i want to translate title label(in admin panel) and other fields in that form. for example if the language is english it shows me the title as a label, if it set to fa(persian) it gives me the translation. how can i set my language file to change them ?</p>
0
2016-08-20T13:56:30Z
39,055,852
<pre><code>from django.utils.translation import ugettext_lazy as _ class MyModel(models.Model): title = models.CharField(_('mymodeltitle'), max_length=80) </code></pre> <p>Do a make message. Translate. Compile messages. It should be translated in the admin. </p> <p>For translations in Django :</p> <p><a href="https://docs.djangoproject.com/en/1.10/topics/i18n/translation/" rel="nofollow">https://docs.djangoproject.com/en/1.10/topics/i18n/translation/</a></p>
2
2016-08-20T15:34:20Z
[ "python", "django", "django-models", "django-admin", "multilingual" ]
Processes not joining even after flushing their queues
39,054,963
<p>I wrote a program using the module <code>multiprocessing</code> which globally executes as follows:</p> <ol> <li>both a <code>simulation</code> and an <code>ui</code> processes are started.</li> <li>the <code>simulation</code> process feeds a queue with new simulation states. If the queue is full, the simulation loop isn't blocked so it can handle possible incoming messages.</li> <li>the <code>ui</code> process consumes the simulation queue.</li> <li>after around 1 second of execution time, the <code>ui</code> process sends a <code>quit</code> event to the main process then exits the loop. Upon exiting it sends a <code>stopped</code> event to the main process through the <code>_create_process()</code>'s inner <code>wrapper()</code> function.</li> <li>the main process receives both events in whichever order. The <code>quit</code> event results in the main process sending <code>stop</code> signals to all the child processes, while the <code>stopped</code> event increments a counter in the main loop which will cause it to exit after having received as many <code>stopped</code> events as there are processes.</li> <li>the <code>simulation</code> process receives the <code>stop</code> event and exits the loop, sending in turn a <code>stopped</code> event to the main process.</li> <li>the main process has now received 2 <code>stopped</code> events in total and concludes that all child processes are—on their way to be—stopped. As a result, the main loop is exited</li> <li>the <code>run()</code> function flushes the queues which have been written by the child processes.</li> <li>the child processes are being joined.</li> </ol> <p>The problem is that quite often (but not always) the program will hang upon trying to join the <code>simulation</code> process, as per the log below.</p> <pre class="lang-none prettyprint-override"><code>[...] [INFO/ui] process exiting with exitcode 0 [DEBUG/MainProcess] starting thread to feed data to pipe [DEBUG/MainProcess] ... done self._thread.start() [DEBUG/simulation] Queue._start_thread() [DEBUG/simulation] doing self._thread.start() [DEBUG/simulation] starting thread to feed data to pipe [DEBUG/simulation] ... done self._thread.start() [DEBUG/simulation] telling queue thread to quit [DEBUG/MainProcess] all child processes (2) should have been stopped! [INFO/simulation] process shutting down [DEBUG/simulation] running all "atexit" finalizers with priority &gt;= 0 [DEBUG/simulation] telling queue thread to quit [DEBUG/simulation] running the remaining "atexit" finalizers [DEBUG/simulation] joining queue thread [DEBUG/MainProcess] joining process &lt;Process(simulation, started)&gt; [DEBUG/simulation] feeder thread got sentinel -- exiting [DEBUG/simulation] ... queue thread joined [DEBUG/simulation] joining queue thread </code></pre> <p>Stopping the execution through a <code>Ctrl + C</code> in the shell results in these mangled tracebacks:</p> <pre class="lang-none prettyprint-override"><code>Process simulation: Traceback (most recent call last): Traceback (most recent call last): File "./debug.py", line 224, in &lt;module&gt; run() File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/multiprocessing/process.py", line 257, in _bootstrap util._exit_function() File "./debug.py", line 92, in run process.join() #&lt; This doesn't work. File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/multiprocessing/util.py", line 312, in _exit_function _run_finalizers() File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/multiprocessing/process.py", line 121, in join File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/multiprocessing/util.py", line 252, in _run_finalizers finalizer() File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/multiprocessing/util.py", line 185, in __call__ res = self._callback(*self._args, **self._kwargs) res = self._popen.wait(timeout) File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/multiprocessing/popen_fork.py", line 54, in wait File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/multiprocessing/queues.py", line 196, in _finalize_join thread.join() return self.poll(os.WNOHANG if timeout == 0.0 else 0) File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/multiprocessing/popen_fork.py", line 30, in poll pid, sts = os.waitpid(self.pid, flag) KeyboardInterrupt File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/threading.py", line 1060, in join self._wait_for_tstate_lock() File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/threading.py", line 1076, in _wait_for_tstate_lock elif lock.acquire(block, timeout): KeyboardInterrupt </code></pre> <p>As for the code, here is a stripped down version of it (hence why it often seems incomplete):</p> <pre class="lang-python prettyprint-override"><code>#!/usr/bin/env python3 import logging import multiprocessing import pickle import queue import time from collections import namedtuple _LOGGER = multiprocessing.log_to_stderr() _LOGGER.setLevel(logging.DEBUG) _BUFFER_SIZE = 4 _DATA_LENGTH = 2 ** 12 _STATUS_SUCCESS = 0 _STATUS_FAILURE = 1 _EVENT_ERROR = 0 _EVENT_QUIT = 1 _EVENT_STOPPED = 2 _MESSAGE_STOP = 0 _MESSAGE_EVENT = 1 _MESSAGE_SIMULATION_UPDATE = 2 _Message = namedtuple('_Message', ('type', 'value',)) _StopMessage = namedtuple('_StopMessage', ()) _EventMessage = namedtuple('_EventMessage', ('type', 'value',)) _SimulationUpdateMessage = namedtuple('_SimulationUpdateMessage', ('state',)) _MESSAGE_STRUCTS = { _MESSAGE_STOP: _StopMessage, _MESSAGE_EVENT: _EventMessage, _MESSAGE_SIMULATION_UPDATE: _SimulationUpdateMessage } def run(): # Messages from the main process to the child ones. downward_queue = multiprocessing.Queue() # Messages from the child processes to the main one. upward_queue = multiprocessing.Queue() # Messages from the simulation process to the UI one. simulation_to_ui_queue = multiprocessing.Queue(maxsize=_BUFFER_SIZE) # Regroup all the queues that can be written by child processes. child_process_queues = (upward_queue, simulation_to_ui_queue,) processes = ( _create_process( _simulation, upward_queue, name='simulation', args=( simulation_to_ui_queue, downward_queue ) ), _create_process( _ui, upward_queue, name='ui', args=( upward_queue, simulation_to_ui_queue, downward_queue ) ) ) try: for process in processes: process.start() _main(downward_queue, upward_queue, len(processes)) finally: # while True: # alive_processes = tuple(process for process in processes # if process.is_alive()) # if not alive_processes: # break # _LOGGER.debug("processes still alive: %s" % (alive_processes,)) for q in child_process_queues: _flush_queue(q) for process in processes: _LOGGER.debug("joining process %s" % process) # process.terminate() #&lt; This works! process.join() #&lt; This doesn't work. def _main(downward_queue, upward_queue, process_count): try: stopped_count = 0 while True: message = _receive_message(upward_queue, False) if message is not None and message.type == _MESSAGE_EVENT: event_type = message.value.type if event_type in (_EVENT_QUIT, _EVENT_ERROR): break elif event_type == _EVENT_STOPPED: stopped_count += 1 if stopped_count &gt;= process_count: break finally: # Whatever happens, make sure that all child processes have stopped. if stopped_count &gt;= process_count: return # Send a 'stop' signal to all the child processes. for _ in range(process_count): _send_message(downward_queue, True, _MESSAGE_STOP) while True: message = _receive_message(upward_queue, False) if (message is not None and message.type == _MESSAGE_EVENT and message.value.type == _EVENT_STOPPED): stopped_count += 1 if stopped_count &gt;= process_count: _LOGGER.debug( "all child processes (%d) should have been stopped!" % stopped_count ) break def _simulation(simulation_to_ui_queue, downward_queue): simulation_state = [i * 0.123 for i in range(_DATA_LENGTH)] # When the queue is full (possibly form reaching _BUFFER_SIZE), the next # solve is computed and kept around until the queue is being consumed. next_solve_message = None while True: message = _receive_message(downward_queue, False) if message is not None and message.type == _MESSAGE_STOP: break if next_solve_message is None: # _step(simulation_state) # Somehow the copy (pickle) seems to increase the chances for # the issue to happen. next_solve_message = _SimulationUpdateMessage( state=pickle.dumps(simulation_state) ) status = _send_message(simulation_to_ui_queue, False, _MESSAGE_SIMULATION_UPDATE, **next_solve_message._asdict()) if status == _STATUS_SUCCESS: next_solve_message = None def _ui(upward_queue, simulation_to_ui_queue, downward_queue): time_start = -1.0 previous_time = 0.0 while True: message = _receive_message(downward_queue, False) if message is not None and message.type == _MESSAGE_STOP: break if time_start &lt; 0: current_time = 0.0 time_start = time.perf_counter() else: current_time = time.perf_counter() - time_start message = _receive_message(simulation_to_ui_queue, False) if current_time &gt; 1.0: _LOGGER.debug("asking to quit") _send_message(upward_queue, True, _MESSAGE_EVENT, type=_EVENT_QUIT, value=None) break previous_time = current_time def _create_process(target, upward_queue, name='', args=None): def wrapper(function, upward_queue, *args, **kwargs): try: function(*args, **kwargs) except Exception: _send_message(upward_queue, True, _MESSAGE_EVENT, type=_EVENT_ERROR, value=None) finally: _send_message(upward_queue, True, _MESSAGE_EVENT, type=_EVENT_STOPPED, value=None) upward_queue.close() process = multiprocessing.Process( target=wrapper, name=name, args=(target, upward_queue) + args, kwargs={} ) return process def _receive_message(q, block): try: message = q.get(block=block) except queue.Empty: return None return message def _send_message(q, block, message_type, **kwargs): message_value = _MESSAGE_STRUCTS[message_type](**kwargs) try: q.put(_Message(type=message_type, value=message_value), block=block) except queue.Full: return _STATUS_FAILURE return _STATUS_SUCCESS def _flush_queue(q): try: while True: q.get(block=False) except queue.Empty: pass if __name__ == '__main__': run() </code></pre> <p>Related questions on StackOverflow and hints in Python's doc basically boil down to needing to flush the queues before joining the processes, which I believe I've been trying to do here. I realize that the simulation queue could still be trying to push the (potentially large) buffered data onto the pipe by the time the program would try to flush them upon exiting, and thus ending up with still non-empty queues. This is why I tried to ensure that all the child processes were stopped before reaching this point. Now, looking at the log above and at the additional log outputted after uncommenting the <code>while True</code> loop checking for alive processes, it appears that the <code>simulation</code> process simply doesn't want to completely shut down even though its target function definitely exited. Could this be the reason of my problem?</p> <p>If so, how am I suppsoed to deal with it cleanly? Otherwise, what am I missing here?</p> <p>Tested with Python 3.4 on Mac OS X 10.9.5.</p> <p>PS: I'm wondering if this couldn't be related to <a href="https://bugs.python.org/msg210368" rel="nofollow">this bug</a> ?</p>
0
2016-08-20T14:00:18Z
39,062,761
<p>Sounds like the issue was indeed due to some delay in pushing the data through the queue, causing the flushes to be ineffective because fired too early.</p> <p>A simple <code>while process.is_alive(): flush_the_queues()</code> seems to do the trick!</p>
0
2016-08-21T09:27:50Z
[ "python", "multithreading", "queue", "multiprocessing", "ipc" ]
How to save state of selenium web driver in python?
39,054,992
<p>I am trying to scrape this website: <a href="http://www.infoempleo.com/ofertas-internacionales/" rel="nofollow">http://www.infoempleo.com/ofertas-internacionales/</a>. I wanted to scrape by selecting the "Last 15 days" radio button. So I wrote this code.</p> <pre><code>browser = webdriver.Chrome('C:\Users\Junaid\Downloads\chromedriver\chromedriver_win32\chromedriver.exe') new_urls = deque(['http://www.infoempleo.com/ofertas-internacionales/']) processed_urls = set() while len(new_urls): print "------ URL LIST -------" print new_urls print "-----------------------" print time.sleep(5) url = new_urls.popleft() processed_urls.add(url) try: print "----------- Scraping ==&gt;",url browser.get(url) elem = browser.find_elements_by_id("fechapublicacion")[-1] if ( elem.is_selected() ): print "already selected" else: elem.click() html = browser.page_source except: print "-------- Failed to Scrape, Moving to Next" continue soup = BeautifulSoup(html) </code></pre> <p>I have been able to select the radio button and scrape the first page. There is a list of pages at the end like 1, 2, 3..</p> <p>When moving to the next page, <code>'browser.get(url)'</code> is called which resets the radio button to 'Any Date' instead of 'Last 15 Days'. Which makes the code execute the else statement <code>else: elem.click()</code> to select the radio button again, which open the first page that has been already scraped.</p> <p>Is there a way around this? Help will be appreciated.</p>
0
2016-08-20T14:03:33Z
39,058,488
<p>I have found a work around this problem. Instead of saving links to next pages in a list. I am selecting the nextPage button/element and using <code>.click()</code>. This way the <code>browser.get(url)</code> is not needed to call again and the page is not reloaded.</p>
0
2016-08-20T20:34:40Z
[ "python", "selenium", "selenium-webdriver" ]
Recursive multi shift caesar cipher - Type error (can't conc None)
39,054,999
<p>First time posting here, newbie to python but really enjoying what I'm doing with it. Working through the MIT Open courseware problems at the moment. Any suggestions of other similar resources?</p> <p>My problem is with returning a recursive function that's meant to build a list of multi layer shifts as tuples where each tuple is (start location of shift,magnitude of shift). A shift of 5 would change a to f, a-b-c-d-e-f.</p> <p>Code below for reference but you shouldn't need to read through it all.</p> <p>text is the multi layered scrambled input, eg: 'grrkxmdffi jwyxechants idchdgyqapufeulij'</p> <pre><code>def find_best_shifts_rec(wordlist, text, start): ### TODO. """Shifts stay in place at least until a space, so shift can only start with a new word Base case? all remaining words are real Need to find the base case which goes at the start of the function to ensure it's all cleanly returned Base case could be empty string if true words are removed? Base case when start = end take recursive out of loop use other functions to simplify """ shifts = [] shift = 0 for a in range(27): shift += 1 #creates a string and only shifts from the start point """text[:start] + optional add in not sure how it'd help""" testtext = apply_shift(text[start:],-shift) testlist = testtext.split() #counts how many real words were made by the current shift realwords = 0 for word in testlist: if word in wordlist: realwords += 1 else: #as soon as a non valid word is found i know the shift is not valid break if a == 27 and realwords == 0: print 'here\'s the prob' #if one or more words are real if realwords &gt; 0: #add the location and magnitude of shift shifts = [(start,shift)] #recursive call - start needs to be the end of the last valid word start += testtext.find(testlist[realwords - 1]) + len(testlist[realwords - 1]) + 1 if start &gt;= len(text): #Base case return shifts else: return shifts + find_best_shifts_rec(wordlist,text,start) </code></pre> <p>This frequently returns the correct list of tuples, but sometimes, with this text input for example, I get the error:</p> <pre><code> return shifts + find_best_shifts_rec(wordlist,text,start) TypeError: can only concatenate list (not "NoneType") to list </code></pre> <p>this error is for the following at the very bottom of my code</p> <pre><code>else: return shifts + find_best_shifts_rec(wordlist,text,start) </code></pre> <p>From what I gather, one of the recursive calls returns the None value, and then trying to conc this with the list throws up the error. How can I get around this?</p> <p>EDIT:</p> <p>By adding to the end:</p> <p>elif a == 26: return [()]</p> <p>I can prevent the type error when it can't find a correct shift. How can I get the entire function to return none?</p>
0
2016-08-20T14:04:20Z
39,056,298
<p>Below is my attempt at reworking your code to do what you want. Specific changes: dropped the range from 27 to 26 to let the loop exit naturally and return the empty <code>shifts</code> array; combined <code>a</code> and <code>shift</code> and started them at zero so an unencoded text will return <code>[(0, 0)]</code>; the <code>.find()</code> logic will mess up if the same word appears in the list twice, changed it to <code>rindex()</code> as a bandaid (i.e. the last correctly decoded one is where you want to start, not the first).</p> <pre><code>def find_best_shifts_rec(wordlist, text, start=0): shifts = [] for shift in range(26): # creates a string and only shifts from the start point testtext = apply_shift(text[start:], -shift) testlist = testtext.split() # words made by the current shift realwords = [] for word in testlist: if word in wordlist: realwords.append(word) else: # as soon as an invalid word is found I know the shift is invalid break if realwords: # if one or more words are real # add the location and magnitude of shift shifts = [(start, shift)] # recursive call - start needs to be the end of the last valid word realword = realwords[-1] start += testtext.rindex(realword) + len(realword) + 1 if start &gt;= len(text): return shifts # base case return shifts + find_best_shifts_rec(wordlist, text, start) return shifts </code></pre> <p>'lbh fwj hlzkv tbizljb'</p>
0
2016-08-20T16:19:59Z
[ "python", "recursion", "caesar-cipher" ]
Multiprocessing using shared memory
39,055,102
<p>Can someone provide me with sample code to share a writable array or a list among a pool of worker processes or even individually spawned processes using the multiprocessing module of python using locks? My code below spawns 2 processes of which one should print '1' and the other should print '2' to the shared array. However, when I try to print out the elements of the array after the processing it only gives me a list of 0's. Where am I going wrong? I want a writable data structure to be shared between multiple processes.</p> <p>Below is my code:</p> <pre><code>import multiprocessing arr=multiprocessing.Array('i',10,lock=True) lock=multiprocessing.RLock() def putitin(n): for i in range(5): lock.acquire() arr.append(n) lock.release() return p1=multiprocessing.Process(target=putitin,args=(1,)) p2=multiprocessing.Process(target=putitin,args=(2,)) p1.start() p2.start() p1.join() p2.join() for i in range(10): print(arr[i]) </code></pre>
0
2016-08-20T14:16:39Z
39,055,967
<p>A few issues that I found in your code. First of all, it <a href="https://docs.python.org/3.5/library/multiprocessing.html#multiprocessing-programming" rel="nofollow">seems to be a good idea</a> to pass all shared resources to child and use <code>if __name__ == '__main__'</code>. Secondly, I don't think <code>multiprocessing.Array</code> has <code>append()</code> method (at least it didn't work for me on Python2 and Python3). Thirdly, since you are using <code>lock=True</code> I don't think you need additional locks.</p> <p>If you need to append values to the Array I'd use separate Counter variable (see the code below).</p> <pre><code>import multiprocessing def putitin(n, arr, counter): for i in range(5): with counter.get_lock(): index = counter.value counter.value += 1 arr[index] = n if __name__ == '__main__': arr = multiprocessing.Array('i', 10,lock=True) counter = multiprocessing.Value('i', 0, lock=True) p1 = multiprocessing.Process(target=putitin,args=(1, arr, counter)) p2 = multiprocessing.Process(target=putitin,args=(2, arr, counter)) p1.start() p2.start() p2.join() p1.join() for i in range(10): print(arr[i]) </code></pre> <p>Having said that, what is your high-level goal? What are you trying to achieve with it? Maybe it's possible to use <code>multiprocessing.Pool</code>?</p>
0
2016-08-20T15:45:04Z
[ "python", "arrays", "multiprocessing", "shared-memory" ]
Multiprocessing using shared memory
39,055,102
<p>Can someone provide me with sample code to share a writable array or a list among a pool of worker processes or even individually spawned processes using the multiprocessing module of python using locks? My code below spawns 2 processes of which one should print '1' and the other should print '2' to the shared array. However, when I try to print out the elements of the array after the processing it only gives me a list of 0's. Where am I going wrong? I want a writable data structure to be shared between multiple processes.</p> <p>Below is my code:</p> <pre><code>import multiprocessing arr=multiprocessing.Array('i',10,lock=True) lock=multiprocessing.RLock() def putitin(n): for i in range(5): lock.acquire() arr.append(n) lock.release() return p1=multiprocessing.Process(target=putitin,args=(1,)) p2=multiprocessing.Process(target=putitin,args=(2,)) p1.start() p2.start() p1.join() p2.join() for i in range(10): print(arr[i]) </code></pre>
0
2016-08-20T14:16:39Z
39,055,993
<p>One potential problem with your code is that to use <code>multiprocessing</code> on Windows you need to put the code for the main process in an <code>if __name__ == '__main__':</code> block. See the <strong>Safe importing of main module</strong> subsection of the <a href="https://docs.python.org/2/library/multiprocessing.html#windows" rel="nofollow">Windows</a> section of the <a href="https://docs.python.org/2/library/multiprocessing.html#programming-guidelines" rel="nofollow"><em>multiprocessing Programming guidelines</em></a>.</p> <p>Another major one is that you're attempting to a share global variable among the processes. which won't work because each one runs in its own unshared memory-space, so each subprocess has it's own <code>arr</code>. (Variables which are just module level constants are OK, though)</p> <p>Lastly, a <code>multiprocessing.Array</code> has a fixed size and doesn't have the <code>extend()</code> method your code is trying to use in the <code>putitin()</code> function — therefore it appears you also want a writable <em>and</em> resizable container (that is ordered and perhaps accessible via integer indices).</p> <p>In that case something the like the following may be suitable. You don't need to explicitly lock the object before make changes to it because it's a thread-safe shared object.</p> <pre><code>import multiprocessing def putitin(lst, value): for i in range(5): lst.append(value) if __name__ == '__main__': manager = multiprocessing.Manager() lst = manager.list() p1 = multiprocessing.Process(target=putitin, args=(lst, 1)) p2 = multiprocessing.Process(target=putitin, args=(lst, 2)) p1.start() p2.start() p1.join() p2.join() for i in range(len(lst)): print(lst[i]) </code></pre> <p>Output:</p> <pre class="lang-none prettyprint-override"><code>1 1 1 1 1 2 2 2 2 2 </code></pre>
0
2016-08-20T15:47:35Z
[ "python", "arrays", "multiprocessing", "shared-memory" ]
Installing basemap: setup.py encounters an error
39,055,140
<p>I followed the rules <a href="http://matplotlib.org/basemap/users/installing.html" rel="nofollow">here</a> to install basemap step by step. But error occured at last.</p> <p>When I typed the command: python setup.py, an erorr appears as follows:</p> <pre><code>gddxz@ubuntu:~/Downloads/basemap-1.0.7$ python setup.py Traceback (most recent call last): File "setup.py", line 92, in &lt;module&gt; if sys.argv[1] not in ['sdist','clean']: IndexError: list index out of range gddxz@ubuntu:~/Downloads/basemap-1.0.7$ </code></pre> <p>If there is anyone encountering the similar problem? Any help will be much appreciated! </p>
0
2016-08-20T14:21:14Z
39,055,536
<p>The problem is that this command requires at least one parameter. According to the instructions you should execute <code>python setup.py install</code>.</p>
0
2016-08-20T15:02:39Z
[ "python", "matplotlib-basemap" ]
Installing basemap: setup.py encounters an error
39,055,140
<p>I followed the rules <a href="http://matplotlib.org/basemap/users/installing.html" rel="nofollow">here</a> to install basemap step by step. But error occured at last.</p> <p>When I typed the command: python setup.py, an erorr appears as follows:</p> <pre><code>gddxz@ubuntu:~/Downloads/basemap-1.0.7$ python setup.py Traceback (most recent call last): File "setup.py", line 92, in &lt;module&gt; if sys.argv[1] not in ['sdist','clean']: IndexError: list index out of range gddxz@ubuntu:~/Downloads/basemap-1.0.7$ </code></pre> <p>If there is anyone encountering the similar problem? Any help will be much appreciated! </p>
0
2016-08-20T14:21:14Z
39,366,781
<p>seems to have worked: 'python setup.py install'</p>
1
2016-09-07T09:57:37Z
[ "python", "matplotlib-basemap" ]
URLError doesn't return json body
39,055,149
<p>I have built a REST interface. On '400 Bad Request' it returns a json body with specific information about the error.</p> <pre><code>(Pdb) error.code 400 </code></pre> <p>Python correctly throws a URLError with these headers</p> <pre><code>(Pdb) print(error.headers) Cache-Control: no-cache Pragma: no-cache Content-Type: application/json; charset=utf-8 Expires: -1 Server: Microsoft-IIS/7.5 X-AspNet-Version: 4.0.30319 X-Powered-By: ASP.NET Date: Sat, 20 Aug 2016 13:01:05 GMT Connection: close Content-Length: 236 </code></pre> <p>There is a content of 236 char, but I cannot find a way to read the body.</p> <p>I can see the extra information using DHC chrome plugin</p> <pre><code>{ "error_code": "00000001", "error_message": "The json data is not in the correct json format.\r\nThe json data is not in the correct json format.\r\n'Execution Start Time' must not be empty.\r\n'Execution End Time' must not be empty.\r\n" } </code></pre> <p>However, I cannot find a way in Python to read the body</p> <p>Here are some of the things I have tried and what was returned.</p> <pre><code>(Pdb) len(error.read()) 0 error.read().decode('utf-8', 'ignore') '' (Pdb) error.readline() b'' </code></pre>
0
2016-08-20T14:22:01Z
39,083,889
<p>I found that this works the first time it is called, but does not work if called again.</p> <p>error.read().decode('utf-8')</p>
0
2016-08-22T15:55:03Z
[ "python", "json", "url", "exception" ]
user profile of other user shows up
39,055,156
<p>The id of admin is <strong>1</strong> when i open the admin user at the admin panel. Likewise the id of <code>michael</code> is <strong>2</strong> but when i click the profile icon instead of showing me the profile of admin i get profile of <code>michael</code>. To get the id i have used <code>user.id</code> of the <code>requested user</code>.</p> <p>Also the problem is i could not use slug in such model.</p> <p><strong>restaurant/base.html</strong></p> <pre><code>{% if user.is_authenticated %} &lt;li class="nav-item"&gt; &lt;a class="nav-link user-icon" href="{% url 'userprofiles:profile' user.id %}"&gt; &lt;i class="fa fa-user"&gt;&lt;/i&gt; &lt;/a&gt; &lt;/li&gt; {% else %} </code></pre> <p><strong>userprofiles/urls.py</strong></p> <pre><code>urlpatterns = [ # url(r'^profile/(?P&lt;profile_name&gt;[-\w]+)/(?P&lt;profile_id&gt;\d+)/$', views.profile, name='profile'), url( r'^profile/(?P&lt;profile_id&gt;\d+)/$', views.profile, name='profile' ), ] </code></pre> <p><strong>userprofiles/views.py</strong></p> <pre><code>def profile(request, profile_id): if profile_id is "0": userProfile = get_object_or_404(UserProfile, pk=profile_id) else: userProfile = get_object_or_404(UserProfile, pk=profile_id) user_restaurant = userProfile.restaurant.all() user_order = userProfile.order_history.all() total_purchase = 0 for ur in user_order: total_purchase += ur.get_cost() return render( request, 'userprofiles/profile.html', { 'userProfile':userProfile, 'user_restaurant':user_restaurant, 'user_order':user_order, 'total_purchase':total_purchase } ) </code></pre> <p><strong>userprofiles/profile.html</strong></p> <pre><code>{% for user_restaurant in user_restaurant %} {{user_restaurant.name}}&lt;br/&gt; {{user_restaurant.address }} {% endfor %} </code></pre> <p><strong>userprofiles/models.py</strong></p> <pre><code>class UserProfile(models.Model): user = models.OneToOneField(User) restaurant = models.ManyToManyField(Restaurant) order_history = models.ManyToManyField(OrderMenu) # favorites = models.ManyToManyField(Restaurant) is_owner = models.BooleanField(default=False) class Meta: def __str__(self): return self.user.username # def get_absolute_url(self): # return reverse('userprofiles:profile', kwargs={'slug':self.slug, 'id':self.id}) </code></pre> <p>How can i use slug for such model so that in admin panel the slug for that user be automatically saved? Because there is no post method.</p> <p>But the main problem is i am getting userprofile of another user.</p>
0
2016-08-20T14:22:43Z
39,055,583
<p>Just add <code>1</code> everywhere you use <code>profile_id</code></p> <pre><code>def profile(request, profile_id): if profile_id is "0": # Is profile_id a string or integer? userProfile = get_object_or_404(UserProfile, pk=(profile_id+1)) # What does this do? else: userProfile = get_object_or_404(UserProfile, pk=(profile_id+1)) user_restaurant = userProfile.restaurant.all() user_order = userProfile.order_history.all() total_purchase = 0 for ur in user_order: total_purchase += ur.get_cost() return render(request, 'userprofiles/profile.html', {'userProfile':userProfile, 'user_restaurant':user_restaurant, 'user_order':user_order, 'total_purchase':total_purchase }) </code></pre> <p>I suspect that somewhere in your code you've got a n-1 problem (i.e. computers start counting at 0 but humans start counting at 1). I haven't found exactly where it is, but this will probably work as a bandage solution in the meantime.</p> <p>Also, I'm not sure what that <code>if</code> does in your code, it looks like it would never get used if <code>profile_id</code> is an integer.</p>
0
2016-08-20T15:06:54Z
[ "python", "django", "django-models", "django-views" ]
user profile of other user shows up
39,055,156
<p>The id of admin is <strong>1</strong> when i open the admin user at the admin panel. Likewise the id of <code>michael</code> is <strong>2</strong> but when i click the profile icon instead of showing me the profile of admin i get profile of <code>michael</code>. To get the id i have used <code>user.id</code> of the <code>requested user</code>.</p> <p>Also the problem is i could not use slug in such model.</p> <p><strong>restaurant/base.html</strong></p> <pre><code>{% if user.is_authenticated %} &lt;li class="nav-item"&gt; &lt;a class="nav-link user-icon" href="{% url 'userprofiles:profile' user.id %}"&gt; &lt;i class="fa fa-user"&gt;&lt;/i&gt; &lt;/a&gt; &lt;/li&gt; {% else %} </code></pre> <p><strong>userprofiles/urls.py</strong></p> <pre><code>urlpatterns = [ # url(r'^profile/(?P&lt;profile_name&gt;[-\w]+)/(?P&lt;profile_id&gt;\d+)/$', views.profile, name='profile'), url( r'^profile/(?P&lt;profile_id&gt;\d+)/$', views.profile, name='profile' ), ] </code></pre> <p><strong>userprofiles/views.py</strong></p> <pre><code>def profile(request, profile_id): if profile_id is "0": userProfile = get_object_or_404(UserProfile, pk=profile_id) else: userProfile = get_object_or_404(UserProfile, pk=profile_id) user_restaurant = userProfile.restaurant.all() user_order = userProfile.order_history.all() total_purchase = 0 for ur in user_order: total_purchase += ur.get_cost() return render( request, 'userprofiles/profile.html', { 'userProfile':userProfile, 'user_restaurant':user_restaurant, 'user_order':user_order, 'total_purchase':total_purchase } ) </code></pre> <p><strong>userprofiles/profile.html</strong></p> <pre><code>{% for user_restaurant in user_restaurant %} {{user_restaurant.name}}&lt;br/&gt; {{user_restaurant.address }} {% endfor %} </code></pre> <p><strong>userprofiles/models.py</strong></p> <pre><code>class UserProfile(models.Model): user = models.OneToOneField(User) restaurant = models.ManyToManyField(Restaurant) order_history = models.ManyToManyField(OrderMenu) # favorites = models.ManyToManyField(Restaurant) is_owner = models.BooleanField(default=False) class Meta: def __str__(self): return self.user.username # def get_absolute_url(self): # return reverse('userprofiles:profile', kwargs={'slug':self.slug, 'id':self.id}) </code></pre> <p>How can i use slug for such model so that in admin panel the slug for that user be automatically saved? Because there is no post method.</p> <p>But the main problem is i am getting userprofile of another user.</p>
0
2016-08-20T14:22:43Z
39,061,048
<p>I used slug instead of id and for using slug i have used pre_save signal where slug value is taken from the username. </p> <pre><code>def profile(request, profile_slug): if profile_slug is None: userprofile = get_object_or_404(UserProfile,slug=profile_slug) else: userprofile = get_object_or_404(UserProfile, slug=profile_slug) user_restaurant = userprofile.restaurant.all() user_order = userprofile.order_history.all() total_purchase = userprofile.total_purchase return render(request, 'userprofiles/profile.html', {'userprofile':userprofile, 'user_restaurant':user_restaurant, 'user_order':user_order, 'total_purchase':total_purchase}) </code></pre> <p>I filled the value of slug in this way.</p> <pre><code>def create_slug(instance, new_slug=None): print('instance',instance.user) slug = slugify(instance.user.username) if new_slug is not None: slug = new_slug qs = UserProfile.objects.filter(slug=slug).order_by("-id") exists = qs.exists() if exists: new_slug = "%s-%s" %(slug, qs.first().id) return create_slug(instance, new_slug=new_slug) return slug def pre_save_post_receiver(sender, instance, *args, **kwargs): if not instance.slug: instance.slug = create_slug(instance) from django.db.models.signals import pre_save pre_save.connect(pre_save_post_receiver, sender=UserProfile) </code></pre>
0
2016-08-21T05:19:02Z
[ "python", "django", "django-models", "django-views" ]
IDE recommends to decorate Django CBV methods with @staticmethod
39,055,195
<p>The recommendation seems to make sense because <code>self</code> isn't used in the method, but now I'm curious:</p> <ul> <li><p>is it an oversight of CBV's and users should manually decorate each <code>@staticmethod</code>?</p></li> <li><p>is there already some code in Django that automagically makes all CBV methods static?</p></li> </ul> <p>Here is a screenshot of what I'm talking about. It's using DRF's CBV, but it was the same recommendation when I was using vanilla Django CBV.</p> <p><a href="http://i.stack.imgur.com/1ZpTa.png" rel="nofollow"><img src="http://i.stack.imgur.com/1ZpTa.png" alt="enter image description here"></a></p>
1
2016-08-20T14:27:02Z
39,056,113
<p>No, you shouldn't do this. These are instance methods and need to remain so.</p> <p>It does seem a bit odd though that you're not using any of the instance values or calling any instance methods there. Usually you would reference the URL arguments via <code>self.kwargs</code>, and call other methods such as <code>self.get_context_data</code>. If you're not doing any of that, I wonder if you're really getting any benefit from using CBVs at all.</p> <p>(In fact my usual recommendation is that you don't override <code>get</code> or <code>post</code> at all; those usually delegate to more specific methods that are more useful to override.)</p>
1
2016-08-20T16:00:38Z
[ "python", "django", "static-methods", "django-class-based-views" ]
Jupyter Notebook: Multiple notebook to one kernel?
39,055,213
<p>I'm doing some complicated works with Jupyter Notebook, so the notebook is very long (<a href="https://github.com/cqcn1991/Wind-Speed-Analysis" rel="nofollow">https://github.com/cqcn1991/Wind-Speed-Analysis</a>).</p> <p>Sometimes, during the middle of the notebook, I want to do some additional analysis. Adding them directly into the current notebook (in the middle) may make it more complex, and breaks its currecnt structure. I think it would be amazing if I can simply open another notebook, connect it to the existing notebook's kernel, then to do the additional analysis.</p> <p>Something may like</p> <pre><code># In the new notebook connect_to 'exisiting_notebook_name' # get access to the existing notebook df.describe() # ... # some additional analysis works </code></pre>
2
2016-08-20T14:29:38Z
39,311,820
<p>The <a href="https://github.com/ipython-contrib/jupyter_contrib_nbextensions/tree/master/src/jupyter_contrib_nbextensions/nbextensions/scratchpad" rel="nofollow">scratchpad</a> notebook extension sounds like exactly what you want.</p>
1
2016-09-03T22:18:54Z
[ "python", "jupyter", "jupyter-notebook" ]
How to perform a tag-agnostic text string search in an html file?
39,055,279
<p>I'm using <a href="https://languagetool.org/" rel="nofollow">LanguageTool</a> (LT) with the --xmlfilter option enabled to spell-check HTML files. This forces LanguageTool to strip all tags before running the spell check. </p> <p>This also means that all reported character positions are off because LT doesn't "see" the tags. </p> <p>For example, if I check the following HTML fragment:</p> <pre><code>&lt;p&gt;This is kin&lt;b&gt;d&lt;/b&gt; o&lt;i&gt;f&lt;/i&gt; a &lt;b&gt;stupid&lt;/b&gt; question.&lt;/p&gt; </code></pre> <p>LanguageTool will treat it as a plain text sentence:</p> <pre><code> This is kind of a stupid question. </code></pre> <p>and returns the following message:</p> <pre><code>&lt;error category="Grammar" categoryid="GRAMMAR" context=" This is kind of a stupid question. " contextoffset="24" errorlength="9" fromx="8" fromy="8" locqualityissuetype="grammar" msg="Don't include 'a' after a classification term. Use simply 'kind of'." offset="24" replacements="kind of" ruleId="KIND_OF_A" shortmsg="Grammatical problem" subId="1" tox="17" toy="8"/&gt; </code></pre> <p>(In this particular example, LT has flagged "kind of a.")</p> <p>Since the search string might be wrapped in tags and might occur multiple times I can't do a simple index search. </p> <p>What would be the most efficient Python solution to reliably locate any given text string in an HTML file? (LT returns an approximate character position, which might be off by 10-30% depending on the number of tags, as well as the words before and after the flagged word(s).)</p> <p>I.e. I'd need to do a search that ignores all tags, but includes them in the character position count. </p> <p>In this particular example, I'd have to locate "kind of a" and find the location of the letter k in:</p> <pre><code>kin&lt;b&gt;d&lt;/b&gt; o&lt;i&gt;f&lt;/i&gt;a </code></pre>
0
2016-08-20T14:36:14Z
39,066,521
<p>The <code>--xmlfilter</code> option is deprecated because of issues like this. The proper solution is to remove the tags yourself but keep the positions so you have a mapping to correct the results that come back from LT. When using LT from Java, this is supported by <a href="https://github.com/languagetool-org/languagetool/blob/master/languagetool-core/src/main/java/org/languagetool/markup/AnnotatedText.java" rel="nofollow">AnnotatedText</a>, but the algorithm should be simple enough to port it. (full disclosure: I'm the maintainer of LT)</p>
1
2016-08-21T16:43:08Z
[ "python", "html", "parsing", "tags", "languagetool" ]
How to perform a tag-agnostic text string search in an html file?
39,055,279
<p>I'm using <a href="https://languagetool.org/" rel="nofollow">LanguageTool</a> (LT) with the --xmlfilter option enabled to spell-check HTML files. This forces LanguageTool to strip all tags before running the spell check. </p> <p>This also means that all reported character positions are off because LT doesn't "see" the tags. </p> <p>For example, if I check the following HTML fragment:</p> <pre><code>&lt;p&gt;This is kin&lt;b&gt;d&lt;/b&gt; o&lt;i&gt;f&lt;/i&gt; a &lt;b&gt;stupid&lt;/b&gt; question.&lt;/p&gt; </code></pre> <p>LanguageTool will treat it as a plain text sentence:</p> <pre><code> This is kind of a stupid question. </code></pre> <p>and returns the following message:</p> <pre><code>&lt;error category="Grammar" categoryid="GRAMMAR" context=" This is kind of a stupid question. " contextoffset="24" errorlength="9" fromx="8" fromy="8" locqualityissuetype="grammar" msg="Don't include 'a' after a classification term. Use simply 'kind of'." offset="24" replacements="kind of" ruleId="KIND_OF_A" shortmsg="Grammatical problem" subId="1" tox="17" toy="8"/&gt; </code></pre> <p>(In this particular example, LT has flagged "kind of a.")</p> <p>Since the search string might be wrapped in tags and might occur multiple times I can't do a simple index search. </p> <p>What would be the most efficient Python solution to reliably locate any given text string in an HTML file? (LT returns an approximate character position, which might be off by 10-30% depending on the number of tags, as well as the words before and after the flagged word(s).)</p> <p>I.e. I'd need to do a search that ignores all tags, but includes them in the character position count. </p> <p>In this particular example, I'd have to locate "kind of a" and find the location of the letter k in:</p> <pre><code>kin&lt;b&gt;d&lt;/b&gt; o&lt;i&gt;f&lt;/i&gt;a </code></pre>
0
2016-08-20T14:36:14Z
39,068,990
<p>This may not be the speediest way to go, but pyparsing will recognize HTML tags in most forms. The following code inverts the typical scan, creating a scanner that will match any single character, and then configuring the scanner to skip over HTML open and close tags, and also common HTML <code>'&amp;xxx;'</code> entities. pyparsing's <code>scanString</code> method returns a generator that yields the matched tokens, the starting, and the ending location of each match, so it is easy to build a list that maps every character outside of a tag to its original location. From there, the rest is pretty much just <code>''.join</code> and indexing into the list. See the comments in the code below:</p> <pre><code>test = "&lt;p&gt;This &amp;nbsp;is kin&lt;b&gt;d&lt;/b&gt; o&lt;i&gt;f&lt;/i&gt; a &lt;b&gt;stupid&lt;/b&gt; question.&lt;/p&gt;" from pyparsing import Word, printables, anyOpenTag, anyCloseTag, commonHTMLEntity non_tag_text = Word(printables+' ', exact=1).leaveWhitespace() non_tag_text.ignore(anyOpenTag | anyCloseTag | commonHTMLEntity) # use scanString to get all characters outside of tags, and build list # of (char,loc) tuples char_locs = [(t[0], loc) for t,loc,endloc in non_tag_text.scanString(test)] # imagine a world without HTML tags... untagged = ''.join(ch for ch, loc in char_locs) # look for our string in the untagged text, then index into the char,loc list # to find the original location search_str = 'kind of a' orig_loc = char_locs[untagged.find(search_str)][1] # print the test string, and mark where we found the matching text print(test) print(' '*orig_loc + '^') """ Should look like this: &lt;p&gt;This &amp;nbsp;is kin&lt;b&gt;d&lt;/b&gt; o&lt;i&gt;f&lt;/i&gt; a &lt;b&gt;stupid&lt;/b&gt; question.&lt;/p&gt; ^ """ </code></pre>
1
2016-08-21T21:21:59Z
[ "python", "html", "parsing", "tags", "languagetool" ]
How does Python pass keyword changes values in list?
39,055,331
<p>I have one small program in Python. I have created list and I am passing it as function parameter. According to me it should give output as 1 2 3 4 5. But it is giving me <code>5 2 3 4 5</code> as output. If I am just writing 'pass' keyword inside for loop then it should not do anything.Then why is that changing my output?</p> <p>Here is my code:</p> <pre><code>def fun1(list1): for list1[0] in list1: pass list2=[1,2,3,4,5] fun1(list2) print(list2) </code></pre>
-4
2016-08-20T14:40:47Z
39,055,361
<p>Your <code>for</code> loops sets the loop variable <code>list1[0]</code> to each value in the list <code>list1</code>. After it has finished, the loop variable contains whatever its value was in the last iteration, which in this case is <code>5</code>. If you don't want your loop to have this weird side effect, don't use an existing variable (like <code>list1[0]</code>) as the loop variable. I have never seen anyone do this before: it is a very odd thing to do.</p>
2
2016-08-20T14:43:46Z
[ "python" ]
Is searchsorted faster than get_loc to find label location in a DataFrame Index?
39,055,530
<p>I need to find the integer location for a label in a Pandas index. I know I can use get_loc method, but then I discovered searchsorted. Just wondering if I should use the latter for speed improvement, as I need to search for thousands of labels.</p>
1
2016-08-20T15:01:47Z
39,055,999
<p>It will depend on your usecase. using @ayhan's example.</p> <p>With <code>get_loc</code> there is a big upfront cost of creating the hash table on the first lookup.</p> <pre><code>In [22]: idx = pd.Index(['R{0:07d}'.format(i) for i in range(10**7)]) In [23]: to_search = np.random.choice(idx, 10**5, replace=False) In [24]: %time idx.get_loc(to_search[0]) Wall time: 1.57 s </code></pre> <p>But, subsequent lookups may be faster. (not guaranteed, depends on data)</p> <pre><code>In [9]: %%time ...: for i in to_search: ...: idx.get_loc(i) Wall time: 200 ms In [10]: %%time ...: for i in to_search: ...: np.searchsorted(idx, i) Wall time: 486 ms </code></pre> <p>Also, as Jeff noted, <code>get_loc</code> is guaranteed to always work, where <code>searchsorted</code> requires monotonicity (and doesn't check).</p>
3
2016-08-20T15:48:28Z
[ "python", "pandas" ]
Finding max value of an attribute of objects in a dictionary
39,055,550
<p>I have a collection of objects stored in a dictionary, and I am wanting to retrieve the maximum value of a particular attribute. The objects are cookies (think chocolate chip), and each cookie has its own temperature, heat capacity, batch number, etc. The batch number describes which set of cookies it exited the oven with.</p> <pre><code>class Cookie: def __init__(self, density, specificheat, batch): self.rho = density self.cp = specificheat self.batch = batch self.volume = 1.2e-5 # m^3 self.surfarea = 4.9e-3 # m^2 ... </code></pre> <p>I want to find the maximum batch number in the dictionary. I know this would be simple if I were using a list, I could just use operator.attrgetter('batch') to sort the list and get the value. However, using a dictionary, this line does not work:</p> <pre><code>sorted(cookies, key=operator.attrgetter('batch')) </code></pre> <p>I could set up a for loop and go through every single object in the dictionary, but I feel there is a better way to do this. I want to avoid switching to a list because I'm running an optimization sorting the cookies into boxes, and it is faster to retrieve data from a dictionary than from a list when you have to worry about 2000 cookies. (I timed it using timeit()). I've looked for similar questions on Stackoverflow, but most of them seem to be in javascript. The Python questions I've found are for dictionaries that don't store objects like mine. Any help would be greatly appreciated!</p>
2
2016-08-20T15:04:02Z
39,055,678
<p>You could just use max on the values:</p> <pre><code>mx_batch = max(cookies.values(), key=operator.attrgetter('batch')).batch </code></pre> <p>Or just use a class attribute to keep the max:</p> <pre><code>class Cookie: mx = 0 def __init__(self, density, specificheat, batch): self.rho = density self.cp = specificheat self.batch = batch self.volume = 1.2e-5 # m^3 self.surfarea = 4.9e-3 # m^2 if batch &gt; Cookie.mx: Cookie.mx = batch </code></pre> <p>Then:</p> <pre><code>In [9]: c1 = Cookie(1, 120, 1) In [10]: c2 = Cookie(2, 120, 4) In [11]: c3 = Cookie(1, 120, 2) In [12]: c4 = Cookie(1, 120, 1) In [13]: print(Cookie.mx) 4 </code></pre>
1
2016-08-20T15:15:44Z
[ "python", "object", "dictionary" ]
Finding max value of an attribute of objects in a dictionary
39,055,550
<p>I have a collection of objects stored in a dictionary, and I am wanting to retrieve the maximum value of a particular attribute. The objects are cookies (think chocolate chip), and each cookie has its own temperature, heat capacity, batch number, etc. The batch number describes which set of cookies it exited the oven with.</p> <pre><code>class Cookie: def __init__(self, density, specificheat, batch): self.rho = density self.cp = specificheat self.batch = batch self.volume = 1.2e-5 # m^3 self.surfarea = 4.9e-3 # m^2 ... </code></pre> <p>I want to find the maximum batch number in the dictionary. I know this would be simple if I were using a list, I could just use operator.attrgetter('batch') to sort the list and get the value. However, using a dictionary, this line does not work:</p> <pre><code>sorted(cookies, key=operator.attrgetter('batch')) </code></pre> <p>I could set up a for loop and go through every single object in the dictionary, but I feel there is a better way to do this. I want to avoid switching to a list because I'm running an optimization sorting the cookies into boxes, and it is faster to retrieve data from a dictionary than from a list when you have to worry about 2000 cookies. (I timed it using timeit()). I've looked for similar questions on Stackoverflow, but most of them seem to be in javascript. The Python questions I've found are for dictionaries that don't store objects like mine. Any help would be greatly appreciated!</p>
2
2016-08-20T15:04:02Z
39,055,690
<p>Here is one way to do it</p> <pre><code># where objs is your dictionary of cookies max(map(lambda i: objs[i].batch, objs)) </code></pre>
0
2016-08-20T15:17:40Z
[ "python", "object", "dictionary" ]
Instantiate shared_ptr objects from SWIG in Python
39,055,643
<p>I have a <code>BaseClass</code> and some derived classes </p> <pre><code>#ifndef TEST_H__ #define TEST_H__ #include &lt;iostream&gt; #include &lt;memory&gt; class BaseClass { public: virtual double eval(double x) const = 0; }; class Square: public BaseClass { public: double eval(double x) const {return x*x;} }; class Add1: public BaseClass { public: Add1(BaseClass &amp; obj): obj_(obj) {} double eval(double x) const {return obj_.eval(x) + 1.0;} private: BaseClass &amp; obj_; }; #endif /* TEST_H__ */ </code></pre> <p>which are treated with SWIG à la</p> <pre><code>%module test %{ #define SWIG_FILE_WITH_INIT %} %{ #include "test.h" %} %include "test.h" </code></pre> <p>This can be used from Python like</p> <pre><code>import test s = test.Square() a = test.Add1(s) print(a.eval(2.0)) </code></pre> <p>What's <em>segfaulting</em>:</p> <pre><code>import test a = test.Add1(test.Square()) print(a.eval(2.0)) </code></pre> <p>Why? The <code>test.Square()</code> is not assigned to a variable, so doesn't exist anymore after the assignment to <code>a</code>, and <code>obj_</code> points to invalid storage.</p> <p>To avoid such behavior, the idea to to use <code>std::shared_ptr&lt;BaseClass&gt;</code> instead of <code>BaseClass&amp;</code>, i.e.</p> <pre><code>class Add1: public BaseClass { public: Add1(std::shared_ptr&lt;BaseClass&gt; &amp; obj): obj_(obj) {} double eval(double x) const {return obj_-&gt;eval(x) + 1.0;} private: std::shared_ptr&lt;BaseClass&gt; obj_; }; </code></pre> <p>This exact code won't work though with</p> <pre><code>TypeError: in method 'new_Add1', argument 1 of type 'std::shared_ptr&lt; BaseClass &gt; &amp;' </code></pre> <p>Makes sense, too: <code>test.Square()</code> doesn't return a <code>std::shared_ptr&lt;BaseClass&gt;</code> but simply a <code>Square</code> aka <code>BaseClass</code> instance.</p> <p>Is it possible to have <code>test.Square()</code> return a shared pointer <code>std::shared_ptr&lt;Square&gt;</code>?</p>
1
2016-08-20T15:12:46Z
39,057,504
<p>SWIG has pretty good <a href="http://www.swig.org/Doc3.0/Library.html#Library_std_shared_ptr" rel="nofollow">support for <code>std::smart_ptr</code></a>. It all happens pretty transparently, so the changes you need to make to your .i file are just:</p> <pre><code>%module test %{ #define SWIG_FILE_WITH_INIT #include "test.h" %} %include &lt;std_shared_ptr.i&gt; %shared_ptr(Square); %shared_ptr(BaseClass); %shared_ptr(Add1); // Not actually needed to make your demo work, but a good idea still %include "test.h" </code></pre> <p>That was sufficient to make your demo Python code work, I also added <code>onlySquare()</code> as a member function of <code>Square</code> and adapted the demo to illustrate it:</p> <pre><code>import test sq=test.Square() test.Add1(sq) # implicitly converted to shared_ptr&lt;BaseClass&gt; here sq.onlySquare() print sq # &lt;test.Square; proxy of &lt;Swig Object of type 'std::shared_ptr&lt; Square &gt; *' at 0xf7424950&gt; &gt; </code></pre> <p>It should 'just work' for non-smart pointer arguments too, but note that now <em>all</em> Python created instances in that hierarchy will be 'smart'.</p> <p>(If you're interested, I've also covered <a href="http://stackoverflow.com/a/27699663/168175"><code>std::unique_ptr</code></a> and <a href="http://stackoverflow.com/a/24898632/168175"><code>std::weak_ptr</code></a> before).</p>
1
2016-08-20T18:36:09Z
[ "python", "c++", "swig" ]
Troubles in 3D points correpondance to 2D
39,055,693
<p>I made a little python script that produce some 3D points coordinates, deriving them from stereo vision (2 IR cameras). 3D coordinates are certainly correct.</p> <p>Now I have a third RGB camera and I was given the calibration matrices (I can't verify them): K is the matrix of intrinsics and R,t are the component of extrinsic parameters. The RGB image is 1280x800 But I can't set the right correspondence.</p> <p>I thought it would be easy use the projection formula, deriving the projection matrix "Pcolor" as Pcolor = K[R|t] and re-projecting the XYZ 3D coordinates (named "Pworld") as it follows: <a href="http://i.stack.imgur.com/0MD2w.gif" rel="nofollow"><img src="http://i.stack.imgur.com/0MD2w.gif" alt="enter image description here"></a></p> <p>I expected to obtain (u,v,w) so I normalized the result dividing it by w.</p> <pre><code>#import numpy as np ExtrColor = np.concatenate((Rcolor,Tcolor), axis = 1) #Rcolor is the 3x3 rotation matrix, Tcolor the column translation array # after calculation of X,Y,Z Pworld = np.matrix([[X], [Y], [Z], [1]]) Pcolor = np.dot((np.dot(Kcolor,ExtrColor)),Pworld) u = round(Pcolor[0,0]/Pcolor[2,0]) v = round(Pcolor[1,0]/Pcolor[2,0]) </code></pre> <p>Then I found that I obtain <em>u</em> and <em>v</em> values greater than 12000 instead of being in the range of the image (x&lt;1280 and y&lt;800).</p> <p>I can't figure out what is the problem. Has anyone ever got a similar problem? I don't think about problem of scale factor in XYZ coordinates, it should be ineffective in this formulation of the problem . Is a problem of my usage of np.dot? I'm quite sure it is a small error but I can't see it. </p> <p>Thanks for answering (and sorry for the poor english) !</p> <p>I checked similar questions in stack-overflow, <a href="http://stackoverflow.com/questions/3670340/projecting-a-3d-point-to-2d-screen-space-using-a-perspective-camera-matrix?rq=1">here</a> the problem seems to be similar but the method is different.</p> <p><em>PS This time I do not want to obtain the result using openCV or other libraries of functions, if it is possible</em> </p>
1
2016-08-20T15:17:53Z
39,507,217
<p>Updating: The problem seems to be this: calibration of the two cameras (IR and RGB) were not made with the same standards, both accepted as true.</p>
0
2016-09-15T09:13:20Z
[ "python", "computer-vision" ]
importance of virtual environment setup for django with python
39,055,728
<p>I am very much new to the process of development of a web-application with django, and i came across this setting up and using virtual environment for python. So i landed with some basic questions.</p> <ol> <li><p>What does this virtual environment exactly mean.</p></li> <li><p>Does that has any sort of importance in the development of web-application using django and python modules.</p></li> <li><p>do i have to worry about setting up of virtual environment each time in the development process.</p></li> </ol>
0
2016-08-20T15:22:07Z
39,055,867
<p>While I can't directly describe the experience with Django and virtual environments, I suspect its pretty similar to how I have been using Flask and virtualenv.</p> <ol> <li>Virtual environment does exactly what it says - where a environment is set up for you to develop your app (including your web app) that does not impact the libraries that you run on your machine. It creates a blank slate, so to speak, with just the core Python modules. You can use pip to install (there's documentation <a class='doc-link' href="http://stackoverflow.com/documentation/python/868/virtual-environments#t=201608201535106734742">post</a> on virtualenv in the stack overflow documention) new modules and freeze it into a requirements.txt file so that any users (including yourself) can see which external libraries are needed.</li> <li>It has a lot of importance because of the ability to track external libraries. For instance, I program between two machines and I have a virtual environment set up for either machine. The requirements.txt file allows me to install only the libraries I need with the exact versions of those libraries. This guarantees that when I am ready to deploy on a production machine, I know what libraries that I need. This prevents any modules that I have installed outside of a virtual environment from impacting the program that I run within a virtual environment.</li> <li>Yes and no. I think it is good practice to use a virtual environment for those above reasons and keeps your projects clean. Not to mention, it is not difficult to set up a virtual environment and maintain it. If you're just running a small script to check on an algorithm or approach, you may not need a virtual environment. But I would still recommend doing so to keep your runtime environments clean and well managed.</li> </ol>
2
2016-08-20T15:35:25Z
[ "python", "django", "virtualenv" ]
importance of virtual environment setup for django with python
39,055,728
<p>I am very much new to the process of development of a web-application with django, and i came across this setting up and using virtual environment for python. So i landed with some basic questions.</p> <ol> <li><p>What does this virtual environment exactly mean.</p></li> <li><p>Does that has any sort of importance in the development of web-application using django and python modules.</p></li> <li><p>do i have to worry about setting up of virtual environment each time in the development process.</p></li> </ol>
0
2016-08-20T15:22:07Z
39,055,882
<ol> <li>A virtual environment is a way for you to have multiple versions of python on your machine without them clashing with each other, each version can be considered as a development environment and you can have different versions of python libraries and modules all isolated from one another</li> <li><p>Yes it's very important, if you're working on an open source project for example and that project uses django 1.5, on the other hand you don't have a virtualenv and you installed django 1.9 it's almost impossible for you to contribute because you'll be having a lot of errors are supposed bugs, due to the fact that you aren't running the version of django that was used for the project, if you decide to uninstall and downgrade to that version, then you can't have django 1.9 anymore for your personal project. A virtualenv handles all this for you by enabling you to create seperate virtual (development) environments that aren't tied to each other and can be activated and deactivated easily when you're done.</p></li> <li><p>You're not forced to but you should, it's as easy as</p> <p><code>virtualenv newenv</code></p> <p><code>cd newenv</code></p> <p><code>source bin/activate # This current shell is now uses the virtual environment</code></p> <p>Moreover it's very important for testing, lets say you want to port a django web app from 1.5 to 1.9, you can easily do that by creating different virtualenv's and installing different versions of django. it's impossible to do this without uninstalling one version (except you want to mess with <code>sys.path</code> which isn't a good idea)</p></li> </ol>
2
2016-08-20T15:36:38Z
[ "python", "django", "virtualenv" ]
importance of virtual environment setup for django with python
39,055,728
<p>I am very much new to the process of development of a web-application with django, and i came across this setting up and using virtual environment for python. So i landed with some basic questions.</p> <ol> <li><p>What does this virtual environment exactly mean.</p></li> <li><p>Does that has any sort of importance in the development of web-application using django and python modules.</p></li> <li><p>do i have to worry about setting up of virtual environment each time in the development process.</p></li> </ol>
0
2016-08-20T15:22:07Z
39,055,884
<ol> <li><p>In most simple way, a virtual environment provides you a development environment independent of the host operating system. You can install and use necessary software in the /bin folder of the virtualenv, instead of using the software installed in the host machine. </p></li> <li><p>Python development generally depends of various libraries and dependencies. For eg. if you install latest version of pip using <code>sudo pip install django</code>, the django software of the specific version will be available system wide. Now, if you you need to use django of another version for a project, you can simply create a virtaulenv, install that version of django in it, and use, without bothering the django version installed in os.</p></li> <li>Yes, it is strongly recommended to setup separate virtualenv for each project. Once you are used to it, it will seem fairly trivial and highly useful for development, removing a lot of future headaches.</li> </ol>
1
2016-08-20T15:36:53Z
[ "python", "django", "virtualenv" ]
Writing list to file -- File written to not found
39,055,783
<p>I am using Python 3.</p> <p>This is a script that i am in the process of writing. It asks for a name/birthday, takes that input, and appends it into a list. The list is then written to another file.</p> <p>I have done research on this and can't find why it isn't working.</p> <p>Here is my code:</p> <pre><code>print("""Enter the name and birthday of the person like this: Adam 1/29 """) all_birthdays = [ "none so far" ] while True: birthday = input("&gt; ").upper() if birthday == "": break if birthday == "LIST": print(all_birthdays) if birthday not in all_birthdays: all_birthdays.append(birthday) else: print("This name/birthday is already known") birthday_list = open('test.txt','w') for bday in all_birthdays birthday_list.write("%s\n" %bday) </code></pre> <hr> <p><strong>SECOND EDIT:</strong> I added code ( bottom-most for loop and the create file ). It worked, but i can't seem to even find the file anywhere. Any help? How can i find it and open it? This code was found at: <a href="http://stackoverflow.com/questions/899103/writing-a-list-to-a-file-with-python">Writing a list to a file with Python</a> </p>
0
2016-08-20T15:27:21Z
39,055,918
<p>This line:</p> <pre><code> birthday = input("&gt; ").upper </code></pre> <p>Should be:</p> <pre><code> birthday = input("&gt; ").upper() </code></pre> <p>The former assigns the <code>upper</code> function to the variable <code>birthday</code> rather than the uppercase of the input string. </p>
0
2016-08-20T15:41:13Z
[ "python", "file", "loops", "python-3.x", "user-input" ]
Adding random numbers to a variable
39,055,820
<p>I'm looking for an output like this</p> <pre><code>Computer Choice: 5 Total: 5 Continue? Yes or No Computer Choice:2 Total: 7 </code></pre> <p>It adds up the random numbers every time it's created. This is the part I'm trying to get to work: </p> <pre><code> if player_bet &lt;= Player.total_money_amount: import random computer_choice = random.randint(1, 5) # Creates random number computer_total =+ computer_choice # Does not work. Also used += same result print('Computer choice: ', computer_choice) print('Total: ', computer_total) player_yes_or_no = input('Continue? Yes or No') if player_yes_or_no == 'Yes': pass </code></pre> <p>Current output </p> <pre><code>Computer Choice: 5 Total: 5 Continue? Yes or No Computer Choice: 2 Total: 2 </code></pre> <p>As you can see it does not add up the random int that where created. If I do += it gives an error </p> <p>Edit: I get the same output when I do </p> <pre><code> computer_total = 0 computer_total += computer_choice </code></pre>
-2
2016-08-20T15:30:43Z
39,055,862
<p>Change <code>=+</code> to <code>+=</code>. The way you currently have it you are reassigning the variable <code>computer_total</code> to the value of <code>computer_choice</code> rather than adding them. Also, make sure to initialize <code>computer_total</code> before you start your loop. </p>
0
2016-08-20T15:35:13Z
[ "python", "random" ]
Adding random numbers to a variable
39,055,820
<p>I'm looking for an output like this</p> <pre><code>Computer Choice: 5 Total: 5 Continue? Yes or No Computer Choice:2 Total: 7 </code></pre> <p>It adds up the random numbers every time it's created. This is the part I'm trying to get to work: </p> <pre><code> if player_bet &lt;= Player.total_money_amount: import random computer_choice = random.randint(1, 5) # Creates random number computer_total =+ computer_choice # Does not work. Also used += same result print('Computer choice: ', computer_choice) print('Total: ', computer_total) player_yes_or_no = input('Continue? Yes or No') if player_yes_or_no == 'Yes': pass </code></pre> <p>Current output </p> <pre><code>Computer Choice: 5 Total: 5 Continue? Yes or No Computer Choice: 2 Total: 2 </code></pre> <p>As you can see it does not add up the random int that where created. If I do += it gives an error </p> <p>Edit: I get the same output when I do </p> <pre><code> computer_total = 0 computer_total += computer_choice </code></pre>
-2
2016-08-20T15:30:43Z
39,055,960
<p>Please check the below code</p> <pre><code>#Added intilization. import random computer_choice = 0 computer_total = 0 for i in range(5): #Just added to make it running. You can add you checkings here computer_choice = random.randint(1, 5) computer_total += computer_choice print('Computer choice: ', computer_choice) print('Total: ', computer_total) #Changed input to raw_input player_yes_or_no = str(raw_input("Computer Choice - Yes or No ? ")) if player_yes_or_no == 'Yes': next </code></pre> <p>Output:</p> <pre><code>C:\Users\dinesh_pundkar\Desktop&gt;python demo.Py ('Computer choice: ', 2) ('Total: ', 2) Computer Choice - Yes or No ? Yes ('Computer choice: ', 5) ('Total: ', 7) Computer Choice - Yes or No ? Yes ('Computer choice: ', 2) ('Total: ', 9) Computer Choice - Yes or No ? Yes ('Computer choice: ', 2) ('Total: ', 11) Computer Choice - Yes or No ? Yes ('Computer choice: ', 2) ('Total: ', 13) </code></pre>
0
2016-08-20T15:44:44Z
[ "python", "random" ]
Adding random numbers to a variable
39,055,820
<p>I'm looking for an output like this</p> <pre><code>Computer Choice: 5 Total: 5 Continue? Yes or No Computer Choice:2 Total: 7 </code></pre> <p>It adds up the random numbers every time it's created. This is the part I'm trying to get to work: </p> <pre><code> if player_bet &lt;= Player.total_money_amount: import random computer_choice = random.randint(1, 5) # Creates random number computer_total =+ computer_choice # Does not work. Also used += same result print('Computer choice: ', computer_choice) print('Total: ', computer_total) player_yes_or_no = input('Continue? Yes or No') if player_yes_or_no == 'Yes': pass </code></pre> <p>Current output </p> <pre><code>Computer Choice: 5 Total: 5 Continue? Yes or No Computer Choice: 2 Total: 2 </code></pre> <p>As you can see it does not add up the random int that where created. If I do += it gives an error </p> <p>Edit: I get the same output when I do </p> <pre><code> computer_total = 0 computer_total += computer_choice </code></pre>
-2
2016-08-20T15:30:43Z
39,056,061
<p>You need to define <code>computer_total</code> outside of the loop first for it to work: </p> <pre><code>import random computer_total= 0 while True: computer_choice = random.randint(1, 5) # Creates random number computer_total += computer_choice print('Computer choice: ', computer_choice) print('Total: ', computer_total) player_yes_or_no = input('Continue? Yes or No\n') if player_yes_or_no == 'Yes': pass </code></pre> <p>I put the code inside an infinite loop for testing. Note that I import random outside of the loop, so that it is not re-imported unnecessarily every time the loop runs. I also added a newline to the end of the <code>input()</code> call.</p>
0
2016-08-20T15:55:48Z
[ "python", "random" ]
Appending grabbed frames from multiple video files into list of lists
39,055,823
<p>I am trying to appending a list with list of frames read from multiple video files. I have three video files,using VideoCapture class i am reading all the three files in a loop and trying to insert the read to a list. Finally I want a list of lists of frames read from the files. for example:</p> <p>frames from file1.avi:[1,2,3,4,5,6]</p> <p>frames from file2.avi:[1,2,3,4,5,6,7,8,9]</p> <p>frames from file3.avi: [1,2,3,4,5,6,7,8,9,10]</p> <p>I want the output as:[[1,2,3,4,5,6],[1,2,3,4,5,6,7,8,9],[1,2,3,4,5,6,7,8,9,10]]</p> <p>I am getting the output as [1,2,3,4,5,6,1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8,9,10]</p> <p>below is my code</p> <pre><code>videoList=glob.glob(r'C:\Users\chaitanya\Desktop\Thesis\*.avi') indices=[] for path in videoList: cap = cv2.VideoCapture(path) while(cap.isOpened()): ret,frame=cap.read() if not ret: break indices.append(cap.get(1)) cap.release() cv2.destroyAllWindows() </code></pre>
0
2016-08-20T15:31:07Z
39,061,540
<blockquote> <p>I want the output as:[[1,2,3,4,5,6],[1,2,3,4,5,6,7,8,9],[1,2,3,4,5,6,7,8,9,10]]</p> </blockquote> <p>You only have one list <code>indices=[]</code>. If you want a "list of lists of frames" you should extend your code by a second list in the for loop:</p> <pre class="lang-py prettyprint-override"><code>videoList=glob.glob(r'C:\Users\chaitanya\Desktop\Thesis\*.avi') videoindices = [] for path in videoList: cap = cv2.VideoCapture(path) #second List indices = [] while(cap.isOpened()): ret,frame=cap.read() if not ret: break # append the frames to the secound list indices.append(cap.get(1)) cap.release() # append the list of frames to the list videoindices.append(indices) print(videoindices) </code></pre> <p>The code is untested. I will test it later and extend my answer by the <code>print(videoindices)</code> output.</p>
1
2016-08-21T06:44:35Z
[ "python", "list", "opencv" ]
"403 Forbidden" when use python urlib package to download the image
39,055,838
<p>i am new to urllib package. i try to download all the images in website "<a href="http://www.girl-atlas.com/album/576545de58e039318beb37f6" rel="nofollow">http://www.girl-atlas.com/album/576545de58e039318beb37f6</a>" the question is: when i copy the the url of an image, and pass the url to a browser, i will get an error <strong>"403 Forbidden"</strong>. However, when i right click an image in the browser, and choose to open the image in a new window, this time, i will get the image in the new window. the problem is: how the urlib simulates the second way?</p>
-2
2016-08-20T15:32:23Z
39,056,014
<p>It is forbidden to use the URLs outside a broweser. To ensure this, browsers send always a referer, the site, from which the image is loaded. If a browser would be written in Python, this would look like this:</p> <pre><code>import urllib.request opener = urllib.request.URLopener() opener.addheader('Referer', 'http://www.girl-atlas.com/album/576545de58e039318beb37f6') image = opener.open('http://girlatlas.b0.upaiyun.com/41/20121222/234720feaa1fc912ba4e.jpg!lrg') data = image.read() image.close() </code></pre>
0
2016-08-20T15:49:55Z
[ "python", "web-crawler" ]
How to start IPython kernel and connect using ZMQ sockets?
39,055,839
<p>I am working on a frontend to IPython in C++ (Qt).</p> <p>I managed to embed Python in my application and retrieve plots and show these in my GUI. Now I want to start an IPython kernel and connect to it through ZMQ sockets.</p> <p>I found a <a href="https://jupyter-client.readthedocs.io/en/latest/messaging.html" rel="nofollow">description</a> for the communication protocol with IPython kernels. However, it doesn't say <strong>anywhere</strong> which ports to connect to. So it's nice and dandy to have a communication protocol, but totally useless if I don't know which ports to use. </p> <p>The documentation mentions 'kernel specs' and tells me to use the <code>jupyter kernelspec list</code> command. This indeed shows me one directory, which only contains two files: logo-32x32.png and logo-64x64.png ...</p> <p>How do I find the ports I need to connect to, to communicate with my IPython kernels?</p> <p>I start my IPython kernel by running the following Python code from my C++ Qt app:</p> <pre><code>import IPython IPython.start_kernel(argv=[]) </code></pre>
0
2016-08-20T15:32:30Z
39,062,831
<p>It turns out Thomas K was right. The right approach to start an IPython/Jupyter kernel in a different process is: (with python3 as example)</p> <pre><code>import jupyter_client kernel_manager, kernel_client = jupyter_client.start_new_kernel(kernel_name='python3') </code></pre> <p>When I initially tried this, I got a permission error. This was fixed by installing the python3 kernel spec (apparently Jupyter does not do this automatically...):</p> <pre><code>python3 -m ipykernel install --user </code></pre> <p>And then you can get the ports by</p> <pre><code>print(kernel_manager.get_connection_info()) </code></pre> <p>It should be possible to use these ports to connect to the kernel via zero-mq. However, the <code>kernel_client</code> exposes a few methods to communicated with the kernel, so it may be easier to use that approach...</p>
0
2016-08-21T09:37:29Z
[ "python", "c++", "qt", "ipython", "zeromq" ]
How to get all the columns from id and filter to specific column? odoo9
39,056,108
<p>I am getting the id of a customer by</p> <pre><code>customer = context.get('partner_id') print customer #output #6 </code></pre> <p>Now i want to fetch all the values of all columns from <code>res.partner</code> where <code>id == 6</code></p> <p>This will will give me many a recordset i guess </p> <p>How do i filter the recordset so i can get the value which i want to work with.</p> <p>Or if it is possible can i get the specific columns value not all. (that would be great)</p> <p>If possible tell me how to do it in <code>old_api</code> and <code>new_api</code></p>
0
2016-08-20T16:00:22Z
39,056,143
<p><strong>Old api</strong></p> <pre><code>self.pool.get('res.partner').search(cr, uid, [('id', '=', customer)]) </code></pre> <p>This would return a list of id's that matched the search so you have to call <code>browse</code> to actually get the records</p> <p><strong>New api</strong></p> <pre><code>self.env['res.partner'].search([('id', '=', customer)]) </code></pre> <p>to get only a specific column, instead of all columns use the <code>search_read</code> method it's very similar to search only that it takes a second argument which is a list of the attributes you're interested in and it returns a list of dictionaries instead of a record sets. so let's say we're only interested in the column <code>value</code></p> <pre><code>self.env['res.partner'].search_read([('id', '=', customer)], ['value']) </code></pre> <p>your result should look like this</p> <pre><code>[{'id': 1, 'value': 'some value'}, ...] </code></pre>
2
2016-08-20T16:02:48Z
[ "python", "openerp", "odoo-9" ]
How to create a dynamic label colour in Tkinter?
39,056,179
<p>I'm trying to create a GUI BMI calculator for summer work. I want to implement a feature where once you're BMI is calculated, the colour of the label changes depending on your BMI.</p> <p>My current code reads:</p> <pre><code>self.AnswerlabelVariable = tkinter.StringVar() #Creates a variable used later for changing the label text Answerlabel = tkinter.Label(self, text=u" ", textvariable=self.AnswerlabelVariable, anchor='w', fg="black",bg="light grey") #Creates a label Answerlabel.grid(column=1,row=4, sticky='EW') #Defines where the label is and how it will move ...the calculation for the BMI happens... if float(BMI2)&lt;int(17): #Creates an 'if' statement self.MessagelabelVariable.set("You are underweight!") #Changes a label to display a new message. self.AnswerlabelVariable.set(fg='black', bg='blue') #Changes a labels colour (WIP WIP WIP) </code></pre> <p>While the label changes it's text, the colour does not change and instead generates an error message;</p> <pre><code>line 56, in OnCalculateButtonClick self.AnswerlabelVariable.set(fg='black', bg='blue') #Changes a labels colour (WIP WIP WIP) TypeError: set() got an unexpected keyword argument 'fg' </code></pre> <p>Can anybody help?</p>
-1
2016-08-20T16:05:43Z
39,056,234
<p>I've never used the StringVar class but whenever I wanted to change the color (or any parameter) of a Label, I'd just do it directly.</p> <pre><code>Answerlabel['fg'] = 'black' </code></pre>
1
2016-08-20T16:12:20Z
[ "python", "tkinter" ]
How to create a dynamic label colour in Tkinter?
39,056,179
<p>I'm trying to create a GUI BMI calculator for summer work. I want to implement a feature where once you're BMI is calculated, the colour of the label changes depending on your BMI.</p> <p>My current code reads:</p> <pre><code>self.AnswerlabelVariable = tkinter.StringVar() #Creates a variable used later for changing the label text Answerlabel = tkinter.Label(self, text=u" ", textvariable=self.AnswerlabelVariable, anchor='w', fg="black",bg="light grey") #Creates a label Answerlabel.grid(column=1,row=4, sticky='EW') #Defines where the label is and how it will move ...the calculation for the BMI happens... if float(BMI2)&lt;int(17): #Creates an 'if' statement self.MessagelabelVariable.set("You are underweight!") #Changes a label to display a new message. self.AnswerlabelVariable.set(fg='black', bg='blue') #Changes a labels colour (WIP WIP WIP) </code></pre> <p>While the label changes it's text, the colour does not change and instead generates an error message;</p> <pre><code>line 56, in OnCalculateButtonClick self.AnswerlabelVariable.set(fg='black', bg='blue') #Changes a labels colour (WIP WIP WIP) TypeError: set() got an unexpected keyword argument 'fg' </code></pre> <p>Can anybody help?</p>
-1
2016-08-20T16:05:43Z
39,056,242
<p>You need to use the <code>config()</code> method of the label to modify its <code>fg</code> and <code>bg</code> properties, like this:</p> <pre><code>self.Answerlabel.config(fg='black', bg='blue') #Changes a labels colour </code></pre>
1
2016-08-20T16:13:27Z
[ "python", "tkinter" ]
Text Based Mechanics in Python: Class, Dictionary, or List?
39,056,208
<p>I'm fairly new to coding in python (3) as somewhat of a hobby, but having fun playing around with some game mechanics without worrying about GUI. I'm currently working on a civilization-type text based game whose foundations lie in an old excel document. It's fairly centred on math and logic, which I think made for a pretty easy but in-depth set of mechanics.</p> <p>Anyway, the game allows for researching tech, producing buildings, growing citizens, gathering culture etc. One thing I'm struggling with is the military system.</p> <p>I have a number of different units for the player to produce. Let's say each unit has a name, strength and resilience (eg. 'Archer', '10', '80'). Wars are based on total player strength (I can calculate this). After each war, the unit's strength decreases by it's resilience ie. this Archer would decrease to 80% of its original strength after a war to strength 8.</p> <p>However, I'm having trouble working out how the user can create units in a fashion that allows this mechanic. I originally used a Unit() class (with different units eg. archer, spearman as objects) with a 'quantity' argument alongside name/strength/resilience for amount of units built, but every time I ran the function to calculate the effect of resilience I realised I was affecting not only currently produced units but all future versions of the unit too. I was running something like the following:</p> <pre><code>class Unit(): def __init__(self, name, quantity, strength, resilience) self.name = name self.quantity = quantity self.strength = strength self.resilience = resilience archer = Unit('archer', 0, 10, 80) </code></pre> <p>etc...</p> <p>Each time the user built a unit, the 'quantity' would increase. However I've come to understand that it's probably this method of coding is probably what is limiting me. Reading other threads tells me I should be aiming to not store object data in such a way, right?</p> <p>I've been playing around and researching and I can't seem to get my head around the solution (which I'm sure is there). I'm having trouble finding the right way of storing each unit's basic data (name, strength, resilience) while allowing the user to produce multiple, unique copies of each unit. Each unit should be a class? A sub class? It should be stored in a dictionary? A list? </p> <p>I apologise for the lack of code in this post, but I don't exactly have erroneous code - I'm just lacking the logic and python knowledge to find the right systems to make this work properly. Been playing with dictionaries, lists, loops, inherited classes, but I just can't get it right.</p> <p>How would one create multiple archers who each take damage, without affecting future archers that might be produced?</p> <p>Thanks if anyone can suggest something. Other than this I'm having a lot of fun coding in python!</p>
0
2016-08-20T16:09:46Z
39,056,390
<p>The point of a class is that it lets you create many <em>instances</em> of that class. You don't need to (and can't/shouldn't) subclass <code>Unit</code> for each unit. You simply need to <em>instantiate</em> the <code>Unit</code> class:</p> <pre><code> archer1= Unit('archer', 0, 10, 80) archer2= Unit('archer', 0, 10, 80) </code></pre> <p>Now you have two separate archer units with separate stats. If one of them fights in a war and its attributes change, the other won't be affected:</p> <pre><code> archer1.strength= 0 print(archer2.strength) # prints 10 </code></pre> <p>Of course, this means you don't need the <code>quantity</code> attribute and you need to store all units in some kind of data structure like a list:</p> <pre><code> all_my_archers= [archer1, archer2] #create a 3rd archer all_my_archers.append(Unit('archer', 0, 10, 80)) </code></pre> <hr> <p>This is less important, but you should also consider subclassing <code>Unit</code> to create an <code>Archer</code> class:</p> <pre><code>class Unit: def fight_war(self): self.strength= self.strength * self.resilience / 100.0 class Archer(Unit): name= 'archer' strength= 10 resilience= 80 </code></pre> <p>Since all archer units start with the same stats (I assume), this will eliminate the need to specify the <code>strength</code> and <code>resilience</code> every time you create a new archer unit (you can just do <code>archer4= Archer()</code> now), and you can still change a unit's stats without affecting other units.</p>
1
2016-08-20T16:31:07Z
[ "python", "text-based" ]
Text Based Mechanics in Python: Class, Dictionary, or List?
39,056,208
<p>I'm fairly new to coding in python (3) as somewhat of a hobby, but having fun playing around with some game mechanics without worrying about GUI. I'm currently working on a civilization-type text based game whose foundations lie in an old excel document. It's fairly centred on math and logic, which I think made for a pretty easy but in-depth set of mechanics.</p> <p>Anyway, the game allows for researching tech, producing buildings, growing citizens, gathering culture etc. One thing I'm struggling with is the military system.</p> <p>I have a number of different units for the player to produce. Let's say each unit has a name, strength and resilience (eg. 'Archer', '10', '80'). Wars are based on total player strength (I can calculate this). After each war, the unit's strength decreases by it's resilience ie. this Archer would decrease to 80% of its original strength after a war to strength 8.</p> <p>However, I'm having trouble working out how the user can create units in a fashion that allows this mechanic. I originally used a Unit() class (with different units eg. archer, spearman as objects) with a 'quantity' argument alongside name/strength/resilience for amount of units built, but every time I ran the function to calculate the effect of resilience I realised I was affecting not only currently produced units but all future versions of the unit too. I was running something like the following:</p> <pre><code>class Unit(): def __init__(self, name, quantity, strength, resilience) self.name = name self.quantity = quantity self.strength = strength self.resilience = resilience archer = Unit('archer', 0, 10, 80) </code></pre> <p>etc...</p> <p>Each time the user built a unit, the 'quantity' would increase. However I've come to understand that it's probably this method of coding is probably what is limiting me. Reading other threads tells me I should be aiming to not store object data in such a way, right?</p> <p>I've been playing around and researching and I can't seem to get my head around the solution (which I'm sure is there). I'm having trouble finding the right way of storing each unit's basic data (name, strength, resilience) while allowing the user to produce multiple, unique copies of each unit. Each unit should be a class? A sub class? It should be stored in a dictionary? A list? </p> <p>I apologise for the lack of code in this post, but I don't exactly have erroneous code - I'm just lacking the logic and python knowledge to find the right systems to make this work properly. Been playing with dictionaries, lists, loops, inherited classes, but I just can't get it right.</p> <p>How would one create multiple archers who each take damage, without affecting future archers that might be produced?</p> <p>Thanks if anyone can suggest something. Other than this I'm having a lot of fun coding in python!</p>
0
2016-08-20T16:09:46Z
39,056,510
<p>For me, especially when you are creating a game, sub-classing is a really good way of writing good code. Mostly because you can implement independent features on your subclasses. For example every <code>Unit</code> may have the same movement mechanism, but an <code>Archer Unit</code> might defer in the attack process. To talk code:</p> <pre><code>class Unit(object): def __init__(self, movement_speed=10, health=100): self.movement_speed = movement_speed self.health = health self.position = 0 def move(self): self.position += movement_speed def get_hit(self, damage=0): self.health -= damage #etc class Archer(Unit): def __init__(self, arrows=10): super(self.__class__, self).init() self.arrows = 10 # Archer has all the Unit methods def attack(self, other_unit_instance): # Here you can check if he is in range, etc other_unit_instance.get_hit(damage=1) self.arrows -= 1 </code></pre>
0
2016-08-20T16:44:56Z
[ "python", "text-based" ]
Python regex get substring after preceding substring match
39,056,227
<p>Text has no spaces, so I cannot split at all and use indexing on a list of strings.</p> <p>The pattern I am looking for is:</p> <p><code>check=</code></p> <p>It is followed by a number and encoded querystring items (apache logfile) and is on every line of the file twice. I want output that gives me just what follows <code>check=</code></p> <p>For instance, the string in a line looks like:</p> <pre><code>11.249.222.103 - - [15/Aug/2016:13:17:56 -0600] "GET /next2/120005079807?check=37593467%2CCOB&amp;check=37593378%2CUAP&amp;box=match&amp;submit=Next HTTP/1.1" 500 1633 "https://mvt.squaretwofinancial.com/newmed/?button=All&amp;submit=Submit" "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:45.0) Gecko/20100101 Firefox/45.0" </code></pre> <p>And I need to fetch <code>37593467</code> and <code>37593378</code> in this case.</p>
0
2016-08-20T16:11:22Z
39,056,290
<p>Please check this code.</p> <pre><code>import re text = '''11.249.222.103 - - [15/Aug/2016:13:17:56 -0600] "GET /next2/120005079807?check=37593467%2CCOB&amp;check=37593378%2CUAP&amp;box=match&amp;submit=Next HTTP/1.1" 500 1633 "https://mvt.squaretwofinancial.com/newmed/?button=All&amp;submit=Submit" "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:45.0) Gecko/20100101 Firefox/45.0"''' for match in re.findall("check=(\d+)",text): print 'Found "%s"' % match </code></pre> <p>Output:</p> <pre><code>C:\Users\dinesh_pundkar\Desktop&gt;python demo.py Found "37593467" Found "37593378" </code></pre> <p>Couple of URLs for help :</p> <ul> <li><a href="http://www.pyregex.com/" rel="nofollow">Python regex Tester</a></li> <li><a href="https://docs.python.org/2/library/re.html" rel="nofollow">re module</a></li> </ul>
2
2016-08-20T16:19:17Z
[ "python", "regex" ]
why it report a error RequirementParseError invalid requirement parse error at '' at sometimes when using newest paramiko 2.0.2 of python 2.7.12
39,056,292
<ol> <li><p>I use python 2.7.12 and newest paramiko 2.0.2, and run a script which ssh login many linux server concurrently.</p> <p>sometimes it runs very well, but sometimes it will report the following weird error:</p> <p>**no handers could be found for logger 'paramiko.transport'</p> <p>.....</p> <p>Exception in thread Thread-2</p> <p>.....</p> <p>.....</p> <p>RequirementParseError invalid requirement parse error at ''**</p></li> <li><p>the script is shown in below:</p> <p>anybody can help me?</p> <p>Thanks in advance with for any help.</p> <pre><code>#! ~/python2.7.12/bin/python import paramiko import threading def ssh2(ip,username,passwd,cmd): try: ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(ip,22,username,passwd,timeout=5) for m in cmd: stdin, stdout, stderr = ssh.exec_command(m) out = stdout.readlines() for o in out: print o, print '%s\tOK\n'%(ip) ssh.close() except : print '%s\tError\n'%(ip) if __name__=='__main__': cmd = ['uptime','free -g'] username = "usera" passwd = "wordad" threads = [] print "Begin......" for i in range(10,154): ip = '10.16.2.'+str(i) a=threading.Thread(target=ssh2,args=(ip,username,passwd,cmd)) threads.append(a) for i in threads: i.start() for i in threads: i.join() </code></pre></li> </ol>
0
2016-08-20T16:19:18Z
39,477,206
<ol> <li>You should <a href="http://stackoverflow.com/questions/19152578/no-handlers-could-be-found-for-logger-paramiko">set up a logger for 'paramiko.transport'</a>.</li> <li>Have you found a solution? I have exactly the same problem when trying to connect concurrently.</li> </ol>
-1
2016-09-13T19:00:08Z
[ "python", "paramiko" ]
why it report a error RequirementParseError invalid requirement parse error at '' at sometimes when using newest paramiko 2.0.2 of python 2.7.12
39,056,292
<ol> <li><p>I use python 2.7.12 and newest paramiko 2.0.2, and run a script which ssh login many linux server concurrently.</p> <p>sometimes it runs very well, but sometimes it will report the following weird error:</p> <p>**no handers could be found for logger 'paramiko.transport'</p> <p>.....</p> <p>Exception in thread Thread-2</p> <p>.....</p> <p>.....</p> <p>RequirementParseError invalid requirement parse error at ''**</p></li> <li><p>the script is shown in below:</p> <p>anybody can help me?</p> <p>Thanks in advance with for any help.</p> <pre><code>#! ~/python2.7.12/bin/python import paramiko import threading def ssh2(ip,username,passwd,cmd): try: ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(ip,22,username,passwd,timeout=5) for m in cmd: stdin, stdout, stderr = ssh.exec_command(m) out = stdout.readlines() for o in out: print o, print '%s\tOK\n'%(ip) ssh.close() except : print '%s\tError\n'%(ip) if __name__=='__main__': cmd = ['uptime','free -g'] username = "usera" passwd = "wordad" threads = [] print "Begin......" for i in range(10,154): ip = '10.16.2.'+str(i) a=threading.Thread(target=ssh2,args=(ip,username,passwd,cmd)) threads.append(a) for i in threads: i.start() for i in threads: i.join() </code></pre></li> </ol>
0
2016-08-20T16:19:18Z
40,035,095
<p>This workaround worked for me. Change from a </p> <pre><code>concurrent.futures.ThreadPoolExecutor </code></pre> <p>to a:</p> <pre><code>concurrent.futures.ProcessPoolExecutor </code></pre> <p><a href="https://github.com/couchbaselabs/mobile-testkit/issues/209#issuecomment-253708295" rel="nofollow">See full context</a></p>
0
2016-10-14T04:46:46Z
[ "python", "paramiko" ]
How can I use a postactivate script using Python 3 venv?
39,056,356
<p>I'm using <code>venv</code> (used <code>pyvenv</code> to create the environment) and would like to set up environment variables here, but <code>postactivate</code> looks like a <code>virtualenv</code> thing. Can this be done with <code>venv</code>?</p>
0
2016-08-20T16:27:30Z
39,056,653
<p><code>venv</code> has the <code>activate</code> script which you can modify to add your environment variables.</p> <p>I would add the variables at the bottom, making a nice comment block to clearly separate the core functionality and my custom variables.</p>
2
2016-08-20T16:58:32Z
[ "python", "python-3.x", "python-venv" ]
Python 3 + Selenium: How to find this element by xpath?
39,056,407
<pre><code>https://www.facebook.com/friends/requests/?fcref=jwl&amp;outgoing=1 </code></pre> <p>I want to click "See more request" in the "friend request sent"</p> <pre><code>&lt;div id="outgoing_reqs_pager_57b87e5793eb04682598549" class="clearfix mtm uiMorePager stat_elem _646 _52jv"&gt; &lt;div&gt; &lt;a class="pam uiBoxLightblue _5cz uiMorePagerPrimary" role="button" href="#" ajaxify="/friends/requests/outgoing/more/?page=2&amp;page_size=10&amp;pager_id=outgoing_reqs_pager_57b87e5793eb04682598549" rel="async"&gt;See More Requests&lt;/a&gt; &lt;span class="uiMorePagerLoader pam uiBoxLightblue _5cz"&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>I used this code but it doesn't work.</p> <pre><code>driver.find_element_by_xpath("//*[contains(@id, 'outgoing_reqs_pager')]").click() </code></pre> <p>I got the error: </p> <blockquote> <p>Message: Element is not clickable at point (371.5, 23.166671752929688). Other element would receive the click: </p> </blockquote> <pre><code>&lt;input aria-owns="js_8" class="_1frb" name="q" value="" autocomplete="off" placeholder="Search Facebook" role="combobox" aria-label="Search" aria-autocomplete="list" aria-expanded="false" aria-controls="js_5" aria-haspopup="true" type="text"&gt; </code></pre> <p>How to click it ? Thank you :)</p>
1
2016-08-20T16:33:20Z
39,056,603
<p>Actually here you are locating element by using partial id match, so may be this xpath is not unique and return multiple element.</p> <p><code>find_element</code> always returns first element by matching locator, may be it's return other element which is overlayed by other element instead of desire element that's why you are in trouble.</p> <p>Here you should try using <code>link_text</code> to locate desire element by using their text as below :-</p> <pre><code>driver.find_element_by_link_text("See More Requests").click() </code></pre> <p>Or using <code>partial_link_text</code> as below :-</p> <pre><code>driver.find_element_by_partial_link_text("See More Requests").click() </code></pre> <p><strong>Edited1</strong> :- If you're still getting same exception you need to scroll first to reach that element using <code>exexute_script()</code> then click as below :-</p> <pre><code>link = driver.find_element_by_partial_link_text("See More Requests") #now scroll to reach this link driver.exexute_script("arguments[0].scrollIntoView()", link) #now click on this link link.click() </code></pre> <p>Or if you don't want to scroll, you can click using <code>exexute_script</code> without scrolling as below :-</p> <pre><code>link = driver.find_element_by_partial_link_text("See More Requests") #now perform click using javascript driver.exexute_script("arguments[0].click()", link) </code></pre> <p><strong>Edited2</strong> :- If you want to click this link inside while loop until it appears, you need to implement <code>WebDriverWait</code> to wait until it present next time as below :-</p> <pre><code>from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC wait = WebDriverWait(driver, 10) # now find link link = wait.until(EC.presence_of_element_located((By.LINK_TEXT, "See More Requests"))) #now perform click one of these above using java_script </code></pre>
1
2016-08-20T16:53:48Z
[ "python", "html", "selenium", "xpath" ]
Apk file build using buildozer closes as soon as i open it
39,056,409
<p>I try to make a simple hello world app for android using python, kivy and buildozer.</p> <p>my hello.py file is</p> <pre><code>from kivy.app import App from kivy.uix.button import Label class Hello2App(App): def build(self): return Label() if __name__=="__main__": Hello2App().run() </code></pre> <p>My hello.kv file</p> <pre><code>&lt;Label&gt;: text: 'Hello World!' </code></pre> <p>I use buildozer in ubuntu to compile apk. Sudo buildozer android debug deploy</p> <p>do i need to apply looping like we do in pygame and Tkinter to show gui or window</p>
0
2016-08-20T16:33:27Z
39,057,484
<p>Your Python script must be named main.py. If you check the error that you are getting it would read something like "Unable to find main.py". Just try renaming the file from hello.py to main.py and build again.</p>
1
2016-08-20T18:34:36Z
[ "android", "python", "kivy", "buildozer" ]
Debug Flask(Python) web application in Visual studio code
39,056,448
<p>How do I configure visual studio code to debug Flask(Python) web application ?</p> <p>For example when I set debugger on view function it should allow me to step through that function when we hit that route in browser.</p> <p>I have already installed python extension in Visual studio code.</p>
0
2016-08-20T16:37:54Z
39,059,501
<p>I don't use VS for python development. However, Flask has really nice debugging option, that allows you to debug from browser. This is not a solution for VS but a workaround. </p> <p>When you define your app pass <code>debug = true</code> parameter to enable debugging mode. Then you can debug your code from browser.</p> <pre><code>app = Flask(__name__) app.config['DEBUG'] = True </code></pre> <p>more information can be found <a href="http://flask.pocoo.org/docs/0.11/config/" rel="nofollow">here</a></p>
0
2016-08-20T23:10:29Z
[ "python", "vscode", "vscode-extensions" ]
Basic DFS space usage
39,056,488
<p>I have a basic question related to space usage, and I'm using DFS as an example. I'm not sure if the space usage in these few implementations are the same, or if a few actually differ. My interpretation of space usage is directly correlated to what the function allocates. <strong>Can anyone help me verify the space usage of these few examples I made? This is a question on space complexity, and not time + functionality</strong></p> <p>Example 1: We allocate a dictionary that will store N nodes. I'm positive this one allocates O(N) space.</p> <pre><code>class Node: def __init__(self, children): self.children = children def getChildren(self): return self.children def dfs(start): stack = [] visited = {} stack.append(start) while(len(stack) &gt; 0): node = stack.pop() if(node not in visited): visited[node] = True for child in node.getChildren(): stack.append(child) </code></pre> <p>Example 2: We don't allocate anything in the dfs function, but instead we are given a flag to set on the Node. We aren't allocating anything in the dfs function so it is O(1) space usage.</p> <pre><code>class Node: def __init__(self, children): self.children = children self.visited = False def getChildren(self): return self.children def getVisited(self): return self.visited def setVisited(self, visit): self.visited = visit def dfs(start): stack = [] stack.append(start) while(len(stack) &gt; 0): node = stack.pop() if(!node.getVisited()): node.setVisited(True) for child in node.getChildren(): stack.append(child) </code></pre> <p>Example 3: We have an object Node that can be manipulated, but does not have a flag attribute up front. DFS is manually creating a flag on each Node, and thus allocating O(N) space. </p> <pre><code>class Node: def __init__(self, children): self.children = children def getChildren(self): return self.children def dfs(start): stack = [] stack.append(start) while(len(stack) &gt; 0): node = stack.pop() if(node.visited is not None): node.visited = True for child in node.getChildren(): stack.append(child) </code></pre>
0
2016-08-20T16:42:39Z
39,056,704
<p><a href="https://en.wikipedia.org/wiki/DSPACE" rel="nofollow">Space complexity</a> is not determined by <em>where</em> the space gets allocated but by <em>how much</em> space (memory) is required to hold a given data structure in relation to the number of objects to be processed by an algorithm. </p> <p>In your examples all data structures require O(N) space (N = # of nodes) </p>
1
2016-08-20T17:04:18Z
[ "python", "performance", "memory" ]
How to make python detect audio from an application?
39,056,494
<p>I'm trying to make something that runs when audio is detected from a windows application. Is there any way to do this using python.</p> <p>I'm running on python 2.7.12 but I'm willing to update if necessary. I'm also fine with detecting any sound at all coming from the computer.</p> <p>Thanks a lot.</p>
-2
2016-08-20T16:43:38Z
39,060,479
<p>take a look at <a href="http://python-sounddevice.readthedocs.io/en/0.3.4/#sounddevice.RawInputStream" rel="nofollow">http://python-sounddevice.readthedocs.io/en/0.3.4/#sounddevice.RawInputStream</a> You could use this to detect audio to and from the sound card of the computer.</p> <p>The particular class is one way to get sound from a mic. </p> <p>from sounddevice library</p> <p>class sounddevice.RawInputStream(samplerate=None, blocksize=None, device=None, channels=None, dtype=None, latency=None, callback=None, finished_callback=None, clip_off=None, dither_off=None, never_drop_input=None, prime_output_buffers_using_stream_callback=None)</p> <p>or you could filter the output of the sound card to know when audio signal is being sent.</p> <p>class sounddevice.OutputStream(samplerate=None, blocksize=None, device=None, channels=None, dtype=None, latency=None, callback=None, finished_callback=None, clip_off=None, dither_off=None, never_drop_input=None, prime_output_buffers_using_stream_callback=None)</p>
0
2016-08-21T02:59:31Z
[ "python", "python-2.7" ]
How to add multiple key-value pair to Dictionary at once?
39,056,654
<p>I have a dictionary <code>dict</code> having some elements like:</p> <p><code>dict={'India':'Delhi','Canada':'Ottawa'}</code></p> <p>now I want to add multiple dictionary key-value pair to a <code>dict</code> like:</p> <p><code>dict= {'India':'Delhi','Canada':'Ottawa','USA':'Washington','Brazil':'Brasilia','Australia':'Canberra'}</code></p> <p>Is there any possible way to do this? Because I don't want to add elements one after the another.</p>
0
2016-08-20T16:58:48Z
39,056,673
<p>You're looking for the <code>dict.update</code> method, documented <a href="https://docs.python.org/2/library/stdtypes.html#dict.update" rel="nofollow">here</a>. </p>
0
2016-08-20T17:01:06Z
[ "python" ]
How to add multiple key-value pair to Dictionary at once?
39,056,654
<p>I have a dictionary <code>dict</code> having some elements like:</p> <p><code>dict={'India':'Delhi','Canada':'Ottawa'}</code></p> <p>now I want to add multiple dictionary key-value pair to a <code>dict</code> like:</p> <p><code>dict= {'India':'Delhi','Canada':'Ottawa','USA':'Washington','Brazil':'Brasilia','Australia':'Canberra'}</code></p> <p>Is there any possible way to do this? Because I don't want to add elements one after the another.</p>
0
2016-08-20T16:58:48Z
39,056,679
<p>Use <code>update()</code> method. </p> <pre><code>d= {'India':'Delhi','Canada':'Ottawa'} d.update({'USA':'Washington','Brazil':'Brasilia','Australia':'Canberra'}) </code></pre> <p>PS: Naming your dictionary as <code>dict</code> is a horrible idea. It replaces the built in <code>dict</code>.</p>
0
2016-08-20T17:01:30Z
[ "python" ]
Python selenium "about:blank&utm_content=firstrun" error
39,056,722
<p>I've being trying so hard to figure out what's going on with my code, but I couldn't help. Whenever I run my program I got this error in the picture bellow. I'm using python 3.4.4 and selenium last version of it. <br><br> Windows 10</p> <pre><code>from selenium import webdriver from selenium.webdriver.common.keys import Keys driver = webdriver.Firefox() driver.get("http://www.python.org") assert "Python" in driver.title elem = driver.find_element_by_name("q") elem.clear() elem.send_keys("pycon") elem.send_keys(Keys.RETURN) assert "No results found." not in driver.page_source driver.close() </code></pre> <p><a href="http://i.stack.imgur.com/l6hSz.png" rel="nofollow">Error Picture</a></p>
3
2016-08-20T17:06:21Z
39,060,403
<p>You didn't mention what your FF version is, I assume it's one of the latest. Anyways you need to use FF below 47 or time to switch to MarionetteDriver </p> <p>here is some useful information <a href="http://stackoverflow.com/questions/37693106/selenium-2-53-not-working-on-firefox-47">Selenium 2.53 not working on Firefox 47</a></p> <p>Hope it helps, cheers. </p>
3
2016-08-21T02:41:22Z
[ "python", "selenium", "selenium-webdriver" ]
TypeError: context must be specified" in zmq unpickling
39,056,746
<p>I am trying to create a very simple chat. Using the PyZMQ library. And since sockets are not threadsafe I am using two sockets and one thread running on each. One checking for incoming messages, and one to send messages. </p> <p>But my program is giving me, error messages:</p> <pre><code> Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; File "C:\Python27\lib\multiprocessing\forking.py", line 381, in main self = load(from_parent) File "C:\Python27\lib\pickle.py", line 1384, in load Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; File "C:\Python27\lib\multiprocessing\forking.py", line 381, in main self = load(from_parent) File "C:\Python27\lib\pickle.py", line 1384, in load return Unpickler(file).load() File "C:\Python27\lib\pickle.py", line 864, in load return Unpickler(file).load() File "C:\Python27\lib\pickle.py", line 864, in load dispatch[key](self) File "C:\Python27\lib\pickle.py", line 1089, in load_newobj dispatch[key](self) File "C:\Python27\lib\pickle.py", line 1089, in load_newobj obj = cls.__new__(cls, *args) File "zmq\backend\cython\socket.pyx", line 279, in zmq.backend.cython.socket.Socket.__cinit__ (zmq\backend\cython\socket.c:3456) TypeError: context must be specified obj = cls.__new__(cls, *args) File "zmq\backend\cython\socket.pyx", line 279, in zmq.backend.cython.socket.Socket.__cinit__ (zmq\backend\cython\socket.c:3456) TypeError: context must be specified </code></pre> <p>I can not figure out why I am getting them, or how to solve it. </p> <p>Also is my logic wrong here?:</p> <blockquote> <p>We start the server which creates a socket and binds it to a port. Then It listens to that sockets for messages/connections. Then we create another socket and binds it to the same port. We create a new thread that makes it so that we wait for messages to be recieved on the first socket to then be sent to the second one. Then we have a client who connects to the first socket. We create a new thread for it so it can listen on the other socket for incoming messages, and thus it can use the first thread to send messages through the first socket.</p> </blockquote> <p><strong>server.py</strong></p> <pre><code>from communication import Communication from multiprocessing import Process import zmq import random import sys import time if __name__ == '__main__': if len(sys.argv) &gt; 1: port = sys.argv[1] else: port = "5556" c = Communication(port) c.bind() recieverP = Process(target=c.reciever) recieverP.start() print("first process") c2 = Communication(port) c2.connect() senderP = Process(target=c2.sender) senderP.start() print("second process") </code></pre> <p><strong>client.py</strong></p> <pre><code>from communication import Communication from multiprocessing import Process import zmq import random import sys import time if __name__ == '__main__': if len(sys.argv) &gt; 1: port = sys.argv[1] else: port = "5556" c = Communication(port) c.connect() recieverP = Process(target=c.reciever, args=()) senderP = Process(target=c.sender,args=()) recieverP.start() senderP.start() </code></pre> <p><strong>communications.py</strong></p> <pre><code>import zmq class Communication: def __init__(self, port): context = zmq.Context.instance() self.port = port self.socket = context.socket(zmq.PAIR) def connect(self): self.socket.connect("tcp://localhost:%s" % self.port) def bind(self): self.socket.bind("tcp://*:%s" % self.port) def sender(self): while True: msg = raw_input("&gt; ") self.socket.send(msg) def reciever(self): while True: msg = self.socket.recv() print("&gt; " + msg) </code></pre>
0
2016-08-20T17:09:47Z
39,057,197
<p>These are processes not threads. The problem occurs because in the background Python has to send a copy of your <code>Communication</code> object to the child process. However, your object contains socket objects that cannot be serialised. Use <code>threading</code> and the <code>Thread</code> object in place of <code>Process</code> and you won't run into this problem. This is because threads run in the same process.</p>
1
2016-08-20T18:01:21Z
[ "python", "multithreading", "sockets", "chat", "pyzmq" ]
TypeError: context must be specified" in zmq unpickling
39,056,746
<p>I am trying to create a very simple chat. Using the PyZMQ library. And since sockets are not threadsafe I am using two sockets and one thread running on each. One checking for incoming messages, and one to send messages. </p> <p>But my program is giving me, error messages:</p> <pre><code> Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; File "C:\Python27\lib\multiprocessing\forking.py", line 381, in main self = load(from_parent) File "C:\Python27\lib\pickle.py", line 1384, in load Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; File "C:\Python27\lib\multiprocessing\forking.py", line 381, in main self = load(from_parent) File "C:\Python27\lib\pickle.py", line 1384, in load return Unpickler(file).load() File "C:\Python27\lib\pickle.py", line 864, in load return Unpickler(file).load() File "C:\Python27\lib\pickle.py", line 864, in load dispatch[key](self) File "C:\Python27\lib\pickle.py", line 1089, in load_newobj dispatch[key](self) File "C:\Python27\lib\pickle.py", line 1089, in load_newobj obj = cls.__new__(cls, *args) File "zmq\backend\cython\socket.pyx", line 279, in zmq.backend.cython.socket.Socket.__cinit__ (zmq\backend\cython\socket.c:3456) TypeError: context must be specified obj = cls.__new__(cls, *args) File "zmq\backend\cython\socket.pyx", line 279, in zmq.backend.cython.socket.Socket.__cinit__ (zmq\backend\cython\socket.c:3456) TypeError: context must be specified </code></pre> <p>I can not figure out why I am getting them, or how to solve it. </p> <p>Also is my logic wrong here?:</p> <blockquote> <p>We start the server which creates a socket and binds it to a port. Then It listens to that sockets for messages/connections. Then we create another socket and binds it to the same port. We create a new thread that makes it so that we wait for messages to be recieved on the first socket to then be sent to the second one. Then we have a client who connects to the first socket. We create a new thread for it so it can listen on the other socket for incoming messages, and thus it can use the first thread to send messages through the first socket.</p> </blockquote> <p><strong>server.py</strong></p> <pre><code>from communication import Communication from multiprocessing import Process import zmq import random import sys import time if __name__ == '__main__': if len(sys.argv) &gt; 1: port = sys.argv[1] else: port = "5556" c = Communication(port) c.bind() recieverP = Process(target=c.reciever) recieverP.start() print("first process") c2 = Communication(port) c2.connect() senderP = Process(target=c2.sender) senderP.start() print("second process") </code></pre> <p><strong>client.py</strong></p> <pre><code>from communication import Communication from multiprocessing import Process import zmq import random import sys import time if __name__ == '__main__': if len(sys.argv) &gt; 1: port = sys.argv[1] else: port = "5556" c = Communication(port) c.connect() recieverP = Process(target=c.reciever, args=()) senderP = Process(target=c.sender,args=()) recieverP.start() senderP.start() </code></pre> <p><strong>communications.py</strong></p> <pre><code>import zmq class Communication: def __init__(self, port): context = zmq.Context.instance() self.port = port self.socket = context.socket(zmq.PAIR) def connect(self): self.socket.connect("tcp://localhost:%s" % self.port) def bind(self): self.socket.bind("tcp://*:%s" % self.port) def sender(self): while True: msg = raw_input("&gt; ") self.socket.send(msg) def reciever(self): while True: msg = self.socket.recv() print("&gt; " + msg) </code></pre>
0
2016-08-20T17:09:47Z
39,057,473
<p>Fully working version below. I made a few changes:</p> <ol> <li>I used threads instead of processes, as suggested by @Dunes.</li> <li>I combined <code>client.py</code> and <code>server.py</code> into a single <code>app.py</code> with a "role" parameter. (This was just to avoid a lot of duplicate code.)</li> <li>I handled <code>KeyboardException</code>s in the main thread so you can Ctrl+C to exit.</li> <li>I dropped the "> " prefix on lines, since it led to confusing output. (When you type something in the other app, you'd get output like "> > hello".)</li> <li>I took out the <code>c2</code> that was in <code>server.py</code>. I'm not sure what the purpose of that was, and I don't know if that's expected to work. (Seems like you were <code>connect</code>ing instead of <code>bind</code>ing?)</li> <li>I fixed the spelling of "receiver" everywhere because it was bothering me. :-)</li> <li>I made <code>port</code> an <code>int</code> instead of a <code>str</code>, because it is. :-)</li> </ol> <p>app.py:</p> <pre><code>import argparse from threading import Thread import time from communication import Communication if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("role", help="either 'client' or 'server'", choices=['client', 'server']) parser.add_argument("--port", "-p", type=int, help="port number", default=5556) args = parser.parse_args() c = Communication(args.port) if args.role == 'client': c.connect() else: c.bind() receiverP = Thread(target=c.receiver) senderP = Thread(target=c.sender) receiverP.daemon = True senderP.daemon = True try: receiverP.start() senderP.start() while True: time.sleep(100) except (KeyboardInterrupt, SystemExit): pass </code></pre> <p>communication.py:</p> <pre><code>import zmq class Communication: def __init__(self, port): self.port = port context = zmq.Context.instance() self.socket = context.socket(zmq.PAIR) def connect(self): self.socket.connect("tcp://localhost:%d" % self.port) def bind(self): self.socket.bind("tcp://*:%d" % self.port) def sender(self): while True: self.socket.send(raw_input()) def receiver(self): while True: print(self.socket.recv()) </code></pre>
1
2016-08-20T18:33:21Z
[ "python", "multithreading", "sockets", "chat", "pyzmq" ]
How to make a POST with ajax just like the form submit?
39,056,749
<p>I'm trying to send a POST request to my python (Google App Engine) server using Ajax just the way we do from a form submit, but it's not working.</p> <p>This is my HTML:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Test&lt;/title&gt; &lt;script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js" type="text/javascript"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;button&gt;apple&lt;/button&gt; &lt;form method="POST" action="/"&gt; &lt;input name="url" value="value1" id="urlimg"&gt; &lt;br&gt; &lt;input class="myButton" type="submit" value="FIND OUT" id="submit_button"&gt; &lt;/form&gt; &lt;script type="text/javascript"&gt; $(document).ready(function(){ $('button').click(function() { $.post('/', { url: 'value1'}); }); }); &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>And this is my python code:</p> <pre><code>import os import webapp2 import jinja2 import urllib2 as urllib template_dir = os.path.join(os.path.dirname(__file__), '') jinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir), autoescape = True) class Handler(webapp2.RequestHandler): def write(self,*a,**kw): self.response.write(*a,**kw) def render_str(self,template,**params): t = jinja_env.get_template(template) return t.render(params) def render(self,template,**kw): self.write(self.render_str(template,**kw)) class MainHandler(Handler): def get(self): self.render('image.html') def post(self): url = self.request.get('url') self.response.write(url + ' is your url') app = webapp2.WSGIApplication([ ('/', MainHandler) ], debug=True) </code></pre>
0
2016-08-20T17:10:04Z
39,070,536
<p>You should return the response as a JSON object:</p> <pre><code>class MainHandler(Handler): def get(self): self.render('image.html') def post(self): import json url = self.request.get('url') response_dict = { 'message': 'Yay, I did it!', 'url': url + ' is your url', } self.response.headers['Content-Type'] = 'application/json' self.response.out.write(json.dumps(response_dict)) </code></pre> <p>And handle the response in your template thusly:</p> <pre><code>$("button").click(function(){ $.post("/", { url: $('#urlimg').val()}, function(data, status){ alert("message: " + data.message + "\nURL: " + data.url + "\nStatus: " + status); }); }); </code></pre>
0
2016-08-22T02:11:21Z
[ "javascript", "jquery", "python", "ajax", "google-app-engine" ]
No module named 'matplotlib.pylot'
39,056,880
<p>I had installed Python 3.5 from anaconda distribution.</p> <pre><code>C:\Users\ananda&gt;python Python 3.5.2 |Anaconda 4.1.1 (64-bit)| (default, Jul 5 2016, 11:41:13) [MSC v.1900 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. </code></pre> <p>I am importing matplotlib on jupyter notebook,where I am getting error related to module not found.</p> <p>I tried to install matplotlib like below:</p> <pre><code>&gt;&gt;&gt;C:\Users\ananda&gt;conda install matplotlib Fetching package metadata ......... Solving package specifications: .......... # All requested packages already installed. # packages in environment at C:\Users\ananda\AppData\Local\Continuum\Anaconda3: matplotlib 1.5.1 np111py35_0 </code></pre> <p>Not sure whats wrong I am doing,how to use matplotlib module here,do i need to install any particular version?</p>
0
2016-08-20T17:24:02Z
39,057,358
<p>Your attempt to install <code>matplotlib</code> seems right, but the submodule you're looking for is called <code>pyplot</code>.</p> <p>Just try:</p> <pre><code>&gt;&gt;&gt; import matplotlib.pyplot as plt &gt;&gt;&gt; # No ImportError or similar, everything is fine </code></pre> <p>If you still get an error, just post the <strong>full</strong> traceback.</p> <p>Hope this helps!</p>
1
2016-08-20T18:19:44Z
[ "python", "matplotlib", "jupyter" ]
Bokeh: run callback on plot init?
39,056,886
<p>I have the majority of my calculations for an interactive chloropeth graph done through callbacks on various attached widgets.</p> <p>Can we run a callback on plot initiation? This could be accomplished by constructing a refresh/init button and attaching an initiating callback to it, but this still requires pushing a button.</p>
0
2016-08-20T17:24:19Z
39,070,711
<p>As of Bokeh <code>0.12.1</code> this is an open feature request:</p> <p><a href="https://github.com/bokeh/bokeh/issues/4272" rel="nofollow">https://github.com/bokeh/bokeh/issues/4272</a></p> <p>As a workaround, you might try adding a timeout callback with a very short interval:</p> <pre><code>curdoc().add_timeout_callback(startup_code, 10) # 10 ms </code></pre>
0
2016-08-22T02:45:05Z
[ "python", "bokeh" ]
Xml write twice the same thing
39,056,914
<p>i'm looking to solve this problem. When i try to write into the xml file , it writes twice the same thing.</p> <p>It's the code:</p> <pre><code> def writeIntoXml(fileName, tagElement, textElement): tree = ET.ElementTree(file = fileName) root = tree.getroot() newElement = ET.SubElement(root, tagElement) newElement.text =textElement; newElement.tail ="\n" root.append(newElement) tree.write(fileName, encoding='utf-8') </code></pre> <p>If i have this xml file, with this tags, if i write a new tag( es "Question-3" Example3 "/Question-3") i get a problem</p> <p>XmlFile before being written:</p> <pre><code>&lt;Questions&gt; &lt;Question-1&gt;Example1&lt;/Question-1&gt; &lt;Question-2&gt;Example2&lt;/Question-2&gt; &lt;/Questions&gt; </code></pre> <p>XmlFile after being written: </p> <pre><code>&lt;Questions&gt; &lt;Question-1&gt;Example1&lt;/Question-1&gt; &lt;Question-2&gt;Example2&lt;/Question-2&gt; &lt;Question-3&gt;Example3&lt;/Question-3&gt; &lt;Question-3&gt;Example3&lt;/Question-3&gt; &lt;/Questions&gt; </code></pre> <p>Sorry for grammatical errors</p>
0
2016-08-20T17:27:35Z
39,057,107
<p>Note that <a href="https://docs.python.org/3/library/xml.etree.elementtree.html#xml.etree.ElementTree.SubElement" rel="nofollow">ET.SubElement()</a> appends the element automatically. You are adding the element twice, first in <code>SubElement()</code>, next in <code>append()</code>. </p> <p>You should use either just</p> <pre><code>newElement = ET.SubElement(root, tagElement) newElement.text = textElement; newElement.tail = "\n" </code></pre> <p>or</p> <pre><code>newElement = ET.Element(tagElement) newElement.text = textElement; newElement.tail = "\n" root.append(newElement) </code></pre>
0
2016-08-20T17:51:07Z
[ "python", "xml", "python-3.x", "xml-parsing" ]
wxPython : Creating a soundboard with panels
39,057,105
<p>I am making a quick and dirty soundboard using the wxPython package and was wondering how to go by implementing a scroll-list of sounds to play. </p> <p>Here is a picture of what I am trying to convey: <a href="http://i.imgur.com/av0E5jC.png" rel="nofollow">http://i.imgur.com/av0E5jC.png</a></p> <p>and here is my code so far: </p> <pre><code>import wx class windowClass(wx.Frame): def __init__(self, *args, **kwargs): super(windowClass,self).__init__(*args,**kwargs) self.basicGUI() def basicGUI(self): panel = wx.Panel(self) menuBar = wx.MenuBar() fileButton = wx.Menu() editButton = wx.Menu() exitItem = fileButton.Append(wx.ID_EXIT, 'Exit','status msg...') menuBar.Append(fileButton, 'File') menuBar.Append(editButton, 'Edit') self.SetMenuBar(menuBar) self.Bind(wx.EVT_MENU, self.Quit, exitItem) wx.TextCtrl(panel,pos=(10,10), size=(250,150)) self.SetTitle("Soundboard") self.Show(True) def Quit(self, e): self.Close() def main(): app = wx.App() windowClass(None) app.MainLoop() main() </code></pre> <p>My question remains, how does one load a list of sounds on that panel and click a certain button to play that sound. I don't really care about implementing pause and fast forward features since this is only going to play really quick sound files. </p> <p>Thanks in advance. </p>
0
2016-08-20T17:50:49Z
39,057,220
<p>Just removed the text widget, replaced by a listbox, and hooked a callback on item click, slightly elaborate: when clicking, it finds the position of the item, retrieves the label name and fetches the filename in the dictionary (we want to play a .wav file with a path, but not necessarily display the full filename)</p> <p>I refactored the code so callbacks and other attributes are private, helps the lisibility.</p> <pre><code>import wx class windowClass(wx.Frame): def __init__(self, *args, **kwargs): super(windowClass,self).__init__(*args,**kwargs) self.__basicGUI() def __basicGUI(self): panel = wx.Panel(self) menuBar = wx.MenuBar() fileButton = wx.Menu() editButton = wx.Menu() exitItem = fileButton.Append(wx.ID_EXIT, 'Exit','status msg...') menuBar.Append(fileButton, 'File') menuBar.Append(editButton, 'Edit') self.SetMenuBar(menuBar) self.Bind(wx.EVT_MENU, self.__quit, exitItem) self.__sound_dict = { "a" : "a.wav","b" : "b.wav","c" : "c2.wav"} self.__sound_list = sorted(self.__sound_dict.keys()) self.__list = wx.ListBox(panel,pos=(20,20), size=(250,150)) for i in self.__sound_list: self.__list.Append(i) self.__list.Bind(wx.EVT_LISTBOX,self.__on_click) #wx.TextCtrl(panel,pos=(10,10), size=(250,150)) self.SetTitle("Soundboard") self.Show(True) def __on_click(self,event): event.Skip() name = self.__sound_list[self.__list.GetSelection()] filename = self.__sound_dict[name] print("now playing %s" % filename) def __quit(self, e): self.Close() def main(): app = wx.App() windowClass(None) app.MainLoop() main() </code></pre>
0
2016-08-20T18:03:08Z
[ "python", "wxpython" ]
Ignore raising exception to the caller in python 3
39,057,162
<p>How can I ignore a certain exception to be raised to the caller in python 3?</p> <p><strong>Example:</strong></p> <pre><code>def do_something(): try: statement1 statement2 except Exception as e: # ignore the exception logging.warning("this is normal, exception is ignored") try: do_something() except Exception as e: # this is unexpected control flow, the first exception is already ignored !! logging.error("unexpected error") logging.error(e) # prints None </code></pre> <p>I found someone mentioned that "<em>Because of the last thrown exception being remembered in Python, some of the objects involved in the exception-throwing statement are being kept live indefinitely</em>" and then mentioned to use "sys.exc_clear()" in this case which is not available anymore in python 3. Any clue how can I completely ignore the exception in python3?</p>
1
2016-08-20T17:57:07Z
39,057,779
<p>There's no need to do this in Python <code>3</code>, <code>sys.exc_clear()</code> was removed because Python doesn't store the last raised exception internally as it did in Python 2:</p> <p>For example, in Python 2, the exception is still kept alive when inside a function:</p> <pre><code>def foo(): try: raise ValueError() except ValueError as e: print(e) import sys; print(sys.exc_info()) </code></pre> <p>Calling <code>foo</code> now shows the exception is kept:</p> <pre><code>foo() (&lt;type 'exceptions.ValueError'&gt;, ValueError(), &lt;traceback object at 0x7f45c57fc560&gt;) </code></pre> <p>You need to call <code>sys.exc_clear()</code> in order to clear the <code>Exception</code> raised.</p> <p>In Python 3, on the contrary:</p> <pre><code>def foo(): try: raise ValueError() except ValueError as e: print(e) import sys; print(sys.exc_info()) </code></pre> <p>Calling the same function:</p> <pre><code>foo() (None, None, None) </code></pre>
0
2016-08-20T19:08:36Z
[ "python", "python-3.x", "exception-handling", "pep" ]
Converting value to key from dictionary
39,057,167
<p>I have a txt file with the following text:</p> <pre><code>water=45 melon=8 apple=35 pineapple=67 I=43 to=90 eat=12 tastes=100 sweet=21 it=80 watermelon=98 want=70 </code></pre> <p>and I have another file with the following text:</p> <pre><code>I want to eat watermelon it tastes sweet pineapple </code></pre> <p>I want to output into:</p> <pre><code>I want to eat watermelon = 43,70,90,12,98 it tastes sweet pineapple = 80,100,21,67 </code></pre> <p>This is what I have so far: </p> <pre><code>import nltk f = open(r'C:\folder\dic\file.txt','r') answer = {} for line in f: k, v = line.strip().split('=') answer[k.strip()] = v.strip() f.close() print answer.values() h = open(r'C:\folder\dic\file2.txt','r') raw=h.read() tokens = nltk.sent_tokenize(raw) text = nltk.Text(tokens) for line in text: word = line for value in answer.values(): if value == word: word=answer[keys] else: word="not found" print word </code></pre> <p>What would be the best way to do this in Python? </p>
1
2016-08-20T17:57:56Z
39,057,631
<p>Please check this code.</p> <pre><code>import re f = open(r'C:\Users\dinesh_pundkar\Desktop\val.txt','r') val_dict = {} for line in f: k, v = line.strip().split('=') val_dict[k.strip()] = v.strip() f.close() print val_dict h = open(r'C:\Users\dinesh_pundkar\Desktop\str_txt.txt','r') str_list = [] for line in h: str_list.append(str(line).strip()) print str_list tmp_str = '' for val in str_list: tmp_str = val for k in val_dict.keys(): if k in val: replace_str = str(val_dict[k]).strip() + "," tmp_str= re.sub(r'\b{0}\b'.format(k),replace_str,tmp_str,flags=re.IGNORECASE) tmp_str = tmp_str.strip(",") print val, " = ", tmp_str tmp_str = '' </code></pre> <p>Output :</p> <pre><code>C:\Users\dinesh_pundkar\Desktop&gt;python demo.py {'apple': '35', 'I': '43', 'sweet': '21', 'it': '80', 'water': '45', 'to': '90', 'taste': '100', 'watermelon': '98', 'want': '70', 'pineapple': '67', 'melon': ' 8', 'eat': '12'} ['I want to eat watermelon', 'it taste sweet pineapple'] I want to eat watermelon = 43, 70, 90, 12, 98 it taste sweet pineapple = 80, 100, 21, 67 </code></pre>
1
2016-08-20T18:50:37Z
[ "python", "python-2.7", "python-3.x" ]
Why doesn't ulimit -t kill a process sleeping beyond the limit with time.sleep?
39,057,299
<p>I am trying to limit the CPU usage of one python script using <code>ulimit -t</code>. The script contains one <code>time.sleep()</code> statement and it is not killed after the specified time limit. Here is the simplified python script named <code>test.py</code>:</p> <pre><code>import time while True: time.sleep(0.1) </code></pre> <p>and I run the command as following:</p> <pre><code>ulimit -v 400000; ulimit -t 30; python test.py </code></pre> <p>The script keeps running forever. Are there any explanations for this? Thanks.</p> <p>The answer of mata is correct. I updated my real code which contains a hidden thing that <code>ulimit -t</code> does not count the running time of spawned subprocesses. </p> <pre><code>#!/usr/bin/env python # Run: python smt.py filename.smt2 timeout # timeout is in seconds import os import subprocess import sys import stat import time current_path = os.path.dirname(os.path.realpath(__file__)) def remove_tmp (filename, version): try: os.remove(filename + '.' + version + '.tmp') except OSError: pass try: os.remove(os.path.splitext(filename)[0] + '.' + version + '.out') except OSError: pass try: os.remove(os.path.splitext(filename)[0] + '.' + version + '.in') except OSError: pass def run_raSAT (filename, bounds, sbox, timeout): startTime = time.time() raSATResult = "unknown" # remove tmps files: remove_tmp(filename, "0.2") remove_tmp(filename, "0.3") proc2 = subprocess.Popen([os.path.join(current_path, "./raSAT-0.2"), filename, bounds, 'sbox=' + str(sbox), 'tout=' + str(timeout-(time.time() - startTime))]) proc3 = subprocess.Popen([os.path.join(current_path, "./raSAT-0.3"), filename, bounds]) while True: if proc2.poll(): # try read output of 0.2 try: with open(filename + '.0.2.tmp', 'r') as outfile: raSATResult = outfile.read().rstrip() outfile.close() if raSATResult == "unknown": sbox /= 10 remove_tmp(filename, "0.2") proc2 = subprocess.Popen([os.path.join(current_path, "./raSAT-0.2"), filename, bounds, 'sbox=' + str(sbox), 'tout=' + str(timeout-(time.time() - startTime))]) except IOError: pass if proc3.poll(): # try read output of 0.3 try: with open(filename + '.0.3.tmp', 'r') as outfile: raSATResult = outfile.read().rstrip() outfile.close() except IOError: pass if raSATResult == "sat" or raSATResult == "unsat": if not proc3.poll(): proc3.kill() if not proc2.poll(): proc2.kill() break time.sleep(0.01) return raSATResult, sbox def run(filename, initLowerBound, initUpperBound, sbox, timeout): lowerBound = initLowerBound upperBound = initUpperBound raSATResult = "unknown" startTime = time.time() while (raSATResult == 'unknown'): (raSATResult, sbox) = run_raSAT(filename, 'lb=' + str(lowerBound) + ' ' + str(upperBound), sbox, timeout - (time.time() - startTime)) if raSATResult == 'unsat': (raSATResult, sbox) = run_raSAT(filename, 'lb=-inf inf', sbox, timeout - (time.time() - startTime)) print (raSATResult) # remove tmps files: remove_tmp(filename, "0.2") remove_tmp(filename, "0.3") # get timeout from environment timeout = float(os.environ.get('STAREXEC_CPU_LIMIT')) run(sys.argv[1], -10, 10, 0.1, timeout) </code></pre>
0
2016-08-20T18:12:49Z
39,057,470
<p><code>ulimit -t</code> sets the <em>CPU</em> time limit. While your program is sleeping it doesn't use any CPU time, so that time doesn't count. It will only occupy a few CPU cycles to go to sleep again, that's why it's not killed.</p> <p>You can't specify a real time limit using ulimit.</p>
3
2016-08-20T18:33:13Z
[ "python", "ulimit" ]
Error received while converting a .txt in to .csv file for plotting two columns
39,057,315
<p>I have four columns in a .txt file and I want to convert in into .csv and then plot two of the columns. my code is the following : </p> <pre><code>import pandas as pd import numpy as np from sys import argv from pylab import * import csv script, filename = argv txt = open(filename) print "Here's your file %r:" % filename print txt.read() # read flash.dat to a list of lists datContent = [i.strip().split() for i in open("./N56_mass.txt").readlines()] # write it as a new CSV file with open("./N56_mass.txt", "wb") as f: writer = csv.writer(f) writer.writerows(datContent) columns_to_keep = ['#Radius(cm)', 'Ni56MassFration'] dataframe = pd.read_csv("./N56_mass.txt", usecols=columns_to_keep) pd.set_option('display.height', 1000) pd.set_option('display.max_rows', 1000) pd.set_option('display.max_columns', 500) pd.set_option('display.width', 1000) dataframe.plot(x='#Radius(cm)', y='Ni56MassFraction', style='r') print dataframe show() </code></pre> <p>I am getting an unsusal syntax error whie executing it with <code>python N56_mass.txt csv_flash.py</code> , the error suggests: </p> <pre><code>File "N56_mass.txt", line 2 0.1e10 0.00326 1.605 0.00203 ^ SyntaxError: invalid syntax </code></pre> <p>I can't see the error either in my .txt file or in the code, I am uploading the .txt here too, please help me find the error. thanks in advance.`</p> <pre><code>#Radius(cm) Ni56Mass TotalMass Ni56MassFraction 0.1e10 0.00326 1.605 0.00203 0.2e10 0.00548 1.896 0.00289 0.3e10 0.00620 1.976 0.00313 0.4e10 0.00658 2.028 0.00324 0.6e10 0.00716 2.113 0.00339 0.8e10 0.00777 2.177 0.00357 1.0e10 0.00808 2.218 0.00364 1.2e10 0.00833 2.247 0.00370 1.4e10 0.00851 2.268 0.00357 1.6e10 0.00859 2.281 0.00377 1.8e10 0.00862 2.288 0.00377 2.0e10 0.00864 2.293 0.00377 2.2e10 0.00864 2.297 0.00377 2.4e10 0.00864 2.299 0.00376 2.6e10 0.00865 2.301 0.00376 </code></pre>
0
2016-08-20T18:14:37Z
39,057,448
<p>Your command line syntax is incorrect.</p> <p>You are passing a text file to python instead of a valid python script by calling <code>python N56_mass.txt csv_flash.py</code></p> <p>Try instead,</p> <pre><code>python csv_flash.py N56_mass.txt </code></pre>
1
2016-08-20T18:30:57Z
[ "python", "csv", "pandas" ]
Error received while converting a .txt in to .csv file for plotting two columns
39,057,315
<p>I have four columns in a .txt file and I want to convert in into .csv and then plot two of the columns. my code is the following : </p> <pre><code>import pandas as pd import numpy as np from sys import argv from pylab import * import csv script, filename = argv txt = open(filename) print "Here's your file %r:" % filename print txt.read() # read flash.dat to a list of lists datContent = [i.strip().split() for i in open("./N56_mass.txt").readlines()] # write it as a new CSV file with open("./N56_mass.txt", "wb") as f: writer = csv.writer(f) writer.writerows(datContent) columns_to_keep = ['#Radius(cm)', 'Ni56MassFration'] dataframe = pd.read_csv("./N56_mass.txt", usecols=columns_to_keep) pd.set_option('display.height', 1000) pd.set_option('display.max_rows', 1000) pd.set_option('display.max_columns', 500) pd.set_option('display.width', 1000) dataframe.plot(x='#Radius(cm)', y='Ni56MassFraction', style='r') print dataframe show() </code></pre> <p>I am getting an unsusal syntax error whie executing it with <code>python N56_mass.txt csv_flash.py</code> , the error suggests: </p> <pre><code>File "N56_mass.txt", line 2 0.1e10 0.00326 1.605 0.00203 ^ SyntaxError: invalid syntax </code></pre> <p>I can't see the error either in my .txt file or in the code, I am uploading the .txt here too, please help me find the error. thanks in advance.`</p> <pre><code>#Radius(cm) Ni56Mass TotalMass Ni56MassFraction 0.1e10 0.00326 1.605 0.00203 0.2e10 0.00548 1.896 0.00289 0.3e10 0.00620 1.976 0.00313 0.4e10 0.00658 2.028 0.00324 0.6e10 0.00716 2.113 0.00339 0.8e10 0.00777 2.177 0.00357 1.0e10 0.00808 2.218 0.00364 1.2e10 0.00833 2.247 0.00370 1.4e10 0.00851 2.268 0.00357 1.6e10 0.00859 2.281 0.00377 1.8e10 0.00862 2.288 0.00377 2.0e10 0.00864 2.293 0.00377 2.2e10 0.00864 2.297 0.00377 2.4e10 0.00864 2.299 0.00376 2.6e10 0.00865 2.301 0.00376 </code></pre>
0
2016-08-20T18:14:37Z
39,057,455
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow"><code>delim_whitespace</code></a> to handle whitespaces as delimiters:</p> <pre><code>dataframe = pd.read_csv("N56_mass.txt", delim_whitespace=True, usecols=columns_to_keep) </code></pre>
1
2016-08-20T18:31:54Z
[ "python", "csv", "pandas" ]