How to build a simple widget or app in jupyter notebook/lab to interactively extract a substring from text? - jupyter-notebook

I want iterate over a list of string, output the string as plain text in jupyter lab then interactively highlight a substring to get easily the start index of the substring and the length. The goal is to do a quick annotation of text and get the coordinates of the substring.
Is it easy or even possible to do something like this with jupyter notebook (lab)? If then How?
I had a look at ipywidgets but couldn't find something for this use case.

Here's an example with the RangeSlider:
import ipywidgets
input_string = 'averylongstring'
widg = ipywidgets.IntRangeSlider(
value = [0, len(input_string)],
min=0, max=len(input_string)
)
output_widg = ipywidgets.Text()
display(widg)
display(output_widg)
def chomp_string(widg):
start,end = tuple(widg['new'])
output_widg.value = input_string[start: end]
widg.observe(chomp_string, names='value')

You can implement this using jp_proxy_widgets. See the following screenshot:
Note that there are warnings about compatibility for selection protocols -- I only tested this on Chrome on a Mac. Also I don't know why the indices are off by one
(select_callback(startOffset+1, endOffset+1);)
Please see https://github.com/AaronWatters/jp_proxy_widget for more information
Edit: Here is the pastable text as requested:
import jp_proxy_widget
select_widget = jp_proxy_widget.JSProxyWidget()
txt = """
Never gonna give you up.
Never gonna let you down.
Never gonna run around and
desert you.
"""
selected_text = None
def select_callback(startOffset, endOffset):
global selected_text
selected_text = txt[startOffset: endOffset]
print ("Selected", startOffset, endOffset, repr(selected_text))
select_widget.js_init("""
// (Javascript) Add a text area.
element.empty()
$("<h3>please select text:</h3>").appendTo(element);
var textarea = $('<textarea cols="50" rows="5">' + txt + "</textarea>").appendTo(element);
// Attach a select handler that calls back to select_callback.
var select_handler = function(event) {;
var target = event.target;
var startOffset = target.selectionStart;
var endOffset = target.selectionEnd;
select_callback(startOffset+1, endOffset+1);
};
textarea[0].addEventListener('select', select_handler);
""", txt=txt, select_callback=select_callback)
# display the widget
select_widget.debugging_display()

Related

InDesign - Script to find specific words between angle brackets, and copy those to a list

Sorry in advance if I’m not phrasing this question correctly. I know nothing about InDesign scripting, but this would solve a workflow problem I’m having at my company, so I would appreciate any and all help.
I want to find all strings in an InDesign file that are between angle brackets (i.e. <variable>) and export that out into a list. Ideally this list would be a separate document but if it can just be dumped into a text frame or something that’s fine.
Any ideas on how to do this? Thank you in advance for any and all help.
Here is something simple:
app.findGrepPreferences=NothingEnum.NOTHING; //to reset the Grep search
app.findGrepPreferences.findWhat = '<[^<]+?>'; //the word(s) you are searching
var fnd = app.activeDocument.findGrep (); //execute search
var temp_str = ''; //initialize an empty string
for (var i = 0; i < fnd.length; i++) { //loop through results and store the results
temp_str += fnd[i].contents.toString() + '\r'; // add next found item text to string
}
var new_doc = app.documents.add (); //create a new document
app.scriptPreferences.measurementUnit = MeasurementUnits.POINTS; //set measurement units to points
var text_frame = new_doc.pages[0].textFrames.add({geometricBounds:[0,0,100,100]});// create a new text frame on the first page
text_frame.contents = temp_str; //output your text to the text frame in the new document
For more data see here.

Python webdriver switch from main window to popup screen (not Java alert) and login

Here is the window I need to enter new password and repeat it again and click 'create'.
My code so far:
createLogin = wait.until(EC.presence_of_element_located((By.XPATH, '//*[#id="Item.MessageUniqueBody"]/div/div/div/div/div[2]/div[2]/a')))
createLogin.click()
time.sleep(10)
try:
newPassword = self.driver.find_elements_by_xpath('//*[#id="editNewUser_newPassword"]')
newPassword1 = self.driver.find_elements_by_xpath('//*[#id="editNewUser_newPasswordRepeat"]')
newPasswordForm = self.driver.find_elements_by_xpath('//*[#id="editNewUserPasswordForm"]/table/tbody/tr[1]/td[1]')
self.driver.switch_to.active_element(newPasswordForm)
time.sleep(3)
newPassword.send_keys('123')
newPassword1.send_keys('123')
time.sleep(2)
# createLog = wait.until(
# EC.presence_of_element_located((By.XPATH, '//*[#id="editNewUserPassword_save"]')))
# createLog.click()
# time.sleep(5)
except NoAlertPresentException as e:
time.sleep(2)
myAccount = wait.until(
EC.presence_of_element_located((By.XPATH, '//*[#id="easMyAccount1"]')))
myAccount.click()
time.sleep(5)
This is the problem.
You are using find_elements_by_xpath rather than find_element_by_xpath
plural vs singular.
find_elements_by_xpath: it gives you a list of web elements with matching identifier.
find_element_by_xpath: it gives you a first web element with matching identifier.
newPassword = self.driver.find_element_by_xpath('//*[#id="editNewUser_newPassword"]')
newPassword1 = self.driver.find_element_by_xpath('//*[#id="editNewUser_newPasswordRepeat"]')
newPasswordForm = self.driver.find_element_by_xpath('//*[#id="editNewUserPasswordForm"]/table/tbody/tr[1]/td[1]')
#gauurang Answer is right, But You have to used find_element_by_xpath, also as your xpath suggested you have id to locate the webelements so it is always better to use id over xpath
Also your xpath are correct
newPassword = self.driver.find_element_by_id('editNewUser_newPassword')
newPassword1 = self.driver.find_element_by_id('editNewUser_newPasswordRepeat')
newPasswordForm = self.driver.find_element_by_xpath('//*[#id="editNewUserPasswordForm"]/table/tbody/tr[1]/td[1]')

