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 |
|---|---|---|---|---|---|---|---|---|---|
Python how to make class object shared across functions | 38,676,443 | <p>Lets say I created a class object someClassObject in function A, and threw that object into a function B:</p>
<pre><code>functionB(someClassObject)
</code></pre>
<p>How do I retain all the modifications I've made in function B to someClassObject so I can continue using someClassObject in function A if my function B cannot return anything?</p>
<p>My function B is a recursive function and I can't think of anyways to have it return my someClassObject</p>
| 0 | 2016-07-30T17:05:15Z | 38,676,870 | <p>I presume you meant instance of a class when you meant class object, in Python even a class is an object and you can pass them like instances.
In Python all objects are passed by reference meaning when you pass an instance to a function you only pass a reference and all changes you make to the object will be preserved.</p>
<p>If you meant instance of a class than the example is:</p>
<pre><code>class Foo():
def __init__(self):
self.x = 1
def functionB(foo):
foo.x += 1
if foo.x < 10:
functionB(foo)
def functionA():
some_instance_of_Foo = Foo()
functionB(some_instance_of_Foo)
print(some_instance_of_Foo.x)
if __name__ == "__main__":
functionA() # 10
</code></pre>
| 0 | 2016-07-30T17:53:52Z | [
"python",
"oop"
] |
How to get the Average of a specific category via Python | 38,676,558 | <p>I was wondering how I could calculate the average of a specific category via Python? I have a csv file called demo.csv</p>
<pre><code> import pandas as pd
import numpy as np
#loading the data into data frame
X = pd.read_csv('demo.csv')
</code></pre>
<p>the two columns of interest are the <code>Category</code> and <code>Totals</code> column:</p>
<pre><code>Category Totals estimates
2 2777 0.43
4 1003 0.26
4 3473 0.65
4 2638 0.17
1 2855 0.74
0 2196 0.13
0 2630 0.91
2 2714 0.39
3 2472 0.51
0 1090 0.12
</code></pre>
<p>I'm interested in finding the average for the Totals corresponding with <code>Category</code> 2. I know how to do this on excel, I would just filter to only show category 2 and get the average(which ends up being 2745.5) but how would I code this via Python?</p>
| 0 | 2016-07-30T17:19:27Z | 38,676,751 | <p>You can restrict your dataframe to the subset of the rows you want(<code>Category=2</code>), followed by taking mean of the columns corresponding to <code>Totals</code> column as follows:</p>
<pre><code>df[df['Category'] == 2]['Totals'].mean()
2745.5
</code></pre>
| 2 | 2016-07-30T17:41:13Z | [
"python",
"csv",
"pandas",
"average"
] |
How to get the Average of a specific category via Python | 38,676,558 | <p>I was wondering how I could calculate the average of a specific category via Python? I have a csv file called demo.csv</p>
<pre><code> import pandas as pd
import numpy as np
#loading the data into data frame
X = pd.read_csv('demo.csv')
</code></pre>
<p>the two columns of interest are the <code>Category</code> and <code>Totals</code> column:</p>
<pre><code>Category Totals estimates
2 2777 0.43
4 1003 0.26
4 3473 0.65
4 2638 0.17
1 2855 0.74
0 2196 0.13
0 2630 0.91
2 2714 0.39
3 2472 0.51
0 1090 0.12
</code></pre>
<p>I'm interested in finding the average for the Totals corresponding with <code>Category</code> 2. I know how to do this on excel, I would just filter to only show category 2 and get the average(which ends up being 2745.5) but how would I code this via Python?</p>
| 0 | 2016-07-30T17:19:27Z | 38,677,486 | <blockquote>
<p>I'm interested in finding the average for the Totals corresponding with Category 2</p>
</blockquote>
<p>You may set the category as the index then calculate the mean for any category using the <code>.loc</code> or <code>.ix</code> indexers:</p>
<pre><code>df.set_index('Category').loc['2', 'Totals'].mean()
=> 2745.50
df.set_index('Category').ix['2', 'Totals'].mean()
=> 2745.50
</code></pre>
<p>The same can be achieved by using <code>groupby</code></p>
<pre><code>df.groupby('Category').Totals.mean().loc['2']
=> 2745.50
</code></pre>
<p>Note I'm assuming <code>Category</code> is a string.</p>
| 0 | 2016-07-30T18:57:03Z | [
"python",
"csv",
"pandas",
"average"
] |
BeautifulSoup parsing returns None | 38,676,569 | <p>There are plenty of websites thats simply return <code>None</code> when I request a value from the website.</p>
<p>Example: </p>
<pre><code>import requests
from bs4 import BeautifulSoup
def spider():
url = 'https://poloniex.com/exchange'
source_code = requests.get(url)
plain_text = source_code.text
soup = BeautifulSoup(plain_text, "html.parser")
High = soup.findAll("div", {"class": "high info"})[0].string
print High
# returns None
spider()
</code></pre>
<p>How do i solve this problem? Please, all I need is a value.</p>
| 0 | 2016-07-30T17:21:44Z | 40,120,977 | <p>The web page has JavaScript code, and because of this the request doesn't return a complete result (the JS code in this case is necessary to complete the page).</p>
<p>I'm using selenium to solve this kind of problem.</p>
| 0 | 2016-10-19T02:14:11Z | [
"python",
"parsing",
"web-scraping",
"beautifulsoup",
"web-crawler"
] |
BeautifulSoup parsing returns None | 38,676,569 | <p>There are plenty of websites thats simply return <code>None</code> when I request a value from the website.</p>
<p>Example: </p>
<pre><code>import requests
from bs4 import BeautifulSoup
def spider():
url = 'https://poloniex.com/exchange'
source_code = requests.get(url)
plain_text = source_code.text
soup = BeautifulSoup(plain_text, "html.parser")
High = soup.findAll("div", {"class": "high info"})[0].string
print High
# returns None
spider()
</code></pre>
<p>How do i solve this problem? Please, all I need is a value.</p>
| 0 | 2016-07-30T17:21:44Z | 40,121,690 | <p>Download chromedriver from this link <a href="http://chromedriver.storage.googleapis.com/index.html?path=2.24/" rel="nofollow">http://chromedriver.storage.googleapis.com/index.html?path=2.24/</a> and uzip it & Put chromedriver.exe in C:\Python27\Scripts </p>
<p>try this code:</p>
<pre><code>from selenium import webdriver
import time
from bs4 import BeautifulSoup
driver = webdriver.Chrome()
url= "https://poloniex.com/exchange"
driver.maximize_window()
driver.get(url)
time.sleep(5)
content = driver.page_source.encode('utf-8').strip()
soup = BeautifulSoup(content,"html.parser")
High = soup.findAll("div", {"class": "high info"})[0].string
print High
driver.quit()
</code></pre>
<p>It will print:</p>
<pre><code>0.02410000
</code></pre>
<p>Hope this helps</p>
| 0 | 2016-10-19T03:37:27Z | [
"python",
"parsing",
"web-scraping",
"beautifulsoup",
"web-crawler"
] |
Refresh HTML page from python input | 38,676,583 | <p>NEW:</p>
<p>It worked without isseus for like 40 mins, then the code itself crashed:
this is the outpud in the console</p>
<pre><code>Gradi: 29.0 C Umidita: 35.0 %
Traceback (most recent call last):
File "temp.py", line 22, in <module>
valori='Gradi: {0:0.1f} C Umidita: {1:0.1f} %'.format(temperature, humidity)
ValueError: Unknown format code 'f' for object of type 'str'
</code></pre>
<p>what do you advice?</p>
<p>OLD:</p>
<p>I have to refresh an HTML page that is rewritten every time by the Python script to have the latest values. Sometimes it happens that the page refresh but shows a white page, with no data. How can I fix this?</p>
<pre><code>import datetime
import sys
import Adafruit_DHT
import time
a = """<html>
<meta http-equiv="refresh" content="">
<head></head>
<body><p>"""
b = """</p></body>
</html>"""
try:
while True:
file = open("logtemperature.txt", "a")
web = open('temperatura.html', 'w')
humidity, temperature = Adafruit_DHT.read_retry(11, 16) #11 modello 16 pin
valori = 'Gradi: {0:0.1f} C Umidita: {1:0.1f} %'.format(temperature, humidity)
print (valori)
file.write("\n" + valori + " " + str(datetime.datetime.now()))
web.write(a + "TEMPERATURA INTERNA:" + " " + valori + b)
time.sleep(1)
web.close()
file.close()
time.sleep(2)
except KeyboardInterrupt:
file.close()
web.close()
</code></pre>
| 0 | 2016-07-30T17:24:03Z | 38,676,796 | <p>For making <em>really</em> sure the file never is empty or incomplete when reading from it with another program keep reading below the first code block.</p>
<p>If it is OK for you to <em>almost</em> never have an empty or incomplete file you would do</p>
<pre><code>import datetime
import sys
import Adafruit_DHT
import time
a="""<html>
<meta http-equiv="refresh" content="">
<head></head>
<body><p>"""
b="""</p></body>
</html>"""
while True:
humidity, temperature = Adafruit_DHT.read_retry(11,16) #11 modello 16 pin
valori='Gradi: {0:0.1f} C Umidita: {1:0.1f} %'.format(temperature, humidity)
print (valori)
ls="\n"+valori+" "+str(datetime.datetime.now())
with open("logtemperature.txt","a") as file:
file.write(ls)
ws=a+"TEMPERATURA INTERNA:"+" "+valori+b
with open('temperatura.html','w') as web:
web.write(ws)
time.sleep(2)
</code></pre>
<p>if you are on Unix/Linux (eg Raspbian), you can make your own quasi-atomic write as <a href="https://docs.python.org/2/library/os.html#os.rename" rel="nofollow">os.rename</a> is atomic, making sure <code>temperatura.html</code> is always complete</p>
<pre><code>import os
def atomic_write(filename, bytes):
shouldnotexist=filename+".deleteme"
with open(shouldnotexist,"wb") as f:
f.write(bytes)
os.rename(shouldnotexist,filename)
</code></pre>
<p>replacing</p>
<pre><code>with open('temperatura.html','w') as web:
web.write(ws)
</code></pre>
<p>with </p>
<pre><code>atomic_write('temperatura.html', ws)
</code></pre>
<p>On Windows it propably is more complicated...</p>
<p>Edit:</p>
<p>To mitigate your ValueError-problem, you can replace </p>
<pre><code>valori='Gradi: {0:0.1f} C Umidita: {1:0.1f} %'.format(temperature, humidity)
</code></pre>
<p>with </p>
<pre><code>try:
valori='Gradi: {0:0.1f} C Umidita: {1:0.1f} %'.format(temperature, humidity)
except ValueError:
valori='Gradi: {0} C Umidita: {1} % (something saying there was a problem)'.format(temperature, humidity)
</code></pre>
| 0 | 2016-07-30T17:46:02Z | [
"python",
"html",
"raspberry-pi"
] |
Returning a PDF from S3 in Flask | 38,676,591 | <p>I'm trying to return a PDF in the browser in a Flask application. I'm using AWS S3 to store the files and boto3 as the SDK to interact with S3. My code so far is:</p>
<pre><code>s3 = boto3.resource('s3', aws_access_key_id=settings.AWS_ACCESS_KEY,
aws_secret_access_key=settings.AWS_SECRET_KEY)
file = s3.Object(settings.S3_BUCKET_NAME, 'test.pdf')).get()
response = make_response(file)
response.headers['Content-Type'] = 'application/pdf'
return response
</code></pre>
<p>I'm able to successfully retrieve the object from S3 in <code>file</code> using boto3, however that is a dictionary of which I'm not sure how to return the PDF from that</p>
| 0 | 2016-07-30T17:25:25Z | 38,679,722 | <p>It turns out that boto3 doesn't have a <code>readLines()</code> method but they do have a <code>read()</code> method, so it worked by doing:</p>
<pre><code>response = make_response(file['Body'].read())
response.headers['Content-Type'] = 'application/pdf'
return response
</code></pre>
| 0 | 2016-07-31T00:26:56Z | [
"python",
"amazon-web-services",
"amazon-s3",
"flask",
"boto3"
] |
Tkinter Show splash screen and hide main screen until __init__ has finished | 38,676,617 | <p>I have a main tkinter window that can take up to a few seconds to load properly. Because of this, I wish to have a splash screen that shows until the <strong>init</strong> method of the main class has finished, and the main tkinter application can be shown. How can this be achieved?</p>
<p>Splash screen code:</p>
<pre><code>from Tkinter import *
from PIL import Image, ImageTk
import ttk
class DemoSplashScreen:
def __init__(self, parent):
self.parent = parent
self.aturSplash()
self.aturWindow()
def aturSplash(self):
self.gambar = Image.open('../output5.png')
self.imgSplash = ImageTk.PhotoImage(self.gambar)
def aturWindow(self):
lebar, tinggi = self.gambar.size
setengahLebar = (self.parent.winfo_screenwidth()-lebar)//2
setengahTinggi = (self.parent.winfo_screenheight()-tinggi)//2
self.parent.geometry("%ix%i+%i+%i" %(lebar, tinggi, setengahLebar,setengahTinggi))
Label(self.parent, image=self.imgSplash).pack()
if __name__ == '__main__':
root = Tk()
root.overrideredirect(True)
progressbar = ttk.Progressbar(orient=HORIZONTAL, length=10000, mode='determinate')
progressbar.pack(side="bottom")
app = DemoSplashScreen(root)
progressbar.start()
root.after(6010, root.destroy)
root.mainloop()
</code></pre>
<p>Main tkinter window minimum working example:</p>
<pre><code>import tkinter as tk
root = tk.Tk()
class Controller(tk.Frame):
def __init__(self, parent):
'''Initialises basic variables and GUI elements.'''
frame = tk.Frame.__init__(self, parent,relief=tk.GROOVE,width=100,height=100,bd=1)
control = Controller(root)
control.pack()
root.mainloop()
</code></pre>
<p>EDIT: I can use the main window until it has finished loading using the .withdraw() and .deiconify() methods. However my problem is that I cannot find a way to have the splash screen running in the period between these two method calls.</p>
| 0 | 2016-07-30T17:27:31Z | 38,678,891 | <p>a simple example for python3:</p>
<pre><code>#!python3
import tkinter as tk
import time
class Splash(tk.Toplevel):
def __init__(self, parent):
tk.Toplevel.__init__(self, parent)
self.title("Splash")
## required to make window show before the program gets to the mainloop
self.update()
class App(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.withdraw()
splash = Splash(self)
## setup stuff goes here
self.title("Main Window")
## simulate a delay while loading
time.sleep(6)
## finished loading so destroy splash
splash.destroy()
## show window again
self.deiconify()
if __name__ == "__main__":
app = App()
app.mainloop()
</code></pre>
<p>one of the reasons things like this are difficult in tkinter is that windows are only updated when the program isn't running particular functions and so reaches the mainloop. for simple things like this you can use the <code>update</code> or <code>update_idletasks</code> commands to make it show/update, however if the delay is too long then on windows the window can become "unresponsive"</p>
<p>one way around this is to put multiple <code>update</code> or <code>update_idletasks</code> command throughout your loading routine, or alternatively use threading.</p>
<p>however if you use threading i would suggest that instead of putting the splash into its own thread (probably easier to implement) you would be better served putting the loading tasks into its own thread, keeping worker threads and GUI threads separate, as this tends to give a smoother user experience.</p>
| 0 | 2016-07-30T22:03:15Z | [
"python",
"tkinter",
"splash-screen"
] |
Cant select a value from a drop down list using Selenium in python | 38,676,636 | <p>I'm trying to select the year 1989 in the drop down list on this sign up page.</p>
<pre><code>driver.get("https://club.pokemon.com/us/pokemon-trainer-club/sign-up/")
elem = driver.find_element_by_id("id_dob")
elem.send_keys(Keys.RETURN)
elem = driver.find_element_by_class_name("picker__footer")
find_element_by_xpath("//*[@id='sign-up-theme']/option[@value='1989']").click()
Select(driver.find_element_by_css_selector("#sign-up-theme")).select_by_value(1989).click()
</code></pre>
<p>I'm using chrome as a browser and right now it says it cannot find the element.</p>
<p>Here is the html but if u need something more/different i included the link to the site im using.
Ps. not a profesional coder or anything super duper scrub when it comes to coding.</p>
<pre><code><div class="custom-select-wrapper" style="visibility: visible;"><select class="year" style="display: none;"><option value="1936">1936</option><option value="1937">1937</option><option value="1938">1938</option><option value="1939">1939</option><option value="1940">1940</option><option value="1941">1941</option><option value="1942">1942</option><option value="1943">1943</option><option value="1944">1944</option><option value="1945">1945</option><option value="1946">1946</option><option value="1947">1947</option><option value="1948">1948</option><option value="1949">1949</option><option value="1950">1950</option><option value="1951">1951</option><option value="1952">1952</option><option value="1953">1953</option><option value="1954">1954</option><option value="1955">1955</option><option value="1956">1956</option><option value="1957">1957</option><option value="1958">1958</option><option value="1959">1959</option><option value="1960">1960</option><option value="1961">1961</option><option value="1962">1962</option><option value="1963">1963</option><option value="1964">1964</option><option value="1965">1965</option><option value="1966">1966</option><option value="1967">1967</option><option value="1968">1968</option><option value="1969">1969</option><option value="1970">1970</option><option value="1971">1971</option><option value="1972">1972</option><option value="1973">1973</option><option value="1974">1974</option><option value="1975">1975</option><option value="1976">1976</option><option value="1977">1977</option><option value="1978">1978</option><option value="1979">1979</option><option value="1980">1980</option><option value="1981">1981</option><option value="1982">1982</option><option value="1983">1983</option><option value="1984">1984</option><option value="1985">1985</option><option value="1986">1986</option><option value="1987">1987</option><option value="1988">1988</option><option value="1989">1989</option><option value="1990">1990</option><option value="1991">1991</option><option value="1992">1992</option><option value="1993">1993</option><option value="1994">1994</option><option value="1995">1995</option><option value="1996">1996</option><option value="1997">1997</option><option value="1998">1998</option><option value="1999">1999</option><option value="2000">2000</option><option value="2001">2001</option><option value="2002">2002</option><option value="2003">2003</option><option value="2004">2004</option><option value="2005">2005</option><option value="2006">2006</option><option value="2007">2007</option><option value="2008">2008</option><option value="2009">2009</option><option value="2010">2010</option><option value="2011">2011</option><option value="2012">2012</option><option value="2013">2013</option><option value="2014">2014</option><option value="2015">2015</option><option value="2016" selected="">2016</option></select><div class="custom-select-menu" tabindex="0"><label class="styled-select button-black opened">2016</label><div class="custom-scrollbar custom-select-scrollbar" style="height: 200px; display: block;"><div class="viewport"><ul data-select-name="undefined" class="overview"><li data-option-value="2016" class="selected">2016</li><li data-option-value="2015" class="">2015</li><li data-option-value="2014" class="">2014</li><li data-option-value="2013" class="">2013</li><li data-option-value="2012" class="">2012</li><li data-option-value="2011" class="">2011</li><li data-option-value="2010" class="">2010</li><li data-option-value="2009" class="">2009</li><li data-option-value="2008" class="">2008</li><li data-option-value="2007" class="">2007</li><li data-option-value="2006" class="">2006</li><li data-option-value="2005" class="">2005</li><li data-option-value="2004" class="">2004</li><li data-option-value="2003" class="">2003</li><li data-option-value="2002" class="">2002</li><li data-option-value="2001" class="">2001</li><li data-option-value="2000" class="">2000</li><li data-option-value="1999" class="">1999</li><li data-option-value="1998" class="">1998</li><li data-option-value="1997" class="">1997</li><li data-option-value="1996" class="">1996</li><li data-option-value="1995" class="">1995</li><li data-option-value="1994" class="">1994</li><li data-option-value="1993" class="">1993</li><li data-option-value="1992" class="">1992</li><li data-option-value="1991" class="">1991</li><li data-option-value="1990" class="">1990</li><li data-option-value="1989" class="">1989</li><li data-option-value="1988" class="">1988</li><li data-option-value="1987" class="">1987</li><li data-option-value="1986" class="">1986</li><li data-option-value="1985" class="">1985</li><li data-option-value="1984" class="">1984</li><li data-option-value="1983" class="">1983</li><li data-option-value="1982" class="">1982</li><li data-option-value="1981" class="">1981</li><li data-option-value="1980" class="">1980</li><li data-option-value="1979" class="">1979</li><li data-option-value="1978" class="">1978</li><li data-option-value="1977" class="">1977</li><li data-option-value="1976" class="">1976</li><li data-option-value="1975" class="">1975</li><li data-option-value="1974" class="">1974</li><li data-option-value="1973" class="">1973</li><li data-option-value="1972" class="">1972</li><li data-option-value="1971" class="">1971</li><li data-option-value="1970" class="">1970</li><li data-option-value="1969" class="">1969</li><li data-option-value="1968" class="">1968</li><li data-option-value="1967" class="">1967</li><li data-option-value="1966" class="">1966</li><li data-option-value="1965" class="">1965</li><li data-option-value="1964" class="">1964</li><li data-option-value="1963" class="">1963</li><li data-option-value="1962" class="">1962</li><li data-option-value="1961" class="">1961</li><li data-option-value="1960" class="">1960</li><li data-option-value="1959" class="">1959</li><li data-option-value="1958" class="">1958</li><li data-option-value="1957" class="">1957</li><li data-option-value="1956" class="">1956</li><li data-option-value="1955" class="">1955</li><li data-option-value="1954" class="">1954</li><li data-option-value="1953" class="">1953</li><li data-option-value="1952" class="">1952</li><li data-option-value="1951" class="">1951</li><li data-option-value="1950" class="">1950</li><li data-option-value="1949" class="">1949</li><li data-option-value="1948" class="">1948</li><li data-option-value="1947" class="">1947</li><li data-option-value="1946" class="">1946</li><li data-option-value="1945" class="">1945</li><li data-option-value="1944" class="">1944</li><li data-option-value="1943" class="">1943</li><li data-option-value="1942" class="">1942</li><li data-option-value="1941" class="">1941</li><li data-option-value="1940" class="">1940</li><li data-option-value="1939" class="">1939</li><li data-option-value="1938" class="">1938</li><li data-option-value="1937" class="">1937</li><li data-option-value="1936" class="">1936</li></ul></div></div><input type="hidden" name="undefined" value="2016"></div></div>
</code></pre>
| 1 | 2016-07-30T17:29:48Z | 38,676,846 | <p>You can actually avoid dealing with the date picker in the first place and set the "date of birth" <em>directly in the input</em>. For that, we can remove the <code>readonly</code> property from the "date of birth" input and <a href="http://stackoverflow.com/a/4386514/771848">replace the element with it's clone to remove all event listeners</a> which would help to avoid having the datepicker being tied to the input.</p>
<p>Works for me:</p>
<pre><code>from selenium import webdriver
driver = webdriver.Firefox()
driver.get("https://club.pokemon.com/us/pokemon-trainer-club/sign-up/")
elem = driver.find_element_by_id("id_dob")
driver.execute_script("arguments[0].removeAttribute('readonly'); arguments[0].removeAttribute('class');", elem)
driver.execute_script("""
var clone = arguments[0].cloneNode();
while (arguments[0].firstChild) {
clone.appendChild(arguments[0].lastChild);
}
arguments[0].parentNode.replaceChild(clone, arguments[0]);
""", elem)
elem = driver.find_element_by_id("id_dob")
elem.clear()
elem.send_keys("1989-02-20")
</code></pre>
| 0 | 2016-07-30T17:51:18Z | [
"python",
"selenium"
] |
How can I create an in-memory database with sqlite? | 38,676,691 | <p>I'm trying to create an in-memory database using <code>sqlite3</code> in Python.</p>
<p>I created a function to create a db database file and store information in to it and that is working 100%.</p>
<p>But trying to connect with <code>:memory:</code> I've faced some problems.</p>
<p>What I'm doing is:</p>
<pre><code>import sqlite3
def execute_db(*args):
db = sqlite3.connect(":memory:")
cur = db.cursor()
data = True
try:
args = list(args)
args[0] = args[0].replace("%s", "?").replace(" update "," `update` ")
args = tuple(args)
cur.execute(*args)
arg = args[0].split()[0].lower()
if arg in ["update", "insert", "delete", "create"]: db.commit()
except Exception as why:
print why
data = False
db.rollback()
db.commit()
db.close()
return data
</code></pre>
<ol>
<li><p>create name table</p>
<pre><code>execute_db("create table name(name text)")
</code></pre>
<p>which returned <code>True</code></p></li>
<li><p>insert some information to this table</p>
<pre><code>execute_db("insert into name values('Hello')")
</code></pre>
<p>which returned</p>
<pre><code>no such table: name
False
</code></pre></li>
</ol>
<p>Why doesn't this work? It works when I use a file:</p>
<pre><code>db = sqlite3.connect("sqlite3.db")
</code></pre>
| 0 | 2016-07-30T17:35:00Z | 38,676,728 | <p>You create a <strong>new</strong> connection each time you call the function. Each connection call produces a <strong>new</strong> in-memory database.</p>
<p>Create the connection outside of the function, and pass it into the function, or create a <a href="https://stackoverflow.com/questions/32681761/how-can-i-attach-an-in-memory-sqlite-database-in-python/32681822#32681822">shared memory connection</a>:</p>
<pre><code>db = sqlite3.connect("file::memory:?cache=shared")
</code></pre>
<p>However, the database will be <em>erased</em> when the last connection is deleted from memory; in your case that'll be each time the function ends.</p>
<p>Rather than explicitly call <code>db.commit()</code>, just use the database connection <a href="https://docs.python.org/2/library/sqlite3.html#using-the-connection-as-a-context-manager" rel="nofollow">as a context manager</a>:</p>
<pre><code>try:
with db:
cur = db.cursor()
# massage `args` as needed
cur.execute(*args)
return True
except Exception as why:
return False
</code></pre>
<p>The transaction is automatically committed if there was no exception, rolled back otherwise. Note that it is safe to commit a query that only reads data.</p>
| 2 | 2016-07-30T17:39:07Z | [
"python",
"python-2.7",
"sqlite",
"sqlite3"
] |
Checking if a list of tuples is a subset of another | 38,676,711 | <p>Firstly, note that I have gone through the other list-subset questions and they are not related to my problem here. </p>
<p>I have two lists</p>
<pre><code>>>> l1 = [[(7, -1, 'VBD', 'null', -1, 'looked', 'looked'), (8, 7, 'JJ', 'xcomp', -1, 'shocked', 'shocked')]]
>>>
>>> l2 = [(7, -1, 'VBD', 'null', -1, 'looked', 'looked'), (8, 7, 'JJ', 'xcomp', -1, 'shocked', 'shocked'), (9, 8, 'CC', 'cc', -1, 'and', 'and'), (10, 7, 'JJ', 'xcomp', -1, 'angry', 'angry')]
</code></pre>
<p>I'm trying to check if one is a subset of another.</p>
<p>But before that I checked out the results of subtracting one list from another and I got disappointing results -</p>
<pre><code>>>> [word for word in l1 if word not in l2]
[[(7, -1, 'VBD', 'null', -1, 'looked', 'looked'), (8, 7, 'JJ', 'xcomp', -1, 'shocked', 'shocked')]]
>>> [word for word in l2 if word not in l1]
[(7, -1, 'VBD', 'null', -1, 'looked', 'looked'), (8, 7, 'JJ', 'xcomp', -1, 'shocked', 'shocked'), (9, 8, 'CC', 'cc', -1, 'and', 'and'), (10, 7, 'JJ', 'xcomp', -1, 'angry', 'angry')]
</code></pre>
<p>Why am I getting identical lists as my results?
Does this have something to do with the fact that they are tuples?</p>
| 0 | 2016-07-30T17:37:30Z | 38,676,750 | <p>You can just use sets and the <= operator (is subset of). </p>
<pre><code>>>> l1 = [2,4,6,8]
>>> l2 = [2,4,6,8,10]
>>> set(l1) <= set(l2)
True
</code></pre>
| 0 | 2016-07-30T17:41:09Z | [
"python",
"list",
"set"
] |
Checking if a list of tuples is a subset of another | 38,676,711 | <p>Firstly, note that I have gone through the other list-subset questions and they are not related to my problem here. </p>
<p>I have two lists</p>
<pre><code>>>> l1 = [[(7, -1, 'VBD', 'null', -1, 'looked', 'looked'), (8, 7, 'JJ', 'xcomp', -1, 'shocked', 'shocked')]]
>>>
>>> l2 = [(7, -1, 'VBD', 'null', -1, 'looked', 'looked'), (8, 7, 'JJ', 'xcomp', -1, 'shocked', 'shocked'), (9, 8, 'CC', 'cc', -1, 'and', 'and'), (10, 7, 'JJ', 'xcomp', -1, 'angry', 'angry')]
</code></pre>
<p>I'm trying to check if one is a subset of another.</p>
<p>But before that I checked out the results of subtracting one list from another and I got disappointing results -</p>
<pre><code>>>> [word for word in l1 if word not in l2]
[[(7, -1, 'VBD', 'null', -1, 'looked', 'looked'), (8, 7, 'JJ', 'xcomp', -1, 'shocked', 'shocked')]]
>>> [word for word in l2 if word not in l1]
[(7, -1, 'VBD', 'null', -1, 'looked', 'looked'), (8, 7, 'JJ', 'xcomp', -1, 'shocked', 'shocked'), (9, 8, 'CC', 'cc', -1, 'and', 'and'), (10, 7, 'JJ', 'xcomp', -1, 'angry', 'angry')]
</code></pre>
<p>Why am I getting identical lists as my results?
Does this have something to do with the fact that they are tuples?</p>
| 0 | 2016-07-30T17:37:30Z | 38,676,757 | <p>Use <a href="https://docs.python.org/2/library/stdtypes.html#set.issubset" rel="nofollow"><code>issubset</code></a>,</p>
<pre><code>l1 = [(7, -1, 'VBD', 'null', -1, 'looked', 'looked'), (8, 7, 'JJ', 'xcomp', -1, 'shocked', 'shocked')]
l2 = [(7, -1, 'VBD', 'null', -1, 'looked', 'looked'), (8, 7, 'JJ', 'xcomp', -1, 'shocked', 'shocked'), (9, 8, 'CC', 'cc', -1, 'and', 'and'), (10, 7, 'JJ', 'xcomp', -1, 'angry', 'angry')]
>>> set(l1).issubset(l2)
True
</code></pre>
| 0 | 2016-07-30T17:41:45Z | [
"python",
"list",
"set"
] |
Checking if a list of tuples is a subset of another | 38,676,711 | <p>Firstly, note that I have gone through the other list-subset questions and they are not related to my problem here. </p>
<p>I have two lists</p>
<pre><code>>>> l1 = [[(7, -1, 'VBD', 'null', -1, 'looked', 'looked'), (8, 7, 'JJ', 'xcomp', -1, 'shocked', 'shocked')]]
>>>
>>> l2 = [(7, -1, 'VBD', 'null', -1, 'looked', 'looked'), (8, 7, 'JJ', 'xcomp', -1, 'shocked', 'shocked'), (9, 8, 'CC', 'cc', -1, 'and', 'and'), (10, 7, 'JJ', 'xcomp', -1, 'angry', 'angry')]
</code></pre>
<p>I'm trying to check if one is a subset of another.</p>
<p>But before that I checked out the results of subtracting one list from another and I got disappointing results -</p>
<pre><code>>>> [word for word in l1 if word not in l2]
[[(7, -1, 'VBD', 'null', -1, 'looked', 'looked'), (8, 7, 'JJ', 'xcomp', -1, 'shocked', 'shocked')]]
>>> [word for word in l2 if word not in l1]
[(7, -1, 'VBD', 'null', -1, 'looked', 'looked'), (8, 7, 'JJ', 'xcomp', -1, 'shocked', 'shocked'), (9, 8, 'CC', 'cc', -1, 'and', 'and'), (10, 7, 'JJ', 'xcomp', -1, 'angry', 'angry')]
</code></pre>
<p>Why am I getting identical lists as my results?
Does this have something to do with the fact that they are tuples?</p>
| 0 | 2016-07-30T17:37:30Z | 38,676,781 | <p>The problem is that <code>l1</code> is a list of list of tuple (i.e. [[tuple]]), whereas <code>l2</code> is a list of tuple (i.e. [tuple]). If you change this the output from the list comprehensions are what you expect:</p>
<pre><code>l1 = [(7, -1, 'VBD', 'null', -1, 'looked', 'looked'), (8, 7, 'JJ', 'xcomp', -1, 'shocked', 'shocked')]
l2 = [(7, -1, 'VBD', 'null', -1, 'looked', 'looked'), (8, 7, 'JJ', 'xcomp', -1, 'shocked', 'shocked'), (9, 8, 'CC', 'cc', -1, 'and', 'and'), (10, 7, 'JJ', 'xcomp', -1, 'angry', 'angry')]
â
a = [word for word in l1 if word not in l2]
b = [word for word in l2 if word not in l1]
â
print a
print b
[]
[(9, 8, 'CC', 'cc', -1, 'and', 'and'), (10, 7, 'JJ', 'xcomp', -1, 'angry', 'angry')]
</code></pre>
| 3 | 2016-07-30T17:44:12Z | [
"python",
"list",
"set"
] |
Fail to Launch Mozilla with selenium | 38,676,719 | <p>I am trying to launch <code>Mozilla</code> but still i am getting this error:</p>
<blockquote>
<p>Exception in thread "main" java.lang.IllegalStateException: The path to the driver executable must be set by the webdriver.gecko.driver system property; for more information, see <a href="https://github.com/mozilla/geckodriver">https://github.com/mozilla/geckodriver</a>. The latest version can be downloaded from <a href="https://github.com/mozilla/geckodriver/releases">https://github.com/mozilla/geckodriver/releases</a></p>
</blockquote>
<p>I am using <code>Selenium 3.0.01</code> Beta version and <code>Mozilla 45</code>. I have tried with <code>Mozilla 47</code> too. but still the same thing.</p>
| 8 | 2016-07-30T17:38:13Z | 38,676,858 | <p><em>The <code>Selenium</code> client bindings will try to locate the <code>geckodriver</code> executable from the system <code>PATH</code>. You will need to add the directory containing the executable to the system path.</em></p>
<ul>
<li><p>On <strong>Unix</strong> systems you can do the following to append it to your systemâs search path, if youâre using a bash-compatible shell:</p>
<pre><code>export PATH=$PATH:/path/to/directory/of/executable/downloaded/in/previous/step
</code></pre></li>
<li><p>On <strong>Windows</strong> you need to update the Path system variable to add the full directory path to the executable. The principle is the same as on Unix.</p></li>
</ul>
<p><em>To use Marionette in your tests you will need to update your desired capabilities to use it.</em></p>
<p><strong>Java</strong> :</p>
<p>As exception is clearly saying you need to download latest <code>geckodriver.exe</code> from <a href="https://github.com/mozilla/geckodriver/releases" rel="nofollow">here</a> and set downloaded <code>geckodriver.exe</code> path where it's exists in your computer as system property with with variable <code>webdriver.gecko.driver</code> before initiating marionette driver and launching firefox as below :-</p>
<pre><code>//if you didn't update the Path system variable to add the full directory path to the executable as above mentioned then doing this directly through code
System.setProperty("webdriver.gecko.driver", "path/to/geckodriver.exe");
//Now you can Initialize marionette driver to launch firefox
DesiredCapabilities capabilities = DesiredCapabilities.firefox();
capabilities.setCapability("marionette", true);
WebDriver driver = new MarionetteDriver(capabilities);
</code></pre>
<p>And for <code>Selenium3</code> use as :- </p>
<pre><code>WebDriver driver = new FirefoxDriver(capabilities);
</code></pre>
<p><a href="http://qavalidation.com/2016/08/whats-new-in-selenium-3-0.html" rel="nofollow">If you're still in trouble follow this link as well which would help you to solving your problem</a></p>
<p><strong>.NET</strong> :</p>
<pre><code>var driver = new FirefoxDriver(new FirefoxOptions());
</code></pre>
<p><strong>Python</strong> :</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
caps = DesiredCapabilities.FIREFOX
# Tell the Python bindings to use Marionette.
# This will not be necessary in the future,
# when Selenium will auto-detect what remote end
# it is talking to.
caps["marionette"] = True
# Path to Firefox DevEdition or Nightly.
# Firefox 47 (stable) is currently not supported,
# and may give you a suboptimal experience.
#
# On Mac OS you must point to the binary executable
# inside the application package, such as
# /Applications/FirefoxNightly.app/Contents/MacOS/firefox-bin
caps["binary"] = "/usr/bin/firefox"
driver = webdriver.Firefox(capabilities=caps)
</code></pre>
<p><strong>Ruby</strong> :</p>
<pre><code># Selenium 3 uses Marionette by default when firefox is specified
# Set Marionette in Selenium 2 by directly passing marionette: true
# You might need to specify an alternate path for the desired version of Firefox
Selenium::WebDriver::Firefox::Binary.path = "/path/to/firefox"
driver = Selenium::WebDriver.for :firefox, marionette: true
</code></pre>
<p><strong>JavaScript (Node.js)</strong> :</p>
<pre><code>const webdriver = require('selenium-webdriver');
const Capabilities = require('selenium-webdriver/lib/capabilities').Capabilities;
var capabilities = Capabilities.firefox();
// Tell the Node.js bindings to use Marionette.
// This will not be necessary in the future,
// when Selenium will auto-detect what remote end
// it is talking to.
capabilities.set('marionette', true);
var driver = new webdriver.Builder().withCapabilities(capabilities).build();
</code></pre>
<p><strong>Using <code>RemoteWebDriver</code></strong></p>
<p>If you want to use <code>RemoteWebDriver</code> in any language, this will allow you to use <code>Marionette</code> in <code>Selenium</code> Grid.</p>
<p><strong>Python</strong>:</p>
<pre><code>caps = DesiredCapabilities.FIREFOX
# Tell the Python bindings to use Marionette.
# This will not be necessary in the future,
# when Selenium will auto-detect what remote end
# it is talking to.
caps["marionette"] = True
driver = webdriver.Firefox(capabilities=caps)
</code></pre>
<p><strong>Ruby</strong> :</p>
<pre><code># Selenium 3 uses Marionette by default when firefox is specified
# Set Marionette in Selenium 2 by using the Capabilities class
# You might need to specify an alternate path for the desired version of Firefox
caps = Selenium::WebDriver::Remote::Capabilities.firefox marionette: true, firefox_binary: "/path/to/firefox"
driver = Selenium::WebDriver.for :remote, desired_capabilities: caps
</code></pre>
<p><strong>Java</strong> :</p>
<pre><code>DesiredCapabilities capabilities = DesiredCapabilities.firefox();
// Tell the Java bindings to use Marionette.
// This will not be necessary in the future,
// when Selenium will auto-detect what remote end
// it is talking to.
capabilities.setCapability("marionette", true);
WebDriver driver = new RemoteWebDriver(capabilities);
</code></pre>
<p><strong>.NET</strong></p>
<pre><code>DesiredCapabilities capabilities = DesiredCapabilities.Firefox();
// Tell the .NET bindings to use Marionette.
// This will not be necessary in the future,
// when Selenium will auto-detect what remote end
// it is talking to.
capabilities.SetCapability("marionette", true);
var driver = new RemoteWebDriver(capabilities);
</code></pre>
<p>Note : Just like the other drivers available to Selenium from other browser vendors, Mozilla has released now an executable that will run alongside the browser. Follow <a href="https://developer.mozilla.org/en-US/docs/Mozilla/QA/Marionette/WebDriver" rel="nofollow">this</a> for more details.</p>
<p><a href="https://github.com/mozilla/geckodriver/releases" rel="nofollow">You can download latest geckodriver executable to support latest firefox from here</a></p>
| 11 | 2016-07-30T17:53:02Z | [
"java",
"python",
"selenium",
"firefox",
"mozilla"
] |
Fail to Launch Mozilla with selenium | 38,676,719 | <p>I am trying to launch <code>Mozilla</code> but still i am getting this error:</p>
<blockquote>
<p>Exception in thread "main" java.lang.IllegalStateException: The path to the driver executable must be set by the webdriver.gecko.driver system property; for more information, see <a href="https://github.com/mozilla/geckodriver">https://github.com/mozilla/geckodriver</a>. The latest version can be downloaded from <a href="https://github.com/mozilla/geckodriver/releases">https://github.com/mozilla/geckodriver/releases</a></p>
</blockquote>
<p>I am using <code>Selenium 3.0.01</code> Beta version and <code>Mozilla 45</code>. I have tried with <code>Mozilla 47</code> too. but still the same thing.</p>
| 8 | 2016-07-30T17:38:13Z | 40,048,585 | <p>Download gecko driver from the seleniumhq website and set the path for gecko driver as below</p>
<pre><code>System.setProperty("webdriver.gecko.driver","C:\\geckodriver-v0.10.0-win64\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
</code></pre>
| 0 | 2016-10-14T17:12:00Z | [
"java",
"python",
"selenium",
"firefox",
"mozilla"
] |
Cut off trailing group with regex | 38,676,726 | <p>I have a couple of strings which all terminate with some numerical digits, immediately preceeded by a number of non-numerical characters, e.g., <code>10.1002/0470868279-ch1</code>. I would like cut off exactly this group; for this example <code>-ch1</code>. I tried</p>
<pre><code>import re
str0 = '10.1002/0470868279-ch1'
a = re.match('(.*)([^0-9]+[0-9]*)', str0)
print(a.group(0))
print(a.group(1))
print(a.group(2))
str1 = '10.1002/0470868279.1' # likewise
</code></pre>
<p>but that's not quite it:</p>
<pre><code>10.1002/0470868279.ch1
10.1002/0470868279.c
h1
</code></pre>
<p>I guess the regex matches greedily from the start.</p>
<p>Any hints?</p>
| -1 | 2016-07-30T17:38:46Z | 38,676,762 | <p>Add <code>?</code> to make first match non-greedy so it matches as little as possible. Also add <code>$</code> so that match will always go to end of string:</p>
<pre><code>a = re.match('(.*?)([^0-9]+[0-9]*)$', str0)
</code></pre>
| 3 | 2016-07-30T17:42:22Z | [
"python",
"regex"
] |
Cut off trailing group with regex | 38,676,726 | <p>I have a couple of strings which all terminate with some numerical digits, immediately preceeded by a number of non-numerical characters, e.g., <code>10.1002/0470868279-ch1</code>. I would like cut off exactly this group; for this example <code>-ch1</code>. I tried</p>
<pre><code>import re
str0 = '10.1002/0470868279-ch1'
a = re.match('(.*)([^0-9]+[0-9]*)', str0)
print(a.group(0))
print(a.group(1))
print(a.group(2))
str1 = '10.1002/0470868279.1' # likewise
</code></pre>
<p>but that's not quite it:</p>
<pre><code>10.1002/0470868279.ch1
10.1002/0470868279.c
h1
</code></pre>
<p>I guess the regex matches greedily from the start.</p>
<p>Any hints?</p>
| -1 | 2016-07-30T17:38:46Z | 38,676,904 | <p>The following should match up to the end of what you want: <code>(-|\+)?\d+(\.\d*)?/(-|\+)?\d+(\.\d*)?</code> This would let you extract the numbers you are looking for.</p>
<p>This pattern would match just the end portion (<em>tested on your <code>-ch1</code> example</em>): <code>(?<=\d)[^\d\./][a-zA-Z0-9]*$</code></p>
<p>I'm not really sure what you mean by "cut off", seeing as your example is just pulling out groups and not actually manipulating the string to cut anything off, but either of those patterns should extract the portions you are looking for.</p>
| 0 | 2016-07-30T17:57:40Z | [
"python",
"regex"
] |
how to know whether login is successfull or not? | 38,676,799 | <p>I am using roboBrowser to login into a website and this the code</p>
<pre><code>from robobrowser import RoboBrowser
browser = RoboBrowser(parser = "html5lib")
login_url = 'someUrl/login.php'
browser.open(login_url)
form = browser.get_form(id='form1')
form['Username'].value = "User"
form['Password'].value = "1234"
browser.submit_form(form)
</code></pre>
<p>I see here the form is submitted successfully.How can i know the login is successful,as it does not returns any response code as successful like in requests.get <code><Response 200></code>but in this case it doesn't return anything.so,how can i know the login is successful or not.</p>
| 0 | 2016-07-30T17:46:16Z | 38,677,236 | <pre><code>p = browser.parsed()
f = open("file.txt","w+",encoding = 'UTF-8')
f.write(str(p))
f.flush()
f.close()
</code></pre>
<p>you can find the username or some data which is visible only after login to confirm the login</p>
| 1 | 2016-07-30T18:31:09Z | [
"python",
"python-3.x",
"beautifulsoup",
"python-requests",
"robobrowser"
] |
how to know whether login is successfull or not? | 38,676,799 | <p>I am using roboBrowser to login into a website and this the code</p>
<pre><code>from robobrowser import RoboBrowser
browser = RoboBrowser(parser = "html5lib")
login_url = 'someUrl/login.php'
browser.open(login_url)
form = browser.get_form(id='form1')
form['Username'].value = "User"
form['Password'].value = "1234"
browser.submit_form(form)
</code></pre>
<p>I see here the form is submitted successfully.How can i know the login is successful,as it does not returns any response code as successful like in requests.get <code><Response 200></code>but in this case it doesn't return anything.so,how can i know the login is successful or not.</p>
| 0 | 2016-07-30T17:46:16Z | 38,678,700 | <p>As the website returns nothing could you use some like <a href="https://www.crummy.com/software/BeautifulSoup/" rel="nofollow">BeautifulSoup</a> to parse the HTML and find something in the site which confirms you are logged in?</p>
| -1 | 2016-07-30T21:34:04Z | [
"python",
"python-3.x",
"beautifulsoup",
"python-requests",
"robobrowser"
] |
how to keep a subprocess running and keep supplying output to it in python? | 38,676,839 | <p>I am not able to keep alive a tunnel created by subprocess to fire multiple commands.
<br>first i tried this to execute a subprocess</p>
<pre><code>command=['gdb']
process=subprocess.Popen(command,stdout=subprocess.PIPE,stdin=subprocess.PIPE)
(out,err)=process.communicate("""file demo
b main
r
""")
print out
</code></pre>
<p>then i tried this</p>
<pre><code>command=['gdb']
process=subprocess.Popen(command,stdout=subprocess.PIPE,stdin=subprocess.PIPE)
process.stdin.write("b main")
process.stdin.write("r")
print repr(process.stdout.readlines())
process.stdin.write("n")
print repr(process.stdout.readlines())
process.stdin.write("n")
print repr(process.stdout.readlines())
process.stdin.write("n")
print repr(process.stdout.readlines())
process.stdin.close()
</code></pre>
<p>in first case it executes the commands and then exits the gdb making it impossible to keep suplying commands to gdb and in second case it does not execute after <code>b main</code> command (i.e. gdb exits).<br>
so how can i keep on giving more commands to gdb from the program as i require. and how to get output of the gdb after execution of each command.<br> command to be given to gdb are not known at the start they can only be entered by user of the python program so passing long strings in
<code>process.communicate</code>
will not help</p>
| 1 | 2016-07-30T17:50:51Z | 38,676,962 | <p>I would use something along the lines of</p>
<pre><code>with Popen(command, stdin=PIPE, stdout=PIPE) as proc:
for line in proc.stdout:
proc.stdin.write("b main")
</code></pre>
<p>This will allow you to write lines to the process, while reading lines from the process.</p>
| 0 | 2016-07-30T18:03:15Z | [
"python",
"linux",
"ubuntu",
"gdb"
] |
how to keep a subprocess running and keep supplying output to it in python? | 38,676,839 | <p>I am not able to keep alive a tunnel created by subprocess to fire multiple commands.
<br>first i tried this to execute a subprocess</p>
<pre><code>command=['gdb']
process=subprocess.Popen(command,stdout=subprocess.PIPE,stdin=subprocess.PIPE)
(out,err)=process.communicate("""file demo
b main
r
""")
print out
</code></pre>
<p>then i tried this</p>
<pre><code>command=['gdb']
process=subprocess.Popen(command,stdout=subprocess.PIPE,stdin=subprocess.PIPE)
process.stdin.write("b main")
process.stdin.write("r")
print repr(process.stdout.readlines())
process.stdin.write("n")
print repr(process.stdout.readlines())
process.stdin.write("n")
print repr(process.stdout.readlines())
process.stdin.write("n")
print repr(process.stdout.readlines())
process.stdin.close()
</code></pre>
<p>in first case it executes the commands and then exits the gdb making it impossible to keep suplying commands to gdb and in second case it does not execute after <code>b main</code> command (i.e. gdb exits).<br>
so how can i keep on giving more commands to gdb from the program as i require. and how to get output of the gdb after execution of each command.<br> command to be given to gdb are not known at the start they can only be entered by user of the python program so passing long strings in
<code>process.communicate</code>
will not help</p>
| 1 | 2016-07-30T17:50:51Z | 38,865,633 | <p>As noticed, <code>communicate()</code> and <code>readlines()</code> are not fit for the task because they don't return before gdb's output has ended, i. e. gdb exited. We want to read gdb's output until it waits for input; one way to do this is to read until gdb's prompt appears - see below function <code>get_output()</code>:</p>
<pre><code>from subprocess import Popen, PIPE, STDOUT
from os import read
command = ['gdb', 'demo']
process = Popen(command, stdin=PIPE, stdout=PIPE, stderr=STDOUT)
def get_output():
output = ""
while not output.endswith("\n(gdb) "): # read output till prompt
buffer = read(process.stdout.fileno(), 4096)
if (not buffer): break # or till EOF (gdb exited)
output += buffer
return output
print get_output()
process.stdin.write("b main\n") # don't forget the "\n"!
print get_output()
process.stdin.write("r\n") # don't forget the "\n"!
print get_output()
process.stdin.write("n\n") # don't forget the "\n"!
print get_output()
process.stdin.write("n\n") # don't forget the "\n"!
print get_output()
process.stdin.write("n\n") # don't forget the "\n"!
print get_output()
process.stdin.close()
print get_output()
</code></pre>
| 1 | 2016-08-10T06:18:49Z | [
"python",
"linux",
"ubuntu",
"gdb"
] |
Allow_Other with fusepy? | 38,676,937 | <p>I have a 16.04 ubuntu server with <a href="https://github.com/sondree/b2_fuse/issues" rel="nofollow">b2_fuse</a> mounting my b2 cloud storage bucket which uses pyfuse. The problem is, I have no idea how I can pass the allow_other argument like with FUSE! This is an issue because other services running under different users cannot see the mounted drive.</p>
<p>Does anybody here have some experience with this that could point me in the right direction?</p>
| 0 | 2016-07-30T18:01:01Z | 39,031,709 | <p>inside of file <code>b2fuse.py</code>
if you change this line <code>FUSE(filesystem, mountpoint, nothreads=True, foreground=True)</code>
to
<code>FUSE(filesystem, mountpoint, nothreads=True, foreground=True,**{'allow_other': True})</code> the volume will be mounted with allow_other</p>
| 1 | 2016-08-19T05:30:43Z | [
"python",
"fuse"
] |
Nested list comprehension against .NET Arrays within Arrays | 38,676,956 | <p>I have a .NET structure that has arrays with arrays in it. I want to crete a list of members of items from a specific array in a specific array using list comprehension in IronPython, if possible.</p>
<p>Here is what I am doing now:</p>
<pre><code>tag_results = [item_result for item_result in results.ItemResults if item_result.ItemId == tag_id][0]
tag_vqts = [vqt for vqt in tag_results.VQTs]
tag_timestamps = [vqt.TimeStamp for vqt in tag_vqts]
</code></pre>
<p>So, get the single item result from the results array which matches my condition, then get the vqts arrays from those item results, THEN get all the timestamp members for each VQT in the vqts array.</p>
<p>Is wanting to do this in a single statement overkill? Later on, the timestamps are used in this manner:</p>
<pre><code>vqts_to_write = [vqt for vqt in resampled_vqts if not vqt.TimeStamp in tag_timestamps]
</code></pre>
<p>I am not sure if a generator would be appropriate, since I am not really looping through them, I just want a list of all the timestamps for all the item results for this item/tag so that I can test membership in the list.</p>
<p>I have to do this multiple times for different contexts in my script, so I was just wondering if I am doing this in an efficient and pythonic manner. I am refactoring this into a method, which got me thinking about making it easier.</p>
<p>FYI, this is IronPython 2.6, embedded in a fixed environment that does not allow the use of numpy, pandas, etc. It is safe to assume I need a python 2.6 only solution.</p>
<p>My main question is:</p>
<p>Would collapsing this into a single line, if possible, obfuscate the code?</p>
<p>If collapsing is appropriate, would a method be overkill?</p>
<p>Two! My two main questions are:</p>
<p>Would collapsing this into a single line, if possible, obfuscate the code?</p>
<p>If collapsing is appropriate, would a method be overkill?</p>
<p>Is a generator appropriate for testing membership in a list?</p>
<p>Three! My three questions are... Amongst my questions are such diverse queries as...I'll come in again...</p>
<p>(it IS python...)</p>
| 1 | 2016-07-30T18:02:47Z | 38,677,000 | <p><code>tag_results = [...][0]</code> builds a <em>whole new list</em> just to get one item. This is what <code>next()</code> on a generator expression is for:</p>
<pre><code>next(item_result for item_result in results.ItemResults if item_result.ItemId == tag_id)
</code></pre>
<p>which only iterates just enough to get a first item.</p>
<p>You <em>can</em> inline that, but I'd keep that as a separate expression for readability.</p>
<p>The remainder is easily put into one expression:</p>
<pre><code>tag_results = next(item_result for item_result in results.ItemResults
if item_result.ItemId == tag_id)
tag_timestamps = [vqt.TimeStamp for vqt in tag_results.VQTs]
</code></pre>
<p>I'd make that a <em>set</em> if you only need to do membership testing:</p>
<pre><code>tag_timestamps = set(vqt.TimeStamp for vqt in tag_results.VQTs)
</code></pre>
<p>Sets allow for constant time membership tests; testing against a list takes linear time as the whole list could end up being scanned for each such test.</p>
| 1 | 2016-07-30T18:07:14Z | [
"python",
"ironpython"
] |
Python: How to split a string column in a dataframe? | 38,676,968 | <p>I have a dataframe with two columns one is <code>Date</code> and the other one is <code>Location(Object)</code> datatype, below is the format of Location columns with values :</p>
<pre><code> Date Location
1 07/12/1912 AtlantiCity, New Jersey
2 08/06/1913 Victoria, British Columbia, Canada
3 09/09/1913 Over the North Sea
4 10/17/1913 Near Johannisthal, Germany
5 03/05/1915 Tienen, Belgium
6 09/03/1915 Off Cuxhaven, Germany
7 07/28/1916 Near Jambol, Bulgeria
8 09/24/1916 Billericay, England
9 10/01/1916 Potters Bar, England
10 11/21/1916 Mainz, Germany
</code></pre>
<p>my requirement is to split the Location by <code>","</code> separator and keep only the second part of it <code>(ex. New Jersey, Canada, Germany, England etc..)</code> in the Location column. I also have to check if its only a single element (values with single element having no ",")</p>
<p>Is there a way I can do it with predefined method without looping each and every row ?</p>
<p>Sorry if the question is off the standard as I am new to Python and still learning.</p>
| 2 | 2016-07-30T18:04:47Z | 38,677,071 | <p>A straight forward way is to <code>apply</code> the <code>split</code> method to each element of the column and pick up the last one:</p>
<pre><code>df.Location.apply(lambda x: x.split(",")[-1])
1 New Jersey
2 Canada
3 Over the North Sea
4 Germany
5 Belgium
6 Germany
7 Bulgeria
8 England
9 England
10 Germany
Name: Location, dtype: object
</code></pre>
<p>To check if each cell has only one element we can use <code>str.contains</code> method on the column:</p>
<pre><code>df.Location.str.contains(",")
1 True
2 True
3 False
4 True
5 True
6 True
7 True
8 True
9 True
10 True
Name: Location, dtype: bool
</code></pre>
| 2 | 2016-07-30T18:14:40Z | [
"python",
"python-3.x",
"pandas"
] |
Python: How to split a string column in a dataframe? | 38,676,968 | <p>I have a dataframe with two columns one is <code>Date</code> and the other one is <code>Location(Object)</code> datatype, below is the format of Location columns with values :</p>
<pre><code> Date Location
1 07/12/1912 AtlantiCity, New Jersey
2 08/06/1913 Victoria, British Columbia, Canada
3 09/09/1913 Over the North Sea
4 10/17/1913 Near Johannisthal, Germany
5 03/05/1915 Tienen, Belgium
6 09/03/1915 Off Cuxhaven, Germany
7 07/28/1916 Near Jambol, Bulgeria
8 09/24/1916 Billericay, England
9 10/01/1916 Potters Bar, England
10 11/21/1916 Mainz, Germany
</code></pre>
<p>my requirement is to split the Location by <code>","</code> separator and keep only the second part of it <code>(ex. New Jersey, Canada, Germany, England etc..)</code> in the Location column. I also have to check if its only a single element (values with single element having no ",")</p>
<p>Is there a way I can do it with predefined method without looping each and every row ?</p>
<p>Sorry if the question is off the standard as I am new to Python and still learning.</p>
| 2 | 2016-07-30T18:04:47Z | 38,677,460 | <p>We could try with <code>str.extract</code></p>
<pre><code>print(df['Location'].str.extract(r'([^,]+$)'))
#0 New Jersey
#1 Canada
#2 Over the North Sea
#3 Germany
#4 Belgium
#5 Germany
#6 Bulgeria
#7 England
#8 England
#9 Germany
</code></pre>
| 1 | 2016-07-30T18:54:07Z | [
"python",
"python-3.x",
"pandas"
] |
python printing dictionary to csv gives blank file | 38,676,978 | <p>I am using the following code as a representation of a larger dictionary which needs to be printed to a csv file:</p>
<pre><code>import csv
dict1 = {"hello": 1}
w = csv.writer(open("C:\output.csv", "w"))
for key, val in dict1.items():
w.writerow([key, val])
</code></pre>
<p>But the <code>output.csv</code> is blank. What am I missing? </p>
| 0 | 2016-07-30T18:05:26Z | 38,677,045 | <p>Files you open need to be closed. Inside a <code>with</code> block, that happens automatically, for example:</p>
<pre><code>import csv
dict1 = {"hello": "world"}
with open("C:\output.csv", "w") as fd:
w = csv.writer(fd)
for key, val in dict1.items():
w.writerow([key, val])
</code></pre>
| 1 | 2016-07-30T18:11:44Z | [
"python",
"csv",
"dictionary"
] |
working with NaN in a dataframe with if condition | 38,677,017 | <p>I have 2 columns in a dataframe and I am trying to enter into a condition based on if the second one is NaN and First one has some values, unsuccessfully using:</p>
<pre><code>if np.isfinite(train_bk['Product_Category_1']) and np.isnan(train_bk['Product_Category_2'])
</code></pre>
<p>and </p>
<pre><code> if not (train_bk['Product_Category_2']).isnull() and (train_bk['Product_Category_3']).isnull()
</code></pre>
| 1 | 2016-07-30T18:09:17Z | 38,682,987 | <p>I would use eval:</p>
<pre><code>df.eval(' ind = ((pc1==pc1) & (pc2!=pc2) )*2+((pc1==pc1)&(pc2==pc2))*3')
df.replace({'ind':{0:1})
</code></pre>
| 0 | 2016-07-31T10:23:36Z | [
"python",
"numpy",
"pandas"
] |
Can not upload file/image in flaskapp | 38,677,022 | <p>I have created a form in html/php, and using flask for backend. </p>
<p>Everything is working perfect except when I am trying to upload image I am always seeing the error: </p>
<pre><code>error is**"UnboundLocalError: local variable 'filename' referenced before assignment"**
</code></pre>
<p>my flaskapp code snippet is</p>
<pre><code>@app.route('/apple', methods=['GET', 'POST'])
def apple():
onlineAppForm = RegForm()
if request.method == 'POST':
try:
file = request.files['file']
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
except Exception as e:
print "Form without file "+str(e)
return render_template("apply2.html", data=data, filename=filename, form=onlineAppForm)
</code></pre>
<p>this is my upload folder</p>
<pre><code>UPLOAD_FOLDER = 'static/uploads'
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.secret_key = os.urandom(24)
</code></pre>
<p>I am not getting where the error is.</p>
<pre><code>def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
</code></pre>
<p>this is my form</p>
<pre><code><tr>
<td class="sectionheading">Upload Scanned Copies</td>
</tr>
<tr>
<td height="12">&nbsp;</td>
</tr>
<tr id="photosignthumb_span" height="40">
<td align="left" valign="middle" width="100%">&nbsp;<b>
<span class="mandatory">*</span>
Please upload scanned copies of your photo </b>
<input type="file" name="photo" id="photofile"
method="post"/><br>
Please upload your recent passport size photograph:max
80KB(Only JPEG and JPG formats)
</td>
</tr>
<tr id="photosignthumb_span" height="40">
<td align="left" valign="middle" width="100%">&nbsp;<b>
<span class="mandatory">*</span>
Please upload scanned copies of your signature </b>
<input type="file" name="sign" id="signfile"
method="post"/><br>
Please upload your recent passport size photograph:max
80KB(Only JPEG and JPG formats)
</td>
</tr>
</code></pre>
| 0 | 2016-07-30T18:09:47Z | 38,677,208 | <p><code>filename</code> existence depends on couple of conditions:</p>
<p>1 - <code>file = request.files['file']</code> <br>
2 - <code>if file and allowed_file(file.filename):</code> <br>
3 - No <em>exception</em> is raised.</p>
<p>So, if any of the above didn't happen, then <code>filename</code> won't spring into existence and hence your error message.</p>
<p>EDIT:</p>
<p>Quoting from <code>flask</code> <a href="http://flask.pocoo.org/docs/0.11/patterns/fileuploads/#uploading-files" rel="nofollow">docs</a> on file upload:</p>
<blockquote>
<ol>
<li>A tag is marked with enctype=multipart/form-data and an is placed in that form. </li>
<li>The application accesses the file from the files dictionary on the request object. </li>
<li>Use the save() method of the file to save the file permanently somewhere on the filesystem.</li>
</ol>
</blockquote>
<p>Looking at the form your provided it seems you don't have any <code>form</code> block, you should have something like:</p>
<pre><code><form action="/apple" method="post" enctype="multipart/form-data">
<tr>
<td class="sectionheading">Upload Scanned Copies</td>
</tr>
<tr>
<td height="12">&nbsp;</td>
</tr>
<tr id="photosignthumb_span" height="40">
<td align="left" valign="middle" width="100%">&nbsp;<b>
<span class="mandatory">*</span>
Please upload scanned copies of your photo </b>
<input type="file" name="photo" id="photofile"
method="post"/><br>
Please upload your recent passport size photograph:max
80KB(Only JPEG and JPG formats)
</td>
</tr>
<tr id="photosignthumb_span" height="40">
<td align="left" valign="middle" width="100%">&nbsp;<b>
<span class="mandatory">*</span>
Please upload scanned copies of your signature </b>
<input type="file" name="sign" id="signfile"
method="post"/><br>
Please upload your recent passport size photograph:max
80KB(Only JPEG and JPG formats)
</td>
</tr>
</form>
</code></pre>
| 0 | 2016-07-30T18:29:13Z | [
"python",
"flask",
"flask-wtforms",
"flask-appbuilder"
] |
OS.rename() not working with tkinter | 38,677,028 | <p>Folks I'm trying to make a tool which gets user path and file name in one entry and new file name with path in another entry, My aim is to use <code>os.rename(oldname, newname)</code> to rename the given file, but its throwing me some error.</p>
<p>My code</p>
<pre><code>from tkinter import *
import os
def Rename_Function(*args):
os.rename(oldname2,newname)
oldname.set(oldname)#"Renamed Successfully !!! ")
root = Tk()
root.title("MyPython App")
root.geometry("250x250+100+50")
oldname = StringVar()
oldname2= StringVar()
newname= StringVar()
Title1 = Label(root,text="FileName (with path):")
Title1.grid(row=0, column=0)
Oldfilename = Entry(root, textvariable=oldname2)
Oldfilename.grid(row=0, column=1)
Title2 = Label(root, text="New Filename:")
Title2.grid(row=1, column=0)
Newfilename = Entry(root, textvariable=newname)
Newfilename.grid(row=1, column=1)
RenameButton = Button(root, text="RENAME MY FILE", command=Rename_Function)
RenameButton.grid(row=3,columnspan=2, sticky="NWES")
FinalOutput = Label(textvariable=oldname)
FinalOutput.grid(row=4, columnspan=2, sticky = "NWES")
root.mainloop()
</code></pre>
<p><a href="http://i.stack.imgur.com/tVO5b.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/tVO5b.jpg" alt="This is how the tool looks"></a></p>
<p><a href="http://i.stack.imgur.com/YUSZW.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/YUSZW.jpg" alt="enter image description here"></a></p>
<p>I'm getting the above error when I click the button,
Can someone guide me how to make it work.</p>
<p>I have a doubt that <code>os.rename()</code> function should be accessed in some other way since its another module's function. Since I'm learner I don't have any clue how to use them effeciently. Please guide me and explain me so that I would understand this concept better.</p>
| 0 | 2016-07-30T18:10:17Z | 38,677,331 | <p>To expand upon what @SuperSaiyan said in the comment(s).</p>
<p>You are using a <code>StringVar</code>, which has the method <code>.get()</code> available to it. When you pass the variable which is set to this stringvar you are just passing the reference to this object. You need to actually use the <code>.get()</code> method to get the string. </p>
<p>e.g. - <code>oldname2.get()</code></p>
<p>Also, for selecting the path you could just use a filedialog, and use <code>os.path.splitext</code> to get the base path + entry in the renaming widget to use as the second parameter with <code>os.rename</code></p>
| 2 | 2016-07-30T18:39:56Z | [
"python",
"function",
"tkinter",
"module"
] |
OS.rename() not working with tkinter | 38,677,028 | <p>Folks I'm trying to make a tool which gets user path and file name in one entry and new file name with path in another entry, My aim is to use <code>os.rename(oldname, newname)</code> to rename the given file, but its throwing me some error.</p>
<p>My code</p>
<pre><code>from tkinter import *
import os
def Rename_Function(*args):
os.rename(oldname2,newname)
oldname.set(oldname)#"Renamed Successfully !!! ")
root = Tk()
root.title("MyPython App")
root.geometry("250x250+100+50")
oldname = StringVar()
oldname2= StringVar()
newname= StringVar()
Title1 = Label(root,text="FileName (with path):")
Title1.grid(row=0, column=0)
Oldfilename = Entry(root, textvariable=oldname2)
Oldfilename.grid(row=0, column=1)
Title2 = Label(root, text="New Filename:")
Title2.grid(row=1, column=0)
Newfilename = Entry(root, textvariable=newname)
Newfilename.grid(row=1, column=1)
RenameButton = Button(root, text="RENAME MY FILE", command=Rename_Function)
RenameButton.grid(row=3,columnspan=2, sticky="NWES")
FinalOutput = Label(textvariable=oldname)
FinalOutput.grid(row=4, columnspan=2, sticky = "NWES")
root.mainloop()
</code></pre>
<p><a href="http://i.stack.imgur.com/tVO5b.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/tVO5b.jpg" alt="This is how the tool looks"></a></p>
<p><a href="http://i.stack.imgur.com/YUSZW.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/YUSZW.jpg" alt="enter image description here"></a></p>
<p>I'm getting the above error when I click the button,
Can someone guide me how to make it work.</p>
<p>I have a doubt that <code>os.rename()</code> function should be accessed in some other way since its another module's function. Since I'm learner I don't have any clue how to use them effeciently. Please guide me and explain me so that I would understand this concept better.</p>
| 0 | 2016-07-30T18:10:17Z | 38,677,488 | <p>You are using <code>StringVar</code>, whereas <code>rename</code> needs Strings. Use <code>oldname.get()</code>:</p>
<pre><code>import tkinter as tk
import os
def rename(oldname, oldname2, newname):
os.rename(oldname2.get(),newname.get())
oldname.set("Renamed Successfully !!! ")
def main():
root = tk.Tk()
root.title("MyPython App")
root.geometry("250x250+100+50")
oldname = tk.StringVar()
oldname2= tk.StringVar()
newname= tk.StringVar()
tk.Label(root, text="FileName (with path):").grid(row=0, column=0)
tk.Entry(root, textvariable=oldname2).grid(row=0, column=1)
tk.Label(root, text="New Filename:").grid(row=1, column=0)
tk.Entry(root, textvariable=newname).grid(row=1, column=1)
tk.Button(root, text="RENAME MY FILE", command=lambda: rename(oldname, oldname2, newname)).grid(row=3,columnspan=2, sticky="NWES")
tk.Label(textvariable=oldname).grid(row=4, columnspan=2, sticky = "NWES")
root.mainloop()
if __name__ == '__main__':
main()
</code></pre>
| 1 | 2016-07-30T18:57:09Z | [
"python",
"function",
"tkinter",
"module"
] |
Checking data in a file for duplicates (Python) | 38,677,037 | <p>I am trying to make a list of topics for another project to use and I am storing the topics in <code>Topics.txt</code>. However, when the topics are stored in the file, I do not want duplicate topics. So when I am saving my topics to my <code>Topics.txt</code> file, I also save them to a <code>Duplicates.txt</code> file. What I want to do is create a conditional statement that won't add topics to <code>Topics.txt</code> if the topics are in the <code>Duplicates.txt</code>. My problem is, I don't know how I could create a conditional statement that could check if the topic is listed in <code>Duplicates.txt</code>. A problem may arise if you scan for keywords such as "music", seeing that "electro-music" contains the word "music". </p>
<pre><code>Entry = input("Enter topic: ")
Topic = Entry + "\n"
Readfilename = "Duplicates.txt"
Readfile = open(Readfilename, "r")
Readdata = Readfile.read()
Readfile.close()
if Topic not in Duplicates:
Filename = "Topics.txt"
File = open(Filename, "a")
File.append(Topic)
File.close()
Duplicate = Topic + "\n"
Readfile = open(Readfilename, "a")
Readfile.append(Topic)
Readfile.close()
</code></pre>
| 1 | 2016-07-30T18:10:39Z | 38,677,187 | <p>You can store your topics in a set. A set is collection of unique items.</p>
<pre><code>topics = {'Banjo', 'Guitar', 'Piano'}
</code></pre>
<p>You can check for membership using:</p>
<pre><code>>>> 'Banjo' in topics
True
</code></pre>
<p>You add new things to a set via <code>.add()</code></p>
<pre><code>topics.add('Iceskating')
>>> topics
set(['Banjo','Guitar', 'Piano', 'Iceskating'])
</code></pre>
<p>Python 3 Docs on sets <a href="https://docs.python.org/3/library/stdtypes.html#set" rel="nofollow">here</a>. The tutorial page on sets is <a href="https://docs.python.org/3/tutorial/datastructures.html#sets" rel="nofollow">here</a>.</p>
| 0 | 2016-07-30T18:27:06Z | [
"python",
"python-3.x",
"duplicates",
"keyword-search"
] |
Checking data in a file for duplicates (Python) | 38,677,037 | <p>I am trying to make a list of topics for another project to use and I am storing the topics in <code>Topics.txt</code>. However, when the topics are stored in the file, I do not want duplicate topics. So when I am saving my topics to my <code>Topics.txt</code> file, I also save them to a <code>Duplicates.txt</code> file. What I want to do is create a conditional statement that won't add topics to <code>Topics.txt</code> if the topics are in the <code>Duplicates.txt</code>. My problem is, I don't know how I could create a conditional statement that could check if the topic is listed in <code>Duplicates.txt</code>. A problem may arise if you scan for keywords such as "music", seeing that "electro-music" contains the word "music". </p>
<pre><code>Entry = input("Enter topic: ")
Topic = Entry + "\n"
Readfilename = "Duplicates.txt"
Readfile = open(Readfilename, "r")
Readdata = Readfile.read()
Readfile.close()
if Topic not in Duplicates:
Filename = "Topics.txt"
File = open(Filename, "a")
File.append(Topic)
File.close()
Duplicate = Topic + "\n"
Readfile = open(Readfilename, "a")
Readfile.append(Topic)
Readfile.close()
</code></pre>
| 1 | 2016-07-30T18:10:39Z | 38,677,227 | <p>You can read a file line by line which would result in a solution like this one</p>
<pre><code>Entry = input("Enter topic: ")
Topic = Entry + "\n"
Readfilename = "Duplicates.txt"
found=False
with open(Readfilename, "r") as Readfile:
for line in Readfile:
if Topic==line:
found=True
break # no need to read more of the file
if not found:
Filename = "Topics.txt"
with open(Filename, "a") as File:
File.write(Topic)
with open(Readfilename, "a") as Readfile:
Readfile.write(Topic)
</code></pre>
| 1 | 2016-07-30T18:30:31Z | [
"python",
"python-3.x",
"duplicates",
"keyword-search"
] |
Python - use AND or OR in this code? | 38,677,089 | <p>I'm writing a simple code to get some easy practice in Python, just to find the maximum out of three numbers, without using the max function.</p>
<p>I wrote this:</p>
<pre><code>num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
num3 = int(input("Enter the third number: "))
def max_of_three(num1,num2,num3):
if num1>num2 and num1>num3:
return num1
elif num2>num1 and num2>num3:
return num2
elif num3>num1 and num3>num2:
return num3
print (max_of_three(5,7,2))
</code></pre>
<p>For this specific piece of code, is there a difference between using AND and OR when comparing two numbers? Obviously in other code there's an important difference, but does it matter in getting the result here?</p>
<p>Also I know there's easier ways to write this, but I'm just trying to get back into writing Python.</p>
<p>Replies are appreciated.</p>
| -3 | 2016-07-30T18:16:37Z | 38,677,132 | <p>Yes, there is a difference. Basically, if you replace <code>and</code> by <code>or</code>, your code no longer works correctly.</p>
<p>The problem is that in each <code>if</code> statement, you need both conditions fulfilled to ensure that the value you want to return is larger than any of the others.</p>
<p>Note that you still have a bug in your code: What happens if all three parameters are equal? You need to either change <code>></code> to <code>>=</code> or else just return <code>num3</code> in the end, instead of checking if num3 is strictly larger than both other parameters.</p>
| 0 | 2016-07-30T18:21:21Z | [
"python"
] |
Python - use AND or OR in this code? | 38,677,089 | <p>I'm writing a simple code to get some easy practice in Python, just to find the maximum out of three numbers, without using the max function.</p>
<p>I wrote this:</p>
<pre><code>num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
num3 = int(input("Enter the third number: "))
def max_of_three(num1,num2,num3):
if num1>num2 and num1>num3:
return num1
elif num2>num1 and num2>num3:
return num2
elif num3>num1 and num3>num2:
return num3
print (max_of_three(5,7,2))
</code></pre>
<p>For this specific piece of code, is there a difference between using AND and OR when comparing two numbers? Obviously in other code there's an important difference, but does it matter in getting the result here?</p>
<p>Also I know there's easier ways to write this, but I'm just trying to get back into writing Python.</p>
<p>Replies are appreciated.</p>
| -3 | 2016-07-30T18:16:37Z | 38,677,199 | <p>Yes there is a difference. Say you used</p>
<pre><code>if num1>num2 or num1>num3:
return num1
</code></pre>
<p>and say we tried <code>print (max_of_three(2,1,3))</code> it would return 2, because when it tries <code>num1>num2 or num1>num3</code> which evaluates to <code>True or False</code> which evaluates to <code>True</code> therefore returning num2 instead of num3. if we try with and</p>
<pre><code>if num1>num2 and num1>num3:
return num1
</code></pre>
<p>and tried <code>print (max_of_three(2,1,3))</code> it would return 3 because <code>num1>num2 and num1>num3</code> evaluates to <code>True and False</code> which evaluates to <code>False</code>. <code>num2>num1 and num2>num3</code> also evaluates to <code>False</code> so we move on. <code>num3>num1 and num3>num2</code> turns into <code>True</code> so we return num3. (side note: this code will not always return a number if two numbers are the same, for instance <code>print (max_of_three(3,3,2))</code> doesn't return anything.) </p>
| 0 | 2016-07-30T18:28:24Z | [
"python"
] |
Python - use AND or OR in this code? | 38,677,089 | <p>I'm writing a simple code to get some easy practice in Python, just to find the maximum out of three numbers, without using the max function.</p>
<p>I wrote this:</p>
<pre><code>num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
num3 = int(input("Enter the third number: "))
def max_of_three(num1,num2,num3):
if num1>num2 and num1>num3:
return num1
elif num2>num1 and num2>num3:
return num2
elif num3>num1 and num3>num2:
return num3
print (max_of_three(5,7,2))
</code></pre>
<p>For this specific piece of code, is there a difference between using AND and OR when comparing two numbers? Obviously in other code there's an important difference, but does it matter in getting the result here?</p>
<p>Also I know there's easier ways to write this, but I'm just trying to get back into writing Python.</p>
<p>Replies are appreciated.</p>
| -3 | 2016-07-30T18:16:37Z | 38,677,362 | <p>First, you need to alter the operators to make them greater than or equal to <code>>=</code> because some numbers may be the same.</p>
<p>Yes there would be a difference if you used <code>or</code> instead of <code>and</code> because of short-circuiting.</p>
<p>When using <code>and</code> to return a boolean value, <em>both</em> expressions need to be true for the entire condition to return <code>True</code>. If the first expression returns false, then then python will "short-circuit" and automatically return <code>False</code>, without even checking the second expression. </p>
<p>On the other hand, when using <code>or</code>, only <em>one</em> of the expressions has to be true for the condition to return <code>True</code>. So when python checks the first expression, if it is true, then the whole condition will short-circuit and return <code>True</code>, without even checking the second expression. </p>
<p>so if you replaced <code>and</code> with <code>or</code> in your first if statement you could have a condition where num1 is greater than num2 but less than num3. Yet this would still return num1 as the max.</p>
<p>Hope this helps.</p>
| 2 | 2016-07-30T18:42:29Z | [
"python"
] |
Python - use AND or OR in this code? | 38,677,089 | <p>I'm writing a simple code to get some easy practice in Python, just to find the maximum out of three numbers, without using the max function.</p>
<p>I wrote this:</p>
<pre><code>num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
num3 = int(input("Enter the third number: "))
def max_of_three(num1,num2,num3):
if num1>num2 and num1>num3:
return num1
elif num2>num1 and num2>num3:
return num2
elif num3>num1 and num3>num2:
return num3
print (max_of_three(5,7,2))
</code></pre>
<p>For this specific piece of code, is there a difference between using AND and OR when comparing two numbers? Obviously in other code there's an important difference, but does it matter in getting the result here?</p>
<p>Also I know there's easier ways to write this, but I'm just trying to get back into writing Python.</p>
<p>Replies are appreciated.</p>
| -3 | 2016-07-30T18:16:37Z | 38,677,452 | <p>Yes there is a difference. The statement <strong>and</strong> requires both the conditions to be true. <strong>Or</strong> would only require one of them to be true. Lets take an example:</p>
<ol>
<li>Num 1 = 1</li>
<li>Num 2 = 2</li>
<li>Num 3 = 3</li>
</ol>
<p>Your code, using or, would:</p>
<p>Disregard the first if statement because 1 is not greater than 2 <strong>or</strong> greater than 3.</p>
<p>Accept the second if statement. 2 is greater than one, and the or condition tells the computer that 2 can be greater than 1 or 3 for the statement to be valid. It is greater than 1 so the statement is valid.</p>
<p>Python would then accept this - and not test the last condition because this one has been found true first. 2 would be the output - despite num 3 being bigger than num 2. Here is the some pseudocode with the values substituted in:</p>
<pre><code>num1 = 1
num2 = 2
num3 = 3
IS: num1 > num 2 or num3?
False
IS: num2 > num1 or num3?
True. num2 > num1
</code></pre>
| 1 | 2016-07-30T18:52:41Z | [
"python"
] |
Python - use AND or OR in this code? | 38,677,089 | <p>I'm writing a simple code to get some easy practice in Python, just to find the maximum out of three numbers, without using the max function.</p>
<p>I wrote this:</p>
<pre><code>num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
num3 = int(input("Enter the third number: "))
def max_of_three(num1,num2,num3):
if num1>num2 and num1>num3:
return num1
elif num2>num1 and num2>num3:
return num2
elif num3>num1 and num3>num2:
return num3
print (max_of_three(5,7,2))
</code></pre>
<p>For this specific piece of code, is there a difference between using AND and OR when comparing two numbers? Obviously in other code there's an important difference, but does it matter in getting the result here?</p>
<p>Also I know there's easier ways to write this, but I'm just trying to get back into writing Python.</p>
<p>Replies are appreciated.</p>
| -3 | 2016-07-30T18:16:37Z | 38,677,476 | <p>We can get rid of the ANDs and ORs altogether, and eliminate the redundant test (once you've decided to neither return num1 nor num2, why test if you should return num3? There's nothing else left!) We end up with something overly Pythonish like:</p>
<pre><code>def max_of_three(num1, num2, num3):
if num2 <= num1 >= num3:
return num1
if num1 <= num2 >= num3:
return num2
return num3
</code></pre>
<p>where the <code>num2 <= num1 >= num3</code> has an implicit AND associated with it which should answer your original question.</p>
<p>To have more fun with computing the maximum sans <code>max()</code>, we can extend to two or more values, not just three, by doing something like:</p>
<pre><code>def max_of_several(num1, num2, *args):
larger = (num1, num2)[num1 < num2]
return max_of_several(larger, *args) if args else larger
</code></pre>
| 2 | 2016-07-30T18:55:56Z | [
"python"
] |
Working efficiently with selected (query()) data from Pandas Dataframe | 38,677,102 | <p>After querying a pandas DataFrame, I want to get the 3 entries before the selected index in my query.</p>
<p>The code below works, but I think it's dirty and not efficient, I can only image there is a better way of doing it with Pandas.</p>
<p>Does someone could help me?</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
import numpy as np
dates = pd.date_range('1/1/2015', periods=50)
df = pd.DataFrame(np.random.randn(50, 4), index=dates, columns=['A', 'B', 'C', 'D'])
x = (df['B'] > df['A']) & \
((df['B'].shift(+1) > df['A'].shift(+1)) == False) & \
(df['B'].shift(+2) > df['A'].shift(+2)) & \
(df['C'] < df['C'].shift(+2)) & \
(df['D'] < df['D'].shift(+1))
for d in df[x].index.values:
idx = df.index.get_loc(d)
print df.iloc[idx - 3:idx]
</code></pre>
<p>Sample Output for the code above:</p>
<pre><code> A B C D
2015-01-02 -0.600371 -1.088227 -1.213046 -0.000058
2015-01-03 -2.373683 -0.455126 -0.852127 0.311744
2015-01-04 0.240301 -1.957885 0.184642 0.690865
A B C D
2015-01-05 -0.833244 -0.787022 -1.490983 -0.540114
2015-01-06 0.569680 1.798457 1.253075 0.835848
2015-01-07 -0.245731 -0.365678 1.452985 2.007146
Process finished with exit code 0
</code></pre>
<p>Another question I have is that if it possible to use "shift" with "Pandas Language" inside the query, instead of using Python.</p>
<p>Thanks for the help!</p>
| 2 | 2016-07-30T18:17:59Z | 38,678,588 | <p>AFAIK, <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#the-query-method-experimental" rel="nofollow">query()</a> method doesn't accept functions and methods, that can be applied on columns - at least i couldn't make it working</p>
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.eval.html" rel="nofollow">eval()</a> method - it will look bit better:</p>
<pre><code>In [168]: %paste
mask = (df.eval('B > A')
& df.shift(1).eval('B <= A')
& df.shift(2).eval('B > A')
& (df.C < df.C.shift(2))
& (df.D < df.D.shift(1)))
df.ix[np.concatenate([np.arange(i-2, i+1) for i in mask.reset_index(name='bool').query('bool').index])]
## -- End pasted text --
Out[168]:
A B C D
2015-01-03 0.027326 1.896523 1.052508 0.279496
2015-01-04 -0.226720 -1.465787 2.459746 0.089118
2015-01-05 0.323047 1.707117 -1.760567 -0.066462
2015-01-31 -1.059314 1.991725 0.819225 -1.212651
2015-02-01 1.372391 0.247049 0.408600 0.908394
2015-02-02 -0.777752 -0.326590 -0.062228 -0.226803
2015-02-16 -0.192333 0.562463 0.126509 -0.342867
2015-02-17 -0.363513 -1.582659 -0.903556 0.973706
2015-02-18 -0.796225 -0.575127 0.078172 -2.182067
</code></pre>
<p>Explanation:</p>
<pre><code>In [162]: mask.reset_index(name='bool').query('bool')
Out[162]:
index bool
4 2015-01-05 True
32 2015-02-02 True
48 2015-02-18 True
In [163]: mask.reset_index(name='bool').query('bool').index
Out[163]: Int64Index([4, 32, 48], dtype='int64')
In [164]: [np.arange(i-2, i+1) for i in mask.reset_index(name='bool').query('bool').index]
Out[164]:
[array([2, 3, 4], dtype=int64),
array([30, 31, 32], dtype=int64),
array([46, 47, 48], dtype=int64)]
In [165]: np.concatenate([np.arange(i-2, i+1) for i in mask.reset_index(name='bool').query('bool').index])
Out[165]: array([ 2, 3, 4, 30, 31, 32, 46, 47, 48], dtype=int64)
</code></pre>
| 0 | 2016-07-30T21:18:21Z | [
"python",
"numpy",
"pandas",
"indexing",
"pandasql"
] |
How to dive into stacked dict gracefully | 38,677,125 | <p>Let's say I have a dict like</p>
<pre><code>{
"key_a": "value",
"key_b": {
"key_b_a": "value",
"key_b_b": {
"key_b_b_a": "value"
}
}
}
</code></pre>
<p>What I want is to create a method to delete the given key or change its value.</p>
<pre><code>def del_key(key):
my_dict = <dictionary described above>
keys = key.split(':')
if len(keys) == 1:
del my_dict[keys[0]]
elif len(keys) == 2:
del my_dict[keys[0]][keys[1]]
elif len(keys) == 3:
del my_dict[keys[0]][keys[1]][keys[2]]
. . .
del_key('key_b:key_b_b:key_b_b_a')
del_key('key_b:key_b_b')
del_key('key_a')
</code></pre>
<p>How can I do this gracefully?</p>
| 2 | 2016-07-30T18:20:51Z | 38,677,271 | <p>It assumes your input is valid key,otherwise you have to check.</p>
<pre><code>data = {
"key_a": "value",
"key_b": {
"key_b_a": "value",
"key_b_b": {
"key_b_b_a": "value"
}
}
}
def del_key(key):
key = key.split(':')
temp = data
for i in key[:-1]:
temp = temp[i]
del temp[key[-1]]
return data
print del_key('key_b:key_b_b:key_b_b_a')
print del_key('key_b:key_b_b')
print del_key('key_a')
output:
{'key_a': 'value', 'key_b': {'key_b_a': 'value', 'key_b_b': {}}}
{'key_a': 'value', 'key_b': {'key_b_a': 'value'}}
{'key_b': {'key_b_a': 'value'}}
</code></pre>
| 4 | 2016-07-30T18:34:07Z | [
"python"
] |
Python: Int is object is not subscriptable | 38,677,130 | <p>I know this is a topic that there are already several threads for. I've reviewed them and understand what this error means, but for some reason cannot get it to work for my code. </p>
<p>I'm trying to code a simple Python function that takes a list of integers as input and outputs the integers in the list that are exactly twice the amount of the previous integer in the list. Here is the code I have so far:</p>
<pre><code> def doubles(lst):
i = -1
for num in lst:
if num == num[i + 1] / 2:
print(num)
</code></pre>
<p>Now I know the issue is that it is trying to print this integer as a string. I have tried editing the codes last line to say print(str(num)) and that does not work, nor does changing my if statement in line 4. Any assistance would be greatly appreciated!</p>
| -1 | 2016-07-30T18:21:19Z | 38,677,143 | <pre><code>if num == num[i + 1] / 2:
</code></pre>
<p>should be</p>
<pre><code>if num == lst[i + 1] / 2:
</code></pre>
<p>Also, I recommend using <a href="http://stackoverflow.com/a/522578/5699206">enumerate</a> to iterate over the list with indexes, but there are better ways of doing such a thing, as shown in <a href="http://stackoverflow.com/questions/38677130/python-int-is-object-is-not-subscriptable/38677177#38677177">galaxyan's answer</a></p>
| 3 | 2016-07-30T18:22:34Z | [
"python"
] |
Python: Int is object is not subscriptable | 38,677,130 | <p>I know this is a topic that there are already several threads for. I've reviewed them and understand what this error means, but for some reason cannot get it to work for my code. </p>
<p>I'm trying to code a simple Python function that takes a list of integers as input and outputs the integers in the list that are exactly twice the amount of the previous integer in the list. Here is the code I have so far:</p>
<pre><code> def doubles(lst):
i = -1
for num in lst:
if num == num[i + 1] / 2:
print(num)
</code></pre>
<p>Now I know the issue is that it is trying to print this integer as a string. I have tried editing the codes last line to say print(str(num)) and that does not work, nor does changing my if statement in line 4. Any assistance would be greatly appreciated!</p>
| -1 | 2016-07-30T18:21:19Z | 38,677,167 | <p>You're attempting to subscript an item in the list, not the list itself. Instead of iterating the items, you could iterate the list's indexes:</p>
<pre><code>def doubles(lst):
for i in range(0, len(lst) - 1):
if lst[i] == lst[i + 1] / 2:
print(lst[i])
</code></pre>
| 0 | 2016-07-30T18:25:04Z | [
"python"
] |
Python: Int is object is not subscriptable | 38,677,130 | <p>I know this is a topic that there are already several threads for. I've reviewed them and understand what this error means, but for some reason cannot get it to work for my code. </p>
<p>I'm trying to code a simple Python function that takes a list of integers as input and outputs the integers in the list that are exactly twice the amount of the previous integer in the list. Here is the code I have so far:</p>
<pre><code> def doubles(lst):
i = -1
for num in lst:
if num == num[i + 1] / 2:
print(num)
</code></pre>
<p>Now I know the issue is that it is trying to print this integer as a string. I have tried editing the codes last line to say print(str(num)) and that does not work, nor does changing my if statement in line 4. Any assistance would be greatly appreciated!</p>
| -1 | 2016-07-30T18:21:19Z | 38,677,177 | <p>you can zip original list and list begin from second element,then compare two elements </p>
<pre><code>def doubles(lst):
return [ i for i,j in zip(lst,lst[1:]) if j==i*2 ]
</code></pre>
<p>example:</p>
<pre><code>lst = [1,2,3,5,66,2,4,5]
print doubles(lst)
[1, 2]
</code></pre>
| 1 | 2016-07-30T18:26:04Z | [
"python"
] |
SSH Python Script Closing Too Early | 38,677,439 | <p>Iâm trying to write a python script to SSH into a box and run a command using the paramiko library. I am still in the learning process when it comes to python but the aim of this exercise is to build upon this program and use it in the work place.
I have been testing the program and so far so good however when the script passes in a command to the Linux box and the command takes awhile to get output, my script doesnât return anything. For example, I tested the script against one of our storage servers. The command I told the script to pass into the server normally returns an output showing the fragmentation of the disk pools. If I was to SSH into one of the storage servers manually and run the command it normally takes 5 seconds for the command to run and output the information. So I get the feeling that my python script is closing the SSH session before the server has fully ran the command.
So my question is whats the best way of telling the script to hold off before closing the session in an attempt to get all the output back from the command? Below is a snippet of the code:</p>
<pre><code>def ssh_command(ip, user, passwd , command):
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(ip, username=user, password=passwd)
ssh_session = client.get_transport().open_session()
if ssh_session.active:
ssh_session.exec_command(command)
print ssh_session.recv(99999)
return
</code></pre>
<p>I tried adjusting</p>
<pre><code>print ssh_session.recv(99999)
</code></pre>
<p>to different values but had no luck. I think Iâm not understanding this function fully. I know its the function thats telling the script to return to the user the output of the terminal command but Iâm not 100% sure what 99999 represents. I thought this was a delay. </p>
<p>Thanks for your help! </p>
| -1 | 2016-07-30T18:51:32Z | 38,677,495 | <pre><code>print ssh_session.recv(99999)
</code></pre>
<p>Tells the program to receive the response up to that limit of characters. So if the length of the server's response was 100,000, then the program would receive only the first 99,999, and not the last character. If the response is less than or equal to 99,999, then the program will print the whole response.</p>
<p>If you want your program to delay before receiving a response, you can use:</p>
<pre><code>import time
# do stuff
time.sleep(5) # delay the program for 5 seconds
print ssh_session.recv(99999)
# do more stuff
</code></pre>
| 0 | 2016-07-30T18:57:46Z | [
"python",
"paramiko"
] |
SSH Python Script Closing Too Early | 38,677,439 | <p>Iâm trying to write a python script to SSH into a box and run a command using the paramiko library. I am still in the learning process when it comes to python but the aim of this exercise is to build upon this program and use it in the work place.
I have been testing the program and so far so good however when the script passes in a command to the Linux box and the command takes awhile to get output, my script doesnât return anything. For example, I tested the script against one of our storage servers. The command I told the script to pass into the server normally returns an output showing the fragmentation of the disk pools. If I was to SSH into one of the storage servers manually and run the command it normally takes 5 seconds for the command to run and output the information. So I get the feeling that my python script is closing the SSH session before the server has fully ran the command.
So my question is whats the best way of telling the script to hold off before closing the session in an attempt to get all the output back from the command? Below is a snippet of the code:</p>
<pre><code>def ssh_command(ip, user, passwd , command):
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(ip, username=user, password=passwd)
ssh_session = client.get_transport().open_session()
if ssh_session.active:
ssh_session.exec_command(command)
print ssh_session.recv(99999)
return
</code></pre>
<p>I tried adjusting</p>
<pre><code>print ssh_session.recv(99999)
</code></pre>
<p>to different values but had no luck. I think Iâm not understanding this function fully. I know its the function thats telling the script to return to the user the output of the terminal command but Iâm not 100% sure what 99999 represents. I thought this was a delay. </p>
<p>Thanks for your help! </p>
| -1 | 2016-07-30T18:51:32Z | 38,677,512 | <p>I'm not entirely familiar with paramiko, but it looks like you are getting some sort of wrapper to the lower level socket object, and doing operations manually, even though the <code>client</code> object you got has functions to take care of this for you. <code>recv</code> looks like the standard <code>Socket</code> call <code>recv</code>, which is how many bytes to read from the socket before returning. </p>
<p>Based on the pydocs I recommend using <code>client.exec_command</code>, which includes an option for a time out. Here is some doc pages which may help:
<a href="http://docs.paramiko.org/en/2.0/api/client.html" rel="nofollow">http://docs.paramiko.org/en/2.0/api/client.html</a></p>
| 0 | 2016-07-30T19:00:20Z | [
"python",
"paramiko"
] |
SSH Python Script Closing Too Early | 38,677,439 | <p>Iâm trying to write a python script to SSH into a box and run a command using the paramiko library. I am still in the learning process when it comes to python but the aim of this exercise is to build upon this program and use it in the work place.
I have been testing the program and so far so good however when the script passes in a command to the Linux box and the command takes awhile to get output, my script doesnât return anything. For example, I tested the script against one of our storage servers. The command I told the script to pass into the server normally returns an output showing the fragmentation of the disk pools. If I was to SSH into one of the storage servers manually and run the command it normally takes 5 seconds for the command to run and output the information. So I get the feeling that my python script is closing the SSH session before the server has fully ran the command.
So my question is whats the best way of telling the script to hold off before closing the session in an attempt to get all the output back from the command? Below is a snippet of the code:</p>
<pre><code>def ssh_command(ip, user, passwd , command):
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(ip, username=user, password=passwd)
ssh_session = client.get_transport().open_session()
if ssh_session.active:
ssh_session.exec_command(command)
print ssh_session.recv(99999)
return
</code></pre>
<p>I tried adjusting</p>
<pre><code>print ssh_session.recv(99999)
</code></pre>
<p>to different values but had no luck. I think Iâm not understanding this function fully. I know its the function thats telling the script to return to the user the output of the terminal command but Iâm not 100% sure what 99999 represents. I thought this was a delay. </p>
<p>Thanks for your help! </p>
| -1 | 2016-07-30T18:51:32Z | 38,677,765 | <p>the <code>recv()</code> method used here is actually expecting 99999 bytes from the socket. If 99999 bytes are not provided within a certain amount of time (i.e. timeout) then the connection will be closed and you'll be given the bytes provided within this time.</p>
<p>This is probably what is happening in your situation.</p>
<p>I've written a script to update SSH keys in multiple servers using Paramiko. You can <a href="https://github.com/VeriTeknik/sshkeyupdate" rel="nofollow">check it out</a> as an example if you'd like.</p>
<p>In your case, if you want the output of the command you run, simply get the stdin, stdout, stderr of the command executed in the remote session.</p>
<pre><code>stdin, stdout, stderr = ssh_session.exec_command("ls -l")
output = stdout.readlines()
</code></pre>
<p>Now you should have the <code>stdout</code> of the command in the variable <code>output</code>.</p>
| 0 | 2016-07-30T19:31:42Z | [
"python",
"paramiko"
] |
How to annotate a range of the x axis in matplotlib? | 38,677,467 | <p>I want to make an annotation, something like <a href="http://matplotlib.org/users/annotations_intro.html" rel="nofollow">here</a>, but I need to show a <em>range in x</em> instead of a single point. It's something like the <a href="https://en.wikipedia.org/wiki/Engineering_drawing#/media/File:Line_types.png" rel="nofollow">dimension lines</a> in technical drawing.</p>
<hr>
<p>Here is an example of what I am looking for:</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
xx = np.linspace(0,10)
yy = np.sin(xx)
fig, ax = plt.subplots(1,1, figsize=(12,5))
ax.plot(xx,yy)
ax.set_ylim([-2,2])
# -----------------------------------------
# The following block attempts to show what I am looking for
ax.plot([4,6],[1,1],'-k')
ax.plot([4,4],[0.9,1.1],'-k')
ax.plot([6,6],[0.9,1.1],'-k')
ax.annotate('important\npart', xy=(4, 1.5), xytext=(4.5, 1.2) )
</code></pre>
<p><a href="http://i.stack.imgur.com/a6jJ1.png" rel="nofollow"><img src="http://i.stack.imgur.com/a6jJ1.png" alt="enter image description here"></a></p>
<hr>
<p><strong>How do I annotate a range in a maplotlib graph?</strong></p>
<hr>
<p>I am using: </p>
<p>python: 3.4.3 + numpy: 1.11.0 + matplotlib: 1.5.1</p>
| 4 | 2016-07-30T18:54:43Z | 38,677,732 | <p>You could use two calls to <a href="http://matplotlib.org/users/annotations_guide.html#plotting-guide-annotation" rel="nofollow"><code>ax.annotate</code></a> - one to add the text and one to draw an arrow with flat ends spanning the range you want to annotate:</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
xx = np.linspace(0,10)
yy = np.sin(xx)
fig, ax = plt.subplots(1,1, figsize=(12,5))
ax.plot(xx,yy)
ax.set_ylim([-2,2])
ax.annotate('', xy=(4, 1), xytext=(6, 1), xycoords='data', textcoords='data',
arrowprops={'arrowstyle': '|-|'})
ax.annotate('important\npart', xy=(5, 1.5), ha='center', va='center')
</code></pre>
<p><a href="http://i.stack.imgur.com/6Cg9Z.png" rel="nofollow"><img src="http://i.stack.imgur.com/6Cg9Z.png" alt="enter image description here"></a></p>
| 1 | 2016-07-30T19:26:54Z | [
"python",
"numpy",
"matplotlib"
] |
How to annotate a range of the x axis in matplotlib? | 38,677,467 | <p>I want to make an annotation, something like <a href="http://matplotlib.org/users/annotations_intro.html" rel="nofollow">here</a>, but I need to show a <em>range in x</em> instead of a single point. It's something like the <a href="https://en.wikipedia.org/wiki/Engineering_drawing#/media/File:Line_types.png" rel="nofollow">dimension lines</a> in technical drawing.</p>
<hr>
<p>Here is an example of what I am looking for:</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
xx = np.linspace(0,10)
yy = np.sin(xx)
fig, ax = plt.subplots(1,1, figsize=(12,5))
ax.plot(xx,yy)
ax.set_ylim([-2,2])
# -----------------------------------------
# The following block attempts to show what I am looking for
ax.plot([4,6],[1,1],'-k')
ax.plot([4,4],[0.9,1.1],'-k')
ax.plot([6,6],[0.9,1.1],'-k')
ax.annotate('important\npart', xy=(4, 1.5), xytext=(4.5, 1.2) )
</code></pre>
<p><a href="http://i.stack.imgur.com/a6jJ1.png" rel="nofollow"><img src="http://i.stack.imgur.com/a6jJ1.png" alt="enter image description here"></a></p>
<hr>
<p><strong>How do I annotate a range in a maplotlib graph?</strong></p>
<hr>
<p>I am using: </p>
<p>python: 3.4.3 + numpy: 1.11.0 + matplotlib: 1.5.1</p>
| 4 | 2016-07-30T18:54:43Z | 38,683,607 | <p>Using <a href="http://stackoverflow.com/a/38677732/776515">ali_m's answer</a>, I could define this function, maybe it can be useful for someone sometime :)</p>
<hr>
<p><strong>Function</strong></p>
<pre><code>def annotation_line( ax, xmin, xmax, y, text, ytext=0, linecolor='black', linewidth=1, fontsize=12 ):
ax.annotate('', xy=(xmin, y), xytext=(xmax, y), xycoords='data', textcoords='data',
arrowprops={'arrowstyle': '|-|', 'color':linecolor, 'linewidth':linewidth})
ax.annotate('', xy=(xmin, y), xytext=(xmax, y), xycoords='data', textcoords='data',
arrowprops={'arrowstyle': '<->', 'color':linecolor, 'linewidth':linewidth})
xcenter = xmin + (xmax-xmin)/2
if ytext==0:
ytext = y + ( ax.get_ylim()[1] - ax.get_ylim()[0] ) / 20
ax.annotate( text, xy=(xcenter,ytext), ha='center', va='center', fontsize=fontsize)
</code></pre>
<hr>
<p><strong>Call</strong></p>
<pre><code>annotation_line( ax=ax, text='Important\npart', xmin=4, xmax=6, \
y=1, ytext=1.4, linewidth=2, linecolor='red', fontsize=18 )
</code></pre>
<hr>
<p><strong>Output</strong></p>
<p><a href="http://i.stack.imgur.com/aRdjv.png" rel="nofollow"><img src="http://i.stack.imgur.com/aRdjv.png" alt="enter image description here"></a></p>
| 1 | 2016-07-31T11:41:42Z | [
"python",
"numpy",
"matplotlib"
] |
Finding specific strings within a column and finding the max corresponding to that string | 38,677,504 | <p>I was wondering: <br></p>
<p>1.) how do I find a specific string in a column <br>
2.) given that string, how would I find it's corresponding max <br>
3.) How do I count the number of strings for each row in that column</p>
<p>I have a csv file called sports.csv</p>
<pre><code> import pandas as pd
import numpy as np
#loading the data into data frame
X = pd.read_csv('sports.csv')
</code></pre>
<p>the two columns of interest are the <code>Totals</code> and <code>Gym</code> column:</p>
<pre><code> Total Gym
40 Football|Baseball|Hockey|Running|Basketball|Swimming|Cycling|Volleyball|Tennis|Ballet
37 Baseball|Tennis
61 Basketball|Baseball|Ballet
12 Swimming|Ballet|Cycling|Basketball|Volleyball|Hockey|Running|Tennis|Baseball|Football
78 Swimming|Basketball
29 Baseball|Tennis|Ballet|Cycling|Basketball|Football|Volleyball|Swimming
31 Tennis
54 Tennis|Football|Ballet|Cycling|Running|Swimming|Baseball|Basketball|Volleyball
33 Baseball|Hockey|Swimming|Cycling
17 Football|Hockey|Volleyball
</code></pre>
<p>Notice that the <code>Gym</code> column has multiple strings for each corresponding sport.I'm trying to find a way to find all of the gyms that have Baseball and find the one with the max total. However, I'm only interested in gyms that have at least two other sports i.e. I wouldn't want to consider:</p>
<pre><code> Total Gym
37 Baseball|Tennis
</code></pre>
| 0 | 2016-07-30T18:59:15Z | 38,677,642 | <p>You can do it in one pass as you read the file:</p>
<pre><code>import csv
with open("sport.csv") as f:
mx, best = float("-inf"), None
for row in csv.reader(f, delimiter=" ", skipinitialspace=1):
row[1:] = row[1].split("|")
if "Baseball" in row and len(row[1:]) > 2 and int(row[0]) > mx:
mx = int(row[0])
best = row
if best:
print(best, mx, len(row[1:]))
</code></pre>
<p>Which would give you:</p>
<pre><code>(['61', 'Basketball', 'Baseball', 'Ballet'], 61, 3)
</code></pre>
<p>Another way without splitting would be to count the pipe chars:</p>
<pre><code>import csv
with open("sports.csv") as f:
mx, best = float("-inf"),None
for row in csv.reader(f, delimiter=" ", skipinitialspace=1):
print(row[1])
if "Baseball" in row[1] and row[1].count("|") > 1 and int(row[0]) > mx:
mx = int(row[0])
best = row
if best:
print(best, mx, row[1].count("|"))
</code></pre>
<p>That means though a substring could potentially be matched as opposed to an exact word.</p>
| 0 | 2016-07-30T19:16:22Z | [
"python",
"csv",
"pandas",
"max"
] |
Finding specific strings within a column and finding the max corresponding to that string | 38,677,504 | <p>I was wondering: <br></p>
<p>1.) how do I find a specific string in a column <br>
2.) given that string, how would I find it's corresponding max <br>
3.) How do I count the number of strings for each row in that column</p>
<p>I have a csv file called sports.csv</p>
<pre><code> import pandas as pd
import numpy as np
#loading the data into data frame
X = pd.read_csv('sports.csv')
</code></pre>
<p>the two columns of interest are the <code>Totals</code> and <code>Gym</code> column:</p>
<pre><code> Total Gym
40 Football|Baseball|Hockey|Running|Basketball|Swimming|Cycling|Volleyball|Tennis|Ballet
37 Baseball|Tennis
61 Basketball|Baseball|Ballet
12 Swimming|Ballet|Cycling|Basketball|Volleyball|Hockey|Running|Tennis|Baseball|Football
78 Swimming|Basketball
29 Baseball|Tennis|Ballet|Cycling|Basketball|Football|Volleyball|Swimming
31 Tennis
54 Tennis|Football|Ballet|Cycling|Running|Swimming|Baseball|Basketball|Volleyball
33 Baseball|Hockey|Swimming|Cycling
17 Football|Hockey|Volleyball
</code></pre>
<p>Notice that the <code>Gym</code> column has multiple strings for each corresponding sport.I'm trying to find a way to find all of the gyms that have Baseball and find the one with the max total. However, I'm only interested in gyms that have at least two other sports i.e. I wouldn't want to consider:</p>
<pre><code> Total Gym
37 Baseball|Tennis
</code></pre>
| 0 | 2016-07-30T18:59:15Z | 38,678,027 | <p>You can easily do this using <code>pandas</code></p>
<p>First, split the strings into a list on the tab delimiter followed by iterating over the list and choosing the ones with the length greater than 2 as you would want baseball along with two other sports as the criteria.</p>
<pre><code>In [4]: df['Gym'] = df['Gym'].str.split('|').apply(lambda x: ' '.join([i for i in x if len(x)>2]))
In [5]: df
Out[5]:
Total Gym
0 40 Football Baseball Hockey Running Basketball Sw...
1 37
2 61 Basketball Baseball Ballet
3 12 Swimming Ballet Cycling Basketball Volleyball ...
4 78
5 29 Baseball Tennis Ballet Cycling Basketball Foot...
6 31
7 54 Tennis Football Ballet Cycling Running Swimmin...
8 33 Baseball Hockey Swimming Cycling
9 17 Football Hockey Volleyball
</code></pre>
<p>Using <code>str.contains</code> to search for the string <code>Baseball</code> in the column <code>Gym</code>.</p>
<pre><code>In [6]: df = df.loc[df['Gym'].str.contains('Baseball')]
In [7]: df
Out[7]:
Total Gym
0 40 Football Baseball Hockey Running Basketball Sw...
2 61 Basketball Baseball Ballet
3 12 Swimming Ballet Cycling Basketball Volleyball ...
5 29 Baseball Tennis Ballet Cycling Basketball Foot...
7 54 Tennis Football Ballet Cycling Running Swimmin...
8 33 Baseball Hockey Swimming Cycling
</code></pre>
<p>Compute respective string counts. </p>
<pre><code>In [8]: df['Count'] = df['Gym'].str.split().apply(lambda x: len([i for i in x]))
</code></pre>
<p>Followed by choosing the subset of the dataframe corresponding to the maximum value in the <code>Totals</code> column.</p>
<pre><code>In [9]: df.loc[df['Total'].idxmax()]
Out[9]:
Total 61
Gym Basketball Baseball Ballet
Count 3
Name: 2, dtype: object
</code></pre>
| 1 | 2016-07-30T20:05:59Z | [
"python",
"csv",
"pandas",
"max"
] |
Finding specific strings within a column and finding the max corresponding to that string | 38,677,504 | <p>I was wondering: <br></p>
<p>1.) how do I find a specific string in a column <br>
2.) given that string, how would I find it's corresponding max <br>
3.) How do I count the number of strings for each row in that column</p>
<p>I have a csv file called sports.csv</p>
<pre><code> import pandas as pd
import numpy as np
#loading the data into data frame
X = pd.read_csv('sports.csv')
</code></pre>
<p>the two columns of interest are the <code>Totals</code> and <code>Gym</code> column:</p>
<pre><code> Total Gym
40 Football|Baseball|Hockey|Running|Basketball|Swimming|Cycling|Volleyball|Tennis|Ballet
37 Baseball|Tennis
61 Basketball|Baseball|Ballet
12 Swimming|Ballet|Cycling|Basketball|Volleyball|Hockey|Running|Tennis|Baseball|Football
78 Swimming|Basketball
29 Baseball|Tennis|Ballet|Cycling|Basketball|Football|Volleyball|Swimming
31 Tennis
54 Tennis|Football|Ballet|Cycling|Running|Swimming|Baseball|Basketball|Volleyball
33 Baseball|Hockey|Swimming|Cycling
17 Football|Hockey|Volleyball
</code></pre>
<p>Notice that the <code>Gym</code> column has multiple strings for each corresponding sport.I'm trying to find a way to find all of the gyms that have Baseball and find the one with the max total. However, I'm only interested in gyms that have at least two other sports i.e. I wouldn't want to consider:</p>
<pre><code> Total Gym
37 Baseball|Tennis
</code></pre>
| 0 | 2016-07-30T18:59:15Z | 38,678,917 | <p>Try This: </p>
<pre><code>df3.loc[(df3['Gym'].str.contains('Hockey') == True) & (df3["Gym"].str.count("\|")>1)].sort_values("Total").tail(1)
Total Gym
0 40 Football|Baseball|Hockey|Running|Basketball|Sw...
df3.loc[(df3['Gym'].str.contains('Baseball') == True) & (df3["Gym"].str.count("\|")>1)].sort_values("Total").tail(1)
Total Gym
2 61 Basketball|Baseball|Ballet
</code></pre>
| 0 | 2016-07-30T22:08:00Z | [
"python",
"csv",
"pandas",
"max"
] |
Python - Convert strings in column into categorical variable | 38,677,615 | <p>I'd like to transform columns filled with strings into categorical variables so that I could run statistics. However, I am having difficulty with this transformation because I'm fairly new to Python.</p>
<p>Here is a sample of my code:</p>
<pre><code># Open txt file and provide column names
data = pd.read_csv('sample.txt', sep="\t", header = None,
names = ["Label", "I1", "I2", "C1", "C2"])
# Convert I1 and I2 to continuous, numeric variables
data = data.apply(lambda x: pd.to_numeric(x, errors='ignore'))
# Convert Label, C1, and C2 to categorical variables
data["Label"] = pd.factorize(data.Label)[0]
data["C1"] = pd.factorize(data.C1)[0]
data["C2"] = pd.factorize(data.C2)[0]
# Split the predictors into training/testing sets
predictors = data.drop('Label', 1)
msk = np.random.rand(len(predictors)) < 0.8
predictors_train = predictors[msk]
predictors_test = predictors[~msk]
# Split the response variable into training/testing sets
response = data['Label']
ksm = np.random.rand(len(response)) < 0.8
response_train = response[ksm]
response_test = response[~ksm]
# Logistic Regression
from sklearn import linear_model
# Create logistic regression object
lr = linear_model.LogisticRegression()
# Train the model using the training sets
lr.fit(predictors_train, response_train)
</code></pre>
<p>However, I'd get this error:</p>
<pre><code>ValueError: could not convert string to float: 'ec26ad35'
</code></pre>
<p>The <code>ec26ad35</code> value is a string from the categorical variables <code>C1</code> and <code>C2</code>. I'm not sure what's going on: Didn't I already convert the strings into categorical variables? Why does the error say that they're still strings?</p>
<p>Using <code>data.head(30)</code>, this is my data:</p>
<pre><code>>> data[["Label", "I1", "I2", "C1", "C2"]].head(30)
Label I1 I2 C1 C2
0 0 1.0 1 68fd1e64 80e26c9b
1 0 2.0 0 68fd1e64 f0cf0024
2 0 2.0 0 287e684f 0a519c5c
3 0 NaN 893 68fd1e64 2c16a946
4 0 3.0 -1 8cf07265 ae46a29d
5 0 NaN -1 05db9164 6c9c9cf3
6 0 NaN 1 439a44a4 ad4527a2
7 1 1.0 4 68fd1e64 2c16a946
8 0 NaN 44 05db9164 d833535f
9 0 NaN 35 05db9164 510b40a5
10 0 NaN 2 05db9164 0468d672
11 0 0.0 6 05db9164 9b5fd12f
12 1 0.0 -1 241546e0 38a947a1
13 1 NaN 2 be589b51 287130e0
14 0 0.0 51 5a9ed9b0 80e26c9b
15 0 NaN 2 05db9164 bc6e3dc1
16 1 1.0 987 68fd1e64 38d50e09
17 0 0.0 1 8cf07265 7cd19acc
18 0 0.0 24 05db9164 f0cf0024
19 0 7.0 102 3c9d8785 b0660259
20 1 NaN 47 1464facd 38a947a1
21 0 0.0 1 05db9164 09e68b86
22 0 NaN 0 05db9164 38a947a1
23 0 NaN 9 05db9164 08d6d899
24 0 0.0 1 5a9ed9b0 3df44d94
25 0 NaN 4 5a9ed9b0 09e68b86
26 1 0.0 1 8cf07265 942f9a8d
27 1 0.0 20 68fd1e64 38a947a1
28 1 0.0 78 68fd1e64 1287a654
29 1 3.0 0 05db9164 90081f33
</code></pre>
<p><strong>Edit</strong>: Included error from imputing missing data after splitting dataframes into training and testing data sets. Not sure what's going on here too.</p>
<pre><code># Impute missing data
>> from sklearn.preprocessing import Imputer
>> imp = Imputer(missing_values='NaN', strategy='mean', axis=0)
>> predictors_train = imp.fit_transform(predictors_train)
TypeError: float() argument must be a string or a number, not 'function'
</code></pre>
| 0 | 2016-07-30T19:12:33Z | 38,678,718 | <p>As @ayhan noted in the comments, you probably want to use <a href="http://www.socialresearchmethods.net/kb/dummyvar.php" rel="nofollow">dummy variables</a> here. This is because it seems highly unlikely from your data that there is really any ordering in your text labels. </p>
<p>This can easily be done via <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.get_dummies.html" rel="nofollow"><code>pandas.get_dummies</code></a>, e.g.:</p>
<pre><code>pd.get_dummies(df.C1)
</code></pre>
<p>Note that this returns a regular DataFrame:</p>
<pre><code>>>> pd.get_dummies(df.C1).columns
Index([u'05db9164', u'1464facd', u'241546e0', u'287e684f', u'3c9d8785',
u'439a44a4', u'5a9ed9b0', u'68fd1e64', u'8cf07265', u'be589b51'],
dtype='object')
</code></pre>
<p>You'd probably want to use this with a horizontal <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow"><code>concat</code></a>, therefore.</p>
<hr>
<p>If you actually are actually looking to transform the labels into something numeric (which does not seem likely), you might look at <a href="http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.LabelEncoder.html" rel="nofollow"><code>sklearn.preprocessing.LabelEncoder</code></a>.</p>
| 1 | 2016-07-30T21:36:36Z | [
"python",
"string",
"pandas",
"statistics",
"categorical-data"
] |
Character Usage Python | 38,677,659 | <p>Python 3.5.2</p>
<p>I am trying to find out how to use characters in python (!,@,$ etc), however i haven't been able to find anything to give any help or any detail about this.</p>
<p>Here is an example:</p>
<pre><code>>>> $
SyntaxError: invalid syntax
</code></pre>
<p>What i'm looking for is why this is happen and an example of syntax. Or wether this simply does nothing and isn't a feature and python however if it wasn't I would assume you could use the character as a variable however you cannot.</p>
<pre><code>>>> $ = 'Example'
SyntaxError: invalid syntax
</code></pre>
| -2 | 2016-07-30T19:18:12Z | 38,677,702 | <p>Generally, Python identifiers can only use <a href="https://docs.python.org/3/reference/lexical_analysis.html#identifiers" rel="nofollow">letters (from various languages), numbers, or underscores</a>. Unlike JavaScript, <code>$</code> isn't a valid identifier character. Likewise, most punctuation, including <code>!</code> and <code>@</code>, is not allowed in identifiers.</p>
<blockquote>
<p>valid characters for identifiers [in Python] are the uppercase and lowercase letters <code>A</code> through <code>Z</code>, the underscore <code>_</code> and, except for the first character, the digits <code>0</code> through <code>9</code>.</p>
</blockquote>
<p>Therefore, a valid assignment might look like</p>
<pre><code>spam = 'Example'
</code></pre>
<p>for the identifier <code>spam</code>.</p>
| 2 | 2016-07-30T19:23:24Z | [
"python",
"syntax"
] |
Character Usage Python | 38,677,659 | <p>Python 3.5.2</p>
<p>I am trying to find out how to use characters in python (!,@,$ etc), however i haven't been able to find anything to give any help or any detail about this.</p>
<p>Here is an example:</p>
<pre><code>>>> $
SyntaxError: invalid syntax
</code></pre>
<p>What i'm looking for is why this is happen and an example of syntax. Or wether this simply does nothing and isn't a feature and python however if it wasn't I would assume you could use the character as a variable however you cannot.</p>
<pre><code>>>> $ = 'Example'
SyntaxError: invalid syntax
</code></pre>
| -2 | 2016-07-30T19:18:12Z | 38,677,715 | <p>Naming convention rules in python only allow numbers, letters, and underscores. Here specifically are the rules</p>
<blockquote>
<pre><code>Variables names must start with a letter or an underscore, such as:
_underscore
underscore_
The remainder of your variable name may consist of letters, numbers and underscores.
password1
n00b
un_der_scores
Names are case sensitive.
case_sensitive, CASE_SENSITIVE, and Case_Sensitive are each a different variable.
</code></pre>
</blockquote>
<p><a href="http://www.thehelloworldprogram.com/python/python-variable-assignment-statements-rules-conventions-naming/" rel="nofollow">Here</a> you can learn more about python variable assignment and naming conventions</p>
| 2 | 2016-07-30T19:25:00Z | [
"python",
"syntax"
] |
python - how to simultaneously iterate and modify list, set, etc | 38,677,708 | <p>In my program I have <strong>many</strong> lines where I need to both iterate over a something <strong>and</strong> modify it in that same <code>for</code> loop.</p>
<p>However, I know that modifying the thing over which you're iterating is bad because it <em>may</em> - probably <strong>will</strong> - result in an undesired result.</p>
<p>So I've been doing something like this:</p>
<pre><code>for el_idx, el in enumerate(theList):
if theList[el_idx].IsSomething() is True:
theList[el_idx].SetIt(False)
</code></pre>
<p>Is this the best way to do this?</p>
| 0 | 2016-07-30T19:24:26Z | 38,677,855 | <p>This is a conceptual misunderstanding. </p>
<p>It is dangerous to modify the list itself from within the iteration, because of the way Python translates the loop to lower level code. This can cause unexpected side effects during the iteration, there's a good example here : </p>
<p><a href="https://unspecified.wordpress.com/2009/02/12/thou-shalt-not-modify-a-list-during-iteration/" rel="nofollow">https://unspecified.wordpress.com/2009/02/12/thou-shalt-not-modify-a-list-during-iteration/</a></p>
<p>But modifying mutable objects stored in the list is acceptable, and common practice. </p>
<p>I suspect that you're thinking that because the list is made up of those objects, that modifying those objects modifies the list. This is understandable - it's just not how it's normally thought of. If it helps, consider that the list only really contains references to those objects. When you modify the objects within the loop - you are merely <em>using</em> the list to modify the objects, not <em>modifying</em> the list itself.</p>
<p>What you should not do is add or remove items from the list during the iteration.</p>
| 1 | 2016-07-30T19:43:07Z | [
"python"
] |
python - how to simultaneously iterate and modify list, set, etc | 38,677,708 | <p>In my program I have <strong>many</strong> lines where I need to both iterate over a something <strong>and</strong> modify it in that same <code>for</code> loop.</p>
<p>However, I know that modifying the thing over which you're iterating is bad because it <em>may</em> - probably <strong>will</strong> - result in an undesired result.</p>
<p>So I've been doing something like this:</p>
<pre><code>for el_idx, el in enumerate(theList):
if theList[el_idx].IsSomething() is True:
theList[el_idx].SetIt(False)
</code></pre>
<p>Is this the best way to do this?</p>
| 0 | 2016-07-30T19:24:26Z | 38,677,860 | <p>you could get index first </p>
<pre><code>idx = [ el_idx for el_idx, el in enumerate(theList) if el.IsSomething() ]
[ theList[i].SetIt(False) for i in idx ]
</code></pre>
| -1 | 2016-07-30T19:44:05Z | [
"python"
] |
python - how to simultaneously iterate and modify list, set, etc | 38,677,708 | <p>In my program I have <strong>many</strong> lines where I need to both iterate over a something <strong>and</strong> modify it in that same <code>for</code> loop.</p>
<p>However, I know that modifying the thing over which you're iterating is bad because it <em>may</em> - probably <strong>will</strong> - result in an undesired result.</p>
<p>So I've been doing something like this:</p>
<pre><code>for el_idx, el in enumerate(theList):
if theList[el_idx].IsSomething() is True:
theList[el_idx].SetIt(False)
</code></pre>
<p>Is this the best way to do this?</p>
| 0 | 2016-07-30T19:24:26Z | 38,678,397 | <p>Your problem seems to be unclear to me. But if we talk about harmful of modifying list during a <code>for</code> loop iteration in Python. I can think about two scenarios.</p>
<p><strong>First</strong>, You modify some elements in list that suppose to be used on the next round of computation as its original value.</p>
<p>e.g. You want to write a program that have such inputs and outputs like these.</p>
<p>Input: </p>
<pre><code>[1, 2, 3, 4]
</code></pre>
<p>Expected output: </p>
<pre><code>[1, 3, 6, 10] #[1, 1 + 2, 1 + 2 + 3, 1 + 2 + 3 + 4]
</code></pre>
<p>But...you write a code in this way:</p>
<pre><code>#!/usr/bin/env python
mylist = [1, 2, 3, 4]
for idx, n in enumerate(mylist):
mylist[idx] = sum(mylist[:idx + 1])
print mylist
</code></pre>
<p>Result is:</p>
<pre><code>[1, 3, 7, 15] # undesired result
</code></pre>
<p><strong>Second</strong>, you make some change on size of list during a <code>for</code> loop iteration.</p>
<p>e.g. From <a href="http://stackoverflow.com/questions/32263634/python-delete-all-entries-of-a-value-in-list/32263821">python-delete-all-entries-of-a-value-in-list</a>:</p>
<pre><code>>>> s=[1,4,1,4,1,4,1,1,0,1]
>>> for i in s:
... if i ==1: s.remove(i)
...
>>> s
[4, 4, 4, 0, 1]
</code></pre>
<p>The example shows the undesired result that raised from side-effect of changing size in list. This obviously shows you that <code>for</code> each loop in Python can not handle list with dynamic size in a proper way. Below, I show you some simple way to overcome this problem:</p>
<pre><code> #!/usr/bin/env python
s=[1, 4, 1, 4, 1, 4, 1, 1, 0, 1]
list_size=len(s)
i=0
while i!=list_size:
if s[i]==1:
del s[i]
list_size=len(s)
else:
i=i + 1
print s
</code></pre>
<p>Result:</p>
<pre><code>[4, 4, 4, 0]
</code></pre>
<p><strong>Conclusion</strong>: It's definitely not harmful to modify any elements in list during a loop iteration, if you don't 1) make change on size of list 2) make some side-effect of computation by your own.</p>
| 0 | 2016-07-30T20:53:11Z | [
"python"
] |
Matching up iterables in lists, having significant difficulty | 38,677,714 | <p>For a personal project I have three lists. One of these contains a set of arrays (l2) the size of which is always determined by a setting l2_size and always contains random members of l1. The next array, l3, on the other hand will always be a set of 0's of quantity len(l1).</p>
<p>This means...</p>
<pre><code>l1 = [1,2,3,4,5,1,2,3,4,5,1,2,3,4,5]
l2 = [[3, 4, 5, 2, 4],[3, 5, 1, 2, 4], [4, 3, 2, 1, 5]]
l3 = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
</code></pre>
<p>I need to perform a search such that </p>
<ol>
<li><p>Beginning with l2[0] if the pointer l2[0] hits l2[0], search through l1 to find l1[i] == the first value of l2[0]. </p></li>
<li><p>Once the first value of l2[0] use l3 to assign its corresponding value. </p></li>
<li><p>Since the size of the arrays in l2[0] are 5 members we are going to assign a corresponding value of 1 to l3 a maximum of five times. Once we have hit that target we're moving onto the next set l2[1]. </p></li>
<li><p>Once we are done with l2[0] (so on to l2[1]) we need to assign the next corresponding value, so 2, without over-writing the values in l3.</p></li>
</ol>
<p><strong>Illustration...</strong> </p>
<p>Imagine these are baseball scoring cards... I have l1 baseball cards in my deck. The compositions of baseball scoring cards I want in my hands are contained in l2. These cards will win me the game! In this case l2 = [1,2,3,4,5]. I'm a massive cheater and must find all l2 in l1 (cards for hands). Finding l2 in l1 I mark where they are using l3. I also use l3 to tell me which hand to put them in. </p>
<p>To be a valid solution we must uniquely pair up the values in l2 such that they are uniquely identified as values in l1 using l3. This would mean...</p>
<pre><code>l1 = [1,2,3,4,5,1,2,3,4,5]
l2 = [[1,2,3,4,5],[1,2,3,4,5]]
l3 = [1,1,1,1,1,2,2,2,2,2]
</code></pre>
<p>Would be valid. But...</p>
<pre><code>l1 = [1,2,3,4,5,1,2,3,4,5]
l2 = [[1,2,3,4,5],[1,2,3,4,5]]
l3 = [1,2,1,1,1,2,2,1,2,2]
</code></pre>
<p>Would be invalid because there is no hand in l2 containing [2,1,2,4,5] in any order.</p>
<p><strong>Example</strong> </p>
<p>From l2[0] we are going to iterate through l1 over and over and pick up all the objects in l2[0] and sign them off to l3. This should then look like (by hand)...</p>
<pre><code>l1 = [1,2,3,4,5,1,2,3,4,5,1,2,3,4,5]
l2 = [[3, 4, 5, 2, 4],[3, 5, 1, 2, 4], [4, 3, 2, 1, 5]]
l3 = [0,0,1,1,1,0,1,0,1,0,0,0,0,0,0]
</code></pre>
<p>The value 1 has been assigned in l3 since these are the first instances of the corresponding values we come across. We are done with l2[0] now because we have found all of its items in l1. The next job is l2[1]...</p>
<pre><code>l1 = [1,2,3,4,5,1,2,3,4,5,1,2,3,4,5]
l2 = [[3, 4, 5, 2, 4],[3, 5, 1, 2, 4], [4, 3, 2, 1, 5]]
l3 = [2,2,1,1,1,0,1,0,1,0,0,0,2,2,2]
</code></pre>
<p>This is what I've cooked up but to no avail...</p>
<pre><code>assignvar = 1
pos = 0
for x in l2:
for y in x:
for z in l1:
while userpos < len(l1):
if y == z:
l1[pos] = assignvar
while l2_size == pos:
assignvar += 1
l2_size = l2_size+l2_size #stops pos going out of range, changes assignvar to 2 (so appending the next set of l3 iterables to 2 .etc)
userpos = userpos+1
</code></pre>
<p>Really quite confounded how to approach this issue in my code. I feel like I have the right idea using the three for loops but I've been hitting this with my wrench for a while now and completely burned out. </p>
<p><strong>Real world input dataset...</strong></p>
<pre><code>l1 = [5005.0, 5002.5, 5003.0, 5003.0, 5003.5, 5002.5, 5003.5, 5004.0, 5004.5, 5004.0, 5002.5, 5005.0, 5004.5, 5004.0, 5005.0, 5002.5, 5003.5, 5004.0, 5002.5, 5002.5, 5004.0, 5004.0, 5003.5, 5001.5, 5001.5, 5005.0, 5003.0, 5005.0, 5003.5, 5000.5, 5002.5, 5003.5, 5005.0]
l2 = [[5002.5, 5004.0], [5002.5, 5004.5], [5002.5, 5004.0], [5002.5, 5005.0], [5002.5, 5004.5], [5002.5, 5004.0], [5002.5, 5005.0], [5002.5, 5004.0], [5002.5, 5004.0], [5002.5, 5004.0], [5002.5, 5005.0], [5002.5, 5005.0], [5002.5, 5005.0], [5003.0, 5003.5], [5003.0, 5003.5], [5003.0, 5004.0], [5003.0, 5004.5], [5003.0, 5004.0], [5003.0, 5005.0], [5003.0, 5004.5], [5003.0, 5004.0], [5003.0, 5005.0], [5003.0, 5003.5], [5003.0, 5004.0], [5003.0, 5004.0], [5003.0, 5004.0], [5003.0, 5003.5], [5003.0, 5005.0], [5003.0, 5005.0], [5003.0, 5003.5], [5003.0, 5003.5], [5003.0, 5005.0], [5003.0, 5003.5], [5003.0, 5003.5], [5003.0, 5004.0], [5003.0, 5004.5], [5003.0, 5004.0], [5003.0, 5005.0], [5003.0, 5004.5], [5003.0, 5004.0], [5003.0, 5005.0], [5003.0, 5003.5], [5003.0, 5004.0], [5003.0, 5004.0], [5003.0, 5004.0], [5003.0, 5003.5], [5003.0, 5005.0], [5003.0, 5005.0], [5003.0, 5003.5], [5003.0, 5003.5], [5003.0, 5005.0], [5002.5, 5004.0], [5002.5, 5004.5], [5002.5, 5004.0], [5002.5, 5005.0], [5002.5, 5004.5], [5002.5, 5004.0], [5002.5, 5005.0], [5002.5, 5004.0], [5002.5, 5004.0], [5002.5, 5004.0], [5002.5, 5005.0], [5002.5, 5005.0], [5002.5, 5005.0], [5002.5, 5005.0], [5002.5, 5004.5], [5002.5, 5004.0], [5002.5, 5005.0], [5002.5, 5004.0], [5002.5, 5004.0], [5002.5, 5004.0], [5002.5, 5005.0], [5002.5, 5005.0], [5002.5, 5005.0], [5002.5, 5004.0], [5002.5, 5004.0], [5002.5, 5004.0], [5002.5, 5005.0], [5002.5, 5005.0], [5002.5, 5005.0], [5002.5, 5004.0], [5002.5, 5004.0], [5002.5, 5005.0], [5002.5, 5005.0], [5002.5, 5005.0], [5002.5, 5004.0], [5002.5, 5004.0], [5002.5, 5005.0], [5002.5, 5005.0], [5002.5, 5005.0], [5001.5, 5005.0], [5001.5, 5005.0], [5001.5, 5005.0], [5001.5, 5005.0], [5001.5, 5005.0], [5001.5, 5005.0], [5003.0, 5005.0], [5003.0, 5003.5], [5003.0, 5003.5], [5003.0, 5005.0], [5002.5, 5005.0]]
l3=[]
for i in range(len(l1)):
l3.append(int(0))
</code></pre>
| 0 | 2016-07-30T19:24:55Z | 38,677,794 | <p>get sublist first, then using sublist's element get l1's index. increase 1 for l3 element based on l1's index</p>
<pre><code>l1 = [1,2,3,4,5,1,2,3,4,5,1,2,3,4,5]
l2 = [[3, 4, 5, 2, 4],[3, 5, 1, 2, 4], [4, 3, 2, 1, 5]]
l3 = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
def combinList( lst ):
''' put list of list together based on index
for example:
a = [1,3,5,7]
b = [2,4,6,8]
combined list should be [1,2,3,4,5,6,7,8] '''
step = len(lst)
res= [None]*len( reduce(lambda x,y:x+y, lst))
for i,item in enumerate(lst):
res[i::step] = sorted(item)
return res
for value,line in enumerate(l2):
counter = 0
record = {}
# count how many time this element appeared
for i in line:
record[ i -1 ] = record.get( i - 1,0) + 1
newList = combinList( [ [ i for i,j in enumerate(l1) if item == j] for item in line ] )
for idx in newList:
# if this element of l3 hasn't been change and there is at least one associated element in l2,put the value to l3 and reduce the number of l2
if not l3[idx] and record.get(idx%5,0):
l3[idx] = value + 1
counter+=1
record[idx%5] = record[idx%5] -1
if counter >=5:
break
print l3
print l3
</code></pre>
<p>output:</p>
<pre><code>#first iteration
[0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0]
#second iteration
[2, 1, 1, 1, 1, 0, 2, 2, 1, 2, 0, 0, 0, 2, 0]
#third iteration
[2, 1, 1, 1, 1, 3, 2, 2, 1, 2, 0, 3, 3, 2, 3]
#final iteration
[2, 1, 1, 1, 1, 3, 2, 2, 1, 2, 0, 3, 3, 2, 3]
</code></pre>
| 2 | 2016-07-30T19:34:51Z | [
"python",
"arrays",
"iterable"
] |
Matching up iterables in lists, having significant difficulty | 38,677,714 | <p>For a personal project I have three lists. One of these contains a set of arrays (l2) the size of which is always determined by a setting l2_size and always contains random members of l1. The next array, l3, on the other hand will always be a set of 0's of quantity len(l1).</p>
<p>This means...</p>
<pre><code>l1 = [1,2,3,4,5,1,2,3,4,5,1,2,3,4,5]
l2 = [[3, 4, 5, 2, 4],[3, 5, 1, 2, 4], [4, 3, 2, 1, 5]]
l3 = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
</code></pre>
<p>I need to perform a search such that </p>
<ol>
<li><p>Beginning with l2[0] if the pointer l2[0] hits l2[0], search through l1 to find l1[i] == the first value of l2[0]. </p></li>
<li><p>Once the first value of l2[0] use l3 to assign its corresponding value. </p></li>
<li><p>Since the size of the arrays in l2[0] are 5 members we are going to assign a corresponding value of 1 to l3 a maximum of five times. Once we have hit that target we're moving onto the next set l2[1]. </p></li>
<li><p>Once we are done with l2[0] (so on to l2[1]) we need to assign the next corresponding value, so 2, without over-writing the values in l3.</p></li>
</ol>
<p><strong>Illustration...</strong> </p>
<p>Imagine these are baseball scoring cards... I have l1 baseball cards in my deck. The compositions of baseball scoring cards I want in my hands are contained in l2. These cards will win me the game! In this case l2 = [1,2,3,4,5]. I'm a massive cheater and must find all l2 in l1 (cards for hands). Finding l2 in l1 I mark where they are using l3. I also use l3 to tell me which hand to put them in. </p>
<p>To be a valid solution we must uniquely pair up the values in l2 such that they are uniquely identified as values in l1 using l3. This would mean...</p>
<pre><code>l1 = [1,2,3,4,5,1,2,3,4,5]
l2 = [[1,2,3,4,5],[1,2,3,4,5]]
l3 = [1,1,1,1,1,2,2,2,2,2]
</code></pre>
<p>Would be valid. But...</p>
<pre><code>l1 = [1,2,3,4,5,1,2,3,4,5]
l2 = [[1,2,3,4,5],[1,2,3,4,5]]
l3 = [1,2,1,1,1,2,2,1,2,2]
</code></pre>
<p>Would be invalid because there is no hand in l2 containing [2,1,2,4,5] in any order.</p>
<p><strong>Example</strong> </p>
<p>From l2[0] we are going to iterate through l1 over and over and pick up all the objects in l2[0] and sign them off to l3. This should then look like (by hand)...</p>
<pre><code>l1 = [1,2,3,4,5,1,2,3,4,5,1,2,3,4,5]
l2 = [[3, 4, 5, 2, 4],[3, 5, 1, 2, 4], [4, 3, 2, 1, 5]]
l3 = [0,0,1,1,1,0,1,0,1,0,0,0,0,0,0]
</code></pre>
<p>The value 1 has been assigned in l3 since these are the first instances of the corresponding values we come across. We are done with l2[0] now because we have found all of its items in l1. The next job is l2[1]...</p>
<pre><code>l1 = [1,2,3,4,5,1,2,3,4,5,1,2,3,4,5]
l2 = [[3, 4, 5, 2, 4],[3, 5, 1, 2, 4], [4, 3, 2, 1, 5]]
l3 = [2,2,1,1,1,0,1,0,1,0,0,0,2,2,2]
</code></pre>
<p>This is what I've cooked up but to no avail...</p>
<pre><code>assignvar = 1
pos = 0
for x in l2:
for y in x:
for z in l1:
while userpos < len(l1):
if y == z:
l1[pos] = assignvar
while l2_size == pos:
assignvar += 1
l2_size = l2_size+l2_size #stops pos going out of range, changes assignvar to 2 (so appending the next set of l3 iterables to 2 .etc)
userpos = userpos+1
</code></pre>
<p>Really quite confounded how to approach this issue in my code. I feel like I have the right idea using the three for loops but I've been hitting this with my wrench for a while now and completely burned out. </p>
<p><strong>Real world input dataset...</strong></p>
<pre><code>l1 = [5005.0, 5002.5, 5003.0, 5003.0, 5003.5, 5002.5, 5003.5, 5004.0, 5004.5, 5004.0, 5002.5, 5005.0, 5004.5, 5004.0, 5005.0, 5002.5, 5003.5, 5004.0, 5002.5, 5002.5, 5004.0, 5004.0, 5003.5, 5001.5, 5001.5, 5005.0, 5003.0, 5005.0, 5003.5, 5000.5, 5002.5, 5003.5, 5005.0]
l2 = [[5002.5, 5004.0], [5002.5, 5004.5], [5002.5, 5004.0], [5002.5, 5005.0], [5002.5, 5004.5], [5002.5, 5004.0], [5002.5, 5005.0], [5002.5, 5004.0], [5002.5, 5004.0], [5002.5, 5004.0], [5002.5, 5005.0], [5002.5, 5005.0], [5002.5, 5005.0], [5003.0, 5003.5], [5003.0, 5003.5], [5003.0, 5004.0], [5003.0, 5004.5], [5003.0, 5004.0], [5003.0, 5005.0], [5003.0, 5004.5], [5003.0, 5004.0], [5003.0, 5005.0], [5003.0, 5003.5], [5003.0, 5004.0], [5003.0, 5004.0], [5003.0, 5004.0], [5003.0, 5003.5], [5003.0, 5005.0], [5003.0, 5005.0], [5003.0, 5003.5], [5003.0, 5003.5], [5003.0, 5005.0], [5003.0, 5003.5], [5003.0, 5003.5], [5003.0, 5004.0], [5003.0, 5004.5], [5003.0, 5004.0], [5003.0, 5005.0], [5003.0, 5004.5], [5003.0, 5004.0], [5003.0, 5005.0], [5003.0, 5003.5], [5003.0, 5004.0], [5003.0, 5004.0], [5003.0, 5004.0], [5003.0, 5003.5], [5003.0, 5005.0], [5003.0, 5005.0], [5003.0, 5003.5], [5003.0, 5003.5], [5003.0, 5005.0], [5002.5, 5004.0], [5002.5, 5004.5], [5002.5, 5004.0], [5002.5, 5005.0], [5002.5, 5004.5], [5002.5, 5004.0], [5002.5, 5005.0], [5002.5, 5004.0], [5002.5, 5004.0], [5002.5, 5004.0], [5002.5, 5005.0], [5002.5, 5005.0], [5002.5, 5005.0], [5002.5, 5005.0], [5002.5, 5004.5], [5002.5, 5004.0], [5002.5, 5005.0], [5002.5, 5004.0], [5002.5, 5004.0], [5002.5, 5004.0], [5002.5, 5005.0], [5002.5, 5005.0], [5002.5, 5005.0], [5002.5, 5004.0], [5002.5, 5004.0], [5002.5, 5004.0], [5002.5, 5005.0], [5002.5, 5005.0], [5002.5, 5005.0], [5002.5, 5004.0], [5002.5, 5004.0], [5002.5, 5005.0], [5002.5, 5005.0], [5002.5, 5005.0], [5002.5, 5004.0], [5002.5, 5004.0], [5002.5, 5005.0], [5002.5, 5005.0], [5002.5, 5005.0], [5001.5, 5005.0], [5001.5, 5005.0], [5001.5, 5005.0], [5001.5, 5005.0], [5001.5, 5005.0], [5001.5, 5005.0], [5003.0, 5005.0], [5003.0, 5003.5], [5003.0, 5003.5], [5003.0, 5005.0], [5002.5, 5005.0]]
l3=[]
for i in range(len(l1)):
l3.append(int(0))
</code></pre>
| 0 | 2016-07-30T19:24:55Z | 38,706,624 | <p>Still a little hazy on the specs but try this - it works for the simple case of <code>l1 = [1,2,3,4,5,1,2,3,4,5]</code> and <code>l2 = [[1,2,3,4,5],[1,2,3,4,5]]</code>.</p>
<pre><code>used_indices = set()
def get_next_index(card, l1 = l1, used_indices = used_indices):
try:
# find the next index that has not been used
index = l1.index(card)
while index in used_indices:
# if the index has already been used, find the next one
index = l1.index(card, index + 1)
except ValueError as e:
# this card cannot be found
print('hand:{}, card:{} not found'.format(hand_no, card))
index = None
return index
for hand_no, hand in enumerate(l2, 1):
for card in hand:
index = get_next_index(card)
if index:
l3[index] = hand_no
used_indices.add(index)
</code></pre>
| 0 | 2016-08-01T19:25:01Z | [
"python",
"arrays",
"iterable"
] |
Matching up iterables in lists, having significant difficulty | 38,677,714 | <p>For a personal project I have three lists. One of these contains a set of arrays (l2) the size of which is always determined by a setting l2_size and always contains random members of l1. The next array, l3, on the other hand will always be a set of 0's of quantity len(l1).</p>
<p>This means...</p>
<pre><code>l1 = [1,2,3,4,5,1,2,3,4,5,1,2,3,4,5]
l2 = [[3, 4, 5, 2, 4],[3, 5, 1, 2, 4], [4, 3, 2, 1, 5]]
l3 = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
</code></pre>
<p>I need to perform a search such that </p>
<ol>
<li><p>Beginning with l2[0] if the pointer l2[0] hits l2[0], search through l1 to find l1[i] == the first value of l2[0]. </p></li>
<li><p>Once the first value of l2[0] use l3 to assign its corresponding value. </p></li>
<li><p>Since the size of the arrays in l2[0] are 5 members we are going to assign a corresponding value of 1 to l3 a maximum of five times. Once we have hit that target we're moving onto the next set l2[1]. </p></li>
<li><p>Once we are done with l2[0] (so on to l2[1]) we need to assign the next corresponding value, so 2, without over-writing the values in l3.</p></li>
</ol>
<p><strong>Illustration...</strong> </p>
<p>Imagine these are baseball scoring cards... I have l1 baseball cards in my deck. The compositions of baseball scoring cards I want in my hands are contained in l2. These cards will win me the game! In this case l2 = [1,2,3,4,5]. I'm a massive cheater and must find all l2 in l1 (cards for hands). Finding l2 in l1 I mark where they are using l3. I also use l3 to tell me which hand to put them in. </p>
<p>To be a valid solution we must uniquely pair up the values in l2 such that they are uniquely identified as values in l1 using l3. This would mean...</p>
<pre><code>l1 = [1,2,3,4,5,1,2,3,4,5]
l2 = [[1,2,3,4,5],[1,2,3,4,5]]
l3 = [1,1,1,1,1,2,2,2,2,2]
</code></pre>
<p>Would be valid. But...</p>
<pre><code>l1 = [1,2,3,4,5,1,2,3,4,5]
l2 = [[1,2,3,4,5],[1,2,3,4,5]]
l3 = [1,2,1,1,1,2,2,1,2,2]
</code></pre>
<p>Would be invalid because there is no hand in l2 containing [2,1,2,4,5] in any order.</p>
<p><strong>Example</strong> </p>
<p>From l2[0] we are going to iterate through l1 over and over and pick up all the objects in l2[0] and sign them off to l3. This should then look like (by hand)...</p>
<pre><code>l1 = [1,2,3,4,5,1,2,3,4,5,1,2,3,4,5]
l2 = [[3, 4, 5, 2, 4],[3, 5, 1, 2, 4], [4, 3, 2, 1, 5]]
l3 = [0,0,1,1,1,0,1,0,1,0,0,0,0,0,0]
</code></pre>
<p>The value 1 has been assigned in l3 since these are the first instances of the corresponding values we come across. We are done with l2[0] now because we have found all of its items in l1. The next job is l2[1]...</p>
<pre><code>l1 = [1,2,3,4,5,1,2,3,4,5,1,2,3,4,5]
l2 = [[3, 4, 5, 2, 4],[3, 5, 1, 2, 4], [4, 3, 2, 1, 5]]
l3 = [2,2,1,1,1,0,1,0,1,0,0,0,2,2,2]
</code></pre>
<p>This is what I've cooked up but to no avail...</p>
<pre><code>assignvar = 1
pos = 0
for x in l2:
for y in x:
for z in l1:
while userpos < len(l1):
if y == z:
l1[pos] = assignvar
while l2_size == pos:
assignvar += 1
l2_size = l2_size+l2_size #stops pos going out of range, changes assignvar to 2 (so appending the next set of l3 iterables to 2 .etc)
userpos = userpos+1
</code></pre>
<p>Really quite confounded how to approach this issue in my code. I feel like I have the right idea using the three for loops but I've been hitting this with my wrench for a while now and completely burned out. </p>
<p><strong>Real world input dataset...</strong></p>
<pre><code>l1 = [5005.0, 5002.5, 5003.0, 5003.0, 5003.5, 5002.5, 5003.5, 5004.0, 5004.5, 5004.0, 5002.5, 5005.0, 5004.5, 5004.0, 5005.0, 5002.5, 5003.5, 5004.0, 5002.5, 5002.5, 5004.0, 5004.0, 5003.5, 5001.5, 5001.5, 5005.0, 5003.0, 5005.0, 5003.5, 5000.5, 5002.5, 5003.5, 5005.0]
l2 = [[5002.5, 5004.0], [5002.5, 5004.5], [5002.5, 5004.0], [5002.5, 5005.0], [5002.5, 5004.5], [5002.5, 5004.0], [5002.5, 5005.0], [5002.5, 5004.0], [5002.5, 5004.0], [5002.5, 5004.0], [5002.5, 5005.0], [5002.5, 5005.0], [5002.5, 5005.0], [5003.0, 5003.5], [5003.0, 5003.5], [5003.0, 5004.0], [5003.0, 5004.5], [5003.0, 5004.0], [5003.0, 5005.0], [5003.0, 5004.5], [5003.0, 5004.0], [5003.0, 5005.0], [5003.0, 5003.5], [5003.0, 5004.0], [5003.0, 5004.0], [5003.0, 5004.0], [5003.0, 5003.5], [5003.0, 5005.0], [5003.0, 5005.0], [5003.0, 5003.5], [5003.0, 5003.5], [5003.0, 5005.0], [5003.0, 5003.5], [5003.0, 5003.5], [5003.0, 5004.0], [5003.0, 5004.5], [5003.0, 5004.0], [5003.0, 5005.0], [5003.0, 5004.5], [5003.0, 5004.0], [5003.0, 5005.0], [5003.0, 5003.5], [5003.0, 5004.0], [5003.0, 5004.0], [5003.0, 5004.0], [5003.0, 5003.5], [5003.0, 5005.0], [5003.0, 5005.0], [5003.0, 5003.5], [5003.0, 5003.5], [5003.0, 5005.0], [5002.5, 5004.0], [5002.5, 5004.5], [5002.5, 5004.0], [5002.5, 5005.0], [5002.5, 5004.5], [5002.5, 5004.0], [5002.5, 5005.0], [5002.5, 5004.0], [5002.5, 5004.0], [5002.5, 5004.0], [5002.5, 5005.0], [5002.5, 5005.0], [5002.5, 5005.0], [5002.5, 5005.0], [5002.5, 5004.5], [5002.5, 5004.0], [5002.5, 5005.0], [5002.5, 5004.0], [5002.5, 5004.0], [5002.5, 5004.0], [5002.5, 5005.0], [5002.5, 5005.0], [5002.5, 5005.0], [5002.5, 5004.0], [5002.5, 5004.0], [5002.5, 5004.0], [5002.5, 5005.0], [5002.5, 5005.0], [5002.5, 5005.0], [5002.5, 5004.0], [5002.5, 5004.0], [5002.5, 5005.0], [5002.5, 5005.0], [5002.5, 5005.0], [5002.5, 5004.0], [5002.5, 5004.0], [5002.5, 5005.0], [5002.5, 5005.0], [5002.5, 5005.0], [5001.5, 5005.0], [5001.5, 5005.0], [5001.5, 5005.0], [5001.5, 5005.0], [5001.5, 5005.0], [5001.5, 5005.0], [5003.0, 5005.0], [5003.0, 5003.5], [5003.0, 5003.5], [5003.0, 5005.0], [5002.5, 5005.0]]
l3=[]
for i in range(len(l1)):
l3.append(int(0))
</code></pre>
| 0 | 2016-07-30T19:24:55Z | 38,806,985 | <p>I simplified the solution by creating two arrays extra arrays called a "configuration space" which are assigned boolean true (represented by the integer 1) depending on a number (a card) has been assigned to a hand or a member of the subset (a hand) has already been assigned to a card. </p>
<p>This solution makes one trip over l2, then makes a trip through l1, and assigns a card to a hand in l3 only if both the hand and card are unassigned (as indicated 0 in each array in configuration space). </p>
<pre><code>l1 = [1,2,3,4,5,1,2,3,4,5,1,2,3,4,5] #Total number of players
l2 = [[3, 4, 5, 2, 4],[3, 5, 1, 2, 4], [4, 3, 2, 1, 5]] #Possible teams
l3 = [] #Assigned teams
for i in range(len(l1)):
l3.append(int(0))
##############################################################################################################################################################
#Configuration space. Responsible for indicating whether (a) a player from l1 has been assigned to a team or (b) a team has already been assigned to a player#
##############################################################################################################################################################
playerbase_configurationspace = []
matchmadeteams_configurationspace = [] #detects if value in l2 has been assigned (if going over a number which has been given value 1 but we need to give it value 2)
for i in range(len(l1)):
playerbase_configurationspace.append(int(0))
for x in l2:
for y in x:
matchmadeteams_configurationspace.append(int(0))
teamsize = len(l2[0])
teamcount = len(l2[0])
assignteam = 1 #Base no. of teams to be assigned
################################
#Flatten list of lists##########
################################
matchmadeteams_processed = []
for x in l2:
for y in x:
matchmadeteams_processed.append(y)
####################################################################################################################################
#Teammate handler: makes lookups into the configuration space to help determine whether either a player has been assigned to a team#
####################################################################################################################################
def teammate_handler(isnotfreeplayer,isnotfreeslot, assignteam):
if playerbase_configurationspace[isnotfreeplayer] == 0 and matchmadeteams_configurationspace[isnotfreeslot] == 0:
playerbase_configurationspace[isnotfreeplayer] = 1
matchmadeteams_configurationspace[isnotfreeslot] = 1
return int(1), assignteam #Outcome 1, safe to add player to empty slot, assign == value to be assigned
#else either, player is set team, teammate of team is set team (or both):: do nothing
elif playerbase_configurationspace[isnotfreeplayer] == 1 and matchmadeteams_configurationspace[isnotfreeslot] == 0:
return int(2) #Outcome 2, continue the for loop iterating through players since the player is not free but the slot is free
elif playerbase_configurationspace[isnotfreeplayer] == 0 and matchmadeteams_configurationspace[isnotfreeslot] == 1:
return int(3) #Outcome 3, break the for loop iterating through slots and players since the slot is not free
elif playerbase_configurationspace[isnotfreeplayer] == 1 and matchmadeteams_configurationspace[isnotfreeslot] == 1:
return int(4)
return int(5) #Unexpected error (catch all)
###############################
for teammatepos in enumerate(matchmadeteams_processed):
print(teamcount)
if teamcount == 0:
assignteam += 1
teamcount = teamsize
for playerpos in enumerate(l1):
if playerpos[1] == teammatepos[1]:
print("Match, using player"+str(playerpos)+" teammate"+str(teammatepos))
print ()
print ("Teammate "+str(teammatepos), matchmadeteams_processed)
print ("Player "+str(playerpos), l1)
print ("")
if teammate_handler(playerpos[0], teammatepos[0], assignteam) == (1, assignteam):
l3[playerpos[0]] = assignteam
print ("I have assigned teams to this player")
else:
continue
else:
continue
teamcount -= 1
print(l3)
</code></pre>
| 0 | 2016-08-06T17:32:37Z | [
"python",
"arrays",
"iterable"
] |
Display Web cam Python | 38,677,741 | <p>I have this code for web cam and should be displayed in the window (designed in Qt designer) this code works well but now i have two cam windows, one in my Main window (form designed in Qt Designer) and one out of the Main window. </p>
<pre><code>def b1_clicked(self):
mycam = cv2.VideoCapture(0)
if mycam.isOpened():
_, frame = mycam.read()
else:
_, frame = False
while (True):
cv2.imshow("preview", frame)
_, frame = mycam.read()
frame = cv2.cvtColor(frame, cv2.cv.CV_BGR2RGB)
image = QtGui.QImage(frame, frame.shape[1], frame.shape[0],frame.strides[0], QtGui.QImage.Format_RGB888)
self.label.setPixmap(QtGui.QPixmap.fromImage(image))
key = cv2.waitKey(20)
if key == 27: # escape ESC
break
</code></pre>
<p>Please any suggestion how to kill and make it not visible the form which is out of the Main window.<br>
Thanks </p>
| 0 | 2016-07-30T19:28:03Z | 38,689,244 | <p>Comment out cv2.imshow which opens its own window.</p>
| 0 | 2016-07-31T23:27:32Z | [
"python",
"opencv",
"qt-designer"
] |
heroku does not load jquery on https | 38,677,808 | <p>i have an app deployed to heroku and i request the jquery to be loaded</p>
<pre><code><script src="//www.highcharts.com/lib/jquery-1.7.2.js" type="text/javascript"></script>
</code></pre>
<p>in order to use highcharts. But when running my app on http the charts are not loaded,whereas when running the app on http the charts are loaded.</p>
<p>the message when running on https is:</p>
<p>"but requested an insecure script '<a href="http://www.highcharts.com/lib/jquery-1.7.2.js" rel="nofollow">http://www.highcharts.com/lib/jquery-1.7.2.js</a>'. This request has been blocked; the content must be served over HTTPS."</p>
<p>how can i safely load jquery?</p>
| 0 | 2016-07-30T19:37:05Z | 38,677,829 | <p>www.highcharts.com doesn't seem to support HTTPS, so you'll need to load jQuery from somewhere else.</p>
<p>Try one of the options here: <a href="http://code.jquery.com/" rel="nofollow">http://code.jquery.com/</a>. Or you could download the copy of jQuery you're using and just include it in your app.</p>
<p><strong>EDIT</strong></p>
<p>Further explanation: when you load <a href="https://www.highcharts.com/lib/jquery-1.7.2.js" rel="nofollow">https://www.highcharts.com/lib/jquery-1.7.2.js</a> (you can try it in the browser), you get redirected to <a href="http://www.highcharts.com/lib/jquery-1.7.2.js" rel="nofollow">http://www.highcharts.com/lib/jquery-1.7.2.js</a>. So the browser is ultimately loading the script from an HTTP source. You need to load from an HTTPS source.</p>
| 2 | 2016-07-30T19:39:53Z | [
"javascript",
"python",
"html",
"heroku",
"highcharts"
] |
How to sort half of the 2d array in descending order (numpy) | 38,678,057 | <p>I'm trying to create an array (10000, 50) size (I'm mentioning the size because efficiency is important), and then : </p>
<ul>
<li>Sort the first 5000 rows in ascending order </li>
<li>Sort the next 5000 rows in descending order.</li>
</ul>
<p>Here is my code : </p>
<pre><code>samples = 10 # I'm going to increase it 10000
sampleLength = 4 # I'm going to increase it 50
halfSamples = int(samples/2)
xx = numpy.multiply(10, numpy.random.random((samples, sampleLength)))
xx[0:halfSamples,0:sampleLength]=numpy.sort(xx[0:halfSamples,0:sampleLength],axis=1)
xx[halfSamples:samples,0:sampleLength]=numpy.sort(xx[halfSamples:samples,0:sampleLength],axis=1)
</code></pre>
<p>This sorts both half of the array in ascending order, the only thing I can't find is what parameter to give in my last line to make it in a descending order.</p>
<p>I've tried based on this link : <a href="http://stackoverflow.com/questions/27054368/reverse-sort-a-2d-numpy-array-in-python">Reverse sort a 2d numpy array in python</a> </p>
<pre><code>xx[halfSamples:samples,0:sampleLength]=numpy.sort(xx[halfSamples:samples,0:sampleLength:-1],axis=1)
</code></pre>
<p>But got an error : </p>
<pre><code>ValueError: could not broadcast input array from shape (5,0) into shape (5,4)
</code></pre>
<p>Thanks</p>
| 3 | 2016-07-30T20:10:05Z | 38,678,185 | <p>It would probably be faster to sort the array in place using its <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.sort.html" rel="nofollow"><code>.sort</code></a> method, rather than <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.sort.html" rel="nofollow"><code>np.sort</code></a> which returns a copy. You can index the second dimension using a negative step size to sort the columns of the last 5000 rows in descending order:</p>
<pre><code>x = np.random.randn(10000, 50)
x[:5000].sort(axis=1)
x[-5000:, ::-1].sort(axis=1)
</code></pre>
| 4 | 2016-07-30T20:25:24Z | [
"python",
"arrays",
"sorting",
"numpy"
] |
Showing both the value and index in the x-ticks in a plot | 38,678,085 | <p>I want to plot something using <code>plot(x,y)</code> and be able to see on the plot the index of the value in <code>x</code></p>
<p>For example.</p>
<pre><code>x = [10,30,100,120]
y = [16,17,19,3]
plot(x,y)
</code></pre>
<p>will show </p>
<p><a href="http://i.stack.imgur.com/C2IKz.png" rel="nofollow"><img src="http://i.stack.imgur.com/C2IKz.png" alt="enter image description here"></a></p>
<p>looking at the plot it is hard to know at every point what was the original index. For example I want to be able to know when looking at the point (100,19) that it is index 2, since <code>x[2]=100</code> and <code>y[2]=19</code>.
How do I do that in matplotlib.
I looked at <code>twiny()</code> function but that seems to just add another axes disregarding the distance between points in x.</p>
| 1 | 2016-07-30T20:13:35Z | 38,679,797 | <p>Here's my solution:</p>
<pre><code>import matplotlib.pyplot as plt
x = [10,30,100,120]
y = [16,17,19,3]
plt.plot(x,y);
for i, (a, b) in enumerate(zip(x, y)):
plt.annotate(str(i), xy=(a, b), textcoords="offset points", xytext=(0, 12),
horizontalalignment='center', verticalalignment='center')
plt.xlim(0, 130)
plt.ylim(0, 22)
</code></pre>
<p>What it does: it enumerates on your <code>y</code> and <code>x</code> arrays, storing the index in the variable <code>i</code> and the respective values of <code>x</code> and <code>y</code> in the variables <code>a</code> and <code>b</code>. It then annotates the index <code>i</code> at the coordinates <code>(a, b)</code>, offsetting the text by 12 pixels on the y-axis to avoid the annotation covering the curve.</p>
<p>The result:</p>
<p><a href="http://i.stack.imgur.com/CrgSR.png" rel="nofollow"><img src="http://i.stack.imgur.com/CrgSR.png" alt="enter image description here"></a></p>
| 1 | 2016-07-31T00:45:26Z | [
"python",
"matplotlib",
"plot"
] |
Project Euler #18 in Python- Beginner | 38,678,131 | <p>By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23.</p>
<pre><code>3
7 4
2 4 6
8 5 9 3
</code></pre>
<p>That is, 3 + 7 + 4 + 9 = 23.</p>
<p>Find the maximum total from top to bottom of the triangle below:</p>
<pre><code>75
95 64
17 47 82
18 35 87 10
20 04 82 47 65
19 01 23 75 03 34
88 02 77 73 07 63 67
99 65 04 28 06 16 70 92
41 41 26 56 83 40 80 70 33
41 48 72 33 47 32 37 16 94 29
53 71 44 65 25 43 91 52 97 51 14
70 11 33 28 77 73 17 78 39 68 17 57
91 71 52 38 17 14 91 43 58 50 27 29 48
63 66 04 68 89 53 67 30 73 16 69 87 40 31
04 62 98 27 23 09 70 98 73 93 38 53 60 04 23
</code></pre>
<p>NOTE: As there are only 16384 routes, it is possible to solve this problem by trying every route. However, Problem 67, is the same challenge with a triangle containing one-hundred rows; it cannot be solved by brute force, and requires a clever method! ;o)</p>
<p>My code is a bit haywire </p>
<pre><code>a="75, 95 64, 17 47 82, 18 35 87 10, 20 04 82 47 65, 19 01 23 75 03 34, 88 02 77 73 07 63 67, 99 65 04 28 06 16 70 92, 41 41 26 56 83 40 80 70 33, 41 48 72 33 47 32 37 16 94 29, 53 71 44 65 25 43 91 52 97 51 14, 70 11 33 28 77 73 17 78 39 68 17 57, 91 71 52 38 17 14 91 43 58 50 27 29 48, 63 66 04 68 89 53 67 30 73 16 69 87 40 31, 04 62 98 27 23 09 70 98 73 93 38 53 60 04 23"
b=a.split(", ")
d=[]
ans=0
for x in range(len(b)):
b[x]= b[x].split(" ")
c= [int(i) for i in b[x]]
d.append(c)
index= d[0].index(max(d[0]))
print index
for y in range(len(d)):
ans+= d[y][index]
if y+1==len(d):
break
else:
index= d[y+1].index(max(d[y+1][index], d[y+1][index+1]))
print ans
</code></pre>
<p>So I'm getting 1063 as the answer whereas the actual answer is 1074. I guess my approach is right but there's some bug I'm still not able to figure out. </p>
| 1 | 2016-07-30T20:17:59Z | 38,678,170 | <p>It looks like you always choose the larger number (of left and right) in the next line (This is called a <a href="https://en.wikipedia.org/wiki/Greedy_algorithm" rel="nofollow">greedy algorithm</a>.) But maybe choosing the smaller number first, you could choose larger numbers in the subsequent lines. (And indeed, by doing so, 1074 can be achieved.)</p>
<p>The hints in the comments are useful:</p>
<ul>
<li><p>A backtrack approach would give the correct result.</p></li>
<li><p>A dynamic programming approach would give the correct result, and it's faster than the backtrack, thus it can work for problem 67 as well.</p></li>
</ul>
| 0 | 2016-07-30T20:23:19Z | [
"python"
] |
Project Euler #18 in Python- Beginner | 38,678,131 | <p>By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23.</p>
<pre><code>3
7 4
2 4 6
8 5 9 3
</code></pre>
<p>That is, 3 + 7 + 4 + 9 = 23.</p>
<p>Find the maximum total from top to bottom of the triangle below:</p>
<pre><code>75
95 64
17 47 82
18 35 87 10
20 04 82 47 65
19 01 23 75 03 34
88 02 77 73 07 63 67
99 65 04 28 06 16 70 92
41 41 26 56 83 40 80 70 33
41 48 72 33 47 32 37 16 94 29
53 71 44 65 25 43 91 52 97 51 14
70 11 33 28 77 73 17 78 39 68 17 57
91 71 52 38 17 14 91 43 58 50 27 29 48
63 66 04 68 89 53 67 30 73 16 69 87 40 31
04 62 98 27 23 09 70 98 73 93 38 53 60 04 23
</code></pre>
<p>NOTE: As there are only 16384 routes, it is possible to solve this problem by trying every route. However, Problem 67, is the same challenge with a triangle containing one-hundred rows; it cannot be solved by brute force, and requires a clever method! ;o)</p>
<p>My code is a bit haywire </p>
<pre><code>a="75, 95 64, 17 47 82, 18 35 87 10, 20 04 82 47 65, 19 01 23 75 03 34, 88 02 77 73 07 63 67, 99 65 04 28 06 16 70 92, 41 41 26 56 83 40 80 70 33, 41 48 72 33 47 32 37 16 94 29, 53 71 44 65 25 43 91 52 97 51 14, 70 11 33 28 77 73 17 78 39 68 17 57, 91 71 52 38 17 14 91 43 58 50 27 29 48, 63 66 04 68 89 53 67 30 73 16 69 87 40 31, 04 62 98 27 23 09 70 98 73 93 38 53 60 04 23"
b=a.split(", ")
d=[]
ans=0
for x in range(len(b)):
b[x]= b[x].split(" ")
c= [int(i) for i in b[x]]
d.append(c)
index= d[0].index(max(d[0]))
print index
for y in range(len(d)):
ans+= d[y][index]
if y+1==len(d):
break
else:
index= d[y+1].index(max(d[y+1][index], d[y+1][index+1]))
print ans
</code></pre>
<p>So I'm getting 1063 as the answer whereas the actual answer is 1074. I guess my approach is right but there's some bug I'm still not able to figure out. </p>
| 1 | 2016-07-30T20:17:59Z | 38,678,252 | <p>Your approach is incorrect. You can't just do a greedy algorithm. Consider the example:</p>
<pre><code>3
7 4
2 4 6
8 5 9 500
</code></pre>
<p>Clearly:</p>
<pre><code>3 + 7 + 4 + 9 = 23 < 500 + (other terms here)
</code></pre>
<p>Yet you follow this algorithm.</p>
<p>However if the triangle were just:</p>
<pre><code>3
7 4
</code></pre>
<p>The greedy approach works, in other words, we need to <strong>reduce</strong> the problem to a kind of "3 number" triangle. So, assume the path you follow gets to <code>6</code>, what choice should be made? Go to <code>500</code>. (What happens if the apath goes to <code>4</code>? What about <code>2</code>?)</p>
<p>How can we use these results to make a smaller triangle?</p>
| 1 | 2016-07-30T20:36:07Z | [
"python"
] |
Project Euler #18 in Python- Beginner | 38,678,131 | <p>By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23.</p>
<pre><code>3
7 4
2 4 6
8 5 9 3
</code></pre>
<p>That is, 3 + 7 + 4 + 9 = 23.</p>
<p>Find the maximum total from top to bottom of the triangle below:</p>
<pre><code>75
95 64
17 47 82
18 35 87 10
20 04 82 47 65
19 01 23 75 03 34
88 02 77 73 07 63 67
99 65 04 28 06 16 70 92
41 41 26 56 83 40 80 70 33
41 48 72 33 47 32 37 16 94 29
53 71 44 65 25 43 91 52 97 51 14
70 11 33 28 77 73 17 78 39 68 17 57
91 71 52 38 17 14 91 43 58 50 27 29 48
63 66 04 68 89 53 67 30 73 16 69 87 40 31
04 62 98 27 23 09 70 98 73 93 38 53 60 04 23
</code></pre>
<p>NOTE: As there are only 16384 routes, it is possible to solve this problem by trying every route. However, Problem 67, is the same challenge with a triangle containing one-hundred rows; it cannot be solved by brute force, and requires a clever method! ;o)</p>
<p>My code is a bit haywire </p>
<pre><code>a="75, 95 64, 17 47 82, 18 35 87 10, 20 04 82 47 65, 19 01 23 75 03 34, 88 02 77 73 07 63 67, 99 65 04 28 06 16 70 92, 41 41 26 56 83 40 80 70 33, 41 48 72 33 47 32 37 16 94 29, 53 71 44 65 25 43 91 52 97 51 14, 70 11 33 28 77 73 17 78 39 68 17 57, 91 71 52 38 17 14 91 43 58 50 27 29 48, 63 66 04 68 89 53 67 30 73 16 69 87 40 31, 04 62 98 27 23 09 70 98 73 93 38 53 60 04 23"
b=a.split(", ")
d=[]
ans=0
for x in range(len(b)):
b[x]= b[x].split(" ")
c= [int(i) for i in b[x]]
d.append(c)
index= d[0].index(max(d[0]))
print index
for y in range(len(d)):
ans+= d[y][index]
if y+1==len(d):
break
else:
index= d[y+1].index(max(d[y+1][index], d[y+1][index+1]))
print ans
</code></pre>
<p>So I'm getting 1063 as the answer whereas the actual answer is 1074. I guess my approach is right but there's some bug I'm still not able to figure out. </p>
| 1 | 2016-07-30T20:17:59Z | 38,679,464 | <p>You can reach each cell only from the adjacent (at most) three cells on the top line, and the most favorable will be the one with the highest number among these, you don't need to keep track of the others. </p>
<p>I put an example of the code. This works for the pyramid aligned to the left as in your question (the original problem is with a centered pyramid, but at least I don't completely spoil the problem). Max total for my case is 1116:</p>
<pre><code>d="""
75
95 64
17 47 82
18 35 87 10
20 04 82 47 65
19 01 23 75 03 34
88 02 77 73 07 63 67
99 65 04 28 06 16 70 92
41 41 26 56 83 40 80 70 33
41 48 72 33 47 32 37 16 94 29
53 71 44 65 25 43 91 52 97 51 14
70 11 33 28 77 73 17 78 39 68 17 57
91 71 52 38 17 14 91 43 58 50 27 29 48
63 66 04 68 89 53 67 30 73 16 69 87 40 31
04 62 98 27 23 09 70 98 73 93 38 53 60 04 23
"""
ll=[line.split() for line in d.split('\n')][1:-1]
topline=ll[0]
for line in ll[1:]:
newline=[]
for i,cell in enumerate(line):
newline.append(int(cell)+max(map(int,topline[max([0,i-1]):min([len(line),i+2])])))
topline=newline
print newline
print "final results is %i"%max(newline)
</code></pre>
| 0 | 2016-07-30T23:34:37Z | [
"python"
] |
Use Pandas dataframe to add lag feature from MultiIindex Series | 38,678,246 | <p>I have a MultiIndex Series (3 indices) that looks like this:</p>
<pre><code>Week ID_1 ID_2
3 26 1182 39.0
4767 42.0
31393 20.0
31690 42.0
32962 3.0
....................................
</code></pre>
<p>I also have a dataframe <code>df</code> which contains all the columns (and more) used for indices in the Series above, and I want to create a new column in my dataframe <code>df</code> that contains the value matching the <code>ID_1</code> and <code>ID_2</code> and the <code>Week - 2</code> from the Series.</p>
<p>For example, for the row in dataframe that has <code>ID_1 = 26</code>, <code>ID_2 = 1182</code> and <code>Week = 3</code>, I want to match the value in the Series indexed by <code>ID_1 = 26</code>, <code>ID_2 = 1182</code> and <code>Week = 1</code> (3-2) and put it on that row in a new column. Further, my Series might not necessarily have the value required by the dataframe, in which case I'd like to just have 0.</p>
<p>Right now, I am trying to do this by using:</p>
<pre><code>[multiindex_series.get((x[1].get('week', 2) - 2, x[1].get('ID_1', 0), x[1].get('ID_2', 0))) for x in df.iterrows()]
</code></pre>
<p>This however is very slow and memory hungry and I was wondering what are some better ways to do this.</p>
<p>FWIW, the Series was created using</p>
<pre><code>saved_groupby = df.groupby(['Week', 'ID_1', 'ID_2'])['Target'].median()
</code></pre>
<p>and I'm willing to do it a different way if better paths exist to create what I'm looking for.</p>
| 1 | 2016-07-30T20:34:57Z | 38,678,549 | <p>Increase the <code>Week</code> by 2:</p>
<pre><code>saved_groupby = df.groupby(['Week', 'ID_1', 'ID_2'])['Target'].median()
saved_groupby = saved_groupby.reset_index()
saved_groupby['Week'] = saved_groupby['Week'] + 2
</code></pre>
<p>and then merge <code>df</code> with <code>saved_groupby</code>:</p>
<pre><code>result = pd.merge(df, saved_groupby, on=['Week', 'ID_1', 'ID_2'], how='left')
</code></pre>
<p>This will augment <code>df</code> with the target median from 2 weeks ago.
To make the median (target) <code>saved_groupby</code> column 0 when there is no match, use <code>fillna</code> to change NaNs to 0:</p>
<pre><code>result['Median'] = result['Median'].fillna(0)
</code></pre>
<hr>
<p>For example,</p>
<pre><code>import numpy as np
import pandas as pd
np.random.seed(2016)
df = pd.DataFrame(np.random.randint(5, size=(20,5)),
columns=['Week', 'ID_1', 'ID_2', 'Target', 'Foo'])
saved_groupby = df.groupby(['Week', 'ID_1', 'ID_2'])['Target'].median()
saved_groupby = saved_groupby.reset_index()
saved_groupby['Week'] = saved_groupby['Week'] + 2
saved_groupby = saved_groupby.rename(columns={'Target':'Median'})
result = pd.merge(df, saved_groupby, on=['Week', 'ID_1', 'ID_2'], how='left')
result['Median'] = result['Median'].fillna(0)
print(result)
</code></pre>
<p>yields</p>
<pre><code> Week ID_1 ID_2 Target Foo Median
0 3 2 3 4 2 0.0
1 3 3 0 3 4 0.0
2 4 3 0 1 2 0.0
3 3 4 1 1 1 0.0
4 2 4 2 0 3 2.0
5 1 0 1 4 4 0.0
6 2 3 4 0 0 0.0
7 4 0 0 2 3 0.0
8 3 4 3 2 2 0.0
9 2 2 4 0 1 0.0
10 2 0 4 4 2 0.0
11 1 1 3 0 0 0.0
12 0 1 0 2 0 0.0
13 4 0 4 0 3 4.0
14 1 2 1 3 1 0.0
15 3 0 1 3 4 2.0
16 0 4 2 2 4 0.0
17 1 1 4 4 2 0.0
18 4 1 0 3 0 0.0
19 1 0 1 0 0 0.0
</code></pre>
| 3 | 2016-07-30T21:13:30Z | [
"python",
"pandas",
"dataframe",
"data-science"
] |
SqlAlchemy: How to implement DROP TABLE ... CASCADE? | 38,678,336 | <p>I need to drop tables in a PostgreSQL database that have foreign key constraints and require <code>DROP TABLE ... CASCADE</code>.</p>
<p>I could execute raw SQL: <code>engine.execute("DROP TABLE %s CASCADE;" % table.name)</code>.
However, I would like to implement this behaviour such that I can do <code>table.drop(engine)</code> for the <code>postgresql</code> dialect.</p>
<p>How would one approach this?</p>
| 1 | 2016-07-30T20:45:17Z | 38,678,459 | <p>You need the data in <code>pg_constraint</code>, which is <a href="https://www.postgresql.org/docs/current/static/catalog-pg-constraint.html" rel="nofollow">a rather complicated table</a>, that handles all constraints, including check constraints and foreign keys. Fortunately, what you want is fairly straightforward.</p>
<p>In order to get the list of all of the tables referencing table <code>foo</code>, you can do something like:</p>
<pre><code>SELECT conrelid
FROM pg_constraint
WHERE confrelid = <the relid for foo>;
</code></pre>
<p>That gets you a list of table relids. But you probably don't want to deal with relids, so let's make it a bit more complicated:</p>
<pre><code>SELECT r.schemaname || '.' || r.relname
FROM pg_stat_user_tables r, pg_constraint c, pg_stat_user_tables s
WHERE
s.relid = c.confrelid AND
c.conrelid = r.relid AND
s.relname = 'foo';
</code></pre>
<p>That returns a list which you can then loop through and issue individual <code>DROP TABLE</code> statements.</p>
| 1 | 2016-07-30T21:01:32Z | [
"python",
"postgresql",
"sqlalchemy"
] |
SqlAlchemy: How to implement DROP TABLE ... CASCADE? | 38,678,336 | <p>I need to drop tables in a PostgreSQL database that have foreign key constraints and require <code>DROP TABLE ... CASCADE</code>.</p>
<p>I could execute raw SQL: <code>engine.execute("DROP TABLE %s CASCADE;" % table.name)</code>.
However, I would like to implement this behaviour such that I can do <code>table.drop(engine)</code> for the <code>postgresql</code> dialect.</p>
<p>How would one approach this?</p>
| 1 | 2016-07-30T20:45:17Z | 38,679,457 | <p>You can <a href="http://docs.sqlalchemy.org/en/latest/core/compiler.html#changing-compilation-of-types" rel="nofollow">customize the compilation of constructs</a> like this:</p>
<pre><code>from sqlalchemy.schema import DropTable
from sqlalchemy.ext.compiler import compiles
@compiles(DropTable, "postgresql")
def _compile_drop_table(element, compiler, **kwargs):
return compiler.visit_drop_table(element) + " CASCADE"
</code></pre>
<p>This appends <code>CASCADE</code> to the <code>DROP TABLE</code> statement issued for the postgresql dialect while keeping all other dialects the same.</p>
| 2 | 2016-07-30T23:34:18Z | [
"python",
"postgresql",
"sqlalchemy"
] |
Python 3 parse PDF from web | 38,678,377 | <p>I was trying to get a PDF from a webpage, parse it and print the result to the screen using <a href="https://github.com/mstamy2/PyPDF2" rel="nofollow">PyPDF2</a>. I got it working without issues with the following code:</p>
<pre><code>with open("foo.pdf", "wb") as f:
f.write(requests.get(buildurl(jornal, date, page)).content)
pdfFileObj = open('foo.pdf', "rb")
pdf_reader = PyPDF2.PdfFileReader(pdfFileObj)
page_obj = pdf_reader.getPage(0)
print(page_obj.extractText())
</code></pre>
<p>Writing a file just so I can then read it though sounded wasteful, so I figured I'd just cut the middleman with this:</p>
<pre><code>pdf_reader = PyPDF2.PdfFileReader(requests.get(buildurl(jornal, date, page)).content)
page_obj = pdf_reader.getPage(0)
print(page_obj.extractText())
</code></pre>
<p>This, however yields me an <code>AttributeError: 'bytes' object has no attribute 'seek'</code>. How can I feed the PDF coming from <code>requests</code> directly onto PyPDF2?</p>
| 0 | 2016-07-30T20:50:59Z | 38,678,451 | <p>Use io to fake the use of a file (Python 3):</p>
<pre><code>import io
output = io.BytesIO()
output.write(requests.get(buildurl(jornal, date, page)).content)
output.seek(0)
pdf_reader = PyPDF2.PdfFileReader(output)
</code></pre>
<p>I did not test in your context but I tested this simple example and it worked:</p>
<pre><code>import io
output = io.BytesIO()
output.write(bytes("hello world","ascii"))
output.seek(0)
print(output.read())
</code></pre>
<p>yields:</p>
<pre><code>b'hello world'
</code></pre>
| 0 | 2016-07-30T21:00:22Z | [
"python",
"pdf",
"python-requests",
"pypdf2"
] |
Python 3 parse PDF from web | 38,678,377 | <p>I was trying to get a PDF from a webpage, parse it and print the result to the screen using <a href="https://github.com/mstamy2/PyPDF2" rel="nofollow">PyPDF2</a>. I got it working without issues with the following code:</p>
<pre><code>with open("foo.pdf", "wb") as f:
f.write(requests.get(buildurl(jornal, date, page)).content)
pdfFileObj = open('foo.pdf', "rb")
pdf_reader = PyPDF2.PdfFileReader(pdfFileObj)
page_obj = pdf_reader.getPage(0)
print(page_obj.extractText())
</code></pre>
<p>Writing a file just so I can then read it though sounded wasteful, so I figured I'd just cut the middleman with this:</p>
<pre><code>pdf_reader = PyPDF2.PdfFileReader(requests.get(buildurl(jornal, date, page)).content)
page_obj = pdf_reader.getPage(0)
print(page_obj.extractText())
</code></pre>
<p>This, however yields me an <code>AttributeError: 'bytes' object has no attribute 'seek'</code>. How can I feed the PDF coming from <code>requests</code> directly onto PyPDF2?</p>
| 0 | 2016-07-30T20:50:59Z | 38,678,468 | <p>You have to convert the returned <code>content</code> to a file-like object using <code>BytesIO</code>:</p>
<pre><code>import io
pdf_content = io.BytesIO(requests.get(buildurl(jornal, date, page)).content)
pdf_reader = PyPDF2.PdfFileReader(pdf_content)
</code></pre>
| 1 | 2016-07-30T21:03:11Z | [
"python",
"pdf",
"python-requests",
"pypdf2"
] |
How to wait for response from modal window before continuing using tkinter? | 38,678,415 | <p>I have a python program in which I've created a few custom modal windows that are children of a top level tkinter window. An example of such a window is below, but I have other, more complicated ones. What I would like to do, but cannot determine how, is to have somewhere that I call this and wait for a response. I've tried something like below, it fails to create the window</p>
<pre><code>modal = ModalWindow(tk.Tk(), 'Title', 'Text')
while modal.choice is None:
pass
if modal.choice == 'Yes':
# Do Something
</code></pre>
<p>What is the appropriate way to handle this type of thing?</p>
<p><strong>Custom Modal Window Example</strong></p>
<pre><code>class ModalWindow(object):
def __init__(self, root, title, text):
self.choice = None
# Setup the window
self.modalWindow = tk.Toplevel(root)
self.modalWindow.title(title)
self.modalWindow.resizable(False, False)
# Setup the widgets in the window
label = ttk.Label(self.modalWindow, text = text, font = '-size 10')
label.grid(row = 0, column = 0, columnspan = 2, padx = 2, pady = 2)
but = ttk.Button(self.modalWindow, text = 'Yes', command = self.choiceYes)
but.grid(row = 1, column = 0, sticky = 'nsew', padx = 2, pady = 5)
but = ttk.Button(self.modalWindow, text = 'No', command = self.choiceNo)
but.grid(row = 1, column = 1, sticky = 'nsew', padx = 2, pady = 5)
self.modalWindow.rowconfigure(1, minsize = 40)
def choiceYes(self):
self.choice = 'Yes'
self.modalWindow.destroy()
def choiceNo(self):
self.choice = 'No'
self.modalWindow.destroy()
</code></pre>
| 0 | 2016-07-30T20:55:22Z | 38,679,126 | <p>After some further digging, I found my own answer. The following does what I want. The function <code>wait_window</code> accepts a tkinter window and pauses until that window has been closed.</p>
<pre><code>root = tk.Tk()
modal = ModalWindow(root, 'Title', 'Text')
root.wait_window(modal.modalWindow)
if modal.choice == 'Yes':
# Do Something
</code></pre>
| 1 | 2016-07-30T22:39:20Z | [
"python",
"tkinter",
"modal-dialog"
] |
How to wait for response from modal window before continuing using tkinter? | 38,678,415 | <p>I have a python program in which I've created a few custom modal windows that are children of a top level tkinter window. An example of such a window is below, but I have other, more complicated ones. What I would like to do, but cannot determine how, is to have somewhere that I call this and wait for a response. I've tried something like below, it fails to create the window</p>
<pre><code>modal = ModalWindow(tk.Tk(), 'Title', 'Text')
while modal.choice is None:
pass
if modal.choice == 'Yes':
# Do Something
</code></pre>
<p>What is the appropriate way to handle this type of thing?</p>
<p><strong>Custom Modal Window Example</strong></p>
<pre><code>class ModalWindow(object):
def __init__(self, root, title, text):
self.choice = None
# Setup the window
self.modalWindow = tk.Toplevel(root)
self.modalWindow.title(title)
self.modalWindow.resizable(False, False)
# Setup the widgets in the window
label = ttk.Label(self.modalWindow, text = text, font = '-size 10')
label.grid(row = 0, column = 0, columnspan = 2, padx = 2, pady = 2)
but = ttk.Button(self.modalWindow, text = 'Yes', command = self.choiceYes)
but.grid(row = 1, column = 0, sticky = 'nsew', padx = 2, pady = 5)
but = ttk.Button(self.modalWindow, text = 'No', command = self.choiceNo)
but.grid(row = 1, column = 1, sticky = 'nsew', padx = 2, pady = 5)
self.modalWindow.rowconfigure(1, minsize = 40)
def choiceYes(self):
self.choice = 'Yes'
self.modalWindow.destroy()
def choiceNo(self):
self.choice = 'No'
self.modalWindow.destroy()
</code></pre>
| 0 | 2016-07-30T20:55:22Z | 38,679,640 | <p>I am missing something fundamental here. If the window is application-modal, you're forced to wait: there's nothing programmatic to be done. If you're trying to wait for an event that transpires in a window belonging to ANOTHER application, you're hosed unless you write some thorny OLE code (I assume Windows here, as UNIX way of doing things would never lead one eve to consider such a solution component).</p>
| 0 | 2016-07-31T00:11:34Z | [
"python",
"tkinter",
"modal-dialog"
] |
Pyplot: changing color depending on class | 38,678,431 | <p>I have an array of values with their associated class labels (0 or 1). I'd like to change the colour of the plotted values based on their class labels.
I'm using the matplotlib.pyplot plot function to plot the values:</p>
<pre><code>plt.plot(data[0])
</code></pre>
<p>For each value the associated class labels are stored in an separate array of the same length as the data array.</p>
<p>The current plot looks like this:
<a href="http://i.stack.imgur.com/jFbmj.png" rel="nofollow"><img src="http://i.stack.imgur.com/jFbmj.png" alt="enter image description here"></a></p>
<p>The areas in between the red lines should be coloured differently.</p>
| 0 | 2016-07-30T20:56:51Z | 38,678,560 | <p>You could split it in two different data sets:</p>
<pre><code>xx0 = class_labels == 0
xx1 = class_labels == 1
data_class_0 = data[0].copy()
data_class_0[xx1] = np.nan
data_class_1 = data[0].copy()
data_class_1[xx0] = np.nan
plt.plot(data_class_0, 'b')
plt.plot(data_class_1, 'r')
</code></pre>
| 1 | 2016-07-30T21:15:22Z | [
"python",
"matplotlib",
"classification"
] |
Random list generates as blocks not individual lines | 38,678,465 | <p>I am attempting to write a piece of code which does probability calculations based on the National lottery.
But I am having an issue with the way the code runs.<br>
It prints out each one 5 times rather than creating a new set of random numbers, does anyone know why?</p>
<pre><code>gen = True
while gen == True:
#Generate Numbers
a = random.randint(1,59)
b = random.randint(1,59)
c = random.randint(1,59)
d = random.randint(1,59)
e = random.randint(1,59)
f = random.randint(1,59)
#Create tickets as lists
ticket = []
balls = []
#print the tickets
for i in ticket:
g = ticket[0]
h = ticket[1]
i = ticket[2]
j = ticket[3]
k = ticket[4]
l = ticket[5]
for i in balls:
m = balls[0]
n = balls[1]
o = balls[2]
p = balls[3]
q = balls[4]
r = balls[5]
print("TICKET")
print(g,h,i,j,k,l)
time.sleep(4)
print("BALLS")
print(m,n,o,p,q,r)
</code></pre>
<p>Thank you to anyone that can, it is greatly appreciated.</p>
| 1 | 2016-07-30T21:02:36Z | 38,678,522 | <p>i'm not sure i understood the purpose of this program, However i saw you printed the <code>g,h,i,j,k,l</code> variables in the second loop, causing the last iteration values to be printed with the same value.</p>
<p>If the purpose is to print these values, place the ticket print in the tickets for loop:</p>
<pre><code>for i in ticket:
g = ticket[0]
h = ticket[1]
i = ticket[2]
j = ticket[3]
k = ticket[4]
l = ticket[5]
print("TICKET")
print(g,h,i,j,k,l)
for i in balls:
m = balls[0]
n = balls[1]
o = balls[2]
p = balls[3]
q = balls[4]
r = balls[5]
print("BALLS")
print(m,n,o,p,q,r)
</code></pre>
| 0 | 2016-07-30T21:09:40Z | [
"python",
"loops",
"numbers"
] |
Combining lists from function that returns lists using list comprehensions | 38,678,486 | <p>I want to populate three lists: <code>A</code>, <code>B</code> and <code>C</code></p>
<p>I have a function that based on a singular input returns N objects that should append to each list. That is, <code>f</code> returns <code>stuff_for_A</code>, <code>stuff_for_B</code>, <code>stuff_for_C</code> where each <code>stuff</code> is a list containing N items. I want to <em>join</em> each of those to their respective lists as I loop over the iterable that sends input to <code>f</code>.</p>
<p>How can I write a super fast list comprehension to create these 3 lists?</p>
<p>Note: I can restructure the output of <code>f</code> (such as zipping the items together) if that makes things easier.</p>
<p>EDIT: Here's some pseudo-code with the bottom list comprehension being incorrect.</p>
<pre><code>def f(input):
x = precompute(input)
stuff_for_A = create_A_list(x)
stuff_for_B = create_B_list(x)
stuff_for_C = create_C_list(x)
return stuff_for_A,stuff_for_B,stuff_for_C
A,B,C = [f(input) for input in iterable]
</code></pre>
| 0 | 2016-07-30T21:04:43Z | 38,678,652 | <p>Extend A, B, C directly, without returning things?</p>
<pre><code>iterable = range(10)
A, B, C = [], [], []
def f(item):
A.extend([item * 2])
B.extend([item * 3])
C.extend([item * 4])
map(f, iterable)
print A
print B
print C
</code></pre>
<p><a href="https://repl.it/Chl6" rel="nofollow">https://repl.it/Chl6</a></p>
<p>(I use <code>.extend()</code> with lists inside because your functions return lists, otherwise use <code>A.add(thing)</code> to add individual things. I also renamed <code>input</code> to <code>item</code> because <code>input()</code> is a built-in function in Python)</p>
| 0 | 2016-07-30T21:26:35Z | [
"python",
"python-2.7"
] |
Combining lists from function that returns lists using list comprehensions | 38,678,486 | <p>I want to populate three lists: <code>A</code>, <code>B</code> and <code>C</code></p>
<p>I have a function that based on a singular input returns N objects that should append to each list. That is, <code>f</code> returns <code>stuff_for_A</code>, <code>stuff_for_B</code>, <code>stuff_for_C</code> where each <code>stuff</code> is a list containing N items. I want to <em>join</em> each of those to their respective lists as I loop over the iterable that sends input to <code>f</code>.</p>
<p>How can I write a super fast list comprehension to create these 3 lists?</p>
<p>Note: I can restructure the output of <code>f</code> (such as zipping the items together) if that makes things easier.</p>
<p>EDIT: Here's some pseudo-code with the bottom list comprehension being incorrect.</p>
<pre><code>def f(input):
x = precompute(input)
stuff_for_A = create_A_list(x)
stuff_for_B = create_B_list(x)
stuff_for_C = create_C_list(x)
return stuff_for_A,stuff_for_B,stuff_for_C
A,B,C = [f(input) for input in iterable]
</code></pre>
| 0 | 2016-07-30T21:04:43Z | 38,678,664 | <p>It appears that you want the same result as</p>
<pre><code>A = [create_A_list(input) for input in iterable]
B = [create_B_list(input) for input in iterable]
C = [create_C_list(input) for input in iterable]
</code></pre>
<p>but with only one pass over <code>iterable</code>. With an explicit <code>for</code> loop, you would use</p>
<pre><code>A = []
B = []
C = []
for input in iterable:
A.append(create_A_input(input))
B.append(create_B_input(input))
C.append(create_C_input(input))
</code></pre>
<p>With a single list comprehension, you can get a list of triples:</p>
<pre><code>triples = [ (create_A_input(input),
create_B_input(input),
create_C_input(input)) for input in iterable ]
</code></pre>
<p>which you could then transpose into a triple of lists:</p>
<pre><code>A, B, C = map(list, zip(*[(create_A_input(input),
create_B_input(input),
create_C_input(input)) for input in iterable]))
</code></pre>
<p>Your original <code>f</code> function returns a triple, so you can use use that in place of the triple in the preceding:</p>
<pre><code>A, B, C = map(list, zip(*[f(input) for input in iterable)]))
</code></pre>
| 1 | 2016-07-30T21:28:39Z | [
"python",
"python-2.7"
] |
Combining lists from function that returns lists using list comprehensions | 38,678,486 | <p>I want to populate three lists: <code>A</code>, <code>B</code> and <code>C</code></p>
<p>I have a function that based on a singular input returns N objects that should append to each list. That is, <code>f</code> returns <code>stuff_for_A</code>, <code>stuff_for_B</code>, <code>stuff_for_C</code> where each <code>stuff</code> is a list containing N items. I want to <em>join</em> each of those to their respective lists as I loop over the iterable that sends input to <code>f</code>.</p>
<p>How can I write a super fast list comprehension to create these 3 lists?</p>
<p>Note: I can restructure the output of <code>f</code> (such as zipping the items together) if that makes things easier.</p>
<p>EDIT: Here's some pseudo-code with the bottom list comprehension being incorrect.</p>
<pre><code>def f(input):
x = precompute(input)
stuff_for_A = create_A_list(x)
stuff_for_B = create_B_list(x)
stuff_for_C = create_C_list(x)
return stuff_for_A,stuff_for_B,stuff_for_C
A,B,C = [f(input) for input in iterable]
</code></pre>
| 0 | 2016-07-30T21:04:43Z | 38,678,670 | <p>To create the lists from the <em>returned</em> tuples, you can use that multiple assignment with <code>zip</code> and <em>unpacking</em> on a generator expression:</p>
<pre><code>def f(input):
...
return stuff_for_A,stuff_for_B,stuff_for_C
A, B, C = zip(*(f(input) for input in iterable))
</code></pre>
<p>This will return the respective items for each list grouped in 3 tuples.</p>
<hr>
<p><em>Trial:</em></p>
<pre><code>>>> A, B, C = zip(*[(1,2,3), (4,5,6), ('x', 'y', 'z'), (8,9,0)])
>>> A
(1, 4, 'x', 8)
>>> B
(2, 5, 'y', 9)
>>> C
(3, 6, 'z', 0)
</code></pre>
<p>To return them as lists instead, you can use a <em>list comprehension</em> with the previous operation:</p>
<pre><code>>>> A, B, C = [list(i) for i in zip(*[(1,2,3), (4,5,6), ('x', 'y', 'z'), (8,9,0)])]
>>> A
[1, 4, 'x', 8]
>>> B
[2, 5, 'y', 9]
>>> C
[3, 6, 'z', 0]
</code></pre>
<hr>
<p>In the event the function returns a tuple of 3 iterables, then you can use <code>itertools.chain</code> to flatten the results from <code>zip</code>:</p>
<pre><code>from itertools import chain
A, B, C = (list(chain.from_iterable(i))
for i in zip(*(f(input)
for input in iterable)))
</code></pre>
| 1 | 2016-07-30T21:29:07Z | [
"python",
"python-2.7"
] |
Combining lists from function that returns lists using list comprehensions | 38,678,486 | <p>I want to populate three lists: <code>A</code>, <code>B</code> and <code>C</code></p>
<p>I have a function that based on a singular input returns N objects that should append to each list. That is, <code>f</code> returns <code>stuff_for_A</code>, <code>stuff_for_B</code>, <code>stuff_for_C</code> where each <code>stuff</code> is a list containing N items. I want to <em>join</em> each of those to their respective lists as I loop over the iterable that sends input to <code>f</code>.</p>
<p>How can I write a super fast list comprehension to create these 3 lists?</p>
<p>Note: I can restructure the output of <code>f</code> (such as zipping the items together) if that makes things easier.</p>
<p>EDIT: Here's some pseudo-code with the bottom list comprehension being incorrect.</p>
<pre><code>def f(input):
x = precompute(input)
stuff_for_A = create_A_list(x)
stuff_for_B = create_B_list(x)
stuff_for_C = create_C_list(x)
return stuff_for_A,stuff_for_B,stuff_for_C
A,B,C = [f(input) for input in iterable]
</code></pre>
| 0 | 2016-07-30T21:04:43Z | 38,678,672 | <p>If <code>A</code>, <code>B</code>, and <code>C</code> exist, the following will update them with the returned values from <code>f</code>:</p>
<p><code>list(map(lambda x: x[0].extend(x[1]), zip([A,B,C], f())))</code></p>
<p><code>list</code> is called, cause <code>map</code> is lazy in python 3.</p>
| 1 | 2016-07-30T21:29:30Z | [
"python",
"python-2.7"
] |
Merge every dataframe in a folder | 38,678,520 | <p>I have <code>.csv</code> files within multiple folders which look like this:</p>
<p>File1</p>
<pre><code>Count 2002_Crop_1 2002_Crop_2 Ecoregion
20 Corn Soy 46
15 Barley Oats 46
</code></pre>
<p>File 2</p>
<pre><code>Count 2003_Crop_1 2003_Crop_2 Ecoregion
24 Corn Soy 46
18 Barley Oats 46
</code></pre>
<p>for each folder I want to merge all of the files within.</p>
<p>My desired output would be something like this:</p>
<pre><code>Crop_1 Crop_2 2002_Count 2003_Count Ecoregion
Corn Soy 20 24 46
Barley Oats 15 18 46
</code></pre>
<p>In reality there are 10 files in each folder, not just 2, that need to be merged.</p>
<p>I am using this code as of now:</p>
<pre><code>import pandas as pd, os
#pathway to all the folders
folders=r'G:\Stefano\CDL_Trajectory\combined_eco_folders'
for folder in os.listdir(folders):
for f in os.listdir(os.path.join(folders,folder)):
dfs=pd.read_csv(os.path.join(folders,folder,f)) #turn each file from each folder into a dataframe
df = reduce(lambda left,right: pd.merge(left,right,on=[dfs[dfs.columns[1]], dfs[dfs.columns[2]]],how='outer'),dfs) #merge all the dataframes based on column location
</code></pre>
<p>but this returns:
<code>
TypeError: string indices must be integers, not Series</code></p>
| 1 | 2016-07-30T21:09:00Z | 38,678,829 | <ul>
<li><p>Use <code>glob.glob</code> to <a href="http://stackoverflow.com/a/7159726/190597">traverse a directory at a fixed depth</a>.</p></li>
<li><p>Try to avoid calling <code>pd.merge</code> repeatedly if you can help it. Each call to <code>pd.merge</code> creates a new DataFrame. So all the data in each intermediate result has to be copied into the new DataFrame. Doing this in a loop leads to <a href="http://stackoverflow.com/a/36489724/190597">quadratic copying</a>, which is bad for performance.</p></li>
<li><p>If you do some column name wrangling to change, for instance,</p>
<pre><code>['Count', '2002_Crop_1', '2002_Crop_2', 'Ecoregion']
</code></pre>
<p>to </p>
<pre><code>['2002_Count', 'Crop_1', 'Crop_2', 'Ecoregion']
</code></pre>
<p>then you can use <code>['Crop_1', 'Crop_2', 'Ecoregion']</code> as the index for each DataFrame, and combine all the DataFrames <em>with one call</em> to <code>pd.concat</code>.</p></li>
</ul>
<hr>
<pre><code>import pandas as pd
import glob
folders=r'G:\Stefano\CDL_Trajectory\combined_eco_folders'
dfs = []
for filename in glob.glob(os.path.join(folders, *['*']*2)):
df = pd.read_csv(filename, sep='\s+')
columns = [col.split('_', 1) for col in df.columns]
prefix = next(col[0] for col in columns if len(col) > 1)
columns = [col[1] if len(col) > 1 else col[0] for col in columns]
df.columns = columns
df = df.set_index([col for col in df.columns if col != 'Count'])
df = df.rename(columns={'Count':'{}_Count'.format(prefix)})
dfs.append(df)
result = pd.concat(dfs, axis=1)
result = result.sortlevel(axis=1)
result = result.reset_index()
print(result)
</code></pre>
<p>yields</p>
<pre><code> Crop_1 Crop_2 Ecoregion 2002_Count 2003_Count
0 Corn Soy 46 20 24
1 Barley Oats 46 15 18
</code></pre>
| 2 | 2016-07-30T21:54:52Z | [
"python",
"csv",
"pandas"
] |
Saving Add to cart items in django models | 38,678,623 | <p>So I am creating something like an e-commerce platform. I am building the project using Django.</p>
<p>Now I have to make an Add to Cart feature. How should I make the model so that I can store the things added to the cart in my table that is connected to user table using foreignkey.</p>
<p>Specifically, I want to know that what kind of field should I define in my wishlist model to save the items added to cart.</p>
| 0 | 2016-07-30T21:23:00Z | 38,678,798 | <p>There is no sense to store such information on a backend. I most cases you can use <code>cookies</code> or <code>localstorage</code>.</p>
<p>But if you want store this information for registered users, device independent, you should create Model with FK to users table and Use that.</p>
<p><strong>Answer:</strong>
Use M2M relation <code>user</code> > <code>m2m with fields</code> > <code>item</code>
In additional data you can store quanity, order time etc...</p>
<p><a href="https://docs.djangoproject.com/en/dev/topics/db/models/#extra-fields-on-many-to-many-relationships" rel="nofollow">Aboud M2M with extra fields</a> -- django docs</p>
| 0 | 2016-07-30T21:48:36Z | [
"python",
"django",
"django-models",
"e-commerce",
"cart"
] |
Iterate in 2 different dictionaries simultaneously in Python | 38,678,686 | <p>---EDIT 2---
So I get the question Why I use dictionaries?,
this question is a follow up on this one: <a href="http://stackoverflow.com/questions/38647250/csv-file-compression-without-using-existing-libraries-in-python/38662750#38662750">csv file compression without using existing libraries in Python</a></p>
<p>I Need to compress a 500k csv file (19MB), and I chose to use dictionary to store the ticks in one csv file and symbs in another to be able to Decompress the values </p>
<p><strong>QUESTION</strong>: How do I iterate the most optimized way? this is just an example of 4 rows, but my real file has 500 000 lines, and takes me for ever to iterate through the list.</p>
<p>I have 3 dictionaries:</p>
<pre><code>originalDict = {
0: ['6NH8', 'F', 'A', '0', '60541567', '60541567', '78.78', '20'],
1: ['6NH8', 'F', 'A', '0', '60541569', '60541569', '78.78', '25'],
2: ['6AH8', 'F', 'B', '0', '60541765', '60541765', '90.52', '1'],
3: ['QMH8', 'F', 'B', '0', '60437395', '60437395', '950.5', '1']
}
ticks = {0: '6NH8', 1: '6AH8', 2: 'QMH8'}
symbs = {0: 'F,A', 1: 'F,B'}
</code></pre>
<p>I want to iterate through originalDict and change the "ticks" and then the symbs at <code>index 1</code> and <code>index 2</code> and then remove <code>index 2</code></p>
<p>so, i.e. </p>
<pre><code>0: ['6NH8', 'F', 'A', '0', '60541567', '60541567', '78.78', '20']
</code></pre>
<p>becomes:</p>
<pre><code>[0, '0', '0', '60541567', '60541567', '78.78', '20']
</code></pre>
<p>I have currently a for loop going through values in originalDict, and inside that another for loop:</p>
<pre><code>for values in originalDict.values():
for ticksKey, ticksValue in ticks.items():
if values[0] == ticksValue:
values[0] = ticksKey
#Change symbs and remove char combination
for symbsKey, symbsValue in symbs.items():
comprComb = values[1] + "," + values[2]
if comprComb == symbsValue:
values[1] = str(symbsKey)
#del values[4]
#del values[4]
del values[2]
</code></pre>
<p>ADDITIONAL INFO ADDED:
The reason I have them as dictionary is because the 500 000 lines, some of the ticks occurs more than once, so, I give them a int which is the key in the dict, so goes for the symbs dictionary too. </p>
| 1 | 2016-07-30T21:32:11Z | 38,678,779 | <p>You can speed up the lookup by inverting the keys and values in the <code>ticks</code> and <code>symbs</code> dicts and then just looking up the right values instead of iterating and comparing all the values in the dicts:</p>
<pre><code>ticks_inv = {v: k for k, v in ticks.items()}
symbs_inv = {v: k for k, v in symbs.items()}
for values in originalDict.values():
if values[0] in ticks_inv:
values[0] = ticks_inv[values[0]]
comprComb = "{v[1]},{v[2]}".format(v=values)
if comprComb in symbs_inv:
values[1] = symbs_inv[comprComb]
del values[2]
</code></pre>
<p>Result is the same as with your code, but should be much faster, particularly if <code>ticks</code> and <code>symbs</code> are large. Of course, this assumes that the values are unique, but if otherwise your code would not work correctly ether.</p>
| 0 | 2016-07-30T21:45:35Z | [
"python",
"list",
"for-loop",
"dictionary",
"iteration"
] |
Iterate in 2 different dictionaries simultaneously in Python | 38,678,686 | <p>---EDIT 2---
So I get the question Why I use dictionaries?,
this question is a follow up on this one: <a href="http://stackoverflow.com/questions/38647250/csv-file-compression-without-using-existing-libraries-in-python/38662750#38662750">csv file compression without using existing libraries in Python</a></p>
<p>I Need to compress a 500k csv file (19MB), and I chose to use dictionary to store the ticks in one csv file and symbs in another to be able to Decompress the values </p>
<p><strong>QUESTION</strong>: How do I iterate the most optimized way? this is just an example of 4 rows, but my real file has 500 000 lines, and takes me for ever to iterate through the list.</p>
<p>I have 3 dictionaries:</p>
<pre><code>originalDict = {
0: ['6NH8', 'F', 'A', '0', '60541567', '60541567', '78.78', '20'],
1: ['6NH8', 'F', 'A', '0', '60541569', '60541569', '78.78', '25'],
2: ['6AH8', 'F', 'B', '0', '60541765', '60541765', '90.52', '1'],
3: ['QMH8', 'F', 'B', '0', '60437395', '60437395', '950.5', '1']
}
ticks = {0: '6NH8', 1: '6AH8', 2: 'QMH8'}
symbs = {0: 'F,A', 1: 'F,B'}
</code></pre>
<p>I want to iterate through originalDict and change the "ticks" and then the symbs at <code>index 1</code> and <code>index 2</code> and then remove <code>index 2</code></p>
<p>so, i.e. </p>
<pre><code>0: ['6NH8', 'F', 'A', '0', '60541567', '60541567', '78.78', '20']
</code></pre>
<p>becomes:</p>
<pre><code>[0, '0', '0', '60541567', '60541567', '78.78', '20']
</code></pre>
<p>I have currently a for loop going through values in originalDict, and inside that another for loop:</p>
<pre><code>for values in originalDict.values():
for ticksKey, ticksValue in ticks.items():
if values[0] == ticksValue:
values[0] = ticksKey
#Change symbs and remove char combination
for symbsKey, symbsValue in symbs.items():
comprComb = values[1] + "," + values[2]
if comprComb == symbsValue:
values[1] = str(symbsKey)
#del values[4]
#del values[4]
del values[2]
</code></pre>
<p>ADDITIONAL INFO ADDED:
The reason I have them as dictionary is because the 500 000 lines, some of the ticks occurs more than once, so, I give them a int which is the key in the dict, so goes for the symbs dictionary too. </p>
| 1 | 2016-07-30T21:32:11Z | 38,678,794 | <p>So first of all you want to <strong>reverse</strong> the mapping, you are currently looking by value, which is wrong and slow:</p>
<pre><code>ticks = {0: '6NH8', 1: '6AH8', 2: 'QMH8'}
symbs = {0: 'F,A', 1: 'F,B'}
</code></pre>
<p>Using <code>ticks = {v: k for k, v in ticks.items()}</code> (same for <code>symbs</code>):</p>
<pre><code>{'6NH8': 0, 'QMH8': 2, '6AH8': 1} # ticks
{'F,A': 0, 'F,B': 1} # symbs
</code></pre>
<p>Now that you have good data structures you can do this rather fast.</p>
<p>Now transform the dictionary that holds the data to a list (not sure why it is a dictionary to start with):</p>
<pre><code>originalList = [originalDict[k] for k in range(len(originalDict))]
</code></pre>
<p>And re-map values:</p>
<pre><code>for line in originalList:
line[0] = ticks[line[0]]
line[1:3] = [symbs["%s,%s" % tuple(line[1:3])]]
</code></pre>
<p>result:</p>
<pre><code>[[0, 0, '0', '60541567', '60541567', '78.78', '20'], [0, 0, '0', '60541569', '60541569', '78.78', '25'], [1, 1, '0', '60541765', '60541765', '90.52', '1'], [2, 1, '0', '60437395', '60437395', '950.5', '1']]
</code></pre>
| 1 | 2016-07-30T21:48:16Z | [
"python",
"list",
"for-loop",
"dictionary",
"iteration"
] |
Iterate in 2 different dictionaries simultaneously in Python | 38,678,686 | <p>---EDIT 2---
So I get the question Why I use dictionaries?,
this question is a follow up on this one: <a href="http://stackoverflow.com/questions/38647250/csv-file-compression-without-using-existing-libraries-in-python/38662750#38662750">csv file compression without using existing libraries in Python</a></p>
<p>I Need to compress a 500k csv file (19MB), and I chose to use dictionary to store the ticks in one csv file and symbs in another to be able to Decompress the values </p>
<p><strong>QUESTION</strong>: How do I iterate the most optimized way? this is just an example of 4 rows, but my real file has 500 000 lines, and takes me for ever to iterate through the list.</p>
<p>I have 3 dictionaries:</p>
<pre><code>originalDict = {
0: ['6NH8', 'F', 'A', '0', '60541567', '60541567', '78.78', '20'],
1: ['6NH8', 'F', 'A', '0', '60541569', '60541569', '78.78', '25'],
2: ['6AH8', 'F', 'B', '0', '60541765', '60541765', '90.52', '1'],
3: ['QMH8', 'F', 'B', '0', '60437395', '60437395', '950.5', '1']
}
ticks = {0: '6NH8', 1: '6AH8', 2: 'QMH8'}
symbs = {0: 'F,A', 1: 'F,B'}
</code></pre>
<p>I want to iterate through originalDict and change the "ticks" and then the symbs at <code>index 1</code> and <code>index 2</code> and then remove <code>index 2</code></p>
<p>so, i.e. </p>
<pre><code>0: ['6NH8', 'F', 'A', '0', '60541567', '60541567', '78.78', '20']
</code></pre>
<p>becomes:</p>
<pre><code>[0, '0', '0', '60541567', '60541567', '78.78', '20']
</code></pre>
<p>I have currently a for loop going through values in originalDict, and inside that another for loop:</p>
<pre><code>for values in originalDict.values():
for ticksKey, ticksValue in ticks.items():
if values[0] == ticksValue:
values[0] = ticksKey
#Change symbs and remove char combination
for symbsKey, symbsValue in symbs.items():
comprComb = values[1] + "," + values[2]
if comprComb == symbsValue:
values[1] = str(symbsKey)
#del values[4]
#del values[4]
del values[2]
</code></pre>
<p>ADDITIONAL INFO ADDED:
The reason I have them as dictionary is because the 500 000 lines, some of the ticks occurs more than once, so, I give them a int which is the key in the dict, so goes for the symbs dictionary too. </p>
| 1 | 2016-07-30T21:32:11Z | 38,678,817 | <p>Your dictionary is backwards; it's not using the dictionary's key-lookup feature. Instead of </p>
<pre><code>for ticksKey, ticksValue in ticks.items():
if values[0] == ticksValue:
values[0] = ticksKey
</code></pre>
<p>try</p>
<pre><code>ticks = {'6NH8': 0, '6AH8': 1, 'QMH8': 2}
...
if values[0] in ticks:
values[0] = ticks[values[0]]
</code></pre>
<p>A little weirder looking would be just</p>
<pre><code>values[0] = ticks[values[0]] or values[0]
</code></pre>
<p>If you do that, and similarly with <code>symbs</code>, you'll remove all but the necessary outmost loop and see a significant performance improvement. </p>
| 0 | 2016-07-30T21:52:36Z | [
"python",
"list",
"for-loop",
"dictionary",
"iteration"
] |
'module' object has no attribute 'questiоn'. Class name considered an attribute? | 38,678,740 | <p>I'm trying to make a quiz for my project and I'm getting this error: <code>AttributeError: 'module' object has no attribute 'question'</code>. I don't understand why it thinks my class is an attribute. </p>
<ul>
<li><p>questionbf.py is where I made the binary file.</p></li>
<li><p>quizbf.py is where I'm trying to make the quiz scoring right.</p></li>
</ul>
<p>I'm lacking experience in Python so anything at all would be helpful. Thank you.</p>
<p><strong>questionbf.py</strong></p>
<pre><code>import pickle
class question:
def __init__(self,a,b,c):
self.q=a
self.an=b
self.o=c
f1=open("Question.DAT","wb")
n=input("Enter no. of Questions ")
for i in range(n):
a=raw_input("Enter Question ")
b=raw_input("Enter Answer ")
c=raw_input("Enter Options ")
s=question(a,b,c)
pickle.dump(s,f1)
f1.close()
</code></pre>
<p><strong>quizbf.py</strong></p>
<pre><code>import pickle
print '''Welcome to the revision quiz.'''
print
score=0
w=0
c=0
f1=open("Question.DAT","rb")
try:
while True:
s=pickle.load(f1)
print s.q
print s.o
guess=input("Enter Choice ")
if guess==s.a:
print "Correct!!"
print
score=score+1
c=c+1
elif guess=="exit" or guess=="Exit":
break
else:
w=w+1
print "Incorrect. Better luck next time!!"
print
except EOFError:
f1.close()
print s
print w
</code></pre>
<p><strong>Error:</strong></p>
<pre><code>Traceback (most recent call last):
File "C:\Users\RUBY\Desktop\questionbf.py", line 32, in <module>
s=pickle.load(f1)
File "C:\Python27\lib\pickle.py", line 1378, in load
return Unpickler(file).load()
File "C:\Python27\lib\pickle.py", line 858, in load
dispatch[key](self)
File "C:\Python27\lib\pickle.py", line 1069, in load_inst
klass = self.find_class(module, name)
File "C:\Python27\lib\pickle.py", line 1126, in find_class
klass = getattr(mod, name)
AttributeError: 'module' object has no attribute 'question'
</code></pre>
| 0 | 2016-07-30T21:40:35Z | 38,679,161 | <p>When you pickle an instance of a class the class name is saved in the pickle to allow the reading program to import the necessary module and gain access to the required class. Unfortunately the class whose elements you are pickling is in the <code>__main__</code> module, which is the name Python gives to the module that is being executed.</p>
<p>When your second program reads the pickle, it therefore looks for the <code>question</code> class in the <code>__main__</code> module, which this time is the second program. So <code>pickle</code> complains that the given class (<code>__main__</code>) does not contain the required class (a defined class is an attrinute in its module just like a method of a class is an attribute in the class).</p>
<p>The necessary fix is to move the <code>question</code> class to a separate module, which your first program explicitly imports (using something like <code>from new_module import question</code>). Your second program will then know it needs to import <code>new_module</code> in order to access the <code>question</code> class, which it will do automatically (<em>i.e.</em> with no need to explicitly import it).</p>
| 0 | 2016-07-30T22:44:46Z | [
"python",
"python-2.7"
] |
Batch executed by Python script is acting like it is in the script's folder | 38,678,745 | <p>I run the batch(it is in different folder than the python script) the using following line of code:</p>
<pre><code>subprocess.Popen("the_bat.bat", creationflags=subprocess.CREATE_NEW_CONSOLE)
</code></pre>
<p>The job of the batch is to launch a .jar(same directory as batch) which creates folders and files in it's directory, but when run by the python script the jar starts doing it's job in the script's folder.
Any suggestions on how to prevent this?</p>
| -2 | 2016-07-30T21:40:53Z | 38,679,019 | <p>This is because the bash script is executed in Python's working directory, which makes the bash script's working directory the same one as Python's. You can fix this by passing a current working directory to the <code>subprocess.Popen</code>.</p>
<p><code>subprocess.Popen(r'your script', cwd=r'd:\the\working\directory\you\want\or\root')</code></p>
| 0 | 2016-07-30T22:23:22Z | [
"python",
"windows",
"batch-file",
"jar"
] |
AttributeError: 'unicode' object has no attribute 'isPalindrome' | 38,678,784 | <p>I'm new to Python thus the question,</p>
<p>I'm trying to solve a simple algorithmic problem of finding the longest palindromic substring given a string.</p>
<p>This is my code.</p>
<pre><code>class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
curr = 0
for i, c in enumerate(s):
for j in range(len(s)):
sub = s[i:i+j]
if sub.isPalindrome():
curr = max(curr, len(sub))
return curr
def isPalindrome(self, s):
for i, c in enumerate(s):
if c != s[-i -1]:
return False
return True
</code></pre>
<p>I get the error,</p>
<pre><code>AttributeError: 'unicode' object has no attribute 'isPalindrome'
</code></pre>
<p>If I change the call to this,</p>
<pre><code> if isPalindrome(sub):
curr = max(curr, len(sub))
</code></pre>
<p>I get the following error,</p>
<pre><code>NameError: global name 'isPalindrome' is not defined
</code></pre>
<p>Can someone help me understand what's going wrong and how can I fix it?</p>
| 0 | 2016-07-30T21:46:27Z | 38,678,799 | <p>You should call the method using the <em>self</em> reference. That would be:</p>
<pre><code>if self.isPalindrome(sub):
curr = max(curr, len(sub))
</code></pre>
<p><code>sub.isPalindrome()</code> will not work because the method is not bound to the unicode/string object</p>
| 1 | 2016-07-30T21:48:49Z | [
"python"
] |
Close a tkinter GUI after a period of time | 38,678,859 | <p>I want to create a GUI that shows a message and it is automatically destroyed after some time. I saw this question in different posts but none of the solutions proposed worked out for my App. Here a small part of the code</p>
<pre><code>class MessageShort(tkSimpleDialog.Dialog):
def __init__(self, parent, text, time):
self.top=Toplevel.__init__(self, parent)
self.transient(parent)
self.parent = parent
self.text=text
self.time=time
body = Frame(self)
self.initial_focus = self.body(body)
body.pack(padx=10, pady=10)
if not self.initial_focus:
self.initial_focus = self
self.geometry("+%d+%d" % (parent.winfo_rootx()+200,
parent.winfo_rooty()+75))
self.initial_focus.focus_set()
self.wait_window(self)
def body(self, master):
m=Message(master, text=self.text).grid(row=0,column=0,sticky=W)
master.after(self.time,master.destroy())
MessageShort(root,"Select date and decimal format",2000)#call from another part to the class to create the GUI message
root = Tk()
app = App(root) #main App
root.mainloop()
</code></pre>
<p>The App have different Menus and Tkinter classes to display the different tools
With the current code I close the App and I just want to close the message but not the App</p>
| 0 | 2016-07-30T21:58:12Z | 38,679,044 | <p>Create a timer and set destroying the root as it's callback:</p>
<pre><code>from threading import Timer
import time
def called_after_timer():
if(root != None):
root.destroy()
t = Timer(20 * 60, called_after_timeout)
t.start()
# do something else, such as
time.sleep(1500)
</code></pre>
| 0 | 2016-07-30T22:27:33Z | [
"python",
"tkinter",
"destroy"
] |
Close a tkinter GUI after a period of time | 38,678,859 | <p>I want to create a GUI that shows a message and it is automatically destroyed after some time. I saw this question in different posts but none of the solutions proposed worked out for my App. Here a small part of the code</p>
<pre><code>class MessageShort(tkSimpleDialog.Dialog):
def __init__(self, parent, text, time):
self.top=Toplevel.__init__(self, parent)
self.transient(parent)
self.parent = parent
self.text=text
self.time=time
body = Frame(self)
self.initial_focus = self.body(body)
body.pack(padx=10, pady=10)
if not self.initial_focus:
self.initial_focus = self
self.geometry("+%d+%d" % (parent.winfo_rootx()+200,
parent.winfo_rooty()+75))
self.initial_focus.focus_set()
self.wait_window(self)
def body(self, master):
m=Message(master, text=self.text).grid(row=0,column=0,sticky=W)
master.after(self.time,master.destroy())
MessageShort(root,"Select date and decimal format",2000)#call from another part to the class to create the GUI message
root = Tk()
app = App(root) #main App
root.mainloop()
</code></pre>
<p>The App have different Menus and Tkinter classes to display the different tools
With the current code I close the App and I just want to close the message but not the App</p>
| 0 | 2016-07-30T21:58:12Z | 38,683,158 | <p>Finally I got something that seems to work</p>
<p>class MessageShort(tkSimpleDialog.Dialog):</p>
<pre><code> def __init__(self, parent, text, time):
self.top=Toplevel.__init__(self, parent)
self.transient(parent)
self.parent = parent
self.text=text
self.time=time
body = Frame(self)
self.initial_focus = self.body(body)
body.pack(padx=10, pady=10)
if not self.initial_focus:
self.initial_focus = self
self.geometry("+%d+%d" % (parent.winfo_rootx()+200,
parent.winfo_rooty()+75))
self.initial_focus.focus_set()
self.wait_window(self)
def body(self, master):
m=Message(master, text=self.text).grid(row=0,column=0,sticky=W)
master.after(self.time,self.destroy)
MessageShort(root,"Select date and decimal format",2000)#call from another part to the class to create the GUI message
root = Tk()
app = App(root) #main App
root.mainloop()
</code></pre>
<p>In the last line self.master.destroy destroys m but not the container itself. So it has to call to self.destroy</p>
| 0 | 2016-07-31T10:45:13Z | [
"python",
"tkinter",
"destroy"
] |
Middleware in flask | 38,678,864 | <p>I just stated using Flask and was trying to implement a small feature in my project. The objective is to set a cookie only if the request comes from a authenticated user.</p>
<p>I found two ways of doing this. </p>
<p>First method</p>
<pre><code>@app.before_request
def before_request():
# set cookie if user is logged in
</code></pre>
<p>Second method, by implementing something like this
<a href="https://ohadp.com/adding-a-simple-middleware-to-your-flask-application-in-1-minutes-89782de379a1#.xq8zafufd" rel="nofollow">adding-a-simple-middleware-to-your-flask-application</a></p>
<p>Can someone explain to me what are the main differences between the two methods and when and where which method should be used.</p>
<p>Also, I am currently using "flask-login" to keep track of the logged in user.
If I use the first method, I can easily verify if someone is logged in by importing the current_user</p>
<pre><code>from flask.ext.login import current_user
</code></pre>
<p>but if I try to do the same while using the second method, the current_user is always "None" as the application context is incorrect.</p>
<p>So, I wanted to know if I decided to go ahead with the second implementation, how do I check if the user is logged in or not.</p>
| 1 | 2016-07-30T21:58:58Z | 38,695,915 | <p>I've never used the second method you've mentioned. I'm sure that it can be done with it, but it's very uncommon. I would suggest to use more common features of flask. For sake of maintainers of your code :)
So the first method you've mentioned is fine.</p>
<p>Or you can use <a href="http://flask.pocoo.org/docs/0.11/patterns/viewdecorators/" rel="nofollow">decorators</a> for more granular access restrictions. Keep in mind that <a href="http://flask.pocoo.org/docs/0.11/quickstart/#cookies" rel="nofollow">setting cookies in flask</a> can be done when making actual response object. That means you should use <a href="http://flask.pocoo.org/docs/0.11/patterns/deferredcallbacks/" rel="nofollow">Deferred Request Callbacks</a> for setting cookies in decorated function.</p>
| 0 | 2016-08-01T09:56:11Z | [
"python",
"cookies",
"flask",
"middleware"
] |
Error while reading Boston data from UCL website using pandas | 38,678,882 | <p>Any help please for reading this file from url website.</p>
<pre><code>eurl = 'https://archive.ics.uci.edu/ml/machine-learning-databases/housing/housing.data'
data = pandas.read_csv(url, sep=',', header = None)
</code></pre>
<p>I tried sep=',', sep=';' and sep='\t' but the data read like this
<a href="http://i.stack.imgur.com/djA4i.png" rel="nofollow"><img src="http://i.stack.imgur.com/djA4i.png" alt="enter image description here"></a></p>
<p>but with </p>
<pre><code>data = pandas.read_csv(url, sep=' ', header = None)
</code></pre>
<p>I received an error, </p>
<pre><code> pandas/parser.pyx in pandas.parser.TextReader.read (pandas/parser.c:7988)()
pandas/parser.pyx in pandas.parser.TextReader._read_low_memory (pandas/parser.c:8244)()
pandas/parser.pyx in pandas.parser.TextReader._read_rows (pandas/parser.c:8970)()
pandas/parser.pyx in pandas.parser.TextReader._tokenize_rows (pandas/parser.c:8838)()
pandas/parser.pyx in pandas.parser.raise_parser_error (pandas/parser.c:22649)()
CParserError: Error tokenizing data. C error: Expected 30 fields in line 2, saw 31
</code></pre>
<p>Maybe same question asked here <a href="http://stackoverflow.com/questions/18039057/python-pandas-error-tokenizing-data">enter link description here</a> but the accepted answer does not help me.</p>
<p>any help please to read this file from the url provide it. </p>
<p>BTW, I know there is Boston = load_boston() to read this data but when I read it from this function, the attribute 'MEDV' in the dataset does not download with the dataset.</p>
| 0 | 2016-07-30T22:02:12Z | 38,678,908 | <p>There are multiple spaces used as a delimiter, that's why it's not working when you use a single space as a delimiter (<code>sep=' '</code>)</p>
<p>you can do it using <code>sep='\s+'</code>:</p>
<pre><code>In [171]: data = pd.read_csv(url, sep='\s+', header = None)
In [172]: data.shape
Out[172]: (506, 14)
In [173]: data.head()
Out[173]:
0 1 2 3 4 5 6 7 8 9 10 11 12 13
0 0.00632 18.0 2.31 0 0.538 6.575 65.2 4.0900 1 296.0 15.3 396.90 4.98 24.0
1 0.02731 0.0 7.07 0 0.469 6.421 78.9 4.9671 2 242.0 17.8 396.90 9.14 21.6
2 0.02729 0.0 7.07 0 0.469 7.185 61.1 4.9671 2 242.0 17.8 392.83 4.03 34.7
3 0.03237 0.0 2.18 0 0.458 6.998 45.8 6.0622 3 222.0 18.7 394.63 2.94 33.4
4 0.06905 0.0 2.18 0 0.458 7.147 54.2 6.0622 3 222.0 18.7 396.90 5.33 36.2
</code></pre>
<p>or using <code>delim_whitespace=True</code>:</p>
<pre><code>In [174]: data = pd.read_csv(url, delim_whitespace=True, header = None)
In [175]: data.shape
Out[175]: (506, 14)
In [176]: data.head()
Out[176]:
0 1 2 3 4 5 6 7 8 9 10 11 12 13
0 0.00632 18.0 2.31 0 0.538 6.575 65.2 4.0900 1 296.0 15.3 396.90 4.98 24.0
1 0.02731 0.0 7.07 0 0.469 6.421 78.9 4.9671 2 242.0 17.8 396.90 9.14 21.6
2 0.02729 0.0 7.07 0 0.469 7.185 61.1 4.9671 2 242.0 17.8 392.83 4.03 34.7
3 0.03237 0.0 2.18 0 0.458 6.998 45.8 6.0622 3 222.0 18.7 394.63 2.94 33.4
4 0.06905 0.0 2.18 0 0.458 7.147 54.2 6.0622 3 222.0 18.7 396.90 5.33 36.2
</code></pre>
| 1 | 2016-07-30T22:06:31Z | [
"python",
"python-2.7",
"csv",
"pandas"
] |
pandas time interval to time series | 38,678,955 | <p>How do i transform time interval data into time series data using Python (and pandas)? </p>
<p>Here's my before data frame as time intervals:</p>
<pre><code>code start_dt end_dt ent_value
156600 1960-01-01 2016-04-21 H:CXP
156600 1960-01-01 2016-01-03 46927
156600 1998-08-31 2016-01-03 5516751
156600 1960-01-01 1998-08-30 4501242
</code></pre>
<p>For each combination of code and ent_value, we want a row in the frame for each day within that combination's start and end date (so as a time series):</p>
<pre><code>code as_of_dt ent_value
156600 1960-01-01 H:CXP
156600 1960-01-02 H:CXP
156600 1960-01-03 H:CXP
156600 1960-01-01 46927
156600 1960-01-02 46927
156600 1960-01-03 46927
156600 1960-01-01 5516751
156600 1960-01-02 5516751
156600 1960-01-03 5516751
...
156600 2016-01-01 H:CXP
156600 2016-01-02 H:CXP
156600 2016-01-03 H:CXP
156600 2016-01-01 46927
156600 2016-01-02 46927
156600 2016-01-03 46927
156600 2016-01-01 5516751
156600 2016-01-02 5516751
156600 2016-01-03 5516751
</code></pre>
<p>How do I do this in an efficient manner?</p>
| 1 | 2016-07-30T22:14:59Z | 38,679,444 | <p>First, try by yourself!
Then, if you do not succeed, this is a possible solution.</p>
<blockquote class="spoiler">
<p> <pre>
<code>data = pd.read_csv(open('/tmp/test.tab', 'r'), sep='\t')</code>
<code>tmp = [(e.code, pd.date_range(e.start_dt, e.end_dt, freq='1D'),</code>
<code>e.ent_value) for e in data.itertuples()]</code>
<code>res = [(line[0], date, line[2]) for date in line[1] for line in tmp]</code>
<code>df = pd.DataFrame(res)</code></pre></p>
</blockquote>
<p>The function <code>pd.date_range()</code> is used to create the dates ranges.</p>
| 1 | 2016-07-30T23:32:52Z | [
"python",
"pandas"
] |
pandas time interval to time series | 38,678,955 | <p>How do i transform time interval data into time series data using Python (and pandas)? </p>
<p>Here's my before data frame as time intervals:</p>
<pre><code>code start_dt end_dt ent_value
156600 1960-01-01 2016-04-21 H:CXP
156600 1960-01-01 2016-01-03 46927
156600 1998-08-31 2016-01-03 5516751
156600 1960-01-01 1998-08-30 4501242
</code></pre>
<p>For each combination of code and ent_value, we want a row in the frame for each day within that combination's start and end date (so as a time series):</p>
<pre><code>code as_of_dt ent_value
156600 1960-01-01 H:CXP
156600 1960-01-02 H:CXP
156600 1960-01-03 H:CXP
156600 1960-01-01 46927
156600 1960-01-02 46927
156600 1960-01-03 46927
156600 1960-01-01 5516751
156600 1960-01-02 5516751
156600 1960-01-03 5516751
...
156600 2016-01-01 H:CXP
156600 2016-01-02 H:CXP
156600 2016-01-03 H:CXP
156600 2016-01-01 46927
156600 2016-01-02 46927
156600 2016-01-03 46927
156600 2016-01-01 5516751
156600 2016-01-02 5516751
156600 2016-01-03 5516751
</code></pre>
<p>How do I do this in an efficient manner?</p>
| 1 | 2016-07-30T22:14:59Z | 38,679,529 | <p>try this:</p>
<pre><code>In [17]: %paste
(df.groupby(['code','ent_value'])
.apply(lambda x: pd.DataFrame({'as_of_dt':pd.date_range(x.start_dt.min(), x.end_dt.max())}))
.reset_index()
.drop('level_2', 1)
)
## -- End pasted text --
Out[17]:
code ent_value as_of_dt
0 156600 4501242 1960-01-01
1 156600 4501242 1960-01-02
2 156600 4501242 1960-01-03
3 156600 4501242 1960-01-04
4 156600 4501242 1960-01-05
5 156600 4501242 1960-01-06
6 156600 4501242 1960-01-07
7 156600 4501242 1960-01-08
8 156600 4501242 1960-01-09
9 156600 4501242 1960-01-10
10 156600 4501242 1960-01-11
11 156600 4501242 1960-01-12
12 156600 4501242 1960-01-13
13 156600 4501242 1960-01-14
14 156600 4501242 1960-01-15
15 156600 4501242 1960-01-16
16 156600 4501242 1960-01-17
17 156600 4501242 1960-01-18
18 156600 4501242 1960-01-19
19 156600 4501242 1960-01-20
20 156600 4501242 1960-01-21
21 156600 4501242 1960-01-22
22 156600 4501242 1960-01-23
23 156600 4501242 1960-01-24
24 156600 4501242 1960-01-25
25 156600 4501242 1960-01-26
26 156600 4501242 1960-01-27
27 156600 4501242 1960-01-28
28 156600 4501242 1960-01-29
29 156600 4501242 1960-01-30
... ... ... ...
61450 156600 H:CXP 2016-03-23
61451 156600 H:CXP 2016-03-24
61452 156600 H:CXP 2016-03-25
61453 156600 H:CXP 2016-03-26
61454 156600 H:CXP 2016-03-27
61455 156600 H:CXP 2016-03-28
61456 156600 H:CXP 2016-03-29
61457 156600 H:CXP 2016-03-30
61458 156600 H:CXP 2016-03-31
61459 156600 H:CXP 2016-04-01
61460 156600 H:CXP 2016-04-02
61461 156600 H:CXP 2016-04-03
61462 156600 H:CXP 2016-04-04
61463 156600 H:CXP 2016-04-05
61464 156600 H:CXP 2016-04-06
61465 156600 H:CXP 2016-04-07
61466 156600 H:CXP 2016-04-08
61467 156600 H:CXP 2016-04-09
61468 156600 H:CXP 2016-04-10
61469 156600 H:CXP 2016-04-11
61470 156600 H:CXP 2016-04-12
61471 156600 H:CXP 2016-04-13
61472 156600 H:CXP 2016-04-14
61473 156600 H:CXP 2016-04-15
61474 156600 H:CXP 2016-04-16
61475 156600 H:CXP 2016-04-17
61476 156600 H:CXP 2016-04-18
61477 156600 H:CXP 2016-04-19
61478 156600 H:CXP 2016-04-20
61479 156600 H:CXP 2016-04-21
[61480 rows x 3 columns]
</code></pre>
<p>Test DF with smaller date ranges:</p>
<pre><code>In [19]: df
Out[19]:
code start_dt end_dt ent_value
0 156600 1960-01-01 1960-01-04 H:CXP
1 156600 1960-01-04 1960-01-09 46927
2 156600 1998-08-31 1998-09-04 5516751
3 156600 1965-01-01 1965-01-04 4501242
In [20]: (df.groupby(['code','ent_value'])
....: .apply(lambda x: pd.DataFrame({'as_of_dt':pd.date_range(x.start_dt.min(), x.end_dt.max())}))
....: .reset_index()
....: .drop('level_2', 1)
....: )
Out[20]:
code ent_value as_of_dt
0 156600 4501242 1965-01-01
1 156600 4501242 1965-01-02
2 156600 4501242 1965-01-03
3 156600 4501242 1965-01-04
4 156600 46927 1960-01-04
5 156600 46927 1960-01-05
6 156600 46927 1960-01-06
7 156600 46927 1960-01-07
8 156600 46927 1960-01-08
9 156600 46927 1960-01-09
10 156600 5516751 1998-08-31
11 156600 5516751 1998-09-01
12 156600 5516751 1998-09-02
13 156600 5516751 1998-09-03
14 156600 5516751 1998-09-04
15 156600 H:CXP 1960-01-01
16 156600 H:CXP 1960-01-02
17 156600 H:CXP 1960-01-03
18 156600 H:CXP 1960-01-04
</code></pre>
| 0 | 2016-07-30T23:47:38Z | [
"python",
"pandas"
] |
Running a python script from another script while passing args from another script/json generated by script? | 38,679,109 | <p>So I have 3 scripts, for the sake of simplicity lets call them a.py,b.py, and c.py</p>
<p>now a.py creates a json containing some data i want to pass to b which uses this data to create another json containing another related subset of data
and I want to do this action from c.py. how can I go about getting b to read from the json generated by a, and then pass the json generated by b into c. I've thought about importing like so</p>
<pre><code>import a
import b
</code></pre>
<p>id assume I would import functions from b, but realistically I need all the functions within b, would I just import all functions from b and pass the arguments normally or would there be another way to handle this? For a little more context,</p>
<p>c.py will create a directory that the json from b.py will be stored in.
also will i need an <strong>init</strong>.py in my working directory to do these imports, they are all in the same directory.</p>
| 0 | 2016-07-30T22:36:21Z | 38,679,477 | <p>(From comments to question)</p>
<p>Consider the following files:</p>
<pre><code>#-- b.py ----------------------------------------------------------------------------------
def main():
name = input("Enter your name: ") # Python 3, use raw_input for Python 2
print("Your name is:", name)
#-- a.py ----------------------------------------------------------------------------------
import json
# Some method of generating a json
j = json.dumps({'name': 'Alice'})
</code></pre>
<p>And you want to have b.py's <code>main</code> function use the data in the json that is generated in a.py, instead of what <code>main</code> prompts the user for.</p>
<p>In other words, in the above example, you'd want to have the program print <code>Your name is: Alice</code> without prompting the user for input.</p>
<p>If that's the case, you might refactor your code to look something like:</p>
<pre><code>#-- b.py ----------------------------------------------------------------------------------
def process(name):
print("Your name is:", name)
def get_user_input():
name = input("Enter your name: ") # Python 3, use raw_input for Python 2
process(name) # Prints: "Your name is: (whatever)"
#-- a.py ----------------------------------------------------------------------------------
import json
from b import process
# Some method of generating a json
j = json.dumps({'name': 'Alice'})
# (We created a json for no real reason, parse it back into a dict to access it)
d = json.loads(j)
# Call b.py's process function, and pass it the name in the json
process(d['name']) # Prints: "Your name is: Alice"
</code></pre>
<p>The "trick" here is to separate "jobs" that the <code>main</code> function does into two separate functions. </p>
<ul>
<li>The first function (<code>process</code>), is given a name and "processes" it. In the example, all it does is print it out.</li>
<li>One second function (named <code>get_user_input</code> in the refactoring) gets the user's input and passes it to the first function.</li>
</ul>
<p>After doing this, you can skip the user input (since you don't need it, you want to use the JSON data) and call <code>process</code> directly, even from other files.</p>
| 2 | 2016-07-30T23:37:34Z | [
"python"
] |
AttributeError: __exit__ while buffering downloaded image on python 2.7 | 38,679,194 | <p>I'm trying to automate captcha file recognition with a python script.
However, after several days of efforts my functions seems to be far from desired result. </p>
<p>Furthermore, the traceback I've got is not informative enough to help me investigate further.</p>
<p>Here is my function:</p>
<pre><code>def getmsg():
solved = ''
probe_request = []
try:
probe_request = api.messages.get(offset = 0, count = 2)
except apierror, e:
if e.code is 14:
key = e.captcha_sid
imagefile = cStringIO.StringIO(urllib.urlopen(e.captcha_img).read())
img = Image.open(imagefile)
imagebuf = img.load()
with imagebuf as captcha_file:
captcha = cptapi.solve(captcha_file)
finally:
while solved is None:
solved = captcha.try_get_result()
tm.sleep(1.500)
print probe_request
</code></pre>
<p>Here is the traceback:</p>
<pre><code>Traceback (most recent call last):
File "myscript.py", line 158, in <module>
getmsg()
File "myscript.py", line 147, in getmsg
with imagebuf as captcha_file:
AttributeError: __exit__
</code></pre>
<p>Can someone please clarify what exactly I'm doing wrong?</p>
<p>Also I did not succeed with image processing without buffering:</p>
<pre><code>key = e.captcha_sid
response = requests.get(e.captcha_img)
img = Image.open(StringIO.StringIO(response.content))
with img as captcha_file:
captcha = cptapi.solve(captcha_file)
</code></pre>
<p>Which leads to:</p>
<pre><code> captcha = cptapi.solve(captcha_file)
File "/usr/local/lib/python2.7/dist-packages/twocaptchaapi/__init__.py", line 62, in proxy
return func(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/twocaptchaapi/__init__.py", line 75, in proxy
return func(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/twocaptchaapi/__init__.py", line 147, in solve
raw_data = file.read()
File "/usr/lib/python2.7/dist-packages/PIL/Image.py", line 632, in __getattr__
raise AttributeError(name)
AttributeError: read
</code></pre>
| -2 | 2016-07-30T22:50:30Z | 38,679,217 | <p><code>imagebuf</code> is not a <a href="https://docs.python.org/2/library/stdtypes.html#context-manager-types" rel="nofollow">context manager</a>. You can't use it in a <code>with</code> statement, which tests for a context manager by first storing the <a href="https://docs.python.org/2/library/stdtypes.html#contextmanager.__exit__" rel="nofollow"><code>contextmanager.__exit__</code> method</a>. There is no need to close it either.</p>
<p><code>cptapi.solve</code> requires a file-like object; from the <a href="https://github.com/athre0z/twocaptcha-api/blob/master/twocaptchaapi/__init__.py#L132-L140" rel="nofollow"><code>solve()</code> docstring</a>:</p>
<blockquote>
<p>Queues a captcha for solving. <code>file</code> may either be a path or a file object.</p>
</blockquote>
<p>There is no point in passing in an <code>Image</code> object here, just pass in the <code>StringIO</code> instance instead:</p>
<pre><code>imagefile = cStringIO.StringIO(urllib.urlopen(e.captcha_img).read())
captcha = cptapi.solve(imagefile)
</code></pre>
<p>Again, there is no need to use close that object here, you don't need to use <code>with</code>.</p>
| 0 | 2016-07-30T22:53:02Z | [
"python",
"image",
"python-2.7",
"python-imaging-library",
"buffering"
] |
numpy diff weird behaviour | 38,679,215 | <p>I have a case of strange behaviour of numpy diff:</p>
<pre><code>a = list(img_arr[y_coord_1,:])
print a
print np.diff(a)
>>[62, 62, 62, 62, 62, 62, 62, 62, 63, 62, 96, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 66, 63, 64, 64, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 64, 65, 65, 64, 63, 63, 63, 63, 63, 63, 63, 64, 64, 63, 63, 63, 63, 63, 64, 65, 65, 64, 63, 63, 63, 63]
>>[ 0 0 0 0 0 0 0 1 255 34 2 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 224 253 1 0 255
0 0 0 0 0 0 0 0 0 1 1 0 255 255 0 0 0 0
0 0 1 0 255 0 0 0 0 1 1 0 255 255 0 0 0]
</code></pre>
<p>Now, when I run this in the terminal I get the correct answer of </p>
<pre><code>array([ 0, 0, 0, 0, 0, 0, 0, 1, -1, 34, 2, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -32, -3, 1,
0, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1,
0, -1, -1, 0, 0, 0, 0, 0, 0, 1, 0, -1, 0,
0, 0, 0, 1, 1, 0, -1, -1, 0, 0, 0])
</code></pre>
<p>What sort of things can cause this - I am using a few other compiled libraries in this script, if this of relevance</p>
<p>Edit: I've just spotted that its the negative numbers that are wrong - and the upper limit is very suspicious. Looks like a dtype issue..</p>
| 3 | 2016-07-30T22:52:52Z | 38,679,528 | <p><code>.tolist()</code> is a better way of converting an array to a list (or nested lists). It carries the conversion all the way down. <code>list()</code> just iterates on one level. And since an array is already iterable, I don't think <code>list(anarray)</code> does anything useful.</p>
<p>start with an array:</p>
<pre><code>In [789]: z
Out[789]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], dtype=uint8)
In [790]: type(list(z)[0])
Out[790]: numpy.uint8
</code></pre>
<p><code>list()</code> is the same as this list comprehension:</p>
<pre><code>In [791]: type([i for i in z][0])
Out[791]: numpy.uint8
</code></pre>
<p>the correct list conversion</p>
<pre><code>In [792]: type(z.tolist()[0])
Out[792]: int
</code></pre>
<p>Why were you using <code>list()</code> in the first place? You didn't need it for <code>diff</code>. If overflow is an issue, dtype conversion is better.</p>
<p><code>np.diff</code> will turn a list back into an array before taking the differences.</p>
<pre><code>In [793]: np.diff(z.tolist())
Out[793]: array([1, 1, 1, 1, 1, 1, 1, 1, 1])
In [794]: np.diff(list(z))
Out[794]: array([1, 1, 1, 1, 1, 1, 1, 1, 1], dtype=uint8)
In [795]: np.diff(z.astype('int'))
Out[795]: array([1, 1, 1, 1, 1, 1, 1, 1, 1])
In [796]: np.diff(z)
Out[796]: array([1, 1, 1, 1, 1, 1, 1, 1, 1], dtype=uint8)
In [797]: np.array(list(z))
Out[797]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], dtype=uint8)
</code></pre>
| 2 | 2016-07-30T23:47:36Z | [
"python",
"numpy"
] |
Trying to capture a particular pattern with regular expressions (Python 3.4) | 38,679,238 | <p>The pattern I'm trying to capture is along the lines of:</p>
<pre><code>Coin: gp (3840)
</code></pre>
<p>"gp" can be replaced with "cp", "sp", or "pp", and there can be any string of digits inside the parentheses. The pattern I came up with is:</p>
<pre><code>"Coin: 'cp|sp|gp|pp' \(\d+\)"
</code></pre>
<p>However, this is my result when I try to get a match:</p>
<pre><code>>>> print(re.match("Coin: 'cp|sp|gp|pp' \(\d+\)", "Coin: gp (3840)"))
None
</code></pre>
<p>Which part of the pattern am I getting wrong? </p>
| 1 | 2016-07-30T22:55:51Z | 38,679,267 | <p>You have pattern matching different options wrong: <code>'cp|sp|gp|pp'</code> It's trying to match the literal character <code>'</code>.</p>
<p>Your regex should really be something like:</p>
<pre><code>>>> re.match("Coin: (?:cp|sp|gp|pp) \(\d+\)", "Coin: gp (3840)")
</code></pre>
<p>The expression <code>(?:cp|sp|gp|pp)</code> creates a non-capturing group of your options.</p>
| 4 | 2016-07-30T22:59:43Z | [
"python",
"regex",
"python-3.x"
] |
using opencv with zbar in python on windows 8.1 to detect qr codes | 38,679,301 | <p>I am using opencv version 3.1.0 with zbar (latest version as of this post) and PIL (latest version as of this post)</p>
<pre><code>import zbar
import Image
import cv2
# create a reader
scanner = zbar.ImageScanner()
# configure the reader
scanner.parse_config('enable')
#create video capture feed
cap = cv2.VideoCapture(0)
while(True):
ret, cv = cap.read()
cv = cv2.cvtColor(cv, cv2.COLOR_BGR2RGB)
pil = Image.fromarray(cv)
width, height = pil.size
raw = pil.tostring()
# wrap image data
image = zbar.Image(width, height, 'Y800', raw)
# scan the image for barcodes
scanner.scan(image)
# extract results
for symbol in image:
# do something useful with results
print 'decoded', symbol.type, 'symbol', '"%s"' % symbol.data
# clean up
print "/n ...Done"
</code></pre>
<p>I don't understand why this is not working it is supposed to constantly check for qrcodes in the current frame of the Video Stream and if it sees one it decodes it and prints what it says inside I hold up printed out qrcodes in front of my webcam and it does not work it shows that my camera is on and that there is a video stream occurring so somewhere in the while loop something is going wrong</p>
<p>I tried it before with qr codes on my computer not printed out and it worked fine</p>
<p>I also tried having it show me the current frame with <code>cv2.imshow("out",cv)</code> but when I did the program showed just a big grey square where it should show the video stream and then it froze so I had to kill Netbeans.</p>
| 0 | 2016-07-30T23:05:27Z | 38,679,701 | <p>zbar works with grayscale images. Change <code>cv = cv2.cvtColor(cv, cv2.COLOR_BGR2RGB)</code> to <code>cv = cv2.cvtColor(cv, cv2.COLOR_BGR2GRAY)</code>.</p>
<p>I'm guessing you're using <a href="https://github.com/herbyme/zbar/blob/3687df80d2a9cd0f95bb293426827d5bf2f8dcbe/python/examples/scan_image.py" rel="nofollow">this example code</a> to base your program off of. They do the color to grayscale conversion with <code>convert('L')</code> on line 15.</p>
| 0 | 2016-07-31T00:22:12Z | [
"python",
"opencv",
"python-imaging-library",
"qr-code",
"zbar"
] |
python based IP address calculator (IPCALC) code | 38,679,383 | <p>I've the python CGI for user entered input for IP address calculation but python ipcalc is not taking input as a variable, for example I'm trying to run this code</p>
<pre><code>>>> import ipcalc
>>> ip='10.84.35.11'
>>> mask=24
>>> print ip
10.84.35.11
>>> print mask
24
>>> subnet = ipcalc.Network(ip/mask)
</code></pre>
<p>It gives me an error-
Traceback (most recent call last):
File "", line 1, in
TypeError: unsupported operand type(s) for /: 'str' and 'int'</p>
<p>where as if I pass the value as it is like subnet = ipcalc.Network('10.84.35.11/24') it works perfect!</p>
<p>I'm new to programming, can someone help to solve this!</p>
| 1 | 2016-07-30T23:22:32Z | 38,679,403 | <p>You probably want a string representing a network:</p>
<pre><code>subnet = ipcalc.Network("%s/%d" % (ip, mask))
</code></pre>
<p>Right now you're trying to use the <code>/</code> operator on <code>str</code> and <code>int</code> which is not defined (as the error says).</p>
| 1 | 2016-07-30T23:25:53Z | [
"python",
"ip",
"ip-address"
] |
Adding nodes to a linked list in Python | 38,679,388 | <p>The addToList() function takes a value as an argument. Values are passed to the addToList() function many times consecutively. </p>
<pre><code>def addToList(value):
node = {}
node["data"] = value
node["next"] = None
head = node
</code></pre>
<p>The question is: how do I create many different nodes? Each value that comes in should be assigned to a node. Only the first node should be equal to head. As of now, I'm creating one node, giving it a value, and then when the next value comes in I overwrite the node I had made instead of creating a new one. How would each new node point to a different ["next"]? If I know my values ahead of time, I can program each node manually. I don't understand how to generate new and unique nodes when I don't know how many values I will have, and they are being fed to a function.</p>
| 0 | 2016-07-30T23:23:11Z | 38,679,435 | <p>the easy answer to your question to make each node point to correct next is to make your function as</p>
<pre><code>def addToList(value):
node = {}
node["data"] = value
node["next"] = None
head[next] = node
head = node
</code></pre>
<p>but you need to keep track of the real head of your list somewhere else so you can travese your list later from head to tail</p>
<p>here is complete example</p>
<pre><code>head={}
head["data"] = "start"
head["next"] = None
start = head
def addToList(value):
global head
node = {}
node["data"] = value
node["next"] = None
head["next"] = node
head = node
addToList("second")
addToList("third")
print start
</code></pre>
<p>it will print this</p>
<pre><code>{'data': 'start', 'next': {'data': 'second', 'next': {'data': 'third', 'next': None}}}
</code></pre>
| -1 | 2016-07-30T23:30:51Z | [
"python",
"linked-list",
"nodes"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.