callback via taptool presents datatable - datatable

From what I can tell in my limited review of bokeh documentation the ability to click on a glyph on a plot then present a Dialog box or Datatable is a feature not yet available. I do not want the Datatable to be presented until a glyph has been selected. Would ideally like the ability to hide the Dialog or Datatable as well.
It seems that bokeh.models.widgets.dialog were deprecated sometime after 0.10.0. I could use that but its not available in python 3.7 at this point. Suggestions?

Some features are not officially supported but sometimes one can come up with a work-arounds like this one (tested on Bokeh v1.0.4):
from bokeh.plotting import figure, show
from bokeh.layouts import column
from bokeh.models import ColumnDataSource, Slider, DataTable, TableColumn, CustomJS
plot = figure(tools = 'tap')
source = ColumnDataSource(dict(x = list(range(6)), y = [x ** 2 for x in range(6)]))
circles = plot.circle('x', 'y', source = source, size = 20)
slider = Slider(start = -1, end = 5, value = 6, step = 1, title = "i", width = 300)
columns = [TableColumn(field = "x", title = "x"), TableColumn(field = "y", title = "x**2")]
table = DataTable(source = source, columns = columns, width = 320)
plot.js_on_event('tap', CustomJS(args = {'table': table, 'source': source, 'slider': slider}, code = '''
const selected_index = source.selected.indices[0]
if (selected_index != null)
table.height = 0;
else
table.height = slider.value * 25 + 25;'''))
callback_code = """ i = slider.value;
new_data = {"x": [0,1,2,3,4,5], "y": [0,1,4,9,16,25]}
table.source.data = new_data
table.height = i * 25 + 25; """
callback = CustomJS(args = dict(slider = slider, table = table), code = callback_code)
slider.js_on_change('value', callback)
show(column(slider, plot, table))
Result:

Related

How to create a line chart with filter option and Data table for a R shiny dashboard?

I'm trying to create a line chart which is based on filter option along with data table. If I click the filter option it only changed in data table. But I want to set the filters for both Line chart and data table. Kindly help me.
My server.r code is:
output$grp_stacked_bar <- renderPlotly({
data <- ex
agg_sum <- aggregate(data$Result,by=list(Category = data$Donor_ID),FUN=sum, na.rm=TRUE)
p <- plot_ly(
data = agg_sum,
x = ~Category,
y = ~x,
type = "scatter",
mode = "lines+markers"
) %>% layout(title = "Functional Outlier Details", xaxis = list(title = "Donor_ID"),
yaxis = list(title = "Result"))
p
})
ui.r:
column(width = 10,
fluidRow(h2("Function Outlier Details",class="box-title",align="center"),
plotlyOutput(height="48vh",width ="82vw",outputId = "grp_stacked_bar")%>%withSpinner(color="#0dc5c1",hide.ui = FALSE,image.height = "73px",image.width = "145px",image= ".\\logo_gif2.gif"))
)
My sample dataset is:
enter image description here

Interacting with sg.image on a clic or a mouse fly over

