How to show all Elements in a Textview - collections

data class Fruit(val name: String, val price: Int)
val fruits = arrayOf(Fruit(name = "Apple", price = 2), Fruit(name = "Grape", price = 3), Fruit(name = "Bananna", price = 4))
for (index in fruits.indices)
textView.text = fruits[index].name
Output = Bananna
I cant seem to get all elements of "Name" to reflect in the Textview
Eg.
Apple, Grape, Pear

I manage to figure it out !
val fruitNamesonly: MutableList<String> = ArrayList()
for (item in fruits) {
val token = item.name
FruitNamesonly.add(token)
}
val fruitNamesonly will be the vaulable you use for what ever

Related

Why do I get error "missing 1 required positional argument"?

Why I continue getting the error :
missing 1 required positional argument: 'category_id'
when the argument is already passed within query function in Backend class? I also don't understand the error of unfilled self or missing positional argument self:
missing 1 required positional argument: 'self'
I tried passing self to display_account_types() in Frontend class but it doesn't reflect. Do I need to pass self within the inner nested functions within a class?
import tkinter
from tkinter import *
from tkinter import ttk
import tkinter.messagebox
import sqlite3
root =Tk()
root.title('Simple Application')
root.config(bg='SlateGrey')
root.geometry("")
# BackEnd
class Backend():
def __init__(self):
self.conn = sqlite3.connect('accounting.db')
self.cur = self.conn.cursor()
self.conn.execute("""CREATE TABLE IF NOT EXISTS account_type(
id INTEGER PRIMARY KEY,
category_type INTEGER NOT NULL,
category_id TEXT NOT NULL
)"""),
self.conn.commit()
self.conn.close()
def insert_account_type(self, category_type, category_id):
self.conn = sqlite3.connect('accounting.db')
self.cur = self.conn.cursor()
self.cur.execute("""INSERT INTO account_type(category_id, category_type) VALUES(?,?);""",
(self,category_type, category_id,))
self.conn.commit()
self.conn.close()
def view_account_type(self):
self.conn = sqlite3.connect('accounting.db')
self.cur = self.conn.cursor()
self.cur.execute("SELECT * FROM account_type")
self.rows = self.cur.fetchall()
self.conn.close()
return self.rows
# calling the class
tb = Backend()
# Front End
class Frontend():
def __init__(self, master):
# Frames
self.top_frame = LabelFrame(master,bg ='SlateGrey', relief=SUNKEN)
self.top_frame.pack()
self.bottom_frame = LabelFrame(master, bg = 'SlateGrey', relief=SUNKEN)
self.bottom_frame.pack()
self.right_frame = LabelFrame(self.top_frame, bg = 'SlateGrey', relief = FLAT,
text = 'Details Entry',fg = 'maroon')
self.right_frame.pack(side = RIGHT, anchor = NE)
self.side_frame = LabelFrame(self.top_frame,bg ='SlateGrey',relief=SUNKEN,text = 'Menu Buttons',fg = 'maroon')
self.side_frame.pack(side = LEFT,anchor = NW)
self.bot_frame = LabelFrame(self.bottom_frame, bg='Grey',relief = SUNKEN,text = 'Field View',fg = 'maroon')
self.bot_frame.pack(side = BOTTOM,anchor = SW)
# Side Buttons
self.btn1 = Button(self.side_frame,
text='Main Account Types',
bg='SteelBlue4',
font=('cambria', 11),
anchor=W,
fg='white',
width=18,height=2,
command=lambda :[self.main_account()])
self.btn1.grid(row=0, column=0, pady=0, sticky=W)
def main_account(self):
# variables
self.category_type = StringVar()
self.category_id = StringVar()
# functions
def add_main_accounts():
if self.category_type.get() == "" or self.category_id.get() == "":
tkinter.messagebox.showinfo('All fields are required')
else:
Backend.insert_account_type(
self.category_type.get(),
self.category_id.get(),) # category type unfilled
tkinter.messagebox.showinfo('Entry successful')
def display_account_types(self):
self.trv.delete(*self.trv.get_children())
for self.rows in Backend.view_account_type(self):
self.trv.insert("", END, values=self.rows)
def get_account_type(e):
self.selected_row = self.trv.focus()
self.data = self.trv.item(self.selected_row)
global row
row = self.data["values"]
"""Grab items and send them to entry fields"""
self.category_id.set(row[1])
self.category_type.set(row[2])
"""=================TreeView==============="""
# Scrollbars
ttk.Style().configure("Treeview", background = "SlateGrey", foreground = "white", fieldbackground = "grey")
scroll_x = Scrollbar(self.bot_frame, orient = HORIZONTAL)
scroll_x.pack(side = BOTTOM, fill = X)
scroll_y = Scrollbar(self.bot_frame, orient = VERTICAL)
scroll_y.pack(side = RIGHT, fill = Y)
# Treeview columns & setting scrollbars
self.trv = ttk.Treeview(self.bot_frame, height=3, columns=
('id', 'category_id', 'category_type'), xscrollcommand = scroll_x.set, yscrollcommand = scroll_y.set)
# Treeview style configuration
ttk.Style().configure("Treeview", background = "SlateGrey", foreground = "white", fieldbackground = "grey")
# Configure vertical and Horizontal scroll
scroll_x.config(command = self.trv.xview)
scroll_y.config(command = self.trv.yview)
# Treeview Headings/columns
self.trv.heading('id', text = "No.")
self.trv.heading('category_id', text = 'Category ID')
self.trv.heading('category_type', text = 'Category Type')
self.trv['show'] = 'headings'
# Treeview columns width
self.trv.column('id', width = 23)
self.trv.column('category_id', width = 70)
self.trv.column('category_type', width = 100)
self.trv.pack(fill = BOTH, expand = YES)
# Binding Treeview with data
self.trv.bind('<ButtonRelease-1>',get_account_type)
# Account Types Labels
self.lbl1 = Label(self.right_frame,text = 'Category ID',anchor = W,
width=10,font = ('cambria',11,),bg = 'SlateGrey')
self.lbl1.grid(row = 0,column = 0,pady = 5)
self.lbl2 = Label(self.right_frame, text = 'Category Type', anchor = W,
width = 10,font = ('cambria',11,),bg = 'SlateGrey')
self.lbl2.grid(row = 1, column = 0,pady = 5,padx=5)
self.blank_label = Label(self.right_frame, bg='SlateGrey')
self.blank_label.grid(row=2, columnspan=2, pady=10)
# Account Type Entries
self.entry1 = Entry(self.right_frame,textvariable = self.category_id,
font = ('cambria',11,),bg = 'Grey',width=14)
self.entry1.grid(row = 0,column=1,sticky = W,padx = 5)
self.entry2 = Entry(self.right_frame, textvariable = self.category_type,
font = ('cambria', 11,), bg = 'Grey',width = 14)
self.entry2.grid(row = 1, column = 1, sticky = W,pady = 5,padx = 5)
# Buttons
self.btn_1 = Button(self.right_frame,text = 'Add',font = ('cambria',12,'bold'),bg = 'SlateGrey',
activebackground='green', fg = 'white',width=12,height = 2,relief=RIDGE,
command = lambda :[add_main_accounts()])
self.btn_1.grid(row = 3,column = 0,pady = 15)
self.btn_2 = Button(self.right_frame, text = 'View', font = ('cambria', 12, 'bold'),
bg = 'SlateGrey',command=lambda :[display_account_types()],
activebackground='green', fg ='white', width=12, height = 2, relief = RIDGE)
self.btn_2.grid(row = 3, column = 1)
# calling the class
app = Frontend(root)
root.mainloop()
I got and answer to this question,
I just passed in the 'self' argument to the inner nested functions of the class as below and it worked.
# functions
def add_main_accounts(self):
if self.category_id.get() == "" or self.category_type.get() == "":
tkinter.messagebox.showinfo('All fields are required')
else:
Backend.insert_account_type(self,
self.category_id.get(),
self.category_type.get()) # category type unfilled
tkinter.messagebox.showinfo('Entry successful')
def display_account_types(self):
self.trv.delete(*self.trv.get_children())
for rows in Backend.view_account_type(self):
self.trv.insert("", END, values = rows)
return
def get_account_type(e):
self.selected_row = self.trv.focus()
self.data = self.trv.item(self.selected_row)
global row
self.row = self.data["values"]
"""Grab items and send them to entry fields"""
self.category_id.set(row[1])
self.category_type.set(row[2])
I think you should remove the self in display_account_types function like you did to the previous one.