kivy button ID's within functions

I am working on a fantasy football type app for a school project.
We have created a scrollview with a list of characters in a team within it, each assigned to a button. on press of the button a new scrollview displaying a second list of 'inactive character buttons' is displayed, allowing the user to press one to swap the first and second character from team to team.
our issue comes from a difficulty in managing to 'locate' which button is pressed in order to tell our swap function which two characters to swap on the list. Is it possible to retain the id of a button and call it into a new function on press of said button?
Our code is a bit messy, but is displayed bellow:
class SMApp(App):
teamlist = []
idvar = ""
btnlist = []
def popupfunc(self, event):
"""
creates a popup asking if the user wishes to swap a character from team to subs
then proceeds to allow user to choose who swaps
"""
def subscroll(self):
"""
opens scroll list of substitute characters in a popup
"""
sublist = []
curs.execute('SELECT * FROM Subs')
for row in curs:
sublist.append([row[0], row[2]])
layout = GridLayout(cols=2, spacing=10, size_hint_y=None)
layout.bind(minimum_height=layout.setter('height'))
for i in range(len(sublist)):
btn = Button(text=str(sublist[i][0]), size_hint_y=None, height=40)
layout.add_widget(btn)
lbl = Label(text=str(sublist[i][1]), size_hinty=None, height=40)
layout.add_widget(lbl)
root = ScrollView(size_hint=(None, None), size=(400, 400))
root.add_widget(layout)
popup2 = Popup(content=root, size=(7, 10), size_hint=(0.55, 0.8), title="list of subs")
popup2.open()
box = BoxLayout()
btn1 = Button(text='yeah ok')
btn2 = Button(text='nope')
popup1 = Popup(content=box, size=(10, 10), size_hint=(0.3, 0.3), title="add to team?")
btn2.bind(on_press=popup1.dismiss)
btn1.bind(on_press=subscroll)
box.add_widget(btn1)
box.add_widget(btn2)
popup1.open()
def build(self):
curs.execute('SELECT * FROM Team')
for row in curs:
self.teamlist.append([row[0], row[2]])
layout = GridLayout(cols=2, spacing=10, size_hint_y=None)
layout.bind(minimum_height=layout.setter('height'))
for i in range(len(self.teamlist)):
btn = Button(text=str(self.teamlist[i][0]), size_hint_y=None, height=40, id=str(i))
btn.bind(on_press=self.popupfunc)
self.btnlist.append(btn)
layout.add_widget(btn)
lbl = Label(text=str(self.teamlist[i][1]), size_hinty=None, height=40)
layout.add_widget(lbl)
for item in self.btnlist:
print item.id
root = ScrollView(size_hint=(None, None), size=(400, 400),
pos_hint={'center_x':.5, 'center_y':.5})
root.add_widget(layout)
return root
if __name__ == '__main__':
SMApp().run()
Each of the btn = Button(...) you create is a different object, therefore you can tell which is pressed. The thing is what way you'll choose.
You can use:
str(your button) and get a specific object address(?) like 0xAABBCCEE
bad, don't do that
Button(id='something', ...)
ids from kv language
or create own widget with a property for specific identificator. Then you'd use a loop for the parent's children which would check for identificator and do something:
for child in layout.children:
if child.id == 'something':
# do something
And it seems you'd need this loop inside your subscroll, or access that layout some other way.

testcomplete dealing with save file in wordpad