I made a code using pysimplegui. it basically shows some images from a database based on a scanned number. it works but sometimes it could be useful to be able to increase the size of the image + it would make my user interface a bit more interactive
i want to have the possibility to either:
when i fly over the image with the mouse, i want the image to increase in size
have the possibility to clic on the image and have a pop-up of the image showing up (in a bigger size)
i am not sure on how to interact with a sg.image()
Below you will find a trunkated part of my code where i show my way of getting the image to show up.
layout = [
[
sg.Text("Numéro de boîte"),
sg.Input(size=(25, 1), key="-FILE-"),
sg.Button("Load Image"),
sg.Button("Update DATA"),
sg.Text("<- useless text ")
],
[sg.Text("Indicateur au max" , size = (120, 1),font = ("Arial", 18), justification = "center")],
[sg.Image(key="-ALV1-"),sg.Image(key="-ALV2-"), sg.Image(key="-ALV3-"), sg.Image(key="-ALV4-"), sg.Image(key="-ALV5-")],
[sg.Image(key="-ALV6-"),sg.Image(key="-ALV7-"), sg.Image(key="-ALV8-"), sg.Image(key="-ALV9-"), sg.Image(key="-ALV10-")],
[sg.Text("_" * 350, size = (120, 1), justification = "center")],
[sg.Text("Indicateur au milieu" , size = (120, 1),font = ("Arial", 18), justification = "center")],
[sg.Image(key="-ALV11-"),sg.Image(key="-ALV12-"), sg.Image(key="-ALV13-"), sg.Image(key="-ALV14-"), sg.Image(key="-ALV15-")],
[sg.Image(key="-ALV16-"),sg.Image(key="-ALV17-"), sg.Image(key="-ALV18-"), sg.Image(key="-ALV19-"), sg.Image(key="-ALV20-")],
[sg.Text("↓↓↓ ↓↓↓" , size = (120, 1),font = ("Arial", 18), justification = "center")],
]
ImageAlv1 = Image.open(PathAlv1)
ImageAlv1.thumbnail((250, 250))
bio1 = io.BytesIO()
ImageAlv1.save(bio1, format="PNG")
window["-ALV1-"].update(data=bio1.getvalue())
Using bind method for events, like
"<Enter>", the user moved the mouse pointer into a visible part of an element.
"<Double-1>", specifies two click events happening close together in time.
Using PIL.Image to resize image and io.BytesIO as buffer.
import base64
from io import BytesIO
from PIL import Image
import PySimpleGUI as sg
def resize(image, size=(256, 256)):
imgdata = base64.b64decode(image)
im = Image.open(BytesIO(imgdata))
width, height = size
w, h = im.size
scale = min(width/w, height/h)
new_size = (int(w*scale+0.5), int(h*scale+0.5))
new_im = im.resize(new_size, resample=Image.LANCZOS)
buffer = BytesIO()
new_im.save(buffer, format="PNG")
return buffer.getvalue()
sg.theme('DarkBlue3')
number = 4
column_layout, line = [], []
limit = len(sg.EMOJI_BASE64_HAPPY_LIST) - 1
for i, image in enumerate(sg.EMOJI_BASE64_HAPPY_LIST):
line.append(sg.Image(data=image, size=(64, 64), pad=(1, 1), background_color='#10C000', expand_y=True, key=f'IMAGE {i}'))
if i % number == number-1 or i == limit:
column_layout.append(line)
line = []
layout = [
[sg.Image(size=(256, 256), pad=(0, 0), expand_x=True, background_color='green', key='-IMAGE-'),
sg.Column(column_layout, expand_y=True, pad=(0, 0))],
]
window = sg.Window("Title", layout, margins=(0, 0), finalize=True)
for i in range(limit+1):
window[f'IMAGE {i}'].bind("<Enter>", "") # Binding for Mouse enter sg.Image
#window[f'IMAGE {i}'].bind("<Double-1>", "") # Binding for Mouse double click on sg.Image
element = window['-IMAGE-']
now = None
while True:
event, values = window.read()
if event == sg.WINDOW_CLOSED:
break
elif event.startswith("IMAGE"):
index = int(event.split()[-1])
if index != now:
element.update(data=resize(sg.EMOJI_BASE64_HAPPY_LIST[index]))
now = index
window.close()

Tkinter: Widget not being applied to the top right hand corner of the screen(grid)

I want to make a GUI for a voice assistant and for that when I try to use the grid option the label's get aligned at the centre of the screen when specified as column 2/3/4/5.
import tkinter
from tkinter import Canvas, Frame, Image, Label, StringVar, Tk, font
from tkinter.constants import ANCHOR, BOTTOM, E, END, GROOVE, RAISED, RIDGE, RIGHT, SUNKEN, TOP, Y
from typing import Text
window = tkinter.Tk()
window.title("App name")
window.geometry("320x640")
f = Frame(window)
x = f.grid_size()
# Add image file
bg = tkinter.PhotoImage(file = "Greybg.png")
# Show image using label
label1 = tkinter.Label( window, image = bg)
label1.place(x = 0, y = 0)
userimg = tkinter.PhotoImage(file = 'user1.png')
userlabel = tkinter.Label(window, image = userimg, bg = '#3D4154')
userlabel.place(relx = 1.0, rely = 0.01, anchor = 'ne')
def clicked():
print("Wow no error")
# Creating a photoimage object to use image
photo = tkinter.PhotoImage(file = "mic.png")
# here, image option is used to
# set image on button
micbtn = tkinter.Button(window, text = 'Click Me !', image = photo, bg = '#808588', border = 0, command = clicked).place(x = 142,y=580)
string_variable = tkinter.StringVar()
string_variable.set("User Text Here")
text = tkinter.Label(window, textvariable = string_variable, bg = "#80EAF7", wraplength= 250, pady = 1, padx = 1, fg = '#020402')
text.grid(row = 0, column=1, sticky=E,)
string_variable1 = tkinter.StringVar()
string_variable1.set("Assistant Reply here")
text1 = tkinter.Label(window, textvariable = string_variable1, wraplength= 250, pady = 1, padx = 1, fg = '#020402', font = ('Helvetica',8,'bold'))
text1.grid(row = 1, column=0)
window.resizable(0, 0)
window.mainloop()
In the above code, the icons get aligned like this, whereas I want the "User Text Here" to be at the top right-hand corner of the screen, how do I do that?
You can make columns 0 and 1 to use all the horizontal available space using
window.columnconfigure((0,1), weight=1)
Credit to https://stackoverflow.com/users/5317403/acw1668

