问:
Store multiple corpus via for loop by different names
I have multiple text documents per ticker which I want to store as an individual corpus.
I've read about creating ''lists in lists'', but this doesn't work for me. For example, ''text mining and termdocumentmatrix'' give the following error: no applicable method for 'TermDocumentMatrix' applied to an object of class "list.

I could possibly put everything within the for loop, but that's not what I want since I want some flexibility to play with the corpus.

Could someone help me out how I can effectively work around this problem? My code is below. Thank you in advance!

```<code>Stocks <- list("AAPL", "AMZN", "BIG", "BYD", "CTWS", "EAT", "FB", "GOOG", "GRMC", "HRL", "MGM", "MSFT",
               "NEM", "PKS", "RGLD", "SCCO", "SLP", "TCO", "USGL", "WDFC"
)

BigList <- list()
for (stock in Stocks) {
  filepath <- file.path("C:/Users/......./Stocks10K", stock)
  a <- Corpus(DirSource(filepath))
  a <- tm_map(a, removePunctuation)
  a <- tm_map(a, removeNumbers)
  a <- tm_map(a, tolower)
  a <- tm_map(a, removeWords, stopwords("en"))
  a <- tm_map(a, stripWhitespace)
  name <- paste('Data:', stock, sep='')
  tmp <- list(Text = a)
  BigList[name] <- tmp
  rm(tmp, stock, name, filepath, a)
}

#Create Term Document Matrix and create Matrix
tdm <- TermDocumentMatrix(BigList['Data:AAPL'])
m <- as.matrix(tdm)
</code>```

答:
It looks like you've done everything right, except getting your entry out of BigList. [ will return a list (containing one element in your case) - you need [[ instead.  Try:

```<code>tdm <- TermDocumentMatrix(BigList[['Data:AAPL']])
</code>```

instead.

https://cran.r-project.org/doc/manuals/R-lang.html#Indexing has more info, including this note (in case what I said above isn't clear):

