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 |
|---|---|---|---|---|---|---|---|---|---|
Autochange values of a variable outside a while loop in Python | 38,290,538 | <p>I do not really know how to correctly ask this question so please bear with me. So,</p>
<pre><code>b=1
a=b
while (a<10):
b+=1
#a=b
print a, b
</code></pre>
<p>This returns an infinite loop UNLESS I remove the #. What I am asking is this: is there a way to UPDATE the value of var a without having t... | 0 | 2016-07-10T09:39:54Z | 38,290,748 | <p>The easiest solution would probably be to rewrite the loop like this:</p>
<pre><code>def generator(tar_cal):
meal_1=["oats", "egg whites", "green apple"]
meal_1_cal=tar_cal*0.27
oats_min=50
egg_whites_min=4
green_apple_min=1
while True:
sum1=(8*9+11*4+60*4)*oats_min/100 + (0.1*9+3.6... | 0 | 2016-07-10T10:07:09Z | [
"python",
"loops",
"variables",
"while-loop"
] |
Extracting HTML between tags | 38,290,588 | <p>I want to extract all HTML between specific HTML tags.</p>
<pre><code><html>
<div class="class1">Included Text</div>
[...]
<h1><b>text</b></h1><span>[..]</span><div>[...]</div>
[...]
<span class="class2">
[...]</span>
</code></pre>
<p>so... | 2 | 2016-07-10T09:46:11Z | 38,290,786 | <p>You can role your own function using <em>bs4</em> and <em>itertools.takewhile</em></p>
<pre><code>h = """<html>
<div class="class1">Included Text</div>
[...]
<h1><b>text</b></h1><span>[..]</span><div>[...]</div>
[...]
<span class="class2">
[... | 2 | 2016-07-10T10:11:21Z | [
"python",
"beautifulsoup"
] |
Django1.9: 'function' object has no attribute '_meta' | 38,290,644 | <p>Django Gives an error message</p>
<p>forms.py:</p>
<pre><code>from django import forms
from django.contrib.auth import authenticate, get_user_model, login, logout
from django.contrib.auth.forms import UserCreationForm
User = get_user_model
class UserLoginForm(forms.Form):
username = forms.CharField()
pa... | 0 | 2016-07-10T09:56:00Z | 38,290,659 | <p>You've set User equal to the <em>function</em> <code>get_user_model</code>. You need to set it to the result of calling that function:</p>
<pre><code>User = get_user_model()
</code></pre>
| 2 | 2016-07-10T09:57:16Z | [
"python",
"django",
"python-3.x",
"django-1.9"
] |
Finding properties of a real function | 38,290,663 | <p>Is there a way, using <code>sympy</code>, to figure out (some) properties of a function, thought of as a real function?</p>
<p>For example, if</p>
<pre><code>>>> x = Symbol('x', real=True)
>>> f = Lambda(x, sqrt((x-2)/(x+2)))
</code></pre>
<p>then something like</p>
<pre><code>>>> f.do... | 5 | 2016-07-10T09:58:01Z | 38,311,770 | <p>Some of these are implemented in <a href="https://github.com/sympy/sympy/blob/master/sympy/calculus/util.py" rel="nofollow"><code>sympy.calculus.util</code></a> and <a href="https://github.com/sympy/sympy/blob/master/sympy/calculus/singularities.py" rel="nofollow"><code>sympy.calculus.singularities</code></a>, altho... | 3 | 2016-07-11T16:24:27Z | [
"python",
"math",
"sympy",
"symbolic-math"
] |
python saving lists to files | 38,290,774 | <p>When using </p>
<pre><code>with open('savefile.dat', 'wb') as f:
pickle.dump([player], f, protocol=2)
</code></pre>
<p>to save a list and then try to open it it works, but when i use this code it gives me an error:</p>
<pre><code>open("KappaClickerSave.json", "rb")
with open("KappaClickerSave.json", "rb") as ... | 0 | 2016-07-10T10:10:25Z | 38,290,794 | <p>You are saving a list with <strong>one</strong> element:</p>
<pre><code>with open('savefile.dat', 'wb') as f:
pickle.dump([player], f, protocol=2)
</code></pre>
<p>If <strong>after</strong> this code you <code>append</code> elements to the list, the changes <strong>will not</strong> be reflected in the file. Y... | 0 | 2016-07-10T10:12:42Z | [
"python",
"list",
"load",
"pickle"
] |
An elegant way to slice a list in python, given another list of ids to slice from | 38,290,825 | <p>I am looking for an elegant way to slice a list <code>l</code> in python, given a list of ids <code>l_ids</code>.
For example, instead of writing </p>
<pre><code>new_list = [l[i] for i in l_ids]
</code></pre>
<p>Write something like (Pseudo code):</p>
<pre><code>new_list = l[*l_ids]
</code></pre>
<p>Is there a... | 2 | 2016-07-10T10:17:05Z | 38,290,872 | <p>You can use <a href="https://docs.python.org/3/library/operator.html#operator.itemgetter" rel="nofollow"><code>operator.itemgetter(*items)</code></a> like this:</p>
<pre><code>from operator import itemgetter
getter = itemgetter(*lst_ids)
new_list = list(getter(lst))
</code></pre>
<p>Also, note that I renamed <cod... | 6 | 2016-07-10T10:22:52Z | [
"python",
"slice"
] |
An elegant way to slice a list in python, given another list of ids to slice from | 38,290,825 | <p>I am looking for an elegant way to slice a list <code>l</code> in python, given a list of ids <code>l_ids</code>.
For example, instead of writing </p>
<pre><code>new_list = [l[i] for i in l_ids]
</code></pre>
<p>Write something like (Pseudo code):</p>
<pre><code>new_list = l[*l_ids]
</code></pre>
<p>Is there a... | 2 | 2016-07-10T10:17:05Z | 38,290,878 | <p>You could use <a href="https://docs.python.org/3.5/library/operator.html" rel="nofollow">itemgetter</a></p>
<pre><code>from operator import itemgetter
l = ['a', 'b', 'c', 'd', 'e']
l_ids = [1, 2, 3]
list(itemgetter(*l_ids)(l))
</code></pre>
<blockquote>
<p>['b', 'c', 'd']</p>
</blockquote>
| 1 | 2016-07-10T10:23:22Z | [
"python",
"slice"
] |
An elegant way to slice a list in python, given another list of ids to slice from | 38,290,825 | <p>I am looking for an elegant way to slice a list <code>l</code> in python, given a list of ids <code>l_ids</code>.
For example, instead of writing </p>
<pre><code>new_list = [l[i] for i in l_ids]
</code></pre>
<p>Write something like (Pseudo code):</p>
<pre><code>new_list = l[*l_ids]
</code></pre>
<p>Is there a... | 2 | 2016-07-10T10:17:05Z | 38,290,905 | <p>I don't think importing anything is particularly elegant, or pythonic.</p>
<p>List comprehensions work, and I can't see a reason not to use them (or no good reason to import something to do the same thing):</p>
<pre><code>>>> x = [3,5,7,0,1,4,2,6]
>>> y = ['a','b','c','d','e','f','g','h']
>>... | 2 | 2016-07-10T10:27:06Z | [
"python",
"slice"
] |
An elegant way to slice a list in python, given another list of ids to slice from | 38,290,825 | <p>I am looking for an elegant way to slice a list <code>l</code> in python, given a list of ids <code>l_ids</code>.
For example, instead of writing </p>
<pre><code>new_list = [l[i] for i in l_ids]
</code></pre>
<p>Write something like (Pseudo code):</p>
<pre><code>new_list = l[*l_ids]
</code></pre>
<p>Is there a... | 2 | 2016-07-10T10:17:05Z | 38,290,921 | <p>I would go with <em>itemgetter</em> but you could also <em>map</em> <em>list.__getitem_</em>_:</p>
<pre><code>l = ['a', 'b', 'c', 'd', 'e']
l_ids = [1, 2, 3]
new = list(map(l.__getitem__, l_ids))
</code></pre>
| 1 | 2016-07-10T10:28:48Z | [
"python",
"slice"
] |
An elegant way to slice a list in python, given another list of ids to slice from | 38,290,825 | <p>I am looking for an elegant way to slice a list <code>l</code> in python, given a list of ids <code>l_ids</code>.
For example, instead of writing </p>
<pre><code>new_list = [l[i] for i in l_ids]
</code></pre>
<p>Write something like (Pseudo code):</p>
<pre><code>new_list = l[*l_ids]
</code></pre>
<p>Is there a... | 2 | 2016-07-10T10:17:05Z | 38,291,251 | <p>If all the list elements are of the same type, it is possible to use numpy:</p>
<pre><code>from numpy import *
new_list = array(l)[l_ids]
</code></pre>
| 0 | 2016-07-10T11:10:12Z | [
"python",
"slice"
] |
OpenCV - VideoCapture(filename) works in Java but not in Python (Windows 7) | 38,290,930 | <p>I've been trying to open a video file using OpenCV and process its frames.
I have both avi file and mp4 file, the mp4 file works well in Java but in Python (where I really need it...) it doesn't work (I keep getting None in videocapture.read()).</p>
<p>Any ideas what can this be? how can it be solved?</p>
<p>EDIT:... | 2 | 2016-07-10T10:29:31Z | 38,291,024 | <p>Check <a href="http://stackoverflow.com/questions/16374633/opencv-videocapture-cannot-read-video-in-python-but-able-in-vs11">this</a> question and the solution provided by <a href="http://stackoverflow.com/a/11703998/410487">this</a> answer.</p>
<p>Maybe it could help.</p>
| 1 | 2016-07-10T10:42:36Z | [
"java",
"python",
"opencv"
] |
OpenCV - VideoCapture(filename) works in Java but not in Python (Windows 7) | 38,290,930 | <p>I've been trying to open a video file using OpenCV and process its frames.
I have both avi file and mp4 file, the mp4 file works well in Java but in Python (where I really need it...) it doesn't work (I keep getting None in videocapture.read()).</p>
<p>Any ideas what can this be? how can it be solved?</p>
<p>EDIT:... | 2 | 2016-07-10T10:29:31Z | 38,292,238 | <p>Try this</p>
<p><code>
import cv2
cap = cv2.VideoCapture('myfile.mp4')
ret = cap.set(3,1280)
ret = cap.set(4,720)
while True:
ret,frame = cap.read()
cv2.imshow('show',frame)
key = cv2.waitKey(10)
if key == 27:
break</code></p>
| 0 | 2016-07-10T13:12:22Z | [
"java",
"python",
"opencv"
] |
scrapy don't detect an html element but it is visible on source page | 38,290,999 | <p>I have a request working normally on regular browsers but not on in scrapy shell. An entire HTML block get vanish as soon as I use "scrapy shell" or "scrapy crawl". I am not banned for sure.</p>
<p>Here, below, is the issue on the github (with pictures) before i was redirect toward here of the below link (french we... | 1 | 2016-07-10T10:39:17Z | 38,294,981 | <p>This is a Javascript issue.</p>
<p>The section of the page that doesn't get loaded is called dynamically by an AJAX request.</p>
<p>Since Scrapy doesn't render any Javascript by default including AJAX requests, the contents of the block in the page stays empty.</p>
<p>This is definitely handleable in Scrapy using... | 1 | 2016-07-10T18:08:17Z | [
"javascript",
"python",
"http-headers",
"scrapy",
"scrapy-shell"
] |
scrapy don't detect an html element but it is visible on source page | 38,290,999 | <p>I have a request working normally on regular browsers but not on in scrapy shell. An entire HTML block get vanish as soon as I use "scrapy shell" or "scrapy crawl". I am not banned for sure.</p>
<p>Here, below, is the issue on the github (with pictures) before i was redirect toward here of the below link (french we... | 1 | 2016-07-10T10:39:17Z | 38,295,034 | <p>If you view the actual HTML source from that page (<code>view-source:http://www.licitor.com/ventes-judiciaires-immobilieres/tgi-fontainebleau/mercredi-15-juin-2016.html</code>) you won't see the data you circled in the GitHub issue.</p>
<p>If you inspect your browser's network tab, when loading <a href="http://www.... | 0 | 2016-07-10T18:14:22Z | [
"javascript",
"python",
"http-headers",
"scrapy",
"scrapy-shell"
] |
Django editing model's fields concurrently | 38,291,003 | <pre><code># /uri/one/{pk}/
class ModelOneView(generic.View):
def post(self, request, pk): # pk has the same value as below
Model.objects.filter(pk=pk).update(name=request.POST['name'])
return HttpResponse(status=200)
# /uri/two/{pk}/
class ModelTwoView(generic.View):
def post(self, request, ... | 1 | 2016-07-10T10:39:40Z | 38,291,066 | <p>Two suggestions you might like to try:</p>
<ol>
<li><p>Run <code>callSecondURI()</code> after completion of <code>callFirstURI()</code> using a callback in your AJAX request</p></li>
<li><p>It might not apply (I am by no means an expert on this) but this sounds like it could be to do with multithreading. Have a loo... | 0 | 2016-07-10T10:47:58Z | [
"python",
"django",
"database"
] |
Django editing model's fields concurrently | 38,291,003 | <pre><code># /uri/one/{pk}/
class ModelOneView(generic.View):
def post(self, request, pk): # pk has the same value as below
Model.objects.filter(pk=pk).update(name=request.POST['name'])
return HttpResponse(status=200)
# /uri/two/{pk}/
class ModelTwoView(generic.View):
def post(self, request, ... | 1 | 2016-07-10T10:39:40Z | 38,298,060 | <p>Have you considered <a href="https://docs.djangoproject.com/en/1.9/ref/models/querysets/#select-for-update" rel="nofollow">select_for_update</a> ?</p>
<blockquote>
<p>Returns a queryset that will lock rows until the end of the
transaction, generating a SELECT ... FOR UPDATE SQL statement on
supported database... | 1 | 2016-07-11T01:44:44Z | [
"python",
"django",
"database"
] |
explanation needed for this subclassing QThread vs moveToThread example | 38,291,105 | <p>I am trying to create a new thread worker outside of my GUI. When I subclass QThread it works as I expect, the GUI is unaffected. When I use the moveToThread technique, I get full lock up of the GUI. I assume I'm accidentally putting the new thread into the main thread, but I don't understand what I'm doing to cause... | 1 | 2016-07-10T10:53:41Z | 38,294,772 | <p>Firstly, you need to keep a reference the worker and thread you have created, otherwise they will get garbage-collected as soon as <code>start2()</code> returns.</p>
<p>Secondly, calling <code>myWorker.run()</code> directly inside <code>start2()</code> means it will be executed within the main thread. So you must a... | 0 | 2016-07-10T17:45:08Z | [
"python",
"pyside",
"qthread"
] |
Flask jsonify - how to send string back? | 38,291,215 | <p>I'm building API that sends result back in string format.</p>
<pre><code>@app.route('/', methods=['POST'])
def converter():
content = request.json
# translate() - english to hindi
converted = translate(content)
print converted
#prints string normally
return jsonify({"result":converted})
</co... | 1 | 2016-07-10T11:06:51Z | 38,291,246 | <p>Don't wrap the result inside the <code>jsonify</code> call, and simply <code>return converted</code>:</p>
<pre><code>@app.route('/', methods=['POST'])
def converter():
content = request.json
converted = translate(content)
return converted
</code></pre>
| 2 | 2016-07-10T11:09:27Z | [
"python",
"json",
"utf-8",
"flask"
] |
Flask jsonify - how to send string back? | 38,291,215 | <p>I'm building API that sends result back in string format.</p>
<pre><code>@app.route('/', methods=['POST'])
def converter():
content = request.json
# translate() - english to hindi
converted = translate(content)
print converted
#prints string normally
return jsonify({"result":converted})
</co... | 1 | 2016-07-10T11:06:51Z | 38,291,271 | <p>I think jsonify uses ASCII by default. There is a configuration option:</p>
<pre><code>app.config['JSON_AS_ASCII'] = False
</code></pre>
<p>that will set the default to unicode.</p>
| 1 | 2016-07-10T11:12:40Z | [
"python",
"json",
"utf-8",
"flask"
] |
Python selenium drop down menu click | 38,291,230 | <p>i want to select option from a drop down menu, for this i use that :</p>
<pre><code>br.find_element_by_xpath("//*[@id='adyen-encrypted-form']/fieldset/div[3]/div[2]/div/div/div/div/div[2]/div/ul/li[5]/span").click()
</code></pre>
<p>To select option month 4 but when i do that pyhton return error message : </p>
<b... | -4 | 2016-07-10T11:08:09Z | 38,291,966 | <p>You should use <code>Select()</code> to select an option from drop down as below :-</p>
<pre><code>from selenium.webdriver.support.ui import Select
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
w... | 0 | 2016-07-10T12:39:49Z | [
"python",
"selenium"
] |
How to use function's return within other function (without using class) | 38,291,249 | <p>I have a function:</p>
<pre><code>def search_result(request):
if request.method =='POST':
data = request.body
qd = QueryDict(data)
place = qd.values()[2]
indate = qd.values()[3]
outdate = qd.values()[0]
url = ('http://terminal2.expedia.com/x/mhotels/search?city=%... | -1 | 2016-07-10T11:09:57Z | 38,291,305 | <p>You have defined <code>func1</code> to take the <code>request</code> parameter, but when you call it in your second function you do not pass it any arguments.</p>
<p>If you pass in <code>request</code> it should work.</p>
<p>EDIT: You are looking for the results, so I suppose you can just return them instead of th... | 0 | 2016-07-10T11:18:24Z | [
"python",
"django"
] |
split list from text into nGrams in Python | 38,291,313 | <p>I have to split a text file into a specific amount of words per list in list, probably be best to show in example.</p>
<p>say the text file looks like this</p>
<pre><code>"i am having a good day today"
</code></pre>
<p>i have to write a function which looks like this</p>
<pre><code>ngrams.makeNGrams("ngrams.txt"... | 1 | 2016-07-10T11:19:31Z | 38,291,382 | <p>Define:</p>
<pre><code>def ngrams(text, n):
words = text.split()
return [ words[i:i+n] for i in range(len(words)-n+1) ]
</code></pre>
<p>And use:</p>
<pre><code>s = "i am having a good day today"
ngrams(s, 2)
</code></pre>
| 0 | 2016-07-10T11:28:34Z | [
"python",
"python-2.7",
"python-3.x"
] |
split list from text into nGrams in Python | 38,291,313 | <p>I have to split a text file into a specific amount of words per list in list, probably be best to show in example.</p>
<p>say the text file looks like this</p>
<pre><code>"i am having a good day today"
</code></pre>
<p>i have to write a function which looks like this</p>
<pre><code>ngrams.makeNGrams("ngrams.txt"... | 1 | 2016-07-10T11:19:31Z | 38,291,398 | <p>I'm sure there is a more pythonic way of doing this. It is not a function (but it should be easy to adapt) but a program. I think it follows your specification:</p>
<pre><code>import sys
num = int(sys.argv[1])
cad = "i am having a good day today"
listCad = cad.split(" ")
listOfLists = []
i = 0
while i <= le... | 0 | 2016-07-10T11:30:39Z | [
"python",
"python-2.7",
"python-3.x"
] |
split list from text into nGrams in Python | 38,291,313 | <p>I have to split a text file into a specific amount of words per list in list, probably be best to show in example.</p>
<p>say the text file looks like this</p>
<pre><code>"i am having a good day today"
</code></pre>
<p>i have to write a function which looks like this</p>
<pre><code>ngrams.makeNGrams("ngrams.txt"... | 1 | 2016-07-10T11:19:31Z | 38,291,456 | <p>I would do it like this:</p>
<pre><code>def ngrams(words, n):
return zip(*(words[i:] for i in range(n)))
</code></pre>
<p>Usage:</p>
<pre><code>>>> words = "i am having a good day today".split()
>>> list(ngrams(words, 2))
[('i', 'am'), ('am', 'having'), ('having', 'a'), ('a', 'good'), ('good... | 1 | 2016-07-10T11:38:35Z | [
"python",
"python-2.7",
"python-3.x"
] |
Assign unique id to list of lists in python where duplicates get the same id | 38,291,372 | <p>I have a list of lists (which can contain up to 90k elements)</p>
<pre><code>[[1,2,3], [1,2,4], [1,2,3], [1,2,4], [1,2,5]]
</code></pre>
<p>I would like to assign an id to each elements, where the id is unique, except when the item is duplicated. So for the list above, I'd need this back:</p>
<pre><code>[0,1,0,1,... | 4 | 2016-07-10T11:27:37Z | 38,291,401 | <p>Keep a map of already seen elements with the associated id.</p>
<pre><code>from itertools import count
from collections import defaultdict
mapping = defaultdict(count().__next__)
result = []
for element in my_list:
result.append(mapping[tuple(element)])
</code></pre>
<p>you could also use a list-comprehensio... | 5 | 2016-07-10T11:30:49Z | [
"python",
"list",
"counting"
] |
Assign unique id to list of lists in python where duplicates get the same id | 38,291,372 | <p>I have a list of lists (which can contain up to 90k elements)</p>
<pre><code>[[1,2,3], [1,2,4], [1,2,3], [1,2,4], [1,2,5]]
</code></pre>
<p>I would like to assign an id to each elements, where the id is unique, except when the item is duplicated. So for the list above, I'd need this back:</p>
<pre><code>[0,1,0,1,... | 4 | 2016-07-10T11:27:37Z | 38,291,768 | <p>This is how I approached it:</p>
<pre><code>from itertools import product
from random import randint
import time
t0 = time.time()
def id_list(lst):
unique_set = set(tuple(x) for x in lst)
unique = [list(x) for x in unique_set]
unique.sort(key = lambda x: lst.index(x))
result = [unique.index(i[1]) ... | 1 | 2016-07-10T12:16:29Z | [
"python",
"list",
"counting"
] |
Assign unique id to list of lists in python where duplicates get the same id | 38,291,372 | <p>I have a list of lists (which can contain up to 90k elements)</p>
<pre><code>[[1,2,3], [1,2,4], [1,2,3], [1,2,4], [1,2,5]]
</code></pre>
<p>I would like to assign an id to each elements, where the id is unique, except when the item is duplicated. So for the list above, I'd need this back:</p>
<pre><code>[0,1,0,1,... | 4 | 2016-07-10T11:27:37Z | 38,420,464 | <p>I slight modification of Bakuriu's solution that works only with numpy arrays, it works better in terms of memory footprint and computation (as it does need to cast arrays to tuples):</p>
<pre><code>from itertools import count
from collections import defaultdict
from functools import partial
def hashing_v1(seq):
... | 0 | 2016-07-17T10:55:03Z | [
"python",
"list",
"counting"
] |
How to remove the datetime part of a string? | 38,291,376 | <p>For example, I have a string "do something by tomorrow 9am". I am using the parsedatetime module to parse the string and get a datetime object from it. I did this according to the parsedatetime documentation:</p>
<pre><code>from datetime import datetime
import parsedatetime as pdt # $ pip install parsedatetime
cal... | 2 | 2016-07-10T11:28:10Z | 38,291,570 | <p>Having a quick look at the doc (<a href="https://bear.im/code/parsedatetime/docs/index.html" rel="nofollow">https://bear.im/code/parsedatetime/docs/index.html</a>) you can see:</p>
<pre><code>nlp(self, inputString, sourceTime=None)
</code></pre>
<p>If you use it with your entry:</p>
<pre><code>cal.nlp(string)
</c... | 1 | 2016-07-10T11:51:50Z | [
"python",
"python-3.x",
"datetime"
] |
Dynamic css files with jinja | 38,291,388 | <p><br>I am trying to make my stylesheets dynamic with django (jinja2) and I want to do something like this:
<br><br> <code><link rel="stylesheet" href="{% static 'home/css/{{ block css }}{{ endblock }}.css' %}"></code></p>
<p>Apparently, I can't use jinja in jinja :), and I don't know how to make this work o... | 0 | 2016-07-10T11:29:32Z | 38,301,785 | <p>Couldn't you do something like this?</p>
<pre><code>{% if condition == True %}
<link rel='stylesheet' href='file1.css'>
{% else %}
<link rel='stylesheet' href='file2.css'>
{% endif %}
</code></pre>
<p>And so on.</p>
| 0 | 2016-07-11T07:54:10Z | [
"python",
"html",
"django",
"dynamic",
"jinja2"
] |
Dynamic css files with jinja | 38,291,388 | <p><br>I am trying to make my stylesheets dynamic with django (jinja2) and I want to do something like this:
<br><br> <code><link rel="stylesheet" href="{% static 'home/css/{{ block css }}{{ endblock }}.css' %}"></code></p>
<p>Apparently, I can't use jinja in jinja :), and I don't know how to make this work o... | 0 | 2016-07-10T11:29:32Z | 38,301,898 | <p>I found a solution that works out pretty well.<br>
<br>I use
<code><link rel="stylesheet" href="{% block css %}{% endblock %}"></code> in the template
<br> and then: <code>{% block css%}{% static 'home/css/file.css' %}{% endblock %</code> in each page</p>
| 0 | 2016-07-11T08:00:49Z | [
"python",
"html",
"django",
"dynamic",
"jinja2"
] |
NLTK: How can I extract information based on sentence maps? | 38,291,460 | <p>I know you can use noun extraction to get nouns out of sentences but how can I use sentence overlays/maps to take out phrases?</p>
<p><strong>For example:</strong></p>
<blockquote>
<p><strong>Sentence Overlay:</strong> </p>
<pre><code>"First, @action; Second, Foobar"
</code></pre>
<p><strong>Input:</strong... | 1 | 2016-07-10T11:39:17Z | 38,296,852 | <p>You can slightly rewrite your string templates to turn them into regexps, and see which one (or which ones) match. </p>
<pre><code>>>> template = "First, (?P<action>.*); Second, Foobar"
>>> mo = re.search(template, "First, Dance and Code; Second, Foobar")
>>> if mo:
print(mo... | 2 | 2016-07-10T22:05:02Z | [
"python",
"nlp",
"artificial-intelligence",
"nltk"
] |
How to show list of foreign keys in Django admin? | 38,291,557 | <p>I'm creating a quiz app for my project. Each <strong>quiz</strong> can have multiple <strong>questions</strong> and each <strong>question</strong> has multiple <strong>answers</strong> from which one is correct. </p>
<p>The problem is that Django doesn't allow <code>OneToMany</code> relationship so I have to use <c... | 2 | 2016-07-10T11:50:43Z | 38,291,657 | <p><code>ForeignKey</code> is the right field type. A <code>OneToMany</code> is only a reverse <code>ManyToOne</code> relation (which is a foreign key).</p>
<p>You can use <a href="https://docs.djangoproject.com/en/stable/ref/contrib/admin/#inlinemodeladmin-objects" rel="nofollow"><code>InlineModelAdmin</code></a> to ... | 0 | 2016-07-10T12:03:21Z | [
"python",
"django",
"django-admin"
] |
Python regex? I'm in a trouble | 38,291,614 | <p><em>Hello, world!</em>
I'm in a regex trouble. I'm using a HTTP API (for searching italian trains) that give me those informations (for example):</p>
<pre><code>10911 - SESTO S. GIOVANNI|10911-S01325
</code></pre>
<p>Format:</p>
<pre><code>TRAIN_NUMBER - STATION|TRAIN_NUMBER - STATION_CODE
</code></pre>
<p>Until... | 3 | 2016-07-10T11:58:59Z | 38,291,668 | <blockquote>
<p>I must use REGEX, true? </p>
</blockquote>
<p>Not true.</p>
<p>I think a better solution is to parse each line into tokens and assign them to sensible variables. You need a solution that is less about string primitives and regex; more about objects and encapsulation.</p>
<p>I'd design a REST API t... | 2 | 2016-07-10T12:03:51Z | [
"python",
"regex"
] |
Python regex? I'm in a trouble | 38,291,614 | <p><em>Hello, world!</em>
I'm in a regex trouble. I'm using a HTTP API (for searching italian trains) that give me those informations (for example):</p>
<pre><code>10911 - SESTO S. GIOVANNI|10911-S01325
</code></pre>
<p>Format:</p>
<pre><code>TRAIN_NUMBER - STATION|TRAIN_NUMBER - STATION_CODE
</code></pre>
<p>Until... | 3 | 2016-07-10T11:58:59Z | 38,291,691 | <p>You don't need regular expressions, actually. You <em>can</em> use them though. There's a rather simple pattern in your information:</p>
<pre><code><Train number> - <city>|<Train number>-<identifier>
</code></pre>
<p>So let's look at what happens if you do</p>
<pre><code>>>> '123 ... | 4 | 2016-07-10T12:06:42Z | [
"python",
"regex"
] |
Python regex? I'm in a trouble | 38,291,614 | <p><em>Hello, world!</em>
I'm in a regex trouble. I'm using a HTTP API (for searching italian trains) that give me those informations (for example):</p>
<pre><code>10911 - SESTO S. GIOVANNI|10911-S01325
</code></pre>
<p>Format:</p>
<pre><code>TRAIN_NUMBER - STATION|TRAIN_NUMBER - STATION_CODE
</code></pre>
<p>Until... | 3 | 2016-07-10T11:58:59Z | 38,291,762 | <p>First, you have to <a href="http://stackoverflow.com/questions/606191/convert-bytes-to-a-python-string">convert your <code>bytearray</code>s to <code>str</code> objects</a>.</p>
<p>With the examples you provided:</p>
<pre><code>examples = [
b'2097 - MILANO CENTRALE|2097-S01700\n',
b'123 - ROMA TERMINI|123-... | 0 | 2016-07-10T12:15:56Z | [
"python",
"regex"
] |
Python regex? I'm in a trouble | 38,291,614 | <p><em>Hello, world!</em>
I'm in a regex trouble. I'm using a HTTP API (for searching italian trains) that give me those informations (for example):</p>
<pre><code>10911 - SESTO S. GIOVANNI|10911-S01325
</code></pre>
<p>Format:</p>
<pre><code>TRAIN_NUMBER - STATION|TRAIN_NUMBER - STATION_CODE
</code></pre>
<p>Until... | 3 | 2016-07-10T11:58:59Z | 38,292,066 | <p>You can actually get the data you want in json format making the correct post, for * Treno - Stazione* using the code for <em>ROMETTA MESSINESE</em>:</p>
<pre><code>from pprint import pprint as pp
import requests
import datetime
station = "S12049"
dt = datetime.datetime.utcnow()
arrival = "http://www.viaggiatre... | 0 | 2016-07-10T12:49:58Z | [
"python",
"regex"
] |
combining patches to obtain single transparency in matplotlib | 38,291,692 | <p>I calculate ellipse-like polygons which are drawn over another image. The polygons together form one shape and must have a single transparency. Unfortunately, if I draw one polygon after another, the stack gets different transparencies. In the example below I have 3 polygons, creating 3 transparencies, resulting in ... | 2 | 2016-07-10T12:06:46Z | 38,291,904 | <p>Like this:</p>
<pre><code>pts1 = get_ellipse_coords(a=4.0, b=1.0)
pts2 = get_ellipse_coords(a=4.0, b=1.0, x=1.0, angle=30)
stoppoint = np.array([[nan,nan]])
pts = np.concatenate((pts1, stoppoint, pts2))
ax.add_patch(Polygon(pts, closed=True, lw=0.5,
color=c, alpha=alp,zorder=2))
</code><... | 1 | 2016-07-10T12:33:24Z | [
"python",
"matplotlib"
] |
Using pandas over csv library for manipulating CSV files in Python3 | 38,291,701 | <p>Forgive me if my questions is too general, or if its been asked before. I've been tasked to manipulate (e.g. copy and paste several range of entries, perform calculations on them, and then save them all to a new csv file) several large datasets in Python3. </p>
<p>What are the pros/cons of using the aforementioned ... | 1 | 2016-07-10T12:07:50Z | 38,291,737 | <p>You should always try to use as much as possible the work that other people have already been doing for you (such as programming the pandas library). This saves you a lot of time. Pandas has a lot to offer when you want to process such files so this seems to me to be the the best way to deal with such files. Since t... | 1 | 2016-07-10T12:12:40Z | [
"python",
"csv"
] |
Using pandas over csv library for manipulating CSV files in Python3 | 38,291,701 | <p>Forgive me if my questions is too general, or if its been asked before. I've been tasked to manipulate (e.g. copy and paste several range of entries, perform calculations on them, and then save them all to a new csv file) several large datasets in Python3. </p>
<p>What are the pros/cons of using the aforementioned ... | 1 | 2016-07-10T12:07:50Z | 38,292,381 | <p>I have not used CSV library, but many people are enjoying the benefits of Pandas. Pandas provides a lot of the tools you'll need, based off Numpy. You can easily then use more advance libraries for all sorts of analysis (sklearn for machine learning, nltk for nlp, etc.).</p>
<p>For your purposes, you'll find it e... | 2 | 2016-07-10T13:27:01Z | [
"python",
"csv"
] |
SQLAlchemy subquery comparison | 38,291,728 | <p>I have the following set of tables:</p>
<pre><code>class Job(db.Model):
__tablename__ = 'jobs'
id = db.Column(db.Integer, primary_key=True)
class Informant(db.Model):
__tablename__ = 'informants'
id = db.Column(db.Integer, primary_key=True)
job_id = db.Column(db.Integer, db.ForeignKey('jobs.id... | 0 | 2016-07-10T12:11:42Z | 38,295,341 | <p>I was close to having the right answer. The piece that was missing is an <code>as_scalar</code> method on both subqueries. So the final query is:</p>
<pre><code>db.session.query(Job.id).filter( \
db.session.query(db.func.sum(Informant.max_students)). \
filter(Informant.job_id == Job.id).as_scalar() <... | 0 | 2016-07-10T18:47:40Z | [
"python",
"sqlalchemy"
] |
redirect_stderr does not work (Python 3.5) | 38,291,744 | <pre><code>#! python3
from contextlib import redirect_stderr
import io
f = io.StringIO()
with redirect_stderr(f):
# simulates an error
erd
</code></pre>
<p>As seen above, I have used the <code>redirect_stderr</code> function to redirect stderr to a <code>StringIO</code> object. However, it doesn't work, as t... | 0 | 2016-07-10T12:13:30Z | 38,291,925 | <p>You need to actually write to stderr, it is not a tool to catch exceptions.</p>
<pre><code>>>> from contextlib import redirect_stderr
>>> import io
>>> f = io.StringIO()
>>> import sys
>>> with redirect_stderr(f):
... print('Hello', file=sys.stderr)
...
>>> f... | 2 | 2016-07-10T12:35:39Z | [
"python",
"python-3.x",
"std",
"stderr"
] |
Python: edit text file by tkinter input | 38,291,805 | <p>I am using Python3. I'm trying to learn how to edit text files by changing the variables on the text file to a user input variables on GUI.
Here is my code:</p>
<pre><code>self.input = TK.Entry(self.root)
self.input.pack()
with open('fl.txt', 'r') as f:
lines = f.readlines()
self.a = lines[0].strip()
lines... | 0 | 2016-07-10T12:22:26Z | 38,291,887 | <p>If you use: </p>
<pre><code>from tkinter import *
</code></pre>
<p>I think you should remove the TK and write:</p>
<pre><code> self.input = Entry(self.root)
</code></pre>
| 1 | 2016-07-10T12:30:45Z | [
"python",
"python-3.x",
"tkinter"
] |
AttributeError: 'module' object has no attribute 'commit_on_success' | 38,291,894 | <p>I'm trying to use <code>Django-nested-inlines</code> application but it raises error. Here is a simple code:</p>
<p><strong>MODELS.PY</strong></p>
<pre><code>class Language_Quiz(models.Model):
name = models.CharField(max_length=40)
language = models.OneToOneField(sfl_models.Language)
class Question(model... | 1 | 2016-07-10T12:31:36Z | 38,293,037 | <p>As Kapil Sachdev and karthikr commented, the problem is with compatibility. <strong>Django-nested-inlines</strong> has probably some issues working with Django 1.8+.</p>
<p>In my case, the solution was very simple. Download using <code>pip</code> <code>Django-nested-inline</code> (without 's' at the end of the 'inl... | 0 | 2016-07-10T14:37:48Z | [
"python",
"django",
"django-models",
"django-admin"
] |
Python public methods inside classes? | 38,291,905 | <p>I cutted out code for better understanding my issue. The question is if there is some way how to create something like public method and how or whether I'm totally misunderstood OOP concept.</p>
<p>I have a major class <code>PlayerWindow</code> which only plays video. Then there is class <code>ControlsWindow</code>... | 1 | 2016-07-10T12:33:33Z | 38,292,000 | <p>You can pass an instance of <code>PlayerWindow</code> to the class constructor of <code>ControlsWindow</code>:</p>
<pre><code>class ControlsWindow(QtGui.QWidget):
def __init__(self, parent): # Notice the new parent argument
super(ControlsWindow, self).__init__()
self.parent = parent
self.playPauseB... | 1 | 2016-07-10T12:43:22Z | [
"python",
"class"
] |
Python public methods inside classes? | 38,291,905 | <p>I cutted out code for better understanding my issue. The question is if there is some way how to create something like public method and how or whether I'm totally misunderstood OOP concept.</p>
<p>I have a major class <code>PlayerWindow</code> which only plays video. Then there is class <code>ControlsWindow</code>... | 1 | 2016-07-10T12:33:33Z | 38,292,064 | <p>Assuming that I understand you correctly and your code can be simplified to something like:</p>
<pre><code># QtGui.QWidget
class B:
pass
# ControlsWindow
class Test(B):
def __init__(self):
# You want to call Actual.play here?
pass
# PlayerWindow
class Actual(B):
def __init__(self):
... | 1 | 2016-07-10T12:49:53Z | [
"python",
"class"
] |
Excel VLOOKUP equivalent in pandas | 38,291,908 | <p>I have following data frame:</p>
<pre><code> A B C
Index
2001-06-30 100 2001-08-31 (=value of A at date B)
2001-07-31 200 2001-09-30 ...
2001-08-31 300 2001-10-31 ...
2001-09-30 400 2001-11-30 ...
</code></pre>
<p>Column <co... | 3 | 2016-07-10T12:33:42Z | 38,291,973 | <p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.map.html"><code>map</code></a> by column <code>A</code>:</p>
<pre><code>df['C'] = df.B.map(df.A)
print (df)
A B C
Index
2001-06-30 100 2001-08-31 300.0
2001-07-31 ... | 5 | 2016-07-10T12:40:28Z | [
"python",
"pandas"
] |
Django: Python variable data as background image | 38,291,952 | <h1>Details and Problem:</h1>
<p>I am making a website which uses steam's social authentication and API, it saves users data in the database, and makes the session cookie that contains two main data, username and logged in cookies.</p>
<p><strong>The data which the variable contains is the url to the image</strong>, ... | 1 | 2016-07-10T12:38:17Z | 38,303,597 | <p>It's hard to answer this question without all of the details, but the first issue that comes to mind is that you are most likely referencing your context variable "picture" incorrectly. Again, I'm not sure by your question what exactly you are doing, but perhaps this example will help:</p>
<p>If I have a model name... | 0 | 2016-07-11T09:33:54Z | [
"python",
"html",
"css",
"django"
] |
Python Text to Dictionary doesn't work | 38,292,011 | <p>I have the following text file in the same folder as my Python Code.</p>
<pre><code>78459581
Black Ballpoint Pen
12345670
Football
49585922
Perfume
83799715
Shampoo
</code></pre>
<p>I have written this Python code.</p>
<pre><code>file = open("ProductDatabaseEdit.txt", "r")
d = {}
for line in file:
x = ... | 1 | 2016-07-10T12:44:22Z | 38,292,030 | <p>A line is terminated by a linebreak, thus <code>line.split("\n")</code> will never give you more than one line.</p>
<p>You could cheat and do:</p>
<pre><code>for first_line in file:
second_line = next(file)
</code></pre>
| 5 | 2016-07-10T12:46:22Z | [
"python",
"dictionary"
] |
Python Text to Dictionary doesn't work | 38,292,011 | <p>I have the following text file in the same folder as my Python Code.</p>
<pre><code>78459581
Black Ballpoint Pen
12345670
Football
49585922
Perfume
83799715
Shampoo
</code></pre>
<p>I have written this Python code.</p>
<pre><code>file = open("ProductDatabaseEdit.txt", "r")
d = {}
for line in file:
x = ... | 1 | 2016-07-10T12:44:22Z | 38,292,175 | <p>You need to strip the \n, not split</p>
<pre><code>file = open("products.txt", "r")
d = {}
for line in file:
a = line.strip()
b = file.next().strip()
# next(file).strip() # if using python 3.x
d[a]=b
print(d)
{'12345670': 'Football', '49585922': 'Perfume', '78459581': 'Black Ballpoint Pen', '83799... | 2 | 2016-07-10T13:04:46Z | [
"python",
"dictionary"
] |
Python Text to Dictionary doesn't work | 38,292,011 | <p>I have the following text file in the same folder as my Python Code.</p>
<pre><code>78459581
Black Ballpoint Pen
12345670
Football
49585922
Perfume
83799715
Shampoo
</code></pre>
<p>I have written this Python code.</p>
<pre><code>file = open("ProductDatabaseEdit.txt", "r")
d = {}
for line in file:
x = ... | 1 | 2016-07-10T12:44:22Z | 38,292,196 | <p>You can simplify your solution by using a <a href="https://wiki.python.org/moin/Generators" rel="nofollow">dictionary generator</a>, this is probably the most pythonic solution I can think of:</p>
<pre><code>>>> with open("in.txt") as f:
... my_dict = dict((line.strip(), next(f).strip()) for line in f)
.... | 2 | 2016-07-10T13:07:08Z | [
"python",
"dictionary"
] |
Python Text to Dictionary doesn't work | 38,292,011 | <p>I have the following text file in the same folder as my Python Code.</p>
<pre><code>78459581
Black Ballpoint Pen
12345670
Football
49585922
Perfume
83799715
Shampoo
</code></pre>
<p>I have written this Python code.</p>
<pre><code>file = open("ProductDatabaseEdit.txt", "r")
d = {}
for line in file:
x = ... | 1 | 2016-07-10T12:44:22Z | 38,292,204 | <p>In my solution i tried to not use any loops. Therefore, I first load the txt data with pandas: </p>
<pre><code>import pandas as pd
file = pd.read_csv("test.txt", header = None)
</code></pre>
<p>Then I seperate keys and values for the dict such as: </p>
<pre><code>keys, values = file[0::2].values, file[1::2].value... | 0 | 2016-07-10T13:07:57Z | [
"python",
"dictionary"
] |
Python Text to Dictionary doesn't work | 38,292,011 | <p>I have the following text file in the same folder as my Python Code.</p>
<pre><code>78459581
Black Ballpoint Pen
12345670
Football
49585922
Perfume
83799715
Shampoo
</code></pre>
<p>I have written this Python code.</p>
<pre><code>file = open("ProductDatabaseEdit.txt", "r")
d = {}
for line in file:
x = ... | 1 | 2016-07-10T12:44:22Z | 38,292,262 | <p>You can loop over a list two items at a time:</p>
<pre><code>file = open("ProductDatabaseEdit.txt", "r")
data = file.readlines()
d = {}
for line in range(0,len(data),2):
d[data[i]] = data[i+1]
</code></pre>
| 0 | 2016-07-10T13:14:59Z | [
"python",
"dictionary"
] |
Python Text to Dictionary doesn't work | 38,292,011 | <p>I have the following text file in the same folder as my Python Code.</p>
<pre><code>78459581
Black Ballpoint Pen
12345670
Football
49585922
Perfume
83799715
Shampoo
</code></pre>
<p>I have written this Python code.</p>
<pre><code>file = open("ProductDatabaseEdit.txt", "r")
d = {}
for line in file:
x = ... | 1 | 2016-07-10T12:44:22Z | 38,292,646 | <h1>What's going on</h1>
<p>When you open a file you get an iterator, which will give you one line at a time when you use it in a <em>for</em> loop. </p>
<p>Your code is iterating over the file, splitting every line in a list with <code>\n</code> as the delimiter, but <strong>that gives you a list with only one item<... | 1 | 2016-07-10T13:57:01Z | [
"python",
"dictionary"
] |
Python Text to Dictionary doesn't work | 38,292,011 | <p>I have the following text file in the same folder as my Python Code.</p>
<pre><code>78459581
Black Ballpoint Pen
12345670
Football
49585922
Perfume
83799715
Shampoo
</code></pre>
<p>I have written this Python code.</p>
<pre><code>file = open("ProductDatabaseEdit.txt", "r")
d = {}
for line in file:
x = ... | 1 | 2016-07-10T12:44:22Z | 38,305,646 | <p>Try this code (where the data is in <em>/tmp/tmp5.txt</em>):</p>
<pre><code>#!/usr/bin/env python3
d = dict()
iskey = True
with open("/tmp/tmp5.txt") as infile:
for line in infile:
if iskey:
_key = line.strip()
else:
_value = line.strip()
d[_key] = _value
... | 0 | 2016-07-11T11:19:42Z | [
"python",
"dictionary"
] |
Django looks for template under djstripe/templates/djstripe/ instead of djstripe/templates/ (TemplateDoesNotExist) | 38,292,047 | <p>I'm working on a Django 1.9.7 project using the dj-stripe library. I'm using the latest commit on the <a href="https://github.com/kavdev/dj-stripe/tree/%23162-api-updates-through_2015-07-28" rel="nofollow"><code>#162-api-updates-through_2015-07-28</code></a> branch of the dj-stripe repository, which is <code>1f0ed7c... | 0 | 2016-07-10T12:47:41Z | 38,292,299 | <p>In settings file, when 'DIRS' is left empty, Django will look for templates only in app_name/templates directory, because you have set 'APP_DIRS': True, by default.</p>
<pre><code>TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'APP_DIRS': True,
'DIRS': [],
... | 0 | 2016-07-10T13:19:00Z | [
"python",
"django",
"django-templates"
] |
Make pytest include functional tests in its count | 38,292,123 | <p>I'm starting a new project and trying to follow strict Test-Driven Development. I have a basic setup in place and working and am using <a href="http://pytest.org/latest/" rel="nofollow">pytest</a> to run tests.</p>
<p>Tests are discovered and run correctly. They fail when they should and pass when they should. But ... | 0 | 2016-07-10T12:57:59Z | 38,293,555 | <h2>Put it in a function.</h2>
<p>Okay, after playing around some more, I may have solved my own problem. This, for instance, works (the whole function gets counted as one test).</p>
<pre><code>def test_import():
# Can we import the package?
import packagename
</code></pre>
<p>I'll leave the question open to... | 1 | 2016-07-10T15:36:14Z | [
"python",
"functional-testing",
"py.test"
] |
python socket.error: [Errno 9] Bad file descriptor | 38,292,142 | <p>I wanted to make a server and a client with Python.
It was supposed to make multiple connections, one, where the server is sending something to the client, and one where the client is sending something to the server.</p>
<p>The first connection worked fine, but the second one crashed with the message:</p>
<pre><co... | 2 | 2016-07-10T13:00:23Z | 38,292,309 | <p>The reason is that you are trying to reconnect a <strong>closed</strong> socket. You have to either create a new socket or reuse the old one as long as it's connected. </p>
<p>In method <code>def sentHOT(...):</code> comment the line <code>self.s.close()</code> and in method <code>def add_event(...)</code> comment ... | 1 | 2016-07-10T13:19:57Z | [
"python",
"sockets"
] |
Can't append the last word from a text file to a list | 38,292,241 | <p>I want to make a list of words contained in a text file. But my code prints all but the last word of the file. What am I doing wrong ?</p>
<pre><code>def word_map(file):
text = file.read()
word = "" # used as a temporary variable
wordmap = []
for letter in text:
if letter != " ":
... | 0 | 2016-07-10T13:12:42Z | 38,292,264 | <p>When exiting the loop you are not appending the last word, just try this:</p>
<pre><code>def word_map(file):
text = file.read()
word = "" # used as a temporary variable
wordmap = []
for letter in text:
if letter != " ":
word = word+letter
else:
wordm... | 1 | 2016-07-10T13:15:05Z | [
"python",
"word-count"
] |
Can't append the last word from a text file to a list | 38,292,241 | <p>I want to make a list of words contained in a text file. But my code prints all but the last word of the file. What am I doing wrong ?</p>
<pre><code>def word_map(file):
text = file.read()
word = "" # used as a temporary variable
wordmap = []
for letter in text:
if letter != " ":
... | 0 | 2016-07-10T13:12:42Z | 38,292,277 | <p>I think you're missing a final :</p>
<pre><code>wordmap.append(word)
</code></pre>
<p>Because if your text file does not end with a space, it won't be appended</p>
| 0 | 2016-07-10T13:16:05Z | [
"python",
"word-count"
] |
Can't append the last word from a text file to a list | 38,292,241 | <p>I want to make a list of words contained in a text file. But my code prints all but the last word of the file. What am I doing wrong ?</p>
<pre><code>def word_map(file):
text = file.read()
word = "" # used as a temporary variable
wordmap = []
for letter in text:
if letter != " ":
... | 0 | 2016-07-10T13:12:42Z | 38,292,281 | <p>Just use <code>wordmap = text.split(" ")</code></p>
<p>I hope this helped, good luck.</p>
| 2 | 2016-07-10T13:16:35Z | [
"python",
"word-count"
] |
How to get current model object in Flask | 38,292,280 | <p>We stored authenticated user (model of User) using</p>
<pre><code>@app.route('/login', methods=['GET', 'POST'])
def login():
...
try:
current_user = User.query.filter(School_Login.mail == form_mail).first()
if user.mail == form_mail and user.password == form_pass:
...
</code></pre>
<p>W... | 0 | 2016-07-10T13:16:34Z | 38,292,360 | <p>To access variables in the same request context, in a different function or class, use the <strong>g</strong> object:</p>
<pre><code>from flask import g
g.current_user = ..
....
current_user = g.current_user
</code></pre>
<p>To do the same but between different requests, you use the <strong>session</strong> dict:<... | 0 | 2016-07-10T13:25:29Z | [
"python",
"mongodb",
"flask",
"mongoalchemy"
] |
XLS with formula in more than one cells within a column with Python | 38,292,310 | <p>After a long day playing with lots of variants I was left with this code:</p>
<pre><code>from xlrd import open_workbook
from xlwt import Workbook, Formula
from xlutils.copy import copy
rb = open_workbook("test.xls")
wb = copy(rb)
s = wb.get_sheet(0)
s.write(2,4, Formula('D3-B3') )
wb.save('test.xls')
</code></pre... | 0 | 2016-07-10T13:20:04Z | 38,292,481 | <p>With a simple loop:</p>
<pre><code>s = wb.get_sheet(0)
last_row = 10 # change to your last required row
for i in range(4, last_row + 1):
s.write(2, i, Formula('D{row}-B{row}'.format(row=i-1)))
wb.save('test.xls')
</code></pre>
| 1 | 2016-07-10T13:38:05Z | [
"python",
"excel",
"xls"
] |
Can Dictionaries in Python be considered objects from C++ with only Data Members? | 38,292,311 | <p>I am studying Python right now and I am learning about Dictionaries. Is it correct to compare dictionaries with objects from C++ who only contain data members and no methods? </p>
<p>Of course there is not class definition so every object instance can be declared differently in Python, but still I think it i a good... | 2 | 2016-07-10T13:20:09Z | 38,292,336 | <p>All values in Python are objects, dictionaries included. Dictionaries have methods too! For example, <code>dict.keys()</code> is a method, so Python's <code>dict</code> instances are <em>not</em> objects with only data members.</p>
<p>There <em>is</em> a class definition for dictionaries; just because it is defined... | 1 | 2016-07-10T13:22:42Z | [
"python",
"class",
"object",
"dictionary"
] |
Can Dictionaries in Python be considered objects from C++ with only Data Members? | 38,292,311 | <p>I am studying Python right now and I am learning about Dictionaries. Is it correct to compare dictionaries with objects from C++ who only contain data members and no methods? </p>
<p>Of course there is not class definition so every object instance can be declared differently in Python, but still I think it i a good... | 2 | 2016-07-10T13:20:09Z | 38,292,385 | <p>Is it correct to compare dictionaries with objects from C++ who only contain data members and no methods? <strong>NO</strong></p>
<p>A dictionary is a data-structure which is analogous to <code>std::unordered_map</code>, though the implementation might differ.</p>
<p>An object is an instance of a class. Both C++ a... | 2 | 2016-07-10T13:27:30Z | [
"python",
"class",
"object",
"dictionary"
] |
How to count rows not values in python pandas? | 38,292,340 | <p>I would like to group DataFrame by some field like</p>
<pre><code>student_data.groupby(['passed'])
</code></pre>
<p>and then count number of rows inside each group. </p>
<p>I know how to count values like</p>
<pre><code>student_data.groupby(['passed'])['passed'].count()
</code></pre>
<p>or</p>
<pre><code>stude... | 1 | 2016-07-10T13:23:08Z | 38,292,772 | <p>You need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.value_counts.html" rel="nofollow"><code>value_counts</code></a> with parameter <code>dropna=False</code>:</p>
<pre><code>import pandas as pd
import numpy as np
student_data = pd.DataFrame({'passed':[1,1,2,2,2,np.nan,np.nan]})
pri... | 3 | 2016-07-10T14:07:57Z | [
"python",
"pandas"
] |
How to count rows not values in python pandas? | 38,292,340 | <p>I would like to group DataFrame by some field like</p>
<pre><code>student_data.groupby(['passed'])
</code></pre>
<p>and then count number of rows inside each group. </p>
<p>I know how to count values like</p>
<pre><code>student_data.groupby(['passed'])['passed'].count()
</code></pre>
<p>or</p>
<pre><code>stude... | 1 | 2016-07-10T13:23:08Z | 38,292,851 | <p>You can use the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.apply.html" rel="nofollow">groupby.aggregate</a> method to compute some function on each group:</p>
<pre><code>student_data.groupby("passed").aggregate(len)
</code></pre>
| 2 | 2016-07-10T14:17:43Z | [
"python",
"pandas"
] |
How to force 'mkproject' (virtualenvwrapper) to use python3 as default? | 38,292,345 | <p>I've added the following lines to my bash, but <code>mkproject</code> keeps creating python 2.7 folders into the virtual env, therefore I still need to use <code>-p python3</code>, which I'd like to not have to do.</p>
<pre><code>export VIRTUALENVWRAPPER_SCRIPT=/usr/local/bin/virtualenvwrapper.sh
export VIRTUALENVW... | 2 | 2016-07-10T13:23:39Z | 38,293,148 | <p><code>virtualenvwrapper</code> understands the <code>VIRTUALENVWRAPPER_VIRTUALENV</code> environment variable, you need to set it to the <code>virtualenv</code> appropriate to the python version you're using. For example:</p>
<pre><code>export VIRTUALENVWRAPPER_VIRTUALENV=virtualenv3
</code></pre>
<p>This is need... | 1 | 2016-07-10T14:49:22Z | [
"python",
"python-2.7",
"python-3.x",
"virtualenv",
"virtualenvwrapper"
] |
frozenset at least x elements | 38,292,379 | <p>I currently have this code, it checks if all elements in the array are the same. If this is the case, return true</p>
<pre><code>def all_equal(lst):
"""
>>> all_equal([1,1,1,1,1,1,1])
True
>>> all_equal([1,2,3,1])
False
"""
return len(frozenset(lst)) == 1
</code></pre>
<p>But what I... | 3 | 2016-07-10T13:26:58Z | 38,292,424 | <p>Instead of using a set, use a <a href="https://en.wikipedia.org/wiki/Multiset" rel="nofollow"><em>bag</em> or <em>multiset</em> type</a>. A multiset counts how many times unique values occur.</p>
<p>In Python that's the <a href="https://docs.python.org/2/library/collections.html#collections.Counter" rel="nofollow">... | 7 | 2016-07-10T13:31:59Z | [
"python",
"frozenset"
] |
frozenset at least x elements | 38,292,379 | <p>I currently have this code, it checks if all elements in the array are the same. If this is the case, return true</p>
<pre><code>def all_equal(lst):
"""
>>> all_equal([1,1,1,1,1,1,1])
True
>>> all_equal([1,2,3,1])
False
"""
return len(frozenset(lst)) == 1
</code></pre>
<p>But what I... | 3 | 2016-07-10T13:26:58Z | 38,292,432 | <p>Use <a href="https://docs.python.org/3/library/collections.html#collections.Counter"><code>collections.Counter()</code></a>:</p>
<pre><code>from collections import Counter
def all_equal(lst, count):
return any(v >= count for v in Counter(lst).values())
</code></pre>
| 8 | 2016-07-10T13:33:04Z | [
"python",
"frozenset"
] |
frozenset at least x elements | 38,292,379 | <p>I currently have this code, it checks if all elements in the array are the same. If this is the case, return true</p>
<pre><code>def all_equal(lst):
"""
>>> all_equal([1,1,1,1,1,1,1])
True
>>> all_equal([1,2,3,1])
False
"""
return len(frozenset(lst)) == 1
</code></pre>
<p>But what I... | 3 | 2016-07-10T13:26:58Z | 38,292,439 | <p>Short answer using <code>Counter</code>:</p>
<pre><code>from collections import Counter
def some_equal(lst):
return max(Counter(lst).values()) >= 5
</code></pre>
<p><code>Counter</code> is a "set" counting occurences of its elements.
<code>Counter.keys()</code> returns the elements, and <code>Counter().va... | 3 | 2016-07-10T13:33:48Z | [
"python",
"frozenset"
] |
frozenset at least x elements | 38,292,379 | <p>I currently have this code, it checks if all elements in the array are the same. If this is the case, return true</p>
<pre><code>def all_equal(lst):
"""
>>> all_equal([1,1,1,1,1,1,1])
True
>>> all_equal([1,2,3,1])
False
"""
return len(frozenset(lst)) == 1
</code></pre>
<p>But what I... | 3 | 2016-07-10T13:26:58Z | 38,292,554 | <p>You could also check as you go, short circuiting as you iterate if any value is 5:</p>
<pre><code>from collections import defaultdict
def five(it):
d = defaultdict(int)
for ele in it:
d[ele] += 1
if d[ele] == 5:
return True
return False
</code></pre>
<p>You could use a Cou... | 2 | 2016-07-10T13:46:14Z | [
"python",
"frozenset"
] |
How to create html file after HTTP GET request in scapy | 38,292,497 | <p>I need some help with scapy and python.
I sending get request to spesific site... and then with sniff and HTTP filter I am filtering the relevant packets and then i want to get only the HTML code but i dont know how to do this...</p>
<pre><code>os.system('iptables -A OUTPUT -p tcp --tcp-flags RST RST -j DROP')
os.s... | 0 | 2016-07-10T13:40:52Z | 38,292,889 | <p>Something like this?</p>
<pre><code>import urllib2
re = urllib2.urlopen("http://www.website.org")
html = re.read()
f = open("html.html", "w")
f.write(html)
f.close()
</code></pre>
| -1 | 2016-07-10T14:21:15Z | [
"python",
"html",
"http",
"scapy",
"packets"
] |
Parsing JSON array for certain strings in Python | 38,292,505 | <p>I'm trying to get certain strings from a website but having difficulty. This is the array (blocking out certain values)</p>
<pre><code>{
"ts": 1468156734285,
"inbox": "email",
"created": 302,
"expire_in": 86098,
"last_eml": 1468156432,
"emls": [{
"eml": "this is the email id",
... | 0 | 2016-07-10T13:41:21Z | 38,292,584 | <p>This should be pretty straightforward, given that <code>data</code> is the dictionary you provided:</p>
<pre><code>data = {
"ts": 1468156734285,
"inbox": "email",
"created": 302,
"expire_in": 86098,
"last_eml": 1468156432,
"emls": [{
"eml": "this is the email id",
"eml_hash": "email hash",
"eml_destroy_... | 0 | 2016-07-10T13:49:52Z | [
"python",
"arrays",
"json"
] |
Parsing JSON array for certain strings in Python | 38,292,505 | <p>I'm trying to get certain strings from a website but having difficulty. This is the array (blocking out certain values)</p>
<pre><code>{
"ts": 1468156734285,
"inbox": "email",
"created": 302,
"expire_in": 86098,
"last_eml": 1468156432,
"emls": [{
"eml": "this is the email id",
... | 0 | 2016-07-10T13:41:21Z | 38,292,608 | <p>What you are doing is actually indexing the root of the dictionary, <code>data</code>, again. Therefore, you wouldn't get the expected output:</p>
<pre><code>response = requests.get(url)
data = response.json()
print data
emal = data['emls']
# You should not be indexing data again. Note that emls is a list too.
eml_... | 0 | 2016-07-10T13:52:52Z | [
"python",
"arrays",
"json"
] |
Parsing JSON array for certain strings in Python | 38,292,505 | <p>I'm trying to get certain strings from a website but having difficulty. This is the array (blocking out certain values)</p>
<pre><code>{
"ts": 1468156734285,
"inbox": "email",
"created": 302,
"expire_in": 86098,
"last_eml": 1468156432,
"emls": [{
"eml": "this is the email id",
... | 0 | 2016-07-10T13:41:21Z | 38,292,613 | <p>This code</p>
<pre><code>response = requests.get(url)
data = response.json()
print data
emls = data['emls'] # emls = [{'status': 'unread','received': 0,...}]
</code></pre>
<p>Makes <code>emls</code> equal the list with a dictionary inside. So you need to take the first (0th) item of that list. Then you can use the... | 1 | 2016-07-10T13:53:11Z | [
"python",
"arrays",
"json"
] |
how to delete multiple random keywords from a file using python | 38,292,563 | <p>I have a file named hello.txt , which contains the following:</p>
<pre class="lang-none prettyprint-override"><code>1 one
2 two
3 three
4 four
5 five
</code></pre>
<p>Now I as a user choose to remove two keywords from this file, namely four and two, in one single click.</p>
| -3 | 2016-07-10T13:47:16Z | 38,292,638 | <p>Implementations may vary depending on file format, libraries used and such.</p>
<p>Let's assume we have a file like:</p>
<pre><code>file = "1 one\n" \
"2 two\n" \
"3 three\n" \
"4 four\n" \
"5 five\n"
</code></pre>
<p>Our keywords to remove are as following:</p>
<pre><code>keys_to_rem... | 0 | 2016-07-10T13:55:46Z | [
"python",
"file"
] |
how to delete multiple random keywords from a file using python | 38,292,563 | <p>I have a file named hello.txt , which contains the following:</p>
<pre class="lang-none prettyprint-override"><code>1 one
2 two
3 three
4 four
5 five
</code></pre>
<p>Now I as a user choose to remove two keywords from this file, namely four and two, in one single click.</p>
| -3 | 2016-07-10T13:47:16Z | 38,292,817 | <p>Try opening your file into a list of lists, then looping through to remove any with the keyword.</p>
<pre><code>file = open('hello.txt','r')
fileData = file.readlines()
newFileData = []
file.close()
removeThese = ['two','four']
for line in fileData:
line = line.split(' ')
if line[1] not in removeThese:
... | 0 | 2016-07-10T14:13:34Z | [
"python",
"file"
] |
how to delete multiple random keywords from a file using python | 38,292,563 | <p>I have a file named hello.txt , which contains the following:</p>
<pre class="lang-none prettyprint-override"><code>1 one
2 two
3 three
4 four
5 five
</code></pre>
<p>Now I as a user choose to remove two keywords from this file, namely four and two, in one single click.</p>
| -3 | 2016-07-10T13:47:16Z | 38,293,017 | <p>my basic query is :</p>
<p>i have a file "hello.txt"
its content are like this --></p>
<p>1 sony
2 samsung
3 nokia
4 iphone
5 toshibha</p>
<p>now user will be asked which two mobile u want to check out </p>
<p>then user will give 3 and 5 </p>
<p>So after accepting the user request the two mobiles should be dele... | 0 | 2016-07-10T14:35:42Z | [
"python",
"file"
] |
how to delete multiple random keywords from a file using python | 38,292,563 | <p>I have a file named hello.txt , which contains the following:</p>
<pre class="lang-none prettyprint-override"><code>1 one
2 two
3 three
4 four
5 five
</code></pre>
<p>Now I as a user choose to remove two keywords from this file, namely four and two, in one single click.</p>
| -3 | 2016-07-10T13:47:16Z | 38,293,048 | <p>Try this out.</p>
<pre><code>new_file_data = []
file_data = [line.strip() for line in open("test.txt", "r")]
remove = ["five"]
for c in file_data:
if c not in remove:
new_file_data.append(c)
with open("test.txt","w") as file:
for c in new_file_data:
file.write("".join(c) + ... | 0 | 2016-07-10T14:39:08Z | [
"python",
"file"
] |
SIFT from OpenCV in kaggle script editor | 38,292,577 | <p>I am trying to use SIFT from OpenCV for image object recongnition, so I started with this code to test the environment:</p>
<pre><code>import cv2
img = cv2.imread('../input/train_2/2.jpg')
gray= cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
sift = cv2.xfeatures2d.SIFT_create()
kp = sift.detect(gray,None)
img=cv2.drawKeypoi... | 0 | 2016-07-10T13:49:01Z | 38,293,866 | <p>SIFT is part from the <a href="https://github.com/opencv/opencv_contrib" rel="nofollow">opencv-contrib</a> package, which is not shipped with the opencv package contain experimental and non-free modules - so be aware of the licensing and so...</p>
<p>You should build opencv with the extra modules, you need to:</p>
... | 0 | 2016-07-10T16:09:23Z | [
"python",
"opencv",
"sift"
] |
Scope of Spark's `persist` or `cache` | 38,292,621 | <p>I am confused about RDD's scoping in Spark.</p>
<p>According to <a href="http://stackoverflow.com/questions/32911128/scope-of-cached-rdds">this thread</a></p>
<blockquote>
<p>Whether an RDD is cached or not is part of the mutable state of the RDD object. If you call rdd.cache it will be marked for caching from t... | 1 | 2016-07-10T13:54:08Z | 38,293,276 | <p>Yes, when an RDD is garbage collected, it is unpersisted. So outside of myFun, newRdd is unpersisted (assuming you do not return it nor a derived rdd), you can also check this <a href="http://stackoverflow.com/questions/32636822/would-spark-unpersist-the-rdd-itself-when-it-realizes-it-wont-be-used-anymore">answer</a... | 1 | 2016-07-10T15:02:54Z | [
"python",
"apache-spark",
"scope",
"rdd"
] |
How to apply random.uniform to two columns of a dataframe? | 38,292,905 | <p>How to apply random.uniform to two columns of a dataframe?</p>
<pre><code>df = pd.DataFrame(np.random.randn(6,4),columns=list('ABCD'))
def f(x):
return random.uniform(x[0],x[1])
df['E'] = f(df[['A','B']])
</code></pre>
| 3 | 2016-07-10T14:22:32Z | 38,292,984 | <p>A vectorized approach would be:</p>
<pre><code>df['E'] = (df.B - df.A) * np.random.rand(df.shape[0]) + df.A
</code></pre>
<p>Same as:</p>
<pre><code>df['E'] = (df.B - df.A) * np.random.uniform(size=df.shape[0]) + df.A
</code></pre>
<hr>
<h3>Timing 1 million rows</h3>
<p>Don't use apply over large datasets if y... | 5 | 2016-07-10T14:32:04Z | [
"python",
"pandas"
] |
How to make pylint recognize variable via astroid | 38,292,993 | <p>I'm trying to "teach" pylint to recognize member function, my scenario can be simplified to the following:</p>
<p>Main module: a.py</p>
<pre><code>from plugins import plu
class FooClass(object):
def bar(self):
self.plu.foo("asdasd")
if __name__ == '__main__':
a = FooClass()
for plugin_name, p... | 1 | 2016-07-10T14:32:45Z | 38,293,212 | <p>You need to instantiate the plugin class when adding it to the locals of the FooClass. So replace this line <code>foo_cls[0].locals['plu'] = plugin_cls_def.lookup('Plugin')[1]</code> with <code>foo_cls[0].locals['plu'] = [cls.instantiate_class() for cls in plugin_cls_def.lookup('Plugin')[1]]</code></p>
| 1 | 2016-07-10T14:56:08Z | [
"python",
"django",
"pylint"
] |
Finding a probability density function that reproduces a histogram in Python | 38,293,018 | <p>So all the data that I actually have is a picture of a histogram from which I can get heights and bin width, the median and one sigma errors.</p>
<p>The histogram is skewed, so the 16th and 84th quantile are not symmetric. I found that the median and the errors can be replicated with a skewed gaussian function, how... | 0 | 2016-07-10T14:35:48Z | 38,328,774 | <p>IMO your best shot is to treat the data as points and fit a function with <a href="http://docs.scipy.org/doc/scipy-0.15.1/reference/generated/scipy.optimize.curve_fit.html" rel="nofollow">scipy.optimize.curve_fit</a></p>
<p><a href="http://stackoverflow.com/questions/5884768/skew-normal-distribution-in-scipy">This ... | 0 | 2016-07-12T12:21:43Z | [
"python",
"scipy",
"histogram",
"curve-fitting",
"probability-density"
] |
Check for invalid input | 38,293,185 | <p>I'm writing a program that will take a string as an input and check if the elements in it are valid or not.
I want my input to only contain lower characters and periods, exclamation marks, and space and not an empty string. If the user enter an empty string or invalid character they will be asked to re-enter the str... | 6 | 2016-07-10T14:53:27Z | 38,293,221 | <p>You can use a set of allowed chars checking if the set is a <em>superset</em> of the string entered:</p>
<pre><code>allowed = set("abcdefghijklmnopqrstuvwxyz! .")
while True:
message = input("Enter message: ")
if message and allowed.issuperset(message):
# do whatever
break
print("Inval... | 4 | 2016-07-10T14:57:03Z | [
"python",
"while-loop",
"caesar-cipher",
"invalid-characters"
] |
Check for invalid input | 38,293,185 | <p>I'm writing a program that will take a string as an input and check if the elements in it are valid or not.
I want my input to only contain lower characters and periods, exclamation marks, and space and not an empty string. If the user enter an empty string or invalid character they will be asked to re-enter the str... | 6 | 2016-07-10T14:53:27Z | 38,293,260 | <pre><code>import re
while True:
txt = input('Enter message: ').strip()
if re.match(r'^[a-z\. !]+$', txt):
break
print('Mistakes:', re.findall(r'[^a-z\. !]', txt))
print('correct!')
</code></pre>
| 2 | 2016-07-10T15:01:23Z | [
"python",
"while-loop",
"caesar-cipher",
"invalid-characters"
] |
Check for invalid input | 38,293,185 | <p>I'm writing a program that will take a string as an input and check if the elements in it are valid or not.
I want my input to only contain lower characters and periods, exclamation marks, and space and not an empty string. If the user enter an empty string or invalid character they will be asked to re-enter the str... | 6 | 2016-07-10T14:53:27Z | 38,293,288 | <p>Give a look at <strong>string.punctuation</strong> python function. You can also set which inputs are allowed/not allowed.</p>
| 0 | 2016-07-10T15:05:52Z | [
"python",
"while-loop",
"caesar-cipher",
"invalid-characters"
] |
Check for invalid input | 38,293,185 | <p>I'm writing a program that will take a string as an input and check if the elements in it are valid or not.
I want my input to only contain lower characters and periods, exclamation marks, and space and not an empty string. If the user enter an empty string or invalid character they will be asked to re-enter the str... | 6 | 2016-07-10T14:53:27Z | 38,293,344 | <p>a more advanced regex that only allows correct sentences:</p>
<pre><code>import re
while True:
txt = input('Enter message: ').strip()
if re.match(r'^[a-z]+[\.\!]?([ ][a-z]+[\.\!]?)*$', txt):
break
</code></pre>
<p>will allow:</p>
<pre><code>ipsum. asd.
dolor sit amet consectetur adipiscing elit!
a... | 1 | 2016-07-10T15:13:15Z | [
"python",
"while-loop",
"caesar-cipher",
"invalid-characters"
] |
How can I make windows in Tkinter that run in succession? (Python 2.7.11) | 38,293,303 | <p>I want to have a login window pop up at first, then once the conditions are satisfied, it <em>closes</em> the login window and <em>opens</em> a new window.</p>
<pre><code>from Tkinter import *
import tkMessageBox
#Not really sure what i'm doing here anymore
while True:
Login = Tk()
Login.title('Login')
... | 0 | 2016-07-10T15:08:24Z | 38,293,589 | <p>You don't want to use two <code>mainloop</code>'s. Generally speaking, your tkinter app should have a single <code>.mainloop</code> called.</p>
<p>As for how to get the login popup and then switch to the window... You can create your root window with the app and when you start your program have a <code>Toplevel</co... | 1 | 2016-07-10T15:39:48Z | [
"python",
"database",
"login",
"tkinter"
] |
How can I make windows in Tkinter that run in succession? (Python 2.7.11) | 38,293,303 | <p>I want to have a login window pop up at first, then once the conditions are satisfied, it <em>closes</em> the login window and <em>opens</em> a new window.</p>
<pre><code>from Tkinter import *
import tkMessageBox
#Not really sure what i'm doing here anymore
while True:
Login = Tk()
Login.title('Login')
... | 0 | 2016-07-10T15:08:24Z | 38,298,403 | <p>I want to thank you for clarifying what you did for me. It proved to be very helpful! Here is what I've settled with. I put the names back and made it to work without classes, as I found it a little too difficult to work with.</p>
<pre><code>from Tkinter import *
import tkMessageBox
import sys
import binascii #Not... | 0 | 2016-07-11T02:39:28Z | [
"python",
"database",
"login",
"tkinter"
] |
sorting key-value pairs in python | 38,293,418 | <p>I am working on a small program as written below</p>
<pre><code>"""Count words."""
# TODO: Count the number of occurences of each word in s
# TODO: Sort the occurences in descending order (alphabetically in case of ties)
# TODO: Return the top n words as a list of tuples (<word>, <count>) ... | 0 | 2016-07-10T15:21:47Z | 38,293,489 | <p>According to the comment at the top, you want to return a list of tuples of key/value. As such, you want to sort the dictionary's <em>items</em> by the value:</p>
<pre><code>sorted(temp.items(), key=itemgetter(1), reverse=True)
</code></pre>
<p>Note that your strategy of sorting the keys and the values separately... | 3 | 2016-07-10T15:29:02Z | [
"python",
"sorting",
"keyvaluepair"
] |
sorting key-value pairs in python | 38,293,418 | <p>I am working on a small program as written below</p>
<pre><code>"""Count words."""
# TODO: Count the number of occurences of each word in s
# TODO: Sort the occurences in descending order (alphabetically in case of ties)
# TODO: Return the top n words as a list of tuples (<word>, <count>) ... | 0 | 2016-07-10T15:21:47Z | 38,293,518 | <pre><code>sorted([(value,key) for (key,value) in temp.items()])
</code></pre>
| 0 | 2016-07-10T15:32:28Z | [
"python",
"sorting",
"keyvaluepair"
] |
sorting key-value pairs in python | 38,293,418 | <p>I am working on a small program as written below</p>
<pre><code>"""Count words."""
# TODO: Count the number of occurences of each word in s
# TODO: Sort the occurences in descending order (alphabetically in case of ties)
# TODO: Return the top n words as a list of tuples (<word>, <count>) ... | 0 | 2016-07-10T15:21:47Z | 38,293,559 | <p>You can sort dictionary by the value like this:</p>
<pre><code>sorted(temp.items(), key = lambda x: x[1], reverse = True)
</code></pre>
| 0 | 2016-07-10T15:36:58Z | [
"python",
"sorting",
"keyvaluepair"
] |
Benchmarks for Python | 38,293,471 | <p>I want to create a list of Python benchmarks. Now I've found only standard benchmarks from <a href="http://stackoverflow.com/questions/34057850/benchmarks-for-cpython">this</a> question and some from <a href="https://benchmarksgame.alioth.debian.org/u64q/python.html" rel="nofollow">Computer Language Benchmarks Game<... | 0 | 2016-07-10T15:27:28Z | 38,293,616 | <p><a href="https://pybenchmarks.org/" rel="nofollow">Python Interpreters Benchmarks</a> </p>
| 1 | 2016-07-10T15:43:20Z | [
"python",
"performance"
] |
Django 1.9 + Passenger on Dreamhost: Web application could not be started | 38,293,498 | <p>I'm trying to use Django 1.9 (With Python 3.4) on Dreamhost shared hosting.</p>
<p>I followed this tutorial:
<a href="https://brobin.me/blog/2015/03/deploying-django-with-virtualenv-on-dreamhost/" rel="nofollow">https://brobin.me/blog/2015/03/deploying-django-with-virtualenv-on-dreamhost/</a></p>
<p>And now my pas... | 0 | 2016-07-10T15:30:10Z | 38,310,297 | <p>This was solved by using the correct settings in the passenger_wsgi.py:</p>
<pre><code>import sys, os
cwd = os.getcwd()
sys.path.append(cwd)
project_location = cwd + '/my_project'
sys.path.insert(0,project_location)
INTERP = os.path.expanduser("/home/user/python/Python-3.4.3/venv/bin/python")
if sys.executable !=... | 1 | 2016-07-11T15:05:21Z | [
"python",
"django",
"passenger",
"dreamhost"
] |
Regular expression matching liquid code | 38,293,572 | <p>I'm building a website using Jekyll I would like to automatically remove liquid code (and <strong>only</strong> liquid code) from a given HTML file. I'm doing it in Python using regular expressions, and so far I have this one:</p>
<pre class="lang-regex prettyprint-override"><code>\{.*?\}|\{\{.*?\}\}
</code></pre>
... | -2 | 2016-07-10T15:37:54Z | 38,293,645 | <p>I actually don't know liquid but I assume that a block of code is always contained in either {} or {{}}. I think it is hard to find a regular expression that will not match something like this:</p>
<pre><code>print "This is my string with a number {}, cool!".format(42)
</code></pre>
<p>I would suggest that you ope... | -1 | 2016-07-10T15:45:49Z | [
"python",
"html",
"regex",
"liquid"
] |
Regular expression matching liquid code | 38,293,572 | <p>I'm building a website using Jekyll I would like to automatically remove liquid code (and <strong>only</strong> liquid code) from a given HTML file. I'm doing it in Python using regular expressions, and so far I have this one:</p>
<pre class="lang-regex prettyprint-override"><code>\{.*?\}|\{\{.*?\}\}
</code></pre>
... | -2 | 2016-07-10T15:37:54Z | 38,294,248 | <p>I am <strong>not</strong> saying that you should but you <strong>could</strong> use a "dirty" solution like:</p>
<pre><code>{%\ (if)[\s\S]*?{%\ end\1\ %}|
{%.+?%}|
{{.+?}}
</code></pre>
<p>This matches all of the template code provided, see <a href="https://regex101.com/r/mH5aT2/1" rel="nofollow"><strong>a demo on... | 0 | 2016-07-10T16:49:57Z | [
"python",
"html",
"regex",
"liquid"
] |
How do I access the timeit magic function directly | 38,293,593 | <p>I want to run timing on a larger scale and output dataframes of results from the iPython <code>%timeit</code> magic function. I don't want to rewrite it. How should I access directly?</p>
<p>I'd like something like this:</p>
<pre><code>f = lambda x: (x * 4. + 2) ** .5
for i in xrange(3):
print timeit(f(i))
... | 0 | 2016-07-10T15:40:22Z | 38,293,623 | <p>You could import the <a href="https://docs.python.org/3/library/timeit.html" rel="nofollow"><code>timeit</code></a> module and manually specify the number of iterations:</p>
<pre><code>from timeit import timeit
f = lambda x: (x * 4. + 2) ** .5
for i in xrange(3):
num = 100
print '%s: %s'%(num, timeit('f(... | 5 | 2016-07-10T15:43:59Z | [
"python",
"ipython"
] |
pandas filter if name appears in column more than n times | 38,293,605 | <p>this is my dataframe</p>
<pre><code>df = pd.DataFrame({'Col1':['Joe','Bob','Joe','Joe'],
'Col2':[55,25,88,80]})
</code></pre>
<p>I only want the names of if it appears more than once in 'Col1'</p>
<p>I can do it like this</p>
<pre><code>grouped = df.groupby("Col1")
grouped.filter(lambda x: x["C... | 4 | 2016-07-10T15:41:08Z | 38,293,618 | <p>Use <code>value_counts</code> and <code>isin</code></p>
<pre><code>vc = df.Col1.value_counts() > 2
vc = vc[vc]
df.loc[df.Col1.isin(vc.index)]
</code></pre>
<p><a href="http://i.stack.imgur.com/fTVzR.png" rel="nofollow"><img src="http://i.stack.imgur.com/fTVzR.png" alt="enter image description here"></a></p>
| 4 | 2016-07-10T15:43:30Z | [
"python",
"python-3.x",
"pandas"
] |
pandas filter if name appears in column more than n times | 38,293,605 | <p>this is my dataframe</p>
<pre><code>df = pd.DataFrame({'Col1':['Joe','Bob','Joe','Joe'],
'Col2':[55,25,88,80]})
</code></pre>
<p>I only want the names of if it appears more than once in 'Col1'</p>
<p>I can do it like this</p>
<pre><code>grouped = df.groupby("Col1")
grouped.filter(lambda x: x["C... | 4 | 2016-07-10T15:41:08Z | 38,293,712 | <p>Here's a NumPy based solution using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.unique.html" rel="nofollow"><code>np.unique</code></a> -</p>
<pre><code>unq,count = np.unique(df.Col1,return_counts=True)
out = unq[count>n]
</code></pre>
<p>Sample run -</p>
<pre><code>In [34]: df
Out[34]:
... | 3 | 2016-07-10T15:52:54Z | [
"python",
"python-3.x",
"pandas"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.