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 listlengths 1 5 |
|---|---|---|---|---|---|---|---|---|---|
Google Calendar API event free/busy | 38,283,217 | <p>There was a previous question about this (<a href="http://stackoverflow.com/questions/12918917/google-calendar-api-event-free-busy-blocking-data">Google Calendar API Event Free/Busy/Blocking Data</a>) asking "...how to tell if an event a calendar should be considered an event that blocks time." I have the same quest... | 0 | 2016-07-09T15:12:47Z | 38,340,836 | <p>It looks like that the transparency field only appears on all-day events and only when it's set to "transparent". I used the following criteria to find all-day events that are marked as "busy". </p>
<pre><code>for event in events:
if 'transparency' not in event and not event['start'].get('dateTime'):
</code></pre... | 0 | 2016-07-13T00:26:15Z | [
"python",
"google-calendar"
] |
python: urllib object cannot be accessed after the first for loop | 38,283,227 | <p>The following codes does not work well since 'line1' does not exist. However, 'line' does exist. It seems that 'fhand' changed after the first for loop. If we comment out the first for loop, then the codes work very well.</p>
<p>Could anyone explain why this happens? </p>
<pre><code>import urllib
fhand = urllib.ur... | 0 | 2016-07-09T15:13:47Z | 38,283,299 | <p><code>urllib.urlopen</code> returns a generetor, which is exhausted by the first loop.</p>
<p>Either convert <code>fhand</code> to a list<br>
(<code>fhand = list(urllib.urlopen('http://www.py4inf.com/code/romeo.txt'))</code>), or do everything inside the first loop (ie have only a single loop).</p>
| 0 | 2016-07-09T15:20:49Z | [
"python",
"urllib2",
"urllib"
] |
How do I store Information when I run the program | 38,283,274 | <p>How do I store Information in python when I run it?</p>
<p>Here is the code:</p>
<pre><code>list = [""]
plist = raw_input("What do you want to append: ")
list.append(plist)
print list
</code></pre>
<p>When it's run:</p>
<pre><code>What do you wan't to append: Hello
Hello
</code></pre>
<p>Now let's say I left to... | 0 | 2016-07-09T15:18:31Z | 38,283,317 | <p>To make information persistent across executions, you should save it to a file. This is standard with programming languages - variables are stored in the memory (RAM), and are reset on each execution.</p>
<p>On top of that, in your example, you are explicitly creating an empty list to append to. To append to a list... | 5 | 2016-07-09T15:23:28Z | [
"python"
] |
How do I store Information when I run the program | 38,283,274 | <p>How do I store Information in python when I run it?</p>
<p>Here is the code:</p>
<pre><code>list = [""]
plist = raw_input("What do you want to append: ")
list.append(plist)
print list
</code></pre>
<p>When it's run:</p>
<pre><code>What do you wan't to append: Hello
Hello
</code></pre>
<p>Now let's say I left to... | 0 | 2016-07-09T15:18:31Z | 38,283,332 | <p>When you restart the program, all of the variables from the previous program are dumped or 'forgotten' by Python. If you want the program to keep asking what word you want to append until you quit, you can use a <code>for</code> loop or <code>while</code> loop. For example, you could just write:</p>
<pre><code>for ... | 1 | 2016-07-09T15:25:06Z | [
"python"
] |
combining huge h5 files with multiple datasets into one with odo | 38,283,279 | <p>I have a a number of large (13GB+ in size) h5 files, each h5 file has two datasets that were created with pandas: </p>
<pre><code>df.to_hdf('name_of_file_to_save', 'key_1',table=True)
df.to_hdf('name_of_file_to_save', 'key_2', table=True) # saved to the same h5 file as above
</code></pre>
<p>I've seen a post here... | 3 | 2016-07-09T15:18:49Z | 38,288,213 | <p>For this specific case it was a matter of having too many columns, which exceeded the memory limit allocated for that piece of information. The solution is to load the dataframe and transpose it. </p>
| 3 | 2016-07-10T03:09:47Z | [
"python",
"pandas",
"hdf5",
"pytables"
] |
Getting, Storing, Setting and Modifying Transform Attributes through PyMel | 38,283,329 | <p>I'm working on something that gets and stores the transforms of an object moved by the user and then allows the user to click a button to return to the values set by the user.</p>
<p>So far, I have figured out how to get the attribute, and set it. However, I can only get and set once. Is there a way to do this mu... | 0 | 2016-07-09T15:24:27Z | 38,294,875 | <p>You aren't passing the variable <code>gx</code> so <code>SetPressed()</code> will fail if you run it as written(it might work sporadically if you tried executing the <code>gx = ...</code> line directly in the listener before running the whole thing -- but it's going to be erratic). You'll need to provide a value i... | 0 | 2016-07-10T17:56:26Z | [
"python",
"maya",
"pymel"
] |
Can threading.Event's set() or clear() function fail in any case | 38,283,349 | <p>Is there any case where <code>threading.Event</code>'s <code>set()</code> or <code>clear()</code> can fail, viz. calling <code>set()</code> again without <code>clear()</code>, etc.</p>
<p>Right now I am adding <code>try-except</code> block around all <code>set()</code> and <code>clear()</code> calls.</p>
<p>In <a ... | 1 | 2016-07-09T15:26:34Z | 38,283,484 | <p>TLDR: No.</p>
<p>The truthiness of <code>Event</code> is a simple boolean, guarded by a lock.</p>
<pre><code>class Event:
"""Class implementing event objects.
Events manage a flag that can be set to true with the set() method and reset
to false with the clear() method. The wait() method blocks until t... | 1 | 2016-07-09T15:41:59Z | [
"python",
"multithreading",
"python-2.7"
] |
How to create an interactive text menu in Python? | 38,283,475 | <p>I'm not sure what to call it. I want to know how to make one of those menus where you use the arrow keys to highlight your options and press enter to accept it.</p>
| -4 | 2016-07-09T15:40:12Z | 38,283,645 | <p>I think you mean <code>Combobox</code>.
Here is a short example based on <a href="http://stackoverflow.com/questions/22775095/pyqt-how-to-set-combobox-items-be-checkable">this</a> and <a href="https://wiki.python.org/moin/PyQt" rel="nofollow">PyQt</a>:</p>
<pre><code>from PyQt4 import QtGui, QtCore
import sys
clas... | 0 | 2016-07-09T15:58:20Z | [
"python"
] |
Using Django Templates with User Authentication | 38,283,526 | <p>I have a site which I am using user authentication to limit access to.
I am using <code>django-allauth</code> to handle social media authentication, but want to limit access to <code>staff</code> accounts only (set in the django admin panel).</p>
<p>I want to use a template as a header (bootstrap, nav bar etc.) wit... | 1 | 2016-07-09T15:46:17Z | 38,294,035 | <p>Turns out I should have used</p>
<pre><code>{% extends "inventory/header.html" %}
</code></pre>
<p>instead of </p>
<pre><code>{% include "inventory/header.html" %}
</code></pre>
<p>Doh!</p>
| 0 | 2016-07-10T16:25:29Z | [
"python",
"django",
"templates",
"django-allauth"
] |
How to format JSON data when writing to a file | 38,283,596 | <p>I'm trying to get this api request and have it formatted when I dump it into the JSON file. Whenever I do, its all one string and very hard to read. I've tried adding the indent but it didn't do anything. I can provide the API key if needed. </p>
<pre><code>import json, requests
url = "http://api.openweathermap.or... | 1 | 2016-07-09T15:52:01Z | 38,283,735 | <p>There are a couple problems with your code, I think.</p>
<p>First of all, it's considered better form to write unrelated imports on separate lines instead of separated by a comma. We generally only use commas when doing things like <code>from module import thing1, thing2</code>.</p>
<p>I'm assuming you left <code>... | 4 | 2016-07-09T16:09:08Z | [
"python",
"json",
"api",
"formatting",
"request"
] |
How to format JSON data when writing to a file | 38,283,596 | <p>I'm trying to get this api request and have it formatted when I dump it into the JSON file. Whenever I do, its all one string and very hard to read. I've tried adding the indent but it didn't do anything. I can provide the API key if needed. </p>
<pre><code>import json, requests
url = "http://api.openweathermap.or... | 1 | 2016-07-09T15:52:01Z | 38,283,816 | <p><code>response.json()</code> is your friend here. I have tested the code below ( of course with different API endpoint returning json data) and it works fine for me and let me know if this worked for you.</p>
<pre><code>with open('weather.json', 'w') as outfile:
json.dump(response.json(), outfile, indent=4) # ... | 0 | 2016-07-09T16:20:12Z | [
"python",
"json",
"api",
"formatting",
"request"
] |
Error while installing Flask in virtualenv - windows | 38,283,599 | <p>i just set my first virtualenv and wanted to work with flask in it
i used the activate script in windows, like it says in every tutorial out there
****i think i should note that i have installed flask out of the virtual env.</p>
<p>i ran the command</p>
<pre><code>pip install flask
Collecting flask
Using cache... | 0 | 2016-07-09T15:52:16Z | 38,289,960 | <p>This has driven me crazy too. Follow these steps:
1) system wide <code>pip uninstall flask</code>
2) create virtualenv in your app folder
3) DON'T USE pip, instead <code>easy_install flask</code>
4) Then use pip to install all other dependencies.</p>
<p>This worked for me, I don't know why but it solved what was a ... | 0 | 2016-07-10T08:13:24Z | [
"python",
"windows",
"flask",
"virtualenv"
] |
Error while installing Flask in virtualenv - windows | 38,283,599 | <p>i just set my first virtualenv and wanted to work with flask in it
i used the activate script in windows, like it says in every tutorial out there
****i think i should note that i have installed flask out of the virtual env.</p>
<p>i ran the command</p>
<pre><code>pip install flask
Collecting flask
Using cache... | 0 | 2016-07-09T15:52:16Z | 38,504,584 | <p>I had this problem. Downgrade your version of Setuptools.
In your virtualenv:</p>
<pre><code>pip install setuptools==21.2.1
pip install flask
</code></pre>
<p>This should do it. The problem is something to do with syntax that I don't get. </p>
| 3 | 2016-07-21T12:42:14Z | [
"python",
"windows",
"flask",
"virtualenv"
] |
Selenium and Python using If statement | 38,283,609 | <p>I am trying understand why an <code>if else</code> isn't working using Selenium and Python. I have tried several different variations, but I believe this should work and stubbornly, maybe blindly, keep coming back to it.</p>
<p>example:</p>
<pre><code> if (self.driver.find_element_by_class_name('product')).text... | 0 | 2016-07-09T15:53:40Z | 38,286,191 | <p>try this following code.</p>
<pre><code>if "FEATURED PRODUCTS" in self.driver.find_element_by_class_name('product').text
</code></pre>
<p>If this isn't working try to debug that. something white space creates an issue. however given the assert statement is passing, following should work. </p>
| 0 | 2016-07-09T20:43:21Z | [
"python",
"selenium"
] |
Proper way to quit/exit a PyQt program | 38,283,705 | <p>I have a script which has a login screen and if the cancel button is pressed, I want to exit the application altogether. I have tried 3 ways:</p>
<ol>
<li>sys.exit()</li>
<li>QApplication.quit()</li>
<li>QCoreApplication.instance().quit() </li>
</ol>
<p>Only number 1 works. The other two makes the dialog box whi... | 0 | 2016-07-09T16:05:23Z | 38,283,750 | <p>Instead of using <code>QApplication.quit()</code>, since you defined <code>app = QApplication(sys.argv)</code>, you could just write <code>app.quit()</code>, and that should work!</p>
<p>Something unrelated but might be helpful: I think it would be easier if you put the login check at the beginning of the <code>__i... | 0 | 2016-07-09T16:11:21Z | [
"python",
"pyqt",
"pyqt5"
] |
Proper way to quit/exit a PyQt program | 38,283,705 | <p>I have a script which has a login screen and if the cancel button is pressed, I want to exit the application altogether. I have tried 3 ways:</p>
<ol>
<li>sys.exit()</li>
<li>QApplication.quit()</li>
<li>QCoreApplication.instance().quit() </li>
</ol>
<p>Only number 1 works. The other two makes the dialog box whi... | 0 | 2016-07-09T16:05:23Z | 38,285,497 | <p>Calling <code>QCoreApplication.quit()</code> is the same as calling <code>QCoreApplication.exit(0)</code>. To quote from the <a href="http://doc.qt.io/qt-5/qcoreapplication.html#exit" rel="nofollow">qt docs</a>:</p>
<blockquote>
<p>After this function has been called, the application leaves the main
event loop ... | 2 | 2016-07-09T19:21:20Z | [
"python",
"pyqt",
"pyqt5"
] |
Python loop through list and return "out of sequence" values | 38,283,710 | <p>Consider this list:</p>
<pre><code>dates = [
('2015-02-03', 'name1'),
('2015-02-04', 'nameg'),
('2015-02-04', 'name5'),
('2015-02-05', 'nameh'),
('1929-03-12', 'name4'),
('2023-07-01', 'name7'),
('2015-02-07', 'name0'),
('2015-02-08', 'nameh'),
('2015-02-15', 'namex'),
('2015... | 0 | 2016-07-09T16:05:53Z | 38,285,372 | <p>This will establish a new anchor_date for you if the current date is greater than the last good date. </p>
<pre><code>import arrow
out_of_order = []
anchor_date = arrow.get(dates[0][0])
for dt, name in dates:
if arrow.get(dt) < anchor_date:
out_of_order.append((dt, name))
else:
anchor_date = arrow.... | 0 | 2016-07-09T19:08:01Z | [
"python",
"list",
"loops"
] |
Python loop through list and return "out of sequence" values | 38,283,710 | <p>Consider this list:</p>
<pre><code>dates = [
('2015-02-03', 'name1'),
('2015-02-04', 'nameg'),
('2015-02-04', 'name5'),
('2015-02-05', 'nameh'),
('1929-03-12', 'name4'),
('2023-07-01', 'name7'),
('2015-02-07', 'name0'),
('2015-02-08', 'nameh'),
('2015-02-15', 'namex'),
('2015... | 0 | 2016-07-09T16:05:53Z | 38,290,885 | <h2>Short answer, general solution</h2>
<p>Using my <a href="http://stackoverflow.com/a/38337443/1916449">answer to the "Longest increasing subsequence" question</a>, this could be implemented simply as:</p>
<pre><code>def out_of_sequence(seq):
indices = set(longest_subsequence(seq, 'weak', key=lambda x: x[0], inde... | 1 | 2016-07-10T10:24:35Z | [
"python",
"list",
"loops"
] |
Redirect to different views from the homepage - django | 38,283,789 | <p>I'm writing a django app and I would like to do something like this: in my homepage there are different options you can reach with links.</p>
<p>This is my homepage.html</p>
<pre><code><title>Homepage</title>
<body>
<li> <a href = "{% url 'options1' %} " > Options1 </a> </li... | -1 | 2016-07-09T16:16:49Z | 38,283,831 | <p>Django provides <code>reverse</code> function, for this purpose. You can pass url name to it, and function will return url path: </p>
<pre><code>from django.core.urlresolvers import reverse
def homepage (request):
HttpResponseRedirect(reverse('option1'))
</code></pre>
<p>Also you can hardcode your url withou... | 0 | 2016-07-09T16:21:38Z | [
"python",
"django",
"django-views"
] |
Redirect to different views from the homepage - django | 38,283,789 | <p>I'm writing a django app and I would like to do something like this: in my homepage there are different options you can reach with links.</p>
<p>This is my homepage.html</p>
<pre><code><title>Homepage</title>
<body>
<li> <a href = "{% url 'options1' %} " > Options1 </a> </li... | -1 | 2016-07-09T16:16:49Z | 38,284,448 | <p>In each view render a template and create an html template for each option. The Polls app from the <a href="https://docs.djangoproject.com/en/1.7/intro/tutorial01/" rel="nofollow">Django tutorial</a> is useful as a reference example. </p>
<p>A redirect is for when you have an old url and want links to it to point t... | 1 | 2016-07-09T17:30:16Z | [
"python",
"django",
"django-views"
] |
how to create new column based on multiple columns with a function | 38,283,897 | <p>This question is following up to my questionabout <a href="http://stackoverflow.com/questions/38282659/linear-interpolation-between-two-data-points/38282695?noredirect=1#comment63984980_38282695this">linear interpolation between two data points</a></p>
<p>I built following function from it:</p>
<pre><code>def inte... | 0 | 2016-07-09T16:28:49Z | 38,283,997 | <p>You need to vectorize your self defined function with <code>np.vectorize</code>, since the function parameters are accepted as pandas Series:</p>
<pre><code>inter = np.vectorize(inter)
df['new'] = inter(df['on95'],df['on102.5'])
df
on95 on102.5 on105 new
#Index
# 1 5... | 2 | 2016-07-09T16:41:05Z | [
"python",
"function",
"pandas",
"vectorization"
] |
python how to get instance variables of a class to another class? | 38,283,944 | <p>I have two classes. When I create an instance in the first one would like to work with its attributes in my second class.</p>
<pre><code>class Dog(object):
def __init__(self, number):
self.number_of_tricks = number
class Statistics(object):
def get_number_of_tricks(self):
return Dog(Max.num... | 1 | 2016-07-09T16:34:37Z | 38,283,993 | <p>Initialize your <code>Statistics</code> with that instance of <code>Dog</code>, then the attributes of that <code>Dog</code> will be accessible from <code>Statistics</code>: </p>
<pre><code>class Dog(object):
def __init__(self, number):
self.number_of_tricks = number
class Statistics(object):
def ... | 4 | 2016-07-09T16:40:38Z | [
"python",
"class",
"oop",
"variables"
] |
How to speed up a repeated execution of exec()? | 38,284,045 | <p>I have the following code:</p>
<pre><code>for k in pool:
x = []
y = []
try:
exec(pool[k])
except Exception as e:
...
do_something(x)
do_something_else(y)
</code></pre>
<p>where <code>pool[k]</code> is python code that will eventually append items to <code>x</code> and <code... | 0 | 2016-07-09T16:46:17Z | 38,284,277 | <p>If you really need to execute some code in such manner, use compile() to prepare it.</p>
<p>I.e. do not pass raw Python code into exec but compiled object. Use compile() on your codes before to make them Python byte compiled objects.</p>
<p>But still, it'll make more sense to write a function that will perform wha... | 2 | 2016-07-09T17:11:34Z | [
"python",
"exec",
"pypy"
] |
Mongodb difference to previous entry | 38,284,079 | <p>I have a mongodb collection that contain the following:</p>
<pre><code>[{'price': 0.74881,,
'date': '20160601 00:00:00.134',
'instrument': 'EUR/GBP'},
{'price': 0.76881,
'date': '20160601 00:00:00.135',
'instrument': 'EUR/GBP'},
{'price': 0.78881,
'date': '20160601 00:00:00.300',
'instrument': 'EUR/GB... | 1 | 2016-07-09T16:49:23Z | 38,285,052 | <p>It appears that you want to process your records in a pairwise fashion.
This function is from the <a href="https://docs.python.org/2.7/library/itertools.html" rel="nofollow">itertools documentation</a> itself.</p>
<pre><code>from itertools import tee, izip
def pairwise(iterable):
"s -> (s0,s1), (s1,s2), (s2, ... | 1 | 2016-07-09T18:35:39Z | [
"python",
"mongodb",
"pymongo"
] |
Clean API results to get the headlines of news articles? | 38,284,094 | <p>I have been having trouble finding a way to pull out specific text info from the Guardian API for my dissertation. I have managed to get all my text onto Python but how do you then clean it to get say, just the headlines of the news articles?</p>
<p>This is a snippet of the API result that I want to pull out info f... | -2 | 2016-07-09T16:50:42Z | 38,284,184 | <p>Hoping the OP adds the used code to the question.</p>
<p>One solution in python is, that whatever you get (from the methods offered by the requests module?) will be either already deeply nested structures you can well index into or you can easily map it to these structures (via json.loads(the_string_you_displayed).... | -1 | 2016-07-09T17:01:41Z | [
"python",
"api",
"news"
] |
How do you find percents of a variable in Python? | 38,284,177 | <p>I can't figure out how you find a percentage of a variable in Python. This is the example of the code:</p>
<pre><code>money =546.97
week=0
for i in range(10):
money=money+16
money=money+(5% money)
print('you have',money,'dollars')
week=week+4
print(week)
i = i +1
</code></pre>
<p>It always just... | -1 | 2016-07-09T17:00:57Z | 38,284,306 | <p>The <code>%</code> symbol in python is the <a href="http://stackoverflow.com/questions/12754680/modulo-operator-in-python">modulo operator</a> in python. </p>
<p>It doesn't compute a percent, rather <code>x % y</code> determines the remainder after dividing <code>x</code> by <code>y</code>. </p>
<p>If you want the... | 0 | 2016-07-09T17:15:00Z | [
"python"
] |
How do you find percents of a variable in Python? | 38,284,177 | <p>I can't figure out how you find a percentage of a variable in Python. This is the example of the code:</p>
<pre><code>money =546.97
week=0
for i in range(10):
money=money+16
money=money+(5% money)
print('you have',money,'dollars')
week=week+4
print(week)
i = i +1
</code></pre>
<p>It always just... | -1 | 2016-07-09T17:00:57Z | 38,284,307 | <p>While the <code>%</code> symbol means "percent of" to us, it means <em>an entirely different thing</em> to Python.</p>
<p>In Python, <code>%</code> is the <a href="https://en.wikipedia.org/wiki/Modulo_operation" rel="nofollow"><em>modulo operator</em></a>. Takes the thing on the left, divides it by the thing on the... | 4 | 2016-07-09T17:15:05Z | [
"python"
] |
Getting n-th ranked column IDs per row of a dataframe - Python/Pandas | 38,284,233 | <p>I am trying to find a method for finding the nth ranked value and returning the column name. So for example, given a data-frame: </p>
<pre><code>df = pd.DataFrame(np.random.randn(5, 4), columns = list('ABCD'))
# Return column name of "MAX" value, compared to other columns in any particular row.
df['MAX1_NAMES'] =... | 2 | 2016-07-09T17:07:04Z | 38,284,400 | <p>You can apply an <code>argsort()</code> per row, reverse the index and pick up the one at the second position:</p>
<pre><code>df['MAX2_NAMES'] = df.iloc[:,:4].apply(lambda r: r.index[r.argsort()[::-1][1]], axis = 1)
df
# A B C D MAX1_NAMES MAX2_NAMES
#0 -0.728424 -0.76... | 3 | 2016-07-09T17:24:45Z | [
"python",
"python-2.7",
"pandas",
"ranking"
] |
Getting n-th ranked column IDs per row of a dataframe - Python/Pandas | 38,284,233 | <p>I am trying to find a method for finding the nth ranked value and returning the column name. So for example, given a data-frame: </p>
<pre><code>df = pd.DataFrame(np.random.randn(5, 4), columns = list('ABCD'))
# Return column name of "MAX" value, compared to other columns in any particular row.
df['MAX1_NAMES'] =... | 2 | 2016-07-09T17:07:04Z | 38,284,893 | <p>You are looking to perform the ranking for a particular rank <code>n</code> only, so I would like to suggest <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.argpartition.html" rel="nofollow"><code>np.argpartition</code></a> that would get sorted indices just for the highest n-ranked entries at eac... | 3 | 2016-07-09T18:18:16Z | [
"python",
"python-2.7",
"pandas",
"ranking"
] |
Extension not added to file name after saving | 38,284,412 | <p>I get files with no extension after saving them, although I give them extensions by <code>filetypes</code> <i>option</i> in my program. I can only do it using <code>defaultextension</code> <i>option</i>, but I want to let user decide to choose an extension without messing with code. Plus, when I use <code>defaultext... | -3 | 2016-07-09T17:26:17Z | 38,286,100 | <p>idlelib.IOBinding (.iomenu in 3.6) has this code that works to add .py or .txt when not explicitly entered. I don't know/remember what "TEXT" is for, but since the code works, I leave it alone.</p>
<pre><code> filetypes = [
("Python files", "*.py *.pyw", "TEXT"),
("Text files", "*.txt", "TEXT"),... | 0 | 2016-07-09T20:31:04Z | [
"python",
"python-3.x",
"tkinter",
"savefiledialog",
"filedialog"
] |
Extension not added to file name after saving | 38,284,412 | <p>I get files with no extension after saving them, although I give them extensions by <code>filetypes</code> <i>option</i> in my program. I can only do it using <code>defaultextension</code> <i>option</i>, but I want to let user decide to choose an extension without messing with code. Plus, when I use <code>defaultext... | -3 | 2016-07-09T17:26:17Z | 38,287,448 | <p>Great! I myself found the answer just by adding <code>defaultextension="*.*"</code> <i>option</i>. Thanks for everyone for trying to answer my question, although none of them solved my problem, <i>in fact</i>, most of them only downvoted my question <i>without</i> explaining their reasons. Well, it was not my fault ... | 2 | 2016-07-10T00:15:19Z | [
"python",
"python-3.x",
"tkinter",
"savefiledialog",
"filedialog"
] |
How do you convert a string representation of a UTF-16 byte sequence to UTF-8 in Python? | 38,284,486 | <p>I'm creating a program that will read .rtf files. .rtf files are encoded in ASCII, but represent non-ASCII characters with an escape sequence followed by two numbers representing a UTF-16 double-byte. For example, "ããã¯æ¥æ¬èªã" is represented as "\'82\'b1\'82\'ea\'82\'cd\'93\'fa\'96\'7b\'8c\'ea\'81\'42".</... | 1 | 2016-07-09T17:34:57Z | 38,285,486 | <p>You appear to have <a href="https://en.wikipedia.org/wiki/Shift_JIS" rel="nofollow"><em>Shift-JIS</em> data</a> inside <a href="https://en.wikipedia.org/wiki/Rich_Text_Format#Character_encoding" rel="nofollow">code-page escapes</a>; you can extract the marked-up bytes and decode those:</p>
<pre><code>import re
from... | 0 | 2016-07-09T19:20:14Z | [
"python",
"encoding",
"utf-8",
"utf-16"
] |
How to get articles for last 2 days only in Python? | 38,284,503 | <p>I write a program in Python3 to parse news. After the parsing every article has a date object (ex. (2016, 7, 9)). </p>
<p>What is the best way to save only articles that were published for the last 2 days only?</p>
| 1 | 2016-07-09T17:37:24Z | 38,284,849 | <p>If it is a list of articles:</p>
<pre><code>import arrow
threshold = arrow.now().replace(days=-2)
filtered_articles = [a for a in articles if arrow.get(a['article_date')) > threshold]
</code></pre>
| 0 | 2016-07-09T18:14:25Z | [
"python",
"date",
"python-3.x",
"datetime"
] |
How to get articles for last 2 days only in Python? | 38,284,503 | <p>I write a program in Python3 to parse news. After the parsing every article has a date object (ex. (2016, 7, 9)). </p>
<p>What is the best way to save only articles that were published for the last 2 days only?</p>
| 1 | 2016-07-09T17:37:24Z | 38,296,180 | <p>As you said this was your answer:</p>
<pre><code>import datetime
datetime.datetime.utcnow().date() - datetime.timedelta(days=2)
</code></pre>
| 1 | 2016-07-10T20:24:22Z | [
"python",
"date",
"python-3.x",
"datetime"
] |
Attributes of super object | 38,284,511 | <pre><code>class Mysuper(object):
def aaa(self):
print "In Superclass"
class Mysub(Mysuper):
def aaa(self):
ss = super(Mysub, self)
print dir(ss) , type(ss)
print ss.__dict__
ss.aaa()
print "In Subclass"
>>> ob = Mysub()
>>> ob.aaa()
['__cla... | 2 | 2016-07-09T17:37:53Z | 38,284,698 | <p>When you pass self to super(Mysub,self) you are binding self as an instance of the superclass. If you omit self you won't see aaa as an attribute.</p>
| -2 | 2016-07-09T17:56:55Z | [
"python",
"python-2.7",
"super"
] |
Attributes of super object | 38,284,511 | <pre><code>class Mysuper(object):
def aaa(self):
print "In Superclass"
class Mysub(Mysuper):
def aaa(self):
ss = super(Mysub, self)
print dir(ss) , type(ss)
print ss.__dict__
ss.aaa()
print "In Subclass"
>>> ob = Mysub()
>>> ob.aaa()
['__cla... | 2 | 2016-07-09T17:37:53Z | 38,284,712 | <p>Methods are contained in the class dict, not the instance dict.</p>
<p>See this:</p>
<pre><code>class C:
def method(self): pass
print(C().__dict__) # prints {}
print(C.__dict__) # prints a lot of stuff plus the method
</code></pre>
<p>The inheritance does not play a role here.</p>
<p>Using <code>super</co... | 0 | 2016-07-09T17:58:35Z | [
"python",
"python-2.7",
"super"
] |
Where is Sphinx search REST API documented | 38,284,555 | <p>Documentation generated by Sphinx and hosted on Web, includes search interface.</p>
<p>For example, when searching official Python documentation for term "popen", this url is constructed:</p>
<p><a href="https://docs.python.org/3/search.html?q=popen&check_keywords=yes&area=default" rel="nofollow">https://d... | 0 | 2016-07-09T17:42:13Z | 38,293,687 | <p>By default, Sphinx (the documentation tool) does not provide a REST API for search.</p>
<p>The search execution is completely JavaScript-based.</p>
<ul>
<li><p>When you build a Sphinx project, a JavaScript file that contains the search index will be created (<code>searchindex.js</code>).</p></li>
<li><p>When you e... | 2 | 2016-07-10T15:50:31Z | [
"python",
"search",
"documentation",
"python-sphinx"
] |
Pandas Compute conditional count for groupby including zero counts | 38,284,609 | <p>Is there a way in Pandas to count the number of rows containing a specific value based on a group including those groups containing no value?</p>
<p>For instance if I have this dataframe:</p>
<pre><code>dd = pd.DataFrame({'g1':['a','b','a','b','a','b','c','c'],\
'g2':['x','x','z','y','y','z','x','z'],\
'cond':['i'... | 1 | 2016-07-09T17:47:00Z | 38,284,660 | <p>Just <code>apply</code> a function that counts the js.</p>
<pre><code>>>> dd.groupby(['g1', 'g2']).cond.apply(lambda g: (g=='j').sum())
g1 g2
a x 0
y 1
z 0
b x 0
y 1
z 1
c x 0
z 0
Name: cond, dtype: int64
</code></pre>
| 2 | 2016-07-09T17:52:36Z | [
"python",
"pandas"
] |
Speed up pandas dataframe lookup | 38,284,615 | <p>I have a pandas data frame with zip codes, city, state and country of ~ 600,000 locations. Let's call it <strong>my_df</strong></p>
<p>I'd like to look up the corresponding <strong><em>longitude</em></strong> and <strong><em>latitude</em></strong> for each of these locations. Thankfully, there is a database for <a ... | 2 | 2016-07-09T17:47:31Z | 38,284,860 | <p>Using <a href="http://pandas.pydata.org/pandas-docs/stable/merging.html" rel="nofollow"><code>merge()</code></a> will be a lot faster than calling a function on every row. Make sure the field types match and strings are stripped:</p>
<pre><code>#Â prepare your dataframe
data['organization_zip'] = data.organization_... | 2 | 2016-07-09T18:15:08Z | [
"python",
"pandas",
"dataframe"
] |
Iterating through DataFrame rows to create new column while referencing other rows | 38,284,638 | <p>I have a large dataframe I am working with that contains fudamental data for equities. Below are images of the head and tail of the dataframe (data). It has data for each security and each year from 2005-2015. Note the 'calendardate' column. </p>
<p>My goal is to go to each row, take the 'revenueusd' datapoint and ... | 1 | 2016-07-09T17:50:10Z | 38,285,605 | <p>There is a nice function called <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.pct_change.html" rel="nofollow">Series.pct_change</a> for your purpose. You could do it for example like this:</p>
<pre><code>import pandas as pd
data = pd.read_csv("data.csv", index_col=0)
data.groupby("tic... | 1 | 2016-07-09T19:33:01Z | [
"python",
"pandas"
] |
Iterating through DataFrame rows to create new column while referencing other rows | 38,284,638 | <p>I have a large dataframe I am working with that contains fudamental data for equities. Below are images of the head and tail of the dataframe (data). It has data for each security and each year from 2005-2015. Note the 'calendardate' column. </p>
<p>My goal is to go to each row, take the 'revenueusd' datapoint and ... | 1 | 2016-07-09T17:50:10Z | 38,285,806 | <p>Starting with this: </p>
<pre><code> ticker ticker.1 calendardate revenueusd gp rnd
0 A A 2015-12-31 4038000000 2041000000 330000000
1 AA AA 2015-12-31 22534000000 4465000000 238000000
2 A A 2014-12-31 403800000 204100000 330000000
3 AA ... | 0 | 2016-07-09T19:54:17Z | [
"python",
"pandas"
] |
Using django subdomain and it says localhost does not belong to the domain example.com | 38,284,661 | <p>I'm using the Django Package <a href="https://django-subdomains.readthedocs.io/en/latest/" rel="nofollow">django-subdomain</a>, and I don't think I've configured it correctly.</p>
<p>Now that I'm trying to load data from the DB I'm getting this error in the terminal</p>
<blockquote>
<p>The host localhost:8000 do... | 0 | 2016-07-09T17:52:52Z | 38,284,807 | <blockquote>
<p>What do I need to change so I can access the BlogListView at
<a href="http://localhost:8000/posts/2016/07/09" rel="nofollow">http://localhost:8000/posts/2016/07/09</a> ? Or better via the actual
subdomain of blog.creativeflow.com</p>
</blockquote>
<p>I've set up my linode with subdomains pointed ... | 0 | 2016-07-09T18:08:53Z | [
"python",
"django",
"subdomain",
"django-subdomains"
] |
Using django subdomain and it says localhost does not belong to the domain example.com | 38,284,661 | <p>I'm using the Django Package <a href="https://django-subdomains.readthedocs.io/en/latest/" rel="nofollow">django-subdomain</a>, and I don't think I've configured it correctly.</p>
<p>Now that I'm trying to load data from the DB I'm getting this error in the terminal</p>
<blockquote>
<p>The host localhost:8000 do... | 0 | 2016-07-09T17:52:52Z | 38,284,830 | <p>Why have you set <code>SITE_ID = 1</code>?</p>
<p>From the Django Docs for <a href="https://docs.djangoproject.com/en/1.9/ref/contrib/sites/#enabling-the-sites-framework" rel="nofollow"><code>django.contrib.site</code></a>:</p>
<blockquote>
<p>django.contrib.sites registers a post_migrate signal handler which cr... | 1 | 2016-07-09T18:11:49Z | [
"python",
"django",
"subdomain",
"django-subdomains"
] |
Using django subdomain and it says localhost does not belong to the domain example.com | 38,284,661 | <p>I'm using the Django Package <a href="https://django-subdomains.readthedocs.io/en/latest/" rel="nofollow">django-subdomain</a>, and I don't think I've configured it correctly.</p>
<p>Now that I'm trying to load data from the DB I'm getting this error in the terminal</p>
<blockquote>
<p>The host localhost:8000 do... | 0 | 2016-07-09T17:52:52Z | 38,286,905 | <p><code>SITE = 1</code> will correspond to the default <code>example.com</code> set by <a href="https://docs.djangoproject.com/en/1.9/ref/contrib/sites/#enabling-the-sites-framework" rel="nofollow"><code>django.contrib.site</code></a>.</p>
<blockquote>
<p>django.contrib.sites registers a post_migrate signal handler... | 1 | 2016-07-09T22:33:01Z | [
"python",
"django",
"subdomain",
"django-subdomains"
] |
django apache configuration with WSGIDaemonProcess not working | 38,284,814 | <p><strong>Updated Question</strong></p>
<pre><code>[Mon Jul 18 09:20:10.517873 2016] [:error] [pid 30316:tid 139756302964480] [remote 122.164.94.99:48261] Traceback (most recent call last):
[Mon Jul 18 09:20:10.518005 2016] [:error] [pid 30316:tid 139756302964480] [remote 122.164.94.99:48261] File "/var/www/rent/Re... | 2 | 2016-07-09T18:09:16Z | 38,434,628 | <pre><code>WSGIDaemonProcess Rent python-path=/var/www/rent:/root/.virtualenvs/rent/lib/python2.7/site-packages
</code></pre>
<p>This is the most likely cause of the problem. You have created a virtualenv inside the super user's home folder. But that folder is unlikely to be accessible to apache. Any user's home fo... | 3 | 2016-07-18T10:39:53Z | [
"python",
"django",
"apache",
"wsgi"
] |
Python, change interpreter what use system. From anaconda2/bin/python2.7 to /usr/bin/pyhon2.7 | 38,284,874 | <p>Hello, stackoverflow I need help again :)</p>
<p>How to change default system python interpreter?
<b>OR</b>
How to solve this? --></p>
<p><a href="http://i.stack.imgur.com/PiS2t.png" rel="nofollow"><img src="http://i.stack.imgur.com/PiS2t.png" alt="enter image description here"></a></p>
<p>Problem comes after in... | 0 | 2016-07-09T18:16:40Z | 38,285,948 | <p>Edit your <code>.bashrc</code> file to add PYTHONPATH or comment the paths added by anaconda then it will work.</p>
| 0 | 2016-07-09T20:11:52Z | [
"python",
"python-2.7",
"anaconda",
"interpreter",
"conda"
] |
removing the \n when extracted the program | 38,284,946 | <p>I made a regex for the number of followers on twitter and i have to extract it</p>
<pre><code> # Create a regex for number of followers
(
(\s|-) # first separator
\d\d # first 2 digits
, # separator
\d\d\d # hundred thousands
, # se... | 0 | 2016-07-09T18:23:41Z | 38,284,993 | <pre><code>>>> lst = ['\n90,280,191', '\n84,239,451', '\n79,215,375', '\n75,925,596', '\n62,869,696']
>>> [i.replace('\n', '') for i in lst]
# ['90,280,191', '84,239,451', '79,215,375', '75,925,596', '62,869,696']
</code></pre>
<p>If you provide more information about the original strings you are app... | 2 | 2016-07-09T18:28:19Z | [
"python",
"python-3.x"
] |
removing the \n when extracted the program | 38,284,946 | <p>I made a regex for the number of followers on twitter and i have to extract it</p>
<pre><code> # Create a regex for number of followers
(
(\s|-) # first separator
\d\d # first 2 digits
, # separator
\d\d\d # hundred thousands
, # se... | 0 | 2016-07-09T18:23:41Z | 38,285,033 | <p>You can use <code>replace</code> or <code>lstrip</code>. </p>
<pre><code>>>>lst = ['\n90,280,191', '\n84,239,451', '\n79,215,375', '\n75,925,596', '\n62,869,696']
>>>[i.lstrip('\n') for i in lst]
['90,280,191', '84,239,451', '79,215,375', '75,925,596', '62,869,696']
</code></pre>
| 2 | 2016-07-09T18:33:27Z | [
"python",
"python-3.x"
] |
How to you import a class into the interactive window for pycharm or Visual Studio | 38,285,022 | <p>I am new to Python and I just began learning classes. I wrote this very simple block of code. It runs fine from the IDE but I can't seem to get it to run in the interactive console. I've tried using the interactive console in Visual Studio and PyCharm. The file is called <strong>monster.py</strong> in the projec... | 0 | 2016-07-09T18:32:39Z | 38,285,083 | <p>Maybe what you want to do is to initialise those parameters in the initiator. Try</p>
<pre><code>class Monster(object):
def __init__(self):
self.hit_points = 1
self.color = "yellow"
self.weapon = "sword"
mo = Monster()
print(mo.color)
</code></pre>
| 0 | 2016-07-09T18:39:37Z | [
"python",
"visual-studio",
"pycharm"
] |
How to you import a class into the interactive window for pycharm or Visual Studio | 38,285,022 | <p>I am new to Python and I just began learning classes. I wrote this very simple block of code. It runs fine from the IDE but I can't seem to get it to run in the interactive console. I've tried using the interactive console in Visual Studio and PyCharm. The file is called <strong>monster.py</strong> in the projec... | 0 | 2016-07-09T18:32:39Z | 38,295,138 | <p>You're only importing a specific name from monster.py into the namespace of your interpreter. </p>
<p>When you do the import, the code you've written does get executed, but <code>mo</code> is not available in your namespace and you therefore can't use it. </p>
<p>You could try one of the following:</p>
<p>1) Crea... | 0 | 2016-07-10T18:24:09Z | [
"python",
"visual-studio",
"pycharm"
] |
Django model variable relative to another | 38,285,072 | <p><br>I am a Django newbie trying a new project, and I am stuck :(</p>
<p>I have a videos Model</p>
<pre><code>class Video(models.Model):
link = models.CharField(max_length=200)
title = models.CharField(max_length=200)
</code></pre>
<p>and I would like to generate a simple link to the video's thumbnail for ... | 0 | 2016-07-09T18:37:53Z | 38,285,147 | <p>Setting properties on Django models is one way to go. If you do not need to store this image URL in the database, you could do the following: </p>
<pre><code>class Video(models.Model):
link = models.CharField(max_length=200)
title = models.CharField(max_length=200)
@property
def image_source(self):... | 2 | 2016-07-09T18:45:53Z | [
"python",
"html",
"django",
"jinja2"
] |
pyspark Dataframe API cast('timestamp') does not work on timestamp strings | 38,285,099 | <p>I have data that looks like this:</p>
<pre><code>{"id":1,"createdAt":"2016-07-01T16:37:41-0400"}
{"id":2,"createdAt":"2016-07-01T16:37:41-0700"}
{"id":3,"createdAt":"2016-07-01T16:37:41-0400"}
{"id":4,"createdAt":"2016-07-01T16:37:41-0700"}
{"id":5,"createdAt":"2016-07-06T09:48Z"}
{"id":6,"createdAt":"2016-07-06T09... | 1 | 2016-07-09T18:41:48Z | 38,309,629 | <p>In order to simply cast a string column to a timestamp, the string column must be properly formatted.</p>
<p>To retrieve the "createdAt" column as a timestamp, you can write the UDF function that would convert the string </p>
<blockquote>
<p>"2016-07-01T16:37:41-0400"</p>
</blockquote>
<p>to </p>
<blockquote>
... | 3 | 2016-07-11T14:33:48Z | [
"python",
"apache-spark",
"pyspark",
"apache-spark-sql",
"pyspark-sql"
] |
Dictionary update sequence element #10 has length 0; 2 is required | 38,285,190 | <p>The same error has been repeating endlessly :( </p>
<p>Code:</p>
<pre><code>def query():
query = input("Please insert your query here:\n")
with open("TroubleShootingKey.txt") as f:
dictq = dict(x.rstrip().split(None, 1)for x in f)
print(dictq)
found =False
for k, v in dictq.... | 1 | 2016-07-09T18:50:07Z | 38,285,267 | <p>That's probably because you reached the end of the file.</p>
<p>You can add a </p>
<pre><code>try:
...
except ValueError:
...
</code></pre>
<p>block around your code to just stop in this case (with a <code>break</code>).</p>
| 0 | 2016-07-09T18:58:18Z | [
"python",
"dictionary"
] |
Dictionary update sequence element #10 has length 0; 2 is required | 38,285,190 | <p>The same error has been repeating endlessly :( </p>
<p>Code:</p>
<pre><code>def query():
query = input("Please insert your query here:\n")
with open("TroubleShootingKey.txt") as f:
dictq = dict(x.rstrip().split(None, 1)for x in f)
print(dictq)
found =False
for k, v in dictq.... | 1 | 2016-07-09T18:50:07Z | 38,285,962 | <p><code>split(None, 1)</code> on an empty string will return an empty list, which could be the reason for this error. You could reproduce the error with following snippet:</p>
<pre><code>dict(x.split(None, 1) for x in [''])
</code></pre>
<p>A potential fix is to avoid calling <code>split()</code> on empty lines</p>
... | 0 | 2016-07-09T20:13:34Z | [
"python",
"dictionary"
] |
Python tutorial says that "5" * 5 should be 55, but my result is '55555' | 38,285,195 | <p>I'm following Xerotic's Python guide on HF and it tells me to do:</p>
<pre><code>x = 5
y = "5"
print x * 5
print y * 5
</code></pre>
<p>and it should print:</p>
<pre><code>25
55
</code></pre>
<p>However mine prints <code>'55555'</code>. What is happening here?</p>
| -2 | 2016-07-09T18:50:19Z | 38,285,214 | <p><code>x</code> is an int<br>
<code>y</code> is a string<br>
<code>x*5</code> is a numerical computation, so it is <code>25</code><br>
<code>y*5</code> means repeat the string <code>y</code> 5 times</p>
<p>What you want is:</p>
<pre><code>print x*5
print y*2
</code></pre>
| 2 | 2016-07-09T18:53:07Z | [
"python"
] |
Why does creating a list from a generator object take so long? | 38,285,201 | <p>I was interested in when I should use a generator in a function, and when I should just use a list, so I did some tests with filter and list comprehensions. </p>
<pre><code>>>> timeit.timeit('list(filter(lambda x: x%10, range(10)))')
3.281250655069016
>>> timeit.timeit('[i for i in range(10) if i%... | 3 | 2016-07-09T18:51:18Z | 38,285,697 | <p>I will begin by answering your last question, yes you should use comprehensive list rather than <code>list</code> + <code>filter</code> combination since it's more pythonic and as you showed it, more efficient.</p>
<p>As for why it is more efficient, you have function call overhead (of the <code>lambda</code>) in t... | -1 | 2016-07-09T19:43:27Z | [
"python",
"list",
"python-3.x",
"generator",
"timeit"
] |
Why does creating a list from a generator object take so long? | 38,285,201 | <p>I was interested in when I should use a generator in a function, and when I should just use a list, so I did some tests with filter and list comprehensions. </p>
<pre><code>>>> timeit.timeit('list(filter(lambda x: x%10, range(10)))')
3.281250655069016
>>> timeit.timeit('[i for i in range(10) if i%... | 3 | 2016-07-09T18:51:18Z | 38,285,754 | <p>There are two different issues that is evident from question</p>
<ol>
<li>From the minuscule timing data for the standalone filter call it is evident that you are using Python 3.x, as filter returns a generator like object. So theoretically nothing actually happens.<a href="https://docs.python.org/3/library/functio... | 3 | 2016-07-09T19:49:06Z | [
"python",
"list",
"python-3.x",
"generator",
"timeit"
] |
Python slice/subset array with different data type | 38,285,208 | <p>As a result from a simulation, I have a bunch of csv files divided by spaces. See example below:</p>
<pre><code>Time Node Type Metric 1 Metric 2
0.00 1 Abcd 1234.5678 9012.3456
0.00 1 Efgh 1234.5678 9012.3456
0.01 2 Abcd 1234.5678 9012.3456
0.01 2 Efgh 1234.5678 9012.3456
0.02 3 Abc... | 0 | 2016-07-09T18:52:09Z | 38,285,350 | <p>You probably want to use <a href="http://pandas.pydata.org/" rel="nofollow">pandas</a> instead of numpy. Assuming you have a tab-delimited file, the code would be as simple as this:</p>
<pre><code>import pandas as pd
data = pd.read_csv("abc.csv", delimiter="\t")
result = data.groupby("Node").mean()
</code></pre>
<... | 2 | 2016-07-09T19:05:27Z | [
"python",
"arrays",
"numpy",
"slice"
] |
Python slice/subset array with different data type | 38,285,208 | <p>As a result from a simulation, I have a bunch of csv files divided by spaces. See example below:</p>
<pre><code>Time Node Type Metric 1 Metric 2
0.00 1 Abcd 1234.5678 9012.3456
0.00 1 Efgh 1234.5678 9012.3456
0.01 2 Abcd 1234.5678 9012.3456
0.01 2 Efgh 1234.5678 9012.3456
0.02 3 Abc... | 0 | 2016-07-09T18:52:09Z | 38,285,617 | <p>My attempt using <a href="https://docs.python.org/2.7/library/itertools.html" rel="nofollow">itertools</a>. Basically this takes advantage of the groupby method which allows you to group consecutive pieces of data together by a lambda function. If you sort the dataset before using groupby, then you can essentially g... | 0 | 2016-07-09T19:34:35Z | [
"python",
"arrays",
"numpy",
"slice"
] |
Python slice/subset array with different data type | 38,285,208 | <p>As a result from a simulation, I have a bunch of csv files divided by spaces. See example below:</p>
<pre><code>Time Node Type Metric 1 Metric 2
0.00 1 Abcd 1234.5678 9012.3456
0.00 1 Efgh 1234.5678 9012.3456
0.01 2 Abcd 1234.5678 9012.3456
0.01 2 Efgh 1234.5678 9012.3456
0.02 3 Abc... | 0 | 2016-07-09T18:52:09Z | 38,286,329 | <p>If I put your sample in a file, I can load it into a structured <code>numpy</code> array with</p>
<pre><code>In [45]: names=['Time','Node','Type','Metric_1','Metric_2']
In [46]: data = np.genfromtxt('stack38285208.txt', dtype=None, names=names, skip_header=1)
In [47]: data
Out[47]:
array([(0.0, 1, b'Abcd', 1234.56... | 1 | 2016-07-09T21:02:45Z | [
"python",
"arrays",
"numpy",
"slice"
] |
A list that contains itself - why resetting its element affects the 1st level? | 38,285,323 | <p>This feels almost like a "Russell's paradox" waiting to happen... :-). I'm pretty sure this must be a well known issue but I didn't find a lot of discussions about this.</p>
<p>I'm on python3. I realize that a list can contain itself</p>
<pre><code>s = [1, 2, 3]
s[1] = s
</code></pre>
<p>which results with</p>
<... | 1 | 2016-07-09T19:02:53Z | 38,285,367 | <p>You didn't set the object with that ID to 5. You set a certain element of the list to 5. The list indices can be thought of as "labels" or "pointers" that point to objects. In setting <code>s[1] = 5</code>, you didn't change the object <code>s[1]</code> previously referred to; you changed what <code>s[1]</code> p... | 4 | 2016-07-09T19:07:21Z | [
"python"
] |
How to predict stock price for the next day with Python? | 38,285,345 | <p>I'm trying to predict the stock price for the next day of my serie, but I don't know how to "query" my model. Here is my code in Python:</p>
<pre><code># Define my period
d1 = datetime.datetime(2016,1,1)
d2 = datetime.datetime(2016,7,1)
# Get the data
df = web.DataReader("GOOG", 'yahoo', d1, d2)
# Calculate some i... | 0 | 2016-07-09T19:05:13Z | 38,285,431 | <pre><code>model.predict(X_test)
</code></pre>
<p>Will do the job. And that's straight out of the wonderful <a href="http://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LinearRegression.html#sklearn.linear_model.LinearRegression.predict" rel="nofollow">documentation</a>
Do your basic reading before ... | 0 | 2016-07-09T19:14:04Z | [
"python",
"machine-learning",
"sklearn-pandas"
] |
How to predict stock price for the next day with Python? | 38,285,345 | <p>I'm trying to predict the stock price for the next day of my serie, but I don't know how to "query" my model. Here is my code in Python:</p>
<pre><code># Define my period
d1 = datetime.datetime(2016,1,1)
d2 = datetime.datetime(2016,7,1)
# Get the data
df = web.DataReader("GOOG", 'yahoo', d1, d2)
# Calculate some i... | 0 | 2016-07-09T19:05:13Z | 38,285,454 | <p>You can use Predict() that is part of sklearn. And calculate the X-value for the "next" day (you need to define this through your own algorithm).</p>
<p>Directly from the sklearn library source code:</p>
<pre><code>def predict(self, X):
"""Predict using the linear model
Parameters
---------... | 1 | 2016-07-09T19:17:20Z | [
"python",
"machine-learning",
"sklearn-pandas"
] |
RAPT: Whats wrong with my JDK? | 38,285,458 | <p>Well, as the question says I have some trouble getting RAPT to run the command:</p>
<pre><code>python android.py installsdk
</code></pre>
<p>It usually returns:</p>
<pre><code> I'm compiling a short test program, to see if you have a working JDK
on your system.
I was unable to use javac to compile a test fil... | 1 | 2016-07-09T19:17:29Z | 38,285,539 | <p>JDK is java development tool kit
JRE is java run-time environment only.
If you have compiled java jar or class file jre is good enough, you do not require jdk.</p>
<p>but if you want to compile java source code you will require javac that comes with JDK.</p>
<p>Try setting JAVA_HOME environment variable.</p>
| 0 | 2016-07-09T19:25:47Z | [
"android",
"python",
"python-2.7",
"pygame",
"renpy"
] |
Why is this thread in python not stopping? | 38,285,480 | <p>I am trying to setup a simple http server in python in a thread. </p>
<pre><code>class MyHandler(SimpleHTTPRequestHandler):
def do_GET(self):
if self.path == '/shutdown':
print 'Got shutdown request'
self.server.running = False
self.send_response(200)
class Server():
... | 0 | 2016-07-09T19:19:41Z | 38,285,871 | <p>In your code you have your own request processing loop (instead of using <code>HTTPServer.serve_forever()</code>). Yet, you call <code>HTTPServer.shutdown()</code> whose job is to tell the <code>serve_forever()</code> loop to stop and wait until it does. Since <code>serve_forever()</code> wasn't even started, <code>... | 2 | 2016-07-09T20:01:50Z | [
"python",
"multithreading",
"python-multithreading",
"simplehttpserver"
] |
Python QtCore.Qt.Key assign several keys to single function | 38,285,569 | <p>Seeking the way how to assign several keys to single function.</p>
<pre><code>def keyPressEvent(self, e):
if e.key() == QtCore.Qt.Key_Enter, Key_Return, Key_Escape:
pass
</code></pre>
<p>Thanks for help in advance!</p>
| -1 | 2016-07-09T19:29:11Z | 38,299,957 | <p>You can use the <code>in</code> operator to test if the key is in a list or tuple. Like this:</p>
<pre><code>def keyPressEvent(self, e):
if e.key() in (QtCore.Qt.Key_Enter, QtCore.Qt.Key_Return, QtCore.Qt.Key_Escape):
pass
</code></pre>
| 0 | 2016-07-11T05:52:17Z | [
"python",
"pyqt4"
] |
Why is str.strip() so much faster than str.strip(' ')? | 38,285,654 | <p>Splitting on white-space can be done in two ways with <strong><a href="https://docs.python.org/3/library/stdtypes.html#str.strip" rel="nofollow"><code>str.strip</code></a></strong>. You can either issue a call with no arguments, <code>str.strip()</code>, which defaults to using a white-space delimiter or explicitly ... | 30 | 2016-07-09T19:38:30Z | 38,285,655 | <h3>In a tl;dr fashion:</h3>
<p>This is because two functions exist for the two different cases, as can be seen in <a href="https://github.com/python/cpython/blob/master/Objects/unicodeobject.c#L12260" rel="nofollow"><code>unicode_strip</code></a>; <code>do_strip</code> and <code>_PyUnicodeXStrip</code> the first exec... | 32 | 2016-07-09T19:38:30Z | [
"python",
"string",
"performance",
"python-3.x",
"python-internals"
] |
Why is str.strip() so much faster than str.strip(' ')? | 38,285,654 | <p>Splitting on white-space can be done in two ways with <strong><a href="https://docs.python.org/3/library/stdtypes.html#str.strip" rel="nofollow"><code>str.strip</code></a></strong>. You can either issue a call with no arguments, <code>str.strip()</code>, which defaults to using a white-space delimiter or explicitly ... | 30 | 2016-07-09T19:38:30Z | 38,286,494 | <p>For the reasons explained in @Jims answer the same behavior is found in <code>bytes</code> objects:</p>
<pre><code>b = bytes(" " * 100 + "a" + " " * 100, encoding='ascii')
b.strip() # takes 427ns
b.strip(b' ') # takes 1.2μs
</code></pre>
<p>For <code>bytearray</code> objects this doesn't happen, the functi... | 7 | 2016-07-09T21:24:51Z | [
"python",
"string",
"performance",
"python-3.x",
"python-internals"
] |
Insert element to list based on previous and next elements | 38,285,679 | <p>I'm trying to add a new tuple to a list of tuples (sorted by first element in tuple), where the new tuple contains elements from both the previous and the next element in the list. </p>
<p>Example:</p>
<pre><code>oldList = [(3, 10), (4, 7), (5,5)]
newList = [(3, 10), (4, 10), (4, 7), (5, 7), (5, 5)]
</code></pre>
... | 9 | 2016-07-09T19:41:19Z | 38,285,773 | <pre><code>oldList = [(3, 10), (4, 7), (5,5)]
def pair(lst):
# create two iterators
it1, it2 = iter(lst), iter(lst)
# move second to the second tuple
next(it2)
for ele in it1:
# yield original
yield ele
# yield first ele from next and first from current
yield (next(i... | 8 | 2016-07-09T19:51:09Z | [
"python",
"list"
] |
Insert element to list based on previous and next elements | 38,285,679 | <p>I'm trying to add a new tuple to a list of tuples (sorted by first element in tuple), where the new tuple contains elements from both the previous and the next element in the list. </p>
<p>Example:</p>
<pre><code>oldList = [(3, 10), (4, 7), (5,5)]
newList = [(3, 10), (4, 10), (4, 7), (5, 7), (5, 5)]
</code></pre>
... | 9 | 2016-07-09T19:41:19Z | 38,285,800 | <p>You can use a list comprehension and <code>itertools.chain()</code>:</p>
<pre><code>>>> list(chain.from_iterable([((i, j), (x, j)) for (i, j), (x, y) in zip(oldList, oldList[1:])])) + oldList[-1:]
[(3, 10), (4, 10), (4, 7), (5, 7), (5, 5)]
</code></pre>
| 5 | 2016-07-09T19:53:36Z | [
"python",
"list"
] |
Insert element to list based on previous and next elements | 38,285,679 | <p>I'm trying to add a new tuple to a list of tuples (sorted by first element in tuple), where the new tuple contains elements from both the previous and the next element in the list. </p>
<p>Example:</p>
<pre><code>oldList = [(3, 10), (4, 7), (5,5)]
newList = [(3, 10), (4, 10), (4, 7), (5, 7), (5, 5)]
</code></pre>
... | 9 | 2016-07-09T19:41:19Z | 38,286,605 | <p>Not being a big fan of one-liners (or complexity) myself, I will propose a very explicit and readable (which is usually a good thing!) solution to your problem.</p>
<p>So, <strong>in a very simplistic approach</strong>, you could do this:</p>
<pre><code>def insertElements(oldList):
"""
Return a new list, a... | 3 | 2016-07-09T21:41:24Z | [
"python",
"list"
] |
Confusing reference ownership: how to properly deallocate (via Py_DECREF) objects of an object? | 38,285,729 | <p>I was analysing the following code, which compiles and runs correctly, but generates a memory leak.</p>
<p>The <code>cfiboheap</code> is a C implementation of a Fibonacci Heap and the following code is a Cython wrapper (a part of it) for <code>cfiboheap</code>.</p>
<p>My doubts starts on the insert function. The o... | 1 | 2016-07-09T19:46:13Z | 38,291,630 | <p>1) It is necessary to increase the reference count in <code>insert</code> because its reference count will be automatically decreased at the end of insert. Cython does not know you are storing the object for later. (You can inspect the generated C code to see the <code>DECREF</code> at the end of the function). If <... | 1 | 2016-07-10T12:00:55Z | [
"python",
"c",
"memory-leaks",
"cython"
] |
Inheritance in Python: What's wrong with my code? | 38,285,737 | <p>Ok so I'm learning inheritance and making instances of another class and I'm having a problem with an error that tells me my <code>ElectricCar</code> class doesn't have a battery attribute. Can someone please point out what I'm missing here? I've been working on this problem for a few days now and I'm at my wit's ... | -3 | 2016-07-09T19:47:02Z | 38,285,781 | <p>The problem is that in your <code>ElectricCar</code> class, you're initializing the <code>Battery</code> class and setting it to the variable <code>self.battery_size</code> instead of <code>self.battery</code>.</p>
<p>Changing your code to:</p>
<pre><code>class ElectricCar(Car):
def __init__(self, make, model,... | 1 | 2016-07-09T19:51:46Z | [
"python",
"class",
"inheritance"
] |
How to save a csv file so iPython shell can open and use it? | 38,285,774 | <p>I'm a newbie to Python. I'm having trouble opening my csv file in the iPython shell, although I can open my file in Spyder just find. How can I save a csv, or any other file, properly to be used by both Spyder and iPython?</p>
<p>For example, I tried opening up and reading a file</p>
<pre><code>DATA_data = open('D... | 0 | 2016-07-09T19:51:09Z | 38,286,225 | <p>A <code>csv</code> file is plain text, so almost any code can read it. With <code>ipython</code> you can read it with shell command, with Python read, or with numpy or pandas.</p>
<p>The first issue knowing where the file is located. That's a file system issue - what's directory. In <code>ipython</code> you can ... | 1 | 2016-07-09T20:48:41Z | [
"python",
"python-2.7",
"csv",
"pandas",
"ipython"
] |
Python append to an string element in a list | 38,285,805 | <p>I'm fairly new to python. I want to know how can you append to a string element in a list cumulatively ? </p>
<pre><code>list = ['1','2','3','4']
list2 = ['a','b','c','d']
</code></pre>
<p>I want a new list like this:</p>
<pre><code>list3 = ['1a', '1b', '1c', '1d']
</code></pre>
<p>I've been running circles for ... | 2 | 2016-07-09T19:54:11Z | 38,285,843 | <p>Using <a href="http://stackoverflow.com/questions/20639180/python-list-comprehension-explained">list comprehension</a>. Note that you need to turn the integer into a string via the <code>str()</code> function, then you can use string concatenation to combine list1[0] and every element in list2. Also note that <code>... | 2 | 2016-07-09T19:58:54Z | [
"python"
] |
Python append to an string element in a list | 38,285,805 | <p>I'm fairly new to python. I want to know how can you append to a string element in a list cumulatively ? </p>
<pre><code>list = ['1','2','3','4']
list2 = ['a','b','c','d']
</code></pre>
<p>I want a new list like this:</p>
<pre><code>list3 = ['1a', '1b', '1c', '1d']
</code></pre>
<p>I've been running circles for ... | 2 | 2016-07-09T19:54:11Z | 38,285,848 | <p>You can use <a href="https://docs.python.org/2/library/functions.html#map" rel="nofollow"><code>map()</code></a> and <a href="https://docs.python.org/2/library/functions.html#zip" rel="nofollow"><code>zip</code></a> like so:</p>
<pre><code>list = ['1','2','3','4']
list2 = ['a','b','c','d']
print map(lambda x: x[0... | 2 | 2016-07-09T19:59:19Z | [
"python"
] |
Python append to an string element in a list | 38,285,805 | <p>I'm fairly new to python. I want to know how can you append to a string element in a list cumulatively ? </p>
<pre><code>list = ['1','2','3','4']
list2 = ['a','b','c','d']
</code></pre>
<p>I want a new list like this:</p>
<pre><code>list3 = ['1a', '1b', '1c', '1d']
</code></pre>
<p>I've been running circles for ... | 2 | 2016-07-09T19:54:11Z | 38,285,901 | <p>In your question you want <code>list3 = ['1a', '1b', '1c', '1d']</code>.</p>
<p>If you really want this: list3 = <code>['1a', '2b', '3c', '4d']</code> then:</p>
<pre><code>>>> list = ['1','2','3','4']
>>> list2 = ['a','b','c','d']
>>> zip(list, list2)
[('1', 'a'), ('2', 'b'), ('3', 'c')... | 1 | 2016-07-09T20:05:51Z | [
"python"
] |
Python append to an string element in a list | 38,285,805 | <p>I'm fairly new to python. I want to know how can you append to a string element in a list cumulatively ? </p>
<pre><code>list = ['1','2','3','4']
list2 = ['a','b','c','d']
</code></pre>
<p>I want a new list like this:</p>
<pre><code>list3 = ['1a', '1b', '1c', '1d']
</code></pre>
<p>I've been running circles for ... | 2 | 2016-07-09T19:54:11Z | 38,286,597 | <p>I'm assuming your goal is [ '1a', '2b', '3c', '4d' ] ?</p>
<pre><code>list = [ '1', '2', '3', '4' ]
list2 = [ 'a', 'b', 'c', 'd' ]
list3 = []
for i in range (len(list)):
elem = list[i] + list2[i]
list3 += [ elem ]
print list3
</code></pre>
<p>In general though, I'd be careful about doing this. There's no... | -2 | 2016-07-09T21:40:14Z | [
"python"
] |
Python's equivalent to null-conditional operator introduced in C# 6 | 38,285,881 | <p>Is there an equivalent in Python to C# <a href="https://msdn.microsoft.com/en-us/library/dn986595.aspx" rel="nofollow">null-conditional operator</a>?</p>
<pre><code>System.Text.StringBuilder sb = null;
string s = sb?.ToString(); // No error
</code></pre>
| 5 | 2016-07-09T20:03:03Z | 38,286,072 | <p>Well, the simplest solution would be:</p>
<pre><code>result = None if obj is None else obj.method()
</code></pre>
<hr>
<p>But if you want the exact equivalent having the same thread safety as the C#'s Null-conditional operator, it would be:</p>
<pre><code>obj = 'hello'
temp = obj
result = None if temp is None el... | 1 | 2016-07-09T20:27:55Z | [
"c#",
"python"
] |
Python's equivalent to null-conditional operator introduced in C# 6 | 38,285,881 | <p>Is there an equivalent in Python to C# <a href="https://msdn.microsoft.com/en-us/library/dn986595.aspx" rel="nofollow">null-conditional operator</a>?</p>
<pre><code>System.Text.StringBuilder sb = null;
string s = sb?.ToString(); // No error
</code></pre>
| 5 | 2016-07-09T20:03:03Z | 38,288,575 | <p>How about:</p>
<pre><code>s = sb and sb.ToString()
</code></pre>
<p>The short circuited Boolean stops if sb is Falsy, else returns the next expression.</p>
<p>Btw, if getting None is important...</p>
<pre><code>sb = ""
#we wont proceed to sb.toString, but the OR will return None here...
s = (sb or None) and sb.... | 3 | 2016-07-10T04:26:01Z | [
"c#",
"python"
] |
excluding elements to be scraped | 38,285,989 | <p>I am trying to exclude certain elements from a list.</p>
<p>on the page <a href="http://www.persimmonhomes.com/rooley-park-10126" rel="nofollow">http://www.persimmonhomes.com/rooley-park-10126</a> there are the elements I want to scrap which are (div class="housetype js-filter-housetype") and there are those I don'... | 2 | 2016-07-09T20:18:07Z | 38,286,018 | <p>If you want to ignore all with a style attribute:</p>
<pre><code>"//div[@class='housetype js-filter-housetype' and not(@style)]"
</code></pre>
<p>Or that particular style, just use <code>and</code>:</p>
<pre><code>"//div[@class='housetype js-filter-housetype' and not(contains(@style,'display: none;'))]"
</code></... | 2 | 2016-07-09T20:22:06Z | [
"python",
"xpath",
"scrapy"
] |
Multiline printing in a "for" loop | 38,286,001 | <p>I'm trying to print a multiline string in a "for" loop. The problem is I'd like to have the output printed all on the same lines. Example:</p>
<pre><code>for i in range(5):
print('''
{a}
|
{b}
'''.format(a=i,b=i+1))
</code></pre>
<p>The output looks like:</p>
<pre><code>0
|
1
1
|
2
2
|
3
3
|
4
4
|
5
</cod... | 1 | 2016-07-09T20:19:47Z | 38,286,023 | <p>You can only print one line at a time. So first you'll have to print the line with all the <code>a</code> elements, then the line with all the bars, and finally the line with all the <code>b</code> elements.</p>
<p>This can be made easier by first preparing every line before printing it:</p>
<pre><code>line_1 = ""... | 0 | 2016-07-09T20:22:36Z | [
"python",
"python-3.x"
] |
Multiline printing in a "for" loop | 38,286,001 | <p>I'm trying to print a multiline string in a "for" loop. The problem is I'd like to have the output printed all on the same lines. Example:</p>
<pre><code>for i in range(5):
print('''
{a}
|
{b}
'''.format(a=i,b=i+1))
</code></pre>
<p>The output looks like:</p>
<pre><code>0
|
1
1
|
2
2
|
3
3
|
4
4
|
5
</cod... | 1 | 2016-07-09T20:19:47Z | 38,286,038 | <pre><code>import sys
myRange = range(5)
for i in myRange:
sys.stdout.write(str(i))
print()
for i in myRange:
sys.stdout.write('|')
print()
for i in myRange:
sys.stdout.write(str(i+1))
print()
</code></pre>
<p>You need <code>sys.stdout.write</code> to write without <code>\n</code>. And this code will not... | 1 | 2016-07-09T20:24:57Z | [
"python",
"python-3.x"
] |
Multiline printing in a "for" loop | 38,286,001 | <p>I'm trying to print a multiline string in a "for" loop. The problem is I'd like to have the output printed all on the same lines. Example:</p>
<pre><code>for i in range(5):
print('''
{a}
|
{b}
'''.format(a=i,b=i+1))
</code></pre>
<p>The output looks like:</p>
<pre><code>0
|
1
1
|
2
2
|
3
3
|
4
4
|
5
</cod... | 1 | 2016-07-09T20:19:47Z | 38,286,120 | <p>Try with list concaternation:</p>
<pre><code>x = 5
print (" ".join(str(i) for i in range(x)))
print ('| '*x)
print (" ".join(str(i) for i in range(1,x+1)))
</code></pre>
| 4 | 2016-07-09T20:33:27Z | [
"python",
"python-3.x"
] |
Multiline printing in a "for" loop | 38,286,001 | <p>I'm trying to print a multiline string in a "for" loop. The problem is I'd like to have the output printed all on the same lines. Example:</p>
<pre><code>for i in range(5):
print('''
{a}
|
{b}
'''.format(a=i,b=i+1))
</code></pre>
<p>The output looks like:</p>
<pre><code>0
|
1
1
|
2
2
|
3
3
|
4
4
|
5
</cod... | 1 | 2016-07-09T20:19:47Z | 38,286,131 | <p>Just to throw in a fun (but bad, don't do this) answer:</p>
<pre><code>for i in range(5):
print('{}\033[1B\033[1D|\033[1B\033[1D{}\033[2A'.format(i, i+1), end='')
print('\033[2B')
</code></pre>
<p>This uses terminal control codes to print column by column rather than row by row. Not useful here but something t... | 0 | 2016-07-09T20:35:16Z | [
"python",
"python-3.x"
] |
Multiline printing in a "for" loop | 38,286,001 | <p>I'm trying to print a multiline string in a "for" loop. The problem is I'd like to have the output printed all on the same lines. Example:</p>
<pre><code>for i in range(5):
print('''
{a}
|
{b}
'''.format(a=i,b=i+1))
</code></pre>
<p>The output looks like:</p>
<pre><code>0
|
1
1
|
2
2
|
3
3
|
4
4
|
5
</cod... | 1 | 2016-07-09T20:19:47Z | 38,286,206 | <p>Similar to Tim's solution, just using <a href="https://docs.python.org/3/library/functions.html#map" rel="nofollow"><code>map</code></a> instead of the genrators, which I think is even more readable in this case:</p>
<pre><code>print(" ".join(map(str, range(i))))
print("| " * i)
print(" ".join(map(str, range(1, i+1... | 0 | 2016-07-09T20:45:05Z | [
"python",
"python-3.x"
] |
Multiline printing in a "for" loop | 38,286,001 | <p>I'm trying to print a multiline string in a "for" loop. The problem is I'd like to have the output printed all on the same lines. Example:</p>
<pre><code>for i in range(5):
print('''
{a}
|
{b}
'''.format(a=i,b=i+1))
</code></pre>
<p>The output looks like:</p>
<pre><code>0
|
1
1
|
2
2
|
3
3
|
4
4
|
5
</cod... | 1 | 2016-07-09T20:19:47Z | 38,286,426 | <p>What's your goal here? If, for example, you print up to n>9, your formatting will be messed up because of double digit numbers.</p>
<p>Regardless, I'd do it like this. You only want to iterate once, and this is pretty flexible, so you can easily change your formatting.</p>
<pre><code>lines = ['', '', '']
for i i... | 0 | 2016-07-09T21:15:11Z | [
"python",
"python-3.x"
] |
Python method decorator to access an instance variable | 38,286,098 | <p>I have a Python class that has a couple of state variables - let's call them <code>self.state</code> and <code>self.process</code>:</p>
<pre><code>class MyClass(object):
def __init__(state=None, process=None):
self.state = state
self.process = process
</code></pre>
<p>Now, I have a LOT of metho... | 1 | 2016-07-09T20:30:48Z | 38,286,176 | <p>Yeah, decorators are ordinary functions, so <code>self</code> is no exception to the rule. So let's say I write a decorator function that takes an argument called <code>self</code>:</p>
<pre><code>def needs_state(fn):
def decorator(self, *args, **kwargs):
if self.state is None:
raise ValueEr... | 3 | 2016-07-09T20:40:52Z | [
"python",
"python-2.7"
] |
Python lxml iterating through tr elements | 38,286,139 | <p>I'm running into an issue when trying to get the parent node of a tr element whilst iterating through them all. </p>
<p>Here's a basic table that I'm working with. </p>
<blockquote>
<pre><code> <table border=1>
<tbody>
<tr>
<td>
<p>Some text</p>
</td>
... | 1 | 2016-07-09T20:36:24Z | 38,286,414 | <p><code>tr</code> is actually a list of xpath matches. <code>x</code> corresponds to individual <code>tr</code> elements - call <code>getparent()</code> method on it instead:</p>
<pre><code>tr = htm.xpath('//tr')
for x in tr:
tbody = x.getparent()
# ...
</code></pre>
<p>Though, I don't see much sense in gett... | 1 | 2016-07-09T21:13:10Z | [
"python",
"python-3.x",
"lxml",
"lxml.html"
] |
Python - Iteratively generated lambda doesn't work | 38,286,166 | <p>I'm having a bit of trouble understanding how Python treats and evaluates lambdas at runtime.</p>
<h2>Iteratively building up an integer</h2>
<p>Consider the following code (Python 3.5.2):</p>
<pre><code>x = 0
for iteration in range(3):
x = x + 1
print(x)
</code></pre>
<p>As expected, this prints 3. Here is ... | 1 | 2016-07-09T20:39:39Z | 38,286,228 | <p>This behavior has nothing to do with 'iterational' lambda generation. When you say <code>add3 = lambda x: add3(x) + 1</code>, the <code>add3</code> object is <em>replaced</em> with a lambda <em>calling itself recursively with no termination condition</em>.</p>
<p>So when you call <code>add3(0)</code>, it becomes:</... | 1 | 2016-07-09T20:49:18Z | [
"python",
"lambda"
] |
Python - Iteratively generated lambda doesn't work | 38,286,166 | <p>I'm having a bit of trouble understanding how Python treats and evaluates lambdas at runtime.</p>
<h2>Iteratively building up an integer</h2>
<p>Consider the following code (Python 3.5.2):</p>
<pre><code>x = 0
for iteration in range(3):
x = x + 1
print(x)
</code></pre>
<p>As expected, this prints 3. Here is ... | 1 | 2016-07-09T20:39:39Z | 38,286,286 | <p>You are correct that it is evaluated at run time. Because of that, <code>add3</code>, when referenced in itself, is calling itself, not the old <code>add3</code>. In the case of your loop, you are always using <code>[-1]</code>. Since it is evaluated at run time, the first one calls the one at the end of the list... | 0 | 2016-07-09T20:56:31Z | [
"python",
"lambda"
] |
Python - Iteratively generated lambda doesn't work | 38,286,166 | <p>I'm having a bit of trouble understanding how Python treats and evaluates lambdas at runtime.</p>
<h2>Iteratively building up an integer</h2>
<p>Consider the following code (Python 3.5.2):</p>
<pre><code>x = 0
for iteration in range(3):
x = x + 1
print(x)
</code></pre>
<p>As expected, this prints 3. Here is ... | 1 | 2016-07-09T20:39:39Z | 38,286,312 | <p>Python allows you to access variables in the enclosing scope, but you are changing those variables during the loop.</p>
<pre><code>add3 = lambda x: x
for iteration in range(3):
# This add3 will call itself!
# It always uses the *current* value of add3,
# NOT the value of add3 when it was created.
ad... | 0 | 2016-07-09T21:00:38Z | [
"python",
"lambda"
] |
Python - Iteratively generated lambda doesn't work | 38,286,166 | <p>I'm having a bit of trouble understanding how Python treats and evaluates lambdas at runtime.</p>
<h2>Iteratively building up an integer</h2>
<p>Consider the following code (Python 3.5.2):</p>
<pre><code>x = 0
for iteration in range(3):
x = x + 1
print(x)
</code></pre>
<p>As expected, this prints 3. Here is ... | 1 | 2016-07-09T20:39:39Z | 38,286,334 | <p>Here's how <code>add3</code> actually changes throughout the loop:</p>
<ul>
<li><strong>Initial Value:</strong> <code>lambda x: x</code></li>
<li><strong>Iteration 1:</strong> <code>lambda x: add3(x) + 1</code></li>
</ul>
<p><code>add3</code> is not immediately substituted inside the lambda body! It gets looked up... | 0 | 2016-07-09T21:03:38Z | [
"python",
"lambda"
] |
Python - Iteratively generated lambda doesn't work | 38,286,166 | <p>I'm having a bit of trouble understanding how Python treats and evaluates lambdas at runtime.</p>
<h2>Iteratively building up an integer</h2>
<p>Consider the following code (Python 3.5.2):</p>
<pre><code>x = 0
for iteration in range(3):
x = x + 1
print(x)
</code></pre>
<p>As expected, this prints 3. Here is ... | 1 | 2016-07-09T20:39:39Z | 38,286,599 | <p>Except for the name and name binding, the expression <code>lambda <args>: <expression></code> creates a function that equals the result of <code>def f(<args>): return <expression></code>. The statement <code>f = lambda <args>: <expression></code> does not even have the name bindi... | 0 | 2016-07-09T21:40:46Z | [
"python",
"lambda"
] |
Python PIL image open and save changes image file size? | 38,286,223 | <p>I used PIL to open and save the same jpg image, but the size reduces significantly. Could somebody explained what's going on under the hood?</p>
<p>I run </p>
<pre><code>a = Image.open('a.jpg')
a.save('b.jpg')
</code></pre>
<p>a.jpg has the size 5MB, whereas b.jpg is only 600KB. and I enlarge them and compared si... | 0 | 2016-07-09T20:48:15Z | 38,286,540 | <p>The default save quality for jpg in Pillow is 75. I bet your original image is saved with a higher quality setting.</p>
<blockquote>
<p>The image quality, on a scale from 1 (worst) to 95 (best). The default
is 75. Values above 95 should be avoided; 100 disables portions of the
JPEG compression algorithm, and ... | 0 | 2016-07-09T21:32:52Z | [
"python",
"image",
"file",
"compression",
"python-imaging-library"
] |
Selenium / python - cannot click on an element | 38,286,371 | <p>I am trying to use python and selenium to go to a website to collect some data, but I can't even get past the initial popup asking me to click an Accept button to agree to the terms of use! The website is <a href="https://www.etfsecurities.com/institutional/uk/en-gb/products.aspx" rel="nofollow">here</a></p>
<p>I c... | 1 | 2016-07-09T21:08:08Z | 38,286,398 | <p>The trick is to <em>wait for the "Accept" button to become clickable</em>, move to the button and click:</p>
<pre><code>from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriv... | 2 | 2016-07-09T21:11:14Z | [
"jquery",
"python",
"selenium",
"selenium-webdriver"
] |
'float' object is not callable error | 38,286,513 | <p>I have a function in a class I have written that reads a reading on a magnetometer and converts it into a direction between 0 and 359 degrees. The function is as follows:</p>
<pre><code>def heading(self):
self.xzy = self.__GetCompassMag()
self.x = self.xzy[0]
self.y = self.xzy[2]
pi = 3.14159
se... | -2 | 2016-07-09T21:28:35Z | 38,286,567 | <p>Because you override you <code>heading</code> method in a plain instance variable in this line</p>
<pre><code>self.heading = round((math.atan2(self.y, self.x) * 180) / pi
</code></pre>
<p>Don't use <code>self</code> to write your local variable because with <code>self</code> you will be referring an instance varia... | 1 | 2016-07-09T21:36:38Z | [
"python"
] |
Can i write a GUI for fedora using pygtk? | 38,286,598 | <p>I would like to write my own frontend for an operating system in python my current choice is linux fedora but after the install i would then remove the x window system so that i could write my own OS frontend but would it still work or does pygtk need the x window system to function?</p>
| -2 | 2016-07-09T21:40:38Z | 38,287,475 | <p>Looks like you can run gtk 2 on the framebuffer, so, without X:</p>
<p><a href="http://www.gtk.org/api/2.6/gtk/gtk-framebuffer.html" rel="nofollow">http://www.gtk.org/api/2.6/gtk/gtk-framebuffer.html</a></p>
<p>Since pygtk seems to use gtk 2, it could work.</p>
| 0 | 2016-07-10T00:21:22Z | [
"python",
"linux",
"x11",
"fedora",
"pygobject"
] |
Archlinux pip and setuptools not upgraded | 38,286,602 | <p>Terminal command :</p>
<pre><code>python -V output: Python 3.5.2
</code></pre>
<p>I'm trying <code>pip</code> and <code>setuptools</code> update on <code>pycharm</code> but this error occurred : </p>
<blockquote>
<p>Error :python packaging tool 'pip' not found.</p>
</blockquote>
<p>Proposed solution:</p>
<blo... | 1 | 2016-07-09T21:41:06Z | 38,286,682 | <p>I'm very sorry, I take care of the problem.</p>
<p>pacman -S --force python-pip and pacman -S --force python-setup tools is working.</p>
<p><a href="http://unix.stackexchange.com/questions/240252/pacman-exists-on-filesystem-error">http://unix.stackexchange.com/questions/240252/pacman-exists-on-filesystem-error</a>... | 0 | 2016-07-09T21:52:53Z | [
"python",
"pip",
"archlinux"
] |
Archlinux pip and setuptools not upgraded | 38,286,602 | <p>Terminal command :</p>
<pre><code>python -V output: Python 3.5.2
</code></pre>
<p>I'm trying <code>pip</code> and <code>setuptools</code> update on <code>pycharm</code> but this error occurred : </p>
<blockquote>
<p>Error :python packaging tool 'pip' not found.</p>
</blockquote>
<p>Proposed solution:</p>
<blo... | 1 | 2016-07-09T21:41:06Z | 38,305,292 | <p>If you want the most up-to-date version from <code>pypi</code> and not from repository, then do something like</p>
<pre><code>pip install -U pip
</code></pre>
| 0 | 2016-07-11T11:03:05Z | [
"python",
"pip",
"archlinux"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.