web scraper Python AttributeError: 'NoneType' object has no attribute 'get'

Hi Can anyone know how to troubleshoot this.
url = "https://www.zillow.com/walnut-ca/?searchQueryState=%7B%22pagination%22%3A%7B%7D%2C%22usersSearchTerm%22%3A%22Walnut%2C%20CA%22%2C%22mapBounds%22%3A%7B%22west%22%3A-117.93482729053105%2C%22east%22%3A-117.75286623096073%2C%22south%22%3A33.93783156520187%2C%22north%22%3A34.06392018234896%7D%2C%22isMapVisible%22%3Atrue%2C%22mapZoom%22%3A12%2C%22filterState%22%3A%7B%22price%22%3A%7B%22min%22%3A400000%2C%22max%22%3A700000%7D%2C%22mp%22%3A%7B%22min%22%3A1448%2C%22max%22%3A2535%7D%2C%22sort%22%3A%7B%22value%22%3A%22globalrelevanceex%22%7D%7D%2C%22isListVisible%22%3Atrue%7D"
d = {'key':'value'}
print(d)
d['new key'] = 'new value'
print(d)
query_houses = {}
house_no = 0
while True:
response = requests.get(url)
data = response.text
soup = BeautifulSoup(data,'html.parser')
houses = soup.find_all('article',{'class':'list-card list-card-short list-card_not-saved'})
for house in houses:
location = house.find('address',{'class': 'list-card-addr'})
value = house.find('div',{'class': 'list-card-price'})
detail = house.find('ul', {'class':'list-card-details'})
seller = house.find('div',{'class':'list-card-truncate'})
link = house.find('a', {'class': 'list-card-link'}).get('href')
house_response = requests.get(link)
house_data = house_response.text
house_soup = BeautifulSoup(house_data, 'html.parser')
square = house_soup.find('span',{'class':'ds-bed-bath-living-area'})
year_build = house_soup.find('span',{'class':'ds-body ds-home-fact-value'})
estimated_sales_range = house_soup.find('div',{'class':'Spacer-sc-17suqs2-0 pfWXf'})
house_no+=1
query_houses[house_no] = [location, value, detail, seller, link, square, year_build, estimated_sales_range]
url_tag = soup.find('a',{'title':'Next-page'})
if url_tag.get('href'):
url= 'https://zillow.com' + url_tag.get('href')
print(url)
else:
break

