Bokeh slider change length of x - callback

In a given DataSeries I want to use a Bokeh slider to change the number of observations I show (the tail). Can this be done, if it can why won't my script work?
import pandas as pd
from bokeh.plotting import show, output_file
from bokeh.models import CustomJS, Slider, Column
from bokeh.io import output_notebook
ds = pd.Series( [i for i in range(20)], pd.date_range('2016-01-02', periods=20, freq='D'))
tail = 5
ds.tail(tail)
#Bokeh slider to change value of "tail"
s1 = Slider(start=1, end=20, value=3, step=1)
s1.callback = CustomJS(args=dict(s1=s1, tail=tail), code="""
ds.tail("tail", s1.get('value'));
""")
show(Column(s1))
ds.tail(tail)

Related

NotFittedError: Vocabulary not fitted or provided or TypeError: string indices must be integers

Hello everyone, im new hier and want to start learning how machine learning works. So i want to build a machine learning email spam detector in colab, but something seems to be wrong:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import nltk import string
from nltk.corpus import stopwords
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB, GaussianNB
from sklearn import svm
from sklearn.model_selection import GridSearchCV
from google.colab import files
uploaded = files.upload() filename = ('spam.tsv')
content = []
with open(filename, "r") as file_content:
for line in file_content.readlines():
line = line.strip() content.append(line)
spam = line
#print(spam) for testinn if it is working
z = spam['EmailText']
y = spam["Label"]
z_train, z_test,y_train, y_test = train_test_split(z,y,test_size = 0.2)
count_vector = CountVectorizer()
features = count_vector.transform(z_train)
model = svm.SVC()
model.fit(features,y_train)
features_test = count_vector.transform(z_test)
print(model.score(features_test,y_test))`
NotFittedError: Vocabulary not fitted or provided TypeError: string indices must be integers
i tried everything but nothing works really haha
i hope, you can help
thank you

how to trigger callback event on a plotly scattermapbox plot

I am trying to run the code below, and the map is generated correctly (showing the locations of interest), but when clicking on a location, the callback function is not triggered. I have tried setting the layout to 'clickmode': 'event', and then the selected point is highlighted, but the callback function is not triggered. It must be something small, but I can't figure out what I am missing, any help or suggestion is highly appreciated.
# Import libraries
import pandas as pd
import numpy as np
import plotly.express as px
import plotly.graph_objects as go
import json
import ipywidgets as widgets
from ipywidgets import Output, VBox
data2 = go.Scattermapbox(lat=list(heat_df.ycoord),
lon=list(heat_df.xcoord),
mode='markers+text',
marker=dict(size=20, color='green'),
)
layout = dict(margin=dict(l=0, t=0, r=0, b=0, pad=0),
mapbox=dict(#accesstoken=mapbox_access_token,
center=dict(lat=51.6, lon=-0.2),
style='light',
zoom=8))
f2 = go.FigureWidget(data=data2, layout=layout);
f2.update_layout(mapbox_style="stamen-terrain"
, mapbox_center = {"lat": map_meanY, "lon": map_meanX}
, mapbox_zoom= 11
#, clickmode='event'
);
scatter = f2.data[0]
scatter.marker.size = [20] * 100
f2.layout.hovermode = 'closest'
out = Output()
#out.capture(clear_output=True)
def click_callback(trace, points, selector):
inds = points.point_inds
print(inds)
f2.data[0].on_click(click_callback,append=False)
#help(f2.data[0].on_click)
f2
Setting mode='markers+text', to mode='markers' throws in the ValueError:
File ~\anaconda3\envs\geemap_test\lib\site-packages\plotly\basedatatypes.py:2637, in BaseFigure._perform_plotly_relayout(self, relayout_data)
2633 for key_path_str, v in relayout_data.items():
2635 if not BaseFigure._is_key_path_compatible(key_path_str, self.layout):
-> 2637 raise ValueError(
2638 """
2639 Invalid property path '{key_path_str}' for layout
2640 """.format(
2641 key_path_str=key_path_str
2642 )
2643 )
2645 # Apply set operation on the layout dict
2646 val_changed = BaseFigure._set_in(self._layout, key_path_str, v)
ValueError:
Invalid property path 'mapbox._derived' for layout

overlay a small image on multiple biger images and save them in a different folder

Hi i want to overlay or paste an image on bigger images(have a folder containinf 10 images and want to overlay the smaller images on all 10) and save them in a different folder. I did try somethings but ran into errors.
import scipy.misc
import numpy as np
import os
import cv2
outPath = "C:\darkflow\Augmented Images\augmented_images\.."
cov = cv2.imread("C:\darkflow\Augmented Images\extracted\cover\extracted_cover.jpg")
bgs = [cv2.imread(file) for file in glob.glob("C:\darkflow\Augmented Images\images\*.jpg")]
for bg in bgs:
bg[y_offset:y_offset+s_img.shape[0], x_offset:x_offset+s_img.shape[1]] = cov
f_image = cv2.cvtColor(bg, cv2.COLOR_BGR2RGB)
fullpath = os.path.join(outPath, 'augmented_'+ bg)
misc.imsave(fullpath, f_image)
with this code i get an error : ufunc 'add' did not contain a loop with signature matching types dtype('
I found the answer while looking into the code. My code is
from scipy import ndimage, misc
import scipy.misc
import numpy as np
import os
import cv2
cov = cv2.imread("C:\darkflow\Augmented Images\extracted\cover\extracted_cover.jpg")
bgs = [cv2.imread(file) for file in glob.glob("C:\darkflow\Augmented Images\images\*.jpg")]
d=1
x_offset=100
y_offset= 100
for bg in bgs:
bg[y_offset:y_offset+ cov.shape[0], x_offset:x_offset+ cov.shape[1]] = cov
filename = "images/file_%d.jpg"%d
cv2.imwrite(filename, bg)
d+=1

Resize screenshot with mss for better reading with pytesseract

I need to resize an screenshot taken by mss in order to get better reading by pytesseract and i get it done with pil+pyscreenshot but can't get it to with mss.
from numpy import array, flip
from mss import mss
from pytesseract import image_to_string
from time import sleep
def screenshot():
cap = array(mss().grab({'top': 171, 'left': 1088, 'width': 40, 'height': 17}))
cap = flip(cap[:, :, :3], 2)
return cap
def read(param):
tesseract = image_to_string(param)
return tesseract
while True:
print(read(screenshot()))
sleep(2)
here its working with pyscreenshot
from time import sleep
from PIL import Image, ImageOps
import pyscreenshot as ImageGrab
import pytesseract
while 1:
test = ImageGrab.grab(bbox=(1088,171,1126,187))
testt = ImageOps.fit(test, (50, 28), method=Image.ANTIALIAS)
testt.save('result.png')
read = pytesseract.image_to_string(testt)
print(read)
sleep(2)
And, i don't care about maintain aspect radio, works better that way with pytesseract.

Bokeh's hovertool inipython refuses to display tooltips

I literally copy and pasted the example of how to use the hover tool from bokeh's documentation and I still can't get this damn thing to work. I just want bokeh's hover tool to display the x and y coordinates. I think I've implemented it correctly but let me know if anything's wrong. (The ASCII file reads in flawlessly and the graph plots correctly and all the other tools work)
from bokeh.plotting import *
from bokeh.objects import HoverTool
from collections import OrderedDict
output_notebook()
%matplotlib inline
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import mpld3
from mpld3 import plugins, utils
mpld3.enable_notebook()
from pylab import *
import pandas as pd
chip1 = pd.io.parsers.read_table("Chip1_Buffer_ASCII", sep=";")
chip2 = pd.io.parsers.read_table("Chip2_Buffer_ASCII", sep=";")
chip3 = pd.io.parsers.read_table("Chip3_Buffer_ASCII", sep=";")
chip1_1=chip1
chip1_2=chip2
chip1_3=chip3
chip1_1["Frequency (Hz)"]=chip1["Frequency (Hz)"].map(lambda x: math.log10(x))
chip1_2["Frequency (Hz)"]=chip2["Frequency (Hz)"].map(lambda x: math.log10(x))
chip1_3["Frequency (Hz)"]=chip3["Frequency (Hz)"].map(lambda x: math.log10(x))
diff_1_2 = chip1 - chip2
diff_1_2["Frequency (Hz)"] = chip1_1["Frequency (Hz)"]
source1 = ColumnDataSource(chip1_1.to_dict("list"))
source2 = ColumnDataSource(chip1_2.to_dict("list"))
source3 = ColumnDataSource(chip1_3.to_dict("list"))
source4=ColumnDataSource(diff_1_2.to_dict("list"))
import bokeh.plotting as bk
bk.figure(plot_width=600, # in units of px
plot_height=600,
title="Hello World!",
tools="pan,wheel_zoom,box_zoom,select,reset,hover")
bk.hold()
bk.line("Frequency (Hz)", "-Phase (°)",line_width=2,source=source1,logx=True,color="red",xlim=[0, 10000])
bk.line("Frequency (Hz)", "-Phase (°)",line_width=2,source=source2,logx=True,color="green",xlim=[0, 10000])
bk.line("Frequency (Hz)", "-Phase (°)",line_width=2,source=source3,logx=True,color="orange",xlim=[0, 10000])
bk.line("Frequency (Hz)", "-Phase (°)",line_width=2,source=source4,logx=True,color="orange",xlim=[0, 10000])
hover = bk.curplot().select(dict(type=HoverTool))
hover.tooltips=OrderedDict([
("(x,y)", "($x, $y)"),
("index", "$index")
])
bk.show()