For lists, one generally uses [[ to select any single element, whereas
  [ returns a list of the selected elements.

Body:
I have multiple text documents per ticker which I want to store as an individual corpus.
I've read about creating ''lists in lists'', but this doesn't work for me. For example, ''text mining and termdocumentmatrix'' give the following error: no applicable method for 'TermDocumentMatrix' applied to an object of class "list.

I could possibly put everything within the for loop, but that's not what I want since I want some flexibility to play with the corpus.

Could someone help me out how I can effectively work around this problem? My code is below. Thank you in advance!

Stocks <- list("AAPL", "AMZN", "BIG", "BYD", "CTWS", "EAT", "FB", "GOOG", "GRMC", "HRL", "MGM", "MSFT",
               "NEM", "PKS", "RGLD", "SCCO", "SLP", "TCO", "USGL", "WDFC"
)

BigList <- list()
for (stock in Stocks) {
  filepath <- file.path("C:/Users/......./Stocks10K", stock)
  a <- Corpus(DirSource(filepath))
  a <- tm_map(a, removePunctuation)
  a <- tm_map(a, removeNumbers)
  a <- tm_map(a, tolower)
  a <- tm_map(a, removeWords, stopwords("en"))
  a <- tm_map(a, stripWhitespace)
  name <- paste('Data:', stock, sep='')
  tmp <- list(Text = a)
  BigList[name] <- tmp
  rm(tmp, stock, name, filepath, a)
}

#Create Term Document Matrix and create Matrix
tdm <- TermDocumentMatrix(BigList['Data:AAPL'])
m <- as.matrix(tdm)

Body:
It looks like you've done everything right, except getting your entry out of BigList. [ will return a list (containing one element in your case) - you need [[ instead.  Try:

tdm <- TermDocumentMatrix(BigList[['Data:AAPL']])

instead.

https://cran.r-project.org/doc/manuals/R-lang.html#Indexing has more info, including this note (in case what I said above isn't clear):

For lists, one generally uses [[ to select any single element, whereas
  [ returns a list of the selected elements.


来源: stackexchange

问:
Editing Play 2.8 Twirl templates in Eclipse
The same question was asked 3 years ago. However, the answer from that time is no longer valid.

I have the last stable version of Debian and the last version of Eclipse (2020-03) running on it. I have a Java Play 2.8 project which sbt compiles and runs just fine. I am able to edit all source files (.java code and .scala.html templates) in Eclipse. However, template files in the Eclipse editor look like ordinary text opened in Notepad: no syntax highlighting, no syntax checking. Editing cmplicated template files without any help from the IDE is very painful.

In the past I was able to download Scala IDE plugin with Play support from Scala IDE project. However, Scala plugin for Eclipse seems to be gone (it's not being developed any more). My tries to install the last version of the plugin have failed.

What is the right way to edit Play templates in Eclipse right now? I need at least syntax highlighting, syntax checking is not critical.

答:
i use eclipse on Linux mint cinnamon, the same version as yours.
in the eclipse marketplace, i can see a plugin is available which can be used for this purpose,
in eclipse, Help->Eclipse Marketplace and then search for Scala IDE 4.7.x and install it.

hopefully this will work.

ContentLicense: CC BY-SA 4.0


问:
How to use the close (X) or any other button while an infinite loop is running in Tkinter
I am writing a program for a GUI to support my Voice Assistant Python script using tkinter. But the problem is once the Voice Assistant program is activated, that is the infinite loop of the function of continuously listening to what the user says is executed, the whole window freezes and I cannot click on any other button and I am not being able to access the close (X) button also. I know I need to use threading in this case but I am not getting the idea of where to use it exactly to achieve my desire. I would be highly obliged if somebody would help me out with this. I am giving the whole code that I have written to help you out with the problem. The infinite running function in the program is Geega()

```<code>from tkinter import *
import tkinter.font as font
import tkinter.messagebox as tmsg
import pyttsx3
import speech_recognition as sr
import datetime
import wikipedia
import webbrowser
import os
import time
import smtplib
import random
import wolframalpha
import apiai
import json
import _thread

#API configuration
engine = pyttsx3.init('sapi5')
client = wolframalpha.Client('AQKXVX-UVQ8TUWUVU')
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[1].id)

#Conversation mode
def convo_mode():
    Text_frame1['text'] = "Geega has entered conversation mode..."
    Button_frame1 = Button(Frame1, image=Button_image, bg='#444444', borderwidth=0, height=200, width=200, state=DISABLED, activebackground='#444444').place(x=5,y=15)
    # Button_frame3 = Button(Frame3, text='Button', bg='white', borderwidth=0, cursor='hand2', state=DISABLED, activebackground='#444444').place(x=5,y=15)
    Button_frame3 = Button(Frame3, image=Button_image2, bg='#333333', borderwidth=0, height=80, width=250, cursor='hand2', command=convo_mode, state=DISABLED, activebackground='#333333').place(x=320,y=360)
    main_window.update()
    speak("Geega has entered Conversation mode...")
    query = takeCommand().lower()
    while "back" not in query:
        response = apiai_connc(query)
        speak(response)
        query = pause().lower()
    else:
        speak("Re-entering Normal Mode...")
        Button_frame1 = Button(Frame1, image=Button_image, bg='#444444', borderwidth=0, height=200, width=200, state=NORMAL, cursor= 'hand2', activebackground='#444444', command=Geega).place(x=5,y=15)
        # Button_frame3 = Button(Frame3, text="Button", bg='white', borderwidth=0, cursor='hand2', state=NORMAL, activebackground='#444444', command = convo_mode).place(x=5,y=15)
        Button_frame3 = Button(Frame3, image=Button_image2, bg='#333333', borderwidth=0, height=80, width=250, cursor='hand2', command=convo_mode, state=NORMAL, activebackground='#333333').place(x=320,y=360)
        Text_frame1['text'] = "Geega has entered Normal mode..."
        main_window.update()

#Function for instructions
def Instructions():
    Instruction = tmsg.showinfo("Instructions", "- Click the mic to activate Geega\n\n- Say \'Hello Geega\' before each command to make Geega do it\n\n- Click on \'Turn on Conversation Mode\' to enter Conversation Mode to make Geega answer your questions!\n\nNote: Geega would not execute command when running in Conversation mode. To bring back Geega to normal mode, just speak \'Back\'.")

#Function for About Geega
def About_Geega():
    copyright_symbol = u"\u00A9"
    About_Geega = tmsg.showinfo("About Geega", u"Geega v1.0.0\n\nReleased on May 16, 2020\n\n%s All rights reserved" % (copyright_symbol))

#Function for authors
def Authors():
    Author = tmsg.showinfo("Authors","Designed by Soham Chatterjee")

#Function to make Geega speak
def speak(audio):
    engine.say(audio)
    engine.runAndWait()

#Function to make Geega wish the user
def wishMe():
    hour = int(datetime.datetime.now().hour)
    if hour>=0 and hour<12:
        speak("Good Morning sir!")

    elif hour>=12 and hour<18:
        speak("Good Afternoon sir!")

    else:
        speak("Good Evening sir!")

    speak("I am Geega - the personal Voice Assistant. Just speak \"Hello Geega\" to activate me. I am always there for your service!")

#Function to take command from user
def takeCommand():
    r = sr.Recognizer()
    with sr.Microphone(device_index=1) as source:
        r.pause_threshold = 1
        audio = r.listen(source)
        query = ''
    try:
        query = r.recognize_google(audio, language='en-in')
    except sr.UnknownValueError:
        speak("Sorry! Couldn\'t get you!! Please say again")
        return takeCommand().lower()
    except sr.RequestError:
        print("Aw, Snap! Geega is down!! Please restart the program!")
        return takeCommand().lower()
    return query.lower()

#Function to pause when user is doing any work
def pause():
    r = sr.Recognizer()
    with sr.Microphone() as source:
        r.pause_threshold = 1
        audio = r.listen(source)
        query = ''
    try:
        query = r.recognize_google(audio, language='en-in')

    except sr.UnknownValueError:
        return pause().lower()
    except sr.RequestError:
        return pause().lower()
    return query

#Function for API connection
def apiai_connc(voice_data):
    CLIENT_ACCESS_TOKEN = "6b496c3a7afe409da201e7e82b3b5215"
    ai = apiai.ApiAI(CLIENT_ACCESS_TOKEN)
    request = ai.text_request()
    request.lang = "de"
    request.session_id = "<SESSION ID, UNIQUE FOR EACH USER>"
    request.query = voice_data
    source = request.getresponse()
    source_data = source.read()
    obj = json.loads(source_data)
    return obj["result"]["fulfillment"]["speech"]

#Main Geega function
def Geega():
    Button_frame3 = Button(Frame3, image=Button_image2, bg='#333333', borderwidth=0, height=80, width=250, cursor='hand2', command=convo_mode, state=DISABLED, activebackground='#333333').place(x=320,y=360)
    Text_frame1['text'] = "Geega is running..."
    main_window.update()
    wishMe()
    while True:
        query = pause().lower()
        if query.count("hello")>0:
            speak("Hello sir! Geega is ready to be instructed...")
            query = takeCommand().lower()
            if query == '':
                speak("Sorry! I couldn't hear you! Can you please say that again?")
            elif 'youtube' in query:
                speak("Opening YouTube...")
                webbrowser.open("www.youtube.com")
            elif 'google' in query:
                speak("Opening Google...")
                webbrowser.open("www.google.com")
            elif 'meet' in query:
                speak("Opening Google Meet...")
                webbrowser.open("https://meet.google.com")
            elif 'physics class' in query:
                speak("Opening your Physics class on Google Meet...")
                webbrowser.open("https://meet.google.com/inw-ncmr-emq")
            elif 'mathematics' in query:
                speak("Opening your Mathematics class on Google Meet...")
                webbrowser.open("https://meet.google.com/inw-ncmr-emq")
            elif 'chemistry class' in query:
                speak("Opening your Chemistry class on Google Meet...")
                webbrowser.open("https://meet.google.com/inw-ncmr-emq")
            elif 'english class' in query:
                speak("Opening your English class on Google Meet...")
                webbrowser.open("https://meet.google.com/eym-ypwa-kkx")
            elif 'play music' in query:
                music_dir = 'E:\\Bony Laptop\\Music'
                songs = os.listdir(music_dir)
                speak("Playing music...")
                os.startfile(os.path.join(music_dir,songs[0]))
            elif 'day' in query:
                now = datetime.datetime.now()
                day = now.strftime("%A")
                speak(f"Today is {day}")
            elif 'date' in query:
                date = datetime.datetime.now().strftime("%B")
                speak(f"Today's date is {date}")
            elif 'time' in query:
                strTime = datetime.datetime.now().strftime("%I:%M:%S")
                speak(f"The time is {strTime}")
            elif 'browser' in query:
                speak('Sure! Opening Internet Explorer...')
                browser_path = webbrowser.open(url="google.com")
            elif 'open python' in query:
                python_path = "C:\\Users\\admin\\AppData\\Local\\Programs\\Python\\Python38-32\\Lib\\idlelib\\idle.pyw"
                speak("Opening Python...")
                os.startfile(python_path)
            elif 'calculate' in query:
                query = query
                speak("Calculating...")
                try:
                    res = client.query(query)
                    results = next(res.results).text
                    speak(f"The results are {results}")
                except:
                    speak("Oops! Something went wrong. I couldn't calculate the problem.")
            elif 'exit' in query or "quit" in query:
                speak("Good Bye Sir! Have a nice day!")
                quit()
            elif 'search' in query:
                speak("Searching on the Web...")
                url = 'https://www.google.co.in/search?q='+query
                webbrowser.get().open(url)
            elif 'weather' in query:
                speak("Getting weather forecast results for your location on Google...")
                url = 'https://www.google.co.in/search?q=weather'
                webbrowser.get().open(url)
            elif 'i want to talk to you' in query:
                convo_mode()
            else:
                speak("Could not get you!")

main_window = Tk()

def close(event):
    global main_window
    key = event.char
    if key == "<ESCAPE>":
        main_window.destroy()

_thread.start_new_thread(main_window.bind("<Key>", lambda a: close(a)))

#Window configuration
windowWidth = 500
windowHeight = 300
screen_width = main_window.winfo_screenwidth()
screen_height = main_window.winfo_screenheight()
x_coordinate = (screen_width/2)-(windowWidth/2)
y_coordinate = (screen_height/2)-(windowHeight/2)

#Main Window Configuration
main_window.configure(bg='white')
main_window.iconbitmap('Geega_logo.ico')
main_window.title("Geega")
main_window.geometry('%dx%d+%d+%d' % (windowWidth, windowHeight, x_coordinate, y_coordinate))
main_window.minsize(500,300)
main_window.update()

#Frame 1 for Speak button
Frame1 = Frame(main_window, bg='#444444', borderwidth=5)
Frame1.place(x=0, y=0, width=500, height=300)

#Frame 2 for features
Frame2 =  Frame(main_window, bg='#555555', borderwidth=5)
Frame2.place(x=0,y=300, width=500, height=440)

#Frame 3 for conversation mode
Frame3 =  Frame(main_window, bg='#333333', borderwidth=5)
Frame3.place(x=500,y=0, width=865, height=740)

#Defining the font
Font = font.Font(family='Segoe UI', size=15, weight='bold')
Font2 = font.Font(family='Segoe UI', size=15)
Font3 = font.Font(family='Segoe UI', size=30)

#Defining the menu bar
MenuBar= Menu(main_window)
Drop_down1 = Menu(MenuBar, tearoff=0)
Drop_down1.add_command(label="Instructions", command=Instructions)
Drop_down1.add_separator()
Drop_down1.add_command(label='About Geega', command=About_Geega)
Drop_down1.add_command(label='Authors', command=Authors)

#Adding the menu bar
main_window.config(menu=MenuBar)
MenuBar.add_cascade(label="Help", menu=Drop_down1)

#Frame 1 button configuration
Button_image = PhotoImage(file="rsz_1speak_button_png.png")
Button_frame1 = Button(Frame1, image=Button_image, bg='#444444', borderwidth=0, height=200, width=200, cursor='hand2', command=Geega, activebackground='#444444').place(x=5,y=15)

#Frame 1 text configuration:
Text_frame1 = Label(Frame1, text="Click the mic to activate Geega...", bg='#444444', fg='white')
Text_frame1.place(x=43,y=225)
Text_frame1['font'] = Font

#Frame 2 text configuration
Text1_frame2 = Label(Frame2, text='Exciting things to do with Geega!', bg='#555555',fg='white')
Text1_frame2.place(x=43, y=15)
Text1_frame2['font'] = Font2

Text2_frame2 = Label(Frame2, text='- Tell her to open Google for you', bg='#555555',fg='white')
Text2_frame2.place(x=50, y=50)
Text2_frame2['font'] = Font2

Text3_frame2 = Label(Frame2, text='- Tell her to open Chrome for you', bg='#555555',fg='white')
Text3_frame2.place(x=50, y=85)
Text3_frame2['font'] = Font2

Text4_frame2 = Label(Frame2, text='- Bored? Ask Geega to play some music', bg='#555555',fg='white')
Text4_frame2.place(x=50, y=120)
Text4_frame2['font'] = Font2

Text5_frame2 = Label(Frame2, text='for you', bg='#555555',fg='white')
Text5_frame2.place(x=63, y=155)
Text5_frame2['font'] = Font2

Text4_frame2 = Label(Frame2, text='- Try out conversing with Geega in the', bg='#555555',fg='white')
Text4_frame2.place(x=50, y=185)
Text4_frame2['font'] = Font2

Text5_frame2 = Label(Frame2, text='Conversation mode', bg='#555555',fg='white')
Text5_frame2.place(x=63, y=220)
Text5_frame2['font'] = Font2

Text6_frame2 = Label(Frame2, text='Check out the other features too. Interact', bg='#555555',fg='white')
Text6_frame2.place(x=43, y=255)
Text6_frame2['font'] = Font2

Text6_frame2 = Label(Frame2, text='with Geega to find more...', bg='#555555',fg='white')
Text6_frame2.place(x=43, y=290)
Text6_frame2['font'] = Font2

Text7_frame2 = Label(Frame2, text='More new features coming soon...', bg='#555555',fg='white')
Text7_frame2.place(x=43, y=325)
Text7_frame2['font'] = Font

#Frame 3 button configuration
Button_image2 = PhotoImage(file="Convo button.png")
Button_frame3 = Button(Frame3, image=Button_image2, bg='#333333', borderwidth=0, height=80, width=250, cursor='hand2', command=convo_mode, state=NORMAL, activebackground='#333333').place(x=320,y=360)

#Frame 3 text configuration
Text_frame3 = Label(Frame3, text="Check out the all new conversation mode!", bg='#333333', fg='white')
Text_frame3.place(x=255,y=300)
Text_frame3['font'] = Font2

main_window.mainloop()
</code>```

答:
You are correct in thinking of threading here.

The standard threading library is sufficient for this. You will want to create two classes, one for your GUI and one for your other processes. You could do something like the following for threading your function:

```<code>import threading
</code>```

...

```<code>class BackgroundProcess(threading.Thread):

def __init__(self, parent=None):
    super().__init__()
    self.parent = parent

def run(self):
    Geega()
</code>```

and instead of just calling Geega() from your UI, create a new BackgroundProcess object and call its start() function as follows:

```<code>process = BackgroundProcess()
process.start()
</code>```

Hope this helps!

Edit:
Forgot to mention that seeing as this process is infinite, you should clean up the thread after closing your GUI to prevent memory leaks. Create an event listener for your window closing that kills all processes, something like

```<code>os._exit(1)
</code>```

Body:
I am writing a program for a GUI to support my Voice Assistant Python script using tkinter. But the problem is once the Voice Assistant program is activated, that is the infinite loop of the function of continuously listening to what the user says is executed, the whole window freezes and I cannot click on any other button and I am not being able to access the close (X) button also. I know I need to use threading in this case but I am not getting the idea of where to use it exactly to achieve my desire. I would be highly obliged if somebody would help me out with this. I am giving the whole code that I have written to help you out with the problem. The infinite running function in the program is Geega()

from tkinter import *
import tkinter.font as font
import tkinter.messagebox as tmsg
import pyttsx3
import speech_recognition as sr
import datetime
import wikipedia
import webbrowser
import os
import time
import smtplib
import random
import wolframalpha
import apiai
import json
import _thread

#API configuration
engine = pyttsx3.init('sapi5')
client = wolframalpha.Client('AQKXVX-UVQ8TUWUVU')
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[1].id)

#Conversation mode
def convo_mode():
    Text_frame1['text'] = "Geega has entered conversation mode..."
    Button_frame1 = Button(Frame1, image=Button_image, bg='#444444', borderwidth=0, height=200, width=200, state=DISABLED, activebackground='#444444').place(x=5,y=15)
    # Button_frame3 = Button(Frame3, text='Button', bg='white', borderwidth=0, cursor='hand2', state=DISABLED, activebackground='#444444').place(x=5,y=15)
    Button_frame3 = Button(Frame3, image=Button_image2, bg='#333333', borderwidth=0, height=80, width=250, cursor='hand2', command=convo_mode, state=DISABLED, activebackground='#333333').place(x=320,y=360)
    main_window.update()
    speak("Geega has entered Conversation mode...")
    query = takeCommand().lower()
    while "back" not in query:
        response = apiai_connc(query)
        speak(response)
        query = pause().lower()
    else:
        speak("Re-entering Normal Mode...")
        Button_frame1 = Button(Frame1, image=Button_image, bg='#444444', borderwidth=0, height=200, width=200, state=NORMAL, cursor= 'hand2', activebackground='#444444', command=Geega).place(x=5,y=15)
        # Button_frame3 = Button(Frame3, text="Button", bg='white', borderwidth=0, cursor='hand2', state=NORMAL, activebackground='#444444', command = convo_mode).place(x=5,y=15)
        Button_frame3 = Button(Frame3, image=Button_image2, bg='#333333', borderwidth=0, height=80, width=250, cursor='hand2', command=convo_mode, state=NORMAL, activebackground='#333333').place(x=320,y=360)
        Text_frame1['text'] = "Geega has entered Normal mode..."
        main_window.update()

#Function for instructions
def Instructions():
    Instruction = tmsg.showinfo("Instructions", "- Click the mic to activate Geega\n\n- Say \'Hello Geega\' before each command to make Geega do it\n\n- Click on \'Turn on Conversation Mode\' to enter Conversation Mode to make Geega answer your questions!\n\nNote: Geega would not execute command when running in Conversation mode. To bring back Geega to normal mode, just speak \'Back\'.")

#Function for About Geega
def About_Geega():
    copyright_symbol = u"\u00A9"
    About_Geega = tmsg.showinfo("About Geega", u"Geega v1.0.0\n\nReleased on May 16, 2020\n\n%s All rights reserved" % (copyright_symbol))

#Function for authors
def Authors():
    Author = tmsg.showinfo("Authors","Designed by Soham Chatterjee")

#Function to make Geega speak
def speak(audio):
    engine.say(audio)
    engine.runAndWait()

#Function to make Geega wish the user
def wishMe():
    hour = int(datetime.datetime.now().hour)
    if hour>=0 and hour<12:
        speak("Good Morning sir!")

    elif hour>=12 and hour<18:
        speak("Good Afternoon sir!")

    else:
        speak("Good Evening sir!")

    speak("I am Geega - the personal Voice Assistant. Just speak \"Hello Geega\" to activate me. I am always there for your service!")

#Function to take command from user
def takeCommand():
    r = sr.Recognizer()
    with sr.Microphone(device_index=1) as source:
        r.pause_threshold = 1
        audio = r.listen(source)
        query = ''
    try:
        query = r.recognize_google(audio, language='en-in')
    except sr.UnknownValueError:
        speak("Sorry! Couldn\'t get you!! Please say again")
        return takeCommand().lower()
    except sr.RequestError:
        print("Aw, Snap! Geega is down!! Please restart the program!")
        return takeCommand().lower()
    return query.lower()

#Function to pause when user is doing any work
def pause():
    r = sr.Recognizer()
    with sr.Microphone() as source:
        r.pause_threshold = 1
        audio = r.listen(source)
        query = ''
    try:
        query = r.recognize_google(audio, language='en-in')

    except sr.UnknownValueError:
        return pause().lower()
    except sr.RequestError:
        return pause().lower()
    return query

#Function for API connection
def apiai_connc(voice_data):
    CLIENT_ACCESS_TOKEN = "6b496c3a7afe409da201e7e82b3b5215"
    ai = apiai.ApiAI(CLIENT_ACCESS_TOKEN)
    request = ai.text_request()
    request.lang = "de"
    request.session_id = "<SESSION ID, UNIQUE FOR EACH USER>"
    request.query = voice_data
    source = request.getresponse()
    source_data = source.read()
    obj = json.loads(source_data)
    return obj["result"]["fulfillment"]["speech"]

#Main Geega function
def Geega():
    Button_frame3 = Button(Frame3, image=Button_image2, bg='#333333', borderwidth=0, height=80, width=250, cursor='hand2', command=convo_mode, state=DISABLED, activebackground='#333333').place(x=320,y=360)
    Text_frame1['text'] = "Geega is running..."
    main_window.update()
    wishMe()
    while True:
        query = pause().lower()
        if query.count("hello")>0:
            speak("Hello sir! Geega is ready to be instructed...")
            query = takeCommand().lower()
            if query == '':
                speak("Sorry! I couldn't hear you! Can you please say that again?")
            elif 'youtube' in query:
                speak("Opening YouTube...")
                webbrowser.open("www.youtube.com")
            elif 'google' in query:
                speak("Opening Google...")
                webbrowser.open("www.google.com")
            elif 'meet' in query:
                speak("Opening Google Meet...")
                webbrowser.open("https://meet.google.com")
            elif 'physics class' in query:
                speak("Opening your Physics class on Google Meet...")
                webbrowser.open("https://meet.google.com/inw-ncmr-emq")
            elif 'mathematics' in query:
                speak("Opening your Mathematics class on Google Meet...")
                webbrowser.open("https://meet.google.com/inw-ncmr-emq")
            elif 'chemistry class' in query:
                speak("Opening your Chemistry class on Google Meet...")
                webbrowser.open("https://meet.google.com/inw-ncmr-emq")
            elif 'english class' in query:
                speak("Opening your English class on Google Meet...")
                webbrowser.open("https://meet.google.com/eym-ypwa-kkx")
            elif 'play music' in query:
                music_dir = 'E:\\Bony Laptop\\Music'
                songs = os.listdir(music_dir)
                speak("Playing music...")
                os.startfile(os.path.join(music_dir,songs[0]))
            elif 'day' in query:
                now = datetime.datetime.now()
                day = now.strftime("%A")
                speak(f"Today is {day}")
            elif 'date' in query:
                date = datetime.datetime.now().strftime("%B")
                speak(f"Today's date is {date}")
            elif 'time' in query:
                strTime = datetime.datetime.now().strftime("%I:%M:%S")
                speak(f"The time is {strTime}")
            elif 'browser' in query:
                speak('Sure! Opening Internet Explorer...')
                browser_path = webbrowser.open(url="google.com")
            elif 'open python' in query:
                python_path = "C:\\Users\\admin\\AppData\\Local\\Programs\\Python\\Python38-32\\Lib\\idlelib\\idle.pyw"
                speak("Opening Python...")
                os.startfile(python_path)
            elif 'calculate' in query:
                query = query
                speak("Calculating...")
                try:
                    res = client.query(query)
                    results = next(res.results).text
                    speak(f"The results are {results}")
                except:
                    speak("Oops! Something went wrong. I couldn't calculate the problem.")
            elif 'exit' in query or "quit" in query:
                speak("Good Bye Sir! Have a nice day!")
                quit()
            elif 'search' in query:
                speak("Searching on the Web...")
                url = 'https://www.google.co.in/search?q='+query
                webbrowser.get().open(url)
            elif 'weather' in query:
                speak("Getting weather forecast results for your location on Google...")
                url = 'https://www.google.co.in/search?q=weather'
                webbrowser.get().open(url)
            elif 'i want to talk to you' in query:
                convo_mode()
            else:
                speak("Could not get you!")

main_window = Tk()

def close(event):
    global main_window
    key = event.char
    if key == "<ESCAPE>":
        main_window.destroy()

_thread.start_new_thread(main_window.bind("<Key>", lambda a: close(a)))

#Window configuration
windowWidth = 500
windowHeight = 300
screen_width = main_window.winfo_screenwidth()
screen_height = main_window.winfo_screenheight()
x_coordinate = (screen_width/2)-(windowWidth/2)
y_coordinate = (screen_height/2)-(windowHeight/2)

#Main Window Configuration
main_window.configure(bg='white')
main_window.iconbitmap('Geega_logo.ico')
main_window.title("Geega")
main_window.geometry('%dx%d+%d+%d' % (windowWidth, windowHeight, x_coordinate, y_coordinate))
main_window.minsize(500,300)
main_window.update()

#Frame 1 for Speak button
Frame1 = Frame(main_window, bg='#444444', borderwidth=5)
Frame1.place(x=0, y=0, width=500, height=300)

#Frame 2 for features
Frame2 =  Frame(main_window, bg='#555555', borderwidth=5)
Frame2.place(x=0,y=300, width=500, height=440)

#Frame 3 for conversation mode
Frame3 =  Frame(main_window, bg='#333333', borderwidth=5)
Frame3.place(x=500,y=0, width=865, height=740)

#Defining the font
Font = font.Font(family='Segoe UI', size=15, weight='bold')
Font2 = font.Font(family='Segoe UI', size=15)
Font3 = font.Font(family='Segoe UI', size=30)

#Defining the menu bar
MenuBar= Menu(main_window)
Drop_down1 = Menu(MenuBar, tearoff=0)
Drop_down1.add_command(label="Instructions", command=Instructions)
Drop_down1.add_separator()
Drop_down1.add_command(label='About Geega', command=About_Geega)
Drop_down1.add_command(label='Authors', command=Authors)

#Adding the menu bar
main_window.config(menu=MenuBar)
MenuBar.add_cascade(label="Help", menu=Drop_down1)

#Frame 1 button configuration
Button_image = PhotoImage(file="rsz_1speak_button_png.png")
Button_frame1 = Button(Frame1, image=Button_image, bg='#444444', borderwidth=0, height=200, width=200, cursor='hand2', command=Geega, activebackground='#444444').place(x=5,y=15)

#Frame 1 text configuration:
Text_frame1 = Label(Frame1, text="Click the mic to activate Geega...", bg='#444444', fg='white')
Text_frame1.place(x=43,y=225)
Text_frame1['font'] = Font

#Frame 2 text configuration
Text1_frame2 = Label(Frame2, text='Exciting things to do with Geega!', bg='#555555',fg='white')
Text1_frame2.place(x=43, y=15)
Text1_frame2['font'] = Font2

Text2_frame2 = Label(Frame2, text='- Tell her to open Google for you', bg='#555555',fg='white')
Text2_frame2.place(x=50, y=50)
Text2_frame2['font'] = Font2

Text3_frame2 = Label(Frame2, text='- Tell her to open Chrome for you', bg='#555555',fg='white')
Text3_frame2.place(x=50, y=85)
Text3_frame2['font'] = Font2

Text4_frame2 = Label(Frame2, text='- Bored? Ask Geega to play some music', bg='#555555',fg='white')
Text4_frame2.place(x=50, y=120)
Text4_frame2['font'] = Font2

Text5_frame2 = Label(Frame2, text='for you', bg='#555555',fg='white')
Text5_frame2.place(x=63, y=155)
Text5_frame2['font'] = Font2

Text4_frame2 = Label(Frame2, text='- Try out conversing with Geega in the', bg='#555555',fg='white')
Text4_frame2.place(x=50, y=185)
Text4_frame2['font'] = Font2

Text5_frame2 = Label(Frame2, text='Conversation mode', bg='#555555',fg='white')
Text5_frame2.place(x=63, y=220)
Text5_frame2['font'] = Font2

Text6_frame2 = Label(Frame2, text='Check out the other features too. Interact', bg='#555555',fg='white')
Text6_frame2.place(x=43, y=255)
Text6_frame2['font'] = Font2

Text6_frame2 = Label(Frame2, text='with Geega to find more...', bg='#555555',fg='white')
Text6_frame2.place(x=43, y=290)
Text6_frame2['font'] = Font2

Text7_frame2 = Label(Frame2, text='More new features coming soon...', bg='#555555',fg='white')
Text7_frame2.place(x=43, y=325)
Text7_frame2['font'] = Font

#Frame 3 button configuration
Button_image2 = PhotoImage(file="Convo button.png")
Button_frame3 = Button(Frame3, image=Button_image2, bg='#333333', borderwidth=0, height=80, width=250, cursor='hand2', command=convo_mode, state=NORMAL, activebackground='#333333').place(x=320,y=360)

#Frame 3 text configuration
Text_frame3 = Label(Frame3, text="Check out the all new conversation mode!", bg='#333333', fg='white')
Text_frame3.place(x=255,y=300)
Text_frame3['font'] = Font2

main_window.mainloop()

Body:
You are correct in thinking of threading here.

The standard threading library is sufficient for this. You will want to create two classes, one for your GUI and one for your other processes. You could do something like the following for threading your function:

import threading

...

class BackgroundProcess(threading.Thread):

def __init__(self, parent=None):
    super().__init__()
    self.parent = parent

def run(self):
    Geega()

and instead of just calling Geega() from your UI, create a new BackgroundProcess object and call its start() function as follows:

process = BackgroundProcess()
process.start()

Hope this helps!

Edit:
Forgot to mention that seeing as this process is infinite, you should clean up the thread after closing your GUI to prevent memory leaks. Create an event listener for your window closing that kills all processes, something like

os._exit(1)


问:
"Left side cannot be assigned to" for record type properties in Delphi
I'm curious to know why Delphi treats record type properties as read only:

```<code>  TRec = record
    A : integer;
    B : string;
  end;

  TForm1 = class(TForm)
  private
    FRec : TRec;
  public
    procedure DoSomething(ARec: TRec);
    property Rec : TRec read FRec write FRec;
  end;
</code>```

If I try to assign a value to any of the members of Rec property, I'll get "Left side cannot be assigned to" error:

```<code>procedure TForm1.DoSomething(ARec: TRec);
begin
  Rec.A := ARec.A;
end;
</code>```

while doing the same with the underlying field is allowed:

```<code>procedure TForm1.DoSomething(ARec: TRec);
begin
  FRec.A := ARec.A;
end;
</code>```

Is there any explanation for that behavior?

答:
Yes this is a problem. But the problem can be solved using record properties:

```<code>type
  TRec = record
  private
    FA : integer;
    FB : string;
    procedure SetA(const Value: Integer);
    procedure SetB(const Value: string);
  public
    property A: Integer read FA write SetA;
    property B: string read FB write SetB;
  end;

procedure TRec.SetA(const Value: Integer);
begin
  FA := Value;
end;

procedure TRec.SetB(const Value: string);
begin
  FB := Value;
end;

TForm1 = class(TForm)
  Button1: TButton;
  procedure Button1Click(Sender: TObject);
private
  FRec : TRec;
public
  property Rec : TRec read FRec write FRec;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  Rec.A := 21;
  Rec.B := 'Hi';
end;
</code>```

This compiles and workes without problem.

OwnerDisplayName: vcldeveloper

Body:
I'm curious to know why Delphi treats record type properties as read only:

  TRec = record
    A : integer;
    B : string;
  end;

  TForm1 = class(TForm)
  private
    FRec : TRec;
  public
    procedure DoSomething(ARec: TRec);
    property Rec : TRec read FRec write FRec;
  end;

If I try to assign a value to any of the members of Rec property, I'll get "Left side cannot be assigned to" error:

procedure TForm1.DoSomething(ARec: TRec);
begin
  Rec.A := ARec.A;
end;

while doing the same with the underlying field is allowed:

procedure TForm1.DoSomething(ARec: TRec);
begin
  FRec.A := ARec.A;
end;

Is there any explanation for that behavior?

Body:
Yes this is a problem. But the problem can be solved using record properties:

type
  TRec = record
  private
    FA : integer;
    FB : string;
    procedure SetA(const Value: Integer);
    procedure SetB(const Value: string);
  public
    property A: Integer read FA write SetA;
    property B: string read FB write SetB;
  end;

procedure TRec.SetA(const Value: Integer);
begin
  FA := Value;
end;

procedure TRec.SetB(const Value: string);
begin
  FB := Value;
end;

TForm1 = class(TForm)
  Button1: TButton;
  procedure Button1Click(Sender: TObject);
private
  FRec : TRec;
public
  property Rec : TRec read FRec write FRec;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  Rec.A := 21;
  Rec.B := 'Hi';
end;

This compiles and workes without problem.

OwnerDisplayName: Gamecat


问:
C++, 'coupling' of member pointers in multiple objects copied from the same original object
```<code>#include <iostream>
#include <vector>
#include <cstdlib>
#include <cassert>

struct s_A {
    bool bin;
    s_A(): bin(0) {}
};

class c_A {
public:
    s_A * p_struct;

    c_A(): p_struct(NULL) {p_struct = new s_A [16];}

    void Reset()
    {
        delete [] p_struct;
        p_struct = new s_A [16];
    }
};

int main ()
{
    srand(1);
    int x = 30;
    std::vector <c_A> objects;
    objects.assign(x, c_A());
    std::vector <c_A> objects_copy;

    for(int q=0; q < x; q++)
    {
        objects_copy.push_back(objects[ rand() % x ]);
        objects_copy[q].Reset();
    }

    for(int q=0; q < 16; q++)
        for(int w=0; w < x; w++)
        {
            // Assertion should not fail, but it does
            assert(!objects_copy[w].p_struct[q].bin);
            objects_copy[w].p_struct[q].bin = true;
        }
}
</code>```

<p>Somehow the pointers in the different copied objects end up pointing to the same memory, and the assertion eventually fails. This behavior does not happen if run on the un-copied vector.I thought that c_A.Reset() should free up the pointers (via delete[]) to point to a new array, but I'm obviously missing something. </p>

答:
The particular source of your problem are these lines here:

```<code>objects_copy.push_back(objects[ rand() % x ]);
objects_copy[q].Reset();
</code>```

The issue is that when you try pushing copies of the objects into objects_copy, you end up making a shallow copy of the objects in the objects vector.  This means that the objects in the two vectors will end up having pointers that are copies of one another.  Consequently, when you invoke Reset on the elements of the objects_copy vector, you deallocate memory that is still being pointed at by by elements of the objects array.

The problem is that your c_A class violates the rule of three.  Because your class encapsulates a resource, it needs to have a destructor, copy constructor, and copy assignment operator.  If you define these three functions, then when you try copying the objects into the objects_copy vector, you will have the ability to manage the underlying resource, perhaps by duplication or by reference-counting.  For details on how to write these functions, check out this description of how to write these functions.

EDIT: Here's a more detailed description of what's going on:

The issue is that when you add an object to a vector, you aren't actually storing that object in the vector.  Rather, you're storing a copy of that object.  Thus when you write objects_copy.push_back(objects[ rand() % x ]);, you are not storing the same object in both vectors.  Instead, you're creating a copy of one of the objects from objects and storing it in objects_copy.  Since your c_A type does not have copy functions defined, this ends up making a shallow-copy of the object, which creates a copy of the pointer.  This means that if you think about the original object from the objects list and its corresponding copy in objects_copy, they will each have a copy of the same p_struct pointer.  When you call Reset on the object in the objects_copy vector, you free the memory pointed at by its pointer.  However, you did not update the pointer of the original object stored in objects, and so that pointer now refers to garbage memory.  Trying to use that pointer leads to undefined behavior, hence the crash.

Adding copy functions will fix this by allowing you to control how the copy is being made.  If you define a copy function for c_A that causes the copy to point to a new copy of the object pointed at by the original, then this problem won't occur because each object will have its own separate pointer.  Alternatively, if you use reference counting, then you can avoid the problem by not deleting the resource if you know that some other object points at it.

Hope this helps!

ContentLicense: CC BY-SA 3.0

Body:
#include <iostream>
#include <vector>
#include <cstdlib>
#include <cassert>

struct s_A {
    bool bin;
    s_A(): bin(0) {}
};

class c_A {
public:
    s_A * p_struct;

    c_A(): p_struct(NULL) {p_struct = new s_A [16];}

    void Reset()
    {
        delete [] p_struct;
        p_struct = new s_A [16];
    }
};

int main ()
{
    srand(1);
    int x = 30;
    std::vector <c_A> objects;
    objects.assign(x, c_A());
    std::vector <c_A> objects_copy;

    for(int q=0; q < x; q++)
    {
        objects_copy.push_back(objects[ rand() % x ]);
        objects_copy[q].Reset();
    }

    for(int q=0; q < 16; q++)
        for(int w=0; w < x; w++)
        {
            // Assertion should not fail, but it does
            assert(!objects_copy[w].p_struct[q].bin);
            objects_copy[w].p_struct[q].bin = true;
        }
}

Somehow the pointers in the different copied objects end up pointing to the same memory, and the assertion eventually fails. This behavior does not happen if run on the un-copied vector.I thought that c_A.Reset() should free up the pointers (via delete[]) to point to a new array, but I'm obviously missing something.

Body:
The particular source of your problem are these lines here:

objects_copy.push_back(objects[ rand() % x ]);
objects_copy[q].Reset();

The issue is that when you try pushing copies of the objects into objects_copy, you end up making a shallow copy of the objects in the objects vector.  This means that the objects in the two vectors will end up having pointers that are copies of one another.  Consequently, when you invoke Reset on the elements of the objects_copy vector, you deallocate memory that is still being pointed at by by elements of the objects array.

The problem is that your c_A class violates the rule of three.  Because your class encapsulates a resource, it needs to have a destructor, copy constructor, and copy assignment operator.  If you define these three functions, then when you try copying the objects into the objects_copy vector, you will have the ability to manage the underlying resource, perhaps by duplication or by reference-counting.  For details on how to write these functions, check out this description of how to write these functions.

EDIT: Here's a more detailed description of what's going on:

The issue is that when you add an object to a vector, you aren't actually storing that object in the vector.  Rather, you're storing a copy of that object.  Thus when you write objects_copy.push_back(objects[ rand() % x ]);, you are not storing the same object in both vectors.  Instead, you're creating a copy of one of the objects from objects and storing it in objects_copy.  Since your c_A type does not have copy functions defined, this ends up making a shallow-copy of the object, which creates a copy of the pointer.  This means that if you think about the original object from the objects list and its corresponding copy in objects_copy, they will each have a copy of the same p_struct pointer.  When you call Reset on the object in the objects_copy vector, you free the memory pointed at by its pointer.  However, you did not update the pointer of the original object stored in objects, and so that pointer now refers to garbage memory.  Trying to use that pointer leads to undefined behavior, hence the crash.

Adding copy functions will fix this by allowing you to control how the copy is being made.  If you define a copy function for c_A that causes the copy to point to a new copy of the object pointed at by the original, then this problem won't occur because each object will have its own separate pointer.  Alternatively, if you use reference counting, then you can avoid the problem by not deleting the resource if you know that some other object points at it.

Hope this helps!


问:
Python, loops with changeable parts of filenames
I have a bunch of very similar commands which all look like this (df means pandas dataframe):

```<code>df1_part1=...
df1_part2=...
...
df1_part5=...
df2_part1=...
</code>```

I would like to make a loop for it, as follows:

```<code>for i in range(1,5):
for j in range(1,5):
df%i_part%j=...
</code>```

Of course, it doesn't work with %. But is has to be some easy way to do it, I suppose.
Could You help me please?

答:
You can try one of the following options:

Create a dictionary which maps the your df and access it by the name of the dataframe:

```<code>mapping = {"df1_part1": df1_part1, "df1_part2": df1_part2}
for i in range(1,5):
    for j in range(1,5):
        mapping[f"df{i}_part{j}"] = ...
</code>```

Use globals to access dynamically your variables:

```<code>df1_part1=...
df1_part2=...
...
df1_part5=...
df2_part1=...

for i in range(1,5):
    for j in range(1,5):
        globals()[f"df{i}_part{j}"] = ...
</code>```

Body:
I have a bunch of very similar commands which all look like this (df means pandas dataframe):

df1_part1=...
df1_part2=...
...
df1_part5=...
df2_part1=...

I would like to make a loop for it, as follows:

for i in range(1,5):
for j in range(1,5):
df%i_part%j=...

Of course, it doesn't work with %. But is has to be some easy way to do it, I suppose.
Could You help me please?

Body:
You can try one of the following options:

Create a dictionary which maps the your df and access it by the name of the dataframe:

mapping = {"df1_part1": df1_part1, "df1_part2": df1_part2}
for i in range(1,5):
    for j in range(1,5):
        mapping[f"df{i}_part{j}"] = ...

Use globals to access dynamically your variables:

df1_part1=...
df1_part2=...
...
df1_part5=...
df2_part1=...

for i in range(1,5):
    for j in range(1,5):
        globals()[f"df{i}_part{j}"] = ...


问:
Scrapy : Unable to extract attribute field using css selector
Here is the HTML code

```<code><!DOCTYPE html>
<html lang="en">
<div class="container" id="content-area">
    <div class="flex-row flex-baseline flex-space-between" data-id="1826" id="info">
      <h1 class="no-margin">XYZ</h1>
        <div class="new-stack" id="sublists">Added</div>
    </div>
</div>
</code>```

I am looking to pull the data-id attribute inside div tag. Here is what I am trying using CSS Selector

```<code>>>> response.css("#content-area div")[0].css("::attr[data-id]").get()
</code>```

And I got below error

```<code>cssselect.parser.SelectorSyntaxError: Got pseudo-element ::attr not at the end of a selector
</code>```

Here is how I solved it by combining CSS and XPATH Selectors.

```<code>>>> response.css("#content-area div")[0].xpath("@data-id").get()
'1826'
</code>```

Is there any solution which can do this using just CSS Selector?

答:
You need to use () instead of []

>>> response.css("#content-area div")[0].css("::attr(data-id)").get()
```

Body:
Here is the HTML code

<!DOCTYPE html>

XYZ

Added

I am looking to pull the data-id attribute inside div tag. Here is what I am trying using CSS Selector

>>> response.css("#content-area div")[0].css("::attr[data-id]").get()

And I got below error

cssselect.parser.SelectorSyntaxError: Got pseudo-element ::attr not at the end of a selector

Here is how I solved it by combining CSS and XPATH Selectors.

>>> response.css("#content-area div")[0].xpath("@data-id").get()
'1826'

Is there any solution which can do this using just CSS Selector?


问:
How to express this concept without dynamic dispatch?
I am building a simulation (the coding equivalent of a model train set). It is a simulated economy with various economic agents interacting with each other. The main mode of interaction between economic agents is a transaction. At each "tic", each agent generates a list of zero or more proposed transactions (such as buying food). At each "toc" all the counter-parties process the proposed transactions that have been targeted at them in random order so that no biases are introduced. In these snippets a proposed transaction is represented as a u32.

My goal is to simulate as many of these economic agents as possible so performance is key. I am new to rust (or any kind of low level language for that matter) and my understanding from reading the rust book is if I want maximum performance then use "zero cost abstractions" and avoid dynamic dispatch.

So with that out the way I have come up with the following 3 approaches.

Option 1

```<code>trait EconomicAgent {
    fn proposed_transactions(&self) -> Vec<u32>;
}

struct Person {
    health:f64,
    energy:f64,
    nutrition:f64,
    money:f64,
    food:f64
}

impl EconomicAgent for Person {
    fn proposed_transactions(&self) -> Vec<u32> {
        vec![1, 2, 3]
    }
}

struct FoodStore {
    money:f64,
    food:f64
}

impl EconomicAgent for FoodStore {
    fn proposed_transactions(&self) -> Vec<u32> {
        vec![4, 5, 6]
    }
}
</code>```

A person and a food store are different types that implement the EconomicAgent trait. I can then iterate over a vector of trait objects to get a list of proposed transactions. Each call is dynamically dispatched, I believe.

Option 2

```<code>enum EconomicAgent2 {
    Person(Person),
    FoodStore(FoodStore)
}

impl EconomicAgent2 {
    fn proposed_transactions(&self) -> Vec<u32> {
        match self{
            EconomicAgent2::Person(person) => person.proposed_transactions(),
            EconomicAgent2::FoodStore(food_store) => food_store.proposed_transactions()
        }
    }
}
</code>```

Here, an EconomicAgent is not a trait, but rather an enum and, well you can see how it works.

Option 3

```<code>const HEALTH_INDEX : u8 = 0;
const ENERGY_INDEX : u8 = 1;
const NUTRITION_INDEX : u8 = 2;
const MONEY_INDEX : u8 = 3;
const FOOD_INDEX : u8 = 4;

enum EconomicAgentTag {
    Person,
    FoodStore
}
struct EconomicAgent3 {
    tag: EconomicAgentTag,
    resources:[f64; 5],
    proposed_transactions: Box<fn(&EconomicAgent3) -> Vec<u32>>
}

fn new_person() -> EconomicAgent3 {
    EconomicAgent3 {
        tag: EconomicAgentTag::Person,
        resources: [0.0,0.0,0.0,0.0,0.0],
        proposed_transactions: Box::new(|_| vec![1, 2, 3])
    }
}

fn new_food_Store() -> EconomicAgent3 {
    EconomicAgent3 {
        tag: EconomicAgentTag::FoodStore,
        resources: [0.0,0.0,0.0,0.0,0.0],
        proposed_transactions: Box::new(|_| vec![4, 5, 6])
    }
}
</code>```

Here an economic agent is more abstract representation.

Now imagine that there a many different types of economic agents (banks, mines, farms, clothing stores etc). They all interact by proposing and accepting transactions. Option 1 seems to suffer from dynamic dispatch. Option 2 seems to be my own version of dynamic dispatch via a match expression so is probably no better, right? Option 3 seems like it should be the most performant but does not really allow much cognitive ease on the part of the programmer.

So finally the questions:

Clearly dynamic dispatch is involved in option 1. What about options 2 and 3?

Which is expected to be most performant? Note I am not really in a position to do testing as the full idea (only on paper right now) is obviously more complex than these snippets and the choice now will affect the entire structure for the whole project.

What would be an idiomatic choice here?

答:
All your options use dynamic dispatch or branches in one way or another to call the right function for each element. The reason is that you are mixing all the agents into a single place, which is where the different performance penalties come from (not just the indirect calls or branches, but also cache misses etc.).

Instead, for a problem like this, you want to separate the different "agents" into separate, independent "entities". Then, to reuse code, you will want to factor out "components" for which subsets of them are iterated by "systems".

This is what is usually called an "Entity-Component-System" (ECS) of which there are many models and implementations. They are typically used by games and other simulations.

If you search for ECS you will find many questions, articles and so on about it and the different approaches.

Body:
I am building a simulation (the coding equivalent of a model train set). It is a simulated economy with various economic agents interacting with each other. The main mode of interaction between economic agents is a transaction. At each "tic", each agent generates a list of zero or more proposed transactions (such as buying food). At each "toc" all the counter-parties process the proposed transactions that have been targeted at them in random order so that no biases are introduced. In these snippets a proposed transaction is represented as a u32.

My goal is to simulate as many of these economic agents as possible so performance is key. I am new to rust (or any kind of low level language for that matter) and my understanding from reading the rust book is if I want maximum performance then use "zero cost abstractions" and avoid dynamic dispatch.

So with that out the way I have come up with the following 3 approaches.

Option 1

trait EconomicAgent {
    fn proposed_transactions(&self) -> Vec<u32>;
}

struct Person {
    health:f64,
    energy:f64,
    nutrition:f64,
    money:f64,
    food:f64
}

impl EconomicAgent for Person {
    fn proposed_transactions(&self) -> Vec<u32> {
        vec![1, 2, 3]
    }
}

struct FoodStore {
    money:f64,
    food:f64
}

impl EconomicAgent for FoodStore {
    fn proposed_transactions(&self) -> Vec<u32> {
        vec![4, 5, 6]
    }
}

A person and a food store are different types that implement the EconomicAgent trait. I can then iterate over a vector of trait objects to get a list of proposed transactions. Each call is dynamically dispatched, I believe.

Option 2

enum EconomicAgent2 {
    Person(Person),
    FoodStore(FoodStore)
}

impl EconomicAgent2 {
    fn proposed_transactions(&self) -> Vec<u32> {
        match self{
            EconomicAgent2::Person(person) => person.proposed_transactions(),
            EconomicAgent2::FoodStore(food_store) => food_store.proposed_transactions()
        }
    }
}

Here, an EconomicAgent is not a trait, but rather an enum and, well you can see how it works.

Option 3

const HEALTH_INDEX : u8 = 0;
const ENERGY_INDEX : u8 = 1;
const NUTRITION_INDEX : u8 = 2;
const MONEY_INDEX : u8 = 3;
const FOOD_INDEX : u8 = 4;

enum EconomicAgentTag {
    Person,
    FoodStore
}
struct EconomicAgent3 {
    tag: EconomicAgentTag,
    resources:[f64; 5],
    proposed_transactions: Box<fn(&EconomicAgent3) -> Vec<u32>>
}

fn new_person() -> EconomicAgent3 {
    EconomicAgent3 {
        tag: EconomicAgentTag::Person,
        resources: [0.0,0.0,0.0,0.0,0.0],
        proposed_transactions: Box::new(|_| vec![1, 2, 3])
    }
}

fn new_food_Store() -> EconomicAgent3 {
    EconomicAgent3 {
        tag: EconomicAgentTag::FoodStore,
        resources: [0.0,0.0,0.0,0.0,0.0],
        proposed_transactions: Box::new(|_| vec![4, 5, 6])
    }
}

Here an economic agent is more abstract representation.

Now imagine that there a many different types of economic agents (banks, mines, farms, clothing stores etc). They all interact by proposing and accepting transactions. Option 1 seems to suffer from dynamic dispatch. Option 2 seems to be my own version of dynamic dispatch via a match expression so is probably no better, right? Option 3 seems like it should be the most performant but does not really allow much cognitive ease on the part of the programmer.

So finally the questions:

Clearly dynamic dispatch is involved in option 1. What about options 2 and 3?

Which is expected to be most performant? Note I am not really in a position to do testing as the full idea (only on paper right now) is obviously more complex than these snippets and the choice now will affect the entire structure for the whole project.

What would be an idiomatic choice here?


问:
Tag quasi-duplicates in MS Excel
Consider a list of strings in columnm A. Each member takes the form a_delimiter_b. The list also has quasi-duplicate members b_delimiter_a.

How can I select all the relevent entries without the "duplicates?" This is how can I query for entries in the columnn, and for each a_delimiter_b exclude b_delimiter_a?

Attempt:
I am trying to tag the duplicates in another column.

```<code>=IF(<condition>,"Keep","Delete")
</code>```

I need a good condition that I cannot think up. If I use VLOOKUP both the "orginal" and the "duplicate" are taggef. For example if the element is A1="a_delim_b"

```<code><condition> = ISERROR(VLOOKUP(b_delim_a, <list_range>, FALSE))
</code>```

I can get "b_delim_a" by

```<code>CONCAT(TRIM(MID(SUBSTITUTE(A1,"_delim_",REPT(" ",LEN(A1))),(2-1)*LEN(A1)+1,LEN(A1))) & "_delim_" & TRIM(MID(SUBSTITUTE(A1,"_delim_",REPT(" ",LEN(A1))),(1-1)*LEN(A1)+1,LEN(A1))))
</code>```

This does not work because if "b_delim_a" exists, all entries in the list are tagged for deletion.

How can I tag to keep only exacly one instance and tag to delete the other occurances?

答:
Try the following in B1 and drag down:

```<code>=IF(COUNTIF(A$1:A1,MID(A1,FIND("; ",A1)+2,LEN(A1))&"; "&LEFT(A1,FIND("; ",A1)-1)),"Delete","Keep")
</code>```

Title: Tag quasi-duplicates in MS Excel

Body:
Consider a list of strings in columnm A. Each member takes the form a_delimiter_b. The list also has quasi-duplicate members b_delimiter_a.

How can I select all the relevent entries without the "duplicates?" This is how can I query for entries in the columnn, and for each a_delimiter_b exclude b_delimiter_a?

Attempt:
I am trying to tag the duplicates in another column.

=IF(<condition>,"Keep","Delete")

I need a good condition that I cannot think up. If I use VLOOKUP both the "orginal" and the "duplicate" are taggef. For example if the element is A1="a_delim_b"

<condition> = ISERROR(VLOOKUP(b_delim_a, <list_range>, FALSE))

I can get "b_delim_a" by

CONCAT(TRIM(MID(SUBSTITUTE(A1,"_delim_",REPT(" ",LEN(A1))),(2-1)*LEN(A1)+1,LEN(A1))) & "_delim_" & TRIM(MID(SUBSTITUTE(A1,"_delim_",REPT(" ",LEN(A1))),(1-1)*LEN(A1)+1,LEN(A1))))

This does not work because if "b_delim_a" exists, all entries in the list are tagged for deletion.

How can I tag to keep only exacly one instance and tag to delete the other occurances?

Body:
Try the following in B1 and drag down:

=IF(COUNTIF(A$1:A1,MID(A1,FIND("; ",A1)+2,LEN(A1))&"; "&LEFT(A1,FIND("; ",A1)-1)),"Delete","Keep")


问:
The pipe 'translation' could not be found
This is my test.component.html file:

```<code><div class="my-container">
  <span>{{ 'locations' | translation }}</span>
</div>
</code>```

This is translation.pipe.ts:

```<code>import { Pipe, PipeTransform } from '@angular/core';
import { TranslationsService } from './translations.service';

@Pipe({ name: 'translation' })
export class TranslationPipe implements PipeTransform {
  constructor(private myTranslationsService: TranslationsService) {}

  transform(value: string): string {
    return this.myTranslationsService.get(value);
  }
}
</code>```

And this is test.module.ts file:

```<code>import { TestComponent } from './test.component';
import { Injector, DoBootstrap, NgModule } from '@angular/core';
import { createCustomElement } from '@angular/elements';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';
import { FormsModule } from '@angular/forms';
import { TranslationsService } from '../shared/translations.service';
import { TranslationPipe } from '../shared/translation.pipe';

@NgModule({
  declarations: [TestComponent, TranslationPipe],
  imports: [BrowserModule, FormsModule, HttpClientModule],
  entryComponents: [TestComponent],
  providers: [TranslationsService],
  exports: []
})
export class TestModule implements DoBootstrap {
  constructor(private injector: Injector) {

  }

  ngDoBootstrap() {
    const ngElement = createCustomElement(TestComponent, { injector: this.injector, });
    customElements.get('my-test') || customElements.define('my-test', ngElement);
  }
}
</code>```

When I run the app I get console error that The pipe 'translation' could not be found! WHat am I doing wrong?

答:
Add yours TranslationPipe to providers

```<code>  providers: [TranslationsService, TranslationPipe],
</code>```

Body:
This is my test.component.html file:

  {{ 'locations' | translation }}

This is translation.pipe.ts:

import { Pipe, PipeTransform } from '@angular/core';
import { TranslationsService } from './translations.service';

@Pipe({ name: 'translation' })
export class TranslationPipe implements PipeTransform {
  constructor(private myTranslationsService: TranslationsService) {}

  transform(value: string): string {
    return this.myTranslationsService.get(value);
  }
}

And this is test.module.ts file:

import { TestComponent } from './test.component';
import { Injector, DoBootstrap, NgModule } from '@angular/core';
import { createCustomElement } from '@angular/elements';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';
import { FormsModule } from '@angular/forms';
import { TranslationsService } from '../shared/translations.service';
import { TranslationPipe } from '../shared/translation.pipe';

@NgModule({
  declarations: [TestComponent, TranslationPipe],
  imports: [BrowserModule, FormsModule, HttpClientModule],
  entryComponents: [TestComponent],
  providers: [TranslationsService],
  exports: []
})
export class TestModule implements DoBootstrap {
  constructor(private injector: Injector) {

  }

  ngDoBootstrap() {
    const ngElement = createCustomElement(TestComponent, { injector: this.injector, });
    customElements.get('my-test') || customElements.define('my-test', ngElement);
  }
}

When I run the app I get console error that The pipe 'translation' could not be found! WHat am I doing wrong?

Body:
Add yours TranslationPipe to providers

  providers: [TranslationsService, TranslationPipe],


问:
Command external field value to be sent with form
I have two forms on one page.

The first form is used to make a calculation (fieldvalue1 + fieldvalue2 = calculatedfield)
The second form is simply just to capture information (Name, Email, etc.)

The first form has no submit button, but the second form has a submit button. Currently, when the user fills in all the info and clicks submit, then only the second form's fields get sent to my admin email.

Is there a way to send calculatedfield along with the form fields sent to my email when clicking the submit button on the second form?

I would like to add a code snippet to command the calculatedfield to also be sent along with the fields of the second form. Not sure which code to use...

I would greatly appreciate any assistance.

答:
Add a new hidden field (lets call it hiddenCalculatedField) to your second form.

In the first form, add a onChange hook to the calculatedfield, and copy the value to the hidden field. This will get submitted when the second form is submitted.

In this example, it assumes

```<code>$(document).ready(function() {
   $("input[name='calculatedfield']").change(function() {
       $("input[name='hiddenCalculatedField']").val($(this).val())
   })
}
</code>```

Body:
Add a new hidden field (lets call it hiddenCalculatedField) to your second form.

In the first form, add a onChange hook to the calculatedfield, and copy the value to the hidden field. This will get submitted when the second form is submitted.

In this example, it assumes

$(document).ready(function() {
   $("input[name='calculatedfield']").change(function() {
       $("input[name='hiddenCalculatedField']").val($(this).val())
   })
}


问:
Jquery, search and show a hidden div
Im working on a grocery list where you can search and add groceries to your list. My grocery items are populated from a MySQL table and the text is added to a div called "foodcard". My Jquery script almost works exactly how i want it, except that all 150+ cards are visible and only when you start typing in the input box do the cards get hidden and fade in the related search term. Im having trouble figuring out how to hide the cards on page load and show only the search term. ill give you all my code, but please tell me if i need to include anymore

$(document).ready(function(){

  $('#grcsearch').on('keyup', function () {
    var grcsearch = $('#grcsearch').val().toLowerCase();

   $('.foodcard').each(function(){
    var $this = $(this);

    if($this.text().toLowerCase().indexOf(grcsearch) === -1)
    $this.closest('.foodcard').fadeOut();
    else $this.closest('.foodcard').fadeIn();

   })

   });
  });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.wrapper {
    text-align: center;

}

.grocerylistcard {
    width: 85%;
    height: 90%;
    border-radius:15px;
    padding-bottom: 20px;
    padding-top: 20px;
    padding-left: 30px;
    padding-right: 30px;
    border-width: 2px;
    border: solid 2px;
    border-color: rgb(199, 185, 201);
    background-color: #D5CAD6;
    margin: auto;
    display: inline-block;
    box-shadow: 5px 5px 3px grey;
}

.pccontainer1 {
   display: flex;
   flex-direction: row;
   }

   .foodcard {
    width: 15%;
    background-color: rgb(236, 231, 203);
    margin: 10px;
    margin-right: 10px !important;
    margin-left: 10px !important;

    border-radius: 10px;
    display: inline-table;

}</code>```

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <meta http-equiv="Expires" content="-1">

    <title>J & K Life Assist</title>

    <link rel="icon" href="img/mdb-favicon.ico" type="image/x-icon">

    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.11.2/css/all.css">

    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap">

    <link rel="stylesheet" href="css/bootstrap.min.css">

    <link rel="stylesheet" href="css/mdb.min.css">

    <link rel="stylesheet" href="/css/style.css">

 Grocery List

Search and add groceries we need to get on our next trip out!

                <input type="text" id="grcsearch" class="form-control form-control-lg">
                Search for Groceries

              Apples

              Banana's

              Oranges

              Butter

              Milk

              Bread

              Ramen

              Chicken

              Ground Beef

              Cheese

 ```

im pretty new to this community. thanks for any help!

答:
The first step is to test if the grcsearch value is an empty string. You can achieve this with:

```<code>grcsearch.trim().length == 0
</code>```

This condition must be in OR with the if condition:

```<code>if(grcsearch.trim().length == 0 || $this.text().toLowerCase().indexOf(grcsearch) === -1)
</code>```

At the end of your keyup event you can trigger the event at dom ready simply triggering it:

```<code>.trigger('keyup');
</code>```

$('#grcsearch').on('keyup', function () {
    var grcsearch = $('#grcsearch').val().toLowerCase();

    $('.foodcard').each(function(){
        var $this = $(this);

        if(grcsearch.trim().length == 0 || $this.text().toLowerCase().indexOf(grcsearch) === -1)
            $this.closest('.foodcard').fadeOut();
        else {
            $this.closest('.foodcard').fadeIn();
        }
    })
}).trigger('keyup');```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.wrapper {
    text-align: center;

}

.grocerylistcard {
    width: 85%;
    height: 90%;
    border-radius:15px;
    padding-bottom: 20px;
    padding-top: 20px;
    padding-left: 30px;
    padding-right: 30px;
    border-width: 2px;
    border: solid 2px;
    border-color: rgb(199, 185, 201);
    background-color: #D5CAD6;
    margin: auto;
    display: inline-block;
    box-shadow: 5px 5px 3px grey;
}

.pccontainer1 {
    display: flex;
    flex-direction: row;
}

.foodcard {
    width: 15%;
    background-color: rgb(236, 231, 203);
    margin: 10px;
    margin-right: 10px !important;
    margin-left: 10px !important;

    border-radius: 10px;
    display: inline-table;

}</code>```

 Grocery List

Search and add groceries we need to get on our next trip out!

            <input type="text" id="grcsearch" class="form-control form-control-lg">
            Search for Groceries

                Apples

                Banana's

                Oranges

                Butter

                Milk

                Bread

                Ramen

                Chicken

                Ground Beef

                Cheese

 ```

Title: Jquery, search and show a hidden div

Body:
Im working on a grocery list where you can search and add groceries to your list. My grocery items are populated from a MySQL table and the text is added to a div called "foodcard". My Jquery script almost works exactly how i want it, except that all 150+ cards are visible and only when you start typing in the input box do the cards get hidden and fade in the related search term. Im having trouble figuring out how to hide the cards on page load and show only the search term. ill give you all my code, but please tell me if i need to include anymore

$(document).ready(function(){

  $('#grcsearch').on('keyup', function () {
    var grcsearch = $('#grcsearch').val().toLowerCase();

   $('.foodcard').each(function(){
    var $this = $(this);

    if($this.text().toLowerCase().indexOf(grcsearch) === -1)
    $this.closest('.foodcard').fadeOut();
    else $this.closest('.foodcard').fadeIn();

   })

   });
  });

.wrapper {
    text-align: center;

}

.grocerylistcard {
    width: 85%;
    height: 90%;
    border-radius:15px;
    padding-bottom: 20px;
    padding-top: 20px;
    padding-left: 30px;
    padding-right: 30px;
    border-width: 2px;
    border: solid 2px;
    border-color: rgb(199, 185, 201);
    background-color: #D5CAD6;
    margin: auto;
    display: inline-block;
    box-shadow: 5px 5px 3px grey;
}

.pccontainer1 {
   display: flex;
   flex-direction: row;
   }

   .foodcard {
    width: 15%;
    background-color: rgb(236, 231, 203);
    margin: 10px;
    margin-right: 10px !important;
    margin-left: 10px !important;

    border-radius: 10px;
    display: inline-table;

}

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <meta http-equiv="Expires" content="-1">

    <title>J & K Life Assist</title>

    <link rel="icon" href="img/mdb-favicon.ico" type="image/x-icon">

    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.11.2/css/all.css">

    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap">

    <link rel="stylesheet" href="css/bootstrap.min.css">

    <link rel="stylesheet" href="css/mdb.min.css">

    <link rel="stylesheet" href="/css/style.css">

 Grocery List

Search and add groceries we need to get on our next trip out!

                <input type="text" id="grcsearch" class="form-control form-control-lg">
                Search for Groceries

              Apples

              Banana's

              Oranges

              Butter

              Milk

              Bread

              Ramen

              Chicken

              Ground Beef

              Cheese

im pretty new to this community. thanks for any help!

Body:
The first step is to test if the grcsearch value is an empty string. You can achieve this with:

grcsearch.trim().length == 0

This condition must be in OR with the if condition:

if(grcsearch.trim().length == 0 || $this.text().toLowerCase().indexOf(grcsearch) === -1)

At the end of your keyup event you can trigger the event at dom ready simply triggering it:

.trigger('keyup');

$('#grcsearch').on('keyup', function () {
    var grcsearch = $('#grcsearch').val().toLowerCase();

    $('.foodcard').each(function(){
        var $this = $(this);

        if(grcsearch.trim().length == 0 || $this.text().toLowerCase().indexOf(grcsearch) === -1)
            $this.closest('.foodcard').fadeOut();
        else {
            $this.closest('.foodcard').fadeIn();
        }
    })
}).trigger('keyup');

.wrapper {
    text-align: center;

}

.grocerylistcard {
    width: 85%;
    height: 90%;
    border-radius:15px;
    padding-bottom: 20px;
    padding-top: 20px;
    padding-left: 30px;
    padding-right: 30px;
    border-width: 2px;
    border: solid 2px;
    border-color: rgb(199, 185, 201);
    background-color: #D5CAD6;
    margin: auto;
    display: inline-block;
    box-shadow: 5px 5px 3px grey;
}

.pccontainer1 {
    display: flex;
    flex-direction: row;
}

.foodcard {
    width: 15%;
    background-color: rgb(236, 231, 203);
    margin: 10px;
    margin-right: 10px !important;
    margin-left: 10px !important;

    border-radius: 10px;
    display: inline-table;

}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="wrapper">
    <div class="grocerylistcard">
        <h3 id="bptitle"> Grocery List </h3>
        <p>Search and add groceries we need to get on our next trip out!</p>
        <hr class="my-4">

        <div class="md-form form-lg" id="grocerysearchwrap">
            <input type="text" id="grcsearch" class="form-control form-control-lg">
            <label for="grocerysearch">Search for Groceries</label>

        </div>

        <!-- Central Modal Small -->
        <br />

        <!-- this is where my PHP sript loads the SQL table items, but heres some hand typed cards for your reference -->
        <div class="pccontainer1">

            <div class="foodcard">

                Apples
            </div>
            <div class="foodcard">

                Banana's
            </div>
            <div class="foodcard">

                Oranges
            </div>
            <div class="foodcard">

                Butter
            </div>
            <div class="foodcard">

                Milk
            </div>

        </div> <!--pc container-->

        <div class="pccontainer1">

            <div class="foodcard">

                Bread
            </div>
            <div class="foodcard">

                Ramen
            </div>
            <div class="foodcard">

                Chicken
            </div>
            <div class="foodcard">

                Ground Beef
            </div>
            <div class="foodcard">

                Cheese
            </div>

        </div> <!--pc container-->
        <!-- grocery items above -->
    </div>
    <!--grocery card ends here-->
</div> <!-- customcard wrapper-->


问:
Tagging and Analysing a Search Query
I'm developing a search engine which functions taking the semantics of data into account, unlike the usual keyword based index. I managed to develop a reasonable index for the search using metadata extraction methods and RDF, but I have difficulty in using such methods on the search query itself since the search query is very much shorter that the actual data. any idea how to perform a successful tagging of a search query, using similar methods, natural language processing, etc. ?

Thank You!

答:
Yes, the sample size of a typical query is too small for semantic analysis to be of any value.

One approach might be to constrain or expand your query using drop-down menus for things like "Named Entities" or "Subject Verb Object" tuples.

Another approach would be to expand simple keywords using rules created from your metadata so that, for example, a query for 'car' might be expanded to the tuple pattern

```<code>(*,[drive,operate,sell],[car,automobile,vehicle])
</code>```

before submission.

Finally, you might try expanding the query with a non-semantically valuable prefix and/or suffix to get the query size large enough to trigger OpenCalais' recognizer.

Something like 'The user has specified the following terms in her query: one, two, three.'.

And once the results are returned, filter out all results that match only the added prefix/suffix.

Just a few quick thoughts.

Title: Tagging and Analysing a Search Query

Body:
Yes, the sample size of a typical query is too small for semantic analysis to be of any value.

One approach might be to constrain or expand your query using drop-down menus for things like "Named Entities" or "Subject Verb Object" tuples.

Another approach would be to expand simple keywords using rules created from your metadata so that, for example, a query for 'car' might be expanded to the tuple pattern

(*,[drive,operate,sell],[car,automobile,vehicle])

before submission.

Finally, you might try expanding the query with a non-semantically valuable prefix and/or suffix to get the query size large enough to trigger OpenCalais' recognizer.

Something like 'The user has specified the following terms in her query: one, two, three.'.

And once the results are returned, filter out all results that match only the added prefix/suffix.

Just a few quick thoughts.


问:
make element visible to upload file using selenium and python
here is the Html snippet:

```<code> <div class="ia-ControlledFilePicker"><input class="ia-ControlledFilePicker-control icl-u-visuallyHidden" type="file" id="ia-FilePicker"><label class="ia-ControlledFilePicker-fakeControl" for="ia-FilePicker">Choose file</label><span class="ia-ControlledFilePicker-info">No file chosen</span></div>
    <input class="ia-ControlledFilePicker-control icl-u-visuallyHidden" type="file" id="ia-FilePicker-resume">
</code>```

Here is the CSS bit:

```<code>.icl-u-visuallyHidden {
border: 0;
clip: rect(0 0 0 0);
height: 1px;
margin: -1px;
overflow: hidden;
padding: 0;
position: absolute;
width: 1px; }
</code>```

Objective: upload file to the page using selenium python.I can't click on the "choose file" button from selenium either, because it's hidden.

Things I have tried so far to make the element visible that don't work:

```<code>    # change_visibility = "document.setElementById('ia-FilePicker').style.visibility='visible';"
    # changWebElemente_display = "document.setElementById('ia-FilePicker').style.display='block';"
    # self.driver.execute_script(change_visibility)
    # self.WebElement.execute_script(change_display)
</code>```

#

```<code>    # change_height = "document.getElementsByClassName('ia-FilePicker.ia-ControlledFilePicker-control.icl-u-visuallyHidden').style.height='100px';"
    # change_width = "document.getElementsByClassName('ia-FilePicker.ia-ControlledFilePicker-control.icl-u-visuallyHidden').style.width='100px';"
    # self.driver.execute_script(change_height)
    # self.driver.execute_script(change_width)
</code>```

#

```<code>WebDriverWait(self.driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input.ia-FilePicker.ia-ControlledFilePicker-control.icl-u-visuallyHidden#ia-FilePicker-resume"))).style.display = "block" )
</code>```

And many more. I've been working on this for days.

Error: Message: javascript error: Cannot read property 'style' of null .

I also know about AutoIT, but I want to stick with Selenium on Chrome and Python for now. What can I do? Thank you for your help.

答:
Make the field visible with setting opacity

```<code>self.driver.execute_script("document.querySelector(\"input[id*='ia-FilePicker-resume']\").style.opacity='1'");
</code>```

and then try to upload file

Body:
here is the Html snippet:

<input class="ia-ControlledFilePicker-control icl-u-visuallyHidden" type="file" id="ia-FilePicker">Choose fileNo file chosen

    <input class="ia-ControlledFilePicker-control icl-u-visuallyHidden" type="file" id="ia-FilePicker-resume">

Here is the CSS bit:

.icl-u-visuallyHidden {
border: 0;
clip: rect(0 0 0 0);
height: 1px;
margin: -1px;
overflow: hidden;
padding: 0;
position: absolute;
width: 1px; }

Objective: upload file to the page using selenium python.I can't click on the "choose file" button from selenium either, because it's hidden.

Things I have tried so far to make the element visible that don't work:

    # change_visibility = "document.setElementById('ia-FilePicker').style.visibility='visible';"
    # changWebElemente_display = "document.setElementById('ia-FilePicker').style.display='block';"
    # self.driver.execute_script(change_visibility)
    # self.WebElement.execute_script(change_display)

#

    # change_height = "document.getElementsByClassName('ia-FilePicker.ia-ControlledFilePicker-control.icl-u-visuallyHidden').style.height='100px';"
    # change_width = "document.getElementsByClassName('ia-FilePicker.ia-ControlledFilePicker-control.icl-u-visuallyHidden').style.width='100px';"
    # self.driver.execute_script(change_height)
    # self.driver.execute_script(change_width)

#

WebDriverWait(self.driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input.ia-FilePicker.ia-ControlledFilePicker-control.icl-u-visuallyHidden#ia-FilePicker-resume"))).style.display = "block" )

And many more. I've been working on this for days.

Error: Message: javascript error: Cannot read property 'style' of null .

I also know about AutoIT, but I want to stick with Selenium on Chrome and Python for now. What can I do? Thank you for your help.

Body:
Make the field visible with setting opacity

self.driver.execute_script("document.querySelector(\"input[id*='ia-FilePicker-resume']\").style.opacity='1'");

and then try to upload file


问:
Sending client security username and password to Spring Boot Admin via Spring Cloud Kubernetes Service Discovery
I am able to discover all services in my namespace and display them on spring boot admin but some of the clients have username/pass protection on some of the actuator endpoints.  How can I get this information to spring boot admin via the kubernetes service discovery?</p>

答:
I was able to pass the client username and password by adding a tag in kubernetes service discovery of user.name and user.password for each client.

This isn't secure though because anyone with read access can read the metadata.

Is there a way to set a global user name and password for all clients?


问:
How do we control web page caching, across all browsers?
Our investigations have shown us that not all browsers respect the HTTP cache directives in a uniform manner.

For security reasons we do not want certain pages in our application to be cached, ever, by the web browser. This must work for at least the following browsers:

Internet Explorer 6+

Firefox 1.5+

Safari 3+

Opera 9+

Chrome

Our requirement came from a security test. After logging out from our website you could press the back button and view cached pages.

答:
Not sure if my answer sounds simple and stupid, and perhaps it has already been known to you since long time ago, but since preventing someone from using browser back button to view your historical pages is one of your goals, you can use:

window.location.replace("https://www.example.com/page-not-to-be-viewed-in-browser-history-back-button.html");

Of course, this may not be possible to be implemented across the entire site, but at least for some critical pages, you can do that. Hope this helps.

OwnerDisplayName: Edward Wilde

LastEditorDisplayName: Edward Wilde


问:
Duplicate Cache-Control header in Spring Boot application
We have a Spring Boot application that runs in Openshift where we configure the Cache-Control header like this:

```<code>@Configuration
@EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.headers().cacheControl().disable().addHeaderWriter((httpServletRequest, httpServletResponse) -> {
            httpServletResponse.setHeader(HttpHeaders.CACHE_CONTROL, "public, max-age=86400");
        });
    }
}
</code>```

In the HTTP responses there are two Cache-Control headers:

```<code>$ curl --header https://<our-url> --head
HTTP/1.1 200 Connection established

HTTP/1.1 200
...
Cache-Control: public, max-age=86400
...
Cache-control: private
</code>```

We expect the first header, and we have no idea where the second header comes from. (Note the lowercase c in the name of the second header.)

Any ideas where the second header comes from and how we can get rid of it?

答:
I found the answer: The Cache-control header is added by HAProxy. HAProxy uses this header and a cookie to create sticky sessions (i.e. to make sure that requests from the same client are handled by the same pod).

See this question for details.

In short, you can disable this behaviour by

```<code>oc annotate route <myroute> haproxy.router.openshift.io/disable_cookies='true'
</code>```

Body:
We have a Spring Boot application that runs in Openshift where we configure the Cache-Control header like this:

@Configuration
@EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.headers().cacheControl().disable().addHeaderWriter((httpServletRequest, httpServletResponse) -> {
            httpServletResponse.setHeader(HttpHeaders.CACHE_CONTROL, "public, max-age=86400");
        });
    }
}

In the HTTP responses there are two Cache-Control headers:

$ curl --header https://<our-url> --head
HTTP/1.1 200 Connection established

HTTP/1.1 200
...
Cache-Control: public, max-age=86400
...
Cache-control: private

We expect the first header, and we have no idea where the second header comes from. (Note the lowercase c in the name of the second header.)

Any ideas where the second header comes from and how we can get rid of it?

Body:
I found the answer: The Cache-control header is added by HAProxy. HAProxy uses this header and a cookie to create sticky sessions (i.e. to make sure that requests from the same client are handled by the same pod).

See this question for details.

In short, you can disable this behaviour by

oc annotate route <myroute> haproxy.router.openshift.io/disable_cookies='true'


问:
Is it possible to have a shared global variable for inter-process communication?
I need to solve a concurrency assignment for my operating systems class. I don't want the solution here, but I am lacking one part.

We should write a process that writes to file, reads from it and then deltetes it. This process we should run two times in two different shells. No fork here for simplicity. Process A should write, Process B then read and then Process should delete the file. Afterwards they switch roles.

I understand that you can achieve atomicity easily by locking. With while loops around the read-, and write sections etc. you can also get further control. But when I run process A and then process B, process B will spin before the write seciton until it achieves the lock and not got into reading when process A releases the lock. So my best guess is to have a read and a write lock. This information must be shared somehow between the processes. The only way I can think of is some global variable, but since both processes hold copies of the variables, I think this is not possible. Another way would be to have a read lock file and a write lock file, but that seems overly complicated to me.

Is there a better way?

答:
Your problem (with files and alternating roles in the creation/deletion of files) seems to be a candidate to use the O_EXCL flag on opening/creating the file.  This flag makes the open(2) system call to succeed in creating a file only if the file doesn't exist, so it makes the file to appear as a semaphore itself.  Each process can liberate the lock (A or B) but the one that does, just liberates the lock and makes the role of owning again accessible.

You will see that both processes try to use one of the roles, but if they both try to use the owner role, one of them will succeed, and the other will fail.

Just enable a SIGINT signal handler on the owning process, to allow it to delete the file in case it gets signalled, or you will leave the file and after that no process will be able to assume the owning role (at least you will need to delete it manually).

This was the first form of locking feature in unix, long before semaphores, shared memory or other ways to block processes existed.  It is based on the atomicity of system calls (you cannot execute two system calls on the same file simultaneously)


问:
How to run debug with c
Good day, i only have the file which is :
sample_: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), statically linked, for GNU/Linux 2.2.5, not stripped

When i run it, it gives an segmentation fault. I tried the debugging with the gdb, but the result was : Reading symbols from sample_...(no debugging symbols found)...done.

Then i tried with the file command :

```<code>(gdb) file sample_
Reading symbols from sample_...(no debugging symbols found)...done.
</code>```

I dont have the .c file itself.

How i can debug it?

答: Seems like the program has not been build with debug flags. If you don't have the source to recompile it with debug flags there is as far as I know no way to properly debug it. You can try to decompile the executable but good luck with that</p>

Title: How to run debug with c

Body:
Good day, i only have the file which is :
sample_: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), statically linked, for GNU/Linux 2.2.5, not stripped

When i run it, it gives an segmentation fault. I tried the debugging with the gdb, but the result was : Reading symbols from sample_...(no debugging symbols found)...done.

Then i tried with the file command :

(gdb) file sample_
Reading symbols from sample_...(no debugging symbols found)...done.

I dont have the .c file itself.

How i can debug it?


问:
Error while compiling code for firebase admin
I got an error while compiling code for Firebase admin.

Error:

Following the info from http://www.slf4j.org/codes.html#StaticLoggerBinder I've tried adding all the dependencies one by one

adding

```<code>testCompile group: 'org.apache.logging.log4j', name: 'log4j-slf4j-impl', version: '2.13.3'
</code>```

or

```<code>testCompile group: 'org.slf4j', name: 'slf4j-nop', version: '1.8.0-beta4'
</code>```

or

```<code>testCompile group: 'org.slf4j', name: 'slf4j-simple', version: '1.8.0-beta4'
</code>```

or

```<code>testCompile group: 'org.slf4j', name: 'slf4j-jdk14', version: '1.8.0-beta4'
</code>```

or

```<code>testCompile group: 'ch.qos.logback', name: 'logback-classic', version: '1.2.3'
</code>```

doesn't remove the error.
May I know what I'm going wrong with?

My Gradle file:

```<code>plugins {
    id 'java'
}

group 'org.example'
version '1.0-SNAPSHOT'

sourceCompatibility = 1.8

repositories {
    mavenCentral()
}

dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.12'
    implementation 'com.google.firebase:firebase-admin:6.13.0'
//None of these seem to remove the error
//    testCompile group: 'org.apache.logging.log4j', name: 'log4j-slf4j-impl', version: '2.13.3'
//    testCompile group: 'org.slf4j', name: 'slf4j-nop', version: '1.8.0-beta4'
//    testCompile group: 'org.slf4j', name: 'slf4j-simple', version: '1.8.0-beta4'
//    testCompile group: 'org.slf4j', name: 'slf4j-jdk14', version: '1.8.0-beta4'
//    testCompile group: 'ch.qos.logback', name: 'logback-classic', version: '1.2.3'
</code>```

My main Class

```<code>import com.google.auth.oauth2.GoogleCredentials;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.database.*;

import java.io.IOException;

public class MainClass {
    public static void main(String[] args) throws IOException {
        FirebaseOptions options = new FirebaseOptions.Builder()
                .setCredentials(GoogleCredentials.getApplicationDefault())
                .setDatabaseUrl("https://{my database name}.firebaseio.com/")
                .build();

        FirebaseApp.initializeApp(options);
        DatabaseReference ref = FirebaseDatabase.getInstance()
                .getReference("restricted_access/secret_document");
        ref.setValue("hiIII", new DatabaseReference.CompletionListener() {
            @Override
            public void onComplete(DatabaseError error, DatabaseReference ref) {
                System.out.println("Completed");
            }
        });
    }
}
</code>```

May I know What I'm going wrong with? and How can I Correct it?

答:
This warning message is reported when the org.slf4j.impl.StaticLoggerBinder class could not be loaded into memory. This happens when no appropriate SLF4J binding could be found on the class path. Placing one (and only one) of slf4j-nop.jar slf4j-simple.jar, slf4j-log4j12.jar, slf4j-jdk14.jar or logback-classic.jar on the class path should solve the problem.

If this problem doesnot solve try clear caches and restart.

Body:
I got an error while compiling code for Firebase admin.

Error:

Following the info from http://www.slf4j.org/codes.html#StaticLoggerBinder I've tried adding all the dependencies one by one

adding

testCompile group: 'org.apache.logging.log4j', name: 'log4j-slf4j-impl', version: '2.13.3'

or

testCompile group: 'org.slf4j', name: 'slf4j-nop', version: '1.8.0-beta4'

or

testCompile group: 'org.slf4j', name: 'slf4j-simple', version: '1.8.0-beta4'

or

testCompile group: 'org.slf4j', name: 'slf4j-jdk14', version: '1.8.0-beta4'

or

testCompile group: 'ch.qos.logback', name: 'logback-classic', version: '1.2.3'

doesn't remove the error.
May I know what I'm going wrong with?

My Gradle file:

plugins {
    id 'java'
}

group 'org.example'
version '1.0-SNAPSHOT'

sourceCompatibility = 1.8

repositories {
    mavenCentral()
}

dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.12'
    implementation 'com.google.firebase:firebase-admin:6.13.0'
//None of these seem to remove the error
//    testCompile group: 'org.apache.logging.log4j', name: 'log4j-slf4j-impl', version: '2.13.3'
//    testCompile group: 'org.slf4j', name: 'slf4j-nop', version: '1.8.0-beta4'
//    testCompile group: 'org.slf4j', name: 'slf4j-simple', version: '1.8.0-beta4'
//    testCompile group: 'org.slf4j', name: 'slf4j-jdk14', version: '1.8.0-beta4'
//    testCompile group: 'ch.qos.logback', name: 'logback-classic', version: '1.2.3'

My main Class

import com.google.auth.oauth2.GoogleCredentials;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.database.*;

import java.io.IOException;

public class MainClass {
    public static void main(String[] args) throws IOException {
        FirebaseOptions options = new FirebaseOptions.Builder()
                .setCredentials(GoogleCredentials.getApplicationDefault())
                .setDatabaseUrl("https://{my database name}.firebaseio.com/")
                .build();

        FirebaseApp.initializeApp(options);
        DatabaseReference ref = FirebaseDatabase.getInstance()
                .getReference("restricted_access/secret_document");
        ref.setValue("hiIII", new DatabaseReference.CompletionListener() {
            @Override
            public void onComplete(DatabaseError error, DatabaseReference ref) {
                System.out.println("Completed");
            }
        });
    }
}

May I know What I'm going wrong with? and How can I Correct it?


问:
Deserialization error : Cannot construct instance of Dto (although at least one Creator exists): cannot deserialize from Object value
Cannot construct instance of DTO (although at least one Creator exists):

```<code>Cannot deserialize from Object value (no delegate- or property-based Creator)
 at [Source: (org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$UnCloseableInputStream); line: 2, column: 2].
</code>```

I am trying to post a JSON object in corda controller. It was working fine with corda 3.3 but after upgrading to 4.1 it is giving the error

```<code>@JsonInclude(JsonInclude.Include.NON_NULL)
@CordaSerializable
public class testDto {

    @JsonProperty("registrationNumber")
    private final String registrationNumber;

    @ConstructorForDeserialization
    public testDto(String registrationNumber) {
        this.registrationNumber = registrationNumber;
    }

    public String getRegistrationNumber() {
        return registrationNumber;
    }
}
</code>```

答:
There must have been an incorrect version upgrade since the serialization mechanism has changed.

Please follow the steps from the link:
https://docs.corda.net/docs/corda-os/4.4/app-upgrade-notes.html

Also, please make sure you upgrade to the newest Corda web server.

Body:
Cannot construct instance of DTO (although at least one Creator exists):

Cannot deserialize from Object value (no delegate- or property-based Creator)
 at [Source: (org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$UnCloseableInputStream); line: 2, column: 2].

I am trying to post a JSON object in corda controller. It was working fine with corda 3.3 but after upgrading to 4.1 it is giving the error

@JsonInclude(JsonInclude.Include.NON_NULL)
@CordaSerializable
public class testDto {

    @JsonProperty("registrationNumber")
    private final String registrationNumber;

    @ConstructorForDeserialization
    public testDto(String registrationNumber) {
        this.registrationNumber = registrationNumber;
    }

    public String getRegistrationNumber() {
        return registrationNumber;
    }
}