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
I have a numpy array, and an array of indexs, how can I access to these positions at the same time
40,038,557
<p>for example, I have the numpy arrays like this</p> <pre><code>a = array([[1, 2, 3], [4, 3, 2]]) </code></pre> <p>and index like this to select the max values</p> <pre><code>max_idx = array([[0, 2], [1, 0]]) </code></pre> <p>how can I access there positions at the same time, to modify them. like "a...
1
2016-10-14T08:31:36Z
40,039,444
<p>Numpy support <a href="http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#advanced-indexing" rel="nofollow">advanced slicing</a> like this:</p> <pre><code>a[b[:, 0], b[:, 1]] = 0 </code></pre> <p>Code above would fit your requirement. </p> <p>If <code>b</code> is more than 2-D. A better way should be ...
0
2016-10-14T09:17:54Z
[ "python", "arrays", "numpy" ]
Using Python to remove paratext (or 'noise') from txt files
40,038,596
<p>I am in the proces of preparing a corpus of textfiles, consisting of 170 Dutch novels. I am a literary scholar and relatively new to Python, and also to programming in general. What I am trying to do is writing a Python script for removing everything from each .txt file that does NOT belong to the actual content of ...
1
2016-10-14T08:33:35Z
40,038,646
<p><code>enumerate</code> already provides the <em>line</em> alongside its index, so you don't need call <code>readline</code> on the file object again as that would lead to unpredictable behavior - more like reading the file object at a double pace:</p> <pre><code>for line_number, line in enumerate(inputfile, 1): ...
1
2016-10-14T08:36:08Z
[ "python", "enumerate", "data-cleaning" ]
type 'set''s difference between __str__ and printing directly
40,038,618
<pre><code>In [1]: import sys In [2]: sys.version_info Out[2]: sys.version_info(major=3, minor=5, micro=2, releaselevel='final', serial=0) In [3]: b=set([10,20,40,32,67,40,20,89,300,400,15]) In [4]: b Out[4]: {10, 11, 15, 20, 32, 40, 67, 89, 111, 300, 400} </code></pre> <pre><code>In [1]: import sys In [2]: sys....
1
2016-10-14T08:34:37Z
40,038,641
<p>Because the <code>{...}</code> syntax <a href="https://docs.python.org/2/whatsnew/2.7.html#python-3-1-features" rel="nofollow">wasn't introduced until Python 2.7</a>, and by that time the <code>set([...])</code> <code>repr()</code> format was already established.</p> <p>So to keep existing Python 2 code that may ha...
5
2016-10-14T08:35:57Z
[ "python", "python-3.x", "set", "python-2.x" ]
if-else sentence in one-line-python
40,038,799
<p>I have some code:</p> <pre><code>a_part = [2001, 12000] b_part = [1001, 2000] c_part = [11, 1000] d_part = [1, 10] data = range(1, 12000) labels = [a_part, b_part, c_part, d_part] sizes = [] # --- for part in labels: sum = 0 for each in data: sum += each if each &gt;= part[0] and each &lt;= part[1...
1
2016-10-14T08:43:58Z
40,038,870
<p>This is not the same syntax at all. The first one is a ternary operator (like (a ? b : c) in C). It wouldn't make any sense not to have the else clause here. The second one is a list comprehension and the purpose of the if clause is to filter the elements of the iterable.</p>
1
2016-10-14T08:47:30Z
[ "python" ]
if-else sentence in one-line-python
40,038,799
<p>I have some code:</p> <pre><code>a_part = [2001, 12000] b_part = [1001, 2000] c_part = [11, 1000] d_part = [1, 10] data = range(1, 12000) labels = [a_part, b_part, c_part, d_part] sizes = [] # --- for part in labels: sum = 0 for each in data: sum += each if each &gt;= part[0] and each &lt;= part[1...
1
2016-10-14T08:43:58Z
40,038,872
<p>You have two very different things here.</p> <p>In the first you have an expression, and are using a <a href="https://docs.python.org/3/reference/expressions.html#conditional-expressions" rel="nofollow"><em>conditional expression</em></a> to produce the value; that requires an <code>else</code> because an expressio...
4
2016-10-14T08:47:30Z
[ "python" ]
if-else sentence in one-line-python
40,038,799
<p>I have some code:</p> <pre><code>a_part = [2001, 12000] b_part = [1001, 2000] c_part = [11, 1000] d_part = [1, 10] data = range(1, 12000) labels = [a_part, b_part, c_part, d_part] sizes = [] # --- for part in labels: sum = 0 for each in data: sum += each if each &gt;= part[0] and each &lt;= part[1...
1
2016-10-14T08:43:58Z
40,038,898
<pre><code>x if y else z </code></pre> <p>This is an inline-if expression which returns a value. It must always return a value, it cannot not return a value, hence it must contain an <code>else</code> clause.</p> <pre><code>[x for x in y if z] </code></pre> <p>This is a list comprehension. The <code>if</code> here a...
1
2016-10-14T08:49:03Z
[ "python" ]
Loop with very large number (2 ^ 64) hangs, how to iterate faster?
40,038,810
<p>I'm using python 2.7 version. I have simple loop like below given</p> <pre><code>while i &lt; math.pow(2,64): do_something() i += 1000 </code></pre> <p>But this code runs too long. I have heard that python has scientific libraries for working with very large numbers like scipy, numpy, but i don't use them previ...
-1
2016-10-14T08:44:39Z
40,039,011
<p><strong>EDIT</strong>: corrected base conversion from 2 to 10 (thanks Nick A!)</p> <p>It's not clear what <code>do_something()</code> does, but I don't think this is a senseful approach. If you have to loop over <code>2^54</code> items it simply won't ever stop because it takes so long. Let's do some math.</p> <p>...
6
2016-10-14T08:55:43Z
[ "python", "numpy", "scipy", "largenumber" ]
Getting whole text of an td in Python (lxml)
40,038,814
<p>I'm trying to get the whole text that is contained in this td:</p> <p>Example:</p> <pre><code>&lt;td&gt; &lt;p&gt;Some Text&lt;/p&gt; &lt;a&gt;SAMPLE&lt;/a&gt; &lt;table&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt;something&lt;/td&gt; .... &lt;/tr&gt; ... &lt;/tbody&gt; &lt;/table&gt; ... &lt;...
0
2016-10-14T08:44:53Z
40,038,927
<p>If it is a website, you want BeautifulSoup! <a href="https://www.crummy.com/software/BeautifulSoup/" rel="nofollow">https://www.crummy.com/software/BeautifulSoup/</a></p> <p>Something like this: </p> <pre><code>import requests from bs4 import BeautifulSoup r = requests.get("Your_Link") soup = BeautifulSoup(r.con...
-1
2016-10-14T08:50:46Z
[ "python", "html", "xpath", "lxml" ]
Getting whole text of an td in Python (lxml)
40,038,814
<p>I'm trying to get the whole text that is contained in this td:</p> <p>Example:</p> <pre><code>&lt;td&gt; &lt;p&gt;Some Text&lt;/p&gt; &lt;a&gt;SAMPLE&lt;/a&gt; &lt;table&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt;something&lt;/td&gt; .... &lt;/tr&gt; ... &lt;/tbody&gt; &lt;/table&gt; ... &lt;...
0
2016-10-14T08:44:53Z
40,039,117
<p>Here I will Give you code.</p> <pre><code>from lxml import etree from lxml.html import tostring,fromstring import re TAG_RE = re.compile(r'&lt;[^&gt;]+&gt;') tree = etree.HTML(''' &lt;td&gt; &lt;p&gt;Some Text&lt;/p&gt; &lt;a&gt;SAMPLE&lt;/a&gt; &lt;table&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt;somet...
-1
2016-10-14T09:01:29Z
[ "python", "html", "xpath", "lxml" ]
Getting whole text of an td in Python (lxml)
40,038,814
<p>I'm trying to get the whole text that is contained in this td:</p> <p>Example:</p> <pre><code>&lt;td&gt; &lt;p&gt;Some Text&lt;/p&gt; &lt;a&gt;SAMPLE&lt;/a&gt; &lt;table&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt;something&lt;/td&gt; .... &lt;/tr&gt; ... &lt;/tbody&gt; &lt;/table&gt; ... &lt;...
0
2016-10-14T08:44:53Z
40,052,997
<p>You should be using <em>.xpath</em> not <em>findall</em>:</p> <pre><code>tr.xpath("//*[@id='Testcases__list']/table/tbody/tr/td//text()") </code></pre> <p>To just get the first td:</p> <pre><code> tr.xpath("(//*[@id='Testcases__list']/table/tbody/tr/td)[1]/text()") </code></pre> <p>I would also verify that the s...
1
2016-10-14T22:43:08Z
[ "python", "html", "xpath", "lxml" ]
Animate matshow function in matplotlib
40,039,112
<p>I have a matrix which is time-depedent and I want to plot the evolution as an Animation. </p> <p>My code is the following:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation n_frames = 3 #Numero de ficheros que hemos generado data = np.empty(n_frames...
1
2016-10-14T09:01:12Z
40,039,691
<p>You're very close to a working solution. Either change</p> <pre><code>plot = plt.matshow(data[0]) </code></pre> <p>to</p> <pre><code>plot = plt.matshow(data[0], fignum=0) </code></pre> <p>or use</p> <pre><code>plot = plt.imshow(data[0]) </code></pre> <p>instead.</p> <hr> <p>The problem with using <code>plt.m...
1
2016-10-14T09:29:02Z
[ "python", "animation", "matplotlib" ]
ASCII codec can't encode character u'\u2013'
40,039,212
<p>I have a little Python code in Q_GIS which opens objects. The problem I have is that in the directory there is a character (underscore like character) that can not be encoded. The error is:</p> <blockquote> <p>Traceback (most recent call last): File "", line 1, in UnicodeEncodeError: 'ascii' codec can't enco...
-1
2016-10-14T09:07:06Z
40,043,279
<p>please bear with my cellphones skills ;).</p> <p>There are different encoding that you can use for making python understand or decode strings. i.e. str("some awkward string",'UTF-16') should be able to decode what you need it to. </p> <p>To help you understand though, i would use an IDE ( i.e. pycharm) and run the...
-1
2016-10-14T12:33:30Z
[ "python", "unicode" ]
ASCII codec can't encode character u'\u2013'
40,039,212
<p>I have a little Python code in Q_GIS which opens objects. The problem I have is that in the directory there is a character (underscore like character) that can not be encoded. The error is:</p> <blockquote> <p>Traceback (most recent call last): File "", line 1, in UnicodeEncodeError: 'ascii' codec can't enco...
-1
2016-10-14T09:07:06Z
40,044,179
<p>I assume:</p> <ul> <li>you are using a Python2 version</li> <li><code>QgsProject.instance().fileName()</code> is a unicode string containing a EN-DASH (Unicode char U+2013: &#8211;) this looks like a normal dash (Unicode char U+2D: -) but does not exists in ASCII nor in any common 8bits character set.</li> </ul> <...
2
2016-10-14T13:17:33Z
[ "python", "unicode" ]
ASCII codec can't encode character u'\u2013'
40,039,212
<p>I have a little Python code in Q_GIS which opens objects. The problem I have is that in the directory there is a character (underscore like character) that can not be encoded. The error is:</p> <blockquote> <p>Traceback (most recent call last): File "", line 1, in UnicodeEncodeError: 'ascii' codec can't enco...
-1
2016-10-14T09:07:06Z
40,074,519
<p>Thanks for the answers,</p> <p>I have found the answer in replacing str with unicode in the python code, see the code below.</p> <p>from os import startfile; proj = QgsProject.instance();UriFile = unicode(proj.fileName()); img = '[% "pad" %]'; Path = unicode(os.path.dirname(UriFile)); startfile(Path+img)</p>
0
2016-10-16T19:28:44Z
[ "python", "unicode" ]
No such option, click version 6.6
40,039,243
<p>Using <a href="http://click.pocoo.org/5/" rel="nofollow">http://click.pocoo.org/5/</a></p> <p>I have this command defined, however, when I run the command, the option missing is passed through correctly (I can see the value), but I get <code>Error: no such option: --missing</code> in the terminal and the command fa...
1
2016-10-14T09:08:26Z
40,082,322
<p>I found the issue. Was nothing much to do with pocoo click. It was because the <code>get_missing_records()</code> function is actually another CLI command. The <code>missing</code> parameter is subsequently passed through to this function as well, and the <code>get_missing_records()</code> method obviously knows not...
0
2016-10-17T09:04:58Z
[ "python", "click", "command-line-interface" ]
Games console troubleshoot code using tkinter python
40,039,322
<p>I need to create a games console troubleshoot using tkinter but I have no idea where to start! Can you recommend what code to use or any good tutorial websites?</p>
-2
2016-10-14T09:12:06Z
40,053,775
<p>Some good tutorials include:</p> <p><a href="https://www.tutorialspoint.com/python3/python_gui_programming.htm" rel="nofollow">https://www.tutorialspoint.com/python3/python_gui_programming.htm</a></p> <p><a href="http://www.python-course.eu/python_tkinter.php" rel="nofollow">http://www.python-course.eu/python_tkin...
0
2016-10-15T00:28:44Z
[ "python", "tkinter" ]
I need to help at for or while loops
40,039,357
<p>Create a scripts which will print the following, using for or while loops:</p> <pre><code> # # ## ## ### ### #### #### ##### ##### ###### ###### ####### ####### ######## ######## ######## ######## ####### ####### ###### ###### ##### ##...
-3
2016-10-14T09:13:50Z
40,039,463
<p>You should understand what a loop do.</p> <ul> <li><strong>For</strong> : You can repeat similar action X times</li> <li><strong>While</strong> : You can repeat similar action until a condition is verified.</li> </ul> <p>If you want your exercise to works, then you only want to run a loop X times, and then run ano...
1
2016-10-14T09:18:59Z
[ "python" ]
How to change date in pandas dataframe
40,039,457
<p>I have dataframe like below</p> <pre><code> day 0 2016-07-12 1 2016-08-13 2 2016-09-14 3 2016-10-15 4 2016-11-01 dtype:datetime64 </code></pre> <p>I would like to change the day like below</p> <pre><code> day 0 2016-07-01 1 2016-08-01 2 2016-09-01 3 2016-10-01 4 2016-11-01 </code></pre> <p>I t...
1
2016-10-14T09:18:26Z
40,039,602
<p>You can use <code>numpy</code>, first convert to <code>numpy array</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.values.html" rel="nofollow"><code>values</code></a> and then convert to <code>datetime64[M]</code> by <a href="http://docs.scipy.org/doc/numpy/reference/generated/...
2
2016-10-14T09:25:16Z
[ "python", "pandas" ]
Python return value
40,039,504
<p>I have a global variable <code>global_a</code> and the function to determine the value</p> <pre><code># long Syntax def assignement_a(): global_a = len(xyz) return global_a </code></pre> <p>The point is to return the value to caller and simultaneously assign the value to the global to saved for further use, so...
-1
2016-10-14T09:21:09Z
40,039,721
<p>You can change the global variable from the caller function or statement for ex:</p> <pre><code>global_a=0 var1=0 xyz="stackoverflow" def assignement_a(): return len(xyz) def test(): global global_a global var1 var1=global_a=assignement_a() print(var1) test() print(var1) print(global_a) </code></pre> <p...
0
2016-10-14T09:30:43Z
[ "python", "function", "return-value" ]
Python return value
40,039,504
<p>I have a global variable <code>global_a</code> and the function to determine the value</p> <pre><code># long Syntax def assignement_a(): global_a = len(xyz) return global_a </code></pre> <p>The point is to return the value to caller and simultaneously assign the value to the global to saved for further use, so...
-1
2016-10-14T09:21:09Z
40,039,872
<p>Just for the record, the correct version of "long syntax" is:</p> <pre><code>def assignement_a(): global global_a global_a = len(xyz) return global_a </code></pre> <p>As for the "short syntax" I don't see why it would be necessary here. Maybe it can be made shorter using a lambda, but that might just obscure...
1
2016-10-14T09:37:01Z
[ "python", "function", "return-value" ]
string.format() stops working correctly in my script
40,039,516
<p>I have this format string:</p> <pre><code>print "{u: &lt;16} {l: &gt;16} {lse: &lt;19} {active: &lt;12}".format(...) </code></pre> <p>which works fine in the Python console, but when run in my program, it prints <code>&lt;19</code> (literally) for the <code>lse</code> part. When I remove the <code>&lt;19</code>...
2
2016-10-14T09:21:29Z
40,039,924
<p>Apparently, a <code>datetime</code> object does not abide by the format specifier rules. When cast to a <code>str</code>, it works:</p> <pre><code>print "{d: &lt;12}".format(str(datetime.datetime.now())) </code></pre>
1
2016-10-14T09:39:53Z
[ "python", "format" ]
Pandas Delete rows from dataframe based on condition
40,039,531
<p>Consider this code:</p> <pre><code>from StringIO import StringIO import pandas as pd txt = """a, RR 10, 1asas 20, 1asasas 30, 40, asas 50, ayty 60, 2asas 80, 3asas""" frame = pd.read_csv(StringIO(txt), skipinitialspace=True) print frame,"\n\n\n" l=[] for i,j in frame[~ frame['RR'].str.startswith("1", na=True)]['...
2
2016-10-14T09:22:13Z
40,045,991
<p><strong>First</strong>, keep all strings starting with <code>1</code> or <code>nan</code>:</p> <pre><code>keep = frame['RR'].str.startswith("1", na=True) keep1 = keep[keep] # will be used at the end </code></pre> <p><strong>Second</strong>, keep strings starting with <code>2</code> or <code>3</code> that are not ...
1
2016-10-14T14:45:10Z
[ "python", "python-2.7", "pandas" ]
Pylatex error when generate PDF file - No such file or directory
40,039,763
<p>I just want to use Pylatex to generate the pdf file. I look at the basic example and re-run the script but it raised the error: OSError: [Errno 2] No such file or directory.</p> <p>Here is my script:</p> <pre><code>import sys from pylatex import Document, Section, Subsection, Command from pylatex.utils import ital...
0
2016-10-14T09:32:36Z
40,140,312
<p>Based on the code around the error, you're probably missing a latex compiler:</p> <pre><code>compilers = ( ('latexmk', latexmk_args), ('pdflatex', []) ) </code></pre> <p>Try doing this:</p> <pre><code>apt-get install latexmk </code></pre>
0
2016-10-19T19:49:02Z
[ "python", "nosuchfileexception" ]
Pandas + HDF5 Panel data storage for large data
40,039,776
<p>As part of my research, I am searching a good storing design for my panel data. I am using pandas for all in-memory operations. I've had a look at the following two questions/contributions, <a href="http://stackoverflow.com/questions/14262433/large-data-work-flows-using-pandas">Large Data Work flows using Pandas</a>...
1
2016-10-14T09:33:03Z
40,041,761
<p>It's bit difficult to answer those questions without particular examples...</p> <blockquote> <p>Updating HDFTable, I suppose I have to delete the entire table in order to update a single column?</p> </blockquote> <p>AFAIK yes unless you are storing single columns separately, but it will be done automatically, ...
1
2016-10-14T11:12:45Z
[ "python", "database", "pandas", "hdf5" ]
Python Ternary Rescursion
40,039,958
<p>I'm creating two functions one, that returns the ternary representation for a base 10 number, and one that returns the base 10 representation for a ternary number using recursion. For example 52 would return 1221. Right now, I have this down, but I'm not sure how to make it. I'm mostly confused with the aspect of th...
-1
2016-10-14T09:41:25Z
40,040,245
<p>You were nearly there with your code. This should do the trick, according to <a href="http://stackoverflow.com/questions/2088201/integer-to-base-x-system-using-recursion-in-python">this question</a>.</p> <p>However, you will have to do the search for "0" outside this function: as it was done in your code, the "0" d...
0
2016-10-14T09:54:56Z
[ "python", "recursion", "ternary" ]
Python Ternary Rescursion
40,039,958
<p>I'm creating two functions one, that returns the ternary representation for a base 10 number, and one that returns the base 10 representation for a ternary number using recursion. For example 52 would return 1221. Right now, I have this down, but I'm not sure how to make it. I'm mostly confused with the aspect of th...
-1
2016-10-14T09:41:25Z
40,040,835
<p>So the big idea with all base change is the following:</p> <p>You take a <code>number n</code> written in <code>base b</code> as this 123. That means <code>n</code> in <code>base 10</code> is equal to <code>1*b² + 2*b + 3</code> . So convertion from <code>base b</code> to <code>base 10</code> is straigtforward: yo...
0
2016-10-14T10:22:50Z
[ "python", "recursion", "ternary" ]
Python using logging module than print
40,040,129
<p>I want to use a logging module to replace the <code>print()</code>, Would appreciate some suggestions on how o get this done.</p> <p><strong>Code in Context</strong></p> <pre><code>from bs4 import BeautifulSoup, Tag import requests from pprint import pprint import sys import logging from logging.config import file...
-2
2016-10-14T09:49:28Z
40,045,723
<p>What you want to achieve is still not quite clear to me - specially, why you want to use a logger here. It looks like your script's goal is to output the jobs listing ? If yes, printing it to stdout was probably the RightThing(tm) to do. </p> <p>As a general rule: for a command line application, stdout is for norma...
0
2016-10-14T14:32:32Z
[ "python", "logging", "beautifulsoup", "python-requests" ]
How to use different env for different projects?
40,040,221
<p>I have two projects running on a server. I'm storing AWS_SECRET in env.</p> <p>I set those env in my ~/.bash_profile. How do I make sure that one project gets the correct key? Can I set env only on project scope?</p> <p>Thanks.</p>
0
2016-10-14T09:53:44Z
40,040,370
<p>On thing you can do is set the environment variables on runtime.</p> <p>Example:</p> <pre><code>$ AWS_SECRET="Secret1" run_server1 arg1 arg2 arg3 $ AWS_SECRET="Secret2" run_server2 arg1 arg2 arg3 </code></pre>
0
2016-10-14T10:00:17Z
[ "python", "unix" ]
How to use different env for different projects?
40,040,221
<p>I have two projects running on a server. I'm storing AWS_SECRET in env.</p> <p>I set those env in my ~/.bash_profile. How do I make sure that one project gets the correct key? Can I set env only on project scope?</p> <p>Thanks.</p>
0
2016-10-14T09:53:44Z
40,040,467
<p><a href="https://github.com/kennethreitz/autoenv" rel="nofollow">Autoenv</a> is built for this for this exact purpose:</p> <pre><code>pip install autoenv echo 'AWS_SECRET="Secret1"' &gt; ./project1/.env echo 'AWS_SECRET="Secret2"' &gt; ./project2/.env </code></pre>
0
2016-10-14T10:06:11Z
[ "python", "unix" ]
How to use different env for different projects?
40,040,221
<p>I have two projects running on a server. I'm storing AWS_SECRET in env.</p> <p>I set those env in my ~/.bash_profile. How do I make sure that one project gets the correct key? Can I set env only on project scope?</p> <p>Thanks.</p>
0
2016-10-14T09:53:44Z
40,040,661
<p>For the AWS CLI (<code>aws</code>) specifically, you can use "<a href="http://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html#cli-multiple-profiles" rel="nofollow">profiles</a>", which you can select with the <code>--profile</code> argument. For example, in your <code>~/.aws/credentials</code>...
1
2016-10-14T10:15:11Z
[ "python", "unix" ]
Creating Weighted Directed Graph in Python based on User Input
40,040,304
<p>I need to create something like this to represent a directed weighted graph based on user input - </p> <pre><code>graph = { 'a': {'b': 1, 'c': 4}, 'b': {'c': 3, 'd': 2, 'e': 2}, 'c': {}, 'd': {'b': 1, 'c': 5}, 'e': {'d': -2} } </code></pre> <p>So far,...
0
2016-10-14T09:57:29Z
40,042,334
<p>Do you have an indentation error?</p> <p>Instead of </p> <pre><code>for i in graph: print(i) for j in graph[i]: var = input() graph[i][j] = var </code></pre> <p>You maybe intended to write</p> <pre><code>for i in graph: print(i) for j in graph[i]: var = input() graph[i][j] = v...
0
2016-10-14T11:42:15Z
[ "python", "python-3.x", "dictionary", "graph-theory" ]
Creating Weighted Directed Graph in Python based on User Input
40,040,304
<p>I need to create something like this to represent a directed weighted graph based on user input - </p> <pre><code>graph = { 'a': {'b': 1, 'c': 4}, 'b': {'c': 3, 'd': 2, 'e': 2}, 'c': {}, 'd': {'b': 1, 'c': 5}, 'e': {'d': -2} } </code></pre> <p>So far,...
0
2016-10-14T09:57:29Z
40,043,068
<pre><code>for i in graph: graph[i] = edges </code></pre> <p>You're assigning the same dict (<code>edges</code>) to each key of <code>graph</code>. Therefore, when you assign a value to any of them, you're assigning that value to <em>all</em> of them. It looks like what you actually want is <em>copies</em> of <cod...
1
2016-10-14T12:23:20Z
[ "python", "python-3.x", "dictionary", "graph-theory" ]
Pip module installation issue
40,040,356
<p>I'm having difficulty installing modules using pip for python. The exact error message is:</p> <pre><code>Could not find a version that satisfies the requirement shapefile (from versions: DistributionNotFound: No matching distribution found for shapefile </code></pre> <p>When I type:</p> <pre><code>pip install -v...
0
2016-10-14T09:59:53Z
40,040,415
<p>Here is a list that matches your module name: <a href="https://pypi.python.org/pypi?%3Aaction=search&amp;term=shapefile&amp;submit=search" rel="nofollow">PyPI search result for shapefile</a></p> <p>Maybe the module is called <code>pyshapefile</code> not just <code>shapefile</code>.</p> <pre><code>pip install pysha...
2
2016-10-14T10:02:34Z
[ "python", "pip" ]
get row and column names of n maximum values in dataframe
40,040,364
<p>For the dataframe </p> <pre><code>import pandas as pd df=pd.DataFrame({'col1':[1,2],'col2':[4,5]},index=['row1','row2']) print df col1 col2 row1 1 4 row2 2 5 </code></pre> <p>I want to get the row name and the col name of the 2 maximum values and the according maximum values, such that the r...
1
2016-10-14T10:00:08Z
40,040,613
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.stack.html" rel="nofollow"><code>stack</code></a> for creating <code>Series</code>, then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.nlargest.html" rel="nofollow"><code>Series.nlargest</code><...
1
2016-10-14T10:12:50Z
[ "python", "pandas" ]
Print elements of ndarray in their storage order
40,040,379
<p>To check whether my assumptions on memory layout are correct, I'd sometimes like to print elements of an <code>ndarray</code> exactly in the storage order in memory.</p> <p>I know <code>flatten</code>, <code>ravel</code>, <code>flat</code>, <code>flatiter</code> but I'm still not sure which function will <strong>tr...
0
2016-10-14T10:00:54Z
40,046,499
<p>Probably <code>ravel</code> will suit your needs, if you use the <code>order='K'</code> option. From the <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.ravel.html" rel="nofollow">docs</a>:</p> <blockquote> <p>order : {‘C’,’F’, ‘A’, ‘K’}, optional</p> <p>[...] ‘Kâ€...
3
2016-10-14T15:10:44Z
[ "python", "numpy" ]
How to send messages with Elixir porcelain to a python script?
40,040,417
<p>I'm trying to learn how to do interop from Elixir with the <a href="https://github.com/alco/porcelain" rel="nofollow" title="porcelain module">porcelain module</a>.</p> <p>So I made this simple example:</p> <p>I have an Elixir function that looks like this:</p> <pre><code>defmodule PythonMessenger do alias Porc...
0
2016-10-14T10:02:54Z
40,040,746
<p>You need to pass <code>-u</code> to disable buffering in <code>sys.stdin.readline()</code>. You won't see this when running the program interactively, but you will see it when the program is spawned without a TTY. Because of the default buffering, the Python process was not printing anything for a short message like...
2
2016-10-14T10:18:34Z
[ "python", "elixir" ]
Can sentences be formed AFTER raw text is converted into nltk.Text?
40,040,423
<p>Usual way of converting file data into nltk.Text seems as follows:</p> <pre><code>f=open('my-file.txt','rU') raw=f.read() tokens = nltk.word_tokenize(raw) text = nltk.Text(tokens) </code></pre> <p>Now, 'text' (the nltk.Text object) is just a list of words. How can I get a list of sentences from it? Basically wish...
0
2016-10-14T10:03:07Z
40,041,123
<p>you can use the 'sent_tokenize()' and 'line_tokenize()' methods on the raw text (depends if you want to split lines (\n), sentences (by '.', '?', etc) or both):</p> <pre><code>f=open('my-file.txt','rU') raw=f.read() # tokenize lines first and then by sentence markers sents = [nltk.tokenize.sent_tokenize(l) for l in...
0
2016-10-14T10:37:10Z
[ "python", "nltk" ]
Scraping Pantip Forum using BeautifulSoup
40,040,427
<p>I'm trying to scrape some forum posts from <a href="http://pantip.com/tag/Isuzu" rel="nofollow">http://pantip.com/tag/Isuzu</a></p> <p>One such page is <a href="http://pantip.com/topic/35647305" rel="nofollow">http://pantip.com/topic/35647305</a></p> <p>I want to get each post text along with its author and timest...
1
2016-10-14T10:03:25Z
40,044,738
<p>The comments are rendered using an Ajax request:</p> <pre><code>import requests from bs4 import BeautifulSoup params = {"tid": "35647305", # in the url "type": "3"} with requests.Session() as s: s.headers.update({"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Geck...
0
2016-10-14T13:44:13Z
[ "python", "html", "web-scraping", "beautifulsoup" ]
Using Python to create a (random) sample of n words from text files
40,040,453
<p>For my PhD project I am evaluating all existing Named Entity Recogition Taggers for Dutch. In order to check the precision and recall for those taggers I want to manually annotate all Named Entities in a random sample from my corpus. That manually annotated sample will function as the 'gold standard' to which I will...
3
2016-10-14T10:05:02Z
40,040,701
<p>You just have to split your lines into words, store them somewhere, and then, after having read all of your files and stored their words, pick 100 with <code>random.sample</code>. It it what I did in the code below. However, I am not quite sure if it is able to deal with 170 novels, since it will likely result in a ...
2
2016-10-14T10:16:40Z
[ "python", "text", "random", "nlp", "named-entity-recognition" ]
Using Python to create a (random) sample of n words from text files
40,040,453
<p>For my PhD project I am evaluating all existing Named Entity Recogition Taggers for Dutch. In order to check the precision and recall for those taggers I want to manually annotate all Named Entities in a random sample from my corpus. That manually annotated sample will function as the 'gold standard' to which I will...
3
2016-10-14T10:05:02Z
40,040,763
<p>A few suggestions:</p> <p>Take random sentences, not words or lines. NE taggers will work much better if input is grammatical sentences. So you need to use a sentence splitter.</p> <p>When you iterate over the files, <code>random_sample_input</code> contains lines from only the last file. You should move the block...
3
2016-10-14T10:19:26Z
[ "python", "text", "random", "nlp", "named-entity-recognition" ]
Using Python to create a (random) sample of n words from text files
40,040,453
<p>For my PhD project I am evaluating all existing Named Entity Recogition Taggers for Dutch. In order to check the precision and recall for those taggers I want to manually annotate all Named Entities in a random sample from my corpus. That manually annotated sample will function as the 'gold standard' to which I will...
3
2016-10-14T10:05:02Z
40,040,953
<p>This solves both problems:</p> <pre><code>import random import os import glob import sys import errno path = '/Users/roelsmeets/Desktop/libris_corpus_clean/*.txt' files = glob.glob(path) with open("randomsample", "w", encoding='utf-8') as random_sample_output: for text in files: try: with ...
1
2016-10-14T10:28:43Z
[ "python", "text", "random", "nlp", "named-entity-recognition" ]
Error while Adding buttons dynamically to Screen in ScreenManager Kivy
40,040,526
<p>I am trying to add buttons dynamicaly to screen. I have the following error when I run the app. Please help me resolve the issue.</p> <blockquote> <p>Traceback (most recent call last): File "main.py", line 174, in screenManager.add_widget( HomeScreen( name = 'homeScreen' ) ) File "main.py", line 1...
0
2016-10-14T10:08:56Z
40,053,198
<p>Let's start with <code>__init__</code>:</p> <pre><code>class HomeScreen(Screen): def __init__(self, **kwargs): for i in range(80): btn = Button(text=str(i), size=(90, 90), size_hint=(None, None)) self.add_widget(btn) </code></pre> <p>although this looks fine and is called when ...
0
2016-10-14T23:04:43Z
[ "python", "kivy" ]
Automating file upload using Selenium and pywinauto
40,040,564
<p>I am trying to automate a file uplad in a form. The form works as follows: - some data insert - click on add attachment button - windows dialogue window appears - select the file - open it</p> <p><strong>I am using python, Selenium webdriver and pywinauto module.</strong></p> <p>Similar approach was described <a h...
3
2016-10-14T10:10:34Z
40,041,063
<p>Try following code and let me know in case of any issues:</p> <pre><code>WebDriverWait(self.driver, 10).until(EC.element_to_be_clickable((By.XPATH, '//input[@type="file"][@name="qqfile"]'))).send_keys("/path/to/Gandalf.jpg") </code></pre> <p>P.S. You should replace string <code>"/path/to/Gandalf.jpg"</code> with a...
2
2016-10-14T10:34:10Z
[ "python", "selenium", "file-upload", "selenium-webdriver", "pywinauto" ]
Probabilities are ignored in numpy
40,040,569
<p>I'm trying to use the numpy library to sample a character from a distribution, but it seems to ignore the probabilities I give in input. I have a probability array, which just to test I set to </p> <pre><code>vec_p=[0,0,1,0,0] </code></pre> <p>and a character array </p> <pre><code>vec_c=[a,b,c,d,e] </code></pre>...
1
2016-10-14T10:10:50Z
40,040,671
<p>Passing the parameters as keyword arguments gives the correct results:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; vec_p = [0,0,1,0,0] &gt;&gt;&gt; num = np.arange(5) &gt;&gt;&gt; np.random.choice(num, size=10, p=vec_p) array([2, 2, 2, 2, 2, 2, 2, 2, 2, 2]) </code></pre>
2
2016-10-14T10:15:30Z
[ "python", "arrays", "numpy" ]
I am deploying Django App on heroku, after successful deployment , I am getting operational Error
40,040,670
<pre><code>OperationalError at /admin/login/ could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"? Request Method: POST Django Version: 1.10b1 Exception Type: OperationalError Exception Value: ...
-1
2016-10-14T10:15:27Z
40,044,438
<p>There is a problem in your database settings. You have to modify database settings to be able to deploy to Heroku. I have never used it, but this page explains how to configure database for Django: <a href="https://devcenter.heroku.com/articles/django-app-configuration" rel="nofollow">https://devcenter.heroku.com/ar...
1
2016-10-14T13:30:43Z
[ "python", "django", "python-2.7", "heroku" ]
set_cookie() missing 1 required positional argument: 'self'
40,040,726
<p>In Django, Im trying to render a template and send a cookie at the same time with this code:</p> <pre><code>template = loader.get_template('list.html') context = {'documents': documents, 'form': form} if ('user') not in request.COOKIES: id_user = ''.join(random.SystemRandom().choice(string.ascii_uppercase + s...
1
2016-10-14T10:17:42Z
40,040,791
<p>Close - HttpResponse is the class, not the instance of the class. The last line is creating one and returning it - so your earlier line needs to act on that instance...</p> <p>try (untested code):</p> <pre><code>myResponse = HttpResponse(template.render(context, request)) myResponse.set_cookie(...) return myRespon...
3
2016-10-14T10:20:39Z
[ "python", "django", "httpcookie" ]
Manual progress bar python
40,040,908
<p>Im trying to make a code so that it displays all numbers from 1 to 100 to show as its loading something.</p> <pre><code>for i in range(101): self.new = Label(self.label_progress, text=i) time.sleep(1) self.new.place(in_= self.label_progress) if i == 100: self.new1=Label(s...
0
2016-10-14T10:26:20Z
40,041,597
<p><code>tkinter</code> has <code>mainloop()</code> which runs all the time and does many thing - ie. it updates data in widget, redraws widgets, executes your function. When <code>mainloop()</code> executes your function then it can't updates/redraws widgets till your function stop running. You can use <code>root.upda...
2
2016-10-14T11:03:13Z
[ "python", "loops", "tkinter" ]
A class instance initializing with previously inititalized attributes
40,040,915
<p>I have a slight complication with my code. I want the pirate attribute to take the value True if the other two attributes are higher than some number when summed up and multiplied by some factor.</p> <p>For instance, maybe I want the pirate attribute to be True only if social*0.6 + fixed is greater than 5, and fals...
0
2016-10-14T10:26:38Z
40,041,005
<p>You need to store the random values for <code>fixed</code> and <code>social</code> and then use them for the comparison that generates <code>pirate</code>:</p> <pre><code>for x in range(1,people): fixed = random.uniform(0,10) social = random.uniform(0,10) pirate = (social * 0.6 + fixed) &gt; 5 # bool...
0
2016-10-14T10:31:24Z
[ "python" ]
A class instance initializing with previously inititalized attributes
40,040,915
<p>I have a slight complication with my code. I want the pirate attribute to take the value True if the other two attributes are higher than some number when summed up and multiplied by some factor.</p> <p>For instance, maybe I want the pirate attribute to be True only if social*0.6 + fixed is greater than 5, and fals...
0
2016-10-14T10:26:38Z
40,041,204
<p>In response to Moses answer: Using a calculated property is safer than calculating the pirate value at initialization only. When decorating a method with the @property attribute, it acts as a property (you don't have to use brackets as is the case for methods), which is always up to date when the social member is ch...
1
2016-10-14T10:41:30Z
[ "python" ]
python script is not running without sudo - why?
40,040,961
<p>This is my python script which downloads the most recent image from my S3 bucket. When I run this script using <code>sudo python script.py</code> it does as expected, but not when I run it as <code>python script.py</code>. In this case, the script finishes cleanly without exceptions or process lockup, but there is ...
0
2016-10-14T10:29:17Z
40,041,548
<p>Presumably the problem is that you try to store things somewhere your user doesn't have permission to. The second issue is that your script is hiding the error. The <code>except</code> block completely ignores what sort of exceptions occur (and of course consumes them so you never see them), and uses <code>logging.i...
1
2016-10-14T10:59:57Z
[ "python", "boto", "sudo" ]
python script is not running without sudo - why?
40,040,961
<p>This is my python script which downloads the most recent image from my S3 bucket. When I run this script using <code>sudo python script.py</code> it does as expected, but not when I run it as <code>python script.py</code>. In this case, the script finishes cleanly without exceptions or process lockup, but there is ...
0
2016-10-14T10:29:17Z
40,043,253
<p>Always install <a href="https://virtualenv.pypa.io/en/stable/" rel="nofollow">virtual environment</a> before you start development in python. </p> <p>The issue you face is typical python newbie problem : use <code>sudo</code> to install all the pypi package. </p> <p>When you do <code>sudo pip install boto3</code>,...
0
2016-10-14T12:32:18Z
[ "python", "boto", "sudo" ]
python script is not running without sudo - why?
40,040,961
<p>This is my python script which downloads the most recent image from my S3 bucket. When I run this script using <code>sudo python script.py</code> it does as expected, but not when I run it as <code>python script.py</code>. In this case, the script finishes cleanly without exceptions or process lockup, but there is ...
0
2016-10-14T10:29:17Z
40,044,137
<p>As @Nearoo in comments had suggested to use <code>except Exception as inst</code> to catch exceptions. </p> <p>catching the exception like this </p> <pre><code>except Exception as inst: print(type(inst)) print(inst.args) print(inst) </code></pre> <p>Should fetch you this error ...
1
2016-10-14T13:15:21Z
[ "python", "boto", "sudo" ]
How to find instances that DONT have a tag using Boto3
40,040,985
<p>I'm trying to find instances that DONT have a certain tag.</p> <p>For instance I want all instances that don't have the Foo tag. I also want instances that don't have the Foo value equal to Bar.</p> <p>This is what I'm doing now:</p> <pre><code>import boto3 def aws_get_instances_by_name(name): """Get EC2 in...
1
2016-10-14T10:30:22Z
40,054,287
<p>Here's some code that will display the <code>instance_id</code> for instances <strong>without</strong> a particular tag:</p> <pre><code>import boto3 instances = [i for i in boto3.resource('ec2', region_name='ap-southeast-2').instances.all()] # Print instance_id of instances that do not have a Tag of Key='Foo' for...
0
2016-10-15T02:17:20Z
[ "python", "amazon-ec2", "boto3" ]
Optimize Python code. Optimize Pandas apply. Numba slow than pure python
40,041,076
<p>I'm facing a huge bottleneck where I apply a method() to each row in Pandas DataFrame. The execution time is in sorts of 15-20 minutes.</p> <p>Now, the code I use is as follows:</p> <pre><code>def FillTarget(self, df): backup = df.copy() target = list(set(df['ACTL_CNTRS_BY_DAY'])) df = df[~df['ACTL_CN...
0
2016-10-14T10:34:57Z
40,045,544
<p>This is a bit rushed solution because I'm about to leave into the weekend now, but it works.</p> <p>Input Dataframe:</p> <pre><code>index APPT_SCHD_ARVL_D ACTL_CNTRS_BY_DAY 919 2020-11-17 NaN 917 2020-11-17 NaN 916 2020-11-17 NaN 915 2020-11-...
1
2016-10-14T14:24:01Z
[ "python", "pandas", "optimization", "jit", "numba" ]
How to fastly build a graph with Numpy?
40,041,205
<p>In order to use PyStruct to perform image segmentation (by means of inference [1]), I first need to build a graph whose nodes correspond to pixels and edges are the link between these pixels.</p> <p>I have thus written a function, which works, to do so:</p> <pre><code> def create_graph_for_pystruct(mrf, betas, ...
0
2016-10-14T10:41:30Z
40,052,094
<p>Here is a code suggestion that should run much faster (in numpy one should focus on using vectorisation against for-loops). I try to build the whole output in a single pass using vectorisation, I used the helpfull <code>np.ogrid</code> to generate xy coordinates.</p> <pre><code>def new(mrf, betas, nb_labels): M...
1
2016-10-14T21:14:18Z
[ "python", "numpy" ]
creating a csv file from a function result, python
40,041,267
<p>I am using this pdf to csv function from {<a href="http://stackoverflow.com/questions/25665/python-module-for-converting-pdf-to-text">Python module for converting PDF to text</a>} and I was wondering how can I now export the result to a csv file on my drive? I tried adding in the function </p> <pre><code>with open(...
1
2016-10-14T10:45:00Z
40,041,972
<p>If you are printing a single character per row, then what you have is a string. Your loop</p> <pre><code>for row in data: </code></pre> <p>translates to</p> <pre><code>for character in string: </code></pre> <p>so you need to break your string up into the chunks you want written on a single row. You might be ab...
1
2016-10-14T11:22:41Z
[ "python", "csv", "pdf" ]
Convert custom strings to datetime format
40,041,398
<p>I have a list of date-time data strings that looks like this:</p> <pre><code>list = ["2016-08-02T09:20:32.456Z", "2016-07-03T09:22:35.129Z"] </code></pre> <p>I want to convert this to the example format (for the first item):</p> <pre><code>"8/2/2016 9:20:32 AM" </code></pre> <p>I tried this:</p> <pre><code>from...
0
2016-10-14T10:52:20Z
40,041,552
<pre><code>s = "2016-08-02T09:20:32.456Z" d = datetime.strptime(s, "%Y-%m-%dT%H:%M:%S.%fZ") </code></pre> <p>The use <code>d.strftime</code> (<a href="https://docs.python.org/3.0/library/datetime.html#id1" rel="nofollow">https://docs.python.org/3.0/library/datetime.html#id1</a>).</p>
1
2016-10-14T11:00:05Z
[ "python", "date", "converter" ]
Convert custom strings to datetime format
40,041,398
<p>I have a list of date-time data strings that looks like this:</p> <pre><code>list = ["2016-08-02T09:20:32.456Z", "2016-07-03T09:22:35.129Z"] </code></pre> <p>I want to convert this to the example format (for the first item):</p> <pre><code>"8/2/2016 9:20:32 AM" </code></pre> <p>I tried this:</p> <pre><code>from...
0
2016-10-14T10:52:20Z
40,041,720
<p>You have several problems in you code:</p> <ul> <li><code>%R</code>doesn't seem to be a <a href="https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior" rel="nofollow">correct directive</a> (that's your error, I think you are looking for <code>%p</code>).</li> <li>the format in strptime is t...
1
2016-10-14T11:10:23Z
[ "python", "date", "converter" ]
XML Processing not working
40,041,410
<p>I am trying to extract data from a sensor (it communicate with "xml type" strings) and convert it to csv. With my actual code i already write xml files, but the data come in single rows (from root to /root it is).</p> <p>Dunno if this is the reason but i get a <strong>elementtree.parse error junk after document ele...
1
2016-10-14T10:52:37Z
40,045,479
<p>You should open your input file by 'read' instead of 'write'. Or you will empty your file when you run your code.</p> <pre><code>fp_xml = open(file_xml, 'r'); </code></pre> <p>Besides, I have a better way to get all elements.You don't need to know what the names of all tags ahead of time.</p> <pre><code>header ...
0
2016-10-14T14:19:36Z
[ "python", "xml", "csv" ]
How to stop or interrupt a function in python 3 with Tkinter
40,041,440
<p>I started with programming in python just a few months ago and I really love it. It's so intuitive and fun to start with.</p> <p>Data for starting point: I have a linux mashine on which runs python 3.2.3 I have three buttons on GUI to start a function with and one to stop that proccess or the proccesses (Idea).</p>...
0
2016-10-14T10:54:34Z
40,046,134
<p>Use <code>threading.Event</code></p> <pre><code>import threading class ButtonHandler(threading.Thread): def __init__(self, event): threading.Thread.__init__(self) self.event = event def run (self): while not self.event.is_set(): print("Button 1 is pressed!") t...
0
2016-10-14T14:52:35Z
[ "python", "tkinter" ]
How to import only in parts of the code? [Python]
40,041,469
<p>I use webbrowser only in one part of my code, and it seems waste to import it since the beginning of the script, is it a way to import it only at the part of the code I need to use it? Thanks!</p>
0
2016-10-14T10:55:52Z
40,041,543
<p>Yes. You move the import statement from the top of the script to the point in your script where you want it. For example, you would move the below line from the top of your script to somewhere in the code.</p> <pre><code>import your_library </code></pre> <p>Be warned though, if the import is in a function, every t...
0
2016-10-14T10:59:35Z
[ "python", "performance", "python-2.7", "libraries" ]
Python multiple search based on enabled or not
40,041,477
<p>Everyone, hello!</p> <p>I'm currently trying to find several strings of text in telnet, from the Telnetlib (<a href="https://docs.python.org/2/library/telnetlib.html" rel="nofollow">https://docs.python.org/2/library/telnetlib.html</a>) in Python 2.7.</p> <p>So far, the snippet I'm using that works great is:</p> <...
0
2016-10-14T10:56:07Z
40,042,559
<p>You can build a list based on the config:</p> <pre><code>strings = [] if string1_enable == "yes": strings.append(string1) if string2_enable == "yes": strings.append(string2) if string3_enable == "yes": strings.append(string3) while True: r = tn.read_some() if any(x in r for x in strings): ...
1
2016-10-14T11:54:13Z
[ "python", "if-statement" ]
Python C extension: Extract parameter from the engine
40,041,498
<p>I would like to use Python to perform Mathematics tests on my functions. A typical program that can gain access to Python is this:</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; #include &lt;Python.h&gt; int RunTests() { Py_Initialize(); PyRun_SimpleString("a=5"); PyRun_SimpleString("...
0
2016-10-14T10:57:06Z
40,041,694
<p><code>PyRun_SimpleString()</code> executes the code in the context of the <code>__main__</code> module. You can retrieve a reference to this module using <code>PyImport_AddModule()</code>, get the globals dictionary from this module and lookup variables:</p> <pre><code>PyObject *main = PyImport_AddModule("__main__"...
0
2016-10-14T11:09:14Z
[ "python", "c++", "c", "python-c-extension" ]
Python Dictionarys
40,041,542
<p>I am stucked with a school project. The following function should set the name of a room in a given dictionary.The rooms dicionary should stay because functions using it.It should randomly set the name of the rom to display it later in another function.</p> <pre><code>import string import random names = ['This', '...
-1
2016-10-14T10:59:25Z
40,041,838
<p>To make the script you posted work, you need to:</p> <ol> <li><p>Move the <code>for</code> lop to the end of the script (after you set the value of <code>rooms</code>). It operates on <code>rooms</code> variable, which must be defined firs</p></li> <li><p>Fix the <code>for</code> loop. If you want to modify a value...
0
2016-10-14T11:16:08Z
[ "python", "python-3.x", "dictionary" ]
How to create index for dic in mongodb with python?
40,041,547
<p>I have some objects like:</p> <pre><code>{ 'id':1 'claims':{ 'c1':{xxxxx}, 'c8':{xxxxx}, 'c20':{xxxxx} } } </code></pre> <p>if I use <code>d.create_index([('claims', 1)])</code> directly, it will use whole <code>{'c1':{xxxxx},'c8':{xxxxx},'c20':{xxxxx}}</code> as index which is ...
0
2016-10-14T10:59:54Z
40,041,987
<p>The way of doing that is as follows:</p> <pre><code>db.collection.createIndex( { 'claims.c1':1, 'claims.c8':1, 'claims.c20':1 } ) </code></pre>
1
2016-10-14T11:23:39Z
[ "python", "arrays", "mongodb", "dictionary", "indexing" ]
How is the output.xml file generated in robot framework
40,041,661
<p>I am currently working on adding support for execution of Robot scripts from our home-grown Automation Framework. I understand that Robot, by default, generates the output.xml file upon the execution of the Robot scripts.</p> <p>So as to maintain uniformity, I am exploring the option of using the Robot Logging modu...
-2
2016-10-14T11:07:21Z
40,042,942
<p><code>robot/running/model.py</code> defines a class named <code>TestSuite</code>. In that class definition is a method named <code>run</code> which is responsible for running the test. As part of its initialization it creates an instance of <code>Output</code>, which is the xml logger. This logger is defined in the ...
0
2016-10-14T12:16:07Z
[ "python", "xml", "python-2.7", "robotframework" ]
Converting pandas dataframe to csv
40,041,757
<p><a href="https://i.stack.imgur.com/ZlUc1.png" rel="nofollow"><img src="https://i.stack.imgur.com/ZlUc1.png" alt="enter image description here"></a> I have the dataframe above and I wish to convert it into a csv file.<br> I am currently using <code>df.to_csv('my_file.csv')</code> to convert it but I want to leave 3 b...
2
2016-10-14T11:12:29Z
40,048,515
<p>Consider outputting data frame initially as is to a temp file. Then, during creation of the <em>MainCSV</em>, read in temp file, iteratively writing lines, then destroy temp file. Also, prior to writing dataframe to csv, create the three blank columns. </p> <p>Below assumes you want two tasks: 1) three blank column...
1
2016-10-14T17:07:33Z
[ "python", "csv", "pandas" ]
python selenium how to deal with absence of an element
40,041,809
<p>So Im trying to translate all the reviews on tripadvisor to save comments(non-translated, original) and translated comments (from portuguese to english). </p> <p>So the scraper first selects portuguese comments to be displayed , then as usual it converts them into english one by one and saves the translated comment...
0
2016-10-14T11:14:50Z
40,042,197
<pre><code>if (gt.size() == 0): insert code here to extract the english comments </code></pre>
0
2016-10-14T11:35:11Z
[ "python", "selenium", "web-scraping" ]
Choosing between pandas, OOP classes, and dicts (Python)
40,041,845
<p>I have written a program that reads a couple of .csv files (they are not large, a couple of thousands rows each), I do some data cleaning and wrangling and this is the final structure of each .csv file looks (fake data for illustration purposes only).</p> <pre><code>import pandas as pd data = [[112233,'Rob',99],[44...
5
2016-10-14T11:16:30Z
40,042,236
<p>I would choose Pandas, because it's much faster, has an excellent and extremely rich API, a source code looks much cleaner and better, etc.</p> <p>BTW the following line can be easily rewritten:</p> <pre><code>managers[managers['ShopId'].isin(sales[sales['Year2010'] &gt; 1500]['ShopId'])]['ManagerName'].values </c...
2
2016-10-14T11:37:11Z
[ "python", "class", "oop", "pandas", "dictionary" ]
Choosing between pandas, OOP classes, and dicts (Python)
40,041,845
<p>I have written a program that reads a couple of .csv files (they are not large, a couple of thousands rows each), I do some data cleaning and wrangling and this is the final structure of each .csv file looks (fake data for illustration purposes only).</p> <pre><code>import pandas as pd data = [[112233,'Rob',99],[44...
5
2016-10-14T11:16:30Z
40,042,283
<p>Creating classes that operate on dataframes is not a good idea, because it'll hide away the fact that you're using a data frame, and open the way to very bad decisions (like iterating over a dataframe with a <code>for</code> loop).</p> <p>Solution 1: Denormalize the data. You don't have to keep your data in a nor...
2
2016-10-14T11:39:46Z
[ "python", "class", "oop", "pandas", "dictionary" ]
How can I make sure the content of a tkinter entry is saved on FocusOut?
40,041,902
<p>I have an app that uses <code>&lt;FocusOut&gt;</code> binding to automatically save the edits in an <code>Entry</code> to a list.</p> <p>There is no problem saving the <code>Entry</code> text when using <code>TAB</code> to navigate through the Entries or when I click on another Entry, but If I change the text on on...
-2
2016-10-14T11:19:18Z
40,042,945
<h3>Realtime edit / save text instead</h3> <p>It looks like you want to get the updated text realtime. What I do in such a case is use the <code>'KeyRelease'</code> -binding. Simple, effective enrtry- specific and works instantly.</p> <p>In concept:</p> <pre class="lang-py prettyprint-override"><code>win = Tk() def ...
0
2016-10-14T12:16:12Z
[ "python", "tkinter", "entry", "focusout" ]
Nicer command line parse python
40,042,071
<p>Using argparse, I have created a small script that contains a command line parser for my analysis program which is part of a self made python package. It works perfectly, but I don't really like how to control it.</p> <p>This is how the code looks in the script itself</p> <pre><code>def myAnalysis(): parser =...
1
2016-10-14T11:28:47Z
40,042,224
<p>Use <em>store_true</em> action</p> <pre><code>parser.add_argument('-e', '--option_1', help='', default=False, action ='store_true') </code></pre> <p>Then just adding to command line <em>--option_1</em> will set its value to <em>True</em>.</p>
5
2016-10-14T11:36:26Z
[ "python", "argparse" ]
Nicer command line parse python
40,042,071
<p>Using argparse, I have created a small script that contains a command line parser for my analysis program which is part of a self made python package. It works perfectly, but I don't really like how to control it.</p> <p>This is how the code looks in the script itself</p> <pre><code>def myAnalysis(): parser =...
1
2016-10-14T11:28:47Z
40,042,275
<p>To have a positional argument instead of an option, replace:</p> <pre><code>parser.add_argument('-d', '--data',help='') </code></pre> <p>by:</p> <pre><code>parser.add_argument('data_file', help='') </code></pre>
1
2016-10-14T11:39:15Z
[ "python", "argparse" ]
Apache virtualenv and mod_wsgi : ImportError : No module named 'django'
40,042,096
<p>I'm having issues running django and apache2/mod_wsgi. This is my current setup:</p> <pre><code>Ubuntu: 16.0 Apache: 2.4.18 Python: 3.5 Django: 1.10 </code></pre> <p>I have installed a virtualenv inside my django project for user 'carma'. Structure is:</p> <pre><code>/home/carma/mycarma |- manage.py static mycarm...
1
2016-10-14T11:29:41Z
40,042,403
<p>I think it is a typo, <code>mycarmanev</code> or <code>mycarmavirtuanev</code> ?</p> <pre><code>WSGIDaemonProcess mycarma python-path=/home/carma/mycarma/ python-home=/home/carma/mycarma/myprojectenv </code></pre>
3
2016-10-14T11:45:55Z
[ "python", "django", "apache", "mod-wsgi" ]
User defined legend in python
40,042,223
I have this plot in which some areas between curves are being filled by definition. Is there any way to include them in legend? Especially where those filled areas are overlapped and as well as that a new and different color is being appeared. <p>Or there is possibility to define an arbitrary legend regardless of the ...
3
2016-10-14T11:36:22Z
40,066,329
<p>Using <code>fill_bettween</code> to plot your data will automatically include the filled area in the legend.</p> <p>To include the areas where the two datasets overlap, you can combine the legend handles from both dataset into a single legend handle.</p> <p>As pointed out in the comments, you can also define any a...
1
2016-10-16T02:51:03Z
[ "python", "matplotlib", "legend-properties" ]
User defined legend in python
40,042,223
I have this plot in which some areas between curves are being filled by definition. Is there any way to include them in legend? Especially where those filled areas are overlapped and as well as that a new and different color is being appeared. <p>Or there is possibility to define an arbitrary legend regardless of the ...
3
2016-10-14T11:36:22Z
40,069,079
<p>Yes, you are absolutely right ian_itor, tacaswell and Jean-Sébastien, user defined legend seems to be the unique solution, in addition I made different <em>linewidth</em> for those area to be distinguishable from the curves, and playing with <em>alpha</em> got the right color.</p> <pre><code>handles, labels = ax...
0
2016-10-16T10:04:33Z
[ "python", "matplotlib", "legend-properties" ]
'type' object is not iterable in using django_enums
40,042,345
<p>I tried to use <a href="https://pypi.python.org/pypi/django-enums/" rel="nofollow">django_enums</a> and got an error with <strong>list(cls)</strong> when making migrations:</p> <pre><code>(venv:SFS)rita@rita-notebook:~/Serpentarium/ServiceForServices/project/serviceforservices$ python manage.py makemigrations T...
2
2016-10-14T11:42:58Z
40,046,073
<p>It looks like you are trying to use the backported enum from the 3.4 stdlib, but you installed <code>enum</code> -- you need to install <code>enum34</code>.</p>
1
2016-10-14T14:49:37Z
[ "python", "django", "enums" ]
Two Hours Mongodb Aggregation
40,042,406
<p>Here is my sample Data:</p> <pre><code>{ "_id": { "$oid": "5654a8f0d487dd1434571a6e" }, "ValidationDate": { "$date": "2015-11-24T13:06:19.363Z" }, "DataRaw": " WL 00100100012015-08-28 02:44:17+0000+ 16.81 8.879 1084.00", "ReadingsAreValid": true, "locationID": " WL 001", "Readings": { "pH": { ...
1
2016-10-14T11:46:09Z
40,042,606
<p>After some formatting, your present aggregation pipeline looks like:</p> <pre><code>Query = [ { "$unwind": "$Readings" }, { '$group' : { "_id": { "year": { "$year": "$Readings.SensoreDate.value" }, "dayOfYear": { "$dayOfYear": "$Readin...
1
2016-10-14T11:56:30Z
[ "javascript", "python", "arrays", "mongodb", "pymongo-3.x" ]
python regular expressions using the re module can you write a regex which looks inside the result of another regex?
40,042,524
<p>I am wanting to write a regular expression which pulls out the following from between but not including <code>&lt;p&gt;</code> and <code>&lt;/p&gt;</code> tags:</p> <p>begins with the word "Cash" has some stuff I don't want then a number $336,008.</p> <p>From:</p> <blockquote> <p><code>&lt;p&gt;Cash nbs $13,000...
0
2016-10-14T11:52:23Z
40,043,001
<p>If you using re.findall, just use () with you want to catch.</p> <pre><code>&gt;&gt;&gt; test = '&lt;p&gt;Cash nbs $13,000&lt;/p&gt;' &gt;&gt;&gt; re.findall(r'&lt;p&gt;(Cash).+\${1}\d*|\,&lt;/p&gt;', test) ['Cash'] </code></pre>
0
2016-10-14T12:19:22Z
[ "python", "regex" ]
Efficiently change order of numpy array
40,042,573
<p>I have a 3 dimensional numpy array. The dimension can go up to 128 x 64 x 8192. What I want to do is to change the order in the first dimension by interchanging pairwise. </p> <p>The only idea I had so far is to create a list of the indices in the correct order.</p> <pre><code>order = [1,0,3,2...127,126] data_n...
2
2016-10-14T11:54:34Z
40,042,659
<p>You could reshape to split the first axis into two axes, such that latter of those axes is of length <code>2</code> and then flip the array along that axis with <code>[::-1]</code> and finally reshape back to original shape.</p> <p>Thus, we would have an implementation like so -</p> <pre><code>a.reshape(-1,2,*a.sh...
4
2016-10-14T11:59:12Z
[ "python", "numpy" ]
why windll.user32.GetWindowThreadProcessID can't find the function?
40,042,596
<p>I'm reading <em>Black Hat Python</em> and in chapter 8 I find "user32.GetWindowThreadProcessID(hwnd,byref(pid))" doesn't work, just like the picture shows.</p> <p>It seems that python can't find <em>GetWindowThreadProcessID</em>, but it can find <em>GetForegroundWindow</em> which also is exported from user32.dll.</...
0
2016-10-14T11:55:55Z
40,043,277
<p>It should work if you your OS version is at least Windows 2000 Professional:</p> <pre><code>import ctypes import ctypes.wintypes pid = ctypes.wintypes.DWORD() hwnd = ctypes.windll.user32.GetForegroundWindow() print( ctypes.windll.user32.GetWindowThreadProcessId(hwnd,ctypes.byref(pid)) ) </code></pre>
0
2016-10-14T12:33:28Z
[ "python" ]
pythonic way of initialization of dict in a for loop
40,042,615
<p>Is there a python way of initialization of a dictionary?</p> <pre><code>animals = ["dog","cat","cow"] for x in animals: primers_pos[x]={} </code></pre> <p>Is there something like</p> <pre><code>(primers_pos[x]={} for x in animals) </code></pre>
0
2016-10-14T11:56:55Z
40,042,640
<p>You can use a dictionary comprehension (supported in Python 2.7+):</p> <pre><code>&gt;&gt;&gt; animals = ["dog", "cat", "cow"] &gt;&gt;&gt; {x: {} for x in animals} {'dog': {}, 'cow': {}, 'cat': {}} </code></pre>
2
2016-10-14T11:58:05Z
[ "python", "dictionary" ]
pythonic way of initialization of dict in a for loop
40,042,615
<p>Is there a python way of initialization of a dictionary?</p> <pre><code>animals = ["dog","cat","cow"] for x in animals: primers_pos[x]={} </code></pre> <p>Is there something like</p> <pre><code>(primers_pos[x]={} for x in animals) </code></pre>
0
2016-10-14T11:56:55Z
40,042,838
<p>You may also use <em>collections.defaultdict</em></p> <pre><code>primer_pos = defaultdict(dict) </code></pre> <p>Then whenever you reference <em>primer_pos</em> with a new key, a dictionary will be created automatically</p> <pre><code>primer_pos['cat']['Fluffy'] = 'Nice kitty' </code></pre> <p>Will by chain crea...
0
2016-10-14T12:09:37Z
[ "python", "dictionary" ]
How to convert an string with array form to an array?
40,042,628
<p>I got a string in this form</p> <pre><code>payload = ["Text 1", "Text 2"] </code></pre> <p>I want to use <code>Text 2</code> as an object. How can I return it? </p> <p><strong>UPDATE</strong> I'm making a function which returns a <a href="https://developers.facebook.com/docs/messenger-platform/send-api-reference/...
0
2016-10-14T11:57:26Z
40,042,717
<p>You need to split the string then trim and keep splitting/trimming to get all parts that you want to have in list</p> <pre><code>s = 'payload = ["Text 1", "Text 2"]' items = s.strip()[1:-1] #if 'payload = ' is also part of string you need to split it also by '=' so it would be: #items = s.split("=").strip()[1:-1] ...
3
2016-10-14T12:02:13Z
[ "python", "arrays", "django", "string" ]
How to convert an string with array form to an array?
40,042,628
<p>I got a string in this form</p> <pre><code>payload = ["Text 1", "Text 2"] </code></pre> <p>I want to use <code>Text 2</code> as an object. How can I return it? </p> <p><strong>UPDATE</strong> I'm making a function which returns a <a href="https://developers.facebook.com/docs/messenger-platform/send-api-reference/...
0
2016-10-14T11:57:26Z
40,042,735
<p>you can try:</p> <pre><code>&gt;&gt;&gt; payload = ["t1", "t2"] &gt;&gt;&gt; t2 = [1,2] &gt;&gt;&gt; eval(payload[1]) [1, 2] </code></pre>
0
2016-10-14T12:02:58Z
[ "python", "arrays", "django", "string" ]
How to convert an string with array form to an array?
40,042,628
<p>I got a string in this form</p> <pre><code>payload = ["Text 1", "Text 2"] </code></pre> <p>I want to use <code>Text 2</code> as an object. How can I return it? </p> <p><strong>UPDATE</strong> I'm making a function which returns a <a href="https://developers.facebook.com/docs/messenger-platform/send-api-reference/...
0
2016-10-14T11:57:26Z
40,042,936
<p>assuming that you want a string object, you can get the specific index in the array(first spot = 0, second spot = 1, etc).</p> <p>you can save the string object contained in the array like this:</p> <pre><code>payload = ["Text 1", "Text 2"] s = payload[1] </code></pre> <p>and than you can return the s object.</p>...
1
2016-10-14T12:15:52Z
[ "python", "arrays", "django", "string" ]
How to convert an string with array form to an array?
40,042,628
<p>I got a string in this form</p> <pre><code>payload = ["Text 1", "Text 2"] </code></pre> <p>I want to use <code>Text 2</code> as an object. How can I return it? </p> <p><strong>UPDATE</strong> I'm making a function which returns a <a href="https://developers.facebook.com/docs/messenger-platform/send-api-reference/...
0
2016-10-14T11:57:26Z
40,087,443
<p>I found another way should work also.</p> <p>I edited my <code>payload</code> to:</p> <pre><code>payload = { 'text': 'Order_item', 'title': product['title'] } </code></pre> <p>Then I use:</p> <p><code>title = json.loads(message['postback']['payload']['title'])</code></p> <p>With ...
0
2016-10-17T13:17:08Z
[ "python", "arrays", "django", "string" ]
Trouble while providing webservices in django python to android
40,042,939
<p>I am new for Django1.10 Python.</p> <p>I've to provide web services for an app. So I created a web service in python's Django framework. The web service is properly working for <code>iOS</code> but getting issue while handling with <code>android</code>. For dealing with web services in android, using <code>Volley</...
0
2016-10-14T12:16:02Z
40,043,335
<ol> <li>Make sure that in your 'request.body', you are getting a proper dictionary which have all the keys u accessed below.Because,if your 'data' variable dont have any key that you accessed below, it will raise keyerror and u didnt handle keyerror in your code. </li> </ol> <p>If above does not worked, then show me...
0
2016-10-14T12:36:12Z
[ "android", "python", "web-services", "django-1.10" ]
Error at my python code
40,042,984
<p>when i run this code :</p> <pre><code>import math print "welcome !This program will solve your quadratic equation" A = input("inter a =") B = input("inter b =") C = input("inter c =") J=math.pow(B,2)-4*A*C X1=-B+math.sqrt(J)/2*A X2=-B-(math.sqrt(J))/(2*A) print "your roots is :" , X1 , X2 </code></pre> <hr> <p>...
-8
2016-10-14T12:18:43Z
40,043,165
<p>Your <code>print</code>'s have missing <code>()</code>. Fixed version:</p> <pre><code>import math print("welcome !This program will solve your quadratic equation") A = input("inter a =") B = input("inter b =") C = input("inter c =") J = math.pow(B,2)-4*A*C X1 = -B+math.sqrt(J)/2*A X2 = -B-(math.sqrt(J))/(2*A) prin...
1
2016-10-14T12:28:24Z
[ "python", "pycharm" ]
Error at my python code
40,042,984
<p>when i run this code :</p> <pre><code>import math print "welcome !This program will solve your quadratic equation" A = input("inter a =") B = input("inter b =") C = input("inter c =") J=math.pow(B,2)-4*A*C X1=-B+math.sqrt(J)/2*A X2=-B-(math.sqrt(J))/(2*A) print "your roots is :" , X1 , X2 </code></pre> <hr> <p>...
-8
2016-10-14T12:18:43Z
40,048,398
<p>Without any information about which kind of error your program raises, I think that the problem is linked to the function <strong>math.sqrt</strong> which doesn't find complex roots.</p> <p>So I suggest you to use <strong>cmath</strong> in this way:</p> <pre><code>import cmath, math print "welcome !This program wi...
0
2016-10-14T16:58:58Z
[ "python", "pycharm" ]
AWS S3 download file from Flask
40,043,018
<p>I have created a small app that should download file from a AWS S3. </p> <p>I can download the data correctly in this way:</p> <pre><code> s3_client = boto3.resource('s3') req = s3_client.meta.client.download_file(bucket, ob_key, dest) </code></pre> <p>but if I add this function in a flask route it does not work...
-1
2016-10-14T12:20:09Z
40,043,126
<p>That is related to your AWS region. Mention the region name as an added parameter.</p> <p>Try it on your local machine, using </p> <pre><code>aws s3 cp s3://bucket-name/file.png file.png --region us-east-1 </code></pre> <p>If you are able to download the file using this command, then it should work fine from your...
0
2016-10-14T12:26:10Z
[ "python", "amazon-s3", "flask", "boto3" ]
AWS S3 download file from Flask
40,043,018
<p>I have created a small app that should download file from a AWS S3. </p> <p>I can download the data correctly in this way:</p> <pre><code> s3_client = boto3.resource('s3') req = s3_client.meta.client.download_file(bucket, ob_key, dest) </code></pre> <p>but if I add this function in a flask route it does not work...
-1
2016-10-14T12:20:09Z
40,044,758
<p>The problem was that with flask I needed to declare s3_client as global variable instead of just inside the function. </p> <p>Now it works perfectly!</p>
-1
2016-10-14T13:45:15Z
[ "python", "amazon-s3", "flask", "boto3" ]
Unable to install modules using 'pip' or 'easy_install' on Mac
40,043,052
<p>Default Python installation is 2.7.x on Mac. (currently running El Capitan)</p> <p>I've changed default to 3.4.5.(mandatory for my course)</p> <p>I was instructed by my professor to use MacPorts and it requires an SSL to download libraries so we are using following code to bypass it:</p> <pre><code>#from https://...
0
2016-10-14T12:22:31Z
40,043,892
<p>Try executing the following command:</p> <pre><code>$ sudo python3 -m pip install textblob </code></pre> <p>Best way would be to clone the repo:[EDIT]</p> <pre><code>$ git clone https://github.com/sloria/TextBlob.git $ cd TextBlob/ $ python setup.py install </code></pre> <p>For more details see <a href="http://t...
2
2016-10-14T13:03:22Z
[ "python", "osx", "python-3.x", "pip" ]
python - subtracting ranges from bigger ranges
40,043,103
<p>The problem I have is that I basically would like to find if there are any free subnets between a BGP aggregate-address (ex: 10.76.32.0 255.255.240.0) and all the network commands on the same router (ex: 10.76.32.0 255.255.255.0, 10.76.33.0 255.255.255.0)</p> <p>In the above example 10.76.34.0 -> 10.76.47.255 would...
0
2016-10-14T12:25:00Z
40,043,669
<p>If you are trying to create a "range" with a gap in it, i.e., with 1-9 and 24-250, you could try to use <a href="https://docs.python.org/3/library/itertools.html#itertools.filterfalse" rel="nofollow"><code>filterfalse</code></a> (or <a href="https://docs.python.org/2.7/library/itertools.html#itertools.ifilterfalse" ...
1
2016-10-14T12:52:24Z
[ "python", "networking", "range", "subnet" ]
Parsing old tweets and putting their attributes into a Pandas dataframe
40,043,112
<p>I am trying to pull a selection of old tweets and then put various attributes into a Pandas dataframe. My code is below. However, when I run the final line, I get a dataframe that only contains attribute data for one tweet rather than for all of them in my selection.</p> <p>Can someone tell me where my error is? ...
0
2016-10-14T12:25:19Z
40,047,140
<p>After the clarification from your comment, this should work:</p> <pre><code># make a list of lists that contain the data # pandas considers a list of lists to be a list of rows data_set = [[x.id, x.date, x.text, x.retweets, x.favorites, x.date, x.id] for x in KYDerby_tweets] df = pd.DataFrame(data=data...
0
2016-10-14T15:42:21Z
[ "python", "pandas", "tweepy" ]
How do I minimize my Tkinter window whilst I run a batch file?
40,043,144
<p>I have a Tkinter window with a button. This button, on click, runs a batch file which in turn runs a test suite. This is working fine so far. But I want the Tkinter window to minimize itself when I click this button and restore itself when the batch file execution is completed. I don't know how to handle this event....
0
2016-10-14T12:27:11Z
40,043,184
<pre><code>top.wm_state('iconic') </code></pre> <p>should minimize your win</p>
1
2016-10-14T12:29:17Z
[ "python", "button", "tkinter", "onclick", "minimize" ]
Python Pandas - multiple arithmetic operation in a single dataframe
40,043,182
<p>I am analysing a stock market data and I was able to get only the open, high, low, close, and volume. Now I wanted to calculate the percentage increase for each day using Pandas. The following is my dataframe:</p> <pre><code>&gt;&gt;&gt; df.head() date open high low close volume...
0
2016-10-14T12:29:13Z
40,043,345
<p>There is a <code>pct_change()</code> function for calculating the percent change between current day and previous day, which you can use (note the <code>NA</code> here is due to the fact that I have access to only five rows of your data):</p> <pre><code>df['per'] = (df.close.replace({',':''}, regex=True).astype(flo...
4
2016-10-14T12:36:55Z
[ "python", "pandas" ]
dict to list, and compare lists python
40,043,225
<p>I have made a function, were I count how many times each word is used in a file, that will say the word frequency. Right now the function can calculate the sum of all words, and show me the seven most common words and how many times they are used. Now I want to compare my first file were I have analyzed the word fre...
0
2016-10-14T12:31:04Z
40,043,503
<p>I'm not in front of an interpreter so my code might be slightly off. But try something more like this.</p> <pre><code>from collections import Counter with open("some_file_with_words") as f_file counter = Counter(f_file.read()) top_seven = counter.most_common(7) with open("commonwords") as f_common: commo...
0
2016-10-14T12:44:56Z
[ "python", "list", "dictionary", "key" ]
How to count number of variables in a dictionary
40,043,235
<p>This is my current code to append different time to the same name id in a dict.</p> <blockquote> <pre><code>for name, date, time ,price in reader(f): group_dict[name].append([time]) </code></pre> </blockquote> <p>my question is how do i count the number of 'time' i have in each key in the dict ? </p> <p...
-3
2016-10-14T12:31:28Z
40,043,637
<pre><code>for key, value in yourDict.iteritems(): print len(value) </code></pre> <p>if you want include to your structure try:</p> <pre><code>for key, value in yourDict.iteritems(): yourDict[key] = (value, len(value)) </code></pre> <p>Code for python2 for python 3 use items() instead of iteritems()</p>
2
2016-10-14T12:51:14Z
[ "python", "csv", "count" ]
How to count number of variables in a dictionary
40,043,235
<p>This is my current code to append different time to the same name id in a dict.</p> <blockquote> <pre><code>for name, date, time ,price in reader(f): group_dict[name].append([time]) </code></pre> </blockquote> <p>my question is how do i count the number of 'time' i have in each key in the dict ? </p> <p...
-3
2016-10-14T12:31:28Z
40,044,837
<p>You can accomplish what you want by reassigning your key's value to include the length of its value:</p> <pre><code>for key, value in yourDict.items(): # Change to .iteritems() if using Python 2.x yourDict[key] = value + [len(value)] </code></pre> <p>Or, you could do this using dictionary comprehension:</p> <...
0
2016-10-14T13:49:17Z
[ "python", "csv", "count" ]