TensorFlow training gets slower every batch

I am new to TensorFlow and I get my code running successfully by modifying tutorials from the official website.
I checked some other answers on StackOverflow, which says my problem is likely due to something is being added to the graph every time. However, I have no idea where to look for the code that might have caused this.
Also, I used tf.py_function to map the dataset because I really need to enable eagerly mode in the mapping.
def get_dataset(data_index):
# data_index is a Pandas Dataframe that contains image/label pair info, each row is one pair
data_index = prepare_data_index(data_index)
# shuffle dataframe here because dataset.shuffle is taking very long time.
data_index = data_index.sample(data_index.shape[0])
path = path_to_img_dir
# list of dataframe indices indicating rows that are going to be included in the dataset for training.
indices_ls = ['{}_L'.format(x) for x in list(data_index.index)] + ['{}_R'.format(x) for x in list(data_index.index)]
# around 310k images
image_count = len(indices_ls)
list_ds = tf.data.Dataset.from_tensor_slices(indices_ls)
# dataset.shuffle is commented out because it takes too much time
# list_ds = list_ds.shuffle(image_count, reshuffle_each_iteration=False)
val_size = int(image_count * 0.2)
train_ds = list_ds.skip(val_size)
val_ds = list_ds.take(val_size)
def get_label(index):
index = str(np.array(index).astype(str))
delim = index.split('_')
state = delim[1]
index = int(delim[0])
if state == 'R':
label = data_index.loc[index][right_labels].to_numpy().flatten()
elif state == 'L':
label = data_index.loc[index][left_labels].to_numpy().flatten()
return tf.convert_to_tensor(label , dtype=tf.float16)
def get_img(index):
index = str(np.array(index).astype(str))
delim = index.split('_')
state = delim[1]
index = int(delim[0])
file_path = '{}_{}.jpg'.format(data_index.loc[index, 'sub_folder'],
str(int(data_index.loc[index, 'img_index'])).zfill(4)
)
img = tf.io.read_file(os.path.join(path, file_path))
img = tf.image.decode_jpeg(img, channels=3)
full_width = 320
img = tf.image.resize(img, [height, full_width])
# Crop half of the image depending on the state
if state == 'R':
img = tf.image.crop_to_bounding_box(img, offset_height=0, offset_width=0, target_height=height,
target_width=int(full_width / 2))
img = tf.image.flip_left_right(img)
elif state == 'L':
img = tf.image.crop_to_bounding_box(img, offset_height=0, offset_width=int(full_width / 2), target_height=height,
target_width=int(full_width / 2))
img = tf.image.resize(img, [height, width])
img = tf.keras.preprocessing.image.array_to_img(
img.numpy(), data_format=None, scale=True, dtype=None
)
# Apply auto white balancing, output an np array
img = AWB(img)
img = tf.convert_to_tensor(img, dtype=tf.float16)
return img
def process_path(index):
label = get_label(index)
img = get_img(index)
return img, label
AUTOTUNE = tf.data.experimental.AUTOTUNE
train_ds = train_ds.map(lambda x: tf.py_function(
process_path,
[x], (tf.float16, tf.float16)), num_parallel_calls=AUTOTUNE)
val_ds = val_ds.map(lambda x: tf.py_function(
process_path,
[x], (tf.float16, tf.float16)), num_parallel_calls=AUTOTUNE)
def configure_for_performance(ds):
ds = ds.cache()
# ds = ds.shuffle(buffer_size=image_count)
ds = ds.batch(batch_size)
ds = ds.prefetch(buffer_size=AUTOTUNE)
return ds
train_ds = configure_for_performance(train_ds)
val_ds = configure_for_performance(val_ds)
return train_ds, val_ds
Can anyone please help me? Thanks!
Here is the rest of my code.
def initialize_model():
IMG_SIZE = (height, width)
preprocess_input = tf.keras.applications.vgg19.preprocess_input
IMG_SHAPE = IMG_SIZE + (3,)
base_model = tf.keras.applications.VGG19(input_shape=IMG_SHAPE,
include_top=False,
weights='imagenet')
global_average_layer = tf.keras.layers.GlobalAveragePooling2D()
prediction_layer = tf.keras.layers.Dense(class_num, activation=tf.nn.sigmoid, use_bias=True)
inputs = tf.keras.Input(shape=(height, width, 3))
x = preprocess_input(inputs)
x = base_model(x, training=True)
x = global_average_layer(x)
outputs = prediction_layer(x)
model = tf.keras.Model(inputs, outputs)
def custom_loss(y_gt, y_pred):
L1_loss_out = tf.math.abs(tf.math.subtract(y_gt, y_pred))
scaler = tf.pow(50.0, y_gt)
scaled_loss = tf.math.multiply(L1_loss_out, scaler)
scaled_loss = tf.math.reduce_mean(
scaled_loss, axis=None, keepdims=False, name=None
)
return scaled_loss
base_learning_rate = 0.001
model.compile(optimizer=tf.keras.optimizers.SGD(learning_rate=base_learning_rate, momentum=0.9),
loss=custom_loss,
metrics=['mean_absolute_error']
)
return model
def train(data_index, epoch_num, save_path):
train_dataset, validation_dataset = get_dataset(data_index)
model = initialize_model()
model.summary()
history = model.fit(train_dataset,
epochs=epoch_num,
validation_data=validation_dataset)
model.save_weights(save_path)
return model, history