How to have observable treeview

I am working on an app which requires TreeView.
I'm able to generate the Treeview but facing issue with dynamically updating the treeview based on underlying dataset change.
Classes:
data class Channels(
val channel: Channel? = null
)
data class Channel(
val id: String? = null,
val name: String? = null,
val parentChannelId: String? = null
)
Data List :
var channels = observableListOf(
Channels(channel = Channel(id = "pc1", name = "P Channel 1")),
Channels(channel = Channel(id = "c11", name = "Child 1-1", parentChannelId = "pc1")),
Channels(channel = Channel(id = "c12", name = "Child 1-2", parentChannelId = "pc1")),
Channels(channel = Channel(id = "c121", name = "Child 1-2-1", parentChannelId = "c12")),
Channels(channel = Channel(id = "c111", name = "Child 1-1-1", parentChannelId = "c11")),
Channels(
channel = Channel(
id = "c1111",
name = "Child 1-1-1-1",
parentChannelId = "c111"
)
),
Channels(channel = Channel(id = "pc2", name = "P Channel 2")),
Channels(channel = Channel(id = "pc3", name = "P Channel 3")),
Channels(channel = Channel(id = "c31", name = "Child 3-1", parentChannelId = "pc3"))
)
Treeview :
treeview<Channels> {
isShowRoot = false
root = TreeItem()
cellFormat { text = it.channel?.name }
populate { parent ->
if (parent == root) channels.filter {
it.channel?.parentChannelId == null
} else channels.filter {
it.channel?.parentChannelId == parent.value?.channel?.id
}
}
}
Now when I modify the channels list, treeview doesn't gets updated.
I've been stuck on this since 3-4 days.
Please help.

Highcharts - drill down to multiple series in R

