title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags list |
|---|---|---|---|---|---|---|---|---|---|
Regex in Python to find Rows in Table | 39,580,495 | <p>i`m using python to automate some test, and at one point i find a table with rows, but this rows are of two different clases:</p>
<p>You have class name "gris-claro-tr" and "gris-oscuro-tr".</p>
<p>I need to iterate the whole table, finding the text of every row. Until now, i have:</p>
<pre><code> for row ... | 1 | 2016-09-19T19:16:11Z | 39,580,588 | <p>You can approach it with a <em>CSS selector</em>:</p>
<pre><code>driver.find_elements_by_css_selector(".gris-claro-tr,.gris-oscuro-tr")
</code></pre>
<p><code>,</code> here means "or", dot defines a class name selector.</p>
<hr>
<p>Or, you can apply the partial matches as well, a little bit less explicit though:... | 1 | 2016-09-19T19:22:44Z | [
"python",
"regex",
"webdriver"
] |
Regex in Python to find Rows in Table | 39,580,495 | <p>i`m using python to automate some test, and at one point i find a table with rows, but this rows are of two different clases:</p>
<p>You have class name "gris-claro-tr" and "gris-oscuro-tr".</p>
<p>I need to iterate the whole table, finding the text of every row. Until now, i have:</p>
<pre><code> for row ... | 1 | 2016-09-19T19:16:11Z | 39,580,665 | <p>If you insist on XPATH you can use</p>
<pre><code>driver.find_elements_by_xpath("//*[@class='gris-claro-tr'] or [@class='gris-oscuro-td'] ")
</code></pre>
<p><code>*</code> can be replced by your tag name</p>
| 0 | 2016-09-19T19:28:55Z | [
"python",
"regex",
"webdriver"
] |
Python: (Beautifulsoup) How to limit extracted text from a html news article to only the news article. | 39,580,633 | <p>I wrote this test code which uses BeautifulSoup.</p>
<pre><code>url = "http://www.dailymail.co.uk/news/article-3795511/Harry-Potter-sale-half-million-pound-house-Iconic-Privet-Drive-market-suburban-Berkshire-complete-cupboard-stairs-one-magical-boy.html"
html = urllib.request.urlopen(url).read()
soup = Beauti... | 2 | 2016-09-19T19:26:14Z | 39,580,690 | <p>You'll need to target more specifically than just the <code>p</code> tag. Try looking for a <code>div class="article"</code> or something similar, then only grab paragraphs from there</p>
| 1 | 2016-09-19T19:30:33Z | [
"python",
"html",
"beautifulsoup"
] |
Python: (Beautifulsoup) How to limit extracted text from a html news article to only the news article. | 39,580,633 | <p>I wrote this test code which uses BeautifulSoup.</p>
<pre><code>url = "http://www.dailymail.co.uk/news/article-3795511/Harry-Potter-sale-half-million-pound-house-Iconic-Privet-Drive-market-suburban-Berkshire-complete-cupboard-stairs-one-magical-boy.html"
html = urllib.request.urlopen(url).read()
soup = Beauti... | 2 | 2016-09-19T19:26:14Z | 39,581,216 | <p>You might have much better luck with <a href="http://newspaper.readthedocs.io/en/latest/" rel="nofollow"><code>newspaper</code> library</a> which is focused on scraping articles.</p>
<p>If we talk about <code>BeautifulSoup</code> only, one option to get closer to the desired result and have more relevant paragraphs... | 1 | 2016-09-19T20:05:43Z | [
"python",
"html",
"beautifulsoup"
] |
Python: (Beautifulsoup) How to limit extracted text from a html news article to only the news article. | 39,580,633 | <p>I wrote this test code which uses BeautifulSoup.</p>
<pre><code>url = "http://www.dailymail.co.uk/news/article-3795511/Harry-Potter-sale-half-million-pound-house-Iconic-Privet-Drive-market-suburban-Berkshire-complete-cupboard-stairs-one-magical-boy.html"
html = urllib.request.urlopen(url).read()
soup = Beauti... | 2 | 2016-09-19T19:26:14Z | 39,581,286 | <p>Be more specific, you need to catch the <code>div</code> with <code>class</code> <code>articleBody</code>, so :</p>
<pre><code>import urllib.request
from bs4 import BeautifulSoup
url = "http://www.dailymail.co.uk/news/article-3795511/Harry-Potter-sale-half-million-pound-house-Iconic-Privet-Drive-market-suburban-Be... | 1 | 2016-09-19T20:10:21Z | [
"python",
"html",
"beautifulsoup"
] |
Python: Threading specific number of times | 39,580,662 | <p>I have the following code that uses <code>threading</code> and prints the current count.</p>
<pre><code>import threading
count = 0
def worker():
"""thread worker function"""
global count
count += 1
print(count)
threads = []
for i in range(5):
t = threading.Thread(target=worker)
threads.app... | 3 | 2016-09-19T19:28:47Z | 39,580,940 | <p>just do a while loop, but protect your counter and your test with a lock, otherwise the value tested will be different from the one you just increased.</p>
<p>I have added the thread id so we see which thread is actually increasing the counter.</p>
<p>Also: check first, increase after.</p>
<p>And wait for the thr... | 2 | 2016-09-19T19:46:15Z | [
"python",
"multithreading",
"python-multithreading"
] |
Python: Threading specific number of times | 39,580,662 | <p>I have the following code that uses <code>threading</code> and prints the current count.</p>
<pre><code>import threading
count = 0
def worker():
"""thread worker function"""
global count
count += 1
print(count)
threads = []
for i in range(5):
t = threading.Thread(target=worker)
threads.app... | 3 | 2016-09-19T19:28:47Z | 39,581,043 | <p>Loop it, of course.</p>
<pre><code>lock = threading.Lock()
count = 0
def worker():
"""thread worker function"""
global count
while True:
with lock:
if count >= 100: break
count += 1
print(count)
</code></pre>
<p>Notice the protected access to <code>count</... | 2 | 2016-09-19T19:53:48Z | [
"python",
"multithreading",
"python-multithreading"
] |
Python: Threading specific number of times | 39,580,662 | <p>I have the following code that uses <code>threading</code> and prints the current count.</p>
<pre><code>import threading
count = 0
def worker():
"""thread worker function"""
global count
count += 1
print(count)
threads = []
for i in range(5):
t = threading.Thread(target=worker)
threads.app... | 3 | 2016-09-19T19:28:47Z | 39,581,415 | <p>To be honest, if you want something like this, it means that you are going to wrong direction. Because this code is <code>stateful</code> and <code>stateful</code> processing is far away from real parallel execution.
Also usually if you want to execute code in parallel in python, you need to use <a href="https://doc... | 1 | 2016-09-19T20:18:47Z | [
"python",
"multithreading",
"python-multithreading"
] |
Using Cookies To Access HTML | 39,580,705 | <p>I'm trying to access a site (for which I have a login) through a <code>.get(url)</code> request. However, I tried passing the cookies that should authenticate my request but I keep getting a <code>401</code> error. I tried passing the cookies in the <code>.get</code> argument like so </p>
<pre><code>requests.post('... | 0 | 2016-09-19T19:31:25Z | 39,603,730 | <p>Solved: </p>
<pre><code>import requests
payload = {
'email': '###@gmail.com', #find the right name for the forms from HTML of site
'pass': '###'}
# Use 'with' to ensure the session context is closed after use.
with requests.Session() as s:
p = s.post('loginURL')
r = s.get('restrictedURL')
pr... | 0 | 2016-09-20T21:07:19Z | [
"python",
"post",
"cookies"
] |
Unable to download Python on Windows System | 39,580,731 | <p>I'm having trouble getting python to work on my Windows 10 computer. I downloaded 3.5.2 off the website and ran the exe, but when I try to use</p>
<p><code>pip install nltk</code></p>
<p>So I copied and ran get-pip.py, but it still tells me "pip" is not recognized as an internal or external command, operable progr... | -1 | 2016-09-19T19:32:56Z | 39,580,904 | <p>When installing "the exe", make sure that you tick the checkbox labelled "Add Python 3.5 to PATH". That will solve the issue you mentionned.</p>
| 0 | 2016-09-19T19:44:14Z | [
"python",
"windows",
"pip",
"windows-10",
"python-3.5"
] |
Unable to download Python on Windows System | 39,580,731 | <p>I'm having trouble getting python to work on my Windows 10 computer. I downloaded 3.5.2 off the website and ran the exe, but when I try to use</p>
<p><code>pip install nltk</code></p>
<p>So I copied and ran get-pip.py, but it still tells me "pip" is not recognized as an internal or external command, operable progr... | -1 | 2016-09-19T19:32:56Z | 39,584,316 | <p>Frito's suggestion works, I had to manually add it to the path following the instructions on the website. Thank you all for the help.</p>
| 0 | 2016-09-20T01:19:20Z | [
"python",
"windows",
"pip",
"windows-10",
"python-3.5"
] |
Python Tkinter Label in Frame | 39,580,739 | <p>I want to place a label inside a frame in tkinter, but I can't figure out how to actually get it inside.</p>
<pre><code>import tkinter
from tkinter import *
W=tkinter.Tk()
W.geometry("800x850+0+0")
W.configure(background="lightblue")
FRAME=Frame(W, width=100, height =50).place(x=700,y=0)
LABEL=Label(FRAME, text=... | 1 | 2016-09-19T19:33:36Z | 39,581,024 | <p>I think it's because you're assigning <code>FRAME</code> to <code>Frame(W, width=100, height =50).place(x=700,y=0)</code>, as opposed to just the actual frame, and according to the <a href="http://effbot.org/tkinterbook/place.htm" rel="nofollow">Place Manager reference</a>, there doesn't seem to be a return value. T... | 1 | 2016-09-19T19:53:06Z | [
"python",
"tkinter",
"label",
"frame"
] |
Python Tkinter Label in Frame | 39,580,739 | <p>I want to place a label inside a frame in tkinter, but I can't figure out how to actually get it inside.</p>
<pre><code>import tkinter
from tkinter import *
W=tkinter.Tk()
W.geometry("800x850+0+0")
W.configure(background="lightblue")
FRAME=Frame(W, width=100, height =50).place(x=700,y=0)
LABEL=Label(FRAME, text=... | 1 | 2016-09-19T19:33:36Z | 39,581,091 | <p>In the line</p>
<pre><code>FRAME=Frame(W, width=100, height =50).place(x=700,y=0)
</code></pre>
<p>You think you are returning a tk frame, but you are not! You get the return value of the place method, which is <code>None</code></p>
<p>So try</p>
<pre><code>frame = Frame(W, width=100, height=50)
frame.place(x=70... | 1 | 2016-09-19T19:57:42Z | [
"python",
"tkinter",
"label",
"frame"
] |
Export MongoDB to CSV Using File Name Variable | 39,580,809 | <p>I have a MongoDB that houses data from a web scrape that runs weekly via Scrapy. I'm going to setup a cron job to run the scrape job weekly. What I would like to do is also export a CSV out of MongoDB using mongoexport however I would like to inject the current date into the file name. I've tried a few different met... | 0 | 2016-09-19T19:38:13Z | 39,580,966 | <p>Replace <code>--out scrape-export.csv</code> in your command with <code>--out scrape-export-$(date +"%Y-%m-%d").csv</code></p>
<p>It'll create filenames in the format <code>scrape-export-2016-09-05</code></p>
| 1 | 2016-09-19T19:48:10Z | [
"python",
"mongodb",
"scrapy",
"mongoexport"
] |
Django Raw query usage | 39,580,881 | <p>I am struggling to use the output of a raw query. My code is as follows:</p>
<pre><code>cursor.execute("select f.fixturematchday, u.teamselection1or2, u.teamselectionid,u.user_id from straightred_fixture f, straightred_userselection u where u.user_id = 349 and f.fixtureid = u.fixtureid and f.fixturematchday=6 orde... | 0 | 2016-09-19T19:42:49Z | 39,581,163 | <p>Your issue is that you are <a href="http://currentSelectedTeams%20=%20cursor.fetchone()" rel="nofollow">using <code>cursor.fetchone()</code></a> and iterating through the result expecting it to return multiple rows. </p>
<p>If you want the top 2 results, you might want to use <a href="https://dev.mysql.com/doc/conn... | 2 | 2016-09-19T20:01:56Z | [
"python",
"mysql",
"django"
] |
AWS DynamoDB Python Connection Error | 39,580,929 | <p>Unable to run sample code on AWS Dynamodb.</p>
<p>I am trying to run the AWS sample python code that they provide on there website. Here is my python file:</p>
<pre><code> from __future__ import print_function # Python 2/3 compatibility
import boto3
dynamodb = boto3.resource('dynamodb', region_name='us-... | 0 | 2016-09-19T19:45:33Z | 39,581,605 | <p>This happens when Dynamodb isn't running. Check <code>localhost:8000/shell</code> to verify it's running.</p>
<p>Ensure all the <a href="http://docs.aws.amazon.com/amazondynamodb/latest/gettingstartedguide/GettingStarted.Python.html" rel="nofollow">prerequisites</a> given in docs are satisfied.</p>
<blockquote>
... | 0 | 2016-09-19T20:30:52Z | [
"python",
"python-2.7",
"ubuntu",
"amazon-web-services",
"amazon-dynamodb"
] |
Bulk update Postgres column from python dataframe | 39,581,003 | <p>I am using the below python code to update postgres DB column <code>value</code>based on <code>Id</code>. This loop has to run for thousands of records and it is taking longer time. </p>
<p>Is there a way where I can pass array of dataframe values instead of looping each row?</p>
<pre><code> for i in range(0,len(d... | 0 | 2016-09-19T19:51:22Z | 39,583,112 | <p>Depends on a library you use to communicate with PostgreSQL, but usually bulk inserts are much faster via <a href="https://www.postgresql.org/docs/9.5/static/sql-copy.html" rel="nofollow">COPY FROM</a> command.</p>
<p>If you use psycopg2 it is as simple as following:</p>
<pre><code>cursor.copy_from(io.StringIO(str... | 0 | 2016-09-19T22:37:55Z | [
"python",
"sql",
"postgresql",
"bulkupdate"
] |
How to add more command arguments to python-daemon? | 39,581,046 | <p>I have a basic Python daemon created using older version of python-daemon and this code:</p>
<pre><code>import time
from daemon import runner
class App():
def __init__(self):
self.stdin_path = '/dev/null'
self.stdout_path = '/dev/tty'
self.stderr_path = '/dev/tty'
self.pidfile_p... | 2 | 2016-09-19T19:54:06Z | 39,581,999 | <p>Looking at the code of the runner module, the following should work... I have problems with defining the stdout and stderr... could you test it?</p>
<pre><code>from daemon import runner
import time
# Inerith from the DaemonRunner class to create a personal runner
class MyRunner(runner.DaemonRunner):
def __ini... | 0 | 2016-09-19T20:58:15Z | [
"python",
"python-2.7",
"daemon",
"python-daemon"
] |
Solving non linear system containing a sum | 39,581,071 | <p>I have several functions which comes from sympy.lambdify:</p>
<pre><code>f_1 = sym.lambdify((z, m_1, m_2, s_1, s_2), expression_1, modules=['numpy', 'sympy'])
f_2 = sym.lambdify((z, m_1, m_2, s_1, s_2), expression_2, modules=['numpy', 'sympy'])
f_3 = sym.lambdify((z, m_1, m_2, s_1, s_2), expression_3, modules=['num... | 0 | 2016-09-19T19:55:50Z | 39,945,958 |
<p>To drive 4 functions F1, F2, F3, F4 all to 0,
minimize the sum of squares F1^2 + F2^2 + F3^2 + F4^2:
if the sum is small, each F must be small too.
(For example, sum < 0.000001 ⇒ each |F| < 0.001 .)
Use <a href="http://docs.scipy.org/doc/scipy/reference/tutorial/optimize.html#least-squares-minimization-... | 0 | 2016-10-09T16:39:47Z | [
"python",
"optimization",
"scipy"
] |
Parsing a python file to find classes with certain label | 39,581,138 | <p>I have a python file with many classes in it. The file looks something like that:</p>
<pre><code>some code, functions and stuff...
class A():
some code...
@label
class B(A):
some code...
@label
class C(A):
some code...
class D(A):
some code...
some extra code...
</code></pre>
<p>What I want to do... | 1 | 2016-09-19T20:00:33Z | 39,581,385 | <p>You have two options:</p>
<ul>
<li><p>use the <a href="https://docs.python.org/3/library/tokenize.html" rel="nofollow"><code>tokenize</code> module</a> to look out for <code>token.OP</code> tokens with the value <code>@</code>, followed by <code>token.NAME</code> tokens for <code>label</code> and, after a newline t... | 2 | 2016-09-19T20:16:59Z | [
"python",
"class",
"parsing"
] |
Difference between tables | 39,581,252 | <p>I have two list of dictionaries representing the rows of two tables, so:</p>
<pre><code>tableA = [{"id": 1, "name": "foo"}, {"id": 2, "name": "bar"}]
tableB = [{"id": 1, "name": "bar"}, {"id": 3, "name": "baz"}]
</code></pre>
<p>I want to obtain the difference in the following way:</p>
<pre><code>added = [{"id":... | 1 | 2016-09-19T20:08:04Z | 39,581,310 | <p>I would <em>restructure</em> the tables into a more conveninent form of <code>id</code>: <code>name</code> dictionaries and then <a href="http://stackoverflow.com/q/1165352/771848">diff</a>:</p>
<pre><code>from deepdiff import DeepDiff
tableA = [{"id": 1, "name": "foo"}, {"id": 2, "name": "bar"}]
tableB = [{"id"... | 2 | 2016-09-19T20:12:07Z | [
"python",
"algorithm",
"list",
"dictionary",
"set"
] |
Python ImageIO Gif Set Delay Between Frames | 39,581,300 | <p>I am using ImageIO: <a href="https://imageio.readthedocs.io/en/latest/userapi.html" rel="nofollow">https://imageio.readthedocs.io/en/latest/userapi.html</a> , and I want to know how to set delay between frames in a gif.</p>
<p>Here are the relevant parts of my code.</p>
<pre><code>import imageio
. . .
imageio.mi... | 0 | 2016-09-19T20:11:44Z | 39,581,406 | <p>Found it using <code>imageio.help("GIF")</code> you would pass in something like</p>
<p><code>imageio.mimsave(args.output + '.gif', ARR_ARR, fps=$FRAMESPERSECOND)</code></p>
<p>And that seems to work.</p>
| 0 | 2016-09-19T20:18:15Z | [
"python",
"image",
"numpy",
"gif"
] |
Find a substring in block of text, unless it is part of another substring | 39,581,339 | <p>I was looking for an efficient way to find a substring between two expressions, unless the expression is a part of another.</p>
<p>For example:</p>
<blockquote>
<p>Once upon a time, in a time far far away, dogs ruled the world. The End.</p>
</blockquote>
<p>If I was searching for the substring between <strong>t... | 1 | 2016-09-19T20:14:13Z | 39,581,430 | <p>Just remove 'Once upon a time' and check what's left.</p>
<pre><code>my_string = 'Once upon a time, in a time far far away, dogs ruled the world. The End.'
if 'time' in my_string.replace('Once upon a time', ''):
pass
</code></pre>
| 1 | 2016-09-19T20:19:15Z | [
"python",
"python-2.7"
] |
Find a substring in block of text, unless it is part of another substring | 39,581,339 | <p>I was looking for an efficient way to find a substring between two expressions, unless the expression is a part of another.</p>
<p>For example:</p>
<blockquote>
<p>Once upon a time, in a time far far away, dogs ruled the world. The End.</p>
</blockquote>
<p>If I was searching for the substring between <strong>t... | 1 | 2016-09-19T20:14:13Z | 39,581,597 | <p>The typical solution here is to use capturing and non-capturing regular expression groups. Since regex alternations get parsed from left to right, placing any <em>exceptions</em> to the rule first (as a non-capture) and end with the alternation that you want to select for.</p>
<pre><code>import re
text = "Once upo... | 0 | 2016-09-19T20:30:08Z | [
"python",
"python-2.7"
] |
Find a substring in block of text, unless it is part of another substring | 39,581,339 | <p>I was looking for an efficient way to find a substring between two expressions, unless the expression is a part of another.</p>
<p>For example:</p>
<blockquote>
<p>Once upon a time, in a time far far away, dogs ruled the world. The End.</p>
</blockquote>
<p>If I was searching for the substring between <strong>t... | 1 | 2016-09-19T20:14:13Z | 39,581,612 | <p>This is possible in regex by using a negative lookahead</p>
<pre><code>>>> s = 'Once upon a time, in a time far far away, dogs ruled the world. The End.'
>>> pattern = r'time((?:(?!time).)*)End'
>>> re.findall(pattern, s)
[' far far away, dogs ruled the world. The ']
</code></pre>
<p>Wit... | 2 | 2016-09-19T20:31:19Z | [
"python",
"python-2.7"
] |
Live graph in matplotlib prevents Python to shutdown | 39,581,416 | <p>Long time ago I designed a little PyQt Gui that plots a live graph. A sensor signal enters the computer, and that signal gets plotted by my Gui in real-time.</p>
<p><a href="http://i.stack.imgur.com/Mggq7.png" rel="nofollow"><img src="http://i.stack.imgur.com/Mggq7.png" alt="enter image description here"></a></p>
... | 0 | 2016-09-19T20:18:49Z | 39,701,853 | <p>Apparently the problem is in the creation of the background thread:</p>
<pre><code>myDataLoop = threading.Thread(name = ..., target = ..., args = ...)
</code></pre>
<p>To make sure that such background thread will terminate when the MainThread ends, you have to define it as <code>daemon</code>:</p>
<pre><code>myD... | 0 | 2016-09-26T11:39:39Z | [
"python",
"python-3.x",
"matplotlib"
] |
Can someone explain how this sort result is produced? | 39,581,483 | <p>Lets say that you have the given function:</p>
<pre><code>def last(word):
return word[-1]
print (sorted(['apple','orange','banana','grape','watermelon'], key=last))
</code></pre>
<p>This will return a list that is sorted by the last index in each string:</p>
<pre><code>['banana', 'apple', 'orange', 'grape', ... | -2 | 2016-09-19T20:22:19Z | 39,581,578 | <p>The sort is <em>exactly right</em>. You asked for the words to be sorted by indices <code>(1, 1, 2, 2, -1)</code>. Lets examine what characters those are:</p>
<pre><code>>>> for index, word in zip((1, 1, 2, 2, -1), ['apple', 'orange', 'banana', 'grape', 'watermelon']):
... print(word[index], word)
...
... | 2 | 2016-09-19T20:28:47Z | [
"python",
"sorting",
"key"
] |
What is the equivalent of python 'in' but for sqlalchemy | 39,581,531 | <p>I have a dictionary that is being used to query the database for a match. I have one single query line that isn't working for me. If i have a list like this:</p>
<pre><code>user['names']= [Alice, Bob, John]
</code></pre>
<p>Since this is a list I tried to use something like this:</p>
<pre><code> q.filter(UserTabl... | 2 | 2016-09-19T20:25:54Z | 39,581,819 | <p>Use the <a href="http://docs.sqlalchemy.org/en/rel_1_0/core/sqlelement.html#sqlalchemy.sql.operators.ColumnOperators.in_" rel="nofollow"><code>in_()</code> column method</a> to test a column against a sequence:</p>
<pre><code>q.filter(UserTable.firstname.in_(user['firstnames'])
</code></pre>
<p>See the <a href="ht... | 1 | 2016-09-19T20:45:17Z | [
"python",
"mysql",
"list",
"sqlalchemy"
] |
why does python takes longer time to sort a copy of list? | 39,581,621 | <p>Why is there so much difference when sorting x and y and y is just a copy of x? Does python not copy the list right away? </p>
<pre><code>python -mtimeit -s'import random; x=range(1000); random.shuffle(x)' 'y=list(x); x.sort()'
100000 loops, best of 3: 19.5 usec per loop
python -mtimeit -s'import random; x=range... | 1 | 2016-09-19T20:31:52Z | 39,581,672 | <p>Your first and last examples have to sort the list <strong>just once</strong>. After that, the sorting algorithm Python uses has an easy time of it as it is optimised to take advantage of <em>already sorted sequences</em>.</p>
<p>From the <a href="https://en.wikipedia.org/wiki/Timsort" rel="nofollow">Wikipedia arti... | 3 | 2016-09-19T20:35:08Z | [
"python",
"performance",
"sorting",
"timeit"
] |
Python Script Loop | 39,581,674 | <p>I wrote the following python script to implement my version of the game nims/stones</p>
<pre><code>def nims_stones(pile, max_stones):
while pile != 0:
move = 0
while move < 1 or move > max_stones:
move = int(raw_input("Player 1 How Many Stones"))
pile -= move
... | -1 | 2016-09-19T20:35:14Z | 39,581,873 | <p>You should stop the loop when player 1 has emptied the pile. As you have almost the same code for the second player, consider reusing the code. Then you'll also have the empty pile check at the end of the loop:</p>
<pre><code>def nims_stones(pile, max_stones):
player = 2
while pile != 0:
player = 3... | 2 | 2016-09-19T20:49:29Z | [
"python"
] |
Python Script Loop | 39,581,674 | <p>I wrote the following python script to implement my version of the game nims/stones</p>
<pre><code>def nims_stones(pile, max_stones):
while pile != 0:
move = 0
while move < 1 or move > max_stones:
move = int(raw_input("Player 1 How Many Stones"))
pile -= move
... | -1 | 2016-09-19T20:35:14Z | 39,581,903 | <p>Adding a break statement after each player wins will solve your problem. You should also consider adding logic for when the pile reaches a negative value.</p>
<pre><code>while pile != 0:
move = 0
while move < 1 or move > max_stones:
move = int(raw_input("Player 1 How Many Stones"))
pile... | 0 | 2016-09-19T20:51:49Z | [
"python"
] |
django calling a python script shows the html code instead of a webpage | 39,581,675 | <p>my django app calls a python script(query.cgi). but when I run it, the website shows the html printout from that script instead of showing the output as a webpage.</p>
<pre><code>def query(request):
if request.method == 'GET':
output = subprocess.check_output(['python', 'query.cgi']).decode('utf-8')
... | 0 | 2016-09-19T20:35:17Z | 39,582,965 | <blockquote>
<pre><code>return HttpResponse(output, content_type="text/plain")
</code></pre>
</blockquote>
<p>The reason it's returning escaped HTML is because you have <code>content_type='text/plain'</code>, which says you are just sending plain text.</p>
<p>Try changing it to <code>'text/html'</code>.</p>
| 1 | 2016-09-19T22:20:45Z | [
"python",
"django"
] |
I think I'm misunderstanding how variables from other functions can be called | 39,581,707 | <p>I'll try with words first. Using Python 3, and I have a main function that sets arg as a variable. When the main() is run, it calls a copy function which calls other functions. After these other functions run, copy() needs that arg variable set by main() at the beginning to finish and allow the main() to complete. <... | 0 | 2016-09-19T20:37:57Z | 39,581,741 | <p>The variable is local to the <code>main</code> function, to use it in <code>copy</code> you have to pass it as an argument, or make it a global variable. try to avoid the latter at all costs except you're sure that you need it, using global variables can lead to a lot of problems that are hard to debug, because a fu... | 3 | 2016-09-19T20:41:01Z | [
"python",
"python-3.x"
] |
I think I'm misunderstanding how variables from other functions can be called | 39,581,707 | <p>I'll try with words first. Using Python 3, and I have a main function that sets arg as a variable. When the main() is run, it calls a copy function which calls other functions. After these other functions run, copy() needs that arg variable set by main() at the beginning to finish and allow the main() to complete. <... | 0 | 2016-09-19T20:37:57Z | 39,581,745 | <p>Each function runs in a different frame. Try printing <code>locals()</code> in each of your functions to see the local variables.</p>
<p>There are 2 ways to access args:</p>
<p>First, the <strong>normal and correct way to do things</strong>: Give it to <code>copy()</code> as an argument:</p>
<pre><code>def copy(a... | 1 | 2016-09-19T20:41:15Z | [
"python",
"python-3.x"
] |
Two Sorted Arrays, sum of 2 elements equal a certain number | 39,581,834 | <p>I was wondering if I could get some help. I want to find an algorithm that is THETA(n) or linear time for determining whether 2 numbers in a 2 sorted arrays add up to a certain number.</p>
<p>For instance, let's say we have 2 sorted arrays: X and Y</p>
<p>I want to determine if there's an element of X and an eleme... | 0 | 2016-09-19T20:46:47Z | 39,581,944 | <p>Here is a 2n for you which doesn't even need sorting:</p>
<pre><code>def check_array(x, y, needed_sum):
y = set(y)
return next(((i, needed_sum-i) for i in x if (needed_sum-i) in y), None)
</code></pre>
| 3 | 2016-09-19T20:54:17Z | [
"python",
"arrays",
"algorithm",
"big-o"
] |
Two Sorted Arrays, sum of 2 elements equal a certain number | 39,581,834 | <p>I was wondering if I could get some help. I want to find an algorithm that is THETA(n) or linear time for determining whether 2 numbers in a 2 sorted arrays add up to a certain number.</p>
<p>For instance, let's say we have 2 sorted arrays: X and Y</p>
<p>I want to determine if there's an element of X and an eleme... | 0 | 2016-09-19T20:46:47Z | 39,581,973 | <p>What you can do is start with the highest in one list and the lowest in the other, and check the sum. </p>
<p>If the sum is your target, you're done. </p>
<p>If it's too high, go to the next highest value in the first list.</p>
<p>If it's too low, go to the next lowest value in the second. </p>
<p>If you go thro... | 6 | 2016-09-19T20:56:15Z | [
"python",
"arrays",
"algorithm",
"big-o"
] |
pandas: find percentile stats of a given column | 39,581,893 | <p>I have a pandas data frame my_df, where I can find the mean(), median(), mode() of a given column:</p>
<pre><code>my_df['field_A'].mean()
my_df['field_A'].median()
my_df['field_A'].mode()
</code></pre>
<p>I am wondering is it possible to find more detailed stats such as 90 percentile? Thanks!</p>
| 1 | 2016-09-19T20:50:57Z | 39,582,161 | <p>I figured out below would work:</p>
<pre><code>my_df.dropna().quantile([0.0, .9])
</code></pre>
| 0 | 2016-09-19T21:11:12Z | [
"python",
"python-2.7",
"pandas",
"statistics"
] |
pandas: find percentile stats of a given column | 39,581,893 | <p>I have a pandas data frame my_df, where I can find the mean(), median(), mode() of a given column:</p>
<pre><code>my_df['field_A'].mean()
my_df['field_A'].median()
my_df['field_A'].mode()
</code></pre>
<p>I am wondering is it possible to find more detailed stats such as 90 percentile? Thanks!</p>
| 1 | 2016-09-19T20:50:57Z | 39,583,179 | <p>assume series <code>s</code></p>
<pre><code>s = pd.Series(np.arange(100))
</code></pre>
<p>Get quantiles for <code>[.1, .2, .3, .4, .5, .6, .7, .8, .9]</code></p>
<pre><code>s.quantile(np.linspace(.1, 1, 9, 0))
0.1 9.9
0.2 19.8
0.3 29.7
0.4 39.6
0.5 49.5
0.6 59.4
0.7 69.3
0.8 79.2
0.9 ... | 1 | 2016-09-19T22:44:48Z | [
"python",
"python-2.7",
"pandas",
"statistics"
] |
PyQt Creates Additive Dialogs After Each Click | 39,582,059 | <p>The title pretty much sums this issue up. I have a GUI that I've coded already and I'm trying to modify my error handling to better take advantage of PyQt's signals and slots. However, I've ran into a bit of an issue. I am testing an error handling statement where if a use clicks on a specific button there get a dia... | 0 | 2016-09-19T21:03:14Z | 39,601,100 | <p>I've answered my own question. The issue wasn't caused by any of my error handling but rather how I was passing information to the QThread class instances I was creating to start new thread. I was creating instances of QThread objects within the <strong>init</strong> method of my script and this wasn't letting the i... | 0 | 2016-09-20T18:17:42Z | [
"python",
"user-interface",
"error-handling",
"dialog",
"pyqt4"
] |
How do I override Django's default admin templates and layouts | 39,582,087 | <p>I am trying to override Django's default template. For now just the base_site.html. I'm trying to change the text django administration.</p>
<p>I did the following:</p>
<ol>
<li>I created a folder in my app directory <code>/opt/mydjangoapp/templates/admin</code></li>
<li>I then copied the original django admin tem... | 1 | 2016-09-19T21:05:13Z | 39,603,518 | <p>First, make sure your application is listed first, because Django always take the resources from the first application where it finds them, according to the order in <code>settings.INSTALLED_APPS</code>.</p>
<p>In this case the app was listed first, but the override was not working because the templates were placed... | 0 | 2016-09-20T20:51:46Z | [
"python",
"django"
] |
Precise timing with serial write | 39,582,088 | <p>The code below sends a character over serial and waits 8 ms.</p>
<pre><code>import serial
import time
from time import sleep
ser = serial.Serial(
port='/dev/cu.usbserial-AD01ST7I',\
writeTimeout = 0,\
baudrate=115200,\
parity=serial.PARITY_NONE,\
stopbits=serial.STOPBITS_ONE,\
bytesize=serial.EIGHTBITS... | 0 | 2016-09-19T21:05:14Z | 39,582,590 | <p><strong>No</strong>, unless you use <a href="https://en.wikipedia.org/wiki/Real-time_operating_system" rel="nofollow" title="RTOS">RTOS</a>. There are many factors that will affect the precision:</p>
<ul>
<li>Serial buffering. You can force to write the data immediately by calling <code>flush</code></li>
<li>Timer ... | 0 | 2016-09-19T21:43:13Z | [
"python",
"serial-port",
"pyserial"
] |
Establish if a document satisifies a query (without actually performing the query) in ElasticSearch | 39,582,094 | <p>I have a document (that I know is in the index), and a query. Is there a way of knowing if the document satisfies the query, without actually querying the index and looking into the results.</p>
<p>So for example, I'd like to know if the document</p>
<pre><code>{ "price" : 30, "productID" : "1937" }
</code></pre>
... | 0 | 2016-09-19T21:05:29Z | 39,582,892 | <p>Unfortunately, I don't think there's a direct way of doing this. You could either:</p>
<p>A) Issue a query, filtering by the document's ID using the <code>ids</code> query to avoid querying all of your documents:</p>
<pre><code>{
"ids" : {
"type" : "my_type",
"values" : ["1", "4", "100"]
}
... | 1 | 2016-09-19T22:12:39Z | [
"python",
"elasticsearch",
"elasticsearch-2.0"
] |
Establish if a document satisifies a query (without actually performing the query) in ElasticSearch | 39,582,094 | <p>I have a document (that I know is in the index), and a query. Is there a way of knowing if the document satisfies the query, without actually querying the index and looking into the results.</p>
<p>So for example, I'd like to know if the document</p>
<pre><code>{ "price" : 30, "productID" : "1937" }
</code></pre>
... | 0 | 2016-09-19T21:05:29Z | 39,586,802 | <p>If you know the document's ID, you can use the "explain" api.
<a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/search-explain.html" rel="nofollow">https://www.elastic.co/guide/en/elasticsearch/reference/current/search-explain.html</a></p>
<p>So assuming your documents id is <code>1234abc</c... | 1 | 2016-09-20T06:06:18Z | [
"python",
"elasticsearch",
"elasticsearch-2.0"
] |
Python dictionary lookup performance, get vs in | 39,582,115 | <p>This isn't premature optimization. My use case has the double-checking of dict's right in the inner-most of inner loops, running all the time. Also, it's intellectually irksome (see results).</p>
<p>Which of these approaches is faster?</p>
<pre><code>mydict = { 'hello': 'yes', 'goodbye': 'no' }
key = 'hello'
# (A... | 0 | 2016-09-19T21:07:15Z | 39,582,288 | <p>We can do some better timings:</p>
<pre><code>import timeit
d = dict.fromkeys(range(10000))
def d_get_has(d):
return d.get(1)
def d_get_not_has(d):
return d.get(-1)
def d_in_has(d):
if 1 in d:
return d[1]
def d_in_not_has(d):
if -1 in d:
return d[-1]
print timeit.timeit('d_get... | 1 | 2016-09-19T21:19:08Z | [
"python",
"performance",
"dictionary"
] |
Pandas check if row exist in another dataframe and append index | 39,582,138 | <p>I'm having one problem to iterate over my dataframe. The way I'm doing is taking a loooong time and I don't have that many rows (I have like 300k rows)</p>
<p>What am I trying to do? </p>
<ol>
<li><p>Check if one DF (A) contains the value of two columns of the other DF (B). You can think this as a multiple key fie... | 1 | 2016-09-19T21:09:05Z | 39,582,426 | <p>you can do it this way:</p>
<p>Data (pay attention at the index in the <code>B</code> DF):</p>
<pre><code>In [276]: cols = ['SampleID', 'ParentID']
In [277]: A
Out[277]:
Real_ID SampleID ParentID Something AnotherThing
0 NaN 10 11 a b
1 NaN 20 21 ... | 1 | 2016-09-19T21:29:24Z | [
"python",
"pandas"
] |
Selenium: Element is not currently visible and so may not be interacted | 39,582,141 | <p>I'm attempting to create an automated login script to netflix website: <a href="https://www.netflix.com/it/" rel="nofollow">https://www.netflix.com/it/</a></p>
<p>That's the code:</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Firefox()
while True:... | 0 | 2016-09-19T21:09:29Z | 39,582,789 | <p>No need to put the test code inside <code>while</code> loop, since login form should be submitted once. I guess when it works successfully, next iteration gives error since there is no form.</p>
<p>You are also clicking the submit button before and after password entry. It is better to click after form is fully fil... | 0 | 2016-09-19T22:01:41Z | [
"python",
"python-3.x",
"selenium"
] |
Trouble understanding function returns in "Functions" section of learnpython.org | 39,582,166 | <p>I'm working through the "Functions" exercise on learnpython.org and had a question about why my version of code is returning a "None" after every string that is output (where I first define the string list and then return it in that specific functions) as opposed to the solution (where they return the list of string... | 2 | 2016-09-19T21:11:34Z | 39,582,253 | <p>The difference is in your <code>build_sentence</code> return value, not your <code>list_benefits</code> return value.</p>
<p>The line:</p>
<pre><code> print build_sentence(benefit)
</code></pre>
<p>instructs the Python interpreter to print the <em>output</em> of the <code>build_sentence</code> functionâbut if y... | 0 | 2016-09-19T21:17:00Z | [
"python"
] |
Python: Search a string for a variable repeating characters | 39,582,192 | <p>I'm trying to write a function that will search a string (all numeric, 0-9) for a variable sequence of 4 or more repeating characters. </p>
<p>Here are some example inputs:</p>
<p>"14888838": the function would return True because it found "8888". </p>
<p>"1111": the function would return True because it foun... | 4 | 2016-09-19T21:13:09Z | 39,582,241 | <p>You may rely on <a href="http://www.regular-expressions.info/brackets.html" rel="nofollow"><strong>capturing</strong></a> and <a href="http://www.regular-expressions.info/backref.html" rel="nofollow"><strong>backreferences</strong></a>:</p>
<pre><code>if re.search(r'(\d)\1{3}', s):
print(s)
</code></pre>
<p>He... | 4 | 2016-09-19T21:16:35Z | [
"python",
"regex"
] |
Command-line setting ignored using latexpdf | 39,582,206 | <p>I am using sphinx-build to create both html and latexpdf output. Output looks amazing in both cases. </p>
<p>I would like to pass the <strong>project</strong> name on the command-line so the documentation can be titled e.g., <strong>TEST</strong>. This works great for the html option. In the example below (from a ... | 0 | 2016-09-19T21:14:11Z | 39,626,449 | <p>Thanks for the reference to latex_elements. I realize that what I was trying to do, override settings in conf.py on the fly by using command-line arguments, is not going to work.</p>
| 0 | 2016-09-21T20:56:49Z | [
"python",
"pdf",
"python-sphinx"
] |
Modular Python output problems | 39,582,289 | <p>So i had to convert my pseudocode to python but my output isnt coming out the way it should be.</p>
<p>i enter the 40 hours work and 20 pay rate but the gross pay isnt coming out (gross pay should be 800). can anyone tell me whats wrong?</p>
<pre class="lang-python prettyprint-override"><code>BASE_HOURS = 40
OT_MU... | -1 | 2016-09-19T21:19:08Z | 39,582,447 | <p>The print statement should instead be <code>print('The gross pay is $'+str(gross_pay))</code> The <code>str()</code> function converts the integer gross_pay into a string so that it can be concatenated in the print function.</p>
| 0 | 2016-09-19T21:31:14Z | [
"python",
"modular"
] |
For loop not working without range() " string indices must be integers" | 39,582,309 | <p><code>i</code> is a string, so how can I make this work? </p>
<p>How can I use <code>i</code> as index?</p>
<pre><code>for i in s[1:]:
if s[i] <= s[i-1]:
temp += s[i]
else:
subs.append(temp)
temp = ''
</code></pre>
<p>I've tried to use </p>
<pre><code>for i in s[1:]:
if s.i... | -1 | 2016-09-19T21:21:00Z | 39,582,444 | <p>the syntax you are using is corresponding to string iteration (see <a href="http://anandology.com/python-practice-book/iterators.html" rel="nofollow">http://anandology.com/python-practice-book/iterators.html</a>) so the <code>i</code> will iterate on the different characters of the string on note on their indices:</... | 0 | 2016-09-19T21:30:59Z | [
"python",
"for-loop"
] |
For loop not working without range() " string indices must be integers" | 39,582,309 | <p><code>i</code> is a string, so how can I make this work? </p>
<p>How can I use <code>i</code> as index?</p>
<pre><code>for i in s[1:]:
if s[i] <= s[i-1]:
temp += s[i]
else:
subs.append(temp)
temp = ''
</code></pre>
<p>I've tried to use </p>
<pre><code>for i in s[1:]:
if s.i... | -1 | 2016-09-19T21:21:00Z | 39,582,470 | <p>When you iterate through a string using "for i in s[1:]", it will assign i the value of each character in the string. You may want to use the iterator "enumerate" in the loop instead. It will assign a sequential numeric value to every byte in the string, while assigning s[i] to v.</p>
<pre><code>for i, v in enumera... | -1 | 2016-09-19T21:33:40Z | [
"python",
"for-loop"
] |
Insert python variable value into SQL table | 39,582,340 | <p>I have a password system that stores the password for a python program in an SQL table. I want the user to be able to change the password in a tkinter window but I am not sure how to use the value of a python variable as the value for the SQL table. Here is a sample code:</p>
<pre><code>import tkinter
from tkinter ... | -1 | 2016-09-19T21:22:55Z | 39,582,516 | <p>There are two valid ways to use <code>VALUES()</code>: with a label or a string literal. A string literal is a string in single or double quotes.</p>
<p>Since you didn't put <code>newPassword</code> in quotes, Sqlite assumes <code>newPassword</code> is a label, i.e. a column name. It goes looking for the value of... | -1 | 2016-09-19T21:36:15Z | [
"python",
"sqlite",
"tkinter"
] |
Assigning probabilities to items in python | 39,582,504 | <p>I understand the question title is vague. My apologies. I have a hashmap that has the key:value <code><string>:<list of lists></code>. For a given list, each of the items in the list has a corresponding probability of being chosen. For example, one item in the hashmap might look like</p>
<pre><code>"NP"... | 0 | 2016-09-19T21:35:12Z | 39,582,694 | <p>So the way I would solve this is by creating a sparse table ranging from <code>0</code> to <code>total probability</code>. In your case, that's </p>
<pre><code>0 -> 0
3 -> 1
4 -> 2
</code></pre>
<p>Then pick an int between 0 and 4, and pick the largest value >= the chosen value (in other words, 1 maps to ... | 0 | 2016-09-19T21:51:54Z | [
"python",
"probability"
] |
Assigning probabilities to items in python | 39,582,504 | <p>I understand the question title is vague. My apologies. I have a hashmap that has the key:value <code><string>:<list of lists></code>. For a given list, each of the items in the list has a corresponding probability of being chosen. For example, one item in the hashmap might look like</p>
<pre><code>"NP"... | 0 | 2016-09-19T21:35:12Z | 39,582,811 | <p>Here is a crude approach that might suffice if your total weight remains small:</p>
<pre><code>>>> NP = [['A', 'B'], ['C', 'D', 'E'], ['F']]
>>> weights = (3,1,1)
>>> indx_list = [idx for idx,w in zip(range(len(NP)), weights) for _ in range(w)]
>>> indx_list
[0, 0, 0, 1, 2]
>&... | 0 | 2016-09-19T22:03:34Z | [
"python",
"probability"
] |
Assigning probabilities to items in python | 39,582,504 | <p>I understand the question title is vague. My apologies. I have a hashmap that has the key:value <code><string>:<list of lists></code>. For a given list, each of the items in the list has a corresponding probability of being chosen. For example, one item in the hashmap might look like</p>
<pre><code>"NP"... | 0 | 2016-09-19T21:35:12Z | 39,582,843 | <p>Here is a simple prototype which uses <strong>linear-search</strong>. The only dependency is <strong>random.random()</strong> to obtain a float within [0,1).</p>
<p>Despite the unoptimized approach, it only needs ~0.25 seconds for 100.000 samples on my PC. But keep in mind, that this performance is dependent on the... | 0 | 2016-09-19T22:07:41Z | [
"python",
"probability"
] |
Read in avro file with boto3 and convert to string (Python) | 39,582,523 | <p>I'm using boto3 to read in an avro file from my s3 bucket.
However, I'm stuck on how to actually convert the avro to a string.</p>
<pre><code>avro_file = file_from_s3.get()['Body'].read()
</code></pre>
<p>After getting to this step, I'm not sure what to do.</p>
| 0 | 2016-09-19T21:36:45Z | 39,600,802 | <p>I found a way. You need to use StringIO from python and download_fileobj() from boto3.</p>
<pre><code>import boto3
import StringIO
from avro.datafile import DataFileReader, DataFileWriter
from avro.io import DatumReader, DatumWriter
output = StringIO.StringIO()
latest_file_object = s3_client.Object('bucket_name','... | 0 | 2016-09-20T17:59:00Z | [
"python",
"boto",
"avro",
"boto3"
] |
Prevent Travis Python environment from pre-installing packages | 39,582,527 | <p>Is there a way to prevent the Travis Python environment from pre-installing <code>pytest</code>, <code>nose</code>, <code>mock</code> etc.? The versions are old and causing order-dependent problems when upgrading. I want to specify my dependencies only in <code>setup.py</code>, but <code>pytest</code> and <code>py</... | 0 | 2016-09-19T21:37:18Z | 39,964,141 | <p>I didn't find a way to do this, but I found a relatively clean workaround: <code>virtualenvwrapper.sh</code> has a <code>wipeenv</code> command I did not previously know. So now I setup a "modern and clean" virtualenv like this:</p>
<pre><code>before_install:
- pip install -U pip setuptools virtualenvwrapper
- ... | 0 | 2016-10-10T18:02:04Z | [
"python",
"pip",
"travis-ci",
"setup.py"
] |
Openstack: Gerrit error with git rebase and merge | 39,582,601 | <p>I am working on fixing a bug in Openstack. I did my changes, since this was a documentation task, I did run the test as I would have usually. I submitted the change to Gerrit. It came back from the reviewers while I was working on a another bug. </p>
<p>I switched branches and worked on the older bug. When I did a... | 0 | 2016-09-19T21:44:08Z | 39,592,765 | <p>The error "you are not allowed to upload merges" is self explanatory: you can't upload your code because you don't have permission to push merge commits. Gerrit is referring to commits 5503c89 and/or 74cc524.</p>
<p>The first thing you need to do is to verify if you should be pushing these commits to Gerrit or ther... | 0 | 2016-09-20T11:22:08Z | [
"python",
"git",
"openstack",
"gerrit",
"openstack-horizon"
] |
using the map function with timeit in Python | 39,582,616 | <p>I am learning python and am looking at the difference in performance between using comprehension and the map function. </p>
<p>So far, I have this code:</p>
<pre><code>import timeit
print timeit.timeit('[x for x in range(100)]',number = 10000)
def mapFunc(i):
print i
print timeit.timeit('map(mapFunc,range(1... | 0 | 2016-09-19T21:45:10Z | 39,582,668 | <p>You should <em>setup</em> the function definition via the <code>setup</code> argument:</p>
<pre><code>>>> setup='def mapFunc(): print(i)'
>>> timeit.timeit('map(mapFunc,range(100))', number=10000, setup=setup)
</code></pre>
<p>See the <a href="https://docs.python.org/2/library/timeit.html#timeit.... | 2 | 2016-09-19T21:49:21Z | [
"python",
"performance",
"function",
"dictionary",
"timeit"
] |
Counting items inside tuples in Python | 39,582,639 | <p>I am fairly new to python and I could not figure out how to do the following. </p>
<p>I have a list of (word, tag) tuples </p>
<pre><code>a = [('Run', 'Noun'),('Run', 'Verb'),('The', 'Article'),('Run', 'Noun'),('The', 'DT')]
</code></pre>
<p>I am trying to find all tags that has been assigned to each word and col... | 2 | 2016-09-19T21:46:44Z | 39,582,689 | <p>Pretty easy with a <a href="https://docs.python.org/2/library/collections.html#collections.defaultdict" rel="nofollow"><code>defaultdict</code></a>:</p>
<pre><code>>>> from collections import defaultdict
>>> output = defaultdict(defaultdict(int).copy)
>>> for word, tag in a:
... outpu... | 2 | 2016-09-19T21:51:16Z | [
"python",
"tuples"
] |
Counting items inside tuples in Python | 39,582,639 | <p>I am fairly new to python and I could not figure out how to do the following. </p>
<p>I have a list of (word, tag) tuples </p>
<pre><code>a = [('Run', 'Noun'),('Run', 'Verb'),('The', 'Article'),('Run', 'Noun'),('The', 'DT')]
</code></pre>
<p>I am trying to find all tags that has been assigned to each word and col... | 2 | 2016-09-19T21:46:44Z | 39,582,744 | <p>You can use <a href="https://docs.python.org/2/library/collections.html#collections.Counter" rel="nofollow"><code>collections.Counter</code></a>:</p>
<pre><code>>>> import collections
>>> a = [('Run', 'Noun'),('Run', 'Verb'),('The', 'Article'),('Run', 'Noun'),('The', 'DT')]
>>> counter =... | 2 | 2016-09-19T21:56:54Z | [
"python",
"tuples"
] |
403 Forbidden while trying to display image from url - Kivy | 39,582,681 | <p>I'm trying to display image in kivy application, but image loader returns error 403 forbidden.</p>
<p>I noticed that I have to send User-Agent header to bypass this error, but i couldn't find any way to pass headers to image loader</p>
<p>Is there any way to solve this problem?</p>
<p>kv file</p>
<pre><code>Asyn... | 1 | 2016-09-19T21:49:57Z | 39,610,264 | <p>Currently you can't modify the User-Agent when using AsyncImage. The responsible code is <a href="https://github.com/kivy/kivy/blob/master/kivy/loader.py#L317" rel="nofollow">here</a>:</p>
<pre><code>fd = urllib_request.urlopen(filename)
</code></pre>
<p>As you see there is no good way to pass a different UserAgen... | 1 | 2016-09-21T07:37:39Z | [
"python",
"kivy",
"kivy-language"
] |
Using pre-trained inception_resnet_v2 with Tensorflow | 39,582,703 | <p>I have been trying to use the pre-trained inception_resnet_v2 model released by Google. I am using their model definition(<a href="https://github.com/tensorflow/models/blob/master/slim/nets/inception_resnet_v2.py" rel="nofollow">https://github.com/tensorflow/models/blob/master/slim/nets/inception_resnet_v2.py</a>) a... | 2 | 2016-09-19T21:52:28Z | 39,597,537 | <p>The Inception networks expect the input image to have color channels scaled from [-1, 1]. As seen <a href="https://github.com/tensorflow/models/blob/master/slim/preprocessing/inception_preprocessing.py#L237-L275" rel="nofollow">here</a>.</p>
<p>You could either use the existing preprocessing, or in your example jus... | 2 | 2016-09-20T15:01:52Z | [
"python",
"computer-vision",
"tensorflow",
"deep-learning"
] |
Running a Python function on Spark Dataframe | 39,582,754 | <p>I have a python function which basically does some sampling from the original dataset and converts it into training_test. </p>
<p>I have written that code to work on pandas data frame. </p>
<p>I was wondering if anyone knows how to implement the same on Spark DAtaframe in pyspark?. Instead of Pandas data frame or ... | 0 | 2016-09-19T21:57:55Z | 39,585,660 | <p>You can use randomSplit function on Spark dataframe. </p>
| 0 | 2016-09-20T04:25:46Z | [
"python",
"pandas",
"apache-spark"
] |
Checking the next object in Python list | 39,582,797 | <p>I have a <code>list</code> (from CSV) with the following information structure:</p>
<pre><code>Item 1
NUMBER Random ID
Item 2
NUMBER Random ID
Item 3
Item 4
Item 5
NUMBER Random ID
</code></pre>
<p>And I would like to create a new <code>list</code> (CSV) that looks like this:</p>
<pre><code>Item 1 NUMBER Random I... | 0 | 2016-09-19T22:02:17Z | 39,582,895 | <pre><code>new_list=[]
i=0
while i < len(raw_list)-1:
if raw_list[i+1][:len("NUMBER")] == "NUMBER":
new_list.append("%s %s" % (raw_list[i], raw_list[i+1]))
i=i+2
else:
i=i+1
</code></pre>
| 0 | 2016-09-19T22:12:56Z | [
"python"
] |
Checking the next object in Python list | 39,582,797 | <p>I have a <code>list</code> (from CSV) with the following information structure:</p>
<pre><code>Item 1
NUMBER Random ID
Item 2
NUMBER Random ID
Item 3
Item 4
Item 5
NUMBER Random ID
</code></pre>
<p>And I would like to create a new <code>list</code> (CSV) that looks like this:</p>
<pre><code>Item 1 NUMBER Random I... | 0 | 2016-09-19T22:02:17Z | 39,582,898 | <p>With <code>enumerate(<list>)</code> you can iterate on indices and elements, so you can easily check the next element:</p>
<pre><code>result = []
for i, val in enumerate(lst):
if i == len(lst) - 1:
break # to avoid IndexError
if lst[i + 1][:3] == 'NUM':
result.append('%s %s' % (val, ls... | 1 | 2016-09-19T22:13:16Z | [
"python"
] |
Checking the next object in Python list | 39,582,797 | <p>I have a <code>list</code> (from CSV) with the following information structure:</p>
<pre><code>Item 1
NUMBER Random ID
Item 2
NUMBER Random ID
Item 3
Item 4
Item 5
NUMBER Random ID
</code></pre>
<p>And I would like to create a new <code>list</code> (CSV) that looks like this:</p>
<pre><code>Item 1 NUMBER Random I... | 0 | 2016-09-19T22:02:17Z | 39,582,977 | <p>With list comprehension:</p>
<pre><code>result = ["%s %s" % (x,raw_list[i+1]) for i, x in enumerate(raw_list)
if i < len(raw_list)-1 and 'NUMBER' in raw_list[i+1]]
</code></pre>
| 1 | 2016-09-19T22:22:39Z | [
"python"
] |
Checking the next object in Python list | 39,582,797 | <p>I have a <code>list</code> (from CSV) with the following information structure:</p>
<pre><code>Item 1
NUMBER Random ID
Item 2
NUMBER Random ID
Item 3
Item 4
Item 5
NUMBER Random ID
</code></pre>
<p>And I would like to create a new <code>list</code> (CSV) that looks like this:</p>
<pre><code>Item 1 NUMBER Random I... | 0 | 2016-09-19T22:02:17Z | 39,583,009 | <pre><code>result = []
i, l = 0, len(raw_input)
while i < l:
if 'item' in raw_input[i]:
result.append(raw_input[i])
else:
result[-1] += raw_input[i]
i += 1
return filter(lambda x: 'random' in x.lower(), result)
</code></pre>
| 0 | 2016-09-19T22:26:54Z | [
"python"
] |
Checking the next object in Python list | 39,582,797 | <p>I have a <code>list</code> (from CSV) with the following information structure:</p>
<pre><code>Item 1
NUMBER Random ID
Item 2
NUMBER Random ID
Item 3
Item 4
Item 5
NUMBER Random ID
</code></pre>
<p>And I would like to create a new <code>list</code> (CSV) that looks like this:</p>
<pre><code>Item 1 NUMBER Random I... | 0 | 2016-09-19T22:02:17Z | 39,583,045 | <p>Fun question!</p>
<pre><code>raw_list = ["Item 1",
"NUMBER Random ID1",
"Item 2",
"NUMBER Random ID2",
"Item 3",
"Item 4",
"Item 5",
"NUMBER Random ID5"]
clean_list = [raw_list[i]+" "+raw_list[i+1] for i in range(0,len(raw_list),2)... | 2 | 2016-09-19T22:30:50Z | [
"python"
] |
Checking the next object in Python list | 39,582,797 | <p>I have a <code>list</code> (from CSV) with the following information structure:</p>
<pre><code>Item 1
NUMBER Random ID
Item 2
NUMBER Random ID
Item 3
Item 4
Item 5
NUMBER Random ID
</code></pre>
<p>And I would like to create a new <code>list</code> (CSV) that looks like this:</p>
<pre><code>Item 1 NUMBER Random I... | 0 | 2016-09-19T22:02:17Z | 39,583,590 | <p>Here's a slightly different take on the problem - search for lines that contain the string <code>NUMBER</code> and then join that line with the previous one. This produces simpler code:</p>
<pre><code>l = ['Item 1', 'NUMBER Random ID', 'Item 2', 'NUMBER Random ID', 'Item 3', 'Item 4', 'Item 5', 'NUMBER Random ID']
... | 2 | 2016-09-19T23:33:27Z | [
"python"
] |
Python Regex remove numbers and numbers with punctaution | 39,582,859 | <p>I have the following string</p>
<pre><code> line = "1234567 7852853427.111 https://en.wikipedia.org/wiki/Dictionary_(disambiguation)"
</code></pre>
<p>I would like to remove the numbers 1234567 7852853427.111 using regular expresisions</p>
<p>I have this re
nline = re.sub("^\d+\s|\s\d+\s|\s\d\w\d|\s\d+$", " "... | 2 | 2016-09-19T22:09:22Z | 39,582,894 | <p>You can use:</p>
<pre><code>>>> line = "1234567 7852853427.111 https://en.wikipedia.org/wiki/Dictionary_(disambiguation)"
>>> print re.sub(r'\b\d+(?:\.\d+)?\s+', '', line)
https://en.wikipedia.org/wiki/Dictionary_(disambiguation)
</code></pre>
<p>Regex <code>\b\d+(?:\.\d+)?\s+</code> will match... | 2 | 2016-09-19T22:12:51Z | [
"python",
"regex"
] |
Python Regex remove numbers and numbers with punctaution | 39,582,859 | <p>I have the following string</p>
<pre><code> line = "1234567 7852853427.111 https://en.wikipedia.org/wiki/Dictionary_(disambiguation)"
</code></pre>
<p>I would like to remove the numbers 1234567 7852853427.111 using regular expresisions</p>
<p>I have this re
nline = re.sub("^\d+\s|\s\d+\s|\s\d\w\d|\s\d+$", " "... | 2 | 2016-09-19T22:09:22Z | 39,582,949 | <p>Here's a non-regex approach, if your regex requirement is not entirely strict, using <a href="https://docs.python.org/2/library/itertools.html#itertools.dropwhile" rel="nofollow"><code>itertools.dropwhile</code></a>:</p>
<pre><code>>>> ''.join(dropwhile(lambda x: not x.isalpha(), line))
'https://en.wikiped... | 1 | 2016-09-19T22:18:30Z | [
"python",
"regex"
] |
Python Regex remove numbers and numbers with punctaution | 39,582,859 | <p>I have the following string</p>
<pre><code> line = "1234567 7852853427.111 https://en.wikipedia.org/wiki/Dictionary_(disambiguation)"
</code></pre>
<p>I would like to remove the numbers 1234567 7852853427.111 using regular expresisions</p>
<p>I have this re
nline = re.sub("^\d+\s|\s\d+\s|\s\d\w\d|\s\d+$", " "... | 2 | 2016-09-19T22:09:22Z | 39,583,039 | <p>I think this is what you want:</p>
<pre><code>nline = re.sub("\d+\s\d+\.\d+", "", line)
</code></pre>
<p>It removes the numbers from line. If you want to keep the space in front of "http..." your second parameter should of course be " ".</p>
<p>If you also want to record the individual number strings you could pu... | 0 | 2016-09-19T22:29:47Z | [
"python",
"regex"
] |
Python Regex remove numbers and numbers with punctaution | 39,582,859 | <p>I have the following string</p>
<pre><code> line = "1234567 7852853427.111 https://en.wikipedia.org/wiki/Dictionary_(disambiguation)"
</code></pre>
<p>I would like to remove the numbers 1234567 7852853427.111 using regular expresisions</p>
<p>I have this re
nline = re.sub("^\d+\s|\s\d+\s|\s\d\w\d|\s\d+$", " "... | 2 | 2016-09-19T22:09:22Z | 39,601,200 | <p>Though you are asking for a regular expression, a better solution would be to use <a href="https://docs.python.org/2/library/stdtypes.html#str.split" rel="nofollow"><code>str.split</code></a>, assuming that your string will always be in the format <code>{number} {number} {hyperlink}</code>.</p>
<p>As @godaygo <a hr... | 0 | 2016-09-20T18:23:24Z | [
"python",
"regex"
] |
Pandas: Drop quasi-duplicates by column values | 39,582,860 | <p>I have a list that, let's say, looks like this (which I'm putting into a DF):</p>
<pre><code>[
['john', '1', '1', '2016'],
['john', '1', '10', '2016'],
['sally', '3', '5', '2016'],
['sally', '4', '1', '2016']
]
</code></pre>
<p><code>columns</code> are <code>['name', 'month', 'day', 'year']</code></p>
<p>I basica... | 1 | 2016-09-19T22:09:27Z | 39,582,963 | <p>You can sort the data frame by <code>year, month, day</code> and then take the first row from each <code>name</code>:</p>
<pre><code>df.sort_values(by = ['year', 'month', 'day']).groupby('name').first()
# month day year
# name
# john 1 1 2016
#sally 3 5 2016
</code></pre>
<p><em>Data</em>:... | 4 | 2016-09-19T22:20:21Z | [
"python",
"pandas"
] |
Pandas: Drop quasi-duplicates by column values | 39,582,860 | <p>I have a list that, let's say, looks like this (which I'm putting into a DF):</p>
<pre><code>[
['john', '1', '1', '2016'],
['john', '1', '10', '2016'],
['sally', '3', '5', '2016'],
['sally', '4', '1', '2016']
]
</code></pre>
<p><code>columns</code> are <code>['name', 'month', 'day', 'year']</code></p>
<p>I basica... | 1 | 2016-09-19T22:09:27Z | 39,582,980 | <p><strong><em>Option 1</em></strong><br>
use <code>pd.to_datetime</code> to parse ['year', 'month', 'day'] columns.<br>
<code>groupby('name')</code> then take <code>first</code></p>
<pre><code>df['date'] = pd.to_datetime(df[['year', 'month', 'day']])
df.sort_values(['name', 'date']).groupby('name').first()
</code></p... | 0 | 2016-09-19T22:22:56Z | [
"python",
"pandas"
] |
"ImportError: No module named google.protobuf" but it's definitely installed | 39,582,868 | <p>I've installed the <code>protobuf</code> package but I'm unable to import it.</p>
<pre><code>> pip uninstall protobuf
... uninstalls
> pip install protobuf
... installs. confirm that it's installed:
pip install protobuf
Requirement already satisfied (use --upgrade to upgrade): protobuf in ./.venv/lib/pyth... | 0 | 2016-09-19T22:10:41Z | 40,051,428 | <p>I had the same issue and found a workaround suggested in <a href="https://github.com/tensorflow/tensorflow/issues/1415" rel="nofollow">this issue</a>: </p>
<blockquote>
<p>1.Adding a new file tensorflow/google/init.py:</p>
<pre><code>try:
import pkg_resources
pkg_resources.declare_namespace(__name__)
exc... | -1 | 2016-10-14T20:23:06Z | [
"python",
"protocol-buffers",
"python-3.5"
] |
QTimer isn't calling myfunction as expected | 39,582,872 | <p>In the code below the first function gets called but the second function doesn't. What am I doing wrong?</p>
<pre><code>def time_cursor_plot(self):
print 'function called'
t = QtCore.QTimer()
t.setInterval(1000)
t.timeout.connect(self.start_timer)
t.start()
def start_timer(self):... | 0 | 2016-09-19T22:11:07Z | 39,585,244 | <p>the method start_timer is in the same class? otherwise remove "self".</p>
<pre><code>def time_cursor_plot(self):
print 'function called'
t = QtCore.QTimer()
t.setInterval(1000)
t.timeout.connect(start_timer)
t.start()
def start_timer(self):
print ' this one too'
</code></pre>
| 1 | 2016-09-20T03:26:24Z | [
"python",
"pyqt4",
"qtimer"
] |
Django - Understanding RelatedManager remove method | 39,582,888 | <p>So here I will be using classic Django Blog and Entry models from the documentation (<a href="https://docs.djangoproject.com/en/1.10/topics/db/queries/" rel="nofollow">link</a>). I added <code>null=True</code> to the Entry's blog attribute.</p>
<pre><code>>>> cb = Blog.objects.get(name__startswith="Cheese"... | 0 | 2016-09-19T22:12:21Z | 39,587,160 | <p>You've said it yourself, you need to go back to the database to get the new information. The <code>gouda</code> object doesn't automatically keep a link to its database row; it only queries it when told to do so.</p>
| 1 | 2016-09-20T06:30:43Z | [
"python",
"django"
] |
Python script uses 100% CPU | 39,582,899 | <p>Hey I was working with python. In my python file I just have 2 lines like : </p>
<pre><code>#!/usr/bin/env
print("hello")
</code></pre>
<p>and I make my .py file executable and run it(./hello.py) on ubuntu server.
With "top" command, i listed all processes.
hello.py uses 100% CPU.
Why it use 100% CPU(Server has 51... | 0 | 2016-09-19T22:13:20Z | 39,583,053 | <p>Your incorrect shebang line of</p>
<pre><code>#!/usr/bin/env
</code></pre>
<p>causes the system to launch <code>/usr/bin/env</code> to handle the script, as follows:</p>
<pre><code>/usr/bin/env ./hello.py
</code></pre>
<p><code>/usr/bin/env</code> treats the first argument not containing <code>=</code> and not s... | 4 | 2016-09-19T22:31:25Z | [
"python",
"python-3.x"
] |
regarding the tensor shape is (?,?,?,1) | 39,582,974 | <p>During debuging the Tensorflow code, I would like to output the shape of a tensor, say, <code>print("mask's shape is: ",mask.get_shape())</code> However, the corresponding output is <code>mask's shape is (?,?,?,1)</code> How to explain this kind of output, is there anyway to know the exactly value of the first thr... | 0 | 2016-09-19T22:21:53Z | 39,583,123 | <p>This output means that TensorFlow's shape inference has only been able to infer a <em>partial shape</em> for the <code>mask</code> tensor. It has been able to infer (i) that <code>mask</code> is a 4-D tensor, and (ii) its last dimension is 1; but it does not know statically the shape of the first three dimensions.</... | 0 | 2016-09-19T22:38:44Z | [
"python",
"tensorflow"
] |
pandas - Merging on string columns not working (bug?) | 39,582,984 | <p>I'm trying to do a simple merge between two dataframes. These come from two different SQL tables, where the joining keys are strings:</p>
<pre><code>>>> df1.col1.dtype
dtype('O')
>>> df2.col2.dtype
dtype('O')
</code></pre>
<p>I try to merge them using this:</p>
<pre><code>>>> merge_res ... | 0 | 2016-09-19T22:23:30Z | 39,605,926 | <p>The issue was that the <code>object</code> dtype is misleading. I thought it mean that all items were strings. But apparently, while reading the file pandas was converting some elements to ints, and leaving the remainders as strings.</p>
<p>The solution was to make sure that every field is a string:</p>
<pre><code... | 0 | 2016-09-21T00:54:45Z | [
"python",
"mysql",
"pandas",
"merge"
] |
If statement with multiple conditions using regex | 39,582,988 | <p>I would like to loop through pull requests in GitHub and if the pull request has the comments in the code below, do something (for now, print the pull request number). I have a pull request that has the comments I'm looking for (spread over multiple comments in the pull request), but it doesn't print the pull reque... | 0 | 2016-09-19T22:23:58Z | 39,583,189 | <p>Your solution requires all of the conditions to be met on the <em>same</em> comment, it won't work if they are on different comments. For that you need to keep track which conditions are met while iterating through the comments, e.g:</p>
<pre><code>for pr in repo.pull_requests():
#check to ensure pull request m... | 1 | 2016-09-19T22:46:53Z | [
"python",
"if-statement"
] |
Update list in-place, converting 'True'/'False' elements to 1/0 | 39,583,016 | <p>In python, supposed I have a list: </p>
<pre><code>l = [ 'True', 'False', 'myname', 1, 0, 'foo' ]
</code></pre>
<p>and I want to convert the <em>strings</em> <code>'True'</code> or <code>'False'</code> to <code>1</code> or <code>0</code>, what is the best way to do this and still retain the index that the value h... | 1 | 2016-09-19T22:27:10Z | 39,583,055 | <p>List comprehension is your friend:</p>
<pre><code>>>> l = [ 'True', 'False', 'myname', 1, 0, 'foo']
>>> mapping = {"True": 1, "False": 0}
>>> [mapping.get(x, x) for x in l]
</code></pre>
| 2 | 2016-09-19T22:31:29Z | [
"python",
"list",
"dictionary"
] |
Update list in-place, converting 'True'/'False' elements to 1/0 | 39,583,016 | <p>In python, supposed I have a list: </p>
<pre><code>l = [ 'True', 'False', 'myname', 1, 0, 'foo' ]
</code></pre>
<p>and I want to convert the <em>strings</em> <code>'True'</code> or <code>'False'</code> to <code>1</code> or <code>0</code>, what is the best way to do this and still retain the index that the value h... | 1 | 2016-09-19T22:27:10Z | 39,583,056 | <pre><code>>>> replace = {'True':1, 'False':0}
>>> my_list = [ 'True', 'False', 'myname', 1, 0, 'foo' ]
>>> [replace.get(e,e) for e in my_list]
[1, 0, 'myname', 1, 0, 'foo']
>>>
</code></pre>
| 1 | 2016-09-19T22:31:32Z | [
"python",
"list",
"dictionary"
] |
Update list in-place, converting 'True'/'False' elements to 1/0 | 39,583,016 | <p>In python, supposed I have a list: </p>
<pre><code>l = [ 'True', 'False', 'myname', 1, 0, 'foo' ]
</code></pre>
<p>and I want to convert the <em>strings</em> <code>'True'</code> or <code>'False'</code> to <code>1</code> or <code>0</code>, what is the best way to do this and still retain the index that the value h... | 1 | 2016-09-19T22:27:10Z | 39,583,236 | <p>Thought I would offer a more robust solution if your list's items are <code>on</code>, <code>off</code>, <code>yes</code>, <code>no</code> etc (<em>refer to <a href="https://docs.python.org/2/distutils/apiref.html?highlight=distutils.util#distutils.util.strtobool" rel="nofollow">documentation</a></em>).</p>
<pre><c... | 1 | 2016-09-19T22:51:24Z | [
"python",
"list",
"dictionary"
] |
Update list in-place, converting 'True'/'False' elements to 1/0 | 39,583,016 | <p>In python, supposed I have a list: </p>
<pre><code>l = [ 'True', 'False', 'myname', 1, 0, 'foo' ]
</code></pre>
<p>and I want to convert the <em>strings</em> <code>'True'</code> or <code>'False'</code> to <code>1</code> or <code>0</code>, what is the best way to do this and still retain the index that the value h... | 1 | 2016-09-19T22:27:10Z | 39,583,283 | <p>You can use a for loop</p>
<pre><code>for i in l:
if i == 'True':
a = l.index(i)
b = l.remove(i)
l.insert(a, 1)
elif i == 'False':
a = l.index(i)
b = l.remove(i)
l.insert(a, 0)
print(l)
</code></pre>
| 0 | 2016-09-19T22:56:45Z | [
"python",
"list",
"dictionary"
] |
Update list in-place, converting 'True'/'False' elements to 1/0 | 39,583,016 | <p>In python, supposed I have a list: </p>
<pre><code>l = [ 'True', 'False', 'myname', 1, 0, 'foo' ]
</code></pre>
<p>and I want to convert the <em>strings</em> <code>'True'</code> or <code>'False'</code> to <code>1</code> or <code>0</code>, what is the best way to do this and still retain the index that the value h... | 1 | 2016-09-19T22:27:10Z | 39,583,922 | <p>Your problem is similar to <code>switch</code> statement:</p>
<pre><code>switch(ch):
case "True":
return 1
case "False":
return 0
default:
return ch
</code></pre>
<p>But since in Python we do not have switch statement but we can achieve similar functionality by creating the f... | -1 | 2016-09-20T00:21:10Z | [
"python",
"list",
"dictionary"
] |
Checksum for a list of numbers | 39,583,070 | <p>I have a large number of lists of integers. I want to check if any of the lists are duplicates. I was thinking a good way of doing this would be to calculate a basic checksum, then only doing an element by element check if the checksums coincide. But I can't find a checksum algorithm with good properties, namely:</p... | 2 | 2016-09-19T22:33:03Z | 39,583,175 | <p>Calculate the checksums with <code>hash()</code>:</p>
<pre><code>checksums = \
list(
map(
lambda l:
hash(tuple(l)),
list_of_lists
)
)
</code></pre>
<p>To know how many duplicates you have:</p>
<pre><code>from collections import Counter
counts = Coun... | 0 | 2016-09-19T22:44:22Z | [
"python",
"algorithm",
"checksum"
] |
Checksum for a list of numbers | 39,583,070 | <p>I have a large number of lists of integers. I want to check if any of the lists are duplicates. I was thinking a good way of doing this would be to calculate a basic checksum, then only doing an element by element check if the checksums coincide. But I can't find a checksum algorithm with good properties, namely:</p... | 2 | 2016-09-19T22:33:03Z | 39,599,425 | <p>If you want something homespun, a version of a Fletcher checksum is possible.</p>
<pre><code>def check_sum(l):
sum1 = sum2 = 0
for v in l:
sum1 = (sum1 + v) % 255
sum2 = (sum2 + sum1) % 255
return sum1*256 + sum2
print(
check_sum([1,2,3,4,5]),
check_sum([1,2,3,5,4]),
check_s... | 0 | 2016-09-20T16:32:44Z | [
"python",
"algorithm",
"checksum"
] |
In Sikuli, How to find and click a minimum of 3 identical images? | 39,583,103 | <p>I'm trying to click no less than 3 of the same image, but with <code>findAll()</code> I am having difficulty with sikuli wanting to select only 1 image when I don't want it to select any if there is not 3 or more.</p>
<pre><code>if exists(Pattern("1474201252795.png").similar(0.95)):
wait(1)
for x in findAll... | 1 | 2016-09-19T22:37:19Z | 39,584,678 | <p>So just count the images first and check if the count is higher than 3.</p>
<pre><code>imageCount=0
images = []
# find all images and store them in a list to prevent additional search
for image in findAll("Win7StartBtn.png"):
images.append(image)
#check list length and act accordingly
if len(images) >= 3:... | 1 | 2016-09-20T02:09:14Z | [
"python",
"automation",
"jython",
"sikuli"
] |
Unexpected error while trying to find the longest string | 39,583,131 | <p>I failed to write a program that prints the longest substring of a string in which the letters occur in alphabetical order for my very first Python test. </p>
<p>The comment read </p>
<blockquote>
<p>"Your program does meet what the question asks but also contradicts with rule number 4 and hence your answer will... | 0 | 2016-09-19T22:39:43Z | 39,583,172 | <p>The rule says "do not include input statements"; you included an input statement (in <code>main</code>).</p>
| 0 | 2016-09-19T22:44:02Z | [
"python",
"python-3.x"
] |
Unexpected error while trying to find the longest string | 39,583,131 | <p>I failed to write a program that prints the longest substring of a string in which the letters occur in alphabetical order for my very first Python test. </p>
<p>The comment read </p>
<blockquote>
<p>"Your program does meet what the question asks but also contradicts with rule number 4 and hence your answer will... | 0 | 2016-09-19T22:39:43Z | 39,583,191 | <p>The rule clearly states <strong>not</strong> to include <code>input</code> statements or define variables (which you also did).</p>
<p>You could try re-writing it as :</p>
<pre><code>current_substring = longest_substring = s[0]
for letter in s[1:]:
if letter >= current_substring[-1]:
current_substri... | 0 | 2016-09-19T22:47:15Z | [
"python",
"python-3.x"
] |
Pandas - is it possible to "rewind" read_csv with chunk= argument? | 39,583,153 | <p>I am dealing with a big dataset, therefore to read it in pandas I use <code>read_csv</code> with <code>chunk=</code> option.</p>
<pre><code>data = pd.read_csv("dataset.csv", chunksize=2e5)
</code></pre>
<p>then I operate on the chunked DataFrame in the following way</p>
<pre><code>any_na_cols = [chunk.do_somethin... | 0 | 2016-09-19T22:41:29Z | 39,583,217 | <p>I don't think it's a good idea to read your CSV <strong>again</strong> - you will double the number of IOs. It's better to "do something else" during the same iteration:</p>
<pre><code>any_na_cols = pd.DataFrame()
for chunk in pd.read_csv("dataset.csv", chunksize=2e5)
any_na_cols = pd.concat([any_na_cols, chun... | 1 | 2016-09-19T22:50:03Z | [
"python",
"pandas",
"chunks",
"chunking"
] |
how to pass realtime form arguments to a python script called by a django app | 39,583,157 | <p>my django app calls a python cgi script:</p>
<pre><code>def query(request):
if request.method == 'GET':
output = subprocess.check_output(['python', 'query.cgi']).decode('utf-8')
return HttpResponse(output, content_type="text/html")
</code></pre>
<p>The query.cgi will be called by a form. How do I pass ... | 0 | 2016-09-19T22:41:51Z | 39,583,235 | <p>They're passed in the <code>GET</code> dictionary from <code>request</code>:</p>
<pre><code>foo = request.GET['foo']
subprocess.check_output(['python', 'query.cgi', 'foo=' + foo])
</code></pre>
<p>You can also use</p>
<pre><code>request.GET.get('foo', 'def')
</code></pre>
<p>to have a default value if the key is... | 0 | 2016-09-19T22:51:19Z | [
"python",
"django"
] |
What Is The Python 3 Equivalent to This | 39,583,222 | <p>What is the Python 3 equivalent to Python 2's statement:</p>
<pre><code>print x,
</code></pre>
<p>I am aware of Python's 3</p>
<pre><code>print(x,end=' ')
</code></pre>
<p>However this is not exactly the same as I will demonstrate.</p>
<p>So lets say I had a list of items I wanted to print out all on one line w... | 1 | 2016-09-19T22:50:33Z | 39,583,261 | <p>If you do not require the loop, you can just print it all at once:</p>
<pre><code>print(" ".join(my_list.join))
</code></pre>
| 0 | 2016-09-19T22:53:59Z | [
"python",
"printing",
"trailing"
] |
What Is The Python 3 Equivalent to This | 39,583,222 | <p>What is the Python 3 equivalent to Python 2's statement:</p>
<pre><code>print x,
</code></pre>
<p>I am aware of Python's 3</p>
<pre><code>print(x,end=' ')
</code></pre>
<p>However this is not exactly the same as I will demonstrate.</p>
<p>So lets say I had a list of items I wanted to print out all on one line w... | 1 | 2016-09-19T22:50:33Z | 39,583,278 | <p>Unless you need to print each element on their own, you can do:</p>
<pre><code>print(' '.join(my_list))
</code></pre>
<p>or</p>
<pre><code>print(*my_list)
</code></pre>
| 1 | 2016-09-19T22:55:54Z | [
"python",
"printing",
"trailing"
] |
Pandas: strip numbers and parenthesis from string | 39,583,264 | <p>My pandas df:</p>
<pre><code>df = pd.DataFrame({'A':[1,2,3,4,5], 'B':['(AAAAA)2','(BCA)1','(CA)5','(DD)8','(ED)15']})
A B
0 1 (AAAAA)2
1 2 (BCA)1
2 3 (CA)5
3 4 (DD)8
4 5 (ED)15
</code></pre>
<p>I want to strip parenthsis and numbers in the column <code>B</code> <br>
Expected output is:</... | 2 | 2016-09-19T22:54:12Z | 39,583,276 | <p>you can do it this way:</p>
<pre><code>In [388]: df
Out[388]:
A B
0 1 (AAAAA)2
1 2 (BCA)1
2 3 (CA)5
3 4 (DD)8
4 5 (ED)15
In [389]: df.B = df.B.str.replace(r'[\(\)\d]+', '')
In [390]: df
Out[390]:
A B
0 1 AAAAA
1 2 BCA
2 3 CA
3 4 DD
4 5 ED
</code></pre>
... | 4 | 2016-09-19T22:55:53Z | [
"python",
"regex",
"pandas",
"dataframe",
"python-3.5"
] |
How to handle microseconds with 7 decimal precision instead of 6 | 39,583,265 | <p>I am processing a csv in <code>python</code> (3.5) that has a date field in it. The date contains a microsecond precision of 7 rather than 6, which I believe is the max that <code>strptime</code> can handle. </p>
<p>Without stripping the field the last character, is there a way to make this a datetime object?</p>... | 2 | 2016-09-19T22:54:26Z | 39,583,462 | <p>If that's the format your numbers are in, just use <code>pd.to_timestamp(d)</code></p>
<p>datetime.datetime objects only have microsecond resolution (6 digits), but <a href="http://pandas.pydata.org/pandas-docs/stable/timeseries.html#converting-to-timestamps" rel="nofollow">Pandas Timestamps</a> are Numpy datetime6... | 2 | 2016-09-19T23:16:06Z | [
"python",
"strptime"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.