Unity3d SelectionGrid cell size adjustment

I try to create game options but got problem with cell size adjustment.For option "First move" I use names of users. I want to increase cell if name is too long. Or decrease font size if it easier.
Style for cells:
mCellStyle = new GUIStyle();//style for cells
mCellStyle.normal.background = Resources.Load<Texture2D>("Textures/button_up_9patch");
mCellStyle.onNormal.background = Resources.Load<Texture2D>("Textures/button_down_9patch");
mCellStyle.focused.background = mButtonStyle.active.background;
mCellStyle.fontSize = GUIUtils.GetKegel() - GUIUtils.GetKegel() / 5;
mCellStyle.border = new RectOffset(7, 7, 7, 7);
mCellStyle.padding = new RectOffset(20, 20, 20, 20);
mCellStyle.alignment = TextAnchor.MiddleCenter;
mCellStyle.wordWrap = true;
My code:
GUIStyle lBackStyle = new GUIStyle(mCellStyle);
lBackStyle.fontSize = GUIUtils.GetKegel();
lBackStyle.active.background = null;
lBackStyle.focused.background = null;
GUIStyle lStyle = new GUIStyle(lBackStyle);
lStyle.normal.background = null;
//create contents and calculate height
GUIContent lContent1 = new GUIContent(LanguageManager.GetText("FirstMove"));
float lElemH1 = lStyle.CalcHeight(lContent1, lMaxWidht);
GUIContent[] lArrayContent2 = new GUIContent[] { new GUIContent(MainScript.Logic.UserName), new GUIContent(MainScript.Logic.NurslingName) };
float lElemH2 = mCellStyle.CalcHeight(lArrayContent2[0], lMaxWidht);
GUIContent lContent3 = new GUIContent(LanguageManager.GetText("Difficulty"));
float lElemH3 = lStyle.CalcHeight(lContent3, lMaxWidht);
GUIContent[] lArrayContent4 = new GUIContent[] { new GUIContent(LanguageManager.GetText("Easy")), new GUIContent(LanguageManager.GetText("Hard")) };
float lElemH4 = mCellStyle.CalcHeight(lArrayContent4[0], lMaxWidht);
float lTotalH = lElemH1 + lElemH2 + lElemH3 /*+ 100*/;//reserve 100 for paddings
GUILayout.BeginArea(mAreaRect);
GUILayout.BeginVertical(lBackStyle, GUILayout.Height(lTotalH));
GUILayout.Label(lContent1, lStyle);
GamePreferences.setAIMakesFirstMove(GUILayout.SelectionGrid(GamePreferences.getAIMakesFirstMove(), lArrayContent2, 2, mCellStyle));
GUILayout.Label(lContent3, lStyle);
GamePreferences.setDifficulty(GUILayout.SelectionGrid(GamePreferences.getDifficulty(), lArrayContent4, 2, mCellStyle));
GUILayout.EndVertical();
GUILayout.EndArea();
ADDED: I just want to set height of cell in Selection Grid. Is it possible?
Ok, I found that I can pass GUILayoutOption as last parameter to set the height of cells:
GUILayout.SelectionGrid(GamePreferences.getFirstMove(), lArrayContent2, 2, mCellStyle, GUILayout.Height(lCellHeight))
But I still have no idea how I can fit cell size to it content.
float lElemH2 = mCellStyle.CalcHeight(lArrayContent2[0], lMaxWidht);
mCellStyle.CalcHeight ignores lenght of content and in lElemH2 I got height for single line text.
EDITED:
My fault, I sent wrong parameters to CalcHeight. Correct version:
float lElemH2 = mCellStyle.CalcHeight(lArrayContent2[0], lMaxWidht / cellsCount);

Resources