I know this has already been answered in JS but I was hoping for a solution using highcharter in R. Highcharts - drill down to multiple series
I'm new to JS and also not that familiar with the highcharter library in R so any help would be greatly appreciated. The following code compiles but as the code is more experimental than anything it does not allow me to drill down to a multi- series chart as hoped.
DATABrowser = list(list(y= 55.11
,drilldown = list(
name = 'MSIE versions',
categories = list('MSIE 6.0', 'MSIE 7.0', 'MSIE 8.0',
'MSIE 9.0'),
series = list(list(
type = 'spline',
name = 'MSIE versions 2000',
data = list(10.85, 7.35, 33.06, 2.81)
),list(
type = 'spline',
name = 'MSIE versions 2010',
data = list (1, 5, 10, 15)
))
)),list(y = 21.6),list(y = 11.6),list(y = 7.3),list(y =
2.6)
)
categories = list('MSIE', 'Firefox', 'Chrome', 'Safari', 'Opera')
name = 'Browser brands'
fn <-"function () {
var drilldown = this.drilldown;
var len = chart.series.length;
var name = null, catergories = drilldown.categories, data = drilldown, type
=drilldown.type;
chart.xAxis[0].setCategories(categories);
for(var i = 0; i < len; i++){
chart.series[0].remove();
}
if(data.series){
for( i = 0; i < data.series.length; i ++ ){
chart.addSeries({
name: data.series[i].name,
data: data.series[i].data,
type: data.series[i].type,
});
}
} else {
chart.addSeries({
name: name,
data: data,
type: type,
});
}
}
"
hc = highchart() %>%
hc_chart(type = "column") %>%
hc_title(text = "Basic Drilldown Big Bossing") %>%
hc_xAxis(categories = categories) %>%
hc_add_series(
name = name
,data = DATABrowser
) %>% hc_plotOptions(
column = list(
# allowPointSelect = TRUE,
cursor = "pointer",
point = list(
events = list(
click = JS(fn)
)
)
)
)
hc
The JS function returns an error
chart is undefined
Indeed we don't have access to the chart from the click event, but we can retrive it with:
var chart = Highcharts.charts[0]
So putting that inside the JS, together with some typo fix gives us:
fn <-"function () {
var chart = Highcharts.charts[0];
var drilldown = this.drilldown;
var len = chart.series.length;
var name = null,
categories = drilldown.categories,
data = drilldown,
type = drilldown.type;
chart.xAxis[0].setCategories(categories);
for(var i = 0; i < len; i++){
chart.series[0].remove();
}
if(data.series){
for( i = 0; i < data.series.length; i ++ ){
chart.addSeries({
name: data.series[i].name,
data: data.series[i].data,
type: data.series[i].type,
});
}
} else {
chart.addSeries({
name: name,
data: data,
type: type,
});
}
}
"
Giving us:
library(highcharter)
highchart() %>%
hc_chart(type = "column") %>%
hc_title(text = "Basic Drilldown Big Bossing") %>%
hc_xAxis(categories = categories) %>%
hc_add_series(
name = name
,data = DATABrowser
) %>% hc_plotOptions(
column = list(
# allowPointSelect = TRUE,
cursor = "pointer",
point = list(
events = list(
click = JS(fn)
)
)
)
)

Change initialize method in subclass of an R6 class

Let's say I have a R6 class Person:
library(R6)
Person <- R6Class("Person",
public = list(name = NA, hair = NA,
initialize = function(name, hair) {
self$name <- name
self$hair <- hair
self$greet()
},
greet = function() {
cat("Hello, my name is ", self$name, ".\n", sep = "")
})
)
If I want to create a subclass whose initialize method should be the same except for adding one more variable to self how would I do this?
I tried the following:
PersonWithSurname <- R6Class("PersonWithSurname",
inherit = Person,
public = list(surname = NA,
initialize = function(name, surname, hair) {
Person$new(name, hair)
self$surname <- surname
})
)
However when I create a new instance of class PersonWithSurname the fields name and hair are NA, i.e. the default value of class Person.
PersonWithSurname$new("John", "Doe", "brown")
Hello, my name is John.
<PersonWithSurname>
Inherits from: <Person>
Public:
clone: function (deep = FALSE)
greet: function ()
hair: NA
initialize: function (name, surname, hair)
name: NA
surname: Doe
In Python I would do the following:
class Person(object):
def __init__(self, name, hair):
self.name = name
self.hair = hair
self.greet()
def greet(self):
print "Hello, my name is " + self.name
class PersonWithSurname(Person):
def __init__(self, name, surname, hair):
Person.__init__(self, name, hair)
self.surname = surname
R6 works very much like Python in this regard; that is, you just call initialize on the super object:
PersonWithSurname <- R6Class("PersonWithSurname",
inherit = Person,
public = list(surname = NA,
initialize = function(name, surname, hair) {
super$initialize(name, hair)
self$surname <- surname
})
)

Resources