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
Find range of arguments that return the same result for a linear function
39,948,543
<p>Consider the <code>y = round(300000/x**2)</code>. I would like to find the ranges of <code>x</code> that return the same <code>y</code> for <code>100 &lt; x &lt; 40000</code>.</p> <p>How would I do that with python/numpy?</p>
2
2016-10-09T21:07:20Z
39,949,136
<p>First of all: the credit of this solution should go to <a href="http://stackoverflow.com/a/39948612/1029516">@CoryKramer</a>, even after the fix in the question.</p> <pre><code>from itertools import groupby groups = groupby(range(100, 40000), key=lambda x: round(300000/x**2)) </code></pre> <p>Anyway there is something you should be aware, due to the division operator you are using: currently you used <em>integer division</em>, but using the <em>true division</em> operator can lead to slightly different grouping due to rounding (<code>300000/x**2</code> vs <code>300000.0/x**2</code>).</p> <pre><code>from itertools import groupby groups_int = groupby(range(100, 40000), key=lambda x: round(300000/x**2)) groups_true = groupby(range(100, 40000), key=lambda x: round(300000.0/x**2)) res_int = [(g[0], [n for n in g[1]]) for g in groups_int] res_true = [(g[0], [n for n in g[1]]) for g in groups_true] for v_int, v_true in zip(res_int, res_true): # show the min and the max for each grouping print v_int[0], min(v_int[1]), 'to', max(v_int[1]), '---', min(v_true[1]), 'to', max(v_true[1]) 30.0 100 to 100 --- 100 to 100 29.0 101 to 101 --- 101 to 102 28.0 102 to 103 --- 103 to 104 27.0 104 to 105 --- 105 to 106 26.0 106 to 107 --- 107 to 108 25.0 108 to 109 --- 109 to 110 24.0 110 to 111 --- 111 to 112 23.0 112 to 114 --- 113 to 115 22.0 115 to 116 --- 116 to 118 21.0 117 to 119 --- 119 to 120 20.0 120 to 122 --- 121 to 124 19.0 123 to 125 --- 125 to 127 18.0 126 to 129 --- 128 to 130 17.0 130 to 132 --- 131 to 134 16.0 133 to 136 --- 135 to 139 15.0 137 to 141 --- 140 to 143 14.0 142 to 146 --- 144 to 149 13.0 147 to 151 --- 150 to 154 12.0 152 to 158 --- 155 to 161 11.0 159 to 165 --- 162 to 169 10.0 166 to 173 --- 170 to 177 9.0 174 to 182 --- 178 to 187 8.0 183 to 193 --- 188 to 200 7.0 194 to 207 --- 201 to 214 6.0 208 to 223 --- 215 to 233 5.0 224 to 244 --- 234 to 258 4.0 245 to 273 --- 259 to 292 3.0 274 to 316 --- 293 to 346 2.0 317 to 387 --- 347 to 447 1.0 388 to 547 --- 448 to 774 0.0 548 to 39999 --- 775 to 39999 </code></pre> <hr> <h2>Alternative solution</h2> <p>Here I propose another solution reversing the problem: the turning point of the rounding is when a value reaches <code>xxx.5</code>, so we can try to reverse the equation and solve</p> <p><img src="http://latex.codecogs.com/gif.latex?x%20%3D%20%5Csqrt%7B%5Cfrac%7B300000%7D%7By%20&plus;%200.5%7D%7D" alt="formula"></p> <p>computing <code>x</code> for each <code>y</code> integer between 0 and 30 (we know it doing a bit of domain analysis or simply peeking from the previous solution :P).</p> <pre><code>points = [(y, (300000.0/(y + 0.5))**.5) for y in range(30,0,-1)] # [(30, 99.17694073609294), (29, 100.84389681792216), (28, 102.59783520851542), (27, 104.44659357341871), (26, 106.3990353197863), (25, 108.46522890932809), (24, 110.65666703449763), (23, 112.98653657320641), (22, 115.47005383792515), (21, 118.12488464372366), (20, 120.97167578182678), (19, 124.03473458920845), (18, 127.34290799340266), (17, 130.93073414159542), (16, 134.8399724926484), (15, 139.12166872805048), (14, 143.83899044561525), (13, 149.07119849998597), (12, 154.91933384829667), (11, 161.51457061744966), (10, 169.03085094570332), (9, 177.7046633277277), (8, 187.86728732554485), (7, 200.0), (6, 214.83446221182987), (5, 233.5496832484569), (4, 258.19888974716116), (3, 292.7700218845599), (2, 346.41016151377545), (1, 447.21359549995793)] </code></pre> <p>Then for each point we can compute your result grouping all the integers between the points we just calculated:</p> <pre><code>from math import ceil, floor res = [(low[0], range(int(ceil(low[1])), int(floor(up[1]))+1)) for low, up in zip(points[:-1], points[1:])] </code></pre>
2
2016-10-09T22:21:38Z
[ "python", "numpy" ]
Non-blocking file read
39,948,588
<p>How can I read the contents of a binary or a text file in a non-blocking mode?</p> <p>For binary files: when I <code>open(filename, mode='rb')</code>, I get an instance of <code>io.BufferedReader</code>. The documentation fort <code>io.BufferedReader.read</code> <a href="https://docs.python.org/3.5/library/io.html#io.BufferedReader.read" rel="nofollow">says</a>:</p> <blockquote> <p>Read and return size bytes, or if size is not given or negative, until EOF or if the read call would block in non-blocking mode.</p> </blockquote> <p>Obviously a straightforward <code>open(filename, 'rb').read()</code> is in a blocking mode. To my surprise, I could not find an explanation anywhere in the <code>io</code> docs of how to choose the non-blocking mode.</p> <p>For text files: when I <code>open(filename, mode='rt')</code>, I get <code>io.TextIOWrapper</code>. I assume the relevant docs are those for <code>read</code> in its base class, <code>io.TextIOBase</code>; and <a href="https://docs.python.org/3.5/library/io.html#io.TextIOBase.read" rel="nofollow">according to those docs</a>, there seems no way to do non-blocking read at all:</p> <blockquote> <p>Read and return at most size characters from the stream as a single str. If size is negative or None, reads until EOF.</p> </blockquote>
0
2016-10-09T21:12:11Z
39,948,643
<p>I suggest using aiofile. <a href="https://pypi.python.org/pypi/aiofiles/0.2.1" rel="nofollow">https://pypi.python.org/pypi/aiofiles/0.2.1</a></p> <pre><code>f = yield from aiofiles.open('filename', mode='r') try: contents = yield from f.read() finally: yield from f.close() print(contents) 'My file contents' </code></pre>
-1
2016-10-09T21:19:28Z
[ "python", "python-3.x", "io" ]
Non-blocking file read
39,948,588
<p>How can I read the contents of a binary or a text file in a non-blocking mode?</p> <p>For binary files: when I <code>open(filename, mode='rb')</code>, I get an instance of <code>io.BufferedReader</code>. The documentation fort <code>io.BufferedReader.read</code> <a href="https://docs.python.org/3.5/library/io.html#io.BufferedReader.read" rel="nofollow">says</a>:</p> <blockquote> <p>Read and return size bytes, or if size is not given or negative, until EOF or if the read call would block in non-blocking mode.</p> </blockquote> <p>Obviously a straightforward <code>open(filename, 'rb').read()</code> is in a blocking mode. To my surprise, I could not find an explanation anywhere in the <code>io</code> docs of how to choose the non-blocking mode.</p> <p>For text files: when I <code>open(filename, mode='rt')</code>, I get <code>io.TextIOWrapper</code>. I assume the relevant docs are those for <code>read</code> in its base class, <code>io.TextIOBase</code>; and <a href="https://docs.python.org/3.5/library/io.html#io.TextIOBase.read" rel="nofollow">according to those docs</a>, there seems no way to do non-blocking read at all:</p> <blockquote> <p>Read and return at most size characters from the stream as a single str. If size is negative or None, reads until EOF.</p> </blockquote>
0
2016-10-09T21:12:11Z
39,948,796
<p>File operations are blocking. There is no non-blocking mode.</p> <p>But you can create a thread which reads the file in the background. In Python 3, <a href="https://docs.python.org/3.4/library/concurrent.futures.html#module-concurrent.futures" rel="nofollow"><code>concurrent.futures</code> module</a> can be useful here.</p> <pre><code>from concurrent.futures import ThreadPoolExecutor def read_file(filename): with open(filename, 'rb') as f: return f.read() executor = concurrent.futures.ThreadPoolExecutor(1) future_file = executor.submit(read_file, 'C:\\Temp\\mocky.py') # continue with other work # later: if future_file.done(): file_contents = future_file.result() </code></pre> <p>Or, if you need a callback to be called when the operation is done:</p> <pre><code>def on_file_reading_finished(future_file): print(future_file.result()) future_file = executor.submit(read_file, 'C:\\Temp\\mocky.py') future_file.add_done_callback(on_file_reading_finished) # continue with other code while the file is loading... </code></pre>
1
2016-10-09T21:36:18Z
[ "python", "python-3.x", "io" ]
One line python code to remove all the strings that doesn't start with T or t and if they contain number greater then 6
39,948,626
<p>Eg:</p> <pre><code>List=["tata1","tata2","Tata3","mdkjd","djhdj","Tata8","t9","t2"] </code></pre> <p>Output should be:<code>["tata1","tata2","Tata3","t2"]</code></p> <p>I tried :</p> <pre><code>content = [item for item in List if terminal.lower().startswith('t')] </code></pre> <p>My doubt if I can append one more condition with the if I used in my code?</p> <p>If yes, how?</p> <p>I tried writing but it gives error.</p>
0
2016-10-09T21:18:05Z
39,948,666
<p>You can use <code>and</code> to test multiple conditions.</p> <pre><code>&gt;&gt;&gt; [i for i in l if i and i[0] in 'tT' and all(j not in i for j in '789')] ['tata1', 'tata2', 'Tata3', 't2'] </code></pre> <p>So from left to right this will test:</p> <ul> <li>non empty string</li> <li>starts with <code>'t</code>' or <code>'T'</code></li> <li>has any of the digits <code>'7'</code>, <code>'8'</code>, or <code>'9'</code></li> </ul> <p>These conditions will "short circuit" meaning upon the first test failing, there is no need to check the following conditions as <code>False and (anything)</code> is always <code>False</code>.</p>
2
2016-10-09T21:21:09Z
[ "python", "python-2.7", "python-3.x", "for-loop", "filter" ]
One line python code to remove all the strings that doesn't start with T or t and if they contain number greater then 6
39,948,626
<p>Eg:</p> <pre><code>List=["tata1","tata2","Tata3","mdkjd","djhdj","Tata8","t9","t2"] </code></pre> <p>Output should be:<code>["tata1","tata2","Tata3","t2"]</code></p> <p>I tried :</p> <pre><code>content = [item for item in List if terminal.lower().startswith('t')] </code></pre> <p>My doubt if I can append one more condition with the if I used in my code?</p> <p>If yes, how?</p> <p>I tried writing but it gives error.</p>
0
2016-10-09T21:18:05Z
39,948,731
<p>Matching your required output requires using <code>all</code> and <code>not in</code> to check that none of the <code>'789'</code> characters are contained in your input string while also checking for the starting characters:</p> <pre><code>res = [s for s in List if s[0] in ('tT') and all(j not in s for j in '789')] </code></pre> <p>Now <code>res</code> contains:</p> <pre><code>['tata1', 'tata2', 'Tata3', 't2'] </code></pre>
0
2016-10-09T21:28:38Z
[ "python", "python-2.7", "python-3.x", "for-loop", "filter" ]
One line python code to remove all the strings that doesn't start with T or t and if they contain number greater then 6
39,948,626
<p>Eg:</p> <pre><code>List=["tata1","tata2","Tata3","mdkjd","djhdj","Tata8","t9","t2"] </code></pre> <p>Output should be:<code>["tata1","tata2","Tata3","t2"]</code></p> <p>I tried :</p> <pre><code>content = [item for item in List if terminal.lower().startswith('t')] </code></pre> <p>My doubt if I can append one more condition with the if I used in my code?</p> <p>If yes, how?</p> <p>I tried writing but it gives error.</p>
0
2016-10-09T21:18:05Z
39,950,542
<pre><code>import re print filter(lambda x: re.match(r'^[Tt].*[0-6]',x),l) </code></pre>
0
2016-10-10T02:29:31Z
[ "python", "python-2.7", "python-3.x", "for-loop", "filter" ]
What does the star in the field_name input mean in the Python str.format() docs?
39,948,673
<p>In "6.1.3. Format String Syntax" in the Python 3.5.2 docs, the <code>field_name</code> for the replacement field grammar for <code>str.format()</code> is written like this:</p> <pre><code>field_name ::= arg_name ("." attribute_name | "[" element_index "]")* </code></pre> <p>What does the star at the very right mean? I can guess that I can get an object's attribute with <code>arg_name.attribute</code> or element with <code>arg_name[element_index]</code>, but I don't know if that extra star means I can do more with the object. I'm guessing it means that <code>.attribute_name</code> and <code>[element_index]</code> are optional, but I thought the parentheses already implied that. </p>
0
2016-10-09T21:21:41Z
39,948,891
<p><a href="https://docs.python.org/3/reference/introduction.html#notation" rel="nofollow">Python Language Reference, section 1.2.</a> says:</p> <blockquote> <p>The descriptions of lexical analysis and syntax use a modified BNF grammar notation. This uses the following style of definition:</p> <pre><code>name ::= lc_letter (lc_letter | "_")* lc_letter ::= "a"..."z" </code></pre> <p>The first line says that a <code>name</code> is an <code>lc_letter</code> followed by a sequence of zero or more <code>lc_letter</code>s and underscores. An <code>lc_letter</code> in turn is any of the single characters <code>'a'</code> through <code>'z'</code>. (This rule is actually adhered to for the names defined in lexical and grammar rules in this document.)</p> <p>Each rule begins with a name (which is the name defined by the rule) and <code>::=</code>. A vertical bar (<code>|</code>) is used to separate alternatives; it is the least binding operator in this notation. A star (<code>*</code>) means zero or more repetitions of the preceding item; likewise, a plus (<code>+</code>) means one or more repetitions, and a phrase enclosed in square brackets (<code>[ ]</code>) means zero or one occurrences (in other words, the enclosed phrase is optional). The <code>*</code> and <code>+</code> operators bind as tightly as possible; parentheses are used for grouping. Literal strings are enclosed in quotes. White space is only meaningful to separate tokens. Rules are normally contained on a single line; rules with many alternatives may be formatted alternatively with each line after the first beginning with a vertical bar.</p> </blockquote> <p>So, asterisk <code>*</code> means, as expected, zero or more repetitions of the preceding group.</p>
1
2016-10-09T21:48:37Z
[ "python", "documentation" ]
Django Template - Cannot iterate throught this list
39,948,719
<p>I am passing this object to my template from my view with the name <code>student_collection</code></p> <pre><code>&lt;class 'list'&gt;: [[31, 'John', ‘Jacob', '1'], [31, 'Jeffrey', ‘Mark', '2'], [39, ‘Borris', ‘Hammer', '1']] </code></pre> <p>And accessing it as such in my template:</p> <pre><code>{% for rows in student_collection %} &lt;tr&gt; {% for items in rows %} {% for entry in items %} &lt;td&gt;{{ entry }}&lt;/td&gt; {% endfor %} {% endfor %} &lt;/tr&gt; {% endfor %} </code></pre> <p>I am getting an error at the point <code>{% for entry in items %}</code> django says 'int' <code>object is not iterable</code> why is that I was expecting to iterate through <code>31,John,Jacob,1</code> . Any help in this regard would be appreciated.</p>
1
2016-10-09T21:27:23Z
39,948,755
<blockquote> <p>I was expecting to iterate through <code>31,John,Jacob,1</code></p> </blockquote> <p>Then you wouldn't need that second inner loop. The first loop gives you each sublist/row in the list of rows, while the inner loop iterates through each row, producing each of the items/entries:</p> <pre><code>{% for rows in student_collection %} &lt;tr&gt; {% for item in row %} &lt;td&gt;{{ item }}&lt;/td&gt; {% endfor %} &lt;/tr&gt; {% endfor %} </code></pre>
2
2016-10-09T21:31:29Z
[ "python", "django" ]
Reading and Wrtiting Fifo Files between C and Python
39,948,721
<p>In general, I am creating two fifo queues to be read and written to by my .c and .py programs. To enable my .c program to interact with python, I have included the <code>&lt;python2.7/Python.h&gt;</code> library. </p> <p>Firstly, my .c program creates a file called CFifo and writes text to it using fprintf. No problem there.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include &lt;python2.7/Python.h&gt; int main() { FILE *CFifo, *pythonFifo, *pythonFile; char buffer[1024]; // declare python Py_SetProgramName("writer.py"); // init python Py_Initialize(); // open python pythonFile = fopen("writer.py", "r"); // C writes to file, python reads from this file CFifo = fopen("./CFifo", "w"); // Print strings to file using fprintf fprintf(CFifo, "This is a test"); // close file python reads fclose(CFifo); </code></pre> <p>The second part of my C program should read the information written (in the second fifo queue) by my python program but instead it just hangs in the terminal when opening <code>./pythonFifo</code>.</p> <pre><code> // make second fifo queue // python writes to this file, C reads from it mkfifo("./pythonFifo", 0777); // run python program PyRun_SimpleFile(pythonFile, "writer.py"); pythonFifo = fopen("./pythonFifo", "r"); while(fgets (buffer, sizeof(buffer), pythonFifo)) { printf("%s", buffer); } // close python Py_Finalize(); fclose(pythonFifo); remove("./pythonFifo"); return 0; } </code></pre> <p>This is the python section responsible for writing to the fifo queue.</p> <pre><code># open fifo file that python writes to filename_write = "./pythonFifo" pipe = os.open(filename_write, os.O_WRONLY) for output in finalStringList: os.write(pipe, output) os.close(pipe) </code></pre> <p>The purpose of the second file is to write modified information read from the first file.</p>
0
2016-10-09T21:27:31Z
39,949,691
<p>You can't get there from here. From the <code>mkfifo</code> man page...</p> <blockquote> <p>Once you have created a FIFO special file in this way, any process can open it for reading or writing, in the same way as an ordinary file. However, it has to be open at both ends simultaneously before you can proceed to do any input or output operations on it. Opening a FIFO for reading normally blocks until some other process opens the same FIFO for writing, and vice versa.</p> </blockquote> <p>Both sides need to open the file before they can continue. But since <code>PyRun_SimpleFile</code> runs a python script sychronously, the latter C code that opens the file is never reached. If you try to open it in the C code first, it would hang before running the python code. You have a classic deadlock.</p> <p>I added several prints to your sample and was able to see the program advance as I did <code>cat pythonFifo</code> and <code>echo foo &gt; pythonFifo</code> in a separate console. It returned garbage of course, but proved the problem.</p> <p>Actually, you can get there from here (again, the man page)</p> <blockquote> <p>See fifo(7) for nonblocking handling of FIFO special files.</p> </blockquote> <p>but you open yourself to more deadlocking if your python code writes more than fits in the pipe. You may be better off having your python program write to some variable and have your C code read it from there.</p>
1
2016-10-09T23:50:50Z
[ "python", "c", "file-io", "fifo" ]
How to fix django send mail?
39,948,749
<p>I'm trying to send mail in django project for several days.I've got documentation from djangoproject.com, but that's not working for me. my settings.py contains these lines of code for sending mail:</p> <pre><code>EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_PASSWORD = '**********' #my gmail account's password EMAIL_HOST_USER = 'showkatalisalim@gmail.com' </code></pre> <p>my views.py contains these lines for contactform:</p> <pre><code>def contactForm(request): form = LocalContactForm(request.POST or None) if form.is_valid(): send_mail( 'Subject here', 'Here is the message.', settings.EMAIL_HOST_USER, ['zellaic.showkatali@gmail.com'], fail_silently=False, ) return HttpResponseRedirect('thanks') context = {"page":"contact_form", "title":"Contact with us", "form":form} return render(request, 'form.html', context) </code></pre> <p>While I'm trying send mail via my form: It show up:</p> <pre><code>SMTPAuthenticationError at /contact/ (534, '5.7.14 &lt;https://accounts.google.com/signin/continue? sarp=1&amp;scc=1&amp;plt=AKgnsbtZ\n5.7.14 4CcZKxu-As7S5tfd-3YTAz6XMdwLYcJKWk7_bViejaO8v_-mx-aD8PLO5zixLUMbTv38LY\n5.7.14 qE3ifOl5aXJOXaOVN5jU9Tl-HJVDj1_bc0n9nJ4PHERsBsyu8L0JRr9rM3ED0TdFXLV3wl\n5.7.14 _GF3jCTuCHIydf-YXcFZidIIqrERHyAORvqYmuPs0qHd_rt3ecbJUBOIW9PvzOXxGBiXg2\n5.7.14 ehh9XhyakjWXfOEuJgbxiNBMdCIM0&gt; Please log in via your web browser and\n5.7.14 then try again.\n5.7.14 Learn more at\n5.7.14 https://support.google.com/mail/answer/78754 ao5sm46546625pad.1 - gsmtp') Request Method: POST Request URL: http://www.zellaic.com/contact/ Django Version: 1.10.1 Exception Type: SMTPAuthenticationError Exception Value: (534, '5.7.14 &lt;https://accounts.google.com/signin/continue?sarp=1&amp;scc=1&amp;plt=AKgnsbtZ\n5.7.14 4CcZKxu-As7S5tfd-3YTAz6XMdwLYcJKWk7_bViejaO8v_-mx-aD8PLO5zixLUMbTv38LY\n5.7.14 qE3ifOl5aXJOXaOVN5jU9Tl-HJVDj1_bc0n9nJ4PHERsBsyu8L0JRr9rM3ED0TdFXLV3wl\n5.7.14 _GF3jCTuCHIydf-YXcFZidIIqrERHyAORvqYmuPs0qHd_rt3ecbJUBOIW9PvzOXxGBiXg2\n5.7.14 ehh9XhyakjWXfOEuJgbxiNBMdCIM0&gt; Please log in via your web browser and\n5.7.14 then try again.\n5.7.14 Learn more at\n5.7.14 https://support.google.com/mail/answer/78754 ao5sm46546625pad.1 - gsmtp') Exception Location: /usr/lib64/python2.7/smtplib.py in login, line 621 Python Executable: /usr/local/bin/python Python Version: 2.7.5 Python Path: ['/home/showkatali/webapps/zellaic/lib/python2.7/Django-1.10.1-py2.7.egg', '/home/showkatali/webapps/zellaic', '/home/showkatali/webapps/zellaic/src', '/home/showkatali/webapps/zellaic/lib/python2.7', '/home/showkatali/lib/python2.7/pip-8.1.2-py2.7.egg', '/home/showkatali/lib/python2.7', '/usr/lib64/python27.zip', '/usr/lib64/python2.7', '/usr/lib64/python2.7/plat-linux2', '/usr/lib64/python2.7/lib-tk', '/usr/lib64/python2.7/lib-old', '/usr/lib64/python2.7/lib-dynload', '/usr/lib64/python2.7/site-packages', '/usr/lib64/python2.7/site-packages/PIL', '/usr/lib64/python2.7/site-packages/geos', '/usr/lib/python2.7/site-packages'] </code></pre> <p>And while I'm trying to use these lines into shell, It show up:</p> <pre><code>send_mail('subject', 'sometext', settings.EMAIL_HOST_USER, ['zellaic.showkatali@gmail.com'], fail_silently = False) Traceback (most recent call last): File "&lt;console&gt;", line 1, in &lt;module&gt; File "/home/endless/Desktop/project/webfaction/env/local/lib/python2.7/site- packages/django/core/mail/__init__.py", line 62, in send_mail return mail.send() File "/home/endless/Desktop/project/webfaction/env/local/lib/python2.7/site- packages/django/core/mail/message.py", line 342, in send return self.get_connection(fail_silently).send_messages([self]) File "/home/endless/Desktop/project/webfaction/env/local/lib/python2.7/site- packages/django/core/mail/backends/smtp.py", line 100, in send_messages new_conn_created = self.open() File "/home/endless/Desktop/project/webfaction/env/local/lib/python2.7/site- packages/django/core/mail/backends/smtp.py", line 67, in open self.connection.login(self.username, self.password) </code></pre> <p>At this moment, What should I do? Need any configuration of my gmail account ?</p>
0
2016-10-09T21:30:47Z
39,950,691
<p>Here is an implementation for gmail using standard <code>email</code> and <code>smtplib</code> packages (note different port and host in settings):</p> <pre><code>//settings.py EMAIL_HOST = 'smtp.googlemail.com' #XXX EMAIL_PORT = 465 #XXX EMAIL_HOST_PASSWORD = '**********' EMAIL_HOST_USER = '***@gmail.com' </code></pre> <p>Code:</p> <pre><code>import smtplib from email import encoders from email.mime.multipart import MIMEMultipart from email.mime.base import MIMEBase from email.mime.text import MIMEText from email.utils import COMMASPACE, formatdate from django.conf import settings #send_to is a list of recipient emails def send_mail(send_to, subject, body): msg = MIMEMultipart() msg['From'] = settings.EMAIL_HOST_USER msg['To'] = COMMASPACE.join(send_to) msg['Date'] = formatdate(localtime = True) msg['Subject'] = subject msg.attach(MIMEText(body)) server_ssl = smtplib.SMTP_SSL(settings.EMAIL_HOST, settings.EMAIL_PORT) server_ssl.ehlo() server_ssl.login(settings.EMAIL_HOST_USER, settings.EMAIL_HOST_PASSWORD) server_ssl.sendmail(settings.EMAIL_HOST_USER, send_to, msg.as_string()) server_ssl.close() </code></pre>
0
2016-10-10T02:53:05Z
[ "python", "django", "email" ]
Is there any way to take the user's input in one variable and use that input in another variable?
39,948,754
<p>Is there any way to take the user's input in one variable and use that input in another variable?</p> <p>For example:</p> <pre><code>def user_input(): numb = input("Please input the number ") numb_process() def numb_process(): if numb == '1': print("Good") else: print("Bad") user_input() </code></pre>
-5
2016-10-09T21:31:28Z
39,948,823
<p>This is python 101 and the standard <a href="https://docs.python.org/3/tutorial/index.html" rel="nofollow">python tutorial</a> is a good place to learn basic concepts. In your case, simple parameter passing will do.</p> <pre><code>def user_input(): numb = input("Input number ") # bind result of the input function # to local variable "numb" numb_process(numb) # pass the object bound to "numb" # to called function def numb_process(some_number): # bind inbound object to local variable # "some_number" if some_number == '1': # use bound object in calculations print("Good") else: print("Bad") user_input() </code></pre>
2
2016-10-09T21:38:41Z
[ "python", "python-3.x" ]
Is there any way to take the user's input in one variable and use that input in another variable?
39,948,754
<p>Is there any way to take the user's input in one variable and use that input in another variable?</p> <p>For example:</p> <pre><code>def user_input(): numb = input("Please input the number ") numb_process() def numb_process(): if numb == '1': print("Good") else: print("Bad") user_input() </code></pre>
-5
2016-10-09T21:31:28Z
39,948,829
<p>It should work. You can call the numb_process function by giving it an argument "numb" that will move from the function "user_input" to function "numb_process".</p> <pre><code>def user_input(): numb = input("Please input the number ") numb_process(numb) def numb_process(numb): if numb == '1': print("Good") else: print("Bad") user_input() </code></pre>
0
2016-10-09T21:40:12Z
[ "python", "python-3.x" ]
How to delete rows in python pandas DataFrame using regular expressions?
39,948,757
<p>I have a pattern:</p> <pre><code>patternDel = "( \\((MoM|QoQ)\\))"; </code></pre> <p>And I want to delete all rows in pandas dataframe where column <code>df['Event Name']</code> matches this pattern. Which is the best way to do it? There are more than 100k rows in dataframe.</p>
0
2016-10-09T21:31:40Z
39,949,288
<p><a href="http://pandas.pydata.org/pandas-docs/version/0.18.1/generated/pandas.Series.str.contains.html" rel="nofollow">str.contains()</a> returns a Series of booleans that we can use to index our frame</p> <pre><code>patternDel = "( \\((MoM|QoQ)\\))" filter = df['Event Name'].str.contains(patternDel) </code></pre> <p>I tend to keep the things we want as opposed to delete rows. Since filter represents things we want to delete we use <code>~</code> to get all the rows that don't match and keep them</p> <pre><code>df = df[~filter] </code></pre>
1
2016-10-09T22:44:42Z
[ "python", "regex", "pandas" ]
How to generate all possible combinations of 0-1 matrix in Python?
39,948,902
<p>How can generate all possible combinations of a 0-1 matrix of size K by N?</p> <p>For example, if I take K=2 and N=2, I get the following combinations.</p> <pre><code>combination 1 [0, 0; 0, 0]; combination 2 [1, 0; 0, 0]; combination 3 [0, 1; 0, 0]; combination 4 [0, 0; 1, 0]; combination 5 [0, 0; 0, 1]; combination 6 [1, 1; 0, 0]; combination 7 [1, 0; 1, 0]; combination 8 [1, 0; 0, 1]; combination 9 [0, 1; 1, 0]; combination 10 [0, 1; 0, 1]; combination 11 [0, 0; 1, 1]; combination 12 [1, 1; 1, 0]; combination 13 [0, 1; 1, 1]; combination 14 [1, 0; 1, 1]; combination 15 [1, 1; 0, 1]; combination 16 [1, 1; 1, 1]; </code></pre>
3
2016-10-09T21:49:24Z
39,948,977
<p>A one-liner solution with <code>numpy</code> and <code>itertools</code>:</p> <pre><code>[np.reshape(np.array(i), (K, N)) for i in itertools.product([0, 1], repeat = K*N)] </code></pre> <p><em>Explanation:</em> the <code>product</code> function returns a Cartesian product of its input. For instance, <code>product([0, 1], [0, 1])</code> returns an iterator that comprises all possible permutations of <code>[0, 1]</code> and <code>[0, 1]</code>. In other words, drawing from a product iterator:</p> <pre><code>for i, j in product([0, 1], [0, 1]): </code></pre> <p>is actually equivalent to running two nested for-loops:</p> <pre><code>for i in [0, 1]: for j in [0, 1]: </code></pre> <p>The for-loops above already solve the problem at hand for a specific case of <code>K, N = (1, 0)</code>. Continuing the above line of thought, to generate all possible zero/one states of a vector <code>i</code>, we need to draw samples from an iterator that is equivalent to a nested for-loop of depth <code>l</code>, where <code>l = len(i)</code>. Luckily, <code>itertools</code> provides the framework to do just that with its <code>repeat</code> keyword argument. In the case of OP's problem this permutation depth should be <code>K*N</code>, so that it can be reshaped into a numpy array of proper sizes during each step of the list comprehension.</p>
4
2016-10-09T22:01:02Z
[ "python", "combinations" ]
How to generate all possible combinations of 0-1 matrix in Python?
39,948,902
<p>How can generate all possible combinations of a 0-1 matrix of size K by N?</p> <p>For example, if I take K=2 and N=2, I get the following combinations.</p> <pre><code>combination 1 [0, 0; 0, 0]; combination 2 [1, 0; 0, 0]; combination 3 [0, 1; 0, 0]; combination 4 [0, 0; 1, 0]; combination 5 [0, 0; 0, 1]; combination 6 [1, 1; 0, 0]; combination 7 [1, 0; 1, 0]; combination 8 [1, 0; 0, 1]; combination 9 [0, 1; 1, 0]; combination 10 [0, 1; 0, 1]; combination 11 [0, 0; 1, 1]; combination 12 [1, 1; 1, 0]; combination 13 [0, 1; 1, 1]; combination 14 [1, 0; 1, 1]; combination 15 [1, 1; 0, 1]; combination 16 [1, 1; 1, 1]; </code></pre>
3
2016-10-09T21:49:24Z
39,949,551
<p>An alternative approach to using <code>itertools.product</code> that is faster:</p> <pre><code>def using_shifts(K, N): shifter = numpy.arange(K*N).reshape( (K, N) ) return [(x &gt;&gt; shifter) % 2 for x in range(2 ** (K*N))] </code></pre> <p>How does this work? We are exploiting that each desired array of <code>0</code> and <code>1</code> will correspond to the binary expansion of an integer. For an integer <code>x</code> to find bit at index <code>y</code> we need to compute <code>(x &gt;&gt; y) % 2</code>. </p> <p>So here we can use <code>numpy</code> operations to find an array of indexes using the corresponding array operations.</p> <p>Compared to <code>itertools.product</code>, relative timing is:</p> <ul> <li><code>using_shifts(2, 5)</code>: 1.9ms</li> <li><code>using_itertools(2, 5)</code>: 2.8ms</li> </ul>
2
2016-10-09T23:26:03Z
[ "python", "combinations" ]
'AttributeError:' when I try to unpickle dictionary
39,948,903
<p>I have made a program on python 3.5 which you can find out the password linked to a username, make a new password for an existing user and add a new user and password to the dictionary then pickles it so every time I load the program all the usernames and passwords will be there.</p> <p>The error that comes up is after you create the pickle file(after running it for the first time) then on line 6 the error</p> <pre><code>AttributeError: Can't get attribute 'NewPass' on &lt;module '__main__' (built-in)&gt; </code></pre> <p>occurs.</p> <p>Here is my script:</p> <pre><code>import sys import pickle import os if os.path.exists("branston.p"): LOGG = pickle.load(open('branston.p', 'rb')) else: LOGG = {'Sam': ('CHRIST')} def Find(): Username = input("Say a Username.") print (LOGG[Username]) def NewPass(): Username = Input("Enter your username.") Newpass = input("Enter your new password") if NewPass == input("Confirm password"): LOGG[Username] = (NewPass) def NewEntry(): NewUser = input("Enter your new username.") Newpass = input("Enter your new password.") LOGG[NewUser] = (NewPass) loop = True while loop == True: function = input("Say what you want me to do.'Find', 'NewPass', 'NewEntry', 'Stop'.") if function == ("Find"): Find() elif function == ("NewPass"): NewPass() elif function == ("NewEntry"): NewEntry() elif function == ("Stop"): f = open('branston.p', 'wb') pickle.dump(LOGG, f) f.close() sys.exit() </code></pre> <p>Any help would be appreciated. Thanks!</p>
0
2016-10-09T21:49:31Z
39,949,156
<p>When you do this</p> <pre><code>LOGG[NewUser] = (NewPass) </code></pre> <p>You are assigning the function <code>NewPass</code> to your dict entry. You are probably intending to assign the password string and therefore it should be.</p> <pre><code>LOGG[NewUser] = Newpass </code></pre> <p>Note: Parenthesis are superfluous. I'd also suggest avoiding using upper case letters as the first character of your variable names, as otherwise it is easy to confuse variable and function names.</p>
2
2016-10-09T22:24:00Z
[ "python", "python-3.x", "dictionary", "pickle" ]
Multiplying pandas dataframe and series, element wise
39,948,935
<p>Lets say I have a pandas series:</p> <pre><code>import pandas as pd x = pd.DataFrame({0: [1,2,3], 1: [4,5,6], 2: [7,8,9] }) y = pd.Series([-1, 1, -1]) </code></pre> <p>I want to multiply x and y in such a way that I get z:</p> <pre><code>z = pd.DataFrame({0: [-1,2,-3], 1: [-4,5,-6], 2: [-7,8,-9] }) </code></pre> <p>In other words, if element j of the series is -1, then all elements of the j-th row of x get multiplied by -1. If element k of the series is 1, then all elements of the j-th row of x get multiplied by 1. </p> <p>How do I do this?</p>
0
2016-10-09T21:54:19Z
39,949,068
<p>You can do that:</p> <pre><code>&gt;&gt;&gt; new_x = x.mul(y, axis=0) &gt;&gt;&gt; new_x 0 1 2 0 -1 -4 -7 1 2 5 8 2 -3 -6 -9 </code></pre>
3
2016-10-09T22:12:41Z
[ "python", "pandas" ]
Multiplying pandas dataframe and series, element wise
39,948,935
<p>Lets say I have a pandas series:</p> <pre><code>import pandas as pd x = pd.DataFrame({0: [1,2,3], 1: [4,5,6], 2: [7,8,9] }) y = pd.Series([-1, 1, -1]) </code></pre> <p>I want to multiply x and y in such a way that I get z:</p> <pre><code>z = pd.DataFrame({0: [-1,2,-3], 1: [-4,5,-6], 2: [-7,8,-9] }) </code></pre> <p>In other words, if element j of the series is -1, then all elements of the j-th row of x get multiplied by -1. If element k of the series is 1, then all elements of the j-th row of x get multiplied by 1. </p> <p>How do I do this?</p>
0
2016-10-09T21:54:19Z
39,949,077
<p>As Abdou points out, the answer is </p> <pre><code>z = x.apply(lambda col: col*y) </code></pre> <p>Moreover, if you instead have a DataFrame, e.g. </p> <pre><code> y = pandas.DataFrame({"colname": [1,-1,-1]}) </code></pre> <p>Then you can do </p> <pre><code> z = x.apply(lambda z: z*y["colname"]) </code></pre>
1
2016-10-09T22:13:36Z
[ "python", "pandas" ]
Multiplying pandas dataframe and series, element wise
39,948,935
<p>Lets say I have a pandas series:</p> <pre><code>import pandas as pd x = pd.DataFrame({0: [1,2,3], 1: [4,5,6], 2: [7,8,9] }) y = pd.Series([-1, 1, -1]) </code></pre> <p>I want to multiply x and y in such a way that I get z:</p> <pre><code>z = pd.DataFrame({0: [-1,2,-3], 1: [-4,5,-6], 2: [-7,8,-9] }) </code></pre> <p>In other words, if element j of the series is -1, then all elements of the j-th row of x get multiplied by -1. If element k of the series is 1, then all elements of the j-th row of x get multiplied by 1. </p> <p>How do I do this?</p>
0
2016-10-09T21:54:19Z
39,949,089
<p>You can multiply the dataframes directly.</p> <pre><code>x * y </code></pre>
0
2016-10-09T22:15:43Z
[ "python", "pandas" ]
Python : Hash extension attack in python
39,949,030
<p>I want to use h to generate the same md5 as b</p> <p>Here is the code:</p> <pre><code>k = "secret" m = "show me the grade" m2 = "show me the grade and change it to 100" x = " and change it to 100" a = md5(k + m) b = md5(k + m2) print "have---&gt; " + a.hexdigest() #9f4bb32ac843d6db979ababa2949cb52 print "want---&gt; " + b.hexdigest() #aba1d6fede83a87d9d6e22bf75974599 h = md5(state="9f4bb32ac843d6db979ababa2949cb52".decode("hex"),count=512) h.update(x) print h.hexdigest() # these two lines get 958acc96a173fd4d7571ac365db06f65 print md5((k + m + padding(len(k + m)*8))+ x).hexdigest() def padding(msg_bits): """padding(msg_bits) - Generates the padding that should be appended to the end of a message of the given size to reach a multiple of the block size.""" index = int((msg_bits &gt;&gt; 3) &amp; 0x3f) if index &lt; 56: padLen = (56 - index) else: padLen = (120 - index) # (the last 8 bytes store the number of bits in the message) return PADDING[:padLen] + _encode((msg_bits &amp; 0xffffffffL, msg_bits&gt;&gt;32), 8) </code></pre> <p>I don't know why the last line couldn't output aba1d6fede83a87d9d6e22bf75974599. Is there something wrong with the padding?</p>
0
2016-10-09T22:09:05Z
39,949,464
<p>This is because the hash you expected (aba1..) is the md5 hash of <code>k + m + x</code> while the hash you got (958a..) is the md5 hash of <code>k + m + padding + x</code>.</p> <p>The length extension attack lets you generate a hash <code>h2 = md5(k + m + padding + x)</code> based on only knowing the hash <code>h1 = md5(k + m)</code> and the length of the message <code>l = len(k + m)</code>. However, as far as I know, it doesn't let you get rid of the padding between the messages, so you're left with some garbage in between.</p>
0
2016-10-09T23:12:54Z
[ "python", "md5" ]
Python function to create an array of particular column of csv file
39,949,206
<p>I need to write a function that, given a CSV file name as a string and a column number, will create an array with the distinct values in that particular column of the file. Assuming my first column is 0 just like in Python lists. This file also has a header and footer row.</p> <pre><code>import csv def facet(file, column): """ (str, int) -&gt; array Gets a list of distinct values from the specified column in the input file. """ </code></pre>
-1
2016-10-09T22:32:26Z
40,127,840
<p>Try the following:</p> <pre><code>import csv def facet(file, column): with open(file, newline='') as f_input: return [row[column] for row in csv.reader(f_input)][1:-1] print(facet('input.csv', 1)) </code></pre> <p>The reads the file as a <code>csv</code> and uses a list comprehension to select only only cell from each row and build a list. Finally <code>[1:-1</code> is used to skip over header and footer in your file.</p>
0
2016-10-19T09:49:23Z
[ "python", "arrays", "python-3.x", "csv" ]
Pandas reading from csv file and filling missing values for datetime index
39,949,432
<p>I have data in a csv file which appears as:</p> <pre><code> DateTime Temp 10/1/2016 0:00 20.35491156 10/1/2016 1:00 19.75320845 10/1/2016 4:00 17.62411292 10/1/2016 5:00 18.30190001 10/1/2016 6:00 19.37101638 </code></pre> <p>I am reading this file into csv file as:</p> <pre><code>import numpy as np import pandas as pd data = pd.read_csv(r'C:\Curve.csv', index_col='DateTime') newIndex = pd.date_range(np.min(data.index), np.max(data.index),freq='1H') data.reindex(newIndex) </code></pre> <p>My goal is to backfill the missing hours 2 and 3 with 19.75320845. i.e. every time there is are missing data it should do the backfill.</p>
0
2016-10-09T23:08:09Z
39,949,714
<pre><code>import pandas as pd data = pd.read_csv(r'Curve.csv', index_col='DateTime', parse_dates=['DateTime']) data = data.asfreq('1H', method='ffill') </code></pre> <p>yields</p> <pre><code> Temp DateTime 2016-10-01 00:00:00 20.354912 2016-10-01 01:00:00 19.753208 2016-10-01 02:00:00 19.753208 2016-10-01 03:00:00 19.753208 2016-10-01 04:00:00 17.624113 2016-10-01 05:00:00 18.301900 2016-10-01 06:00:00 19.371016 </code></pre> <p><code>method='ffill'</code> tells <code>asfreq</code> to "forward-fill" missing values using the last valid (non-NaN) value.</p>
3
2016-10-09T23:55:02Z
[ "python", "pandas" ]
Specifying custom nested objects in Django Rest Framework ModelSerializer
39,949,434
<p>I have lat, long specified in my DB as:</p> <pre><code>... lat = models.DecimalField(_('Latitude'), max_digits=8, decimal_places=5, null=True, blank=True) lng = models.DecimalField(_('Longitude'), max_digits=8, decimal_places=5, null=True, blank=True) ... </code></pre> <p>I want my ModalSerialization to come out as:</p> <pre><code>{ ... "location": { "lat": ..., "long": ... } ... } </code></pre> <p>How do I achieve that?</p>
-1
2016-10-09T23:08:49Z
39,950,486
<p>One of the way is you can create a property in a model like below.</p> <pre><code>@property def location_info(self): return dict( lat=self.lat, lng=self.lng ) </code></pre> <p>Then you can create a dict field in your serializer and specify source as your property. Since it is property it can be readonly field.</p> <pre><code>location = serializers.DictField(source='location_info', read_only=True) </code></pre>
1
2016-10-10T02:19:58Z
[ "python", "django", "django-rest-framework" ]
Flask G variable Simple example
39,949,455
<p>From what i understand a g variable is a temporary storage that last form one single request to the other. For example i was thinking it should work like this. But i can seem to get it to work.</p> <pre><code>from flask import Flask, g, redirect, url_for app = Flask(__name__) @app.route('/') def hello_world(): g = "hello world" return redirect(url_for('test')) @app.route('/test') def test(): return str(g) if __name__ == "__main__": app.run(debug=True) </code></pre>
-1
2016-10-09T23:12:03Z
39,955,536
<p>Flask <code>g</code> is available in application context and lasts for the lifetime of the request.</p> <p><code>What is application context?</code></p> <p>As cited on <a href="http://flask.pocoo.org/docs/0.11/appcontext/" rel="nofollow">Application Context Page</a>, flask app is in many states while being executed.</p> <blockquote> <p>One of the design ideas behind Flask is that there are two different “states” in which code is executed. The application setup state in which the application implicitly is on the module level. It starts when the Flask object is instantiated, and it implicitly ends when the first request comes in. While the application is in this state a few assumptions are true:</p> <ul> <li>the programmer can modify the application object safely.</li> <li>no request handling happened so far</li> <li>you have to have a reference to the application object in order to modify it, there is no magic proxy that can give you a reference to the application object you’re currently creating or modifying.</li> </ul> <p>In contrast, during request handling, a couple of other rules exist:</p> <ul> <li>while a request is active, the context local objects (flask.request and others) point to the current request.</li> <li>any code can get hold of these objects at any time.</li> </ul> <p>There is a third state which is sitting in between a little bit. Sometimes you are dealing with an application in a way that is similar to how you interact with applications during request handling; just that there is no request active. Consider, for instance, that you’re sitting in an interactive Python shell and interacting with the application, or a command line application.</p> </blockquote> <p>So, basically while you run the app, it exits in many states.</p> <p>Example : One is serving your requests, one is watching the files for reloading.</p> <p>If you ever use <a href="http://www.celeryproject.org/" rel="nofollow">Celery</a>, then you would have to run it in separate application context. That is when role of <code>g</code> comes into play. One very common use of celery is to send mails asynchronously. Imagine you catch a request and after processing it you need to send a mail. You can store the user information in <code>g</code> to be passed to celery.</p>
3
2016-10-10T09:45:52Z
[ "python", "flask" ]
Capturing all operators, parentheses and numbers separately in "(3 + 44)* 5 / 7" with Regex
39,949,497
<p>For input string: <code>st = "(3 + 44)* 5 / 7"</code></p> <p>I'm looking to get the following result using only regex: <code>["(", "3", "+", "44", ")", "*", "5", "/", "7"]</code></p> <p>Attempts:</p> <ol> <li><pre><code>&gt;&gt;&gt; re.findall("[()\d+\-*/].?", st) ['(3', '+ ', '44', ')*', '5 ', '/ ', '7'] </code></pre> <p>But I need to capture the parentheses in <code>'(3'</code> and <code>')*'</code> separately as well. </p></li> <li><pre><code>&gt;&gt;&gt; re.findall("[()\d+\-*/]?", st) ['(', '3', '', '+', '', '4', '4', ')', '*', '', '5', '', '/', '', '7', ''] </code></pre> <p>This gives tons of blank tokens.</p></li> </ol>
2
2016-10-09T23:18:46Z
39,949,523
<p>You can't use multi-character constructs like <code>\d+</code> in a character class.</p> <p>So you can do it by brute force like this:</p> <pre><code>re.findall(r"\(|\)|\d+|-|\*|/", st) </code></pre> <p>Or you can use a character class for single-character tokens, alternated with other things:</p> <pre><code>re.findall(r"[()\-*/]|\d+", st) </code></pre>
3
2016-10-09T23:22:02Z
[ "python", "regex", "tokenize" ]
In Python 2, How to raise a Python error without changing its traceback?
39,949,525
<p>In the following typical try-except block:</p> <pre><code>try: do something except Exception as e: {clean up resources} raise e ^ </code></pre> <p>However, this will print out an error message with traceback pointing to ^, where the error is raised, in contrast to most other languages, where the traceback of e when it is first generated is remembered and printed instead.</p> <p>The Python style of handling exception creates significant difficulty in figuring out the source of the error, and I would like to override it. Is there a simple way of doing this?</p>
0
2016-10-09T23:22:34Z
39,949,830
<p>To catch an exception, do something with it and then re-raise the same exception:</p> <pre><code>try: do something except Exception as e: {clean up resources} raise # raises the same exception with the same traceback </code></pre> <p>To catch an exception, raise a new exception, but keep the old traceback:</p> <pre><code>try: do something except Exception as e: exctype, value, traceback = sys.exc_info() raise NewException, 'Argument for new exception', traceback </code></pre> <p>This is described in <a href="https://docs.python.org/2.7/reference/simple_stmts.html#the-raise-statement" rel="nofollow">Python 2.7 specification section 6.9</a>:</p> <blockquote> <p>If no expressions are present, raise re-raises the last exception that was active in the current scope. If no exception is active in the current scope, a TypeError exception is raised indicating that this is an error (if running under IDLE, a Queue.Empty exception is raised instead).</p> <p>Otherwise, raise evaluates the expressions to get three objects, using None as the value of omitted expressions. The first two objects are used to determine the type and value of the exception.</p> <p>...</p> <p>If a third object is present and not None, it must be a traceback object (see section The standard type hierarchy), and it is substituted instead of the current location as the place where the exception occurred.</p> </blockquote> <h2>Python 3</h2> <p>Note that in Python 3, the original traceback is always preserved when raising from the <code>except</code> block. In other cases, syntax <code>raise Exception() from another_exception</code> is used.</p>
3
2016-10-10T00:16:03Z
[ "python", "exception", "exception-handling" ]
How do I suppress printing under certain circumstances in python?
39,949,527
<p>I have written following code in python for a simulation of an ATM:</p> <pre><code>withd = int(input("How much do you want to withdraw? ")) # Withdrawal shown to customer print("Withdrawal: ", withd, " CHF") # 100 bills a = withd // 100 a_rest = withd % 100 # 50 bills b = a_rest // 50 b_rest = a_rest % 50 # 20 bills c = b_rest // 20 c_rest = b_rest % 20 # 10 bills d = c_rest // 10 print("100", a) print("50", b) print("20", c) print("10", d) </code></pre> <p>If I type in 50 in the beginning, I get following output:</p> <pre><code>How much do you want to withdraw? 50 Withdrawal: 50 CHF 100 0 50 1 20 0 10 0 </code></pre> <p>I want to change the display, so that in the output it shows only the bills that are being used, which in this case would be only the <code>50</code> bill. All bills which aren't used shouldn't be printed. Is there a way to change the output in that direction?</p>
-1
2016-10-09T23:22:43Z
39,949,607
<p>The solution is obviously to check <code>if a&gt;0:</code>, <code>if b&gt;0:</code> and so on. But what about throwing in a loop, so you don't have to hardcode the conditions for all the bills?</p> <pre><code>withd = int(input("How much do you want to withdraw? ")) # Withdrawal shown to customer print("Withdrawal: ", withd, " CHF") bills = [100, 50, 20, 10] res = {} rest = withd for bill in bills: res[bill] = rest // bill rest = rest % bill if res[bill] &gt; 0: print(bill, res[bill]) </code></pre> <p>In this example you also store the number of bills in a dictionary if you need also it for further computations</p>
0
2016-10-09T23:34:32Z
[ "python" ]
Extracting a data from dictionary in python
39,949,545
<pre><code>list1 = ["a","c","d"] dict1 = {"a":9, "b":2, "c":5, "d":9, "e":6, "f":7 } </code></pre> <p>I want to get only list1's word from dict1.</p> <p>The following is the result I want to get.</p> <pre><code>{"a":9, "c":5, "d":9} </code></pre> <p>What am I supposed to do?</p>
-1
2016-10-09T23:25:22Z
39,949,562
<p>You can use a <em>dictionary comprehension</em> to do this:</p> <pre><code>&gt;&gt;&gt; list1 = ["a","c","d"] &gt;&gt;&gt; dict1 = {"a":9, "b":2, "c":5, "d":9, "e":6, "f":7 } &gt;&gt;&gt; {k: dict1[k] for k in list1} {'c': 5, 'd': 9, 'a': 9} </code></pre> <p>This works as long as the dictionary keys contains all the items in <code>list1</code>, otherwise you may use a filter, to test for items in <code>list1</code> that are not in the dictionary:</p> <pre><code>&gt;&gt;&gt; {k: dict1[k] for k in list1 if k in dict1} {'c': 5, 'd': 9, 'a': 9} </code></pre>
4
2016-10-09T23:27:19Z
[ "python", "list", "dictionary" ]
Can Python "os.environ.get" ever return a non-string?
39,949,587
<p>In this code <a href="https://github.com/chimpler/pyhocon/blob/master/pyhocon/config_parser.py#L291" rel="nofollow">here</a>, they use <code>os.environ</code> to get the value of an environment variable, and then immediately check to see if it is an instance of their custom classes.</p> <pre><code>value = os.environ.get(variable) ... elif isinstance(value, ConfigList) or isinstance(value, ConfigTree): </code></pre> <p>Is it actually possible that the <code>value</code> will be an instance of their custom classes? Is this dead code?</p>
0
2016-10-09T23:31:04Z
39,949,644
<p>Anything that comes from the <em>outside</em> will be just a string, I guess.</p> <p>On the other hand if you are adding something to the environment from the Python code, then you have just a bit more freedom.</p> <p>Adding anything but a string still fails:</p> <pre><code>&gt;&gt;&gt; os.environ['a'] = 89 Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "C:\Program Files\Python27\lib\os.py", line 420, in __setitem__ putenv(key, item) TypeError: must be string, not int </code></pre> <p>However, you could make your own class inherited from str:</p> <pre><code>class C(str): pass os.environ['a'] = C() </code></pre> <p>In Python2 this seems to do the trick:</p> <pre><code>&gt;&gt;&gt; type(os.environ['a']) &lt;class '__main__.C'&gt; </code></pre> <p>However, in Python 3 it does not. It looks like it just saves a string:</p> <pre><code>&gt;&gt;&gt; type(os.environ['a']) &lt;class 'str'&gt; </code></pre> <hr> <p>Still, that does not explain the code from <a href="https://github.com/chimpler/pyhocon/blob/master/pyhocon/config_parser.py#L291" rel="nofollow">pyhocon</a>. I don't see how that object could be pushed into <code>os.environ</code>.</p> <p>Unless they monkeypatched <code>os.environ</code>... In that case, anything would be possible.</p>
1
2016-10-09T23:41:44Z
[ "python", "environment-variables" ]
Can Python "os.environ.get" ever return a non-string?
39,949,587
<p>In this code <a href="https://github.com/chimpler/pyhocon/blob/master/pyhocon/config_parser.py#L291" rel="nofollow">here</a>, they use <code>os.environ</code> to get the value of an environment variable, and then immediately check to see if it is an instance of their custom classes.</p> <pre><code>value = os.environ.get(variable) ... elif isinstance(value, ConfigList) or isinstance(value, ConfigTree): </code></pre> <p>Is it actually possible that the <code>value</code> will be an instance of their custom classes? Is this dead code?</p>
0
2016-10-09T23:31:04Z
39,949,658
<p>The <code>os.environ</code> is just a simple mapping of <code>name: value</code>. It just adds some flavour on top of a dict to interact with the environment. Environment variables do not have type - their plain strings.</p> <p>You can set variable types in bash, but this is not passed on to other programs.</p> <pre><code>$ declare -xi FOO=2 $ python -c 'import os;print(type(os.environ["FOO"]))' </code></pre> <p>Even when you call a process from inside of python, you cannot pass other types than <code>str</code> or <code>bytes</code>.</p> <pre><code>In [4]: subprocess.check_output(['python', '-c', 'import os;print(os.environ["FOO"])'], env={"FOO": 2}) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-4-94f33d136e8f&gt; in &lt;module&gt;() ----&gt; 1 subprocess.check_output(['python', '-c', 'import os;print(os.environ["FOO"])'], env={"FOO": 2}) </code></pre>
0
2016-10-09T23:43:37Z
[ "python", "environment-variables" ]
pandas read_csv create columns based on value in one of the csv columns
39,949,597
<p>I have csv data that looks like this:</p> <pre><code>1471361094509,doorLowerPosition,-73.3348875 1471361094509,doorUpperPosition,-3.29595 1471361094512,sectionLowerCurrFiltered,-0.2 1471361094512,actuatorLowerFrontDuty,0.0 1471361094515,doorCtrlStatus,5.0 1471361094515,SMState,14.0 1471361094516,lateralAccel,25.55 1471361094516,longitudinalAccel,25.55 1471361094519,ambientTemperature,23.5 </code></pre> <p>Which I would like to import into a DataFrame with the the leftmost value being the index, the middle a column identifier and the rightmost, the value for the column at that index.</p> <p>Previously I was separating these and importing them manually, then joining into a single frame. I wonder if there is quicker way to do it in one step.</p>
0
2016-10-09T23:33:05Z
39,949,636
<p>Read the data into a DataFrame using <code>pd.read_csv</code>, and then <a href="http://pandas.pydata.org/pandas-docs/stable/reshaping.html#reshaping-by-pivoting-dataframe-objects" rel="nofollow"><code>pivot</code></a>:</p> <pre><code>import pandas as pd df = pd.read_csv('data', header=None, names=['index','columns','value']) df = df.pivot('index', 'columns', 'value') print(df) </code></pre> <p>yields</p> <pre><code>columns SMState actuatorLowerFrontDuty ambientTemperature \ index 1471361094509 NaN NaN NaN 1471361094512 NaN 0.0 NaN 1471361094515 14.0 NaN NaN 1471361094516 NaN NaN NaN 1471361094519 NaN NaN 23.5 columns doorCtrlStatus doorLowerPosition doorUpperPosition \ index 1471361094509 NaN -73.334887 -3.29595 1471361094512 NaN NaN NaN 1471361094515 5.0 NaN NaN 1471361094516 NaN NaN NaN 1471361094519 NaN NaN NaN columns lateralAccel longitudinalAccel sectionLowerCurrFiltered index 1471361094509 NaN NaN NaN 1471361094512 NaN NaN -0.2 1471361094515 NaN NaN NaN 1471361094516 25.55 25.55 NaN 1471361094519 NaN NaN NaN </code></pre>
3
2016-10-09T23:39:25Z
[ "python", "pandas" ]
How do you combine variables to form function in python?
39,949,625
<pre><code>ypos = 1 ypos2 = ypos-1 xpos = 1 xpos2 = 2 </code></pre> <p>Using these variables, that are changed each time the code loops, how do I get it to print the result below?</p> <pre><code>=B(ypos)-B(ypos2) </code></pre> <p>Every time the code loops the ypos increases by one and therefore the ypos2 increases by one</p> <p>so as the code loops the results should be 1) B1-B0 2) B2-B1 3) B3-B2 etc.</p> <p>Any help is much appreciated, and if you don't understand the question let me know, I wasn't quite sure how to explain it.(P.S. I am using python2.7)</p> <p>Thanks, Anthony</p>
0
2016-10-09T23:37:33Z
39,949,650
<pre><code>print('B({})-B({})'.format(ypos, ypos2)) </code></pre> <p>or</p> <pre><code>print('B(' + str(ypos) + ')-B(' + str(ypos2) + ')') </code></pre> <p>These should work in Python 2.7 or Python 3.x.</p>
2
2016-10-09T23:42:53Z
[ "python", "excel", "string", "python-2.7", "function" ]
How do you combine variables to form function in python?
39,949,625
<pre><code>ypos = 1 ypos2 = ypos-1 xpos = 1 xpos2 = 2 </code></pre> <p>Using these variables, that are changed each time the code loops, how do I get it to print the result below?</p> <pre><code>=B(ypos)-B(ypos2) </code></pre> <p>Every time the code loops the ypos increases by one and therefore the ypos2 increases by one</p> <p>so as the code loops the results should be 1) B1-B0 2) B2-B1 3) B3-B2 etc.</p> <p>Any help is much appreciated, and if you don't understand the question let me know, I wasn't quite sure how to explain it.(P.S. I am using python2.7)</p> <p>Thanks, Anthony</p>
0
2016-10-09T23:37:33Z
39,949,683
<p>This should be it:</p> <pre><code>print 'B({})-B({})'.format(ypos, ypos2) </code></pre> <p>For python2.7 prints are without parentheses, unlike in python3. Check this to verify <a href="https://docs.python.org/2/tutorial/inputoutput.html" rel="nofollow">link</a></p>
1
2016-10-09T23:49:34Z
[ "python", "excel", "string", "python-2.7", "function" ]
Confused by python's unicode regex errors
39,949,679
<p>Can someone explain why the middle code excerpt in python 2.7x throws an error?</p> <pre><code>import re walden = "Waldenström" walden print(walden) s1 = "ö" s2 = "Wal" s3 = "OOOOO" out = re.sub(s1, s3, walden) print(out) out = re.sub("W", "w", walden) print(out) # I need this one to work out = re.sub('W', u'w', walden) # ERROR out = re.sub(u'W', 'w', walden) print(out) out = re.sub(s2, s1, walden) print(out) </code></pre> <p>I'm very confused and have tried reading the manual</p>
1
2016-10-09T23:48:28Z
39,949,732
<p><code>walden</code> is a <code>str</code>:</p> <pre><code>walden = "Waldenström" </code></pre> <p>This code replaces a character with a <code>unicode</code> string:</p> <pre><code>re.sub('W', u'w', walden) </code></pre> <p>The result of that should be <code>u'w' + "aldenström"</code>. This is the part that fails.</p> <p>In order to concatenate <code>str</code> and <code>unicode</code>, both have to be first converted to <code>unicode</code>. The result is <code>unicode</code> as well.</p> <p>The problem is, the interpreter does not know how to convert <code>'ö'</code> to unicode, because it does not know which encoding to use. The result is ambiguous.</p> <p>The solution is to convert yourself before doing the replacement:</p> <pre><code>re.sub('W', u'w', unicode(walden, encoding)) </code></pre> <p>The <code>encoding</code> should be the one you use to create that file, e.g.</p> <pre><code>re.sub('W', u'w', unicode(walden, 'utf-8')) </code></pre>
2
2016-10-09T23:59:14Z
[ "python", "unicode" ]
Django: python manage.py makemigrations returns IntegrityError: Column 'content_type_id' cannot be null
39,949,719
<p>I hooked up my Django project the the MySQL Database, and I am certain that it is actually connected because when I try to makemigrations. I checked MySQL workbench and all my models are synced into the database. However, the problem is when i try to migrate, I get this error. It is complaining that No migrations to apply because mysql.connector.errors.IntegrityError: 1048 (23000): Column 'content_type_id' cannot be null. I am not even sure where content_type_id is coming from because my model doesn't even have that. </p> <pre><code>Operations to perform: Target specific migration: 0001_initial, from bookSell Running migrations: No migrations to apply. Traceback (most recent call last): File "/Users/JenniferLiu/.virtualenvs/bookSell/lib/python3.5/site-packages/mysql/connector/django/base.py", line 177, in _execute_wrapper return method(query, args) File "/Users/JenniferLiu/.virtualenvs/bookSell/lib/python3.5/site-packages/mysql/connector/cursor.py", line 515, in execute self._handle_result(self._connection.cmd_query(stmt)) File "/Users/JenniferLiu/.virtualenvs/bookSell/lib/python3.5/site-packages/mysql/connector/connection.py", line 488, in cmd_query result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query)) File "/Users/JenniferLiu/.virtualenvs/bookSell/lib/python3.5/site-packages/mysql/connector/connection.py", line 395, in _handle_result raise errors.get_exception(packet) mysql.connector.errors.IntegrityError: 1048 (23000): Column 'content_type_id' cannot be null During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 10, in &lt;module&gt; execute_from_command_line(sys.argv) File "/Users/JenniferLiu/.virtualenvs/bookSell/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/Users/JenniferLiu/.virtualenvs/bookSell/lib/python3.5/site-packages/django/core/management/__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/JenniferLiu/.virtualenvs/bookSell/lib/python3.5/site-packages/django/core/management/base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "/Users/JenniferLiu/.virtualenvs/bookSell/lib/python3.5/site-packages/django/core/management/base.py", line 345, in execute output = self.handle(*args, **options) File "/Users/JenniferLiu/.virtualenvs/bookSell/lib/python3.5/site-packages/django/core/management/commands/migrate.py", line 224, in handle self.verbosity, self.interactive, connection.alias, apps=post_migrate_apps, plan=plan, File "/Users/JenniferLiu/.virtualenvs/bookSell/lib/python3.5/site-packages/django/core/management/sql.py", line 53, in emit_post_migrate_signal **kwargs File "/Users/JenniferLiu/.virtualenvs/bookSell/lib/python3.5/site-packages/django/dispatch/dispatcher.py", line 191, in send response = receiver(signal=self, sender=sender, **named) File "/Users/JenniferLiu/.virtualenvs/bookSell/lib/python3.5/site-packages/django/contrib/auth/management/__init__.py", line 83, in create_permissions Permission.objects.using(using).bulk_create(perms) File "/Users/JenniferLiu/.virtualenvs/bookSell/lib/python3.5/site-packages/django/db/models/query.py", line 452, in bulk_create ids = self._batched_insert(objs_without_pk, fields, batch_size) File "/Users/JenniferLiu/.virtualenvs/bookSell/lib/python3.5/site-packages/django/db/models/query.py", line 1068, in _batched_insert self._insert(item, fields=fields, using=self.db) File "/Users/JenniferLiu/.virtualenvs/bookSell/lib/python3.5/site-packages/django/db/models/query.py", line 1045, in _insert return query.get_compiler(using=using).execute_sql(return_id) File "/Users/JenniferLiu/.virtualenvs/bookSell/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 1054, in execute_sql cursor.execute(sql, params) File "/Users/JenniferLiu/.virtualenvs/bookSell/lib/python3.5/site-packages/django/db/backends/utils.py", line 79, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "/Users/JenniferLiu/.virtualenvs/bookSell/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/Users/JenniferLiu/.virtualenvs/bookSell/lib/python3.5/site-packages/mysql/connector/django/base.py", line 227, in execute return self._execute_wrapper(self.cursor.execute, query, new_args) File "/Users/JenniferLiu/.virtualenvs/bookSell/lib/python3.5/site-packages/mysql/connector/django/base.py", line 183, in _execute_wrapper utils.IntegrityError(err.msg), sys.exc_info()[2]) File "/Users/JenniferLiu/.virtualenvs/bookSell/lib/python3.5/site-packages/django/utils/six.py", line 685, in reraise raise value.with_traceback(tb) File "/Users/JenniferLiu/.virtualenvs/bookSell/lib/python3.5/site-packages/mysql/connector/django/base.py", line 177, in _execute_wrapper return method(query, args) File "/Users/JenniferLiu/.virtualenvs/bookSell/lib/python3.5/site-packages/mysql/connector/cursor.py", line 515, in execute self._handle_result(self._connection.cmd_query(stmt)) File "/Users/JenniferLiu/.virtualenvs/bookSell/lib/python3.5/site-packages/mysql/connector/connection.py", line 488, in cmd_query result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query)) File "/Users/JenniferLiu/.virtualenvs/bookSell/lib/python3.5/site-packages/mysql/connector/connection.py", line 395, in _handle_result raise errors.get_exception(packet) django.db.utils.IntegrityError: Column 'content_type_id' cannot be null </code></pre> <p>Here is my model.py:</p> <pre><code>class Book(models.Model): title = models.CharField(max_length=200,default='') author = models.CharField(max_length=200,default='') year_published = models.DateField(default='1998-09-18') description = models.CharField(max_length = 500,default='') rating = models.IntegerField(default=1) </code></pre> <p>This is migrations 0001_initial.py:</p> <pre><code>class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Book', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(default='', max_length=200)), ('author', models.CharField(default='', max_length=200)), ('year_published', models.DateField(default='1998-09-18')), ('description', models.CharField(default='', max_length=500)), ('rating', models.IntegerField(default=1)), ], ), ] </code></pre> <p>python manage.py makemigrations worked fine. This was the result</p> <pre><code>Migrations for 'bookSell': bookSell/migrations/0001_initial.py: - Create model Book </code></pre> <p>Much help is appreciated, thank you, please leave a comment if any additional information is needed to solve this problem. :D</p> <p>EDIT 2 Setting.py </p> <pre><code>INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'bookSell', ] </code></pre> <p>So I manage to get python to runserver, and in admin I do get it to run with the Books Model, but issue is that when i try to add books. I get the error, Column 'user_id' cannot be null</p>
2
2016-10-09T23:55:53Z
39,949,904
<blockquote> <p>I am certain that it is actually connected because when I try to makemigrations. I checked MySQL workbench and all my models are synced into the database.</p> </blockquote> <p>It sounds more like you are connecting to a database that was already being used for something, or you have run <code>migrate</code> on this database before. <code>makemigrations</code> does not make any changes to the database. The only thing it does is to create a set of files in the migrations folder of your apps.</p> <p>There could be several </p> <p>The content_type_id comes from the <a href="https://docs.djangoproject.com/en/1.10/ref/contrib/contenttypes/" rel="nofollow">content types frame work</a> which means one of the libraries you are using probably uses a generic foreign key.</p> <p>There are several things you could try, if this is a new installation without any data, just drop the database and start again.</p>
0
2016-10-10T00:31:34Z
[ "python", "mysql", "django" ]
How can I use auto increment in my composite unique key in Django?
39,949,728
<p>I have a model class like this:</p> <pre><code>class TestModel(models.Model): class Meta: unique_together = ('prefix', 'number') prefix = models.CharField(max_length=30) number = models.IntegerField() </code></pre> <p>prefix and number together form a natural key for my model, but I don't particularly care what the number is. Thus, auto increment (not per-prefix) would be fine. I don't want to have to specify the number, but I want to be able to (e.g. because there are existing prefix+number pairs that need to put into this system).</p> <p>For eaxmple, most times I'd just want to use auto increment:</p> <pre><code>'the_prefix', 1 'the_prefix', 2 </code></pre> <p>However, I might want to use particular (prefix, number) combination in a few cases, such as (prefix, number) pairs from a legacy system:</p> <pre><code>'manually', 2 # number is not unique alone... 'manually', 4 # ... or sequential </code></pre> <hr> <p>As I understand it,</p> <ul> <li>only Single-column PKs are supported, so I can't use prefix+number as a composite PK directly;</li> <li>only AutoField is auto-incrementing, and there can be only one AutoField per model (and it must be the PK), so I can't have both id &amp; number auto incremented; and</li> <li>instead making prefix+id unique together makes no sense, as id is already unique on its own.</li> </ul> <p>Is there a way to achieve this (or is one of my statements wrong)? If there is a database-agnostic solution, that would of course be preferred, but otherwise, SQLite (development) and MySQL (production) are most important to me personally.</p> <p>Workarounds are also welcome - I'm trying to use the PK as "default" for number, but</p> <ul> <li>keeping number blank to specify the default defeats the unique constraint, and</li> <li>to copy the id, one needs to save the object without a number first. I struggle to implement this in a way that seems reliable and transparent to the user</li> </ul>
1
2016-10-09T23:58:09Z
39,967,356
<p>Here is a proof-of-concept approach, it's by no means production ready, but it seems to demonstrate the heavy lifting necessary to achieve this. I don't claim that's a clean or good way.</p> <p>Anyway, here it is:</p> <pre><code>class Subquery(str): query = None class MyIntegerField(models.IntegerField): def get_prep_value(self, value): value = super(models.IntegerField, self).get_prep_value(value) if value is None: return None if isinstance(value, models.QuerySet): subquery = Subquery() subquery.query = '({} WHERE %s = "")'.format(value.query) return subquery return int(value) def get_placeholder(self, value, compiler, connection): if isinstance(value, Subquery): return value.query return "%s" class TestModel(models.Model): class Meta: unique_together = ('prefix', 'number') prefix = models.CharField(max_length=30) number = MyIntegerField() def __str__(self): return "{}: {} {}".format(self.id, self.prefix, self.number) </code></pre> <p>Now you can do this:</p> <pre><code>In [1]: from app.models import TestModel In [2]: from django.db.models import * In [3]: next_number = TestModel.objects.all() \ ...: .annotate(max=Func(F('number'), function='MAX')) \ ...: .annotate(result=Case(When(max=None, then=0), default='max') + 1) \ ...: .values('result') In [4]: str(next_number.query) Out[4]: 'SELECT (CASE WHEN MAX("app_testmodel"."number") IS NULL THEN 0 ELSE MAX("app_testmodel"."number") END + 1) AS "result" FROM "app_testmodel"' In [5]: TestModel(prefix='the_prefix', number=next_number).save() In [6]: TestModel(prefix='the_prefix', number=next_number).save() In [7]: TestModel(prefix='manually', number=2).save() In [8]: TestModel(prefix='manually', number=4).save() In [9]: TestModel.objects.all() Out[9]: [&lt;TestModel: 1: the_prefix 1&gt;, &lt;TestModel: 2: the_prefix 2&gt;, &lt;TestModel: 3: manually 2&gt;, &lt;TestModel: 4: manually 4&gt;] </code></pre> <p>How it works:</p> <ul> <li>Before being passed into a query, the field value is processed with <code>get_prep_value</code></li> <li>We use this to replace <code>QuerySet</code> values by the SQL that evaluates them. To make the query pass, the "field value" must still translate to a SQL-valid value, which is why <code>Subquery</code> is a subclass of <code>str</code> - to the database, a <code>Subquery</code> is an empty string.</li> <li>The subquery is used as part of the <code>INSERT</code> query via <code>get_placeholder</code>. The placeholder must consume the field value; in this draft, a <code>WHERE %s = ""</code> is appended to the subquery, which of course does <em>not</em> work for all possible queries.</li> <li>The query used in this situation (<code>next_number</code>) computes the maximum <code>number</code> and returns that plus 1, i.e. auto-increment</li> </ul> <p>The result is a query like this:</p> <pre><code>INSERT INTO app_testmodel(..., number, ...) VALUES(..., (SELECT ...), ...) </code></pre> <p>Working from there, it should be easy to implement a custom <code>AutoField</code>, thus solving the problem.</p>
0
2016-10-10T21:55:44Z
[ "python", "mysql", "django", "database", "sqlite" ]
When accessing dictionary values, how to impute 'NaN' if no value exists for a certain key?
39,949,766
<p>I am looping through dictionaries and accessing the dictionary values to append to a list. </p> <p>Consider one dictionary as an example, <code>example_dict</code>:</p> <pre><code>example_dict = {"first":241, "second": 5234, "third": "Stevenson", "fourth":3.141592...} first_list = [] second_list = [] third_list = [] fourth_list = [] ... first_list.append(example_dict["first"]) # append the value for key "first" second_list.append(example_dict["second"]) # append the value for key "second" third_list.append(example_dict["third"]) # append the value for key "third" fourth_list.append(example_dict["fourth"]) # append the value for key "fourth" </code></pre> <p>I am looping through hundreds of dictionaries. It is possible that some keys do not have values. In this case, I would like an <code>NaN</code> appended to the lists---after running the script, each list should have the same number of elements. </p> <p>If <code>new_dict = {"first":897, "second": '', "third": "Duchamps", ...}</code>, then <code>second_list.append(new_dict["second"])</code> would append <code>NaN</code>. </p> <p>How does one write in a check for this to occur? An if statement?</p>
0
2016-10-10T00:04:31Z
39,949,782
<p>You can perform a check for values that are not <code>""</code> and simply do something like this:</p> <pre><code>second_list.append(new_dict["second"] if new_dict["second"] != "" else "NaN")) </code></pre> <p>So, if key <code>second</code> exists in <code>new_dict</code> and is an empty string, then <code>NaN</code> will be appended to <code>second_list</code>. </p> <p>If you were looking to create a list of values from the dictionary applying the logic above, you can do the following, both are the same, first is expanded, and the second is the shortened comprehension: </p> <h1>method 1</h1> <pre><code>new_dict = {"first":897, "second": '', "third": "Duchamps"} new_list = [] for _, v in new_dict.items(): if v != "": new_list.append(v) else: new_list.append('NaN') </code></pre> <h1>method 2 (comprehension)</h1> <pre><code>new_dict = {"first":897, "second": '', "third": "Duchamps"} new_list = [v if v != "" else 'NaN' for _, v in new_dict.items()] </code></pre>
2
2016-10-10T00:06:35Z
[ "python", "python-3.x", "dictionary", null, "key-value" ]
How to make code that's functionally similar to enumerate without actually using enumerate?
39,949,783
<p>I suppose to write a code that prints out the value of a number that occurs twice in the list given, but they don't allow us to use a built in function on python. How would I be able to write it without using enumerate? </p> <pre><code>def find_second_occurrence(xs,v): count = 0 value = None for i, x in enumerate(xs): if v == x: count += 1 if count == 2: return i if (count &lt; 2): return value </code></pre>
0
2016-10-10T00:06:42Z
39,949,872
<p><code>enumerate(sequence)</code> is pretty much similar to a construct of the form:</p> <pre><code>for i in range(len(sequence)): # get sequence[i] and return i and sequence[i] for all i's </code></pre> <p>So, in your code, replacing <code>enumerate</code> altogether could be done by:</p> <pre><code>for i in range(len(xs)): x = xs[i] if v == x: count += 1 if count == 2: return i </code></pre> <p>Or, without assigning to an <code>x</code> name to temporarily hold the sequence item:</p> <pre><code>for i in range(len(xs)): if v == xs[i]: count += 1 if count == 2: return i </code></pre> <p>Creating a little <code>my_enumerate</code> function, is also rather simple:</p> <pre><code>def my_enumerate(sequence, start=0): for i in range(len(sequence)): yield start+i, sequence[i] </code></pre> <p><code>start</code> has also been defined as to match that as used in <code>enumerate</code> and gets a default value of <code>0</code>.</p> <p>Rather than <code>yield</code>ing values (if this is mystifying to you), you can create a list (generator comprehensions are similar to <code>yield</code>ing) comprehension and return that instead:</p> <pre><code>def my_enumerate(sequence, start=0): return [(start+i, sequence[i]) for i in range(len(sequence))] </code></pre>
0
2016-10-10T00:24:11Z
[ "python", "list", "function", "python-3.x", "enumerate" ]
How to make code that's functionally similar to enumerate without actually using enumerate?
39,949,783
<p>I suppose to write a code that prints out the value of a number that occurs twice in the list given, but they don't allow us to use a built in function on python. How would I be able to write it without using enumerate? </p> <pre><code>def find_second_occurrence(xs,v): count = 0 value = None for i, x in enumerate(xs): if v == x: count += 1 if count == 2: return i if (count &lt; 2): return value </code></pre>
0
2016-10-10T00:06:42Z
39,949,908
<p>Your own enumerate function might be something like this: </p> <pre><code>def my_enumerate(a_list): result = [] counter = 0 for item in a_list: result.append((counter, item)) counter += 1 return result </code></pre> <p>Unlike the built-in <code>enumerate</code>, which is a generator that yields one item at a time, your function is returning a list. </p>
0
2016-10-10T00:32:12Z
[ "python", "list", "function", "python-3.x", "enumerate" ]
How to zoom in a histogram in seaborn/matplotlib?
39,949,841
<p>I produced a histogram which looks something like this:</p> <p><a href="http://i.stack.imgur.com/M96Am.png" rel="nofollow"><img src="http://i.stack.imgur.com/M96Am.png" alt="enter image description here"></a></p> <p>Code that I used to produce this plot:</p> <pre><code>sns.countplot(table.column_name) </code></pre> <p>As you can notice, the entire histogram gets clustered at the left end due to uneven distribution of data.</p> <p>How do I zoom in at the left end?</p> <p>One way that I tried and it gave me a marginally better result was :</p> <pre><code>plt.xlim(0,25) </code></pre> <p>Is there a better way to do this?</p>
-1
2016-10-10T00:18:19Z
39,949,881
<p>Looks like the data would be better viewed on a logarithmic scale. On your matplotlib plot axis, <code>ax</code>, use:</p> <pre><code>ax.set_yscale('log') </code></pre>
-1
2016-10-10T00:26:30Z
[ "python", "matplotlib", "histogram", "seaborn" ]
How to direct directory from file to another on Mac
39,949,879
<p>So I am currently trying to install python3 into my Mac and whenever I type in </p> <pre><code>which python3 </code></pre> <p>It gives me the response of </p> <pre><code>/usr/local/bin/python3 </code></pre> <p>However, I want it to point to this directory below:</p> <pre><code>/usr/local/Cellar/python3/3.5.2_2/bin/python3 </code></pre> <p>How do I make this happen? Please Help!!</p>
0
2016-10-10T00:26:13Z
39,949,957
<p>When you install <code>python</code> with brew, it will actually create a symlink from <code>/usr/loca/bin/...</code> to <code>/usr/loca/Cellar/...</code>. You can check this for example by running this command:</p> <pre><code>$ ls -l /usr/local/bin/python3 lrwxr-xr-x 1 mfischer admin 35 3 Aug 07:34 /usr/local/bin/python3 -&gt; ../Cellar/python3/3.5.1/bin/python3 </code></pre> <p>If this is not the case, simply recreate the link.</p> <pre><code>rm /usr/local/bin/python3 ln -s /usr/local/Cellar/python3/3.5.2_2/bin/python3 /usr/local/bin/python3 </code></pre>
0
2016-10-10T00:43:13Z
[ "python", "python-3.x", "terminal", "directory" ]
Get the index of the max value using argmax in numpy array
39,949,887
<ol> <li><p>I have allocated about 34G of memory and read the data in: sst = np.empty([365,3600,7200], dtype-np.float32)</p></li> <li><p>using the argmax(sst,axis=0) to get the index of the max value for each pixel. </p></li> <li><p>the memory error problem appeared when running the program.</p></li> </ol> <p>Can anyone help me with this? Are there any other ways to get the index of the max value for each pixel [365,3600,7200]? Thank you!</p>
1
2016-10-10T00:27:12Z
39,950,506
<p><a href="https://github.com/numpy/numpy/blob/v1.11.0/numpy/core/fromnumeric.py#L917-L974" rel="nofollow">This source code</a> shows that argMax returns an array populated by the max on that axis. Instead of doing this, you could say allocate a new array for each axis, and do np.argMax on that array. If you make sure to overwrite the old array after getting the index of that max value you should have less memory issues. </p> <p>If you're doing a lot of stuff dealing with out-of-memory problems, it may be worth looking into <a href="http://dask.pydata.org/en/latest/array.html" rel="nofollow">dask</a>.</p>
0
2016-10-10T02:23:17Z
[ "python", "numpy" ]
Python pandas interpolating series
39,949,897
<p>I have data in a csv file which appears as:</p> <pre><code> DateTime Temp 10/1/2016 0:00 20.35491156 10/1/2016 1:00 19.75320845 10/1/2016 4:00 17.62411292 10/1/2016 5:00 18.30190001 10/1/2016 6:00 19.37101638 </code></pre> <p>I am reading this file from csv file as:</p> <pre><code>import numpy as np import pandas as pd d2 = pd.Series.from_csv(r'C:\PowerCurve.csv') d3 = d2.interpolate(method='time') </code></pre> <p>My goal is to fill the missing hours 2 and 3 with interpolation based on nearby values. i.e. every time there is are missing data it should do the interpolation.</p> <p>However, d3 doesn't show any interpolation.</p> <p>Edit: Based on suggestions below my Python 2.7 still errors out. I am trying the following:</p> <pre><code>import pandas as pd d2 = pd.Series.from_csv(r'C:\PowerCurve.csv') d2.set_index('DateTime').resample('H').interpolate() </code></pre> <p>Error is:</p> <pre><code>File "C:\Python27\lib\site-packages\pandas\core\generic.py", line 2672, in __getattr__ return object.__getattribute__(self, name) AttributeError: 'Series' object has no attribute 'set_index' </code></pre>
1
2016-10-10T00:29:20Z
39,949,953
<p>Use resample with datetime as index and use one of the methods of <a href="http://pandas.pydata.org/pandas-docs/stable/timeseries.html#resampling" rel="nofollow">resampling</a> that fits your need. For instance:</p> <pre><code>df.set_index('DateTime').resample('1H').pad() Out[23]: Temp DateTime 2016-10-01 00:00:00 20.354912 2016-10-01 01:00:00 19.753208 2016-10-01 02:00:00 19.753208 2016-10-01 03:00:00 19.753208 2016-10-01 04:00:00 17.624113 2016-10-01 05:00:00 18.301900 2016-10-01 06:00:00 19.371016 </code></pre>
2
2016-10-10T00:42:20Z
[ "python", "pandas", "interpolation" ]
Python pandas interpolating series
39,949,897
<p>I have data in a csv file which appears as:</p> <pre><code> DateTime Temp 10/1/2016 0:00 20.35491156 10/1/2016 1:00 19.75320845 10/1/2016 4:00 17.62411292 10/1/2016 5:00 18.30190001 10/1/2016 6:00 19.37101638 </code></pre> <p>I am reading this file from csv file as:</p> <pre><code>import numpy as np import pandas as pd d2 = pd.Series.from_csv(r'C:\PowerCurve.csv') d3 = d2.interpolate(method='time') </code></pre> <p>My goal is to fill the missing hours 2 and 3 with interpolation based on nearby values. i.e. every time there is are missing data it should do the interpolation.</p> <p>However, d3 doesn't show any interpolation.</p> <p>Edit: Based on suggestions below my Python 2.7 still errors out. I am trying the following:</p> <pre><code>import pandas as pd d2 = pd.Series.from_csv(r'C:\PowerCurve.csv') d2.set_index('DateTime').resample('H').interpolate() </code></pre> <p>Error is:</p> <pre><code>File "C:\Python27\lib\site-packages\pandas\core\generic.py", line 2672, in __getattr__ return object.__getattribute__(self, name) AttributeError: 'Series' object has no attribute 'set_index' </code></pre>
1
2016-10-10T00:29:20Z
39,953,120
<p>use the <code>interpolate</code> method after <code>resample</code> on an hourly basis.</p> <pre><code>d2.set_index('DateTime').resample('H').interpolate() </code></pre> <p>If <code>d2</code> is a series then we don't need the set_index</p> <pre><code>d2.resample('H').interpolate() </code></pre> <p><a href="http://i.stack.imgur.com/cMbuU.png" rel="nofollow"><img src="http://i.stack.imgur.com/cMbuU.png" alt="enter image description here"></a></p>
1
2016-10-10T07:23:00Z
[ "python", "pandas", "interpolation" ]
Unable to scrape this movie website using BeautifulSoup
39,949,917
<p>I am trying to scrap a movie website here: <a href="http://www.21cineplex.com/nowplaying" rel="nofollow">http://www.21cineplex.com/nowplaying</a></p> <p>I have uploaded the screenshot with the HTML body as the image in this questions.<a href="http://i.stack.imgur.com/OncE1.png" rel="nofollow">link to screenshot here</a> I am having difficulty trying to grab the movie title and the description which is part of the <code>&lt;P&gt;</code> tag. For some strange reason, the description is not part of requests object. Also when I tried to use soup to find the ul and class name it cannot be found. Anyone know why? I am using python 3. This is my code so far:</p> <pre><code> r = requests.get('http://www.21cineplex.com/nowplaying') r.text (no description here) soup = bs4.BeautifulSoup(r.text) soup.find('ul', class_='w462') # why is this empty? </code></pre>
0
2016-10-10T00:33:37Z
39,950,335
<p>This server is checking <code>Referer</code> header. If there is no <code>Referer</code> it sends main page. But it doesn't check text in this header so it can be even empty string.</p> <pre><code>import requests import bs4 headers = { #'Referer': any url (or even random text, or empty string) #'Referer': 'http://google.com', #'Referer': 'http://www.21cineplex.com', #'Referer': 'hello world!', 'Referer': '', } s = requests.get('http://www.21cineplex.com/nowplaying', headers=headers) soup = bs4.BeautifulSoup(s.text) for x in soup.find_all('ul', class_='w462'): print(x.text) for x in soup.select('ul.w462'): print(x.text) for x in soup.select('ul.w462'): print(x.select('a')[0].text) print(x.select('p')[0].text) </code></pre>
1
2016-10-10T01:50:52Z
[ "python", "html", "web-scraping", "beautifulsoup", "python-requests" ]
beautifulsoup does not find all p with a certain class
39,949,923
<p>I am using beautifulsoup to find all p in a certain html page I saved locally. My code is</p> <pre><code>with open ("./" + str(filename) + ".txt", "r") as myfile: data=myfile.read().replace('\n', '') soup = BeautifulSoup(data) t11 = soup.findAll("p", {"class": "commentsParagraph"}) </code></pre> <p>this codes works for part of the page, but some part of the page is loaded with ajax (which I preloaded before I saved the source), and the code is not working on it.</p> <p>to test this I added to one of the <code>p</code> tags in the ajax portion the class <code>commentsParagraph2</code>, and changed my code to </p> <pre><code>t11 = soup.findAll("p", {"class": "commentsParagraph2"}) </code></pre> <p>but t11 is an empty list.</p> <p>I am attaching the page file as well<a href="https://justpaste.it/z64t" rel="nofollow">here</a></p> <p>Any ideas?</p>
0
2016-10-10T00:35:04Z
39,950,231
<p>I have downloaded you html and done some tests, the beautifulsoup module could only find out three p nodes. And I guess, that's because there is some iframes in the html, so BS does not work probably. My suggestion is using <code>re</code> module instead of <code>bs</code></p> <p>sample code for your reference:</p> <pre><code>import re with open('1.html', 'r') as f: data = f.read() m=re.findall(r'(?&lt;=&lt;p class="commentsParagraph"&gt;)[\!\w\s.\'\,\-\(\)\@\#\$\%\^\&amp;\*\+\=\/|\^&lt;]+(?=&lt;/p&gt;)', data) print(m) </code></pre>
-1
2016-10-10T01:32:20Z
[ "python", "beautifulsoup" ]
beautifulsoup does not find all p with a certain class
39,949,923
<p>I am using beautifulsoup to find all p in a certain html page I saved locally. My code is</p> <pre><code>with open ("./" + str(filename) + ".txt", "r") as myfile: data=myfile.read().replace('\n', '') soup = BeautifulSoup(data) t11 = soup.findAll("p", {"class": "commentsParagraph"}) </code></pre> <p>this codes works for part of the page, but some part of the page is loaded with ajax (which I preloaded before I saved the source), and the code is not working on it.</p> <p>to test this I added to one of the <code>p</code> tags in the ajax portion the class <code>commentsParagraph2</code>, and changed my code to </p> <pre><code>t11 = soup.findAll("p", {"class": "commentsParagraph2"}) </code></pre> <p>but t11 is an empty list.</p> <p>I am attaching the page file as well<a href="https://justpaste.it/z64t" rel="nofollow">here</a></p> <p>Any ideas?</p>
0
2016-10-10T00:35:04Z
39,955,133
<p>There is one p tag with the commentsParagraph2 class in your html which bs4 can find without issue using all three parsers:</p> <pre><code>In [8]: from bs4 import BeautifulSoup ...: soup1 = BeautifulSoup(open("/home/padraic ...: /t.html").read(),"html5lib") ...: soup2 = BeautifulSoup(open("/home/padraic ...: /t.html"),"html.parser") ...: soup3 = BeautifulSoup(open("/home/padraic ...: /t.html"),"lxml") ...: print(soup1.select_one("p.commentsParagraph2")) ...: print(soup2.select_one("p.commentsParagraph2")) ...: print(soup3.select_one("p.commentsParagraph2")) ...: &lt;p class="commentsParagraph2"&gt; So much better than Ryder. Only take Econ 11 if she's one of the professors teaching it. Beware her tests though, which are much different from Ryder's. &lt;/p&gt; &lt;p class="commentsParagraph2"&gt; So much better than Ryder. Only take Econ 11 if she's one of the professors teaching it. Beware her tests though, which are much different from Ryder's. &lt;/p&gt; &lt;p class="commentsParagraph2"&gt; So much better than Ryder. Only take Econ 11 if she's one of the professors teaching it. Beware her tests though, which are much different from Ryder's. &lt;/p&gt; </code></pre> <p>So either you are using the broken and no longer maintained <em>BeautifulSoup3</em> or an older version of bs4.</p>
1
2016-10-10T09:23:58Z
[ "python", "beautifulsoup" ]
Kivy: how to reference widgets from python code?
39,949,990
<p>Basic Kivy question. Given this kv file:</p> <pre><code>BoxLayout: MainMenu: MyCanvasWidget: &lt;MainMenu&gt;: Button: on_press: root.do_action() </code></pre> <p>How do I call a method of MyCanvasWidget (for drawing something) from the do_action method when the button in MainMenu is pressed?</p>
0
2016-10-10T00:49:40Z
39,956,239
<pre><code>BoxLayout: MainMenu: do_action: mycanvas.method MyCanvasWidget: id: mycanvas &lt;MainMenu&gt;: Button: on_press: root.do_action() </code></pre> <p>Got some inspiration from <a href="http://stackoverflow.com/questions/39807997/how-to-access-some-widget-attribute-from-another-widget-in-kivy?rq=1">How to access some widget attribute from another widget in Kivy?</a></p>
0
2016-10-10T10:29:52Z
[ "python", "python-2.7", "kivy", "kivy-language" ]
Get unique entries in list of lists by an item
39,950,042
<p>This seems like a fairly straightforward problem but I can't seem to find an efficient way to do it. I have a list of lists like this:</p> <pre><code>list = [['abc','def','123'],['abc','xyz','123'],['ghi','jqk','456']] </code></pre> <p>I want to get a list of unique entries by the third item in each child list (the 'id'), i.e. the end result should be</p> <pre><code>unique_entries = [['abc','def','123'],['ghi','jqk','456']] </code></pre> <p>What is the most efficient way to do this? I know I can use set to get the unique ids, and then loop through the whole list again. However, there are more than 2 million entries in my list and this is taking too long. Appreciate any pointers you can offer! Thanks. </p>
1
2016-10-10T01:00:45Z
39,950,098
<p>How about this: Create a <code>set</code> that keeps track of ids already seen, and only append sublists where id's where not seen.</p> <pre><code>l = [['abc','def','123'],['abc','xyz','123'],['ghi','jqk','456']] seen = set() new_list = [] for sl in l: if sl[2] not in seen: new_list.append(sl) seen.add(sl[2]) print new_list </code></pre> <p>Result:</p> <pre><code>[['abc', 'def', '123'], ['ghi', 'jqk', '456']] </code></pre>
4
2016-10-10T01:09:29Z
[ "python", "list", "set" ]
Get unique entries in list of lists by an item
39,950,042
<p>This seems like a fairly straightforward problem but I can't seem to find an efficient way to do it. I have a list of lists like this:</p> <pre><code>list = [['abc','def','123'],['abc','xyz','123'],['ghi','jqk','456']] </code></pre> <p>I want to get a list of unique entries by the third item in each child list (the 'id'), i.e. the end result should be</p> <pre><code>unique_entries = [['abc','def','123'],['ghi','jqk','456']] </code></pre> <p>What is the most efficient way to do this? I know I can use set to get the unique ids, and then loop through the whole list again. However, there are more than 2 million entries in my list and this is taking too long. Appreciate any pointers you can offer! Thanks. </p>
1
2016-10-10T01:00:45Z
39,950,105
<p>One approach would be to create an inner loop. within the first loop you iterate over the outer list starting from 1, previously you will need to create an arraylist which will add the first element, inside the inner loop starting from index 0 you will check only if the third element is located as part of the third element within the arraylist current holding elements, if it is not found then on another arraylist whose scope is outside outher loop you will add this element, else you will use "continue" keyword. Finally you will print out the last arraylist created.</p>
0
2016-10-10T01:10:13Z
[ "python", "list", "set" ]
How to join two new numeric columns in a dataframe using a separator?
39,950,057
<p>I have the dataframe df: </p> <pre><code>start end 836 845 3341 3350 4647 4661 4932 4942 10088 10098 13679 13690 16888 16954 20202 20225 </code></pre> <p>Now I need a third column "JoinedCol" as</p> <pre><code>836:845 3341:3350 4647:4661 4932:4942 10088:10098 ... ... </code></pre> <p>I don't want to use paste() as it is producing column with char-type or factor. I want to use the new column "JoinedCol" to use in R for getting the data like </p> <pre><code>836, 837,838,...844,845,3341,3342........ ..... 10098 </code></pre>
0
2016-10-10T01:03:03Z
39,950,157
<p>As far as I know, you can't have this type of data in R. If you join the ':' symbol to any number, the new string will always be a factor, a character or a matrix.</p> <p>To retrieve data from that specific column you would have to specify which part you want, lets say with <code>substring()</code>. Otherwise you have to have both numbers in different columns, just as you original dataframe is.</p> <hr> <p>Still, you can have your data using the new JoinedCol:</p> <pre><code>&gt;DF$JoinedCol=paste(DF$start,DF$end, sep=":") #Create the new column as you say DF start end JoinedCol 1 836 10088 836:10088 2 845 10098 845:10098 3 3341 13679 3341:13679 4 3350 13690 3350:13690 5 4647 16888 4647:16888 6 4661 16954 4661:16954 7 4932 20202 4932:20202 8 4942 20225 4942:20225 </code></pre> <hr> <pre><code>&gt;substring(DF$JoinedCol,1,((regexpr(":", DF$JoinedCol))-1)) #To get first set of numbers (before the ':') [1] "836" "845" "3341" "3350" "4647" "4661" "4932" "4942" </code></pre> <hr> <pre><code>&gt;substring(DF$JoinedCol,(regexpr(":", DF$JoinedCol))+1,nchar(DF$JoinedCol)) #To get second set of numbers (after the ':') [1] "10088" "10098" "13679" "13690" "16888" "16954" "20202" "20225" </code></pre>
0
2016-10-10T01:17:43Z
[ "python" ]
How to join two new numeric columns in a dataframe using a separator?
39,950,057
<p>I have the dataframe df: </p> <pre><code>start end 836 845 3341 3350 4647 4661 4932 4942 10088 10098 13679 13690 16888 16954 20202 20225 </code></pre> <p>Now I need a third column "JoinedCol" as</p> <pre><code>836:845 3341:3350 4647:4661 4932:4942 10088:10098 ... ... </code></pre> <p>I don't want to use paste() as it is producing column with char-type or factor. I want to use the new column "JoinedCol" to use in R for getting the data like </p> <pre><code>836, 837,838,...844,845,3341,3342........ ..... 10098 </code></pre>
0
2016-10-10T01:03:03Z
39,957,285
<p>Based on </p> <blockquote> <p>I want to use the new column "JoinedCol" to use in R for further getting the data like 836, 837,838,...844,845,3341,3342........ ..... 10098</p> </blockquote> <p>you actually want this:</p> <pre><code>DF &lt;- read.table(text = "start end 836 845 3341 3350 4647 4661 4932 4942 10088 10098 13679 13690 16888 16954 20202 20225", header = TRUE) #create the sequences DF$sequences &lt;- Map(`:`, DF$start, DF$end) #access the first sequence DF$sequences[[1]] #[1] 836 837 838 839 840 841 842 843 844 845 </code></pre> <p>You should not create commands as text, which you need then to parse, as you propose in your question.</p>
0
2016-10-10T11:32:01Z
[ "python" ]
how to execute python code with tkinter user input
39,950,082
<p>when user input cluster in this tkinter code (tkintt.py) and click submit button, i want the program execute k-medoids code (example.py) based on how many cluster that user input but it gets some errors. could you help me?</p> <p>tkintt.py</p> <pre><code>import Tkinter from _tkinter import * root = Tkinter.Tk() label1 = Tkinter.Label(text = " enter cluster : ") label1.pack() clvar = Tkinter.IntVar() cluster = Tkinter.Entry(bd = 5) clvar = cluster.get() cluster.pack() def open1(): print ("K-MEDOIDS CLUSTERING") execfile('example.py') button_1 = Tkinter.Button(text = "SUBMIT", command = open1) button_1.pack() root.mainloop() </code></pre> <p>example.py</p> <pre><code>from k_medoids import KMedoids import numpy as np import matplotlib.pyplot as plt def example_distance_func(data1, data2): '''example distance function''' return np.sqrt(np.sum((data1 - data2)**2)) if __name__ == '__main__': X = np.random.normal(0,3,(500,2)) model = KMedoids(n_clusters= cluster, dist_func=example_distance_func) model.fit(X, plotit=True, verbose=True) plt.show() </code></pre> <p>error:</p> <pre><code> Traceback (most recent call last): File "C:\Users\user\Anaconda2\lib\lib-tk\Tkinter.py", line 1537, in __call__ return self.func(*args) File "C:/Users/user/Anaconda2/K_Medoids-master/tkintt.py", line 15, in open1 execfile('example.py') File "example.py", line 13, in &lt;module&gt; model.fit(X, plotit=True, verbose=True) File "C:\Users\user\Anaconda2\K_Medoids-master\k_medoids.py", line 114, in fit X,self.n_clusters, self.dist_func, max_iter=self.max_iter, tol=self.tol,verbose=verbose) File "C:\Users\user\Anaconda2\K_Medoids-master\k_medoids.py", line 54, in _kmedoids_run members, costs, tot_cost, dist_mat = _get_cost(X, init_ids,dist_func) File "C:\Users\user\Anaconda2\K_Medoids-master\k_medoids.py", line 37, in _get_cost mask = np.argmin(dist_mat,axis=1) File "C:\Users\user\Anaconda2\lib\site-packages\numpy\core\fromnumeric.py", line 1034, in argmin return argmin(axis, out) ValueError: attempt to get argmin of an empty sequence </code></pre>
0
2016-10-10T01:07:37Z
39,965,803
<p>It appears as if that k-medoid does not handle allethe corner cases correctly.</p> <p>Most likely, you have an empty cluster.</p>
0
2016-10-10T19:55:51Z
[ "python", "python-2.7", "tkinter", "pycharm", "cluster-analysis" ]
Recursive sequence generator
39,950,111
<p>Does Python have a recursive sequence generating function? For instance,</p> <pre><code>def generateSequence(seed, f, n): sequence = list(seed) for i in range(n): sequence.append(f(sequence, i)) return sequence </code></pre> <p>Which may be used like so:</p> <pre><code>fibSequence = generateSequence([0, 1], lambda x, i: x[-1] + x[-2], 8) </code></pre> <p>To produce:</p> <pre><code>[0, 1, 1, 2, 3, 5, 8, 13, 21, 34] </code></pre>
2
2016-10-10T01:11:33Z
39,950,583
<p>I think the <a href="https://docs.python.org/3/library/itertools.html#itertools.accumulate" rel="nofollow"><code>itertools.accumulate</code></a> may meet your needs, but it's return value may be different from what you expect.</p> <p>For instance:</p> <pre><code>#!/usr/bin/env python3 # -*- coding: utf-8 -*- from itertools import accumulate def callback(seq, i): """ seq: the sequence you will modified i: the number of times this function is called """ seq.append(seq[-1] + seq[-2]) return seq res = accumulate([[0, 1]] + list(range(1, 8 + 1)), callback) for item in res: print(item) </code></pre> <p>The <code>[0, 1]</code> is the init sequence, and the <code>8</code> is the number of times you want to call the <code>callback</code> function. </p> <p>And the result of above code is this:</p> <pre><code>In [48]: run test.py [0, 1] [0, 1, 1] [0, 1, 1, 2] [0, 1, 1, 2, 3] [0, 1, 1, 2, 3, 5] [0, 1, 1, 2, 3, 5, 8] [0, 1, 1, 2, 3, 5, 8, 13] [0, 1, 1, 2, 3, 5, 8, 13, 21] [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] </code></pre> <p>The last one is you wanted.</p>
0
2016-10-10T02:34:46Z
[ "python" ]
How to avoid re-importing modules and re-defining large object every time a script runs
39,950,130
<p>This must have an answer but I cant find it. I am using a quite large python module called quippy. With this module one can define an intermolecular potential to use as a calculator in ASE like so: </p> <pre><code>from quippy import * from ase import atoms pot=Potential("Potential xml_label=gap_h2o_2b_ccsdt_3b_ccsdt",param_filename="gp.xml") some_structure.set_calculator(pot) </code></pre> <p>This is the beginning of a script. The problem is that the <code>import</code> takes about 3 seconds and <code>pot=Potential...</code> takes about 30 seconds with 100% cpu load. (I believe it is due to parsing a large ascii xml-file.) If I would be typing interactively I could keep the module imported and the potential defined, but when running the script it is done again on each run. </p> <p>Can I save the module and the potential object in memory/disk between runs? Maybe keep a python process idling and keeping those things in memory? Or run these lines in the interpreter and somehow call the rest of the script from there? </p> <p>Any approach is fine, but some help is be appreciated!</p>
2
2016-10-10T01:13:39Z
39,950,290
<p>You can either use raw files or modules such as <code>pickle</code> to store data easily.</p> <pre><code>import cPickle as pickle from quippy import Potential try: # try previously calculated value with open('/tmp/pot_store.pkl') as store: pot = pickle.load(store) except OSError: # fall back to calculating it from scratch pot = quippy.Potential("Potential xml_label=gap_h2o_2b_ccsdt_3b_ccsdt",param_filename="gp.xml") with open('/tmp/pot_store.pkl', 'w') as store: pot = pickle.dump(pot, store) </code></pre> <p>There are various optimizations to this, e.g. checking whether your pickle file is older than the file generating it's value.</p>
0
2016-10-10T01:43:37Z
[ "python", "python-2.7", "optimization", "import", "load" ]
How to avoid re-importing modules and re-defining large object every time a script runs
39,950,130
<p>This must have an answer but I cant find it. I am using a quite large python module called quippy. With this module one can define an intermolecular potential to use as a calculator in ASE like so: </p> <pre><code>from quippy import * from ase import atoms pot=Potential("Potential xml_label=gap_h2o_2b_ccsdt_3b_ccsdt",param_filename="gp.xml") some_structure.set_calculator(pot) </code></pre> <p>This is the beginning of a script. The problem is that the <code>import</code> takes about 3 seconds and <code>pot=Potential...</code> takes about 30 seconds with 100% cpu load. (I believe it is due to parsing a large ascii xml-file.) If I would be typing interactively I could keep the module imported and the potential defined, but when running the script it is done again on each run. </p> <p>Can I save the module and the potential object in memory/disk between runs? Maybe keep a python process idling and keeping those things in memory? Or run these lines in the interpreter and somehow call the rest of the script from there? </p> <p>Any approach is fine, but some help is be appreciated!</p>
2
2016-10-10T01:13:39Z
39,950,446
<p>I found one solution, but I'm interested in alternatives. You can divide the script into two parts: </p> <p>start.py:</p> <pre><code>from quippy import Potential from ase import atoms pot=Potential(... etc... </code></pre> <p>body.py:</p> <pre><code>for i in range(max_int): print "doing things" # etc... </code></pre> <p>Then enter python interpreter and run the start-script only once but the body as much as needed:</p> <pre><code>me@laptop:~/dir$ python &gt;&gt;&gt; execfile('start.py') &gt;&gt;&gt; execfile('body.py') &gt;&gt;&gt; #(change code of "body.py" in editor) &gt;&gt;&gt; execfile('body.py') # again without reloading "start.py" </code></pre> <p>So this means a terminal is occupied and the script is affected, but it works. </p>
0
2016-10-10T02:11:48Z
[ "python", "python-2.7", "optimization", "import", "load" ]
How to dynamically replace some field in Flask-Admin into Select2?
39,950,182
<p>I have a flask-admin form, where when user select the topmost dropdown field, certain fields in this form must change into Select2 (dropdown) field. This is what I have so far:</p> <pre><code>for(var idx in formData.custom_field_chooser) { var custom_field = $('#' + idx); custom_field.select2(); //This generate error } </code></pre> <p>I think my code is correct, but that <code>custom_field.select2()</code> code geneate this error <code>Uncaught query function not defined for Select2 undefined</code>.</p> <p>Now, I am sure Select2 has already been included by <code>flask-admin</code> (cmiiw), but how do we use that?</p>
0
2016-10-10T01:21:56Z
39,969,300
<p>Finally looking at the trivial error message <code>Uncaught query function not defined for Select2</code>, <a href="http://stackoverflow.com/questions/14483348/query-function-not-defined-for-select2-undefined-error">this post in SO</a> solved my problem. This is how you properly initialized an empty Select2:</p> <pre><code>custom_field.select2({ data: { id: "", text: "" } }); </code></pre> <p>This will change that <code>custom_field</code> element into <code>select2</code>.</p>
0
2016-10-11T01:45:55Z
[ "python", "twitter-bootstrap-3", "select2", "flask-admin" ]
Python to php server Get Data
39,950,201
<p>Ok I'm a little confused here I need to send data to a php server and receive back a response from it example: a raspberry pi sends a unit id and the server returns json file. </p> <p>I have tried this .py code</p> <pre><code>import requests import json url = 'http://localhost/updateContent.php' payload = {"device":"gabriel","data_type":"data","zone":1,"sample":4,"count":0,"time_stamp":"00:00"} headers = {'content-type': 'application/json'} response = requests.post(url, data=json.dumps(payload), headers=headers) </code></pre> <p>but obviously this post the data but I don't get a response from the php server</p> <p>What kind of protocal should I use for this?</p>
0
2016-10-10T01:26:43Z
39,971,538
<pre><code>response = requests.post(url, data=json.dumps(payload), headers=headers) </code></pre> <p>To output the result of your post you have to print out <code>response.text</code> <code>print(response.text);</code></p>
0
2016-10-11T06:28:19Z
[ "php", "python", "json", "raspberry-pi" ]
Windchill nested loops python code equation
39,950,205
<p>I started python only a few months ago and I have been given a task to use a nested loops to calculate wind chill.</p> <p>I have most of the code completed (I think), however the equation is not working the way it want it to work.</p> <p>Here is my code at the moment:</p> <pre><code>def main(): temp = 0 wind = 0 windChill = 13.12 + (.6215 * temp) - (11.37 * wind ** 770.16) + (.3965 * temp * wind **0.16) for temp in range(-35,15,5): print 'temperature is %d' % temp for wind in range(0,85,5): answer = float(windChill) print 'wind is %d calculated wind chill is: %d' % (wind, answer) main() </code></pre> <p>This comes out with this:</p> <pre><code>temperature is -35 wind is 0 calculated wind chill is: 13 wind is 5 calculated wind chill is: 13 wind is 10 calculated wind chill is: 13 wind is 15 calculated wind chill is: 13 wind is 20 calculated wind chill is: 13 wind is 25 calculated wind chill is: 13 wind is 30 calculated wind chill is: 13 wind is 35 calculated wind chill is: 13 wind is 40 calculated wind chill is: 13 wind is 45 calculated wind chill is: 13 wind is 50 calculated wind chill is: 13 wind is 55 calculated wind chill is: 13 wind is 60 calculated wind chill is: 13 wind is 65 calculated wind chill is: 13 wind is 70 calculated wind chill is: 13 wind is 75 calculated wind chill is: 13 wind is 80 calculated wind chill is: 13 temperature is -30 wind is 0 calculated wind chill is: 13 </code></pre> <p>I understand why 13 is spited out, it's because if the temp and wind are 0, it comes to the answer 13.12. But if I do the range for the definition of temp and wind, it will not accept a list for the definition.</p> <p>How do I make it so that the wind chill isn't 13, but the answer which the equation should spit out. </p> <p>e.g. comes out with this:</p> <pre><code>temperature is -35 wind is 0 calculated wind chill is: -8.63 wind is 5 calculated wind chill is: -41.29 wind is 10 calculated wind chill is: -45.12 etc. etc. </code></pre> <p>Thank you very much!</p> <p>If what I have put is simple, and I should just google it, I tried googling it but it makes a table, instead of statements.</p> <p>Carny.</p>
0
2016-10-10T01:27:21Z
39,950,234
<p>You must define an actual <em>function</em>. What you have is just an assignment:</p> <pre><code>temp = 0 wind = 0 windChill = 13.12 + (.6215 * temp) - (11.37 * wind ** 770.16) + (.3965 * temp * wind **0.16) print(windChill) # 13.12 </code></pre> <p>Basically, <code>temp</code> and <code>wind</code> are used with their current values to resolve the expression. <code>windChill</code> then just gets that fixed value assigned to it.</p> <p>A function would look like this:</p> <pre><code>def windChill(temp, wind): return 13.12 + (.6215 * temp) - (11.37 * wind ** 770.16) + (.3965 * temp * wind **0.16) </code></pre> <p>Then <em>call</em> that function in your loop:</p> <pre><code>for temp in range(-35,15,5): print 'temperature is %d' % temp for wind in range(0,85,5): answer = float(windChill(temp, wind)) # note me! print 'wind is %d calculated wind chill is: %d' % (wind, answer) </code></pre> <p>Alternatively, you can move the definition of <code>windChill</code> into both loops, so it gets reevaluated every time.</p> <pre><code>for temp in range(-35,15,5): print 'temperature is %d' % temp for wind in range(0,85,5): answer = 13.12 + (.6215 * temp) - (11.37 * wind ** 770.16) + (.3965 * temp * wind **0.16) print 'wind is %d calculated wind chill is: %d' % (wind, answer) </code></pre>
1
2016-10-10T01:33:08Z
[ "python" ]
"PermissionError: [Errno 13] Permission denied: '/usr/lib/python3.5/site-packages'" installing Django
39,950,254
<p>I cannot install basic django packages on ubuntu. I just deleted virtualenv and remade it. <code>pip3install</code> = <code>pip3 install -r requirements.txt</code></p> <pre><code>[mything] cchilders@cchilders-desktop:~/projects/mything (master) $ cat requirements.txt Django==1.10.1 django-filter djangorestframework psycopg2 twilio ipdb ipython [mything] cchilders@cchilders-desktop:~/projects/mything (master) $ pip3install Collecting Django==1.10.1 (from -r requirements.txt (line 1)) Using cached Django-1.10.1-py2.py3-none-any.whl Collecting django-filter (from -r requirements.txt (line 2)) Using cached django_filter-0.15.2-py2.py3-none-any.whl Requirement already satisfied (use --upgrade to upgrade): djangorestframework in /home/cchilders/.local/lib/python3.5/site-packages (from -r requirements.txt (line 3)) Requirement already satisfied (use --upgrade to upgrade): psycopg2 in /usr/lib/python3/dist-packages (from -r requirements.txt (line 4)) Collecting twilio (from -r requirements.txt (line 5)) Requirement already satisfied (use --upgrade to upgrade): ipdb in /home/cchilders/.local/lib/python3.5/site-packages (from -r requirements.txt (line 6)) Requirement already satisfied (use --upgrade to upgrade): ipython in /home/cchilders/.local/lib/python3.5/site-packages (from -r requirements.txt (line 7)) Collecting pysocks; python_version == "3.5" (from twilio-&gt;-r requirements.txt (line 5)) Requirement already satisfied (use --upgrade to upgrade): six in /home/cchilders/.local/lib/python3.5/site-packages (from twilio-&gt;-r requirements.txt (line 5)) Collecting httplib2&gt;=0.7 (from twilio-&gt;-r requirements.txt (line 5)) Requirement already satisfied (use --upgrade to upgrade): pytz in /usr/lib/python3/dist-packages (from twilio-&gt;-r requirements.txt (line 5)) Requirement already satisfied (use --upgrade to upgrade): setuptools in /home/cchilders/.local/lib/python3.5/site-packages (from ipdb-&gt;-r requirements.txt (line 6)) Requirement already satisfied (use --upgrade to upgrade): prompt-toolkit&lt;2.0.0,&gt;=1.0.3 in /home/cchilders/.local/lib/python3.5/site-packages (from ipython-&gt;-r requirements.txt (line 7)) Requirement already satisfied (use --upgrade to upgrade): pickleshare in /home/cchilders/.local/lib/python3.5/site-packages (from ipython-&gt;-r requirements.txt (line 7)) Requirement already satisfied (use --upgrade to upgrade): decorator in /home/cchilders/.local/lib/python3.5/site-packages (from ipython-&gt;-r requirements.txt (line 7)) Requirement already satisfied (use --upgrade to upgrade): simplegeneric&gt;0.8 in /home/cchilders/.local/lib/python3.5/site-packages (from ipython-&gt;-r requirements.txt (line 7)) Requirement already satisfied (use --upgrade to upgrade): traitlets&gt;=4.2 in /home/cchilders/.local/lib/python3.5/site-packages (from ipython-&gt;-r requirements.txt (line 7)) Requirement already satisfied (use --upgrade to upgrade): pygments in /home/cchilders/.local/lib/python3.5/site-packages (from ipython-&gt;-r requirements.txt (line 7)) Requirement already satisfied (use --upgrade to upgrade): pexpect; sys_platform != "win32" in /home/cchilders/.local/lib/python3.5/site-packages (from ipython-&gt;-r requirements.txt (line 7)) Requirement already satisfied (use --upgrade to upgrade): wcwidth in /home/cchilders/.local/lib/python3.5/site-packages (from prompt-toolkit&lt;2.0.0,&gt;=1.0.3-&gt;ipython-&gt;-r requirements.txt (line 7)) Requirement already satisfied (use --upgrade to upgrade): ipython-genutils in /home/cchilders/.local/lib/python3.5/site-packages (from traitlets&gt;=4.2-&gt;ipython-&gt;-r requirements.txt (line 7)) Requirement already satisfied (use --upgrade to upgrade): ptyprocess&gt;=0.5 in /home/cchilders/.local/lib/python3.5/site-packages (from pexpect; sys_platform != "win32"-&gt;ipython-&gt;-r requirements.txt (line 7)) Installing collected packages: Django, django-filter, pysocks, httplib2, twilio Exception: Traceback (most recent call last): File "/home/cchilders/.local/lib/python3.5/site-packages/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/home/cchilders/.local/lib/python3.5/site-packages/pip/commands/install.py", line 317, in run prefix=options.prefix_path, File "/home/cchilders/.local/lib/python3.5/site-packages/pip/req/req_set.py", line 742, in install **kwargs File "/home/cchilders/.local/lib/python3.5/site-packages/pip/req/req_install.py", line 831, in install self.move_wheel_files(self.source_dir, root=root, prefix=prefix) File "/home/cchilders/.local/lib/python3.5/site-packages/pip/req/req_install.py", line 1032, in move_wheel_files isolated=self.isolated, File "/home/cchilders/.local/lib/python3.5/site-packages/pip/wheel.py", line 346, in move_wheel_files clobber(source, lib_dir, True) File "/home/cchilders/.local/lib/python3.5/site-packages/pip/wheel.py", line 287, in clobber ensure_dir(dest) # common for the 'include' path File "/home/cchilders/.local/lib/python3.5/site-packages/pip/utils/__init__.py", line 83, in ensure_dir os.makedirs(path) File "/usr/lib/python3.5/os.py", line 241, in makedirs mkdir(name, mode) PermissionError: [Errno 13] Permission denied: '/usr/lib/python3.5/site-packages' </code></pre> <p>the <code>mything</code> at the left is an active virtualenv (I just remade)</p> <p>any help appreciated, thank you</p>
1
2016-10-10T01:37:07Z
39,950,376
<p>Try using <code>sudo pip install django</code> when installing django. This will work if you have root privileges, otherwise you may need to use virtualenv. The django documentation and installation guides can be found <a href="https://docs.djangoproject.com/en/1.10/" rel="nofollow" > Here </a></p>
1
2016-10-10T01:59:22Z
[ "python", "django", "pip", "virtualenv", "django-1.10" ]
"PermissionError: [Errno 13] Permission denied: '/usr/lib/python3.5/site-packages'" installing Django
39,950,254
<p>I cannot install basic django packages on ubuntu. I just deleted virtualenv and remade it. <code>pip3install</code> = <code>pip3 install -r requirements.txt</code></p> <pre><code>[mything] cchilders@cchilders-desktop:~/projects/mything (master) $ cat requirements.txt Django==1.10.1 django-filter djangorestframework psycopg2 twilio ipdb ipython [mything] cchilders@cchilders-desktop:~/projects/mything (master) $ pip3install Collecting Django==1.10.1 (from -r requirements.txt (line 1)) Using cached Django-1.10.1-py2.py3-none-any.whl Collecting django-filter (from -r requirements.txt (line 2)) Using cached django_filter-0.15.2-py2.py3-none-any.whl Requirement already satisfied (use --upgrade to upgrade): djangorestframework in /home/cchilders/.local/lib/python3.5/site-packages (from -r requirements.txt (line 3)) Requirement already satisfied (use --upgrade to upgrade): psycopg2 in /usr/lib/python3/dist-packages (from -r requirements.txt (line 4)) Collecting twilio (from -r requirements.txt (line 5)) Requirement already satisfied (use --upgrade to upgrade): ipdb in /home/cchilders/.local/lib/python3.5/site-packages (from -r requirements.txt (line 6)) Requirement already satisfied (use --upgrade to upgrade): ipython in /home/cchilders/.local/lib/python3.5/site-packages (from -r requirements.txt (line 7)) Collecting pysocks; python_version == "3.5" (from twilio-&gt;-r requirements.txt (line 5)) Requirement already satisfied (use --upgrade to upgrade): six in /home/cchilders/.local/lib/python3.5/site-packages (from twilio-&gt;-r requirements.txt (line 5)) Collecting httplib2&gt;=0.7 (from twilio-&gt;-r requirements.txt (line 5)) Requirement already satisfied (use --upgrade to upgrade): pytz in /usr/lib/python3/dist-packages (from twilio-&gt;-r requirements.txt (line 5)) Requirement already satisfied (use --upgrade to upgrade): setuptools in /home/cchilders/.local/lib/python3.5/site-packages (from ipdb-&gt;-r requirements.txt (line 6)) Requirement already satisfied (use --upgrade to upgrade): prompt-toolkit&lt;2.0.0,&gt;=1.0.3 in /home/cchilders/.local/lib/python3.5/site-packages (from ipython-&gt;-r requirements.txt (line 7)) Requirement already satisfied (use --upgrade to upgrade): pickleshare in /home/cchilders/.local/lib/python3.5/site-packages (from ipython-&gt;-r requirements.txt (line 7)) Requirement already satisfied (use --upgrade to upgrade): decorator in /home/cchilders/.local/lib/python3.5/site-packages (from ipython-&gt;-r requirements.txt (line 7)) Requirement already satisfied (use --upgrade to upgrade): simplegeneric&gt;0.8 in /home/cchilders/.local/lib/python3.5/site-packages (from ipython-&gt;-r requirements.txt (line 7)) Requirement already satisfied (use --upgrade to upgrade): traitlets&gt;=4.2 in /home/cchilders/.local/lib/python3.5/site-packages (from ipython-&gt;-r requirements.txt (line 7)) Requirement already satisfied (use --upgrade to upgrade): pygments in /home/cchilders/.local/lib/python3.5/site-packages (from ipython-&gt;-r requirements.txt (line 7)) Requirement already satisfied (use --upgrade to upgrade): pexpect; sys_platform != "win32" in /home/cchilders/.local/lib/python3.5/site-packages (from ipython-&gt;-r requirements.txt (line 7)) Requirement already satisfied (use --upgrade to upgrade): wcwidth in /home/cchilders/.local/lib/python3.5/site-packages (from prompt-toolkit&lt;2.0.0,&gt;=1.0.3-&gt;ipython-&gt;-r requirements.txt (line 7)) Requirement already satisfied (use --upgrade to upgrade): ipython-genutils in /home/cchilders/.local/lib/python3.5/site-packages (from traitlets&gt;=4.2-&gt;ipython-&gt;-r requirements.txt (line 7)) Requirement already satisfied (use --upgrade to upgrade): ptyprocess&gt;=0.5 in /home/cchilders/.local/lib/python3.5/site-packages (from pexpect; sys_platform != "win32"-&gt;ipython-&gt;-r requirements.txt (line 7)) Installing collected packages: Django, django-filter, pysocks, httplib2, twilio Exception: Traceback (most recent call last): File "/home/cchilders/.local/lib/python3.5/site-packages/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/home/cchilders/.local/lib/python3.5/site-packages/pip/commands/install.py", line 317, in run prefix=options.prefix_path, File "/home/cchilders/.local/lib/python3.5/site-packages/pip/req/req_set.py", line 742, in install **kwargs File "/home/cchilders/.local/lib/python3.5/site-packages/pip/req/req_install.py", line 831, in install self.move_wheel_files(self.source_dir, root=root, prefix=prefix) File "/home/cchilders/.local/lib/python3.5/site-packages/pip/req/req_install.py", line 1032, in move_wheel_files isolated=self.isolated, File "/home/cchilders/.local/lib/python3.5/site-packages/pip/wheel.py", line 346, in move_wheel_files clobber(source, lib_dir, True) File "/home/cchilders/.local/lib/python3.5/site-packages/pip/wheel.py", line 287, in clobber ensure_dir(dest) # common for the 'include' path File "/home/cchilders/.local/lib/python3.5/site-packages/pip/utils/__init__.py", line 83, in ensure_dir os.makedirs(path) File "/usr/lib/python3.5/os.py", line 241, in makedirs mkdir(name, mode) PermissionError: [Errno 13] Permission denied: '/usr/lib/python3.5/site-packages' </code></pre> <p>the <code>mything</code> at the left is an active virtualenv (I just remade)</p> <p>any help appreciated, thank you</p>
1
2016-10-10T01:37:07Z
39,950,544
<p>You could accidentally recreate virtualenv with Python2 by forgetting to put path to Python3 interpreter so when you execute pip3 it refers to system Python3. </p> <p>Make sure that you use correct Python in your virtualenv and also make sure that you create virtualenv with pip (yes it's the default option but we don't know how you create your virtual environment).</p>
1
2016-10-10T02:29:38Z
[ "python", "django", "pip", "virtualenv", "django-1.10" ]
Tkinter filedialog reading in a file path
39,950,322
<p>I have searched around and have not really found the answer to my problem yet. </p> <p>I am trying to browse through files to take in an image file and a use its path as a variable to pass into my qr function, but when using file dialog it gives me this </p> <p>&lt;_io.TextIOWrapper name='C:/Users/Elias/Desktop/New folder/IMG_2635.JPG' mode='r' encoding='cp1252'></p> <p>rather than this C:/Users/Elias/Desktop/New folder/IMG_2635.JPG</p> <p>Is there any way to do this better?</p> <pre><code>import tkinter as tk from tkinter import ttk from MyQR import myqr from tkinter import filedialog import os LARGE_FONT = ("Verdana", 12) class QRgenerator(tk.Tk): def __init__(self, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) container = tk.Frame(self) tk.Tk.wm_title(self,"CST-205-Project2") container.pack(side = "top", fill = "both", expand = True) container.grid_rowconfigure(0,weight = 1) container.grid_columnconfigure(0,weight = 1) self.frames = {} for f in (StartPage,PageOne,QR1,QR2): frame = f(container, self) self.frames[f] = frame frame.grid(row = 0, column = 0, sticky = "nsew") self.show_frame(StartPage) def show_frame(self,cont): frame = self.frames[cont] frame.tkraise() def qr_2(size,url_in,path): print('\n\n\n\n1 being smaller \n40 being bigger') num = size # url = 'https://www.instagram.com/jayrfitz/?hl=en' url = url_in pic = path version, level, qr_name = myqr.run( words=url, version=num, level='H', picture=pic, colorized=True, contrast=1.0, brightness=1.0, save_name=None, #outputdirectory I deleted but we can set it here ) class StartPage(tk.Frame): def __init__(self,parent,controller): tk.Frame.__init__(self,parent) label = ttk.Label(self,text = "start page", font = LARGE_FONT) label.pack(pady = 10, padx = 10) button1 = ttk.Button(self,text = "next page", command = lambda: controller.show_frame(PageOne)) button1.pack() class PageOne(tk.Frame): def __init__(self,parent,controller): tk.Frame.__init__(self,parent) label = ttk.Label(self,text = "Page One", font = LARGE_FONT) label.pack(pady = 10, padx = 10) button1 = ttk.Button(self,text = "Option1", command = lambda: controller.show_frame(QR1)) button1.place(x = 0, y = 0) button2 = ttk.Button(self,text = "Option2", command = lambda: controller.show_frame(QR2)) button2.place(x = 425, y = 0) class QR1(tk.Frame): def __init__(self,parent,controller): URLin = ' ' Size = 1 filePath = ' ' def submit(): content = url_entry.get() URLin = content print(URLin) def submit2(): content = size_entry.get() Size = content print(Size) def Browse(): filename = filedialog.askopenfile() filePath = filename print(filePath) tk.Frame.__init__(self,parent) label = ttk.Label(self,text = "start page", font = LARGE_FONT) label.pack() label = ttk.Label(self,text = "start page", font = LARGE_FONT) button1 = ttk.Button(self,text = "Page 1", command = lambda: controller.show_frame(PageOne)) button1.place(x = 0, y = 450) url_label = ttk.Label(self,text = "Enter URL in box", font = LARGE_FONT) url_label.place(x = 100, y = 25) submit1 = ttk.Button(self,text = "submit", command = submit) submit1.place(x = 0, y = 25) url_entry = ttk.Entry(self,width = 50) url_entry.place(x = 0, y = 100) submit2 = ttk.Button(self,text = "submit", command = submit2) submit2.place(x = 0, y = 150) size_label = ttk.Label(self,text = "Enter the size of the QR code", font = LARGE_FONT) size_label.place(x = 100, y = 150) size_entry = ttk.Entry(self,width = 50) size_entry.place(x = 0, y = 200) file_label = ttk.Label(self,text = "Press Browse to locate file or enter and click submit", font = LARGE_FONT) file_label.place(x = 0, y = 350) FileBrowse = ttk.Button(self,text = "Browse",command = Browse,) FileBrowse.place(x = 0, y= 250) file_ent = ttk.Entry(self,width = 50, text = filePath) file_ent.place(x = 0, y = 300) run = ttk.Button(self,text = "Run", command = lambda: qr_2(Size,URLin,filePath)) run.place(x = 0, y = 400) class QR2(tk.Frame): def __init__(self,parent,controller): tk.Frame.__init__(self,parent) label = ttk.Label(self,text = "start page", font = LARGE_FONT) label.pack(pady = 10, padx = 10) button1 = ttk.Button(self,text = "next page", command = lambda: controller.show_frame(PageOne)) button1.pack() app = QRgenerator() app.geometry("500x500") app.mainloop() </code></pre>
0
2016-10-10T01:49:20Z
39,950,353
<p>You are using <code>filedialog.askopenfile()</code>. This gives you a file <em>handle</em>. If you just want the file <em>name</em>, use <code>filedialog.askopenfilename()</code>.</p>
2
2016-10-10T01:54:25Z
[ "python", "tkinter", "filedialog" ]
list comprehension in python with if and else
39,950,416
<p>after i test,</p> <pre><code>len_stat = [len(x) if len(x) &gt; len_stat[i] else len_stat[i] for i, x in enumerate(a_list)] </code></pre> <p>is same with </p> <pre><code>for i, x in enumerate(a_list): if len(x) &gt; len_stat[i]: len_stat[i] = len(x) </code></pre> <p>of course, but,</p> <pre><code>len_stat = [len(x) if len(x) &gt; len_stat[a_list.index(x)] else len_stat[a_list.index(x)] for x in a_list] </code></pre> <p>is different with</p> <pre><code>for x in a_list: if len(x) &gt; len_stat[a_list.index(x)]: len_stat[a_list.index(x)] = len(x) </code></pre> <p>later, i know <code>&lt;list&gt;.index</code> is a bad method used here.</p> <p>but why they are different in last two examples?</p> <hr> <p>my fault! here is my test code,</p> <pre><code>a_list = ['Bacteroides fragilis YCH46', 'YCH46', '20571', '-', 'PRJNA13067', 'FCB group', 'Bacteroidetes/Chlorobi group', 'GCA_000009925.1 ', '5.31099', '43.2378', 'chromosome:NC_006347.1/AP006841.1; plasmid pBFY46:NC_006297.1/AP006842.1', '-', '2', '4717', '4625', '2004/09/17', '2016/08/03', 'Complete Genome', 'ftp://ftp.ncbi.nlm.nih.gov/genomes/all/GCF_000009925.1_ASM992v1', 'ftp://ftp.ncbi.nlm.nih.gov/genomes/all/GCA_000009925.1_ASM992v1'] len_stat_1 = [0 for x in a_list] len_stat_2 = [0 for x in a_list] len_stat_3 = [0 for x in a_list] len_stat_4 = [0 for x in a_list] len_stat_1 = [len(x) if len(x) &gt; len_stat_1[i] else len_stat_1[i] for i, x in enumerate(a_list)] for i, x in enumerate(a_list): if len(x) &gt; len_stat_2[i]: len_stat_2[i] = len(x) len_stat_3 = [len(x) if len(x) &gt; len_stat_3[a_list.index(x)] else len_stat_3[a_list.index(x)] for x in a_list] for x in a_list: if len(x) &gt; len_stat_4[a_list.index(x)]: len_stat_4[a_list.index(x)] = len(x) print len_stat_1 print len_stat_2 print len_stat_3 print len_stat_4 </code></pre> <p>output:</p> <pre><code>[26, 5, 5, 1, 10, 9, 28, 16, 7, 7, 72, 1, 1, 4, 4, 10, 10, 15, 63, 63] [26, 5, 5, 1, 10, 9, 28, 16, 7, 7, 72, 1, 1, 4, 4, 10, 10, 15, 63, 63] [26, 5, 5, 1, 10, 9, 28, 16, 7, 7, 72, 1, 1, 4, 4, 10, 10, 15, 63, 63] [26, 5, 5, 1, 10, 9, 28, 16, 7, 7, 72, 0, 1, 4, 4, 10, 10, 15, 63, 63] </code></pre> <p>as you can see, the last two is different!</p> <p>it really confused me.</p>
0
2016-10-10T02:06:57Z
39,950,484
<p>This list comprehension:</p> <pre><code>len_stat = [len(x) if len(x) &gt; len_stat[a_list.index(x)] else len_stat[a_list.index(x)] for x in a_list] </code></pre> <p>Is equivalent to:</p> <pre><code>temp = [] for x in a_list: temp.append(len(x) if len(x) &gt; len_stat[a_list.index(x)] else len_stat[a_list.index(x)]) len_stat = temp </code></pre> <p>Which is equivalent to:</p> <pre><code>temp = [] for x in a_list: if len(x) &gt; len_stat[a_list.index(x)]: val = len(x) else: val = len_stat[a_list.index(x)] temp.append(val) len_stat = temp </code></pre> <p>Equivalent, of course, except for the <code>temp</code> list. The comprehension approach will replace <code>len_stat</code> with a new list, that will always be the same length as <code>len_stat</code> that will have either <code>len(x)</code> for every x in <code>len_stat</code> or will have <code>len_stat[a_list.index(x)]</code>. The for-loop you wrote will mutate <code>len_stat</code> based on the conditional, and it's hard to say exactly what will happen without knowing the content of your lists, but it could potentially change values of <code>len_stat</code> all over the place.</p> <p><h2> To be clear</h2> I do <strong>not</strong> recommend this approach, but I am trying to illustrate how the comprehension is different than the for-loop.</p>
0
2016-10-10T02:19:55Z
[ "python" ]
How do I find the max integer of a string of integer without using a list?
39,950,481
<p>I must use a for loop, no list allowed. May assume string is non-empty. What I have:</p> <pre><code>def max_numbers(s): n_string = '' for char in s: if char.isdigit(): n_string += char return max(n_string) max_numbers('22 53 123 54 243') 5 expected 243 </code></pre> <p>Please don't use any advance methods, I am still a beginner. I wanted 243 to show up but ended up with 5 instead.</p>
-1
2016-10-10T02:19:36Z
39,950,517
<p>If @IvanCai's answer is too advanced try:</p> <pre><code>def max_numbers(s): top=0 curr=0 for char in s: if char.isdigit(): curr*=10 curr+=int(char) if curr&gt;top: top=curr elif char==' ' or char=='\n': curr=0 return top print(max_numbers('22 53 123 54 243')) </code></pre>
-2
2016-10-10T02:25:20Z
[ "python" ]
How do I find the max integer of a string of integer without using a list?
39,950,481
<p>I must use a for loop, no list allowed. May assume string is non-empty. What I have:</p> <pre><code>def max_numbers(s): n_string = '' for char in s: if char.isdigit(): n_string += char return max(n_string) max_numbers('22 53 123 54 243') 5 expected 243 </code></pre> <p>Please don't use any advance methods, I am still a beginner. I wanted 243 to show up but ended up with 5 instead.</p>
-1
2016-10-10T02:19:36Z
39,950,580
<p>Not going to write any code for you because doing it the way you have specified is just boring. Also since you have not indicated what version of python you are using, I will just assume version 2.</p> <p>Here are a few things you will need:</p> <ul> <li><a href="https://docs.python.org/2/library/stdtypes.html#str.isspace" rel="nofollow"><strong>str.isspace()</strong></a> Use this to determine when you have reached a space</li> <li><a href="https://docs.python.org/2/library/stdtypes.html#str.isdigit" rel="nofollow"><strong>str.isdigit()</strong></a> Use this to determine when you have read a number</li> <li><a href="https://docs.python.org/2/library/functions.html#int" rel="nofollow"><strong>int()</strong></a> Use this to convert a string number to integer</li> </ul> <h2>The algorithm goes like this:</h2> <ol> <li><p>First initialize a variable called <code>num</code> to the empty string</p></li> <li><p>Read digits until you either reach the end of the string or reach a non digit. Each digit read should be appended to <code>num</code></p></li> <li>If you reach a space or end of the string and <code>neg</code> is not empty, use <code>int</code> to convert <code>num</code> to an integer otherwise skip to step 5</li> <li>Compare this value to your current max and replace max with the value if it is larger</li> <li>Repeat from step 1 if you have not reached the end of the string</li> <li>Finally print your current max</li> </ol> <h2>Special case to handle negative numbers</h2> <ol> <li>Initialize a variable called <code>num</code> to the empty string and a variable called <code>neg</code> to <code>1</code></li> <li>If the first thing read is not a digit and is not space but is the <code>-</code> character, set <code>neg</code> to <code>-1</code> otherwise read digits until you either reach the end of the string or reach a non digit. Each digit read should be appended to <code>num</code></li> <li>If you reach a space or end of the string and <code>num</code> is not empty, use <code>int</code> to convert <code>num</code> to an integer; otherwise skip to step 6</li> <li>Multiply this integer by <code>neg</code></li> <li>Compare this value to your current max and replace max with the value if it is larger</li> <li>Repeat from step 1 if you have not reached the end of the string</li> <li>Finally print your current max</li> </ol> <hr> <p>The non boring version:</p> <pre><code>print (max(map(int, my_str.split()))) </code></pre>
1
2016-10-10T02:34:24Z
[ "python" ]
How do I find the max integer of a string of integer without using a list?
39,950,481
<p>I must use a for loop, no list allowed. May assume string is non-empty. What I have:</p> <pre><code>def max_numbers(s): n_string = '' for char in s: if char.isdigit(): n_string += char return max(n_string) max_numbers('22 53 123 54 243') 5 expected 243 </code></pre> <p>Please don't use any advance methods, I am still a beginner. I wanted 243 to show up but ended up with 5 instead.</p>
-1
2016-10-10T02:19:36Z
39,950,607
<pre><code>def max_numbers(s): # biggest number we've seen so far. init to a very small number so # it will get replaced immediately by real input data biggest = -999 # accumulate digit characters from input n_string = '' # loop through each input character for char in s: # is it a digit 0-9? if char.isdigit(): # add it onto the end of n_string n_string += char # not a digit else: # if n_string has some digits in it if n_string: # calculate integer value of n_string, and if it's bigger # than the previous biggest, save it as the new biggest biggest = max(biggest, int(n_string)) # reset n_string back to empty n_string = '' return biggest </code></pre>
1
2016-10-10T02:38:45Z
[ "python" ]
How do I find the max integer of a string of integer without using a list?
39,950,481
<p>I must use a for loop, no list allowed. May assume string is non-empty. What I have:</p> <pre><code>def max_numbers(s): n_string = '' for char in s: if char.isdigit(): n_string += char return max(n_string) max_numbers('22 53 123 54 243') 5 expected 243 </code></pre> <p>Please don't use any advance methods, I am still a beginner. I wanted 243 to show up but ended up with 5 instead.</p>
-1
2016-10-10T02:19:36Z
39,950,621
<p>The idea is to separate out the integers from the string (as you are already doing, but a bit wrongly), and keep track of the max so far. When a character is not digit, you convert the <code>n_string</code> to <code>int</code> and compare with <code>max_</code> which keeps track of maximum int found so far, and then set <code>n_string</code> empty for next number.</p> <p>The final checking is for the last number, since at the end of the string there may not always be a non-digit, so the last iteration will not be in the <code>else</code> part.</p> <pre><code>def max_numbers(s): n_string = '' max_ = 0 for char in s: if char.isdigit(): n_string += char else: if n_string and int(n_string) &gt; max_: max_ = int(n_string) n_string = '' if n_string and int(n_string) &gt; max_: max_ = int(n_string) return max_ print(max_numbers('22 53 123 54 243')) </code></pre> <p>Output:</p> <pre><code>243 </code></pre> <hr> <p><strong>Edit:</strong></p> <p>If <code>n_string</code> is empty, <code>int(n_string)</code> fails with an error</p> <blockquote> <p>ValueError: invalid literal for int() with base 10: ' '</p> </blockquote> <p>So in order to avoid that, a check to see if <code>n_string</code> is empty or not is required <strong>before</strong> doing <code>int(n_string)</code>. In python, <a href="https://docs.python.org/3.5/library/stdtypes.html#truth-value-testing" rel="nofollow">empty string evaluates to <code>False</code>, and non-empty string to <code>True</code></a>. So, simply writing</p> <pre><code>if n_string and int(n_string) &gt; max_: </code></pre> <p>checks if <code>n_string</code> is non-empty <em>and</em> <code>n_string</code> as integer is greater than <code>max_</code>. When <code>n_string</code> is empty, the second part of the <code>if</code> is not evaluated due to <a href="http://stackoverflow.com/questions/2580136/does-python-support-short-circuiting">short-circuiting</a> behaviour of <code>if</code>, thus the error is avoided.</p> <hr> <p>Some related links:</p> <ul> <li>Short-circuit in boolean expressions in python: <a href="http://stackoverflow.com/questions/2580136/does-python-support-short-circuiting">Link</a></li> <li>Truth value testing in python: <a href="https://docs.python.org/3.5/library/stdtypes.html#truth-value-testing" rel="nofollow">official docs</a> and <a href="http://stackoverflow.com/questions/53513/best-way-to-check-if-a-list-is-empty/34558732#34558732">an answer by me</a></li> </ul>
4
2016-10-10T02:42:16Z
[ "python" ]
Inserting generated Matplotlib plots into Flask with python3
39,950,522
<p>I am using Python 3 and Flask with Matplotlib and numpy.</p> <p>I wish to load pages that generate many plots which are embedded into the page.</p> <p>I have tried following suggestions made in other places, such as this <a href="http://stackoverflow.com/questions/20107414/passing-a-matplotlib-figure-to-html-flask">stackoverflow question</a> and this <a href="https://gist.github.com/wilsaj/862153" rel="nofollow">github post</a>.</p> <p>However, when I try to implement anything of the kind I get all kinds of IO related errors. Usually of the form:</p> <pre><code>TypeError: string argument expected, got 'bytes' </code></pre> <p>and is generated inside of:</p> <pre><code>site-packages/matplotlib/backends/backend_agg.py </code></pre> <p>specifically the <code>print_png</code> function</p> <p>I understand python3 no longer has a <code>StringIO import</code>, which is what is producing the error, and instead we are to <code>import io</code> and call it with <code>io.StringIO()</code> - at least that is what I understand we are to do, however, I can't seem to get any of the examples I have found to work. </p> <p>The structure of my example is almost identical to that of the stackoverflow question listed above. The page generates as does the image route. It is only the image generation itself that fails. </p> <p>I am happy to try a different strategy if someone has a better idea. To be clear, I need to generate plots - some times many (100+ on any single page and hundreds of pages) - from data in a database and display them on a webpage. I was hoping to avoid generating files that I then have to clean up given the large number of files I will probably generate and the fact they may change as data in the DB changes.</p>
-1
2016-10-10T02:25:58Z
39,951,208
<p>The code taken from this <a href="http://stackoverflow.com/questions/20107414/passing-a-matplotlib-figure-to-html-flask?rq=1">stackoverflow question</a> which is used in the above question contains the following:</p> <pre><code> import StringIO ... fig = draw_polygons(cropzonekey) img = StringIO() fig.savefig(img) </code></pre> <p>As poitned out by @furas, Python3 treats bytes and strings differently to Python2. In many Python 2 examples StringIO is used for cases like the above but in Python3 it will not work. Therefore, we need modify the above like this:</p> <pre><code> import io ... fig = draw_polygons(cropzonekey) img = BytesIO() fig.savefig(img) </code></pre> <p>Which appears to work.</p>
1
2016-10-10T04:10:56Z
[ "python", "python-3.x", "numpy", "matplotlib", "flask" ]
Python for maximum pairwise product
39,950,568
<pre><code>n = int(input("Enter the number of elements in the array (2-200,000):")) a = [int(x) for x in input("Enter all numbers of the sequence with only non-negative intergers not exceeding 100,000:").split()] c = list()3 for i in range(0,n): for j in range (1,n): if a[i] != a[j]: m = a[i]*a[j] c.append(m) else: continue print(max(c)) </code></pre> <p>This code works. However, I want to define a function to automatically calculating the max product from the 5th line in the code shown below.</p> <pre><code>def MaxPairwiseProduct(n,a,c): for i in range(0,n): for j in range (1,n): if a[i] != a[j]: m = a[i]*a[j] c.append(m) else: continue Product = max(c) return Product n = int(input("Enter the number of elements in the array (2-200,000):")) a = [int(x) for x in input("Enter all numbers of the sequence with only non-negative intergers not exceeding 100,000:").split()] c = list() MaxPairwiseProduct(n,a,c) </code></pre> <p>I re-write the function but it does not work. It reveals "IndentationError: expected an indented block"</p>
0
2016-10-10T02:33:01Z
39,950,700
<pre><code>def MaxPairwiseProduct(n,a,c): for i in range(0,n): for j in range (1,n): if a[i] != a[j]: m = a[i]*a[j] c.append(m) else: continue Product = max(c) return Product n = int(input("Enter the number of elements in the array (2-200,000):")) a = [int(x) for x in input("Enter all numbers of the sequence with only non-negative intergers not exceeding 100,000:").split()] c = list() print(MaxPairwiseProduct(n,a,c)) </code></pre>
1
2016-10-10T02:55:01Z
[ "python", "product" ]
Python for maximum pairwise product
39,950,568
<pre><code>n = int(input("Enter the number of elements in the array (2-200,000):")) a = [int(x) for x in input("Enter all numbers of the sequence with only non-negative intergers not exceeding 100,000:").split()] c = list()3 for i in range(0,n): for j in range (1,n): if a[i] != a[j]: m = a[i]*a[j] c.append(m) else: continue print(max(c)) </code></pre> <p>This code works. However, I want to define a function to automatically calculating the max product from the 5th line in the code shown below.</p> <pre><code>def MaxPairwiseProduct(n,a,c): for i in range(0,n): for j in range (1,n): if a[i] != a[j]: m = a[i]*a[j] c.append(m) else: continue Product = max(c) return Product n = int(input("Enter the number of elements in the array (2-200,000):")) a = [int(x) for x in input("Enter all numbers of the sequence with only non-negative intergers not exceeding 100,000:").split()] c = list() MaxPairwiseProduct(n,a,c) </code></pre> <p>I re-write the function but it does not work. It reveals "IndentationError: expected an indented block"</p>
0
2016-10-10T02:33:01Z
39,965,104
<pre><code># Uses python3 def MaxPairwiseProduct(n,a,c): for i in range(0,n): for j in range (1,n): if a[i] != a[j]: m = a[i]*a[j] c.append(m) else: continue Product1 = max(c) return Product1 def MaxPairwiseProductFast(n,a): max_index1 = -1 for i in range(0,n): if a[i] &gt; a[max_index1]: max_index1 = i else: continue max_index2 = -1 for j in range(0,n): if a[j] &gt; a[max_index2] and a[j] != a[max_index1]: max_index2 = j else: continue Product2 = a[max_index1]*a[max_index2] return Product2 n = int(input("Enter the number of elements in the array (2-200,000):")) a = [int(x) for x in input("Enter all numbers of the sequence with only non-negative intergers not exceeding 100,000:").split()] c = list() print('The max value by regular algorithm:', MaxPairwiseProduct(n,a,c)) print('The max value by faster algorithm:', MaxPairwiseProductFast(n,a)) </code></pre> <p>This code contains the second algorithm to calculate the max value.</p>
1
2016-10-10T19:06:00Z
[ "python", "product" ]
Using different dbs on production and test environment
39,950,769
<p>I want to use a test db on my test environment, and the production db on production environment in my Python application.</p> <p>How should I handle routing to two dbs? Should I have an untracked <code>config.yml</code> file that has the test db's connection string on my test server, and the production db's connection string on production server?</p> <p>I'm using <code>github</code> for version control and <code>travis ci</code> for deployment.</p>
0
2016-10-10T03:06:16Z
39,951,058
<p>Let's take Linux environment for example. Often, the user level configuration of an application is placed under your home folder as a dot file. So what you can do is like this:</p> <ol> <li>In your git repository, track a sample configure file, e.g., <code>config.sample.yaml</code>, and put the configuration structure here.</li> <li>When deploying, either in test environment or production environment, you can copy and rename this file as a dot-file, e.g., <code>$HOME/.{app}.config.yaml</code>. Then in your application, you can read this file.</li> </ol> <p>If you are developing an python package, you can make the file copy operation done in the setup.py. There are some advantages:</p> <ol> <li>You can always track the structure changes of your configuration file.</li> <li>Separate configuration between test and production enviroment.</li> <li>More secure, you do not need to code your import db connection information in the public file.</li> </ol> <p>Hope this would be helpful. </p>
0
2016-10-10T03:50:35Z
[ "python", "github", "configuration", "travis-ci", "configuration-files" ]
How to assign the elements of a list as file names in python?
39,950,794
<p>I am trying to assign the elements of a list as names for some files that live in a directory, so far I created a function that recover the name of a each file from a directory and returns them in a list:</p> <pre><code>def retrive(directory_path): path_names = [] for filename in sorted(glob.glob(os.path.join(directory_path, '*.pdf'))): retrieved_files = filename.split('/')[-1] path_names.append(retrieved_files) print (path_names) </code></pre> <p>The above function returns in a list the names of each file, then I am writing the files into another directory as follows:</p> <pre><code> path = os.path.join(new_dir_path, "list%d.txt" % i) #This is the path of each new file: #print(path) with codecs.open(path, "w", encoding='utf8') as filename: for item in [a_list]: filename.write(item+"\n") </code></pre> <p>Finally, my question is: how can I assign as a name of each file, each element of <code>path_names</code>?, something like this line:</p> <pre><code>path = os.path.join(new_dir_path, "list%d.txt" % i) </code></pre> <p>I also tried to use the <code>format()</code> function. However I still cant assign the the correct name to each file.</p> <p>Here's the full script:</p> <pre><code>def transform_directoy(input_directory, output_directory): import codecs, glob, os from tika import parser all_texts = [] for filename in sorted(glob.glob(os.path.join(input_directory, '*.pdf'))): parsed = parser.from_file(filename) texts = parsed['content'] all_texts.append(texts) for i , a_list in enumerate(all_texts): new_dir_path = output_directory #print(new_dir_path) path = os.path.join(new_dir_path, "list%d.txt" % i) with codecs.open(path, "w", encoding='utf8') as filename: for item in [a_list]: filename.write(item+"\n") </code></pre> <p>The desired output will consist of the actual names of each processed file.</p>
1
2016-10-10T03:10:30Z
39,951,319
<p>You’re almost there:</p> <pre><code>for path_name in path_names: path = os.path.join(new_dir_path, "list%s.txt" % path_name) #This is the path of each new file: #print(path) with codecs.open(path, "w", encoding='utf8') as f: for item in [a_list]: f.write(item+"\n") </code></pre> <hr> <p>Update based on updated code sample. You are using different loops here, and that is not ideal unless you are doing processing in between the two loops. Since I am going to keep that structure, we are going to have to make sure to associate each block of content with the original filename. The best structure for that is a dict, and in case order is important, we use an <code>OrderedDict</code>. Now, when we’re looping over the filename, content pairs in the <code>OrderedDict</code> we’ll want to change the extension of the file to match the new file type. Luckily, python has some nice utilities for file/path manipulation in the <code>os.path</code> module. <code>os.path.basename</code> can be used to strip off the directory from a file and <code>os.path.splitext</code> will strip off an extension from a filename. We use both of those to get just the filename without the extension and then append <code>.txt</code> to designate the new file type. Putting it all together, we get :</p> <pre><code>def transform_directoy(input_directory, output_directory): import codecs, glob, os from collections import OrderedDict from tika import parser all_texts = OrderedDict() for filename in sorted(glob.glob(os.path.join(input_directory, '*.pdf'))): parsed = parser.from_file(filename) filename = os.path.basename(filename) texts = parsed['content'] all_texts[filename] = texts for i, (original_filename, a_list) in enumerate(all_texts.items()): new_filename, _ = os.path.splitext(original_filename) new_filename += '.txt' new_dir_path = output_directory #print(new_dir_path) path = os.path.join(new_dir_path, new_filename) # Print out the name of the file we are processing print('Transforming %s =&gt; %s' % (original_filename, path,)) with codecs.open(path, "w", encoding='utf8') as filename: for item in [a_list]: filename.write(item+"\n") </code></pre> <hr> <p>Second update: OP asked how I would write this code if this was all that there was, so here goes:</p> <pre><code># move imports to top of file: PEP 8 import codecs, glob, os from tika import parser def transform_directoy(input_directory, output_directory): for filename in sorted(glob.glob(os.path.join(input_directory, '*.pdf'))): parsed = parser.from_file(filename) parsed_content = parsed['content'] original_filename = os.path.basename(filename) new_filename, _ = os.path.splitext(original_filename) new_filename += '.txt' path = os.path.join(output_directory, new_filename) # Print out the name of the file we are processing print('Transforming %s =&gt; %s' % (original_filename, path,)) # no need for a second loop since we can piggy back off the first loop with codecs.open(path, "w", encoding='utf8') as filename: # No need for a for loop here since our list only has one item filename.write(parsed_content) filename.write("\n") </code></pre>
1
2016-10-10T04:28:47Z
[ "python", "python-2.7", "python-3.x", "io", "python-3.5" ]
python XML get text inside <p>...</p> tag
39,950,810
<p>I guys, I have an xml structure which looks somewhat like this.</p> <pre><code>&lt;abstract&gt; &lt;p id = "p-0001" num = "0000"&gt; blah blah blah &lt;/p&gt; &lt;/abstract&gt; </code></pre> <p>I would like to extract the <code>&lt;p&gt;</code> tag inside the <code>&lt;abstract&gt;</code> tag only.</p> <p>I tried:</p> <pre><code>import xml.etree.ElementTree as ET xroot = ET.parse('100/A/US07640598-20100105.XML').getroot() for row in xroot.iter('p'): print row.text </code></pre> <p>This get all the <code>&lt;p&gt;</code> tag in my xml which is not a good idea.</p> <p>Is there anyway i can extract the text inside </p> <p>My desire output would be extracting "blah blah blah"</p>
1
2016-10-10T03:14:12Z
39,950,858
<p>You can use an <em>XPath expression</em> to search for <code>p</code> elements specifically inside the <code>abstract</code>:</p> <pre><code>for p in xroot.xpath(".//abstract//p"): print(p.text.strip()) </code></pre> <p>Or, if using <code>iter()</code> you may have a nested loop:</p> <pre><code>for abstract in xroot.iter('abstract'): for p in abstract.iter('p'): print(p.text.strip()) </code></pre>
2
2016-10-10T03:21:14Z
[ "python", "xml" ]
Extract results from a dictionary
39,950,856
<p>I have a dictionary as follows:</p> <pre><code> D = { "America": { "Washington": { "Seattle": ('park', 'museum'), "Kent": ("market",) }, 'Colorado': { "Boulder": ("hiking",) } } } </code></pre> <p>how can I make the following results using that dictionary.</p> <pre><code>America Wahington Seattle park America Wahington Seattle museum America Wahington Kent market America Colorado Boulder hiking </code></pre> <p>I tried as follows:</p> <p>for x in D.iteritems(): print x</p> <p>Could not figure out how to extract each elements after that. Alos wan to to how is the good way of getting the above result.</p>
1
2016-10-10T03:20:56Z
39,950,903
<p>Here is a solution almost entirely based on the <a href="http://stackoverflow.com/a/6027615/771848">"recursive"-approach answer</a> for the "flattening the dictionary" problem:</p> <pre><code>import collections def flatten(d, parent_key='', sep=' '): items = [] for k, v in d.items(): new_key = parent_key + sep + k if parent_key else k if isinstance(v, collections.MutableMapping): items.extend(flatten(v, new_key, sep=sep).items()) else: items.append((new_key, v)) return dict(items) </code></pre> <p>Usage:</p> <pre><code>$ ipython -i test.py In [1]: D = {"America": {"Washington": {"Seattle": ('park', 'museum'), "Kent": ("market",)}, ...: 'Colorado': {"Boulder": ("hiking",)}}} In [2]: for key, values in flatten(D, sep=" ").items(): ...: for value in values: ...: print(key + " " + value) ...: America Washington Seattle park America Washington Seattle museum America Colorado Boulder hiking America Washington Kent market </code></pre> <p>One of the biggest advantages of this approach is that it is <em>scalable</em> - it would work for different depths of the dictionary <code>D</code>.</p>
0
2016-10-10T03:28:15Z
[ "python", "python-2.7", "dictionary" ]
Extract results from a dictionary
39,950,856
<p>I have a dictionary as follows:</p> <pre><code> D = { "America": { "Washington": { "Seattle": ('park', 'museum'), "Kent": ("market",) }, 'Colorado': { "Boulder": ("hiking",) } } } </code></pre> <p>how can I make the following results using that dictionary.</p> <pre><code>America Wahington Seattle park America Wahington Seattle museum America Wahington Kent market America Colorado Boulder hiking </code></pre> <p>I tried as follows:</p> <p>for x in D.iteritems(): print x</p> <p>Could not figure out how to extract each elements after that. Alos wan to to how is the good way of getting the above result.</p>
1
2016-10-10T03:20:56Z
39,950,906
<p>Recursion is your friend...</p> <pre><code>D = { "America": { "Washington": { "Seattle": ('park', 'museum'), "Kent": ("market",) }, 'Colorado': { "Boulder": ("hiking",) } } } def printOut(d,s): if(type(d)==dict): for k in d.keys(): printOut(d[k],s+" "+str(k)) # add the key to a string and pass the contained dictionary and the new string to the same function. (this is the recursive part...) else: try: # this try catch allows the method to handle iterable and non-iterable leaf nodes in your dictionary. for k in d: print s+" "+str(k) except TypeError: print s+" "+str(d) printOut(D,"") </code></pre> <p>prints::</p> <pre><code> America Washington Seattle park America Washington Seattle museum America Washington Kent market America Colorado Boulder hiking </code></pre> <p>notice that there is a leading space so this code might fail a test if it looking for a specific output, to eliminate the leading space we would simply add the line <code>s = s[1:] if len(s)&gt;0 else s</code> immediately after the else.</p>
0
2016-10-10T03:29:27Z
[ "python", "python-2.7", "dictionary" ]
Extract results from a dictionary
39,950,856
<p>I have a dictionary as follows:</p> <pre><code> D = { "America": { "Washington": { "Seattle": ('park', 'museum'), "Kent": ("market",) }, 'Colorado': { "Boulder": ("hiking",) } } } </code></pre> <p>how can I make the following results using that dictionary.</p> <pre><code>America Wahington Seattle park America Wahington Seattle museum America Wahington Kent market America Colorado Boulder hiking </code></pre> <p>I tried as follows:</p> <p>for x in D.iteritems(): print x</p> <p>Could not figure out how to extract each elements after that. Alos wan to to how is the good way of getting the above result.</p>
1
2016-10-10T03:20:56Z
39,950,961
<p>This versions should be more readable for you. But they are not so universal like other versions.</p> <pre><code>for country in D: for state in D[country]: for city in D[country][state]: for place in D[country][state][city]: print(country, state, city, place) for country, A in D.items(): for state, B in A.items(): for city, C in B.items(): for place in C: print(country, state, city, place) </code></pre>
1
2016-10-10T03:36:16Z
[ "python", "python-2.7", "dictionary" ]
Extract results from a dictionary
39,950,856
<p>I have a dictionary as follows:</p> <pre><code> D = { "America": { "Washington": { "Seattle": ('park', 'museum'), "Kent": ("market",) }, 'Colorado': { "Boulder": ("hiking",) } } } </code></pre> <p>how can I make the following results using that dictionary.</p> <pre><code>America Wahington Seattle park America Wahington Seattle museum America Wahington Kent market America Colorado Boulder hiking </code></pre> <p>I tried as follows:</p> <p>for x in D.iteritems(): print x</p> <p>Could not figure out how to extract each elements after that. Alos wan to to how is the good way of getting the above result.</p>
1
2016-10-10T03:20:56Z
39,950,977
<p>I would suggest recursive solution to work with your different kind of data:</p> <pre><code>def printX(data, prefix=''): if isinstance(data, dict): for itemKey, itemValue in data.iteritems(): newPrefix = '{} {}'.format(prefix, itemKey) printX(itemValue, newPrefix) elif isinstance(data, tuple): for itemValue in data: printX(itemValue, prefix) else: print('{} {}'.format(prefix, data)) </code></pre> <p>Did a test as below:</p> <pre><code>D = { 'America': { 'Washington': { 'Seattle': ('park', 'museum'), 'Kent': ('market',) }, 'Colorado': { 'Boulder': ('hiking',) } } } printX(D) </code></pre> <p>Output is as below</p> <pre><code>America Washington Seattle park America Washington Seattle museum America Washington Kent market America Colorado Boulder hiking </code></pre>
0
2016-10-10T03:38:16Z
[ "python", "python-2.7", "dictionary" ]
Building a LSTM Cell using Keras
39,950,872
<p>I'm trying to build a RNN for text generation. I'm stuck at building my LSTM cell. The data is shaped like this- X is the input sparse matrix of dim(90809,2700) and Y is the output matrix of dimension(90809,27). The following is my code for defining the LSTM Cell-</p> <pre><code>model = Sequential() model.add(LSTM(128, input_shape=(X.shape[0], X.shape[1]))) model.add(Dropout(0.2)) model.add(Dense(Y.shape[1], activation='softmax')) model.compile(loss='categorical_crossentropy', optimizer='adam') </code></pre> <p>My understanding is that the input_shape should be the dimension of the input matrix, and the dense layer should be the size of the output for each observation, i.e 27 in this case. However, I get the following error-</p> <pre><code>Exception: Error when checking model input: expected lstm_input_3 to have 3 dimensions, but got array with shape (90809, 2700) </code></pre> <p>I'm not able to figure out what is going wrong. Can anyone please help me figure out why is the lstm_input expecting 3 dimensions?</p> <p>I tried the following as well-</p> <pre><code>X= np.reshape(np.asarray(dataX), (n_patterns, n_vocab*seq_length,1)) Y=np.reshape(np.asarray(dataY), (n_patterns, n_vocab,1)) </code></pre> <p>This gave me the following error-</p> <pre><code>Exception: Error when checking model input: expected lstm_input_7 to have shape (None, 90809, 2700) but got array with shape (90809, 2700, 1) </code></pre> <p>Any help will be appreciated. Thanks!</p>
0
2016-10-10T03:23:43Z
40,013,716
<p>You should read about the difference between <code>input_shape</code>, <code>batch_input_shape</code> and <code>input_dim</code> <a href="https://keras.io/getting-started/sequential-model-guide/#specifying-the-input-shape" rel="nofollow">here</a>.</p> <p>For <code>input_shape</code>, we don't need to define the <code>batch_size</code>. This is how your LSTM layer should look like.</p> <pre><code>model.add(LSTM(128, input_shape=(X.shape[1], 1))) </code></pre> <p>or</p> <pre><code>model.add(LSTM(128, batch_input_shape=(X.shape[0], X.shape[1], 1))) </code></pre>
0
2016-10-13T06:25:09Z
[ "python", "keras", "recurrent-neural-network", "lstm" ]
Convert string based NaN's to numpy NaN's
39,950,951
<p>I have a dataframe with a part of it shown as below:</p> <pre><code>2016-12-27 NaN 2016-12-28 NaN 2016-12-29 NaN 2016-12-30 NaN 2016-12-31 NaN Name: var_name, dtype: object </code></pre> <p>The column contains NaN as strings/objects. How can I convert it to a numpy nan instead. Best would be able to do so when I read in the csv file.</p>
2
2016-10-10T03:34:26Z
39,951,125
<p>Suppose we have:</p> <pre><code>&gt;&gt;&gt; df=pd.DataFrame({'col':['NaN']*10}) </code></pre> <p>You can use <code>.apply</code> to convert:</p> <pre><code>&gt;&gt;&gt; new_df=df.apply(float, axis=1) &gt;&gt;&gt; type(new_df[0]) &lt;type 'numpy.float64'&gt; </code></pre>
1
2016-10-10T03:58:45Z
[ "python", "pandas", "numpy" ]
Convert string based NaN's to numpy NaN's
39,950,951
<p>I have a dataframe with a part of it shown as below:</p> <pre><code>2016-12-27 NaN 2016-12-28 NaN 2016-12-29 NaN 2016-12-30 NaN 2016-12-31 NaN Name: var_name, dtype: object </code></pre> <p>The column contains NaN as strings/objects. How can I convert it to a numpy nan instead. Best would be able to do so when I read in the csv file.</p>
2
2016-10-10T03:34:26Z
39,951,175
<p>Yes, you can do this when reading the csv file.</p> <pre><code>df = pd.read_csv('test.csv', names=['t', 'v'], dtype={'v':np.float64}) </code></pre> <p>Check the docs of <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow">pandas.read_csv</a>. There are some parameters is useful for your application:</p> <ul> <li>names </li> <li>dtype</li> <li>na_values</li> </ul> <p>Hope this would be helpful.</p>
1
2016-10-10T04:06:54Z
[ "python", "pandas", "numpy" ]
Convert string based NaN's to numpy NaN's
39,950,951
<p>I have a dataframe with a part of it shown as below:</p> <pre><code>2016-12-27 NaN 2016-12-28 NaN 2016-12-29 NaN 2016-12-30 NaN 2016-12-31 NaN Name: var_name, dtype: object </code></pre> <p>The column contains NaN as strings/objects. How can I convert it to a numpy nan instead. Best would be able to do so when I read in the csv file.</p>
2
2016-10-10T03:34:26Z
39,951,856
<p>I'd use the <code>converters</code> option in <code>read_csv</code>. In this case, we are aiming to convert the column in question to numeric values and treat everything else as <code>numpy.nan</code> which includes string version of <code>'NaN'</code></p> <pre><code>converter = lambda x: pd.to_numeric(x, 'coerce') df = pd.read_csv(StringIO(txt), delim_whitespace=True, converters={1: converter}, header=None) df </code></pre> <p><a href="http://i.stack.imgur.com/mPA8c.png" rel="nofollow"><img src="http://i.stack.imgur.com/mPA8c.png" alt="enter image description here"></a></p> <pre><code>df.dtypes 0 object 1 float64 dtype: object </code></pre>
1
2016-10-10T05:37:55Z
[ "python", "pandas", "numpy" ]
Harden sshd_config via python
39,951,199
<ol> <li>Find line starting with "#PermitRootLogin yes" and replace with "PermitRootLogin no"</li> <li>Append line at the bottom saying "AllowUsers user1@test.com"</li> <li>Restart sshd daemon</li> </ol> <p>(My Code)</p> <pre><code>#!/usr/bin/python3 import fileinput for line in fileinput.input("/etc/ssh/sshd_config", inplace=True), : print (line.replace("#PermitRootLogin", "PermitRootLogin no")) </code></pre> <p>(Error)</p> <p>Traceback (most recent call last): File "./assignment4-part1.py", line 6, in print (line.replace("#PermitRootLogin", "PermitRootLogin=no")) AttributeError: 'FileInput' object has no attribute 'replace'</p> <p>(Notes)</p> <p>I tried different methods as seen from other posts doing find and replace line, but run into similar problems/errors. Any guidance would be much appreciated. I am using CentOS, and python3 is installed/updated.</p>
0
2016-10-10T04:09:30Z
39,951,293
<p>You have a syntax error in your code. Your <code>for</code> loop expression has an erroneous comma:</p> <pre><code>for line in fileinput.input("/etc/ssh/sshd_config", inplace=True), : </code></pre> <p>That means that you're actually iterating over a single-element tuple, containing a <code>fileinput.FileInput</code> object, rather than iterating over the object itself.</p> <p>Remove the comma:</p> <pre><code>for line in fileinput.input("sshd_config", inplace=True): </code></pre> <p>Two other short recommendations:</p> <p>Don't use <code>print</code> in your loop, because <code>print</code> appends a newline, so you'll end up double-spacing your entire file. Consider instead:</p> <pre><code>for line in fileinput.input("sshd_config", inplace=True): sys.stdout.write(line.replace("#PermitRootLogin", "PermitRootLogin no")) </code></pre> <p>Lastly, consider what will happen if your input file contains:</p> <pre><code>#PermitRootLogin no </code></pre> <p>Your code will rewrite this as:</p> <pre><code>PermitRootLogin no no </code></pre> <p>Which is invalid.</p>
0
2016-10-10T04:24:17Z
[ "python", "python-3.x" ]
SQLAlchemy not finding Postgres table connected with postgres_fdw
39,951,230
<p>Please excuse any terminology typos, don't have a lot of experience with databases other than SQLite. I'm trying to replicate what I would do in SQLite where I could ATTACH a database to a second database and query across all the tables. I wasn't using SQLAlchemy with SQLite</p> <p>I'm working with SQLAlchemy 1.0.13, Postgres 9.5 and Python 3.5.2 (using Anaconda) on Win7/54. I have connected two databases (on localhost) using postgres_fdw and imported a few of the tables from the secondary database. I can successfully manually query the connected table with SQL in PgAdminIII and from Python using psycopg2. With SQLAlchemy I've tried:</p> <pre><code># Same connection string info that psycopg2 used engine = create_engine(conn_str, echo=True) class TestTable(Base): __table__ = Table('test_table', Base.metadata, autoload=True, autoload_with=engine) # Added this when I got the error the first time # test_id is a primary key in the secondary table Column('test_id', Integer, primary_key=True) </code></pre> <p>and get the error:</p> <pre><code>sqlalchemy.exc.ArgumentError: Mapper Mapper|TestTable|test_table could not assemble any primary key columns for mapped table 'test_table' </code></pre> <p>Then I tried:</p> <pre><code>insp = reflection.Inspector.from_engine(engine) print(insp.get_table_names()) </code></pre> <p>and the attached tables aren't listed (the tables from the primary database do show up). Is there a way to do what I am trying to accomplish?</p>
0
2016-10-10T04:16:20Z
39,995,132
<p>In order to map a table <a href="http://docs.sqlalchemy.org/en/latest/faq/ormconfiguration.html#how-do-i-map-a-table-that-has-no-primary-key" rel="nofollow">SQLAlchemy needs there to be at least one column denoted as a primary key column</a>. This does not mean that the column need actually be a primary key column in the eyes of the database, though it is a good idea. Depending on how you've imported the table from your foreign schema it may not have a representation of a primary key constraint, or any other constraints for that matter. You can work around this by either <a href="http://docs.sqlalchemy.org/en/latest/core/reflection.html#overriding-reflected-columns" rel="nofollow">overriding the reflected primary key column</a> in the <strong><code>Table</code> instance</strong> (not in the mapped classes body), or better yet tell the mapper what columns comprise the candidate key:</p> <pre><code>engine = create_engine(conn_str, echo=True) test_table = Table('test_table', Base.metadata, autoload=True, autoload_with=engine) class TestTable(Base): __table__ = test_table __mapper_args__ = { 'primary_key': (test_table.c.test_id, ) # candidate key columns } </code></pre> <p>To inspect foreign table names use the <a href="http://docs.sqlalchemy.org/en/latest/dialects/postgresql.html#sqlalchemy.dialects.postgresql.base.PGInspector.get_foreign_table_names" rel="nofollow"><code>PGInspector.get_foreign_table_names()</code></a> method:</p> <pre><code>print(insp.get_foreign_table_names()) </code></pre>
1
2016-10-12T09:28:20Z
[ "python", "postgresql", "sqlalchemy", "postgres-fdw" ]
How to find the starting element name in xml using iterparse
39,951,264
<p>I have the following sample xml</p> <pre><code>&lt;osm version="0.6" generator="CGImap 0.3.3 (28791 thorn-03.openstreetmap.org)" copyright="OpenStreetMap and contributors" attribution="http://www.openstreetmap.org/copyright" license="http://opendatacommons.org/licenses/odbl/1-0/"&gt; &lt;bounds minlat="41.9704500" minlon="-87.6928300" maxlat="41.9758200" maxlon="-87.6894800"/&gt; &lt;node id="261114295" visible="true" version="7" changeset="11129782" timestamp="2012-03-28T18:31:23Z" user="bbmiller" uid="451048" lat="41.9730791" lon="-87.6866303"/&gt; </code></pre> <p> </p> <p>and I want to extract bounds and node from the xml using python iter parse I have tried the following code snippet </p> <pre><code>import xml.etree.cElementTree as ET import pprint def count_tags(filename): mytags = {} osmfile = open('example.osm', 'r') for event, elem in ET.iterparse(osmfile,events=('end',)): if elem.tag == "tag": if elem.attrib['k'] in mytags: mytags[elem.attrib['k']] += 1 else: mytags[elem.attrib['k']] = 1 </code></pre> <p>but i m not able to extract the bounds and node ...what am i missing ?</p>
0
2016-10-10T04:20:15Z
39,953,418
<p>Assuming <code>bounds</code> and <code>node</code> are one level under the root of the XML, this should work:</p> <pre><code>def count_tags(): mytags = {} for event, child in ET.iterparse('example.osm'): if child.tag in ('bounds', 'node'): mytags[child.tag] = child.attrib print mytags </code></pre> <p>Calling <code>count_tags</code> outputs:</p> <pre><code>{ 'node': {'changeset': '11129782', 'uid': '451048', 'timestamp': '2012-03-28T18:31:23Z', 'lon': '-87.6866303', 'visible': 'true', 'version': '7', 'user': 'bbmiller', 'lat': '41.9730791', 'id': '261114295'}, 'bounds': {'minlat': '41.9704500', 'maxlon': '-87.6894800', 'minlon': '-87.6928300', 'maxlat': '41.9758200'} } </code></pre>
0
2016-10-10T07:42:29Z
[ "python", "xml", "iterparse" ]
Polygons in Python
39,951,281
<p>I've been trying to figure out how to find an approximation of PI using Polygons' method. And drawing out the polygons that are approximating PI.</p> <p>I've seen multiple ways to approximate PI, but none of them writing out the polygon on screen using Turtle (So you can see the visual aspect of the approximation) Could somebody please explain to me how to do so ? </p> <p>Any help would be much appreciated. This is more of a learning question then error. </p>
0
2016-10-10T04:22:35Z
39,964,824
<p>Taking a new approach, I've used turtle graphics to animate <a href="http://www.craig-wood.com/nick/articles/pi-archimedes/" rel="nofollow">Craig Wood's Pi - Archimedes code</a> from his <a href="http://www.craig-wood.com/nick/articles/fun-with-maths-and-python-introduction/" rel="nofollow">Fun with Maths and Python</a> series.</p> <p>This code only illustrates inscribed, even sided polygons. It doesn't use pi but instead estimates it from each polygon and outputs the increasingly accurate result to the console:</p> <pre><code>from math import sqrt from turtle import Turtle, Screen SCALE = 300 ITERATIONS = 7 def draw_circle(turtle): turtle.goto(0, -SCALE) turtle.pendown() turtle.circle(SCALE) turtle.penup() def inscribe_circle(turtle, sides, edge_length): turtle.goto(0, -SCALE) turtle.setheading(0) turtle.left(180 / sides) turtle.pendown() for _ in range(sides): turtle.forward(edge_length * SCALE) turtle.left(360 / sides) turtle.penup() # based on code and analysis from http://www.craig-wood.com/nick/articles/pi-archimedes/ def pi_archimedes(turtle, n): """ Calculate n iterations of Archimedes PI recurrence relation """ polygon_edge_length_squared = 2.0 polygon_edge_length = sqrt(polygon_edge_length_squared) polygon_sides = 4 inscribe_circle(turtle, polygon_sides, polygon_edge_length) print(polygon_sides * polygon_edge_length / 2) for _ in range(n - 1): polygon_sides *= 2 polygon_edge_length_squared = 2 - 2 * sqrt(1 - polygon_edge_length_squared / 4) polygon_edge_length = sqrt(polygon_edge_length_squared) inscribe_circle(turtle, polygon_sides, polygon_edge_length) print(polygon_sides * polygon_edge_length / 2) yertle = Turtle() yertle.penup() draw_circle(yertle) pi_archimedes(yertle, ITERATIONS) yertle.hideturtle() Screen().exitonclick() </code></pre> <p><a href="http://i.stack.imgur.com/ZVRd5.png" rel="nofollow"><img src="http://i.stack.imgur.com/ZVRd5.png" alt="enter image description here"></a></p> <p>Hopefully, this should give you a jump start on your own Archimedes Pi illustration.</p>
1
2016-10-10T18:47:20Z
[ "python", "turtle-graphics" ]
How to use for loop to plot figures saved to different files with matplotlib?
39,951,334
<p>I wanted to plot n independent figures by a for loop, with each figure saved to one file. My code is as following:</p> <pre><code>import matplotlib.pyplot as plt import numpy as np for i in range(len(nfile)): #nfile is a list of file names data = np.load(nfile[i]) plt.plot(data[0], data[1]) plt.savefig("figure_%d.png"%i, dpi=300) </code></pre> <p>I wanted only the plotting of data[i] to show in figure_i.png, but the former plottings (j=0, ..., i-1) also showed in figure_i.png. Is there any way to solve this?</p> <p>Thanks a lot!</p>
-2
2016-10-10T04:30:41Z
39,951,449
<p>At the beginning of your loop, add:</p> <pre><code>plt.close() </code></pre>
1
2016-10-10T04:47:56Z
[ "python", "matplotlib", "plot" ]
Python program returning none
39,951,335
<p>The following code (allegedly) returns none.</p> <pre><code>def addTwo(startingvalue): endingvalue = startingvalue + 2 return endingvalue sum1 = addTwo(5) sum2 = addTwo(52) print('The results of adding are ', sum1, sum2) </code></pre>
-3
2016-10-10T04:30:55Z
39,951,382
<p>As people have mentioned in the comments, you had a small typo in one of your function calls which would throw a NameError. But other than that, it works perfectly fine with the following output:</p> <pre><code>The results of adding are 7 54 </code></pre> <p>Okay, here's the problem, the code in the question is properly indented, the code in <a href="https://postimg.cc/image/x84h94xtj/" rel="nofollow">your screenshot</a> is improperly indented. In the screenshot lines 6,7 and 8 are indented, which means they're <em>inside</em> the function. Since the function returns on line 3 and is never called, you aren't getting the proper output.</p>
2
2016-10-10T04:39:09Z
[ "python", "return" ]
NLTK AssertionError when taking sentences from PlaintextCorpusReader
39,951,340
<p>I'm using a PlaintextCorpusReader to work with some files from Project Gutenberg. It seems to handle word tokenization without issue, but chokes when I request sentences or paragraphs.</p> <p>I start by downloading <a href="http://www.gutenberg.org/cache/epub/345/pg345.txt" rel="nofollow">a Gutenberg book (in UTF-8 plaintext)</a> to the current directory. Then:</p> <pre><code>&gt;&gt;&gt; from nltk.corpus import PlaintextCorpusReader &gt;&gt;&gt; r = PlaintextCorpusReader('.','Dracula.txt') &gt;&gt;&gt; r.words() ['DRACULA', 'CHAPTER', 'I', 'JONATHAN', 'HARKER', "'", ...] &gt;&gt;&gt; r.sents() Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/local/lib/python3.5/dist-packages/nltk/util.py", line 765, in __repr__ for elt in self: File "/usr/local/lib/python3.5/dist-packages/nltk/corpus/reader/util.py", line 296, in iterate_from new_filepos = self._stream.tell() File "/usr/local/lib/python3.5/dist-packages/nltk/data.py", line 1333, in tell assert check1.startswith(check2) or check2.startswith(check1) AssertionError </code></pre> <p>I've tried modifying the book in various ways: stripping off the header, removing newlines, adding a period to the end to finish the last "sentence". The error remains. Am I doing something wrong? Or am I running up against some limitation in NLTK?</p> <p>(Running Python 3.5.0, NLTK 3.2.1, on Ubuntu. Problem appears in other Python 3.x versions as well.)</p> <p>EDIT: Introspection shows the following locals at the point of exception.</p> <pre><code>&gt;&gt;&gt; pprint.pprint(inspect.trace()[-1][0].f_locals) {'buf_size': 63, 'bytes_read': 75, 'check1': "\n\n\n CHAPTER I\n\nJONATHAN HARKER'S JOURNAL\n\n(_Kept i", 'check2': '\n' '\n' ' CHAPTER I\n' '\n' "JONATHAN HARKER'S JOURNAL\n" '\n' '(_Kept in shorthand._)', 'est_bytes': 9, 'filepos': 11, 'orig_filepos': 75, 'self': &lt;nltk.data.SeekableUnicodeStreamReader object at 0x7fd2694b90f0&gt;} </code></pre> <p>In other words, check1 is losing an initial newline somehow.</p>
0
2016-10-10T04:31:39Z
39,963,074
<p>That particular file has a UTF-8 Byte Order Mark (EF BB BF) at the start, which is confusing NLTK. Removing those bytes manually, or copy-pasting the entire text into a new file, fixes the problem.</p> <p>I'm not sure why NLTK can't handle BOMs, but at least there's a solution.</p>
0
2016-10-10T16:49:45Z
[ "python", "nlp", "nltk" ]
python, plot triangular function into 2d arrays
39,951,392
<p>I'm new to python, in this case, I want to put my function into 2d arrays, so I can plot the function. Here is my triangle function, I'm using it for fuzzy logic:</p> <pre><code>def triangle (z,a,b,c): if (z&lt;=a) | (z&gt;=c): y = 0 elif (a&lt;=z) &amp; (z&lt;=b): y = (z-a) / (b-a) elif (b&lt;=z) &amp; (z&lt;=c): y = (b-z) / (c-b) return y </code></pre> <p>and I'm trying to make the array using numpy, <code>np.linspace</code> but I can't get it done, I've tried to use the fuzzy library, but nothing works.</p>
1
2016-10-10T04:40:49Z
39,951,997
<p>Looks like <code>a, b, c</code> are constants and <code>z</code> is a <code>np.linspace</code> between <code>a</code>, and <code>c</code>.</p> <p>You can make use of <a href="http://docs.scipy.org/doc/numpy/user/basics.indexing.html#boolean-or-mask-index-arrays" rel="nofollow">Boolean Indexing</a> , <a href="https://scipy.github.io/old-wiki/pages/Cookbook/Indexing#Boolean_indexing" rel="nofollow">SciPy cookbook/Indexing</a></p> <pre><code>a = 1 b = 2 c = 3 def triangle (z, a = a, b = b, c = c): y = np.zeros(z.shape) y[z &lt;= a] = 0 y[z &gt;= c] = 0 first_half = np.logical_and(a &lt; z, z &lt;= b) y[first_half] = (z[first_half]-a) / (b-a) second_half = np.logical_and(b &lt; z, z &lt; c) y[second_half] = (c-z[second_half]) / (c-b) return y z = np.linspace(a, c, num = 51) y = triangle(z, a, b, c) q = np.vstack((z, y)) # shape = (2, 50) ... [[z, z, z, ...], [y, y, y, ...]] q = q.T # shape = (50, 2) ... [[z, y], [z, y], ....] </code></pre> <p><a href="http://i.stack.imgur.com/X3sNY.png" rel="nofollow"><img src="http://i.stack.imgur.com/X3sNY.png" alt="enter image description here"></a></p> <hr> <p>When you use a numpy ndarray in a comparison expression the result is a boolean array:</p> <pre><code>&gt;&gt;&gt; q = np.linspace(0, 20, num = 50) &gt;&gt;&gt; print(q) [ 0. 0.40816327 0.81632653 1.2244898 1.63265306 2.04081633 2.44897959 2.85714286 3.26530612 3.67346939 4.08163265 4.48979592 4.89795918 5.30612245 5.71428571 6.12244898 6.53061224 6.93877551 7.34693878 7.75510204 8.16326531 8.57142857 8.97959184 9.3877551 9.79591837 10.20408163 10.6122449 11.02040816 11.42857143 11.83673469 12.24489796 12.65306122 13.06122449 13.46938776 13.87755102 14.28571429 14.69387755 15.10204082 15.51020408 15.91836735 16.32653061 16.73469388 17.14285714 17.55102041 17.95918367 18.36734694 18.7755102 19.18367347 19.59183673 20. ] &gt;&gt;&gt; print(q &lt; 5) [ True True True True True True True True True True True True True False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False] &gt;&gt;&gt; print(q &gt; 15) [False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False True True True True True True True True True True True True True] &gt;&gt;&gt; print(np.logical_and(q &gt; 5, q &lt; 15)) [False False False False False False False False False False False False False True True True True True True True True True True True True True True True True True True True True True True True True False False False False False False False False False False False False False] &gt;&gt;&gt; </code></pre> <p>You can use a boolean array to <em>select</em> portions of an array that meet your condition:</p> <pre><code>&gt;&gt;&gt; q[np.logical_and(q &gt; 7, q &lt; 11)] array([ 7.34693878, 7.75510204, 8.16326531, 8.57142857, 8.97959184, 9.3877551 , 9.79591837, 10.20408163, 10.6122449 ]) &gt;&gt;&gt; </code></pre> <p>When you use boolean indexing in an assignment statement the <em>right-hand-side</em> is only assigned to the indices where the comparison is <code>True</code>:</p> <pre><code>&gt;&gt;&gt; q[np.logical_and(q &gt; 7, q &lt; 11)] = -1 &gt;&gt;&gt; print(q) [ 0. 0.40816327 0.81632653 1.2244898 1.63265306 2.04081633 2.44897959 2.85714286 3.26530612 3.67346939 4.08163265 4.48979592 4.89795918 5.30612245 5.71428571 6.12244898 6.53061224 6.93877551 -1. -1. -1. -1. -1. -1. -1. -1. -1. 11.02040816 11.42857143 11.83673469 12.24489796 12.65306122 13.06122449 13.46938776 13.87755102 14.28571429 14.69387755 15.10204082 15.51020408 15.91836735 16.32653061 16.73469388 17.14285714 17.55102041 17.95918367 18.36734694 18.7755102 19.18367347 19.59183673 20. ] &gt;&gt;&gt; </code></pre>
2
2016-10-10T05:51:19Z
[ "python", "arrays", "numpy", "triangular" ]
I lose my values in the columns
39,951,581
<p>HI~ I wanna ask about my problem I've organized my data using pandas. and I fill my procedure out like below</p> <pre><code>import pandas as pd import numpy as np df1 = pd.read_table(r'E:\빅데이터 캠퍼스\골목상권 프로파일링 - 서울 열린데이터 광장 3.초기-16년5월분1\17.상권-추정매출\201301-201605\tbsm_trdar_selng.txt\tbsm_trdar_selng_utf8.txt' , sep='|' ,header=None ,dtype = { '0' : pd.np.int}) df1 = df1.replace('201301', int(201301)) df2 = df1[[0 ,1, 2, 3 ,4, 11,12 ,82 ]] df2_rename = df2.columns = ['STDR_YM_CD', 'TRDAR_CD', 'TRDAR_CD_NM', 'SVC_INDUTY_CD', 'SVC_INDUTY_CD_NM', 'THSMON_SELNG_AMT', 'THSMON_SELNG_CO', 'STOR_CO' ] print(df2.head(40)) df3_groupby = df2.groupby(['STDR_YM_CD', 'TRDAR_CD' ]) df4_agg = df3_groupby.agg(np.sum) print(df4_agg.head(30)) </code></pre> <p>When I print df2 I can see the 11947 and 11948 values in my TRDAR_CD column. like below picture</p> <p><a href="http://i.stack.imgur.com/OlrK9.png" rel="nofollow">enter image description here</a></p> <p>after that, I used groupby function and I lose my 11948 values in my TRDAR_CD column. You can see this situation in below picture</p> <p><a href="http://i.stack.imgur.com/EshYF.png" rel="nofollow">enter image description here</a></p> <p>probably, this problem from the warning message?? warning message is 'sys:1: DtypeWarning: Columns (0) have mixed types. Specify dtype option on import or set low_memory=False.' </p> <p>help me plz</p> <p>print(df2.info()) is</p> <p> RangeIndex: 1089023 entries, 0 to 1089022</p> <p>Data columns (total 8 columns):</p> <p>STDR_YM_CD 1089023 non-null object</p> <p>TRDAR_CD 1089023 non-null int64</p> <p>TRDAR_CD_NM 1085428 non-null object</p> <p>SVC_INDUTY_CD 1089023 non-null object</p> <p>SVC_INDUTY_CD_NM 1089023 non-null object</p> <p>THSMON_SELNG_AMT 1089023 non-null int64</p> <p>THSMON_SELNG_CO 1089023 non-null int64</p> <p>STOR_CO 1089023 non-null int64</p> <p>dtypes: int64(4), object(4)</p> <p>memory usage: 66.5+ MB</p> <p>None</p>
2
2016-10-10T05:06:11Z
39,951,608
<p><a href="http://pandas.pydata.org/pandas-docs/stable/advanced.html#creating-a-multiindex-hierarchical-index-object" rel="nofollow"><code>MultiIndex</code></a> is called first and second columns and if first level has duplicates by default it 'sparsified' the higher levels of the indexes to make the console output a bit easier on the eyes.</p> <p>You can show data in first level of <code>MultiIndex</code> by setting <a href="http://pandas.pydata.org/pandas-docs/stable/options.html#available-options" rel="nofollow"><code>display.multi_sparse</code></a> to <code>False</code>.</p> <p>Sample:</p> <pre><code>df = pd.DataFrame({'A':[1,1,3], 'B':[4,5,6], 'C':[7,8,9]}) df.set_index(['A','B'], inplace=True) print (df) C A B 1 4 7 5 8 3 6 9 #temporary set multi_sparse to False #http://pandas.pydata.org/pandas-docs/stable/options.html#getting-and-setting-options with pd.option_context('display.multi_sparse', False): print (df) C A B 1 4 7 1 5 8 3 6 9 </code></pre> <p>EDIT by edit of question:</p> <p>I think problem is type of value <code>11948</code> is <code>string</code>, so it is omited.</p> <p>EDIT1 by file:</p> <p>You can simplify your solution by add parameter <code>usecols</code> in <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow"><code>read_csv</code></a> and then aggregating by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.sum.html" rel="nofollow"><code>GroupBy.sum</code></a>:</p> <pre><code>import pandas as pd import numpy as np df2 = pd.read_table(r'tbsm_trdar_selng_utf8.txt' , sep='|' , header=None , usecols=[0 ,1, 2, 3 ,4, 11,12 ,82], names=['STDR_YM_CD', 'TRDAR_CD', 'TRDAR_CD_NM', 'SVC_INDUTY_CD', 'SVC_INDUTY_CD_NM', 'THSMON_SELNG_AMT', 'THSMON_SELNG_CO', 'STOR_CO'], dtype = { '0' : int}) df4_agg = df2.groupby(['STDR_YM_CD', 'TRDAR_CD' ]).sum() print(df4_agg.head(10)) THSMON_SELNG_AMT THSMON_SELNG_CO STOR_CO STDR_YM_CD TRDAR_CD 201301 11947 1966588856 74798 73 11948 3404215104 89064 116 11949 1078973946 42005 45 11950 1759827974 93245 71 11953 779024380 21042 84 11954 2367130386 94033 128 11956 511840921 23340 33 11957 329738651 15531 50 11958 1255880439 42774 118 11962 1837895919 66692 68 </code></pre>
2
2016-10-10T05:09:48Z
[ "python", "pandas" ]
django-if template doesnt work properly
39,951,616
<p>I have a list of stations and I have to display stations from 'start'. start and stop contain station ids. I am trying in this way but when I run all I get is a blank page. showtrain.html :-</p> <pre><code> &lt;table&gt; &lt;tr&gt; {% for st in st_list %} {% if st.station_id &gt;= start %} &lt;td&gt; {{ st.station_id }} &lt;/td&gt; {% endif %} {% endfor %} &lt;/tr&gt; &lt;/table&gt; </code></pre> <p>nothing works inside if except conditions like {% if start %}. i know i am missing something trivial. Please help me figure it out. i am using django 1.6. edit: views.py-</p> <pre><code>def runtrain(request): if request.method == 'POST': #request.post.get method retrieves user input from a form start = request.POST.get('start', None) stop = request.POST.get('stop', None) rid = request.session.get('route_id') stlist = SequenceTable.objects.filter(route_id = rid) #print start data2 = { "start" : start, "stop" : stop, "st_list" : stlist, } return render(request,"showtrain.html",data2) </code></pre> <p>models.py-</p> <pre><code> class SequenceTable(models.Model): id = models.AutoField( primary_key=True ) route_id = models.ForeignKey( route, on_delete=models.CASCADE) station_id = models.ForeignKey(Stations, on_delete=models.CASCADE) sequence_no = models.IntegerField( null=True ) #def __str__(self): # return self.sequence_no class Stations(models.Model): station_id = models.AutoField( primary_key=True ) station = models.CharField( max_length=20 ) station_code = models.CharField( max_length=10 ) def __str__(self): return self.station_code </code></pre>
-2
2016-10-10T05:11:05Z
39,955,495
<p>as stated by RemcoGerlich the problem lies in mismatched datatype. the value of start returned from form is string type and station_id is integer. if cannot compare them and hence control doesnt enter if statements so nothing gets printed</p>
0
2016-10-10T09:43:50Z
[ "python", "django" ]
Django Integrity Error in Bulk Import via CSV in Admin
39,951,637
<p>I am trying to implement a CSV Import in Django Admin and save bulk data corresponding to the CSV file's rows. I have a model <code>Employee</code> with a <code>OneToOneField</code> to Django's <code>Auth</code> model. I have written a custom Form that accepts a csv file. However, when I call the super().save() method, I get an Integrity Error.</p> <p>My Model class is:</p> <pre><code>class Employee(models.Model): user = models.OneToOneField(User, primary_key=True) company = models.ForeignKey(Companies) department = models.ForeignKey(Departments) mobile = models.CharField(max_length=16, default="0", blank=True) gender = models.CharField(max_length=1, default="m", choices=GENDERS) image = models.ImageField(upload_to=getImageUploadPath, null=True, blank=True) designation = models.CharField(max_length=64) is_hod = models.BooleanField(default=False) is_director = models.BooleanField(default=False) </code></pre> <p>This is my Admin class:</p> <pre><code>class EmployeeAdmin(admin.ModelAdmin): list_display = ('user', 'company', 'department', 'designation', 'is_hod', 'is_director') search_fields = ['user__email', 'user__first_name', 'user__last_name'] form = EmployeeForm </code></pre> <p>This is my Form class:</p> <pre><code>class EmployeeForm(forms.ModelForm): company = forms.ModelChoiceField(queryset=Companies.objects.all()) file_to_import = forms.FileField() class Meta: model = Employee fields = ("company", "file_to_import") def save(self, commit=True, *args, **kwargs): try: company = self.cleaned_data['company'] records = csv.reader(self.cleaned_data['file_to_import']) for line in records: # Get CSV Data. # Create new employee. employee = CreateEmployee(email, firstName, lastName, gender, '', company.id, dept[0].id, designation, isSuperuser, isHod, isDirector) super(EmployeeForm, self).save(*args, **kwargs) except Exception as e: traceback.print_exc() raise forms.ValidationError('Something went wrong.') </code></pre> <p>The <code>CreateEmployee</code> method is defined as:</p> <pre><code>@transaction.atomic def CreateEmployee(email='', firstName='', lastName='', gender='', mobile='', companyId='', departmentId='', designation='', isSuperuser=False, isHod=False, isDirector=False): try: user = User( username=email, email=email, first_name=firstName, last_name=lastName, is_superuser=isSuperuser, is_active=True) password = getPassword(firstName, lastName) user.set_password(password) user.save() company = Companies(id=companyId) dept = Departments(id=departmentId) employee = Employee( user=user, mobile=mobile, gender=gender, designation=designation, company=company, department=dept, is_hod=isHod, is_director=isDirector) employee.save() return employee except DatabaseError as e: raise e return None </code></pre> <p>I am getting an exception in the form's except block with the error: <code>IntegrityError: (1048, "Column 'user_id' cannot be null")</code></p> <p>In the traceback, I can see that the exception is being raised in the <code>super(EmployeeForm, self).save(*args, **kwargs)</code> line. I am assuming the super method is trying to save an instance.</p> <p>The complete traceback is:</p> <pre><code>Traceback (most recent call last): File "/home/rachit/Projects/project/users/forms.py", line 81, in save super(EmployeeForm, self).save(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/forms/models.py", line 455, in save construct=False) -- lot of text -- IntegrityError: (1048, "Column 'user_id' cannot be null") </code></pre> <p>I am guessing the ModelForm's save method is trying to save an instance, but I don't want that to happen as I have created multiple users.</p> <p>What am I doing wrong here? Is there an alternative way to achieve what I want?</p> <p>TIA.</p>
1
2016-10-10T05:14:10Z
39,951,711
<p>Since you’re doing your own save, you don’t need to call save on the Super form. Typically when you have foreign key fields that you need to fill in like this, you use commit=False to get an instance of the unsaved model., but you can do either of these:</p> <pre><code>def save(self, commit=True, *args, **kwargs): try: company = self.cleaned_data['company'] records = csv.reader(self.cleaned_data['file_to_import']) for line in records: # Get CSV Data. # Create new employee. employee = CreateEmployee(email, firstName, lastName, gender, '', company.id, dept[0].id, designation, isSuperuser, isHod, isDirector) # super(EmployeeForm, self).save(*args, **kwargs) # - or - super(EmployeeForm, self).save(commit=False) # updated based on additional comment return employee except Exception as e: traceback.print_exc() raise forms.ValidationError('Something went wrong.') </code></pre>
3
2016-10-10T05:22:48Z
[ "python", "django", "csv" ]
Python - Create multiple folders from CSV file
39,951,684
<p>I want to create multiple folders/directories (if they don't exist) using information from a CSV file.</p> <p>I have the information from csv as follows:</p> <pre><code> Column0 Column1 Column2 Column3 51 TestName1 0 https://siteAdress//completed/file.txt 53 TestName2 0 https://siteAdress//completed/file.txt 67 TestName1 2 https://siteAdress//uploads/file.txt 68 TestName1 2 https://siteAdress//uploads/file.txt </code></pre> <p>I want to iterate column3, if it contains 'uploads' then it should make a folder with the corresponding jobname mentioned on column1 then create 'input' folder and within it create respective file.txt file, and if column3 contains 'completed' then it should make 'output' folder (within that same jobname folder next to input folder) and then within it the 'file.txt' file. And do this for all jobs mentioned in column1.</p> <p>Something like this:</p> <pre><code>TestName1/input/file.txt TestName1/output/file.txt TestName1/output2/file.txt TestName2/input/file.txt TestName2/output/file.txt </code></pre> <p>Note: Most of data will contain multiple output folders for each jobname. In this case it should create as many output folders as are mentioned in the csv file.</p> <p>So far, I have done this:</p> <pre><code>import csv, os #reads from csv file with open('limitedresult.csv') as csvfile: readCSV = csv.reader(csvfile, delimiter = ',') for row in readCSV: print(row) </code></pre> <p>Your help would be highly appreciated, please let me know if the question is still confusing and I will try to explain in more detail.</p>
0
2016-10-10T05:20:00Z
39,952,538
<p>The following approach should help get you started:</p> <ol> <li>Open the CSV file and skip the header row.</li> <li>Read a row, splitting it into named columns.</li> <li>If the <code>file_url</code> contains <code>input</code>, use a sub folder of <code>input</code>, etc.</li> <li>Create a folder based on <code>output_root</code> and the sub folder name.</li> <li>Use a Python <code>Counter</code> to keep track of the number of times each sub folder is used.</li> <li>Add the current sub folder count to the folder name and create any necessary output folders.</li> <li>Use the Python <code>requests</code> library to download the text file from the website.</li> <li>Extract the filename from the URL and use this to write the file contents.</li> </ol> <p>The script is as follows:</p> <pre><code>from collections import Counter import requests import csv import os output_root = r'/myroot' output_counter = Counter() with open('limitedresult.csv', newline='') as csvfile: readCSV = csv.reader(csvfile) header = next(readCSV) for number, test, col2, file_url in readCSV: if 'completed' in file_url: sub_folder = 'input' elif 'uploads' in file_url: sub_folder = 'output' else: sub_folder = None print('Invalid URL -', file_url) if sub_folder: output_folder = os.path.join(output_root, test, sub_folder) output_counter.update([output_folder]) output_folder += str(output_counter[output_folder]) os.makedirs(output_folder, exist_ok=True) data = requests.get(file_url) file_name = os.path.split(file_url)[1] with open(os.path.join(output_folder, file_name), 'w') as f_output: f_output.write(data.text) </code></pre> <p>Note, you may need to install <code>requests</code>, this can usually be done using <code>pip install requests</code>.</p>
0
2016-10-10T06:40:15Z
[ "python", "csv" ]
Python simple interest calculation
39,951,705
<p>I am trying to calculate how much monthly payment in order to pay off a loan in 12 month. use $10 as incremental.</p> <pre><code>Payment = 0 balance = float (1200) interest = float (0.18) MonthlyInt = interest/12.0 while balance &gt; 0 : Payment = Payment + 10 month = 0 while month &lt; 12 and balance &gt; 0: IntPay = balance* MonthlyInt balance += IntPay balance -= Payment month += 1 print Payment </code></pre> <p>The correct answer should be 110, why am I getting 60?</p>
0
2016-10-10T05:22:09Z
39,952,051
<p>The main things generating the difference are: </p> <ul> <li>The balance should be reset to 1200 before looping through the 12 months again</li> <li>The payment should be deducted from the balance before calculating the interest</li> </ul> <p>A couple smaller python things are:</p> <ul> <li><code>float()</code> isn't needed around numbers like <code>0.18</code>, it's already a float</li> <li><code>1200.</code> would imply that the number is a float, so <code>float()</code> isn't needed</li> </ul> <p>Accounting for these things then:</p> <pre><code>Payment = 0 interest = 0.18 MonthlyInt = interest/12.0 balance = 1200. while balance &gt; 0 : Payment = Payment + 10 month = 0 balance = 1200. while month &lt; 12 and balance &gt; 0: balance -= Payment IntPay = balance* MonthlyInt balance += IntPay month += 1 print(Payment) </code></pre> <p>gives a result of <code>110</code>.</p>
3
2016-10-10T05:56:35Z
[ "python" ]
click iteration fails in selenium
39,951,766
<p>Im trying to translate user comments from tripadvisor. So the scraper reads the link, then one by one iterates through each of the comments and translates them. But my code stops after translating the first comment itself.</p> <pre><code>from selenium import webdriver from selenium.webdriver.common.by import By import time driver = webdriver.Chrome() driver.maximize_window() driver.get("https://www.tripadvisor.in/ShowUserReviews-g1-d8729164-r425811350-TAP_Portugal-World.html") gt= driver.find_elements(By.CSS_SELECTOR,".googleTranslation&gt;.link") for i in gt: i.click() time.sleep(2) driver.find_element_by_class_name("ui_close_x").click() time.sleep(2) </code></pre>
1
2016-10-10T05:28:07Z
39,951,801
<p>try this:</p> <pre><code>from selenium import webdriver from selenium.webdriver.common.by import By import time from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC driver = webdriver.Chrome() driver.maximize_window() url="https://www.tripadvisor.com/Airline_Review-d8729164-Reviews-Cheap-Flights-TAP-Portugal#REVIEWS" driver.get(url) wait = WebDriverWait(driver, 10) langselction = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "span.sprite-date_picker-triangle"))) langselction.click() driver.find_element_by_xpath("//div[@class='languageList']//li[normalize-space(.)='Portuguese first']").click() gt= driver.find_elements(By.CSS_SELECTOR,".googleTranslation&gt;.link") for i in gt: i.click() time.sleep(2) driver.find_element_by_class_name("ui_close_x").click() time.sleep(2) </code></pre>
1
2016-10-10T05:32:32Z
[ "python", "selenium", "web-scraping" ]
click iteration fails in selenium
39,951,766
<p>Im trying to translate user comments from tripadvisor. So the scraper reads the link, then one by one iterates through each of the comments and translates them. But my code stops after translating the first comment itself.</p> <pre><code>from selenium import webdriver from selenium.webdriver.common.by import By import time driver = webdriver.Chrome() driver.maximize_window() driver.get("https://www.tripadvisor.in/ShowUserReviews-g1-d8729164-r425811350-TAP_Portugal-World.html") gt= driver.find_elements(By.CSS_SELECTOR,".googleTranslation&gt;.link") for i in gt: i.click() time.sleep(2) driver.find_element_by_class_name("ui_close_x").click() time.sleep(2) </code></pre>
1
2016-10-10T05:28:07Z
39,952,293
<p>I tried the same code of yours just increased the sleep time and list is getting traversed through the list and comments are also getting translated </p> <p>Note: I tried the program on Firefox</p> <pre><code>from selenium import webdriver from selenium.webdriver.common.by import By import time driver = webdriver.Firefox() driver.maximize_window() driver.get("https://www.tripadvisor.in/ShowUserReviews-g1-d8729164-r425811350-TAP_Portugal-World.html") gt= driver.find_elements(By.CSS_SELECTOR,".googleTranslation&gt;.link") print(type(gt)) for i in gt: i.click() time.sleep(15) driver.find_element_by_class_name("ui_close_x").click() time.sleep(15) </code></pre>
1
2016-10-10T06:18:29Z
[ "python", "selenium", "web-scraping" ]
Finding subset of dataframe rows that maximize one column sum while limiting sum of another
39,951,768
<p>A beginner to pandas and python, I'm trying to find select the 10 rows in a dataframe such that the following requirements are fulfilled:</p> <ol> <li>Only 1 of each category in a categorical column</li> <li>Maximize sum of a column</li> <li>While keeping sum of another column below a specified threshold</li> </ol> <p>The concept I struggle with is how to do all of this at the same time. In this case, the goal is to <em>select</em> 10 rows resulting in a subset where sum of <code>OPW</code> is maximized, while the sum of <code>salary</code> remains below an integer threshold, and all strings in <code>POS</code> are unique. If it helps understanding the problem, I'm basically trying to come up with the baseball dream team on a budget, with <code>OPW</code> being the metric for how well the player performs and <code>POS</code> being the position I would assign them to. The current dataframe looks like this:</p> <pre><code> playerID OPW POS salary 87 bondsba01 62.061290 OF 8541667 439 heltoto01 41.002660 1B 10600000 918 thomafr04 38.107000 1B 7000000 920 thomeji01 37.385272 1B 6337500 68 berkmla01 36.210367 1B 10250000 785 ramirma02 35.785630 OF 13050000 616 martied01 32.906884 3B 3500000 775 pujolal01 32.727629 1B 13870949 966 walkela01 30.644305 OF 6050000 354 giambja01 30.440007 1B 3103333 859 sheffga01 29.090699 OF 9916667 511 jonesch06 28.383418 3B 10833333 357 gilesbr02 28.160054 OF 7666666 31 bagweje01 27.133545 1B 6875000 282 edmonji01 23.486406 CF 4500000 0 abreubo01 23.056375 RF 9000000 392 griffke02 22.965706 OF 8019599 ... ... ... ... </code></pre> <p>If my team was only 3 people, with a <code>OF</code>,<code>1B</code>, and <code>3B</code>, and I had a sum<code>salary</code> threshold of $19,100,000, I would get the following team:</p> <pre><code> playerID OPW POS salary 87 bondsba01 62.061290 OF 8541667 918 thomafr04 38.107000 1B 7000000 616 martied01 32.906884 3B 3500000 </code></pre> <p>The output would ideally be another dataframe with just the 10 rows that fulfill the requirements. The only solution I can think of is to bootstrap a bunch of teams (10 rows) with each row having a unique <code>POS</code>, remove teams above the 'salary' sum threshold, and then <code>sort_value()</code> the teams by <code>df.OPW.sum()</code>. Not sure how to implement that though. Perhaps there is a more elegant way to do this? Edit: Changed dataframe to provide more information, added more context. </p>
0
2016-10-10T05:28:45Z
39,951,826
<p>IIUC you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow"><code>groupby</code></a> with aggregating <code>sum</code>:</p> <pre><code>df1 = df.groupby('category', as_index=False).sum() print (df1) category value cost 0 A 70 2450 1 B 67 1200 2 C 82 1300 3 D 37 4500 </code></pre> <p>Then filter by <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow"><code>boolean indexing</code></a> with <code>treshold</code>:</p> <pre><code>tresh = 3000 df1 = df1[df1.cost &lt; tresh] </code></pre> <p>And last get top 10 values by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.nlargest.html" rel="nofollow"><code>nlargest</code></a>:</p> <pre><code>#in sample used top 3, in real data is necessary set to 10 print (df1.nlargest(3,columns=['value'])) category value cost 2 C 82 1300 0 A 70 2450 1 B 67 1200 </code></pre>
0
2016-10-10T05:35:12Z
[ "python", "algorithm", "pandas", "numpy", "data-science" ]
Finding subset of dataframe rows that maximize one column sum while limiting sum of another
39,951,768
<p>A beginner to pandas and python, I'm trying to find select the 10 rows in a dataframe such that the following requirements are fulfilled:</p> <ol> <li>Only 1 of each category in a categorical column</li> <li>Maximize sum of a column</li> <li>While keeping sum of another column below a specified threshold</li> </ol> <p>The concept I struggle with is how to do all of this at the same time. In this case, the goal is to <em>select</em> 10 rows resulting in a subset where sum of <code>OPW</code> is maximized, while the sum of <code>salary</code> remains below an integer threshold, and all strings in <code>POS</code> are unique. If it helps understanding the problem, I'm basically trying to come up with the baseball dream team on a budget, with <code>OPW</code> being the metric for how well the player performs and <code>POS</code> being the position I would assign them to. The current dataframe looks like this:</p> <pre><code> playerID OPW POS salary 87 bondsba01 62.061290 OF 8541667 439 heltoto01 41.002660 1B 10600000 918 thomafr04 38.107000 1B 7000000 920 thomeji01 37.385272 1B 6337500 68 berkmla01 36.210367 1B 10250000 785 ramirma02 35.785630 OF 13050000 616 martied01 32.906884 3B 3500000 775 pujolal01 32.727629 1B 13870949 966 walkela01 30.644305 OF 6050000 354 giambja01 30.440007 1B 3103333 859 sheffga01 29.090699 OF 9916667 511 jonesch06 28.383418 3B 10833333 357 gilesbr02 28.160054 OF 7666666 31 bagweje01 27.133545 1B 6875000 282 edmonji01 23.486406 CF 4500000 0 abreubo01 23.056375 RF 9000000 392 griffke02 22.965706 OF 8019599 ... ... ... ... </code></pre> <p>If my team was only 3 people, with a <code>OF</code>,<code>1B</code>, and <code>3B</code>, and I had a sum<code>salary</code> threshold of $19,100,000, I would get the following team:</p> <pre><code> playerID OPW POS salary 87 bondsba01 62.061290 OF 8541667 918 thomafr04 38.107000 1B 7000000 616 martied01 32.906884 3B 3500000 </code></pre> <p>The output would ideally be another dataframe with just the 10 rows that fulfill the requirements. The only solution I can think of is to bootstrap a bunch of teams (10 rows) with each row having a unique <code>POS</code>, remove teams above the 'salary' sum threshold, and then <code>sort_value()</code> the teams by <code>df.OPW.sum()</code>. Not sure how to implement that though. Perhaps there is a more elegant way to do this? Edit: Changed dataframe to provide more information, added more context. </p>
0
2016-10-10T05:28:45Z
40,125,521
<p>This is a linear programming problem. For each POS, you're trying to maximize individual OPW while total salary across the entire team is subject to a constraint. You can't solve this with simple pandas operations, but <a href="https://pythonhosted.org/PuLP/" rel="nofollow">PuLP</a> could be used to formulate and solve it (see the Case Studies there for some examples).</p> <p>However, you could get closer to a manual solution by using pandas to group by (or sort by) POS and then either (1) sort by OPW descending and salary ascending, or (2) add some kind of "return on investment" column (OPW divided by salary, perhaps) and sort on that descending to find the players that give you the biggest bang for the buck in each position.</p>
1
2016-10-19T08:03:52Z
[ "python", "algorithm", "pandas", "numpy", "data-science" ]
I want to trigger a response at different points in a loop
39,952,000
<p>I have created a task on Psychopy in which beads a drawn from a jar. 50 different beads are drawn and after each bead the participant is asked to make a probability rating. The task is looped from an excel file but it takes too long to do 50 ratings. I was hoping to get ratings for the first 10 beads. Then draw up a rating for ever second bead until 20 beads are drawn. Then for the next 30 beads until the 50th bead to only ask for a rating every five beads drawn (I'm really new to coding, sorry for how incorrect this may be in advance). I've written the code like this however unfortunately it doesn't work? (on the turns that don't have a rating i've tried to put a keyboard response to trigger the next thing in the sequence to emerge) -</p> <pre><code>for row_index, row in (beads_params_pinkbluegreyratingparamters.xlsx): if row(0:10) and t &gt;= 0.0 and rating.status == NOT_STARTED: break rating.tStart = t # underestimates by a little under one frame rating.frameNStart = frameN # exact frame index rating.setAutoDraw(True) continueRoutine &amp;= rating.noResponse # a response ends the trial elif row(12:20:2) and t &gt;= 0.0 and rating.status == NOT_STARTED: break rating.tStart = t # underestimates by a little under one frame rating.frameNStart = frameN # exact frame index rating.setAutoDraw(True) continueRoutine &amp;= rating.noResponse elif rows.event.getkeys, row(11:19:2): elif len(theseKeys) &gt; 0: break key_resp_2.keys = theseKeys [-1] key_resp_2.rt = key_resp_2.clock.getTime() continueRoutine = False elif row(20:50:5) and t &gt;= 0.0 and rating.status == NOT_STARTED: break rating.tStart = t # underestimates by a little under one frame rating.frameNStart = frameN # exact frame index rating.setAutoDraw(True) continueRoutine &amp;= rating.noResponse rows.event.getKeys, row[21, 22, 23, 24, 26, 27, 28, 29, 31, 32, 33, 34, 36, 37, 38 ,39, 41, 42, 43, 44, 46, 47, 48, 49]: elif len(theseKeys) &gt; 0: key_resp_2.Keys = theseKeys [-1] key_resp_2.rt = key_resp_2.clock.getTtime() continueRoutine = False </code></pre>
1
2016-10-10T05:51:40Z
39,952,074
<p>You should loop only once, but perform all checks inside that one loop:</p> <pre><code>for row_index, rows in (beads_params_pinkbluegreyratingparamters.xlsx): if (row_index &lt; 10): rows.ratingscale(0:10) elif (row_index &gt;=10 and row_index &lt;20): rows.ratingscale(12:20:2) rows.key_resp_2(11:19:2) elif (row_index &gt;=20): rows.ratingscale(25:50:5) rows.key_resp_2[21, 22, 23, 24, 26, 27, 28, 29, 31, 32, 33, 34, 36, 37, 38, 39, 41, 42, 43, 44, 46, 47, 48, 49] </code></pre> <p>Note that there are some syntax errors in your code, e.g. <code>rows.key_resp_2(11:19:2)</code> doesn't make sense.</p>
1
2016-10-10T05:59:00Z
[ "python", "excel", "psychopy" ]
Extract specific XML tags Values in python
39,952,139
<p>I have a XML file which contains tags like these. </p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8" standalone="yes"?&gt; &lt;DataFlows&gt; &lt;DataFlow id="ABC"&gt; &lt;Flow name="flow4" type="Ingest"&gt; &lt;Ingest dataSourceName="type1" tableName="table1"&gt; &lt;DataSet&gt; &lt;DataSetRef&gt;value1-${d1}-${t1}&lt;/DataSetRef&gt; &lt;DataStore&gt;ingest&lt;/DataStore&gt; &lt;/DataSet&gt; &lt;Mode&gt;Overwrite&lt;/Mode&gt; &lt;/Ingest&gt; &lt;/Flow&gt; &lt;/DataFlow&gt; &lt;DataFlow id="MHH" dependsOn="ABC"&gt; &lt;Flow name="flow5" type="Reconcile"&gt; &lt;Reconciliation&gt; &lt;Source&gt;QW&lt;/Source&gt; &lt;Target&gt;EF&lt;/Target&gt; &lt;ComparisonKey&gt; &lt;Column&gt;dealNumber&lt;/Column&gt; &lt;/ComparisonKey&gt; &lt;ReconcileColumns mode="required"&gt; &lt;Column&gt;bookId&lt;/Column&gt; &lt;/ReconcileColumns&gt; &lt;/Reconciliation&gt; &lt;/Flow&gt; &lt;Flow name="output" type="Export" format="Native"&gt; &lt;Table publishToSQLServer="true"&gt; &lt;DataSet&gt; &lt;DataSetRef&gt;value4_${cob}_${ts}&lt;/DataSetRef&gt; &lt;DataStore&gt;recon&lt;/DataStore&gt; &lt;Date&gt;${run_date}&lt;/Date&gt; &lt;/DataSet&gt; &lt;Mode&gt;Overwrite&lt;/Mode&gt; &lt;/Table&gt; &lt;/Flow&gt; &lt;/DataFlow&gt; &lt;/DataFlows&gt; </code></pre> <p>I want to process this XML in python using Python Minimal DOM implementation. I need to extract information in DataSet Tag only when the Flow type in “Reconcile".</p> <p>For Example:</p> <p>If my Flow Type is "Reconcile" then i need to go to next Flow tag named "output" and extract values of DataSetRef,DataSource and Date tags.</p> <p>So far i have tried below mentioned Code but i am getting blank values in all may fields.</p> <pre><code>#!/usr/bin/python from xml.dom.minidom import parse import xml.dom.minidom # Open XML document using minidom parser DOMTree = xml.dom.minidom.parse("Store.xml") collection = DOMTree.documentElement #if collection.hasAttribute("DataFlows"): # print "Root element : %s" % collection.getAttribute("DataFlows") pretty = DOMTree.toprettyxml() print "Collectio: %s" % collection dataflows = DOMTree.getElementsByTagName("DataFlow") # Print detail of each movie. for dataflow in dataflows: print "*****dataflow*****" if dataflow.hasAttribute("dependsOn"): print "Depends On is present" flows = DOMTree.getElementsByTagName("Flow") print "flows" for flow in flows: print "******flow******" if flow.hasAttribute("type") and flow.getAttribute("type") == "Reconcile": flowByReconcileType = flow.getAttribute("type") TagValue = flow.getElementsByTagName("DataSet") print "Tag Value is %s" % TagValue print "flow type is: %s" % flowByReconcileType </code></pre> <p>From there onwards i need to pass these 3 values extracted above to Unix Shell scripts to process some directories. Any Help would be appreciated.</p>
0
2016-10-10T06:04:58Z
39,953,268
<p>First of all check if your XML is well formatted. You are missing a root tag and you got wrong double quotes for example here <code>&lt;Flow name=“flow4" type="Ingest"&gt;</code></p> <p>IN your code you are correctly grabbing the dataflows.</p> <p>You dont need to query the DOMTree again for the flows, you can check every dataflow's flow by quering like this:</p> <pre><code>flows = dataflow.getElementsByTagName("Flow") </code></pre> <p>Your condition <code>if flow.hasAttribute("type") and flow.getAttribute("type") == "Reconcile":</code> looks ok to me, so in order to get the next flow item you can do something like this always checking your index is inside the array.</p> <pre><code>for index, flow in enumerate(flows): if flow.hasAttribute("type") and flow.getAttribute("type") == "Reconcile": if index + 1 &lt; len(flows): your_flow = flows[index + 1] </code></pre>
0
2016-10-10T07:31:05Z
[ "python", "xml" ]