could anyone help how to deal with ribbon commnad bars in testcomplete
I'm trying to save a wordpad file
I'm writing the next code
function saveFile() {
TestedApps.wordpad.Run();
var pWordPad = Sys.Process("wordpad");
var wWordPad = pWordPad.Window("WordPadClass", "Документ - WordPad", 1).Window("RICHEDIT50W", "", 1);
wWordPad.Keys("smth");
var ribbon = pWordPad.Window("WordPadClass", "* - WordPad", 1).Window("UIRibbonCommandBarDock", "UIRibbonDockTop", 3).Window("UIRibbonCommandBar", "Ribbon", 1).Window("UIRibbonWorkPane", "Ribbon", 1).Window("NUIPane", "", 1).Window("NetUIHWND", "", 1);
}
Here I'm stack...I wonder how to open dialog save file?
I tried like this
ribbon.Click("File|Save as...");
however, it doen't work
Use keyboard shortcuts to work with Ribbon in WordPad.
function wordPadSaveAs()
{
var wordpad = Sys.Process("wordpad");
wndWordPadClass = wordpad.Window("WordPadClass", "*");
wndWordPadClass.Activate();
Sys.Keys("~fa");
}
You need to add the NetUIHWND class name to the MSAA or UI Automation list so that TestComplete could recognize different objects on a ribbon. After this, try recording the actions.

Getting my buttons to add text to a list

I'm having a problem getting my buttons to actually do something, when one of the buttons on the top left are clicked, I want a text box in the frame below it adding the name of that button to a list but getting really stuck with it, any help would be much appreciated, thank you
Here is my code:
import tkinter
import tkinter as tk
root = tk.Tk()
root.geometry('1000x600')
var=tk.StringVar()
Frame1 = tk.Frame(root)
Frame1.configure(background='light blue',height='300',width='500')
Frame1.grid(sticky="nsew",row='0',column='0')
Frame2 = tk.Frame(root)
Frame2.configure(background='grey',height='300',width='500')
Frame2.grid(sticky="nsew",row='0',column='1')
Frame3 = tk.Frame(root)
Frame3.configure(background='grey',height='300',width='500')
Frame3.grid(sticky="nsew",row='1',column='0')
Frame4 = tk.Frame(root)
Frame4.configure(background='light blue',height='300',width='500')
Frame4.grid(sticky="nsew",row='1',column='1')
def PrintOrder():
LabelOrder = tk.Label(Frame3,text="DONUT ORDER")
LabelOrder.grid(row='0',column='0')
return
Button1 = tk.Button(Frame1,text="Apple Cinnamon",height='2',width='15',padx=10, pady=5,command=PrintOrder).grid(row='0',column='0')
Button2 = tk.Button(Frame1,text="Strawberry",height='2',width='15',padx=10, pady=5,command=PrintOrder).grid(row='0',column='2')
Button3 = tk.Button(Frame1,text="Custard",height='2',width='15',padx=10, pady=5,command=PrintOrder).grid(row='0',column='4')
Button4 = tk.Button(Frame1,text="Sugar Ring",height='2',width='15',padx=10, pady=5,command=PrintOrder).grid(row='2',column='0')
Button5 = tk.Button(Frame1,text="Chocolate Caramel",height='2',width='15',padx=10, pady=5,command=PrintOrder).grid(row='2',column='2')
Button6 = tk.Button(Frame1,text="Lemon Circle",height='2',width='15',padx=10, pady=5,command=PrintOrder).grid(row='2',column='4')
Button7 = tk.Button(Frame1,text="Blueberry Blaster",height='2',width='15',padx=10, pady=5,command=PrintOrder).grid(row='4',column='0')
Button8 = tk.Button(Frame1,text="Strawberry Surprise",height='2',width='15',padx=10, pady=5,command=PrintOrder).grid(row='4',column='2')
Button9 = tk.Button(Frame1,text="Simple Sugar",height='2',width='15',padx=10, pady=5,command=PrintOrder).grid(row='4',column='4')
Label1 = tk.Label(Frame2,text="Donut special 6 for the price of 5",height='5',width='30').grid(row='0',column='0')
Button10 = tk.Button(Frame2,text="SPECIAL",padx=5, pady=5,height='5',width='20').grid(row='2',column='0')
Button11 = tk.Button(Frame3,text="ORDER TOTAL",padx=5, pady=5,height='5',width='20').grid(row='2',column='0')
Button12 = tk.Button(Frame4,text="RUNNING TOTAL",padx=5, pady=5,height='5',width='20').grid(row='2',column='0')
root.mainloop()
The problem is that when you call the PrintOrder function, it doesn't necessarily know what button called it.
To fix this, use a lambda: [see http://effbot.org/zone/tkinter-callbacks.htm, "Passing Arguments to Callbacks"]
Also, you'll need variable strings to work with the list.
Above your PrintOrder function, write this (move the Label creation outside of the function):
LabelContents = tk.StringVar()
LabelOrder = tk.Label(Frame3, textvariable=LabelContents)
LabelOrder.grid(row='0', column='0')
then you can update the text in the label.
So change the PrintOrder function to
def PrintOrder(flavor):
LabelContents.set(LabelContents.get() + '\n' + flavor)
return
This appends the flavor, with a new line, to the label.
then in the button:
Button(text="lemon", command=lambda: PrintOrder("lemon"))
Of course you can modify to fit your program.
For the reasoning behind the lambda, see the link.
Hope that helps!

Resources