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
expand plot for readability without expanding lines
39,267,981
<p>I am plotting 2 lines and a dot, X axis is a date range. The dot is most important, but it appears on the boundary of the plot. I want to "expand" the plot further right so that the dot position is more visible. In other words I want to expand the X axis without adding new values to Y values of lines. However if I j...
0
2016-09-01T09:39:17Z
39,268,167
<p>Just change the <a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.xlim" rel="nofollow">xlim()</a>. Something like:</p> <pre><code>xmin, xmax = plt.xlim() # return the current xlim plt.xlim(xmax=xmax+1) </code></pre>
2
2016-09-01T09:47:27Z
[ "python", "matplotlib", "plot" ]
expand plot for readability without expanding lines
39,267,981
<p>I am plotting 2 lines and a dot, X axis is a date range. The dot is most important, but it appears on the boundary of the plot. I want to "expand" the plot further right so that the dot position is more visible. In other words I want to expand the X axis without adding new values to Y values of lines. However if I j...
0
2016-09-01T09:39:17Z
39,268,548
<p>There are a couple of ways to do this.</p> <p>An easy, automatic way to do this, without needing knowledge of the existing <code>xlim</code> is to use <a href="http://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes.margins" rel="nofollow"><code>ax.margins</code></a>. This will add a certain fraction of the da...
3
2016-09-01T10:04:04Z
[ "python", "matplotlib", "plot" ]
Combine Rows in Pandas DataFrame
39,268,010
<p>I have financial performance Indicators for different companies, one row per year. Now I would like to have all the indicators per company over a specific range of years in one row.</p> <p>Now my data looks similar to this:</p> <pre><code>import numpy as np import pandas as pd startyear = 2014 endyear = 2015 df...
0
2016-09-01T09:40:31Z
39,271,199
<p>Probably easier to create the new DataFrame, then adjust the column names:</p> <pre><code># limit to data you want dfnew = df[df.Year.isin(['2014', '2015'])] # set index to 'Name' and pivot 'Year's into the columns dfnew = dfnew.set_index(['Name', 'Year']).unstack() # sort the columns by year dfnew = dfnew.sortl...
2
2016-09-01T12:08:29Z
[ "python", "dataframe" ]
How to compare Enums in Python?
39,268,052
<p>Since Python 3.4, the <code>Enum</code> class exists.</p> <p>I am writing a program, where some constants have a specific order and I wonder which way is the most pythonic to compare them:</p> <pre><code>class Information(Enum): ValueOnly = 0 FirstDerivative = 1 SecondDerivative = 2 </code></pre> <p>N...
0
2016-09-01T09:42:28Z
39,268,706
<p>I hadn'r encountered Enum before so I scanned the doc (<a href="https://docs.python.org/3/library/enum.html" rel="nofollow">https://docs.python.org/3/library/enum.html</a>) ... and found OrderedEnum (section 8.13.13.2) Isn't this what you want? From the doc:</p> <pre><code>&gt;&gt;&gt; class Grade(OrderedEnum): .....
0
2016-09-01T10:10:48Z
[ "python", "enums", "compare" ]
How to compare Enums in Python?
39,268,052
<p>Since Python 3.4, the <code>Enum</code> class exists.</p> <p>I am writing a program, where some constants have a specific order and I wonder which way is the most pythonic to compare them:</p> <pre><code>class Information(Enum): ValueOnly = 0 FirstDerivative = 1 SecondDerivative = 2 </code></pre> <p>N...
0
2016-09-01T09:42:28Z
39,269,589
<p>You should always implement the rich comparison operaters if you want to use them with an <code>Enum</code>. Using the <code>functools.total_ordering</code> class decorator, you only need to implement an <code>__eq__</code> method along with a single ordering, e.g. <code>__lt__</code>. Since <code>enum.Enum</code> a...
1
2016-09-01T10:52:04Z
[ "python", "enums", "compare" ]
Understand pandas groupby/apply behaviour
39,268,147
<p>Let's take the following DataFrame:</p> <pre><code> location outlook play players temperature 0 Hamburg sunny True 2.00 25.00 1 Berlin sunny True 2.00 25.00 2 Stuttgart NaN True 4.00 19.00 3 NaN NaN NaN nan nan ...
0
2016-09-01T09:46:43Z
39,268,532
<p>According to the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html" rel="nofollow">docs</a></p> <blockquote> <p>In the current implementation apply calls func twice on the first column/row to decide whether it can take a fast or slow code path. This can lead to unexpected ...
3
2016-09-01T10:03:17Z
[ "python", "pandas" ]
Understand pandas groupby/apply behaviour
39,268,147
<p>Let's take the following DataFrame:</p> <pre><code> location outlook play players temperature 0 Hamburg sunny True 2.00 25.00 1 Berlin sunny True 2.00 25.00 2 Stuttgart NaN True 4.00 19.00 3 NaN NaN NaN nan nan ...
0
2016-09-01T09:46:43Z
39,268,538
<p>I.. don't know. It's weird. I'm actually able to replicate the problem. </p> <p>Note that you have a small mistake, you should write <code>df.groupby(["series"])</code> instead of <code>df(by=["series"])</code>.</p> <pre><code>import seaborn as sns iris = sns.load_dataset('iris') </code></pre> <p>Now this statem...
1
2016-09-01T10:03:33Z
[ "python", "pandas" ]
Generator from function prints
39,268,377
<p>At the moment I have a little <code>flask</code> project that calls another python file. I'm fully aware that this way is kinda awful, and so, I want to swap it for a function call while maintaining <strong>the prints getting yelded to the website</strong>. </p> <pre><code>def get_Checks(): root = request.url_r...
2
2016-09-01T09:56:57Z
39,269,182
<p>Assuming that all the printing you want to grab is done within the same module, You can monkey-patch the <code>print</code> function of the other module. In the example below, I use a context manager to revert the original print function after the grabbing is done.</p> <p>This is <code>mod1</code>, the module with ...
1
2016-09-01T10:33:03Z
[ "python", "python-3.x", "flask", "subprocess", "generator" ]
Generator from function prints
39,268,377
<p>At the moment I have a little <code>flask</code> project that calls another python file. I'm fully aware that this way is kinda awful, and so, I want to swap it for a function call while maintaining <strong>the prints getting yelded to the website</strong>. </p> <pre><code>def get_Checks(): root = request.url_r...
2
2016-09-01T09:56:57Z
39,271,254
<p>A simple way would be to temporarily change <code>sys.stdout</code> to a file-like object, call the function, then restore <code>sys.stdout</code>. The output will be available in the file-like object.</p> <p>Here is a working Flask app that demonstrates the method:</p> <pre><code>import sys from io import StringI...
1
2016-09-01T12:11:15Z
[ "python", "python-3.x", "flask", "subprocess", "generator" ]
Displaying rows according to Specific Values
39,268,518
<p>I want to select several rows according to the attributes in Type column.</p> <p>Let's pretend I have this dataframe:</p> <pre><code>Type | Killed | Survive Dog 1 0 Cat 3 5 Dog 4 1 Cow 2 4 Fish 1 3 </code></pre> <p>I would like to select the row that...
1
2016-09-01T10:02:53Z
39,268,580
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.isin.html" rel="nofollow"><code>isin</code></a>:</p> <pre><code>df[df['Type'].isin(['Dog', 'Cat', 'Fish'])] </code></pre>
3
2016-09-01T10:05:20Z
[ "python", "pandas" ]
Selenium fails to change dropdown selection
39,268,637
<p>Here is the isolated HTML code:</p> <pre><code>&lt;span style="position: relative; width: 100%; display: inline-block;"&gt; &lt;select id="0ac88542d16d6200fb983d094f655c76_select" class="form-control"&gt; &lt;option value="display_value"&gt;Number&lt;/option&gt; &lt;option value="sys_class_name"...
0
2016-09-01T10:08:03Z
39,269,522
<p>Class <code>form-control</code> might give you other elements. Try to locate by partial id</p> <pre><code>search_elemet = driver.find_element_by_css_selector('[id*="select"]') Select(search_elemet).select_by_visible_text('Number') # or Select(search_elemet).select_by_value('display_value') </code></pre>
0
2016-09-01T10:48:54Z
[ "python", "html", "selenium", "selenium-webdriver", "drop-down-menu" ]
Selenium fails to change dropdown selection
39,268,637
<p>Here is the isolated HTML code:</p> <pre><code>&lt;span style="position: relative; width: 100%; display: inline-block;"&gt; &lt;select id="0ac88542d16d6200fb983d094f655c76_select" class="form-control"&gt; &lt;option value="display_value"&gt;Number&lt;/option&gt; &lt;option value="sys_class_name"...
0
2016-09-01T10:08:03Z
39,270,297
<p>@katericata Your html is as like- Number Type Type2 Type3</p> <p>and my web driver class is as, here you can replace the drop down items as Type2,type 3 etc which you want to select.</p> <p>driver.findElement(By.xpath("code']")).sendKeys("Type3"); } } let me know if there are any concern.</p>
0
2016-09-01T11:27:13Z
[ "python", "html", "selenium", "selenium-webdriver", "drop-down-menu" ]
Selenium fails to change dropdown selection
39,268,637
<p>Here is the isolated HTML code:</p> <pre><code>&lt;span style="position: relative; width: 100%; display: inline-block;"&gt; &lt;select id="0ac88542d16d6200fb983d094f655c76_select" class="form-control"&gt; &lt;option value="display_value"&gt;Number&lt;/option&gt; &lt;option value="sys_class_name"...
0
2016-09-01T10:08:03Z
39,281,752
<p>I'm not sure why the action chain isn't working I've used that on styled options and had it work. But if you don't care about mimicking the user behavior exactly as it will occur you can use this to change the option.</p> <pre><code> option = driver.find_element_by_xpath("//select[@id='0ac88542d16d6200fb983...
0
2016-09-01T22:22:36Z
[ "python", "html", "selenium", "selenium-webdriver", "drop-down-menu" ]
python installations, directories and environments - good resource to understand the basics
39,268,717
<p>newbie here. I'm using python (3) on my mac, and although I'm able to write some (basic) scripts, I realise I have lots of confusion around where python is stored, the famous usr/bin directory, where packages are saved, etc.</p> <p>For example I had pip installed and working fine, but then I installed miniconda and...
0
2016-09-01T10:11:18Z
39,268,898
<p>First of all I suggest to see: <a href="https://www.python.org/doc/" rel="nofollow">https://www.python.org/doc/</a></p> <p>Then I suggest to look: <a href="http://code.tutsplus.com/series/python-from-scratch--net-20566" rel="nofollow">http://code.tutsplus.com/series/python-from-scratch--net-20566</a></p>
1
2016-09-01T10:19:06Z
[ "python" ]
python installations, directories and environments - good resource to understand the basics
39,268,717
<p>newbie here. I'm using python (3) on my mac, and although I'm able to write some (basic) scripts, I realise I have lots of confusion around where python is stored, the famous usr/bin directory, where packages are saved, etc.</p> <p>For example I had pip installed and working fine, but then I installed miniconda and...
0
2016-09-01T10:11:18Z
39,270,243
<p>I started with python 1 month back. The best thing is to read the python documentation.</p> <p>but to begin with you can try <a href="http://www.tutorialspoint.com/python/index.htm" rel="nofollow">http://www.tutorialspoint.com/python/index.htm</a> or <a href="https://learnpythonthehardway.org/book/ex0.html" rel="no...
0
2016-09-01T11:23:53Z
[ "python" ]
python installations, directories and environments - good resource to understand the basics
39,268,717
<p>newbie here. I'm using python (3) on my mac, and although I'm able to write some (basic) scripts, I realise I have lots of confusion around where python is stored, the famous usr/bin directory, where packages are saved, etc.</p> <p>For example I had pip installed and working fine, but then I installed miniconda and...
0
2016-09-01T10:11:18Z
39,270,661
<p>Python has a lot off stuff. The very basics you can learn on codecademy.com. </p> <p>On python-course.org you have some more advanced topics. </p> <p>If you want to learn something specific you should look on the official python documentation. </p> <p>Overal I don't think you want to use anaconda. It is better to...
0
2016-09-01T11:43:36Z
[ "python" ]
Build 2 lists in one go while reading from file, pythonically
39,268,792
<p>I'm reading a big file with hundreds of thousands of number pairs representing the edges of a graph. I want to build 2 lists as I go: one with the forward edges and one with the reversed. </p> <p>Currently I'm doing an explicit <code>for</code> loop, because I need to do some pre-processing on the lines I read. How...
11
2016-09-01T10:14:47Z
39,268,933
<p>You <em>can't</em> create two lists in one comprehension, so, instead of doing the same operations twice on the two lists, one viable option would be to initialize one of them and then create the second one by reversing each entry in the first one. That way you don't iterate over the file twice.</p> <p>To that end,...
5
2016-09-01T10:21:10Z
[ "python", "list", "python-3.x" ]
Build 2 lists in one go while reading from file, pythonically
39,268,792
<p>I'm reading a big file with hundreds of thousands of number pairs representing the edges of a graph. I want to build 2 lists as I go: one with the forward edges and one with the reversed. </p> <p>Currently I'm doing an explicit <code>for</code> loop, because I need to do some pre-processing on the lines I read. How...
11
2016-09-01T10:14:47Z
39,269,024
<p>I would keep your logic as it is the <em>Pythonic</em> approach just not <em>split/rstrip</em> the same line multiple times:</p> <pre><code>with open('SCC.txt') as data: for line in data: spl = line.split() if spl: i, j = map(int, spl) edge_list.append((i, j)) ...
11
2016-09-01T10:25:31Z
[ "python", "list", "python-3.x" ]
Build 2 lists in one go while reading from file, pythonically
39,268,792
<p>I'm reading a big file with hundreds of thousands of number pairs representing the edges of a graph. I want to build 2 lists as I go: one with the forward edges and one with the reversed. </p> <p>Currently I'm doing an explicit <code>for</code> loop, because I need to do some pre-processing on the lines I read. How...
11
2016-09-01T10:14:47Z
39,269,110
<p>Maybe not clearer, but shorter:</p> <pre><code>with open('SCC.txt') as data: process_line = lambda line, r: (int(line.rstrip().split()[r]), int(line.rstrip().split()[1-r])) edge_list, reverved_edge_list = map(list, zip(*[(process_line(line, 0), process_line(line, 1)) ...
3
2016-09-01T10:28:59Z
[ "python", "list", "python-3.x" ]
Build 2 lists in one go while reading from file, pythonically
39,268,792
<p>I'm reading a big file with hundreds of thousands of number pairs representing the edges of a graph. I want to build 2 lists as I go: one with the forward edges and one with the reversed. </p> <p>Currently I'm doing an explicit <code>for</code> loop, because I need to do some pre-processing on the lines I read. How...
11
2016-09-01T10:14:47Z
39,269,494
<p>Here comes a solution</p> <p>A test file:</p> <pre><code>In[19]: f = ["{} {}".format(i,j) for i,j in zip(xrange(10), xrange(10, 20))] In[20]: f Out[20]: ['0 10', '1 11', '2 12', '3 13', '4 14', '5 15', '6 16', '7 17', '8 18', '9 19'] </code></pre> <p>One liner using comprehension, zip and map:</p> <pre...
3
2016-09-01T10:47:40Z
[ "python", "list", "python-3.x" ]
VALIGN in reportlab TableStyle apparently without effect
39,268,829
<p>So, for a while now I have been struggling with this one. I know there are a lot of similar questions with good answers, and I have tried these answers, but the code I have basically reflects the answers given.</p> <p>I am writing code to automatically generate matching exercises for worksheets. All this informatio...
1
2016-09-01T10:16:26Z
39,269,293
<p>The problem is the way you are indexing the <code>TableStyle</code>. The indexing in Reportlab starts at <code>(0, 0)</code> for first row, first column. So in your case <code>(1, 1)</code> only applies the styling to everything below the first row and right of the first column.</p> <p>The correct way would be to u...
1
2016-09-01T10:37:43Z
[ "python", "formatting", "reportlab" ]
Hello, i have written the below code to go out and look on a Cisco device, return output, write to a file and then save the file and close it off
39,268,831
<p>Okay Massive edit to better ask what im seeking:</p> <p>I have the below code, which thanks to the answer below now will go and look in the .txt file for the IP address and then go to the device and return the commands, it will then print to the file requested and everything works.</p> <p>What i cant get it to do ...
-1
2016-09-01T10:16:30Z
39,269,093
<p>Keep in mind that every line will be a new IP addresses.</p> <p>And you're not writing to ciscoOutput file , you can use command <code>fd.write('text')</code> for that.</p> <pre><code>from __future__ import print_function from netmiko import ConnectHandler import sys import time import select import paramiko impo...
0
2016-09-01T10:28:07Z
[ "python", "python-3.x", "cisco", "cisco-ios" ]
Selenium Python (Import Error) Python-Selenium-Eclipse
39,268,865
<p><strong>After Running the below Command:</strong></p> <pre><code>from selenium import webdriver </code></pre> <p><strong>I get the Following error:</strong></p> <pre><code>Traceback (most recent call last): File "C:\Users\tempjatop\workspace\TestPython\Sample.py", line 1, in &lt;module&gt; from selenium imp...
0
2016-09-01T10:17:30Z
39,283,996
<p>As the error says:</p> <blockquote> <p>TabError: inconsistent use of tabs and spaces in indentation</p> </blockquote> <p>Check for indentations in your code and correct the inconsistent ones.</p>
0
2016-09-02T03:44:30Z
[ "python", "eclipse", "selenium", "testing", "automation" ]
Python: how to get rid of spaces in str(dict)?
39,268,928
<p>For example, if you use str() on a dict, you get:</p> <pre><code>&gt;&gt;&gt; str({'a': 1, 'b': 'as df'}) "{'a': 1, 'b': 'as df'}" </code></pre> <p>However, I want the string to be like:</p> <pre><code>"{'a':1,'b':'as df'}" </code></pre> <p>How can I accomplish this?</p>
3
2016-09-01T10:20:57Z
39,269,016
<p>You could build the compact string representation yourself:</p> <pre><code>In [9]: '{' + ','.join('{0!r}:{1!r}'.format(*x) for x in dct.items()) + '}' Out[9]: "{'b':'as df','a':1}" </code></pre> <p>It will leave extra spaces inside string representations of nested <code>list</code>s, <code>dict</code>s etc.</p> <...
8
2016-09-01T10:25:11Z
[ "python" ]
Python: how to get rid of spaces in str(dict)?
39,268,928
<p>For example, if you use str() on a dict, you get:</p> <pre><code>&gt;&gt;&gt; str({'a': 1, 'b': 'as df'}) "{'a': 1, 'b': 'as df'}" </code></pre> <p>However, I want the string to be like:</p> <pre><code>"{'a':1,'b':'as df'}" </code></pre> <p>How can I accomplish this?</p>
3
2016-09-01T10:20:57Z
39,270,269
<p>There are two spaces naturally occurring. <code>': '</code> and <code>", "</code>. So I think you can just replace them using <code>replace</code> </p> <pre><code>str({'a': 1, 'b': 'as df'}).replace(": ", ":").replace(", ", ",") </code></pre> <p>Note: To use this solution plz assume, you are not having <code>:</co...
0
2016-09-01T11:25:33Z
[ "python" ]
Getting error on redirect django
39,269,025
<p>What am I trying to do is </p> <p>if a user comes with a slug </p> <p>Case 1</p> <p>'new' I am either creating a new box for him or fetching his existing empty box and redirecting him based on the slug of the box</p> <p>Case 2</p> <p>anything else works fine</p> <p>URL pattern is </p> <pre><code>url(r'^box/ma...
1
2016-09-01T10:25:34Z
39,269,299
<p>In the else condition of the get method, you are trying to return an object instead of a response. You have to return a response like <code>return render(request, template_name, {'box': box, 'drafts': box.drafts})</code> instead of <code>return {'box': box, 'drafts': box.drafts}</code> .</p>
2
2016-09-01T10:38:04Z
[ "python", "django", "django-1.7" ]
Scipy maximum filter for all equal values
39,269,133
<p>I want to use scipy's maximum_filter to detect local maximas, but there is one issue. If the filter applies the function on values that are all equal, it returns all of them as local maximas, but I need to have them the opposite way.</p> <p>An example script:</p> <pre><code>import numpy as np import scipy.ndimage ...
0
2016-09-01T10:30:24Z
39,269,757
<p>You could change your sentence:</p> <pre><code>max_arr = (ones_matrix == sc.maximum_filter(ones_matrix, 3, mode = 'constant')) </code></pre> <p>for this one:</p> <pre><code>max_arr = (ones_matrix != sc.maximum_filter(ones_matrix, 3, mode = 'constant')) </code></pre>
1
2016-09-01T11:00:21Z
[ "python", "scipy", "filtering" ]
uwsgi working with nginx, systemd emperor not working with same configs and setup
39,269,278
<p>The issue here is that everything is configured, and runs without error, and yet I do not know why it is not working. As you'll see I get no app can't load error, I get no errors at all, in fact it's the most complete without errors I've had since I started. And yet, 500 response. Alot of this is here for completene...
0
2016-09-01T10:36:57Z
39,366,640
<p>uWSGI installed by yum and by pip are different. Systemd will probably use one installed by <code>yum</code>. When you're SSH'ing and running uWSGI by yourself, system will use one installed by <code>pip</code> by default.</p> <p>Main difference between that uWSGI versions is: lack of python support in one installe...
0
2016-09-07T09:51:39Z
[ "python", "nginx", "flask", "uwsgi" ]
Update image of a button depending on its previous image
39,269,346
<p>I am trying to program a start/pause button in Tkinter (Pyhton) but the following code doesn't work:</p> <pre><code>def startpause(): if startpause_button.cget('image')=='start_image': startpause_button.config(image=pause_image) else: startpause_button.config(image=start_image) return start_image=ImageTk.Pho...
0
2016-09-01T10:40:00Z
39,270,338
<p><code>startpause_button.cget('image')</code> and <code>'start_image'</code> are two different things, <code>.cget('image')</code> returns the name of the image in a list e.g. <code>('pyimage1',)</code>. This means to compare them you need to take it out of the list with <code>[0]</code> and make sure both variables ...
0
2016-09-01T11:29:10Z
[ "python", "image", "tkinter" ]
Saving record to rails database from python script
39,269,461
<p>I have Rails application with classic forum models like <code>Post</code>, <code>Topic</code>. Then I have python script using <code>praw</code> to download certain posts and topics from Reddit. (I know that I can use ruby version, but lets say we have to use this python script)</p> <p>I'd like to put them directly...
0
2016-09-01T10:45:55Z
39,270,061
<p>So you can use this one:</p> <pre><code>import psycopg2 db_uri = "dbname='template1' user='dbuser' host='localhost' password='dbpass'" with psycopg2.connect(db_uri) as conn: cur = conn.cursor() cur.execute("""SELECT datname from pg_database""") </code></pre>
0
2016-09-01T11:15:23Z
[ "python", "ruby-on-rails" ]
PyBossa vagrant is not working
39,269,483
<p>We are facing issues while configuring PyBossa on following Cloud server.</p> <pre><code>DigitalOcean RAM: 8GB SSD: 80GB OS: UBUNTU 16.04.1 Arch: 64 </code></pre> <p>I am trying to configure it using following commands.</p> <pre><code>apt-get install virtualbox apt-get install vagrant git clone --recursive https:...
0
2016-09-01T10:47:00Z
39,287,492
<p>I've just tested a new installation of PYBOSSA with latest version of VirtualBox (v5.1.4) and Vagrant (v1.8.5) and everything has worked as expected. I don't know exactly what could be wrong, but I run vagrant up in my own laptop, not inside a virtual machine (did you use a virtual machine within Digital Ocean?). Th...
0
2016-09-02T08:14:46Z
[ "python", "vagrant", "pybossa" ]
PySpark Dataframe identify distinct value on one column based on duplicate values in other columns
39,269,564
<p>I have a pyspark dataframe like: where c1,c2,c3,c4,c5,c6 are the columns</p> <blockquote> <pre><code> +----------------------------+ |c1 | c2 | c3 | c4 | c5 | c6 | |----------------------------| | a | x | y | z | g | h | | b | m | f | l | n | o | | c | x | y | z | g | ...
1
2016-09-01T10:51:00Z
39,271,137
<p>This is actually very simple, let's create some data first :</p> <pre><code>schema = ['c1','c2','c3','c4','c5','c6'] rdd = sc.parallelize(["a,x,y,z,g,h","b,x,y,z,l,h","c,x,y,z,g,h","d,x,f,y,g,i","e,x,y,z,g,i"]) \ .map(lambda x : x.split(",")) df = sqlContext.createDataFrame(rdd,schema) # +---+---+---+---+...
3
2016-09-01T12:05:10Z
[ "python", "apache-spark", "dataframe", "pyspark" ]
calling a function before its definition in python
39,269,601
<p>Is there any way to call a function before its definition.</p> <pre><code>def Insert(value): """place value at an available leaf, then bubble up from there""" heap.append(value) BubbleUp(len(heap) - 1) def BubbleUp(position): print 'something' </code></pre> <p>This code shows "unresolved reference...
0
2016-09-01T10:52:44Z
39,269,656
<p>The code here doesn't show anything, least of all an error, because neither of the functions is called. What matters is the location of the call to <code>Insert</code>, and as long as it comes after <code>BubbleUp</code> (and why wouldn't it), there is no issue. Function <em>definitions</em> don't execute the functi...
3
2016-09-01T10:55:42Z
[ "python" ]
python: trouble with Popen FileNotFoundError: [WinError 2]
39,269,675
<p>I've search a while and still can not figure it out... Here's part of my code that went wrong.</p> <pre><code>import subprocess as sp import os cmd_args = [] cmd_args.append('start ') cmd_args.append('/wait ') cmd_args.append(os.path.join(dirpath,filename)) print(cmd_args) child = sp.Popen(cmd_args) </code></pre> ...
0
2016-09-01T10:57:01Z
39,269,884
<p>This is happening because <code>Popen</code> is trying to find the file <code>start</code> instead of the file you want to run.</p> <p>For example, using <code>notepad.exe</code>:</p> <pre><code>&gt;&gt;&gt; import subprocess &gt;&gt;&gt; subprocess.Popen(['C:\\Windows\\System32\\notepad.exe', '/A', 'randomfile.tx...
0
2016-09-01T11:06:06Z
[ "python" ]
FFT normalization with numpy
39,269,804
<p>Just started working with numpy package and started it with the simple task to compute the FFT of the input signal. Here's the code:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt #Some constants L = 128 p = 2 X = 20 x = np.arange(-X/2,X/2,X/L) fft_x = np.linspace(0,128,128, True) fwhl = 1 fwh...
3
2016-09-01T11:02:30Z
39,270,151
<p>Here's a possible solution to your problem:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt from scipy import fft from numpy import log, pi, e # Signal setup Fs = 150 Ts = 1.0 / Fs t = np.arange(0, 1, Ts) ff = 50 fwhl = 1 y = (2 / fwhl) * (log([2]) / pi)**0.5 * e**(-(4 * log([2]) * t**2) / fwhl**...
0
2016-09-01T11:20:17Z
[ "python", "numpy", "fft" ]
FFT normalization with numpy
39,269,804
<p>Just started working with numpy package and started it with the simple task to compute the FFT of the input signal. Here's the code:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt #Some constants L = 128 p = 2 X = 20 x = np.arange(-X/2,X/2,X/L) fft_x = np.linspace(0,128,128, True) fwhl = 1 fwh...
3
2016-09-01T11:02:30Z
39,346,237
<p>I've finally solved my problem. All you need to bond FFT with Fourier integral is to multiply the result of the transform (FFT) by the step (X/L in my case, FFT<em>X/L), it works in general. In my case it's a bit more complex since I have an extra rule for the function to be transformed. I have to be sure that the a...
2
2016-09-06T10:05:01Z
[ "python", "numpy", "fft" ]
Trying to use GET on a weather api but python keeps adding a questionmark
39,269,843
<p>So I wanted to try some things out with a weather api but I can't seem to get it working. When I run the code, the Python interpreter keeps adding a questionmark to my request so I just get a 404 response, not found.</p> <p>This is my code:</p> <pre><code>import requests from requests.auth import HTTPDigestAuth im...
0
2016-09-01T11:04:13Z
39,269,951
<p>Try to use:</p> <pre><code>myResponse = requests.get("{}/api/category/pmp2g/version/2/geotype/point/lon/16.158/lat/58.5812/data.json".format(url)) </code></pre> <p>Currently you're passing the rest of URL as GET params.</p> <p>From <code>requests</code> docs:</p> <pre><code>&gt;&gt;&gt; payload = {'key1': 'value...
0
2016-09-01T11:09:14Z
[ "python", "api", "request" ]
Using Numpy's random.choice to randomly remove item from list
39,270,111
<p>According to the <a href="http://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.random.choice.html" rel="nofollow">http://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.random.choice.html</a>, using the <code>replace = False</code> with Numpy's <code>random.choice</code> method should make the sample...
-1
2016-09-01T11:18:05Z
39,270,341
<p>I ended up defining a function using the <code>random</code> library:</p> <pre><code>import random def sample_without_replacement(arr): random.shuffle(arr) return arr.pop() </code></pre> <p>Its use is shown below:</p> <pre><code>In [51]: arr = range(5) In [52]: number = sample_without_replacement(arr) I...
0
2016-09-01T11:29:18Z
[ "python", "numpy", "random" ]
Using Numpy's random.choice to randomly remove item from list
39,270,111
<p>According to the <a href="http://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.random.choice.html" rel="nofollow">http://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.random.choice.html</a>, using the <code>replace = False</code> with Numpy's <code>random.choice</code> method should make the sample...
-1
2016-09-01T11:18:05Z
39,270,413
<p>As mentioned in one of the comments, np.choice selects with or without replacement, a series of numbers from a sequence. But it does not modify the sequence. </p> <p><strong>Easy alternative</strong></p> <pre><code>arr = range(5) # numbers below will never contain repeated numbers (replace=False) numbers = np.rand...
3
2016-09-01T11:32:19Z
[ "python", "numpy", "random" ]
Unittesting a function containing an infinite loop
39,270,120
<p>Given a function handling requests on a connection the body of the function is a infinite loop:</p> <pre><code>def handle_connection(): # initialize stuff ... while True: # stuff to get the request ... # stuff to handle the request ... </code></pre> <p>How would I unit...
0
2016-09-01T11:18:23Z
39,270,192
<p>You can limit it to run only once while testing, like:</p> <pre><code>a = 0 while True and not a: # do your stuff a = 1 </code></pre> <p>that will not require you to change indentation,</p> <p>or output specific content while running to make sure it gets the right values into the variables while running:<...
1
2016-09-01T11:22:07Z
[ "python", "unit-testing" ]
MySQLdb cursor.execute formatter
39,270,265
<p>I'm working with Python and MySQLdb library. This is part of a code which has been working for a lot of time.</p> <p>I was testing if the code executes correctly in other Ubuntu versions since we are planning a SO upgrade.</p> <p>The following code works fine in Ubuntu 12.04 (our baseline system now with Python 2....
0
2016-09-01T11:25:09Z
39,270,387
<p>The parameters passed need to be iterables i.e. list or tuple. So it should be <code>(path,)</code> and not <code>(path)</code></p> <pre><code>cursor.execute('UPDATE configuration SET value=%s WHERE ' + 'property=\'OUTPUT_PATH\'', (path,)) &gt;&gt;&gt; path = 'hello' &gt;&gt;&gt; a = (path) &gt...
0
2016-09-01T11:31:18Z
[ "python", "mysql", "ubuntu" ]
How to output spark data to a csv file with separate columns?
39,270,584
<p>My code 1st extracts data using a regex and writes that data to a text file (string format). I then tried creating a dataframe out of the contents in the text file so that i can have separate columns which led to an error. (Writing it to a csv file writes the entire thing into just one column). </p> <pre><code>wit...
1
2016-09-01T11:40:17Z
39,274,991
<p>In order to replace "space separated words" into a list of words you'll need to replace:</p> <pre><code>lines1 = new.map(lambda x: (x, )) </code></pre> <p>with</p> <pre><code> lines1 = new.map(lambda line: line.split(' ')) </code></pre> <p>I tried it on my machine, and after executing the following</p> <pre><co...
1
2016-09-01T15:00:57Z
[ "python", "csv", "apache-spark", "pyspark", "apache-spark-sql" ]
Python alter external variable from within function
39,270,728
<p>When I run this it works, but it says </p> <pre><code>"name 'select_place' is assigned to before global declaration" </code></pre> <p>When I get rid of the second global, no comment appears, but as select_place is no longer global it is not readable (if selected) in my last line of code. I'm really new to python,...
1
2016-09-01T11:47:21Z
39,270,864
<p>You need to declare the variable first, additionally the function code can be made clearer:</p> <pre><code>select_place = False def attempt(x): global select_place if location == 'a': select_place = 0 elif location == 'b': select_place = 1 </code></pre> <p>Also, there is no return value...
1
2016-09-01T11:52:58Z
[ "python" ]
Python: Write data to file (excel or txt) with field names
39,270,738
<p>What is the best way (or what would you suggest) to do the following thing in Pyhton:</p> <p>I run several simulations in Python and I want to store some results (each simulation in a new sheet, or new txt file). </p> <p>Example:</p> <pre><code>for model in simmodels: result = simulate(model) speed = result...
-1
2016-09-01T11:47:54Z
39,271,040
<p>Please check link - <a href="https://pymotw.com/2/csv/" rel="nofollow">CSV Module</a> </p> <p>CSV files can be opened in Excel also.</p> <p>Please check the below code :</p> <pre><code>import csv speed = [10,20] dist = [100,200] f = open("out.csv", 'wb') try: writer = csv.writer(f) writer.writerow( ('Spe...
0
2016-09-01T12:00:07Z
[ "python", "export-to-excel" ]
Python: Call for value inside nested class
39,270,798
<p>I'm trying to call for value from class B that is nested in class A and use it in class C. I'm getting AttributeError:</p> <pre><code>class A(): class B(): a = 1 class C(): b = 2 c = B.a + b AttributeError: class B has no attribute 'a' </code></pre> <p>I also tried to call From 'A'...
0
2016-09-01T11:50:20Z
39,270,913
<p>The problem is that the class template (<code>A</code>) is not constructed while you're calling <code>A.B.a</code>. That is, <code>A</code> is not bound yet to a class.</p> <p>Try this workaround:</p> <pre><code>class A(): class B(): a = 1 </code></pre> <p>Now create <code>C</code> separately (<code>A...
1
2016-09-01T11:55:08Z
[ "python" ]
Python: Call for value inside nested class
39,270,798
<p>I'm trying to call for value from class B that is nested in class A and use it in class C. I'm getting AttributeError:</p> <pre><code>class A(): class B(): a = 1 class C(): b = 2 c = B.a + b AttributeError: class B has no attribute 'a' </code></pre> <p>I also tried to call From 'A'...
0
2016-09-01T11:50:20Z
39,272,192
<p>At compile time, the class definition for class A is not complete hence you can not access the classes, variables and methods defined in a parent class inside a nested class.</p> <p>You can try separating the class definitions though as suggested by @Reut Sharabani.</p>
0
2016-09-01T12:58:21Z
[ "python" ]
Python: Call for value inside nested class
39,270,798
<p>I'm trying to call for value from class B that is nested in class A and use it in class C. I'm getting AttributeError:</p> <pre><code>class A(): class B(): a = 1 class C(): b = 2 c = B.a + b AttributeError: class B has no attribute 'a' </code></pre> <p>I also tried to call From 'A'...
0
2016-09-01T11:50:20Z
39,272,724
<p>You can not access the class by its name, while the class definition statement is still executed. </p> <pre><code>class A(object): class B(object): a = 1 class C(object): b = 2 c = A.B.a + b # here class A statement is still executed, there is no A class yet </code></pre> <p>To solve the...
0
2016-09-01T13:23:05Z
[ "python" ]
Python, How to Define a Function whose input is a Variable in the Global Namespace it must then Alter
39,270,841
<p>I have been learning to program in python, and came across this question which I have been struggling to solve. The question is as follows:</p> <p>Write a function f(list, start, end) which takes as arguments a list and two indices and modifies the argument list so that it is equal to the result of the slice expres...
-2
2016-09-01T11:51:54Z
39,271,912
<p>As someone already mentioned in the comments, you should definitely read <a href="http://nedbatchelder.com/text/names.html" rel="nofollow">Facts and myths about Python names and values</a></p> <p>The simple solution to your problem is making a new value and returning it. This will work : </p> <pre><code>def f(this...
0
2016-09-01T12:43:19Z
[ "python", "list", "function" ]
Printing PHP errors with python
39,270,902
<p>I'm using the following to run PHP code with python. If the PHP code located in the file.php encounters an error, I can see the error on my terminal, but I want to have the error on the result variable.</p> <p>How can I catch the error as a string?</p> <pre><code>proc = subprocess.Popen("php /path/file.php", shell...
0
2016-09-01T11:54:50Z
39,271,382
<p>The error messages are usually written to <code>stderr</code>, rather than <code>stdout</code>. If that is the case, you can get it from the corresponding attribute.</p> <pre><code>proc = subprocess.Popen(["php", "/path/file.php"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) out = proc.s...
0
2016-09-01T12:17:41Z
[ "php", "python" ]
how to split this type of string?
39,270,944
<pre><code>row_data=" 'NULL','to_date(to_char(to_date('19700101'',''YYYYMMDD') + interval '1s' * logevent_timestamp_seconds',''YYYY-MM-DD')',''YYYY-MM-DD')','NULL'" row_data_list = row_data.split("\',\'") </code></pre> <p>I want to split the data accordingly into three objects</p> <ul> <li>NULL </li> <li>to_date(to_...
-2
2016-09-01T11:56:13Z
39,271,227
<p>Split the string by <code>,</code>, then trim the <code>'</code> from both sides for every element:</p> <pre><code>&gt;&gt;&gt; row_data=" 'NULL','to_date(to_char(to_date('19700101'',''YYYYMMDD') + interval '1s' * logevent_timestamp_seconds',''YYYY-MM-DD')',''YYYY-MM-DD')','NULL'" &gt;&gt;&gt; row_data_list = list(...
2
2016-09-01T12:09:44Z
[ "python", "string", "parsing", "split" ]
datetime date value not updating into MySQL database in Python correctly (updates the integer 2005 instead)
39,270,990
<p>I am having a weird issue while trying to update a record in my database. Here is the section of the code that doesn't make sense:</p> <pre><code> """code preceeds""" self.NextMail = self.get_NextMail() if self.NextMail != None: """debugging""" print(self.NextMail) ...
1
2016-09-01T11:58:02Z
39,271,267
<p>Try this instead:</p> <pre><code>self.cur.execute("""UPDATE Mailouts SET NextMail=? WHERE StudentID=? """, (self.NextMail, record[0])) </code></pre> <p>The string formatter will convert your <code>self.NextMail</code> to a string so when it passes the query ...
1
2016-09-01T12:12:29Z
[ "python", "mysql", "sql" ]
Trying to combine elements of 2 lists into 1
39,271,077
<p>I've written a function that should randomly pick 2 lists from the first 9 items of a bigger list and randomly pick values from each list and create a new list of the same length. When testing it on it's own the function seems to work properly, but when called as a part of the program it doesn't seem to do anything....
-1
2016-09-01T12:02:07Z
39,276,776
<p>There were 2 very stupid issues in the original code. </p> <ol> <li>The output of the cost function was reading network[x][10], but new cost values were appended rather than replacing the old value, so the output was just putting out the same variable on a loop.</li> <li>The calculate and cost loops were both set t...
0
2016-09-01T16:40:06Z
[ "python", "neural-network", "genetic-algorithm", "evolutionary-algorithm" ]
Pop out the whole dic if element of 1st dic in list is repeated?
39,271,253
<p>Here I have a list of dic, where I want to remove duplicates which is equal to 1st element of dic. Input :</p> <pre><code>data = [ [ [{'color': '1'},{'color': '0'},{'color': '2'},{'color': '1'}], [{'color': '2'},{'color': '3'},{'color': '2'},{'color': '5'}], [{'color': '1'},{'col...
1
2016-09-01T12:11:13Z
39,271,434
<p>No need for all the temporary lists:</p> <pre><code>for item in data: for i,subitem in enumerate(item): item[i] = [item[i][0]] + [dct for dct in item[i][1:] if dct['color'] != item[i][0]['color']] </code></pre> <p>Basically it just iterates through each of the subitems...
1
2016-09-01T12:20:07Z
[ "python", "list", "dictionary" ]
Python boilerpipe installation issue
39,271,350
<p>I am trying to insatll <a href="https://github.com/misja/python-boilerpipe" rel="nofollow">Python Boilerpipe</a> in my Ubuntu 14. It fails with the following error:</p> <pre><code> Traceback (most recent call last): File "setup.py", line 27, in &lt;module&gt; download_jars(datapath=DATAPATH) File "setup.py"...
0
2016-09-01T12:16:23Z
39,286,265
<p>Found the issue, so in the setup.py they are looking for boiler-pipe tar file. And they download it from googlecode, which is not there any more.</p> <pre><code>def download_jars(datapath, version=boilerpipe_version): tgz_url = 'https://boilerpipe.googlecode.com/files/boilerpipe-{0}- bin.tar.gz'.format(version)...
1
2016-09-02T07:06:41Z
[ "python", "ubuntu-14.04", "boilerpipe" ]
Count all files in all folders/subfolders with Python
39,271,372
<p>Which is the <strong>most efficient way</strong> to count all files in all folders and subfolders in Python? I want to use this on Linux systems.</p> <p>Example output:</p> <blockquote> <p>(Path files)</p> <p>/ 2</p> <p>/bin 100</p> <p>/boot 20</p> <p>/boot/efi/EFI/redhat 1</p> <p>....</...
0
2016-09-01T12:17:05Z
39,271,574
<p>You can do it with <code>os.walk()</code>;</p> <pre><code>import os for root, dirs, files in os.walk('/some/path'): if files: print('{0} {1}'.format(root, len(files))) </code></pre> <p>Note that this will also include hidden files, i.e. those that begin with a dot (<code>.</code>).</p>
-1
2016-09-01T12:27:08Z
[ "python", "linux", "file", "count" ]
Count all files in all folders/subfolders with Python
39,271,372
<p>Which is the <strong>most efficient way</strong> to count all files in all folders and subfolders in Python? I want to use this on Linux systems.</p> <p>Example output:</p> <blockquote> <p>(Path files)</p> <p>/ 2</p> <p>/bin 100</p> <p>/boot 20</p> <p>/boot/efi/EFI/redhat 1</p> <p>....</...
0
2016-09-01T12:17:05Z
39,271,575
<pre><code>import os print [(item[0], len(item[2])) for item in os.walk('/path') if item[2]] </code></pre> <p>It returns a list of tuples of folders/subfolders and files count in <code>/path</code>.</p> <p>OR</p> <pre><code>import os for item in os.walk('/path'): if item[2]: print item[0], len(item[2])...
-1
2016-09-01T12:27:09Z
[ "python", "linux", "file", "count" ]
Solving two coupled ODEs by matrix form in Python
39,271,424
<p>I want to solve a coupled system of ODEs in matrix form which has such a form:</p> <blockquote> <p>y'_n = ((m_n)**2) * y_n+(C * y)_n , m'_n=-4*m_n*y_n </p> </blockquote> <p>where <code>C</code> is a matrix, <code>[2 1, -1 3]</code>. </p> <p>On the other hand I want to solve these equations:</p> <blockquot...
0
2016-09-01T12:19:35Z
39,272,763
<p>The initial value to odeint must be an array, not a matrix. Try use <code>y0=np.hstack((y_init, m_init))</code> and put that as the initial value (y0 is the second argument to odeint).</p>
1
2016-09-01T13:24:22Z
[ "python", "scipy", "odeint" ]
Node with as many children as possible python
39,271,546
<p>I want to create a data structure in Python, but since I'm very C oriented. I need a little bit of help.</p> <p>In general, I want to create a Node class which will contain the data, a pointer to a sibling, pointers to the children and a pointer to the parent.</p> <p>this is a way to think of the Node class:</p> ...
0
2016-09-01T12:25:53Z
39,271,663
<p>Python recursion is limited to prevent stack overflowing and infinite recursion. There for recursion without break conditions or counter will be stopped after some-many iterations.</p> <p>Stop creating any more nodes after a number of levels, otherwise python will stop you. <strong>You are activating <code>__init_<...
0
2016-09-01T12:31:03Z
[ "python", "tree" ]
Node with as many children as possible python
39,271,546
<p>I want to create a data structure in Python, but since I'm very C oriented. I need a little bit of help.</p> <p>In general, I want to create a Node class which will contain the data, a pointer to a sibling, pointers to the children and a pointer to the parent.</p> <p>this is a way to think of the Node class:</p> ...
0
2016-09-01T12:25:53Z
39,272,829
<p>Operator overriding in Python is allowed, but using the <code>+</code> operator for something that is not concatenation or summing is frowned upon. A more pythonic implementation would be something like this untested fragment:</p> <pre><code>class Node(object): def __init__(self, parent=None): self.set_...
0
2016-09-01T13:26:47Z
[ "python", "tree" ]
The fastest way to update (partial sum of elements with complex conditions) the pandas dataframe
39,271,564
<p>I try to update a pandas dataframe which has 3 million rows. At the below, I reduced my problem into a more simple problem. In short, it does add values in a cummulative sense. </p> <p>But, this function takes too long time for me like more than 10 hours in a real problem. Is there any room for speeds up? Should I ...
2
2016-09-01T12:26:35Z
39,273,011
<blockquote> <p>Update B column if C is true with sum of A column's elements</p> </blockquote> <pre><code>import numpy as np df['B'] = np.where(df.C, df.A.sum(), 0) </code></pre> <blockquote> <p>After then, if D is also tru then update B with the sum of E (using the comment to the question above)</p> </blockquot...
2
2016-09-01T13:34:02Z
[ "python", "algorithm", "pandas", "complexity-theory" ]
Local server by PythonJS
39,271,645
<p>I downloaded this <a href="https://github.com/PythonJS/pythonjs-demo-server-nodejs" rel="nofollow">demo server</a>. I follow the instruction, so</p> <blockquote> <p>First, git clone this repo, and then run: npm install python-js. Now you are ready to run the server, run: ./run-demo.js and then open your browser ...
1
2016-09-01T12:30:17Z
39,271,719
<p>I don't believe <code>#</code> is a valid character in Javascript. If the <code>run0demo.js</code> file is being delivered to your browser, it certainly won't know what to make of the shebang (<code>#!</code>) line, which is used by the UNIX kernel to determine which executbale should be used to process the file.</p...
1
2016-09-01T12:34:10Z
[ "javascript", "python", "node.js", "server" ]
Local server by PythonJS
39,271,645
<p>I downloaded this <a href="https://github.com/PythonJS/pythonjs-demo-server-nodejs" rel="nofollow">demo server</a>. I follow the instruction, so</p> <blockquote> <p>First, git clone this repo, and then run: npm install python-js. Now you are ready to run the server, run: ./run-demo.js and then open your browser ...
1
2016-09-01T12:30:17Z
39,280,125
<p>If anyone else will be looking for solution, here is it:</p> <pre><code>node run-demo.js </code></pre> <p>Simple as... ;)</p>
0
2016-09-01T20:10:04Z
[ "javascript", "python", "node.js", "server" ]
Why does get_name_by_addr return '' and org_by_addr return None?
39,271,683
<p>I am currently testing one of my classes which sets variables with the help of pygeoip.</p> <p><code>org_by_addr</code> returns <code>None</code> when there is nothing found in the database:</p> <pre><code>seek_org = self._seek_country(ipnum) if seek_org == self._databaseSegments: return None </code></pre> <p...
0
2016-09-01T12:31:57Z
39,272,349
<p>Other than the obvious "variable uniformity", what is the point of changing the NoneType to an empty string? There is a reason why </p> <pre><code>bool ('') == bool (None) == False </code></pre> <p>In my opinion this is a stylistic difference. However, when a package has different return types like this, it can hi...
0
2016-09-01T13:06:12Z
[ "python", "geoip", "maxmind" ]
Unit-testing a boost::python library in python
39,271,702
<p>So I have a shared library created with boost::python (C++). For the C++ functions inside I have unit-tests that check that they are working. Now I would like to use unit-test to see if I implemented the python interface correctly. For this I thought about using using the python package <code>unittest</code>.</p> ...
0
2016-09-01T12:32:58Z
39,272,941
<p>What you could do is run the tests while you are in the root directory in your case <code>project</code>. You can do <code>python Test/test_name.py</code>. Make sure your build library has a <code>__init__.py</code> file</p> <p>The only change to the test is you'd have</p> <pre><code>from build import blah #blah i...
1
2016-09-01T13:31:02Z
[ "python", "c++", "unit-testing", "boost", "out-of-source" ]
What is the minimum number of swaps required to bubble sort an array?
39,271,749
<p>I'm trying to solve the Hackerrank problem <a href="https://www.hackerrank.com/challenges/new-year-chaos?h_r=next-challenge&amp;h_v=zen" rel="nofollow">New Year Chaos</a>:</p> <p><a href="http://i.stack.imgur.com/DBaq0.png" rel="nofollow"><img src="http://i.stack.imgur.com/DBaq0.png" alt="enter image description he...
0
2016-09-01T12:35:56Z
39,272,234
<p>You just have to count the number of necessary swaps in bubble sort. Here is my code that got accepted.</p> <pre><code>T = input() for test in range(T): n = input() l = map(int, raw_input().split()) for i,x in enumerate(l): if x-(i+1) &gt; 2: print "Too chaotic" break ...
1
2016-09-01T13:00:36Z
[ "python", "algorithm", "sorting" ]
Python:Changing path at the end of if statement
39,271,783
<p>My gui currently has a combo box with the the option of selecting four different file locations. Once its selected every file in that directory will be displayed in a listbox:</p> <pre><code>def ComboBox(self, event): current = self.buttonChoice.current() if (current == 0): self.lb.delete(0, END) ...
-1
2016-09-01T12:37:13Z
39,271,910
<p>Indeed you should be using <code>os.chdir</code> and not <code>sys.path.insert</code>.</p> <p>To give you a full answer, one needs to see the rest of your class. More specifically, one must know what there is in <code>self.lb</code> and <code>self.files</code> and the logic filling it.</p>
0
2016-09-01T12:43:17Z
[ "python", "python-3.x", "tkinter", "sys" ]
Python:Changing path at the end of if statement
39,271,783
<p>My gui currently has a combo box with the the option of selecting four different file locations. Once its selected every file in that directory will be displayed in a listbox:</p> <pre><code>def ComboBox(self, event): current = self.buttonChoice.current() if (current == 0): self.lb.delete(0, END) ...
-1
2016-09-01T12:37:13Z
39,271,914
<p>How about this?</p> <pre><code>example_dir = r'C:\Users\****\Desktop\PythonScripts\ResidualCreation' def move_back_dir(a_dir, steps=1): return '\\'.join(a_dir.split('\\')[:-steps]) print(move_back_dir(example_dir)) # -&gt; C:\Users\****\Desktop\PythonScripts print(move_back_dir(example_dir, 2)) # -&gt; C...
1
2016-09-01T12:43:29Z
[ "python", "python-3.x", "tkinter", "sys" ]
Sequence number groupby ID with reset
39,271,859
<p>I'am looking for a way to générate a sequence of numbers that reset on every break</p> <p>Example </p> <pre><code>ID VAR A 0 A 0 A 1 A 1 A 0 A 0 A 1 A 1 B 1 B 1 B 1 B 0 B 0 B 0 B 0 </code></pre> <p>Each time var is at 1 and ID the same as before, you start the counter. but if ID i...
0
2016-09-01T12:40:53Z
39,272,237
<p>You can create an intermediate index, and then <code>groupby</code> this index and <code>ID</code>, cumsumming up on <code>VAR</code>:</p> <pre><code>df['ix'] = df['VAR'].diff().fillna(0).abs().cumsum() df['DESIRED'] = df.groupby(['ID','ix'])['VAR'].cumsum() In [21]: df Out[21]: ID VAR ix DESIRED 0 A 0...
1
2016-09-01T13:00:39Z
[ "python", "pandas" ]
AttributeError on Django
39,271,876
<p>I'm stuck with (I think) a dummy error on Django that I can't find where it's the fault.</p> <p>On "catalog/models.py" I have (it connects to a MySQL database):</p> <pre><code>from django.db import models class Application(models.Model): nameApp = models.CharField(max_length=50) tarification = models.Fore...
0
2016-09-01T12:41:39Z
39,272,899
<p>You're very confused about how to use django-tables. You need to specify one model in the Meta class, then just the <code>fields</code> attribute to add a list of fields from that model, as strings, to display. You can't just specify fields from three arbitrary models.</p>
1
2016-09-01T13:29:19Z
[ "python", "mysql", "django" ]
AttributeError on Django
39,271,876
<p>I'm stuck with (I think) a dummy error on Django that I can't find where it's the fault.</p> <p>On "catalog/models.py" I have (it connects to a MySQL database):</p> <pre><code>from django.db import models class Application(models.Model): nameApp = models.CharField(max_length=50) tarification = models.Fore...
0
2016-09-01T12:41:39Z
39,276,176
<p>As Daniel Roseman mentioned above, the code you might looking for is below, it does not need a new model:</p> <pre><code>import django_tables2 as tables from catalog.models import AppCost, Application, Tarification class AppCostTable(tables.Table): userApp = tables.Column() startTime = tables.Column() ...
1
2016-09-01T16:02:09Z
[ "python", "mysql", "django" ]
Flask send stream as response
39,272,072
<p>I'm trying to "proxy" my Flask server (i will call it Server#01) with another server(Server#02). It's working well except for one thing : when the Server#01 use send_from_directory(), i don't know how to re-send this file. </p> <p><strong>My classic "proxy"</strong></p> <pre><code>result = requests.get(my_path_to_...
0
2016-09-01T12:51:43Z
39,274,008
<p>There should not be any problem with your "classic" proxy other than that it should use <code>stream=True</code>, and specify a <code>chunk_size</code> for <code>response.iter_content()</code>.</p> <p>By default <code>chunk_size</code> is 1 byte, so the streaming will be very inefficient and consequently very slow....
1
2016-09-01T14:17:14Z
[ "python", "redirect", "flask", "proxy" ]
Validate Credit Card Number Using Luhn Algorithm Python
39,272,087
<p>I am trying to implement Luhn algorithm in Python. Here is my code</p> <pre><code>def validate(n): if len(str(n)) &gt; 16: return False else: if len(str(n)) % 2 == 0: for i in str(n[0::2]): digit = int(str(n[i])) * 2 while digit &gt; 9: ...
1
2016-09-01T12:52:29Z
39,272,155
<p>It is hard to tell without the complete error message, but it is likely because you confused in some places where you put the indexing and where you put the string conversion, for example: <code>for i in str(**n[1::2]**)</code> and <code>digit = int(str(**n[i]**)) * 2</code></p> <p>A good way to handle it is to jus...
1
2016-09-01T12:56:18Z
[ "python", "algorithm" ]
load_pem_private_key fails with ecdsa key of size 521
39,272,161
<p>I have the following two ECDSA private key for testing.</p> <pre><code>from cryptography.hazmat.primitives.serialization import load_pem_private_key from cryptography.hazmat.backends import default_backend privateECDSA_openssh521 = b"""-----BEGIN EC PRIVATE KEY----- MIHcAgEBBEIAjn0lSVF6QweS4bjOGP9RHwqxUiTastSE0MV...
2
2016-09-01T12:56:33Z
39,293,047
<p>Have tried to load your data and got the following error string <code>b'bad end line'</code></p> <p>You have six dashes at the end line. Just fix it.</p> <pre><code>&gt;&gt;&gt; privateECDSA_openssh521 = b"""-----BEGIN EC PRIVATE KEY----- ... MIHcAgEBBEIAjn0lSVF6QweS4bjOGP9RHwqxUiTastSE0MVuLtFvkxygZqQ712oZ ... ewM...
2
2016-09-02T12:58:39Z
[ "python", "cryptography" ]
Python - Inner Class Not Found
39,272,195
<p>(Sorry I'm new to Python)</p> <p>I'm running a python django script as follows:</p> <p><code>python3 manage.py test</code></p> <hr> <pre><code>class Command(NoArgsCommand): help = 'Help Test' def handle(self, **options): gs = self.create_goalscorer(1,"Headed") class GoalScorerX(object): ...
0
2016-09-01T12:58:27Z
39,272,262
<p>Inner classes are very rarely useful in Python. Certainly here there is nothing to be gained by making GoalScorerX an inner class. Move it outside; also note that there is no restriction in Python in the number of classes in a file, so it's fine to have them both as top-level classes.</p> <p>(Note, you <em>could</e...
2
2016-09-01T13:01:25Z
[ "python", "django" ]
How to get the IP address of the request to a Heroku app?
39,272,216
<p>Heroku has a routing system to forward requests to the dynos. My application needs to know from where the request came, but it always gets random addresses in a network, probably Heroku's internals.</p> <p>And I see that in the logs, it (Heroku's router) gets my IP address and forwards the request. Is there a way t...
1
2016-09-01T12:59:45Z
39,273,565
<p>Checking Flask's documentation on filtering headers etc., I found that:</p> <pre><code>request.headers['X-Forwarded-For'] </code></pre> <p>is where you'll get the client's real IP address.</p> <hr> <p>From a deleted comment by OP, this article provides a <a href="http://esd.io/blog/flask-apps-heroku-real-ip-spoo...
0
2016-09-01T13:59:40Z
[ "python", "heroku", "flask", "ip-address" ]
Local Maxima with circular window
39,272,267
<p>I am trying to compute a local maxima filter on a matrix, using a circular kernel. The output should be the cells that are local maximas. For each pixel in the input 'data', I need to see if it is a local maximum by a circular window, thus returning a value of 1, otherwise 0.</p> <p>I have this code, built upon ans...
1
2016-09-01T13:01:39Z
39,273,614
<p>The second parameter of <code>sc.filters.generic_filter()</code> should be a function, you are passing it the value returned by the <code>local_maxima(data, np.shape(kernel))</code> call, i.e. a matrix.</p> <p>I'm a bit confused as to what exactly you have done here, but I think you do not need the <code>generic_fi...
1
2016-09-01T14:01:24Z
[ "python", "numpy", "filtering" ]
Local Maxima with circular window
39,272,267
<p>I am trying to compute a local maxima filter on a matrix, using a circular kernel. The output should be the cells that are local maximas. For each pixel in the input 'data', I need to see if it is a local maximum by a circular window, thus returning a value of 1, otherwise 0.</p> <p>I have this code, built upon ans...
1
2016-09-01T13:01:39Z
39,288,450
<p>You can use the code below that return <code>1</code> if the cell visited is a local maximum by a circular window defined by <code>kernel</code> (I just used <code>%pylab</code> to plot the results as an illustration):</p> <pre><code>%pylab import scipy.ndimage as sc data = np.array([(1, 1, 1, 1, 1, 1, 1, 1, 1), (1...
1
2016-09-02T09:03:51Z
[ "python", "numpy", "filtering" ]
pandas row operation to keep only the right most non zero value per row
39,272,271
<p>How to keep the right most number in each row in a dataframe?</p> <pre><code>a = [[1, 2, 0], [1, 3, 0], [1, 0, 0]] df = pd.DataFrame(a, columns=['col1','col2','col3']) df col1 col2 col3 row0 1 2 NaN row1 1 3 0 row2 1 0 0 </code></pre> <p>Then after transformation</p> <p...
2
2016-09-01T13:01:44Z
39,272,962
<p>Here is a workaround that requires the use of helper functions:</p> <pre><code>import pandas as pd #Helper functions def last_number(lst): if all(map(lambda x: x == 0, lst)): return 0 elif lst[-1] != 0: return len(lst)-1 else: return last_number(lst[:-1]) def fill_others(ls...
2
2016-09-01T13:32:00Z
[ "python", "pandas", "dataframe" ]
pandas row operation to keep only the right most non zero value per row
39,272,271
<p>How to keep the right most number in each row in a dataframe?</p> <pre><code>a = [[1, 2, 0], [1, 3, 0], [1, 0, 0]] df = pd.DataFrame(a, columns=['col1','col2','col3']) df col1 col2 col3 row0 1 2 NaN row1 1 3 0 row2 1 0 0 </code></pre> <p>Then after transformation</p> <p...
2
2016-09-01T13:01:44Z
39,273,030
<p>Working at NumPy level, here's one vectorized approach using <a href="http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow"><code>broadcasting</code></a> -</p> <pre><code>np.where(((a!=0).cumsum(1).argmax(1))[:,None] == np.arange(a.shape[1]),a,0) </code></pre> <p>Sample run -</p> <pre><cod...
2
2016-09-01T13:35:03Z
[ "python", "pandas", "dataframe" ]
pandas row operation to keep only the right most non zero value per row
39,272,271
<p>How to keep the right most number in each row in a dataframe?</p> <pre><code>a = [[1, 2, 0], [1, 3, 0], [1, 0, 0]] df = pd.DataFrame(a, columns=['col1','col2','col3']) df col1 col2 col3 row0 1 2 NaN row1 1 3 0 row2 1 0 0 </code></pre> <p>Then after transformation</p> <p...
2
2016-09-01T13:01:44Z
39,273,276
<p>You can fill null values "from the left", and then take the values of the resulting last column:</p> <pre><code>In [49]: df.fillna(axis=0, method='bfill')['col3'] Out[49]: 0 0.0 1 0.0 2 0.0 Name: col3, dtype: float64 </code></pre> <p><strong>Full Example</strong></p> <pre><code>In [50]: a = [[1, 2, None...
1
2016-09-01T13:46:43Z
[ "python", "pandas", "dataframe" ]
Unable to locate popup with Chrome in selenium
39,272,283
<p>Before marking this as duplicate, please read the below points, as i have tried all the possible solutions given :</p> <ol> <li>Tried switching to alert and accepting it &amp; dismissing it. It gets stuck to the accept statement.</li> <li>Tried sending the ENTER/RETURN key to the popup. Nothing happens</li> <li>Tri...
0
2016-09-01T13:02:30Z
39,274,619
<p>Resolved it by upgrading the Chrome Driver to version 2.22, earlier it was 2.21 which is buggy in handling javascript popups.</p>
0
2016-09-01T14:44:29Z
[ "python", "selenium-webdriver", "popup", "selenium-chromedriver" ]
ImportError for a custom SimpleTestCase child using python manage.py test app
39,272,288
<p>I want to use a generic custom TestCase for my_app that is currently running fine. I have the following simplified directory architecture :</p> <pre><code>my_app ├── tests │ ├── __init__.py │ └── test_views │ ├── __init__.py │ ├── custom_test.py │ ├─...
2
2016-09-01T13:02:50Z
39,272,964
<p>put the application name on the left of import:</p> <pre><code>from myapp.tests.test_views.custom_test import CustomTest </code></pre>
2
2016-09-01T13:32:02Z
[ "python", "django", "testing" ]
Derive from C++ base class in SWIGged Python
39,272,413
<p>Note: The corresponding gist is <a href="https://gist.github.com/nschloe/3d8bc8a22a1bea81237c0db2c4af7a1f" rel="nofollow">here</a>.</p> <hr> <p>I have an abstract base class and a method that accepts a pointer to the base class, e.g.,</p> <pre><code>#ifndef MYTEST_HPP #define MYTEST_HPP #include &lt;iostream&g...
1
2016-09-01T13:09:30Z
39,273,055
<p>Got it (via <a href="http://stackoverflow.com/a/9042139/353337">http://stackoverflow.com/a/9042139/353337</a>):</p> <p>Add the director feature to <code>MyBaseClass</code></p> <pre><code>%module(directors="1") mytest %{ #define SWIG_FILE_WITH_INIT #include "mytest.hpp" %} %include &lt;std_shared_ptr.i&gt; %share...
1
2016-09-01T13:36:06Z
[ "python", "c++", "swig" ]
uWSGI-Django spending too much time on poll method
39,272,445
<p>I am using Nginx-uWSGI combination for my Django project, but the performance is sub-par when I compare it with Nginx-Apache-modwsgi combination. Apparently uwsgi was taking about 3-5 seconds to provide response for requests which should be server in about 300-400ms at most.</p> <p>When I ran profiling, I realized ...
1
2016-09-01T13:11:23Z
39,483,433
<p>Finally I fixed the issue. Apparently the issue was that I'd offline compression disabled, but I was using <code>sass</code> files which needed to be transformed into <code>css</code> at runtime. Turns out that was causing a lot of IO. When I enabled offline compression, response time fell back to 200ms.</p>
0
2016-09-14T06:00:15Z
[ "python", "django", "sockets", "nginx", "uwsgi" ]
make np.vectorize return scalar value on scalar input
39,272,465
<p>The following code returns an array instead of expected float value.</p> <pre><code>def f(x): return x+1 f = np.vectorize(f, otypes=[np.float]) &gt;&gt;&gt; f(10.5) array(11.5) </code></pre> <p>Is there a way to force it return simple scalar value if the input is scalar and not the weird array type?</p> <p>I ...
1
2016-09-01T13:12:16Z
39,273,064
<p>The result is technically a scalar as its shape is <code>()</code>. For instance, <code>np.array(11.5)[0]</code> is not a valid operation and will result in an exception. Indeed, the returned results will act as a scalar in most circumstances.</p> <p>eg.</p> <pre><code>x = np.array(11.5) print(x + 1) # prints 12.5...
1
2016-09-01T13:36:36Z
[ "python", "numpy", "numpy-ufunc" ]
Average Time difference in pandas
39,272,470
<p>I am trying to calculate the average time difference, in hours/minutes/seconds, iterating on a field - in my example, for each different ip address. Moreover, a column containing the count of each ip row.</p> <p>My dataframe looks like:</p> <pre><code>date ipAddress 2016-08-08 00:39:00 98.249.24...
2
2016-09-01T13:12:29Z
39,272,783
<p>See <a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html#applying-different-functions-to-dataframe-columns" rel="nofollow">applying different functions to dataframe columns</a>:</p> <pre><code>(df.groupby('ipAddress') .date .agg({'count': 'count', 'avg_time_diff': lambda group: group.so...
1
2016-09-01T13:25:01Z
[ "python", "datetime", "pandas" ]
OpenLabs connector Magento OpenERP 7.0
39,272,641
<p>I'm trying to connect my OpenERP 7.0 to my Magento webSite 1.9.</p> <p>I'm using the connector developed by openLabs <a href="https://github.com/openlabs/magento_integration" rel="nofollow">https://github.com/openlabs/magento_integration</a></p> <p>I follow the instructions of <a href="https://openerp-magento-conn...
0
2016-09-01T13:19:27Z
39,289,839
<p>Ok, So I again restoring my snapshot ...</p> <p>But now, instead using the installer, I downloaded the library manually and install it one by one.</p> <p>So I install, pycountry lib and magento lib. I update the file "magento_.py" and "pycountry.py" of openLab connector to add the path of my library on sys.path.</...
0
2016-09-02T10:10:16Z
[ "python", "magento", "openerp", "magento-1.9", "openerp-7" ]
Wrapping method returning c++ std::array<std::string, 4> in cython
39,272,646
<p>My method returns <code>std::array&lt;std::string, 4&gt;</code> in C++ code. I wrap this code using Cython. I tried to wrap array using memory views. But the result is <code>Invalid base type for memoryview slice: string</code>. So can I wrap my <code>std::array&lt;std::string, 4&gt;</code> to use it in python like ...
2
2016-09-01T13:19:34Z
39,275,275
<p>The easiest way is probably just to copy to a Python list.</p> <p>For the sake of this answer I'm assuming you've wrapped your array similar to <a href="http://stackoverflow.com/a/36402807/4657412">this answer</a> and called it <code>arrstr4</code>. The code then looks something like:</p> <pre><code>def f(): c...
2
2016-09-01T15:13:35Z
[ "python", "c++", "arrays", "string", "cython" ]
Matplotlib contourf with 3 colors
39,272,675
<p>I would like to make a contour plot with 3 distinct colors. So far, my code looks like the following:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt xMin = 0 xMax = 3 xList = np.linspace(xMin, xMax, 10) X1, X2 = np.meshgrid(xList, xList) Z = [] # do some processing with Z # Z now contains 0, 0.5...
0
2016-09-01T13:20:32Z
39,279,279
<p>You can control the colors of a contour plot with the colors option but you might want to use imshow to avoid interpolation between the levels. You create a colormap for imshow with discrete levels using <a href="http://matplotlib.org/api/colors_api.html#matplotlib.colors.ListedColormap" rel="nofollow">ListedColorma...
1
2016-09-01T19:16:17Z
[ "python", "matplotlib" ]
Olympus camera kit bluetooth wakeup
39,272,712
<p>I'm working on a Python script destined to run on a Raspberry Pi which controls an Olympus Air A01 camera remotely via WiFi. The WiFi control works fine but I would also like for the script to be able to turn the camera on remotely.</p> <p>As far as I can tell this can only be done through Bluetooth LE but the OPC ...
0
2016-09-01T13:22:12Z
39,376,042
<p>So I ended up imitating the traffic between the Olympus Android App and the camera while turning it on and I am now able to wake up the camera using Gatttool to send the same values.</p> <p>Here is the minimal Gatttool sequence which wakes up the camera:</p> <pre><code>sudo gatttool -b 90:B6:86:XX:YY:ZZ -I connect...
0
2016-09-07T17:30:38Z
[ "python", "raspberry-pi", "bluetooth-lowenergy", "olympus-camerakit", "olympus-air" ]
Readlines function for an xlsx file works inproper
39,272,775
<p>The goal is sentiment classification. The steps are to open 3 xlsx files, read them, process with gensim.doc2vec methods and classify with SGDClassificator. Just try to repeat <a href="https://districtdatalabs.silvrback.com/modern-methods-for-sentiment-analysis#disqus_thread" rel="nofollow">this code on doc2vec</a>...
0
2016-09-01T13:24:46Z
39,274,171
<p>Generally you can't read Microsoft Excel files as a text files using methods like <code>readlines</code> or <code>read</code>. You should convert files to another format before (good solution is .csv which can be readed by <a href="https://docs.python.org/2/library/csv.html" rel="nofollow">csv</a> module) or use a s...
0
2016-09-01T14:23:52Z
[ "python", "xlsx", "readlines", "doc2vec" ]
Replace a portion of a specific line
39,272,776
<p>I do in python an history file, so that a user puts an URL and after that the program writes the URL in a txt file and on the same link the time that the user enter the website.</p> <p>So my txt is like below:</p> <pre><code>- google.com 14:30 - yahoo.com 17:06 - apple.com 23:02 </code></pre> <p>I want to create ...
0
2016-09-01T13:24:47Z
39,272,840
<p>If you copy the list without the last element will you get the correct answer?</p> <pre><code>def Update(link): for line in fileinput.input("history.txt", inplace=True): newline = line[:-1] return newline </code></pre>
0
2016-09-01T13:27:23Z
[ "python" ]
Replace a portion of a specific line
39,272,776
<p>I do in python an history file, so that a user puts an URL and after that the program writes the URL in a txt file and on the same link the time that the user enter the website.</p> <p>So my txt is like below:</p> <pre><code>- google.com 14:30 - yahoo.com 17:06 - apple.com 23:02 </code></pre> <p>I want to create ...
0
2016-09-01T13:24:47Z
39,273,068
<p>You can use regular expressions.</p> <pre><code>import re def Update(link): for line in fileinput.input("history.txt", inplace=True): localtime = time.asctime(time.localtime(time.time())) print re.sub('\d{2}:\d{2}', localtime, line) </code></pre>
0
2016-09-01T13:36:59Z
[ "python" ]
Is printing defaultdict supposed to be ugly (non human-readable) by default?
39,272,862
<p>Print <code>dict</code> and <code>defaultdict</code>:</p> <pre><code>&gt;&gt;&gt; d = {'key': 'value'} &gt;&gt;&gt; print(d) {'key': 'value'} &gt;&gt;&gt; dd = defaultdict(lambda: 'value') &gt;&gt;&gt; dd['key'] 'value' &gt;&gt;&gt; print(dd) defaultdict(&lt;function &lt;lambda&gt; at 0x7fbd44cb6b70&gt;, {'key': '...
-2
2016-09-01T13:28:02Z
39,272,982
<p><code>repr()</code> output (<code>defaultdict</code> has no <code>__str__</code>, only <code>__repr__</code>) is <em>debugging output</em>. It is not meant to be pretty, it is meant to be <em>functional</em>. It tells you the type, the <code>repr()</code> of the callable that produces the default, and the contents....
2
2016-09-01T13:32:47Z
[ "python" ]
Is printing defaultdict supposed to be ugly (non human-readable) by default?
39,272,862
<p>Print <code>dict</code> and <code>defaultdict</code>:</p> <pre><code>&gt;&gt;&gt; d = {'key': 'value'} &gt;&gt;&gt; print(d) {'key': 'value'} &gt;&gt;&gt; dd = defaultdict(lambda: 'value') &gt;&gt;&gt; dd['key'] 'value' &gt;&gt;&gt; print(dd) defaultdict(&lt;function &lt;lambda&gt; at 0x7fbd44cb6b70&gt;, {'key': '...
-2
2016-09-01T13:28:02Z
39,273,757
<p>There's no way to know what, if anything, the author(s) were thinking or even whether they gave it much consideration at all.</p> <p>For the specific case of nested <code>defaultdict</code>s, as shown your example code:</p> <pre><code>def factory(): return defaultdict(factory) nested_dd = defaultdict(factory) ...
1
2016-09-01T14:07:27Z
[ "python" ]
Creating an naming variables from an array
39,272,885
<p>I have several arrays:</p> <pre><code>foo_1 = [URL, 2, 30] foo_2 = [URL, 4, 1230] foo_3 = [URL, 11, 980] foo_4 = [URL, 6, 316] </code></pre> <p>... I want to create a function that creates variables and renames them like so:</p> <pre><code>foo_1Count = foo_1[2] foo_2Count = foo_2[2] foo_3Count = foo_3[2] foo_4Cou...
-1
2016-09-01T13:28:56Z
39,273,080
<pre><code>URL = 'www.abc.com' foo_1 = [URL, 2, 30] foo_2 = [URL, 4, 1230] foo_3 = [URL, 11, 980] foo_4 = [URL, 6, 316] for i in range(4): globals()['foo_{}Count'.format(i+1)] = globals()['foo_{}'.format(i+1)][2] print foo_4Count # 316 </code></pre>
0
2016-09-01T13:37:33Z
[ "python", "arrays", "list" ]
Creating an naming variables from an array
39,272,885
<p>I have several arrays:</p> <pre><code>foo_1 = [URL, 2, 30] foo_2 = [URL, 4, 1230] foo_3 = [URL, 11, 980] foo_4 = [URL, 6, 316] </code></pre> <p>... I want to create a function that creates variables and renames them like so:</p> <pre><code>foo_1Count = foo_1[2] foo_2Count = foo_2[2] foo_3Count = foo_3[2] foo_4Cou...
-1
2016-09-01T13:28:56Z
39,273,631
<p>If you're asking how to rename (understanding this action like create a new variable and deleting the existing old one) you could manipulate <a href="https://docs.python.org/2/library/functions.html#globals" rel="nofollow">globals</a> like this:</p> <pre><code>if __name__ == "__main__": URL = 'www.abc.com' ...
1
2016-09-01T14:02:14Z
[ "python", "arrays", "list" ]
Creating an naming variables from an array
39,272,885
<p>I have several arrays:</p> <pre><code>foo_1 = [URL, 2, 30] foo_2 = [URL, 4, 1230] foo_3 = [URL, 11, 980] foo_4 = [URL, 6, 316] </code></pre> <p>... I want to create a function that creates variables and renames them like so:</p> <pre><code>foo_1Count = foo_1[2] foo_2Count = foo_2[2] foo_3Count = foo_3[2] foo_4Cou...
-1
2016-09-01T13:28:56Z
39,273,985
<p>Dynamically creating variables is usually not a good idea. Instead, you can just get the attribute from the aggregating list object directly. It's even shorter than <code>foo_1Count</code>:</p> <pre><code>&gt;&gt;&gt; foo_1 = ["URL", 2, 30] &gt;&gt;&gt; foo_1[2] 30 </code></pre> <p>But you might not want to memori...
0
2016-09-01T14:16:20Z
[ "python", "arrays", "list" ]
Timed method in Python
39,272,925
<p>How do I have a part of python script(only a method, the whole script runs in 24/7) run everyday at a set-time, exactly at every 20th minutes? Like 12:20, 12:40, 13:00 in every hour.</p> <p>I can not use cron, I tried periodic execution but that is not as accurate as I would... It depends from the script starting t...
2
2016-09-01T13:30:24Z
39,273,308
<p>You can either put calling this method in a loop, which would sleep for some time </p> <pre><code>import time while True: sleep(1200) my_function() </code></pre> <p>and be triggered once in a while, you could use datetime to compare current timestamp and set next executions.</p> <pre><code>import datetime...
0
2016-09-01T13:48:04Z
[ "python" ]
Timed method in Python
39,272,925
<p>How do I have a part of python script(only a method, the whole script runs in 24/7) run everyday at a set-time, exactly at every 20th minutes? Like 12:20, 12:40, 13:00 in every hour.</p> <p>I can not use cron, I tried periodic execution but that is not as accurate as I would... It depends from the script starting t...
2
2016-09-01T13:30:24Z
39,273,486
<p>Use for example redis for that and <a href="https://github.com/ui/rq-scheduler" rel="nofollow">rq-scheduler</a> package. You can schedule tasks with specific time. So you can run first script, save to the variable starting time, calculate starting time + 20 mins and if your current script will end, at the end you wi...
0
2016-09-01T13:56:06Z
[ "python" ]