问:
Tkinter freezes when looping through OHLC data
I programmed an app in Tkinter and when I run it the ohlc plot is working properly but the tkinter window is freezing. I am a beginner of multiprocessing in Tkinter and any help is appreciated.

https://github.com/DataScientist2807/Tkinter/blob/master/SetupFrameWindowStockkApp_031_stackoverflow.py

edit: I attached the code below. The GUI is freezing. I do not know how to best solve this issue. Whether I use Multiprocessing or using the animate function in Matplotlib or any other solution.

```<code>import tkinter as tk
from tkinter import Tk, Frame, Menu, ttk
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
from matplotlib.figure import Figure
from matplotlib import pyplot as plt
import os
import pandas as pd
import json
import matplotlib.dates as mdates
from mplfinance.original_flavor import candlestick_ohlc
from datetime import datetime
import time
import matplotlib.animation as animation
import matplotlib.ticker as mticker
import numpy as np
import threading
from multiprocessing import Process
import multiprocessing

def convert_ticks_to_ohlc(df, df_column, timeframe):
    data_frame = df[df_column].resample(timeframe).ohlc()
    return data_frame

valInterval = "5Min"
valCandles = 30
valValueSim = 0

class StockApp(Frame):

    def __init__(self):
        super().__init__()

        Process(target=self.initiate_mastergrid()).start()
        Process(target=self.init_menuBar()).start()
        Process(target=self.initFrames()).start()
        Process(target=self.main_frame()).start()

    def initiate_mastergrid(self):
        # Configure the grid
        self.master.grid_rowconfigure(1, weight=4)
        self.master.grid_columnconfigure(1, weight=1)
        self.master.grid_columnconfigure(2, weight=1)
        self.master.grid_columnconfigure(3, weight=1)

    def initialize_mainchart(self):
        self.figmain = plt.figure(figsize=(20,5), dpi=80)
        dataPlot2 = FigureCanvasTkAgg(self.figmain, master=self.mainFrame)
        self.am2 = plt.subplot2grid((4,5), (1,0), rowspan=2, colspan=5)
        self.am1 = plt.subplot2grid((4,5), (0,0), rowspan=1, colspan=5, facecolor="#F0F0F0", sharex=self.am2)
        self.am3 = plt.subplot2grid((4,5), (3,0), rowspan=1, colspan=5, sharex=self.am2)
        self.am2.yaxis.tick_right() # Price, Indicator and Volume Labels on the right
        self.am1.yaxis.tick_right() # Price, Indicator and Volume Labels on the right
        self.am3.yaxis.tick_right() # Price, Indicator and Volume Labels on the right

        plt.setp(self.am2.get_xticklabels(), visible=False)
        plt.setp(self.am1.get_xticklabels(), visible=False)
        plt.tight_layout(pad=0, w_pad=-1, h_pad=-1)

        plt.ion() # Necessary to animate plot
        dataPlot2.draw()
        dataPlot2.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)

    def load_data(self):
        global tick_data
        os.chdir("C:\\Trainings\\Python\\Tkinter\\StockApp\\SampleData")
        tick_data = pd.read_csv("EURUSD-2019_01_01.csv",
                        index_col=["time"],
                        usecols=["time", "ask", "bid"],
                        parse_dates=["time"])

        print("Data has been loaded")

    def clear_axes(self, axes):
        axes.clear() # - Clear the chart

    def update_chart(self, candle_data):

        candlestick_ohlc(self.am2, candle_data, width=(15*0.5)/(24*60),
                         colorup='#075105',
                         colordown='#AF141A')

        for label in self.am2.xaxis.get_ticklabels():
            label.set_rotation(45)
        self.am2.xaxis.set_major_locator(mticker.MaxNLocator(10))
        self.am2.grid(True)
        plt.grid(False)
        plt.xlabel('Candle count')
        plt.ylabel('Price')
        plt.title('Candlestick chart simulation')
        plt.subplots_adjust(left=0.09, bottom=0.20, right=0.94,
                            top=0.90, wspace=0.2, hspace=0)
        self.figmain.canvas.draw() # - Draw on the chart

    def candlestick_simulation(self, tick_data, time_frame, candle_window):

        candlestick_data = convert_ticks_to_ohlc(tick_data,
                                                 "ask",
                                                 "15Min").dropna()

        print("Converts tick to ohlc")

        candlestick_data = candlestick_data.reset_index()

        dvalues = candlestick_data[['open', 'high', 'low', 'close']].values.tolist()
        pdates = mdates.date2num(candlestick_data.time)
        ohlc = [[pdates[i]] + dvalues[i] for i in range(len(pdates))]

        print("Converted ohlc")

        self.ohlc_animate(ohlc)

        print("Start animation")

    def ohlc_animate(self, ohlclist):

        emptyOHLC = []

        for i in range(0, 20):

            valuesOHLC = ohlclist[i]

            emptyOHLC = emptyOHLC + [valuesOHLC]

            p_update = Process(target=self.update_chart(emptyOHLC))
            p_update.start()
            p_update.join()

            #self.update_chart(emptyOHLC)

            print("Sleep 3 seconds")

            time.sleep(3.0)

            self.clear_axes(self.am2)

    def start_simulation(self):

        Process(target=self.candlestick_simulation(tick_data, valInterval, valCandles)).start()
        print("Start Simulation")

    def main_frame(self):
        global dataB

        Process(target=self.initialize_mainchart()).start()
        print("Main Frame initialised")

        Process(target=self.load_data()).start()
        print(len(tick_data))

    def initFrames(self):

        self.mainFrame = Frame(self.master,bd=1, relief="sunken") #whatever
        self.mainFrame.grid(row=1, column=1, columnspan=2, sticky="nsew", padx=1, pady=1)

    def init_menuBar(self):

        menubar = Menu(self.master)
        self.master.config(menu=menubar)

        # Add menu items
        file_menu = Menu(menubar, tearoff=0)
        menubar.add_cascade(label="File", menu=file_menu)
        indicator_menu = Menu(menubar, tearoff=0)
        indicator_menu.add_command(label="EURUSD", command=lambda: self.start_simulation())
        file_menu.add_cascade(label="Interval", menu=indicator_menu)

def main():
    app = StockApp()
    app.master.title("Stock App 2020 by datascience2807@gmail.com")
    width_value = app.master.winfo_screenwidth()
    height_value = app.master.winfo_screenheight()
    app.master.geometry("%dx%d+0+0" % (width_value,height_value))
    app.mainloop()

if __name__ == '__main__':
    pool = multiprocessing.Pool()
    threading.Thread(target=main()).start()
</code>```

答:
Tkinter itself is difficult to use with multiprocessing due to mutliprocessing's reliance on pickle and the lack of ability to pickle a Tkinter app. This often results in errors when using class based functions with the Process command. Furthermore, time.sleep forces the whole of the tkinter thread to hang for, in your case, 3 seconds. This then stop the code from working and prevents you from being able to close the window in the mean time.

The answer to this problem is to utilize, self.after within your code. self.after allows for asynchronous code to be written for Tkinter applications and is often used as an example for how to build stopwatch applications.

I have made quite a few changes your code, by dropping both threading and mutliprocessing throughout the code and moving the necessary objects to self.after. I feel one of the reasons your code did hang rather a lot was also the fact you loaded the data on the creation of the main frame. Perhaps it would've been better to load this before the tkinter program starts (by placing it in the main() function), this will prevent that long hang at the start.

Now for updated code:

# -*- coding: utf-8 -*-
"""
Created on Sun May 17 11:21:57 2020

@author: Marcel
"""

import tkinter as tk
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib import pyplot as plt
import pandas as pd
import matplotlib.dates as mdates
from mplfinance.original_flavor import candlestick_ohlc
import matplotlib.ticker as mticker

def convert_ticks_to_ohlc(df, df_column, timeframe):
    data_frame = df[df_column].resample(timeframe).ohlc()
    return data_frame

valInterval = "5Min"
valCandles = 30
valValueSim = 0

class StockApp(tk.Frame):
    def __init__(self):
        super().__init__()

        self.initiate_mastergrid()
        self.init_menuBar()
        self.initFrames()
        self.main_frame()

    def initiate_mastergrid(self):
        # Configure the grid
        self.master.grid_rowconfigure(1, weight=4)
        self.master.grid_columnconfigure(1, weight=1)
        self.master.grid_columnconfigure(2, weight=1)
        self.master.grid_columnconfigure(3, weight=1)

    def initialize_mainchart(self):
        self.figmain = plt.figure(figsize=(20, 5), dpi=80)
        dataPlot2 = FigureCanvasTkAgg(self.figmain, master=self.mainFrame)
        self.am2 = plt.subplot2grid((4, 5), (1, 0), rowspan=2, colspan=5)
        self.am1 = plt.subplot2grid(
            (4, 5), (0, 0), rowspan=1, colspan=5, facecolor="#F0F0F0", sharex=self.am2
        )
        self.am3 = plt.subplot2grid(
            (4, 5), (3, 0), rowspan=1, colspan=5, sharex=self.am2
        )
        self.am2.yaxis.tick_right()  # Price, Indicator and Volume Labels on the right
        self.am1.yaxis.tick_right()  # Price, Indicator and Volume Labels on the right
        self.am3.yaxis.tick_right()  # Price, Indicator and Volume Labels on the right

        plt.setp(self.am2.get_xticklabels(), visible=False)
        plt.setp(self.am1.get_xticklabels(), visible=False)
        plt.tight_layout(pad=0, w_pad=-1, h_pad=-1)

        plt.ion()  # Necessary to animate plot
        dataPlot2.draw()
        dataPlot2.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)

    def load_data(self):
        global tick_data
        # os.chdir("C:\\Trainings\\Python\\Tkinter\\StockApp\\SampleData")
        tick_data = pd.read_csv(
            "EURUSD-2019_01_01.csv",
            index_col=["time"],
            usecols=["time", "ask", "bid"],
            parse_dates=["time"],
        )

        print("Data has been loaded")

    def clear_axes(self, axes):
        axes.clear()  # - Clear the chart

    def update_chart(self, candle_data):

        candlestick_ohlc(
            self.am2,
            candle_data,
            width=(15 * 0.5) / (24 * 60),
            colorup="#075105",
            colordown="#AF141A",
        )

        for label in self.am2.xaxis.get_ticklabels():
            label.set_rotation(45)
        self.am2.xaxis.set_major_locator(mticker.MaxNLocator(10))
        self.am2.grid(True)
        plt.grid(False)
        plt.xlabel("Candle count")
        plt.ylabel("Price")
        plt.title("Candlestick chart simulation")
        plt.subplots_adjust(
            left=0.09, bottom=0.20, right=0.94, top=0.90, wspace=0.2, hspace=0
        )
        self.figmain.canvas.draw()  # - Draw on the chart

    def candlestick_simulation(self, tick_data, time_frame, candle_window):

        candlestick_data = convert_ticks_to_ohlc(tick_data, "ask", "15Min").dropna()

        print("Converts tick to ohlc")

        candlestick_data = candlestick_data.reset_index()

        dvalues = candlestick_data[["open", "high", "low", "close"]].values.tolist()
        pdates = mdates.date2num(candlestick_data.time)
        ohlc = [[pdates[i]] + dvalues[i] for i in range(len(pdates))]

        print("Converted ohlc")

        self.ohlc_animate(ohlc)

        print("Start animation")

    def ohlc_animate(self, ohlclist):

        emptyOHLC = []

        for i in range(0, 20):

            valuesOHLC = ohlclist[i]

            emptyOHLC = emptyOHLC + [valuesOHLC]

            self.after(3000 * (i + 1), self.update_chart, emptyOHLC)

    def start_simulation(self):
        self.candlestick_simulation(tick_data, valInterval, valCandles)
        print("Start Simulation")

    def main_frame(self):
        self.initialize_mainchart()
        print("Main Frame initialised")

        self.load_data()
        print(len(tick_data))

    def initFrames(self):
        self.mainFrame = tk.Frame(self.master, bd=1, relief="sunken")  # whatever
        self.mainFrame.grid(
            row=1, column=1, columnspan=2, sticky="nsew", padx=1, pady=1
        )

    def init_menuBar(self):

        menubar = tk.Menu(self.master)
        self.master.config(menu=menubar)

        # Add menu items
        file_menu = tk.Menu(menubar, tearoff=0)
        menubar.add_cascade(label="File", menu=file_menu)
        indicator_menu = tk.Menu(menubar, tearoff=0)
        indicator_menu.add_command(
            label="EURUSD", command=lambda: self.start_simulation()
        )
        file_menu.add_cascade(label="Interval", menu=indicator_menu)

def main():

    app = StockApp()
    app.master.title("Stock App 2020 by datascience2807@gmail.com")
    width_value = app.master.winfo_screenwidth()
    height_value = app.master.winfo_screenheight()
    app.master.geometry("%dx%d+0+0" % (width_value, height_value))
    app.mainloop()

if __name__ == "__main__":
    main()
```

<h3>The important line of code</h3>

<pre class="lang-py prettyprint-override"><code>self.after(3000 * (i + 1), self.update_chart, emptyOHLC)
</code>```

What this does is it builds a queue of chart updates and executes them 3 seconds after each other. So the first run of the loop would give, 3000 miliseconds and the second run would give 6000 milliseconds. This method results in a lot less hanging, in comparison to pausing the whole code with time.sleep(1).

I hope this helps,

James

Body:
I programmed an app in Tkinter and when I run it the ohlc plot is working properly but the tkinter window is freezing. I am a beginner of multiprocessing in Tkinter and any help is appreciated.

https://github.com/DataScientist2807/Tkinter/blob/master/SetupFrameWindowStockkApp_031_stackoverflow.py

edit: I attached the code below. The GUI is freezing. I do not know how to best solve this issue. Whether I use Multiprocessing or using the animate function in Matplotlib or any other solution.

import tkinter as tk
from tkinter import Tk, Frame, Menu, ttk
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
from matplotlib.figure import Figure
from matplotlib import pyplot as plt
import os
import pandas as pd
import json
import matplotlib.dates as mdates
from mplfinance.original_flavor import candlestick_ohlc
from datetime import datetime
import time
import matplotlib.animation as animation
import matplotlib.ticker as mticker
import numpy as np
import threading
from multiprocessing import Process
import multiprocessing

def convert_ticks_to_ohlc(df, df_column, timeframe):
    data_frame = df[df_column].resample(timeframe).ohlc()
    return data_frame

valInterval = "5Min"
valCandles = 30
valValueSim = 0

class StockApp(Frame):

    def __init__(self):
        super().__init__()

        Process(target=self.initiate_mastergrid()).start()
        Process(target=self.init_menuBar()).start()
        Process(target=self.initFrames()).start()
        Process(target=self.main_frame()).start()

    def initiate_mastergrid(self):
        # Configure the grid
        self.master.grid_rowconfigure(1, weight=4)
        self.master.grid_columnconfigure(1, weight=1)
        self.master.grid_columnconfigure(2, weight=1)
        self.master.grid_columnconfigure(3, weight=1)

    def initialize_mainchart(self):
        self.figmain = plt.figure(figsize=(20,5), dpi=80)
        dataPlot2 = FigureCanvasTkAgg(self.figmain, master=self.mainFrame)
        self.am2 = plt.subplot2grid((4,5), (1,0), rowspan=2, colspan=5)
        self.am1 = plt.subplot2grid((4,5), (0,0), rowspan=1, colspan=5, facecolor="#F0F0F0", sharex=self.am2)
        self.am3 = plt.subplot2grid((4,5), (3,0), rowspan=1, colspan=5, sharex=self.am2)
        self.am2.yaxis.tick_right() # Price, Indicator and Volume Labels on the right
        self.am1.yaxis.tick_right() # Price, Indicator and Volume Labels on the right
        self.am3.yaxis.tick_right() # Price, Indicator and Volume Labels on the right

        plt.setp(self.am2.get_xticklabels(), visible=False)
        plt.setp(self.am1.get_xticklabels(), visible=False)
        plt.tight_layout(pad=0, w_pad=-1, h_pad=-1)

        plt.ion() # Necessary to animate plot
        dataPlot2.draw()
        dataPlot2.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)

    def load_data(self):
        global tick_data
        os.chdir("C:\\Trainings\\Python\\Tkinter\\StockApp\\SampleData")
        tick_data = pd.read_csv("EURUSD-2019_01_01.csv",
                        index_col=["time"],
                        usecols=["time", "ask", "bid"],
                        parse_dates=["time"])

        print("Data has been loaded")

    def clear_axes(self, axes):
        axes.clear() # - Clear the chart

    def update_chart(self, candle_data):

        candlestick_ohlc(self.am2, candle_data, width=(15*0.5)/(24*60),
                         colorup='#075105',
                         colordown='#AF141A')

        for label in self.am2.xaxis.get_ticklabels():
            label.set_rotation(45)
        self.am2.xaxis.set_major_locator(mticker.MaxNLocator(10))
        self.am2.grid(True)
        plt.grid(False)
        plt.xlabel('Candle count')
        plt.ylabel('Price')
        plt.title('Candlestick chart simulation')
        plt.subplots_adjust(left=0.09, bottom=0.20, right=0.94,
                            top=0.90, wspace=0.2, hspace=0)
        self.figmain.canvas.draw() # - Draw on the chart

    def candlestick_simulation(self, tick_data, time_frame, candle_window):

        candlestick_data = convert_ticks_to_ohlc(tick_data,
                                                 "ask",
                                                 "15Min").dropna()

        print("Converts tick to ohlc")

        candlestick_data = candlestick_data.reset_index()

        dvalues = candlestick_data[['open', 'high', 'low', 'close']].values.tolist()
        pdates = mdates.date2num(candlestick_data.time)
        ohlc = [[pdates[i]] + dvalues[i] for i in range(len(pdates))]

        print("Converted ohlc")

        self.ohlc_animate(ohlc)

        print("Start animation")

    def ohlc_animate(self, ohlclist):

        emptyOHLC = []

        for i in range(0, 20):

            valuesOHLC = ohlclist[i]

            emptyOHLC = emptyOHLC + [valuesOHLC]

            p_update = Process(target=self.update_chart(emptyOHLC))
            p_update.start()
            p_update.join()

            #self.update_chart(emptyOHLC)

            print("Sleep 3 seconds")

            time.sleep(3.0)

            self.clear_axes(self.am2)

    def start_simulation(self):

        Process(target=self.candlestick_simulation(tick_data, valInterval, valCandles)).start()
        print("Start Simulation")

    def main_frame(self):
        global dataB

        Process(target=self.initialize_mainchart()).start()
        print("Main Frame initialised")

        Process(target=self.load_data()).start()
        print(len(tick_data))

    def initFrames(self):

        self.mainFrame = Frame(self.master,bd=1, relief="sunken") #whatever
        self.mainFrame.grid(row=1, column=1, columnspan=2, sticky="nsew", padx=1, pady=1)

    def init_menuBar(self):

        menubar = Menu(self.master)
        self.master.config(menu=menubar)

        # Add menu items
        file_menu = Menu(menubar, tearoff=0)
        menubar.add_cascade(label="File", menu=file_menu)
        indicator_menu = Menu(menubar, tearoff=0)
        indicator_menu.add_command(label="EURUSD", command=lambda: self.start_simulation())
        file_menu.add_cascade(label="Interval", menu=indicator_menu)

def main():
    app = StockApp()
    app.master.title("Stock App 2020 by datascience2807@gmail.com")
    width_value = app.master.winfo_screenwidth()
    height_value = app.master.winfo_screenheight()
    app.master.geometry("%dx%d+0+0" % (width_value,height_value))
    app.mainloop()

if __name__ == '__main__':
    pool = multiprocessing.Pool()
    threading.Thread(target=main()).start()

Body:
Tkinter itself is difficult to use with multiprocessing due to mutliprocessing's reliance on pickle and the lack of ability to pickle a Tkinter app. This often results in errors when using class based functions with the Process command. Furthermore, time.sleep forces the whole of the tkinter thread to hang for, in your case, 3 seconds. This then stop the code from working and prevents you from being able to close the window in the mean time.

The answer to this problem is to utilize, self.after within your code. self.after allows for asynchronous code to be written for Tkinter applications and is often used as an example for how to build stopwatch applications.

I have made quite a few changes your code, by dropping both threading and mutliprocessing throughout the code and moving the necessary objects to self.after. I feel one of the reasons your code did hang rather a lot was also the fact you loaded the data on the creation of the main frame. Perhaps it would've been better to load this before the tkinter program starts (by placing it in the main() function), this will prevent that long hang at the start.

Now for updated code:

# -*- coding: utf-8 -*-
"""
Created on Sun May 17 11:21:57 2020

@author: Marcel
"""

import tkinter as tk
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib import pyplot as plt
import pandas as pd
import matplotlib.dates as mdates
from mplfinance.original_flavor import candlestick_ohlc
import matplotlib.ticker as mticker

def convert_ticks_to_ohlc(df, df_column, timeframe):
    data_frame = df[df_column].resample(timeframe).ohlc()
    return data_frame

valInterval = "5Min"
valCandles = 30
valValueSim = 0

class StockApp(tk.Frame):
    def __init__(self):
        super().__init__()

        self.initiate_mastergrid()
        self.init_menuBar()
        self.initFrames()
        self.main_frame()

    def initiate_mastergrid(self):
        # Configure the grid
        self.master.grid_rowconfigure(1, weight=4)
        self.master.grid_columnconfigure(1, weight=1)
        self.master.grid_columnconfigure(2, weight=1)
        self.master.grid_columnconfigure(3, weight=1)

    def initialize_mainchart(self):
        self.figmain = plt.figure(figsize=(20, 5), dpi=80)
        dataPlot2 = FigureCanvasTkAgg(self.figmain, master=self.mainFrame)
        self.am2 = plt.subplot2grid((4, 5), (1, 0), rowspan=2, colspan=5)
        self.am1 = plt.subplot2grid(
            (4, 5), (0, 0), rowspan=1, colspan=5, facecolor="#F0F0F0", sharex=self.am2
        )
        self.am3 = plt.subplot2grid(
            (4, 5), (3, 0), rowspan=1, colspan=5, sharex=self.am2
        )
        self.am2.yaxis.tick_right()  # Price, Indicator and Volume Labels on the right
        self.am1.yaxis.tick_right()  # Price, Indicator and Volume Labels on the right
        self.am3.yaxis.tick_right()  # Price, Indicator and Volume Labels on the right

        plt.setp(self.am2.get_xticklabels(), visible=False)
        plt.setp(self.am1.get_xticklabels(), visible=False)
        plt.tight_layout(pad=0, w_pad=-1, h_pad=-1)

        plt.ion()  # Necessary to animate plot
        dataPlot2.draw()
        dataPlot2.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)

    def load_data(self):
        global tick_data
        # os.chdir("C:\\Trainings\\Python\\Tkinter\\StockApp\\SampleData")
        tick_data = pd.read_csv(
            "EURUSD-2019_01_01.csv",
            index_col=["time"],
            usecols=["time", "ask", "bid"],
            parse_dates=["time"],
        )

        print("Data has been loaded")

    def clear_axes(self, axes):
        axes.clear()  # - Clear the chart

    def update_chart(self, candle_data):

        candlestick_ohlc(
            self.am2,
            candle_data,
            width=(15 * 0.5) / (24 * 60),
            colorup="#075105",
            colordown="#AF141A",
        )

        for label in self.am2.xaxis.get_ticklabels():
            label.set_rotation(45)
        self.am2.xaxis.set_major_locator(mticker.MaxNLocator(10))
        self.am2.grid(True)
        plt.grid(False)
        plt.xlabel("Candle count")
        plt.ylabel("Price")
        plt.title("Candlestick chart simulation")
        plt.subplots_adjust(
            left=0.09, bottom=0.20, right=0.94, top=0.90, wspace=0.2, hspace=0
        )
        self.figmain.canvas.draw()  # - Draw on the chart

    def candlestick_simulation(self, tick_data, time_frame, candle_window):

        candlestick_data = convert_ticks_to_ohlc(tick_data, "ask", "15Min").dropna()

        print("Converts tick to ohlc")

        candlestick_data = candlestick_data.reset_index()

        dvalues = candlestick_data[["open", "high", "low", "close"]].values.tolist()
        pdates = mdates.date2num(candlestick_data.time)
        ohlc = [[pdates[i]] + dvalues[i] for i in range(len(pdates))]

        print("Converted ohlc")

        self.ohlc_animate(ohlc)

        print("Start animation")

    def ohlc_animate(self, ohlclist):

        emptyOHLC = []

        for i in range(0, 20):

            valuesOHLC = ohlclist[i]

            emptyOHLC = emptyOHLC + [valuesOHLC]

            self.after(3000 * (i + 1), self.update_chart, emptyOHLC)

    def start_simulation(self):
        self.candlestick_simulation(tick_data, valInterval, valCandles)
        print("Start Simulation")

    def main_frame(self):
        self.initialize_mainchart()
        print("Main Frame initialised")

        self.load_data()
        print(len(tick_data))

    def initFrames(self):
        self.mainFrame = tk.Frame(self.master, bd=1, relief="sunken")  # whatever
        self.mainFrame.grid(
            row=1, column=1, columnspan=2, sticky="nsew", padx=1, pady=1
        )

    def init_menuBar(self):

        menubar = tk.Menu(self.master)
        self.master.config(menu=menubar)

        # Add menu items
        file_menu = tk.Menu(menubar, tearoff=0)
        menubar.add_cascade(label="File", menu=file_menu)
        indicator_menu = tk.Menu(menubar, tearoff=0)
        indicator_menu.add_command(
            label="EURUSD", command=lambda: self.start_simulation()
        )
        file_menu.add_cascade(label="Interval", menu=indicator_menu)

def main():

    app = StockApp()
    app.master.title("Stock App 2020 by datascience2807@gmail.com")
    width_value = app.master.winfo_screenwidth()
    height_value = app.master.winfo_screenheight()
    app.master.geometry("%dx%d+0+0" % (width_value, height_value))
    app.mainloop()

if __name__ == "__main__":
    main()

The important line of code

self.after(3000 * (i + 1), self.update_chart, emptyOHLC)

What this does is it builds a queue of chart updates and executes them 3 seconds after each other. So the first run of the loop would give, 3000 miliseconds and the second run would give 6000 milliseconds. This method results in a lot less hanging, in comparison to pausing the whole code with time.sleep(1).

I hope this helps,

James


来源: stackexchange

问:
Is there any way to monitor Azure Synapse Pipelines execution?
In my project, I've a need where I need to show how Pipeline is progressing on custom Web Portal built in PHP. Is there any way in any language such as C# or Java through which I can list pipelines and monitor the progress or even log into Application Insights?</p>

答:
Are you labelling your queries with the OPTION (LABEL='MY LABEL') syntax?

This will make it easy to monitor the progress of your pipeline by querying sys.dm_pdw_exec_requests to pick individual queries (see last paragraph under link heading), and if you use a naming convention like 'pipeline_query' you can probably achieve what you want.

ContentLicense: CC BY-SA 4.0


问:
Disable click outside of bootstrap modal area to close modal
I am making a bootstrap website, with a couple of Bootstrap 'Modals'.
I'm trying to customize some of the default features.

Problem is this;
You can close the modal by clicking on the background.
Is there anyway to disable this feature?
On specifc modals only?

Bootstrap modal page

答:
Use this if you want to disable the outer click for all modals using jQuery. Add this script to your Javascript after jQuery.</p>

```<code>jQuery(document).ready(function () {
    jQuery('[data-toggle="modal"]').each(function () {
       jQuery(this).attr('data-backdrop','static');
       jQuery(this).attr('data-keyboard','false');
    });
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Use this if you want to disable the outer click for all modals using jQuery. Add this script to your Javascript after jQuery.

jQuery(document).ready(function () {
    jQuery('[data-toggle="modal"]').each(function () {
       jQuery(this).attr('data-backdrop','static');
       jQuery(this).attr('data-keyboard','false');
    });
});


问:
Angular, Nginx, Docker results in 404 error on page refresh
I have an angular application, and using nginx on docker container. When I run the application then the localhost works fine, and it redirects to localhost/auth but when I refresh the browser with localhost/auth in address then it gives error 404.
I had followed other forums like 404 Error on page refresh with Angular 7, NGINX and Docker, Angular Nginx Docker 404 also but still same problem exists.

DockerFile

```<code>FROM node:alpine as builder

WORKDIR /app
# Install app dependencies
COPY . /app/
RUN cd /app && yarn install
RUN cd /app && yarn build:aot:dev

COPY ./nginx.conf /etc/nginx/nginx.conf

# STEP 2 build a small nginx image with static website
FROM nginx:alpine
COPY ./nginx.conf /etc/nginx/nginx.conf
RUN rm -rf /usr/share/nginx/html/*
COPY --from=builder /app/dist/apps/martor /usr/share/nginx/html
RUN ls /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
</code>```

nginx.conf

```<code>user  nginx;
worker_processes  auto;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;

events {
    worker_connections  1024;
}

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    gzip  on;

    include /etc/nginx/conf.d/*.conf;
    server {
    listen       80;
    server_name localhost;

    #charset koi8-r;
    #access_log  /var/log/nginx/host.access.log  main;

    error_page 403 404 /index.html;
    location / {
        root   /usr/share/nginx/html;
        try_files $uri $uri/ index.html;
        index  index.html index.html;

        # Allo CORS
        if ($request_method ~* "(GET|POST|PUT|DELETE|PATCH|OPTIONS)") {
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, DELETE, PUT, PATCH, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'Content-Type, x-access-token,access-control-allow-origin,access-control-allow-credentials,access-control-allow-headers';
        add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
        }
    }

    #error_page  404              /404.html;

    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
    }
}

</code>```

答: The issue is solved by adding error pages in to aws CDN cloud front</p>

Body:
I have an angular application, and using nginx on docker container. When I run the application then the localhost works fine, and it redirects to localhost/auth but when I refresh the browser with localhost/auth in address then it gives error 404.
I had followed other forums like 404 Error on page refresh with Angular 7, NGINX and Docker, Angular Nginx Docker 404 also but still same problem exists.

DockerFile

FROM node:alpine as builder

WORKDIR /app
# Install app dependencies
COPY . /app/
RUN cd /app && yarn install
RUN cd /app && yarn build:aot:dev

COPY ./nginx.conf /etc/nginx/nginx.conf

# STEP 2 build a small nginx image with static website
FROM nginx:alpine
COPY ./nginx.conf /etc/nginx/nginx.conf
RUN rm -rf /usr/share/nginx/html/*
COPY --from=builder /app/dist/apps/martor /usr/share/nginx/html
RUN ls /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]

nginx.conf

user  nginx;
worker_processes  auto;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;

events {
    worker_connections  1024;
}

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    gzip  on;

    include /etc/nginx/conf.d/*.conf;
    server {
    listen       80;
    server_name localhost;

    #charset koi8-r;
    #access_log  /var/log/nginx/host.access.log  main;

    error_page 403 404 /index.html;
    location / {
        root   /usr/share/nginx/html;
        try_files $uri $uri/ index.html;
        index  index.html index.html;

        # Allo CORS
        if ($request_method ~* "(GET|POST|PUT|DELETE|PATCH|OPTIONS)") {
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, DELETE, PUT, PATCH, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'Content-Type, x-access-token,access-control-allow-origin,access-control-allow-credentials,access-control-allow-headers';
        add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
        }
    }

    #error_page  404              /404.html;

    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
    }
}


问:
Discord.js -- message is not defined
```<code>const client = new Discord.Client();
const ayarlar = require('./ayarlar.json');

var prefix = ayarlar.prefix;

client.on('ready', () => {
console.log(`Botun olan ${client.user.tag}sunucuya giriş yaptı ve artık aktif!`);
});

client.on('message', msg => {
if (msg.content.toLowerCase() === 'salak aziz') {
  msg.channel.send('nerden bildin? helal olsun');
}
if (message.content === `${prefix}mal`) {
message.channel.send('Aziz Mert');
} else if (message.content === `${prefix}adam`) {
message.channel.send('Ata');
}

});
</code>```

Im a beginner.

The error is 'ReferenceError: message is not defined' How can i fix it?

Thanks.

答:
That is because you defined the parameter of the message event as msg not message

const client = new Discord.Client();
const ayarlar = require('./ayarlar.json');

var prefix = ayarlar.prefix;

client.on('ready', () => {
console.log(`Botun olan ${client.user.tag}sunucuya giriş yaptı ve artık aktif!`);
});

client.on('message', message => {
if (message.content.toLowerCase() === 'salak aziz') {
  message.channel.send('nerden bildin? helal olsun');
}
if (message.content === `${prefix}mal`) {
message.channel.send('Aziz Mert');
} else if (message.content === `${prefix}adam`) {
message.channel.send('Ata');
}

});
```

Title: Discord.js -- message is not defined

Body:
const client = new Discord.Client();
const ayarlar = require('./ayarlar.json');

var prefix = ayarlar.prefix;

client.on('ready', () => {
console.log(`Botun olan ${client.user.tag}sunucuya giriş yaptı ve artık aktif!`);
});

client.on('message', msg => {
if (msg.content.toLowerCase() === 'salak aziz') {
  msg.channel.send('nerden bildin? helal olsun');
}
if (message.content === `${prefix}mal`) {
message.channel.send('Aziz Mert');
} else if (message.content === `${prefix}adam`) {
message.channel.send('Ata');
}

});

Im a beginner.

The error is 'ReferenceError: message is not defined' How can i fix it?

Thanks.


问:
Freezing UI Thread with AsyncTask
I'm trying to use an AsyncTask to download a file with a notification progress. Everything works fine (downloads in background thread), except whenever I add the code to update the progress bar through publishProgress(), it freezes the whole phone, until the download is finished and the notification shows "Download Completed".

I'm completely lost as to why this is the case, but I am maybe thinking it's along the lines of the publishProgress((downloadedSize / totalSize) * 100) that i'm using?

Anyways here is the DownloadDataTask:

```<code>    protected String doInBackground(RomDataSet... params) {
        try {

            // Download file here, all good

            //now, read through the input buffer and write the contents to the file
            while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
                //add the data in the buffer to the file in the file output stream (the file on the sd card
                fileOutput.write(buffer, 0, bufferLength);
                //add up the size so we know how much is downloaded
                downloadedSize += bufferLength;
                //this is where you would do something to report the prgress, like this maybe

                publishProgress((downloadedSize / totalSize) * 100);
            }
            //close the output stream when done
            fileOutput.close();

        //catch some possible errors...
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPreExecute() {
        Intent intent = new Intent(ListActivity.this, ListActivity.class);
        pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, 0);

        // configure the notification
        notification = new Notification(R.drawable.ic_stat_rom, "Downloading Rom via RomGet", System
                .currentTimeMillis());
        notification.flags = notification.flags | Notification.FLAG_ONGOING_EVENT;
        notification.contentView = new RemoteViews(getApplicationContext().getPackageName(), R.layout.layout_download);
        notification.contentIntent = pendingIntent;
        notification.contentView.setImageViewResource(R.id.status_icon, R.drawable.icon_rom);
        notification.contentView.setTextViewText(R.id.download_description, "Downloading");
        notification.contentView.setProgressBar(R.id.download_progress, 100, 0, false);

        getApplicationContext();
        notificationManager = (NotificationManager) getApplicationContext().getSystemService(
                Context.NOTIFICATION_SERVICE);

        notificationManager.notify(43, notification);
    }

    @Override
    protected void onProgressUpdate(Integer... progress) {
        //notification.contentView.setProgressBar(R.id.download_progress, 100, Math.round(progress[0]), false);
        notification.contentView.setTextViewText(R.id.download_description, Integer.toString(progress[0]));
        // inform the progress bar of updates in progress
        notificationManager.notify(43, notification);
    }

    @Override
    protected void onPostExecute(String result) {
        notification.contentView.setProgressBar(R.id.download_progress, 100, 100, false);
        notification.contentView.setTextViewText(R.id.download_description, "Done");
        notificationManager.notify(43, notification);
    }
</code>```

I'm really stuck on this one - Any help would be appreciated. Cheers

```<code>    @Override
    protected void onProgressUpdate(Integer... progress) {
        if ((progress[0] - lastSize) > 5000) {
            lastSize = progress[0];
            notification.contentView.setProgressBar(R.id.download_progress, totalSize, progress[0], false);
            //notification.contentView.setTextViewText(R.id.download_description, Integer.toString(progress[0]));
            // inform the progress bar of updates in progress
            notificationManager.notify(43, notification);
        }
    }
</code>```

答:
Use a mod operator to only update on 5, 10 or 20 %.  You're calling onProgressUpdate() constantly during the download.</p>

```<code>if (downloadedSize % (totalSize / 20) == 0) { // 20 updates every 5%, 10 every 10% and 5 every 20%, etc.
    publishProgress((downloadedSize / totalSize) * 100);
}
</code>```

Title: Freezing UI Thread with AsyncTask

Body:
I'm trying to use an AsyncTask to download a file with a notification progress. Everything works fine (downloads in background thread), except whenever I add the code to update the progress bar through publishProgress(), it freezes the whole phone, until the download is finished and the notification shows "Download Completed".

I'm completely lost as to why this is the case, but I am maybe thinking it's along the lines of the publishProgress((downloadedSize / totalSize) * 100) that i'm using?

Anyways here is the DownloadDataTask:

    protected String doInBackground(RomDataSet... params) {
        try {

            // Download file here, all good

            //now, read through the input buffer and write the contents to the file
            while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
                //add the data in the buffer to the file in the file output stream (the file on the sd card
                fileOutput.write(buffer, 0, bufferLength);
                //add up the size so we know how much is downloaded
                downloadedSize += bufferLength;
                //this is where you would do something to report the prgress, like this maybe

                publishProgress((downloadedSize / totalSize) * 100);
            }
            //close the output stream when done
            fileOutput.close();

        //catch some possible errors...
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPreExecute() {
        Intent intent = new Intent(ListActivity.this, ListActivity.class);
        pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, 0);

        // configure the notification
        notification = new Notification(R.drawable.ic_stat_rom, "Downloading Rom via RomGet", System
                .currentTimeMillis());
        notification.flags = notification.flags | Notification.FLAG_ONGOING_EVENT;
        notification.contentView = new RemoteViews(getApplicationContext().getPackageName(), R.layout.layout_download);
        notification.contentIntent = pendingIntent;
        notification.contentView.setImageViewResource(R.id.status_icon, R.drawable.icon_rom);
        notification.contentView.setTextViewText(R.id.download_description, "Downloading");
        notification.contentView.setProgressBar(R.id.download_progress, 100, 0, false);

        getApplicationContext();
        notificationManager = (NotificationManager) getApplicationContext().getSystemService(
                Context.NOTIFICATION_SERVICE);

        notificationManager.notify(43, notification);
    }

    @Override
    protected void onProgressUpdate(Integer... progress) {
        //notification.contentView.setProgressBar(R.id.download_progress, 100, Math.round(progress[0]), false);
        notification.contentView.setTextViewText(R.id.download_description, Integer.toString(progress[0]));
        // inform the progress bar of updates in progress
        notificationManager.notify(43, notification);
    }

    @Override
    protected void onPostExecute(String result) {
        notification.contentView.setProgressBar(R.id.download_progress, 100, 100, false);
        notification.contentView.setTextViewText(R.id.download_description, "Done");
        notificationManager.notify(43, notification);
    }

I'm really stuck on this one - Any help would be appreciated. Cheers

    @Override
    protected void onProgressUpdate(Integer... progress) {
        if ((progress[0] - lastSize) > 5000) {
            lastSize = progress[0];
            notification.contentView.setProgressBar(R.id.download_progress, totalSize, progress[0], false);
            //notification.contentView.setTextViewText(R.id.download_description, Integer.toString(progress[0]));
            // inform the progress bar of updates in progress
            notificationManager.notify(43, notification);
        }
    }

Body:
Use a mod operator to only update on 5, 10 or 20 %.  You're calling onProgressUpdate() constantly during the download.

if (downloadedSize % (totalSize / 20) == 0) { // 20 updates every 5%, 10 every 10% and 5 every 20%, etc.
    publishProgress((downloadedSize / totalSize) * 100);
}


问:
how to turn a for loop with if statement working on datetime df into a list comprehension
I am trying to  turn the below for loop with if statement into a list comprehension.

```<code># Create dictionary to hold results
    trip_counts = {'AM': 0, 'PM': 0}

# Loop over all trips
for trip in onebike_datetimes:
  # Check to see if the trip starts before noon
  if trip['start'].hour < 12:
    # Increment the counter for before noon
    trip_counts["AM"] += 1
  else:
    # Increment the counter for after noon
    trip_counts["PM"] += 1
</code>```

I tried

```<code>[trip_counts["AM"]+=1 if trip['start'].hour <12 else trip_counts['PM']+= 1 for trip in onebike_datetimes]
</code>```

but I keep getting a syntaxerror

答:
If this is a pandas DataFrame you're working with, why not filter values and sum them all at once?

Something like this might work:

```<code>trip_counts['AM'] = len(trip[trip.loc[:, 'hour'] < 12].index)
trip_counts['PM'] = len(trip[trip.loc[:, 'hour'] >= 12].index)
</code>```

EDIT: I just ran some benchmarks on the answers given here, given that some people think that list comprehensions are automatically faster.

As you can see, the regular for-loop more or less has the best performance in this case, matched only by the use of Counter with a list comprehension as mentioned in one of the other answers here.

Note that I modified my Pandas implementation slightly to match how I believe your data might be structured, (i.e., not in a DataFrame), and thus there may a little more overhead to convert your data to a DataFrame on each run.

The code to produce this plot is shown below:

```<code>import pandas as pd
import numpy as np
from collections import Counter
from types import SimpleNamespace

import perfplot

def gen_data(n):
    onebike_datetimes = [
    {'start': SimpleNamespace(hour=9)},
    {'start': SimpleNamespace(hour=3)},
    {'start': SimpleNamespace(hour=14)},
    {'start': SimpleNamespace(hour=19)},
    {'start': SimpleNamespace(hour=7)},
    {'start': SimpleNamespace(hour=14)},
    {'start': SimpleNamespace(hour=19)},
    {'start': SimpleNamespace(hour=2)},
    {'start': SimpleNamespace(hour=20)},
    {'start': SimpleNamespace(hour=12)},
    ]*n

    return onebike_datetimes

def use_vanilla_for(a):
#     onebike_datetimes = gen_data(n)
    onebike_datetimes = a

    trip_counts = {'AM': 0, 'PM': 0}

    for trip in onebike_datetimes:
        if trip['start'].hour < 12:
            trip_counts["AM"] += 1
        else:
            trip_counts["PM"] += 1
    return 1
#     return trip_counts

def use_list_comp(a):
#     onebike_datetimes = gen_data(n)
    onebike_datetimes = a

    trip_counts = {'AM': 0, 'PM': 0}

    l = ["AM" if trip["start"].hour < 12 else "PM" for trip in onebike_datetimes]
    trip_counts = {i: l.count(i) for i in l}
    return 1
#     return trip_counts

def use_counter(a):
#     onebike_datetimes = gen_data(n)
    onebike_datetimes = a

    trip_counts = {'AM': 0, 'PM': 0}

    trip_counts = Counter(("AM" if trip['start'].hour < 12 else "PM")
                       for trip in onebike_datetimes)
    return 1
#     return trip_counts

def use_pandas(a):
#     onebike_datetimes = gen_data(n)
    onebike_datetimes = a

    trip = pd.DataFrame(list(map(lambda a: a['start'].hour, onebike_datetimes)), columns=['hrs'])

    trip_counts = {'AM': 0, 'PM': 0}

    trip_counts['AM'] = len(trip[trip['hrs'] < 12].index)
    trip_counts['PM'] = len(trip[trip['hrs'] >= 12].index)
    return 1
#     return trip_counts

perfplot.show(
    setup=lambda n: gen_data(n),
    kernels=[
        lambda a: use_vanilla_for(a),
        lambda a: use_list_comp(a),
        lambda a: use_counter(a),
        lambda a: use_pandas(a),
    ],
    labels=["vanilla_for", "list_comp", "counter", "dataframe"],
    n_range=[2 ** k for k in range(10)],
    xlabel="len(a)",
)
</code>```

Body:
I am trying to  turn the below for loop with if statement into a list comprehension.

# Create dictionary to hold results
    trip_counts = {'AM': 0, 'PM': 0}

# Loop over all trips
for trip in onebike_datetimes:
  # Check to see if the trip starts before noon
  if trip['start'].hour < 12:
    # Increment the counter for before noon
    trip_counts["AM"] += 1
  else:
    # Increment the counter for after noon
    trip_counts["PM"] += 1

I tried

[trip_counts["AM"]+=1 if trip['start'].hour <12 else trip_counts['PM']+= 1 for trip in onebike_datetimes]

but I keep getting a syntaxerror

Body:
If this is a pandas DataFrame you're working with, why not filter values and sum them all at once?

Something like this might work:

trip_counts['AM'] = len(trip[trip.loc[:, 'hour'] < 12].index)
trip_counts['PM'] = len(trip[trip.loc[:, 'hour'] >= 12].index)

EDIT: I just ran some benchmarks on the answers given here, given that some people think that list comprehensions are automatically faster.

As you can see, the regular for-loop more or less has the best performance in this case, matched only by the use of Counter with a list comprehension as mentioned in one of the other answers here.

Note that I modified my Pandas implementation slightly to match how I believe your data might be structured, (i.e., not in a DataFrame), and thus there may a little more overhead to convert your data to a DataFrame on each run.

The code to produce this plot is shown below:

import pandas as pd
import numpy as np
from collections import Counter
from types import SimpleNamespace

import perfplot

def gen_data(n):
    onebike_datetimes = [
    {'start': SimpleNamespace(hour=9)},
    {'start': SimpleNamespace(hour=3)},
    {'start': SimpleNamespace(hour=14)},
    {'start': SimpleNamespace(hour=19)},
    {'start': SimpleNamespace(hour=7)},
    {'start': SimpleNamespace(hour=14)},
    {'start': SimpleNamespace(hour=19)},
    {'start': SimpleNamespace(hour=2)},
    {'start': SimpleNamespace(hour=20)},
    {'start': SimpleNamespace(hour=12)},
    ]*n

    return onebike_datetimes

def use_vanilla_for(a):
#     onebike_datetimes = gen_data(n)
    onebike_datetimes = a

    trip_counts = {'AM': 0, 'PM': 0}

    for trip in onebike_datetimes:
        if trip['start'].hour < 12:
            trip_counts["AM"] += 1
        else:
            trip_counts["PM"] += 1
    return 1
#     return trip_counts

def use_list_comp(a):
#     onebike_datetimes = gen_data(n)
    onebike_datetimes = a

    trip_counts = {'AM': 0, 'PM': 0}

    l = ["AM" if trip["start"].hour < 12 else "PM" for trip in onebike_datetimes]
    trip_counts = {i: l.count(i) for i in l}
    return 1
#     return trip_counts

def use_counter(a):
#     onebike_datetimes = gen_data(n)
    onebike_datetimes = a

    trip_counts = {'AM': 0, 'PM': 0}

    trip_counts = Counter(("AM" if trip['start'].hour < 12 else "PM")
                       for trip in onebike_datetimes)
    return 1
#     return trip_counts

def use_pandas(a):
#     onebike_datetimes = gen_data(n)
    onebike_datetimes = a

    trip = pd.DataFrame(list(map(lambda a: a['start'].hour, onebike_datetimes)), columns=['hrs'])

    trip_counts = {'AM': 0, 'PM': 0}

    trip_counts['AM'] = len(trip[trip['hrs'] < 12].index)
    trip_counts['PM'] = len(trip[trip['hrs'] >= 12].index)
    return 1
#     return trip_counts

perfplot.show(
    setup=lambda n: gen_data(n),
    kernels=[
        lambda a: use_vanilla_for(a),
        lambda a: use_list_comp(a),
        lambda a: use_counter(a),
        lambda a: use_pandas(a),
    ],
    labels=["vanilla_for", "list_comp", "counter", "dataframe"],
    n_range=[2 ** k for k in range(10)],
    xlabel="len(a)",
)


问:
How to change content of VuePress page via Plugin
I am trying to set up a plugin to change the content of a VuePress markdown file on the dev server and production build.  According to documentation, I should be able to use the _content and _strippedContent that is available to me with the extendPageData

The following code is what I have set up in a plugin to do this.

module.exports = (options = {}, context) => ({
  extendPageData($page) {
    const {
      _filePath, // file's absolute path
      _computed, // access the client global computed mixins at build time, e.g _computed.$localePath.
      _content, // file's raw content string
      _strippedContent, // file's content string without frontmatter
      key, // page's unique hash key
      frontmatter, // page's frontmatter object
      regularPath, // current page's default link (follow the file hierarchy)
      path, // current page's real link (use regularPath when permalink does not exist)
    } = $page

    $page._content = "replaced"
    $page._strippedContent = "replaced"
  }
})```

The best I can tell is that this code should work as it updates the $page._content however it is not showing testing but rather the original content.

I know that I am getting into this code as I can console.log from the file and it shows in the console.

I fear that $page._content is immutable and wonder if there is a way to do this kind of content swapping during dev or build

答:
You can to modify your .vuepress/config.js. For example, if you want to replace '---my text---' with 'MY TEXT
' (with uppercase, for example) in all yours files markdown, you have to add the next code to .vuepress/config.js, into chainWebpack section where I use a regex expression:

```<code>// File: .vuepress/config.js
module.exports = {
...,
chainWebpack: config => {
    // Each loader in the chain applies transformations to the processed resource:
    config.module
      .rule('md')
      .test(/\.md$/)
      .use("string-replace-loader")
      .loader("string-replace-loader")
      .options({
        multiple: [{
            search: '---(.*?)---',
            replace: (match, p1, offset, string, groups) => `<div><p class="myclass">${p1.toUpperCase()}</p></div>`,
            flags: 'ig'
          },
          {
            search: ' ... ',
            replace: (match, p1, p2, ..., pn, offset, string) => ` ... `,
            flags: 'ig'
          }
        ],
      }, )
      .end()

  },
};
</code>```

Body:
I am trying to set up a plugin to change the content of a VuePress markdown file on the dev server and production build.  According to documentation, I should be able to use the _content and _strippedContent that is available to me with the extendPageData

The following code is what I have set up in a plugin to do this.

module.exports = (options = {}, context) => ({
  extendPageData($page) {
    const {
      _filePath, // file's absolute path
      _computed, // access the client global computed mixins at build time, e.g _computed.$localePath.
      _content, // file's raw content string
      _strippedContent, // file's content string without frontmatter
      key, // page's unique hash key
      frontmatter, // page's frontmatter object
      regularPath, // current page's default link (follow the file hierarchy)
      path, // current page's real link (use regularPath when permalink does not exist)
    } = $page

    $page._content = "replaced"
    $page._strippedContent = "replaced"
  }
})

The best I can tell is that this code should work as it updates the $page._content however it is not showing testing but rather the original content.

I know that I am getting into this code as I can console.log from the file and it shows in the console.

I fear that $page._content is immutable and wonder if there is a way to do this kind of content swapping during dev or build

Body:
You can to modify your .vuepress/config.js. For example, if you want to replace '---my text---' with 'MY TEXT
' (with uppercase, for example) in all yours files markdown, you have to add the next code to .vuepress/config.js, into chainWebpack section where I use a regex expression:

// File: .vuepress/config.js
module.exports = {
...,
chainWebpack: config => {
    // Each loader in the chain applies transformations to the processed resource:
    config.module
      .rule('md')
      .test(/\.md$/)
      .use("string-replace-loader")
      .loader("string-replace-loader")
      .options({
        multiple: [{
            search: '---(.*?)---',
            replace: (match, p1, offset, string, groups) => `<div><p class="myclass">${p1.toUpperCase()}</p></div>`,
            flags: 'ig'
          },
          {
            search: ' ... ',
            replace: (match, p1, p2, ..., pn, offset, string) => ` ... `,
            flags: 'ig'
          }
        ],
      }, )
      .end()

  },
};


问:
Syntax when pattern matching with tuples (Elixir)
I'm following a tutorial and there's a basic syntax issue that I'm not sure about.

Sometimes when we are pattern matching (in say function arguments), we use = and match the left to the right.

However, at times I see -> being used instead of =. For example this code:

receive do {:result, filename} -> filename do

I'm assuming this is wrong:

receive do {:result, filename} = filename do

Does this have to do with an anonymous function? Or maybe a special syntax for tuples(which are basically maps?).

答:
This is how I think about it. You can use pattern matching to "deconstruct" data as in:

```<code> [x|xs] = mylist
</code>```

You are getting an object and peeking at its structure, so you get access to its components. That's where the = is used.

For receive and case _ do, you are looking at "making decisions" or "control flow" based on the structure of the data you are manipulating. In your receive example, you are planning to return the filename, if the message received is "ok".

Body:
This is how I think about it. You can use pattern matching to "deconstruct" data as in:

 [x|xs] = mylist

You are getting an object and peeking at its structure, so you get access to its components. That's where the = is used.

For receive and case _ do, you are looking at "making decisions" or "control flow" based on the structure of the data you are manipulating. In your receive example, you are planning to return the filename, if the message received is "ok".


问:
Data files with html content
I'm making a nice simple html page using external data... here's the bit that's causing me grief:

{% for section in faq.sections %}

{{ section.heading }}

    {% for question in section.questions %}

            + {{ question.question }}
            - {{ question.question }}

                {{ question.answer }}

    {% endfor %}

{% endfor %}

```

<p>... and the matching <code>faq.json</code> file:</p>

```{
    "sections" : [
      { "heading" : "Section the first",
        "code" : "gn",
        "questions" : [
                {
                    "question": "What do questions need?",
                    "code" : "1",
                    "answer": "An answer"
                },
                {
                    "question": "Is this also a question?",
                    "code" : "2",
                    "answer": "Yes, it is"
                },
                {
                    "question": "Is this junk data?",
                    "code" : "a",
                    "answer": "Yes"
                },
            ]
        },
        {
            "heading": "Another section",
            "code" : "f",
            "questions": [
                {
                    "question": "Can I have html in my answer?",
                    "code" : "2",
                    "answer": "
\n
First, json needs newlines escaped to be newlines
\\n
Eleventy seems to 'sanitize' the string
\\n
"
                },
                {
                    "question": "question b",
                    "code" : "b",
                    "answer": "answer b"
                },
                {
                    "question": "question c",
                    "code" : "or",
                    "answer": "answer c"
                },
            ]
        }
    ]
}
```

<p>.... and the rendered text for the answer in question is:</p>

```

First, json needs newlines escaped to be newlines
\n
Eleventy seems to 'sanitize' the string

```

Do I have any options here? Is there a way to allow [even a subset of] html elements into the page?

(and yes, the CSS does the clever show/hide descriptions using the '+'/'-' symbols - all that side of things works just lovely)

答:
It should work by inserting the symbols directly into the quotes in the json. Use Non-breaking spaces for indentation, and unicode points for dots.
Otherwise, the framework is broken.</p>

Title: Data files with html content

Body:
I'm making a nice simple html page using external data... here's the bit that's causing me grief:

{% for section in faq.sections %}

{{ section.heading }}

    {% for question in section.questions %}

            + {{ question.question }}
            - {{ question.question }}

                {{ question.answer }}

    {% endfor %}

{% endfor %}

... and the matching faq.json file:

{
    "sections" : [
      { "heading" : "Section the first",
        "code" : "gn",
        "questions" : [
                {
                    "question": "What do questions need?",
                    "code" : "1",
                    "answer": "An answer"
                },
                {
                    "question": "Is this also a question?",
                    "code" : "2",
                    "answer": "Yes, it is"
                },
                {
                    "question": "Is this junk data?",
                    "code" : "a",
                    "answer": "Yes"
                },
            ]
        },
        {
            "heading": "Another section",
            "code" : "f",
            "questions": [
                {
                    "question": "Can I have html in my answer?",
                    "code" : "2",
                    "answer": "
\n
First, json needs newlines escaped to be newlines
\\n
Eleventy seems to 'sanitize' the string
\\n
"
                },
                {
                    "question": "question b",
                    "code" : "b",
                    "answer": "answer b"
                },
                {
                    "question": "question c",
                    "code" : "or",
                    "answer": "answer c"
                },
            ]
        }
    ]
}

.... and the rendered text for the answer in question is:

First, json needs newlines escaped to be newlines
\n
Eleventy seems to 'sanitize' the string

Do I have any options here? Is there a way to allow [even a subset of] html elements into the page?

(and yes, the CSS does the clever show/hide descriptions using the '+'/'-' symbols - all that side of things works just lovely)


问:
LARAVEL 7 - How to pass variables to views
I have two tables, Companies and Projects. A company hasMany projects and a project belongsTo a company.

Company.php model

```<code>protected $fillable = [
    'id', 'name', 'description'
];

public function projects()
{
    return $this->hasMany('App/Project');
}
</code>```

Project.php model

```<code>protected $fillable = [
    'name', 'description', 'company_id', 'days'
];

public function company()
{
    return $this->belongsTo('App/Company');
}
</code>```

From my index.blade.php, I list the companies only and I have made them clickable so that when a user clicks on a company listed, they are taken to show.blade.php where the name of the company and the projects that belong to that company are displayed like so.

```<code><div class="jumbotron">
     <h1>{{ $company->name }}</h1>
       <p class="lead">{{ $company->description }}</p>
    </div>

<div class="row">
    @foreach($company->projects as $project)
    <div class="col-lg-4">
        <h2>{{ $project->name }}</h2>
        <p class="text-danger">{{ $project->description }}</p>
        <p><a class="btn btn-primary" href="/projects/{{ $project->id }}" role="button">View Projects »</a></p>
    </div>
    @endforeach
</div>
</code>```

Now am getting an undefined variable $project error. So I decided to declare variable in my show() function of the CompaniesController.php like so

```<code>public function show(Company $company)
{
    $company = Company::find($company->id);
    $projects = Company::find(1)->projects;

    return view('companies.show', ['company' => $company, 'projects' => $projects]);
}
</code>```

And access variable in show.blade.php like so

```<code>    <div class="jumbotron">

    <h1>{{ $company->name }}</h1>
    <p class="lead">{{ $company->description }}</p>
</div>
<div class="row">

    @foreach($projects as $project)
    <div class="col-lg-4">
        <h2>{{ $project->name }}</h2>
        <p class="text-danger">{{ $project->description }}</p>
        <p><a class="btn btn-primary" href="/projects/{{ $project->id }}" role="button">View Projects »</a></p>
    </div>
    @endforeach
</div>
</code>```

Now am getting a Class 'App/Project' not found error when I access show.blade.php. I am having a challenge passing company projects to the view. Any help will be appreciated. Here are my routes;

```<code>    Route::get('/', function () {
    return view('welcome');
});

Auth::routes();

Route::get('/home', 'HomeController@index')->name('home');
Route::resource('companies', 'CompaniesController');
Route::resource('projects', 'ProjectsController');
</code>```

答:
I would be hilarious if I am right....

In your models where defining relations replace App/Project with App\Project. Do the same for Company.... Replace "/" with "\".

Body:
I have two tables, Companies and Projects. A company hasMany projects and a project belongsTo a company.

Company.php model

protected $fillable = [
    'id', 'name', 'description'
];

public function projects()
{
    return $this->hasMany('App/Project');
}

Project.php model

protected $fillable = [
    'name', 'description', 'company_id', 'days'
];

public function company()
{
    return $this->belongsTo('App/Company');
}

From my index.blade.php, I list the companies only and I have made them clickable so that when a user clicks on a company listed, they are taken to show.blade.php where the name of the company and the projects that belong to that company are displayed like so.

{{ $company->name }}

{{ $company->description }}

    @foreach($company->projects as $project)

{{ $project->name }}

{{ $project->description }}

id }}" role="button">View Projects »

    @endforeach

Now am getting an undefined variable $project error. So I decided to declare variable in my show() function of the CompaniesController.php like so

public function show(Company $company)
{
    $company = Company::find($company->id);
    $projects = Company::find(1)->projects;

    return view('companies.show', ['company' => $company, 'projects' => $projects]);
}

And access variable in show.blade.php like so

{{ $company->name }}

{{ $company->description }}

    @foreach($projects as $project)

{{ $project->name }}

{{ $project->description }}

id }}" role="button">View Projects »

    @endforeach

Now am getting a Class 'App/Project' not found error when I access show.blade.php. I am having a challenge passing company projects to the view. Any help will be appreciated. Here are my routes;

    Route::get('/', function () {
    return view('welcome');
});

Auth::routes();

Route::get('/home', 'HomeController@index')->name('home');
Route::resource('companies', 'CompaniesController');
Route::resource('projects', 'ProjectsController');


问:
How to create a file with content and download it with THYMELEAF
I'm working on a spring boot project with thymeleaf and I need to create a file and put some lines on it then send it for the user to download it.

@PostMapping("/filegenerator")
public String createFile(@ModelAttribute("page") Page page, Model model) {
    List<String> lines = new ArrayList<String>();

    //Some code ..........

    lines.forEach(l->{
        System.out.println(l);
    });

    //Here I need to create a file with the List of lines

    //And also put some code to download it

    return "filegenerator";
}
```

答:
So if you want to return a file, you probably want to stream it to limit the amount of memory used (or at least that was probably the reasoning of Spring Framework creators). In your case I understand that the file is fairly small and doesn't really have to be persisted anywhere. It's just a one time download based on the uploaded form, right?

so this approach worked on my PC:

@PostMapping("/filegenerator")
public void createFile(HttpServletResponse response) throws IOException {
    List<String> lines = Arrays.asList("line1", "line2");
    InputStream is = new ByteArrayInputStream(lines.stream().collect(Collectors.joining("\n")).getBytes());
    IOUtils.copy(is, response.getOutputStream());
    response.setContentType("application/sql");
    response.setHeader("Content-Disposition", "attachment; filename=\"myquery.sql\"");
    response.flushBuffer();
}
```

note the content-disposition header. It explicitly states that you don't want to display the file in the browser, but instead you want it to be downloaded as a file and myquery.sql is the name of that file that will be downloaded.

Body:
So if you want to return a file, you probably want to stream it to limit the amount of memory used (or at least that was probably the reasoning of Spring Framework creators). In your case I understand that the file is fairly small and doesn't really have to be persisted anywhere. It's just a one time download based on the uploaded form, right?

so this approach worked on my PC:

@PostMapping("/filegenerator")
public void createFile(HttpServletResponse response) throws IOException {
    List<String> lines = Arrays.asList("line1", "line2");
    InputStream is = new ByteArrayInputStream(lines.stream().collect(Collectors.joining("\n")).getBytes());
    IOUtils.copy(is, response.getOutputStream());
    response.setContentType("application/sql");
    response.setHeader("Content-Disposition", "attachment; filename=\"myquery.sql\"");
    response.flushBuffer();
}

note the content-disposition header. It explicitly states that you don't want to display the file in the browser, but instead you want it to be downloaded as a file and myquery.sql is the name of that file that will be downloaded.


问:
What is the difference in accessing Cloudflare website using ChromeDriver/Chrome in normal/headless mode through Selenium Python
I have a question about --headless mode in Python Selenium for Chrome.

Code

```<code> from selenium import webdriver
 from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

 CHROME_DRIVER_DIR = "selenium/chromedriver"

 chrome_options = webdriver.ChromeOptions()
 caps = DesiredCapabilities().CHROME
 chrome_options.add_argument("--disable-dev-shm-usage")
 chrome_options.add_argument("--remote-debugging-port=9222")
 chrome_options.add_argument("--headless")  # Runs Chrome in headless mode.
 chrome_options.add_argument('--no-sandbox')  # # Bypass OS security model
 chrome_options.add_argument("--disable-extensions")
 chrome_options.add_argument("--disable-gpu")

 browser = webdriver.Chrome(desired_capabilities=caps, executable_path=CHROME_DRIVER_DIR, options=chrome_options)

 browser.get("https://www.manta.com/c/mm2956g/mashuda-contractors")
 print(browser.page_source)
 browser.quit()
</code>```

When I'm remove chrome_options.add_argument("--headless") all working good, but with this --headless* got next issue

```<code>Please enable cookies.

Error 1020 Ray ID: 53fd62b4087d8116 • 2019-12-04 11:19:28 UTC

Access denied

What happened?
This website is using a security service to protect itself from online attacks.

Cloudflare Ray ID: 53fd62b4087d8116 • Your IP: 168.81.117.111 • Performance & security by Cloudflare
</code>```

What is the difference for normal mode and --headless?

答:
I tested using this server-side script:

<?php
echo "```<code>";
var_dump($_SERVER);
echo "</code>```";
?>

```

<p>I loaded this page using ChromeDriver, with and without using <code>--headless</code>, and printed the output using <code>print(driver.find_element_by_tag_name('code').text)</code>. I then diff-ed both outputs.<br>
Here's the differences I found:</p>

<ul>
<li>HTTP <code>Accept-Language</code> header: <code>en-US,en;q=0.9</code> vs <code>en-US</code></li>
<li>HTTP <code>User-Agent</code> header: <code>Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36</code> vs <code>Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/83.0.4103.61 Safari/537.36</code> (Note the <code>HeadlessChrome</code> mention in the second string.)</li>
<li>Javascript <code>window.navigator.plugins</code>: <code>{"0":{"0":{}},"1":{"0":{}},"2":{"0":{},"1":{}}}</code> vs <code>{}</code></li>
<li>Javascript <code>window.navigator.mimeTypes</code>: <code>{"0":{},"1":{},"2":{},"3":{}}</code> vs <code>{}</code></li>
<li>Javascript <code>window.outerWidth</code>: <code>1367</code> vs <code>0</code></li>
<li>Javascript <code>window.outerHeight</code>: <code>641</code> vs <code>0</code></li>
</ul>

<p>Of note: in the Python script you posted, you are missing a few lines, to remove the <code>window.webdriver</code> property (without this, it is trivial for the server to detect you are using WebDriver) [ref]:</p>

```driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
    "source": """
    Object.defineProperty(navigator, 'webdriver', {
      get: () => undefined
    })
  """
})
```

Body:
I have a question about --headless mode in Python Selenium for Chrome.

Code

 from selenium import webdriver
 from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

 CHROME_DRIVER_DIR = "selenium/chromedriver"

 chrome_options = webdriver.ChromeOptions()
 caps = DesiredCapabilities().CHROME
 chrome_options.add_argument("--disable-dev-shm-usage")
 chrome_options.add_argument("--remote-debugging-port=9222")
 chrome_options.add_argument("--headless")  # Runs Chrome in headless mode.
 chrome_options.add_argument('--no-sandbox')  # # Bypass OS security model
 chrome_options.add_argument("--disable-extensions")
 chrome_options.add_argument("--disable-gpu")

 browser = webdriver.Chrome(desired_capabilities=caps, executable_path=CHROME_DRIVER_DIR, options=chrome_options)

 browser.get("https://www.manta.com/c/mm2956g/mashuda-contractors")
 print(browser.page_source)
 browser.quit()

When I'm remove chrome_options.add_argument("--headless") all working good, but with this --headless* got next issue

Please enable cookies.

Error 1020 Ray ID: 53fd62b4087d8116 • 2019-12-04 11:19:28 UTC

Access denied

What happened?
This website is using a security service to protect itself from online attacks.

Cloudflare Ray ID: 53fd62b4087d8116 • Your IP: 168.81.117.111 • Performance & security by Cloudflare

What is the difference for normal mode and --headless?

Body:
I tested using this server-side script:

<?php
echo "<pre><code>";
var_dump($_SERVER);
echo "</code></pre>";
?>
<script>
    var el = document.getElementsByTagName('code')[0];
    for(var prop in window.navigator){
        var str = JSON.stringify(window.navigator[prop])
        el.innerHTML = el.innerHTML + "window.navigator." + prop + " = " + str + "\n";
    }
    var skip_props = ['parent', 'top', 'frames', 'self', 'window'];
    for(var prop in window){
        if (skip_props.indexOf(prop) > -1) { continue; }
        el.innerHTML = el.innerHTML + "window." + prop + " = ";
        var str = JSON.stringify(window[prop])
        el.innerHTML = el.innerHTML + str + "\n";
    }
</script>

I loaded this page using ChromeDriver, with and without using --headless, and printed the output using print(driver.find_element_by_tag_name('code').text). I then diff-ed both outputs.

Here's the differences I found:

HTTP Accept-Language header: en-US,en;q=0.9 vs en-US

HTTP User-Agent header: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36 vs Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/83.0.4103.61 Safari/537.36 (Note the HeadlessChrome mention in the second string.)

Javascript window.navigator.plugins: {"0":{"0":{}},"1":{"0":{}},"2":{"0":{},"1":{}}} vs {}

Javascript window.navigator.mimeTypes: {"0":{},"1":{},"2":{},"3":{}} vs {}

Javascript window.outerWidth: 1367 vs 0

Javascript window.outerHeight: 641 vs 0

Of note: in the Python script you posted, you are missing a few lines, to remove the window.webdriver property (without this, it is trivial for the server to detect you are using WebDriver) [ref]:

driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
    "source": """
    Object.defineProperty(navigator, 'webdriver', {
      get: () => undefined
    })
  """
})


问:
Typescript enumeration instance type
This must be something extremelly simple but couldn't find the words to search here on stackoverflow.

Basically I would like to be able to typehint a variable being of an enumeration type. Something like this:

```<code>enum RecurringEventDeleteOptions {
  THIS_EVENT = 1,
  THIS_AND_FUTURE_EVENTS = 2,
  ALL_EVENTS = 3,
}

const foo: RecurringEventDeleteOptions = RecurringEventDeleteOptions;
</code>```

I get an error from the variable foo (Type 'typeof RecurringEventDeleteOptions' is not assignable to type 'RecurringEventDeleteOptions')

Is there a way to tell that foo will be of type RecurringEventDeleteOptions?

playground

Why? Because I have a VueJS template that will have to access these options. An example:

```<code><template>
  <div> {{ foo.THIS_EVENT }} </div>
</template>

<script lang="ts">

@Component
export default class FooClass extends Vue {
  public foo = RecurringEventDeleteOptions;
}
</script>
</code>```

答:
If you really want to store the type of the enumeration, and not a value of it, you simply have to add typeof:

const a: typeof RecurringEventDeleteOptions = RecurringEventDeleteOptions;
```

Title: Typescript enumeration instance type

Body:
This must be something extremelly simple but couldn't find the words to search here on stackoverflow.

Basically I would like to be able to typehint a variable being of an enumeration type. Something like this:

enum RecurringEventDeleteOptions {
  THIS_EVENT = 1,
  THIS_AND_FUTURE_EVENTS = 2,
  ALL_EVENTS = 3,
}

const foo: RecurringEventDeleteOptions = RecurringEventDeleteOptions;

I get an error from the variable foo (Type 'typeof RecurringEventDeleteOptions' is not assignable to type 'RecurringEventDeleteOptions')

Is there a way to tell that foo will be of type RecurringEventDeleteOptions?

playground

Why? Because I have a VueJS template that will have to access these options. An example:

<template>

 {{ foo.THIS_EVENT }}

</template>


问:
Confusion Matrix only considering predictions > threshold
The output layer of my network is

```<code>model.add(Dense(2, activation=activations.softmax))
</code>```

outputting a one hot encoded category prediction.

model.predict therefore returns n predictions like

```<code>[9.9584144e-01, 4.1585001e-03],
[7.5779420e-01, 2.4220583e-01],
...
</code>```

I now not only want the full confusion matrix provided by sklearn through

```<code>metrics.confusion_matrix(y_TEST.argmax(axis=1), y_pred.argmax(axis=1), normalize='pred')
</code>```

but I'd like to see how the confusion matrix looks only for the cases where the max prediction is larger than a given threshold.

Something like

```<code>metrics.confusion_matrix(y_TEST.argmax(axis=1), y_pred.argmax(axis=1), normalize='pred',
                         min_confidence_threshold='0.9')
</code>```

Does sklearn or any of the standard tools here provide a functionality like that?

If not, how would I filter two arrays (y_TEST, y_pred) based on a condition of one of the arrays?

答:
Here's a function that can do this:

def threshold_matrix(labels,probs,threshold=0):
    assert 0 <= threshold <= 1
    t_map = lambda x : 1 if tf.math.reduce_max(x) > threshold else 0
    thres = tf.map_fn(t_map, probs)

    pred  = tf.boolean_mask(tf.argmax(probs,1),thres)
    labs  = tf.boolean_mask(tf.cast(labels, tf.int64),thres)

    return tf.math.confusion_matrix(labs,pred)
```

Body:
The output layer of my network is

model.add(Dense(2, activation=activations.softmax))

outputting a one hot encoded category prediction.

model.predict therefore returns n predictions like

[9.9584144e-01, 4.1585001e-03],
[7.5779420e-01, 2.4220583e-01],
...

I now not only want the full confusion matrix provided by sklearn through

metrics.confusion_matrix(y_TEST.argmax(axis=1), y_pred.argmax(axis=1), normalize='pred')

but I'd like to see how the confusion matrix looks only for the cases where the max prediction is larger than a given threshold.

Something like

metrics.confusion_matrix(y_TEST.argmax(axis=1), y_pred.argmax(axis=1), normalize='pred',
                         min_confidence_threshold='0.9')

Does sklearn or any of the standard tools here provide a functionality like that?

If not, how would I filter two arrays (y_TEST, y_pred) based on a condition of one of the arrays?


问:
Flutter app crashing while using flutter_pdfview package
Package : flutter_pdfview

My app crashes when the pdf downloading is completed in apk I build using flutter apk build.

At the same operation in debugging after downloading is finished console gives an error but does not crashes and pdf_viewer works fine.

```<code> W/System  (31159): A resource failed to call release.
</code>```

Please suggest what i can do to stop my app to crash after downloading the file.

Code is like this

```<code>import 'dart:async';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/material.dart';
import 'package:flutter_pdfview/flutter_pdfview.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'dart:io';
import 'package:path_provider/path_provider.dart';

class PdfViewerPage extends StatefulWidget {
  final name;
  final title;
  PdfViewerPage({this.name, this.title});
  @override
  _PdfViewerPageState createState() => _PdfViewerPageState();
}

class _PdfViewerPageState extends State<PdfViewerPage> {
  bool loading = true;
  String localfile;
  int current = 1;
  int total;

  Future<String> loaddata() async {
    var dir = await getTemporaryDirectory();
    File file = new File(dir.path + widget.name);

    await FirebaseStorage()
        .ref()
        .child(widget.name)
        .getData(50000000)
        .then((value) async {
      file.writeAsBytes(value);
    }).catchError((onError) {
      Fluttertoast.showToast(msg: onError);
    });
    return file.path;
  }

  @override
  void initState() {
    super.initState();
    loaddata().then((value) {
      setState(() {
        localfile = value;
        loading = false;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
        child: Scaffold(
      appBar: AppBar(
        title: Text(widget.title, style: TextStyle(color: Colors.black)),
      ),
      body: loading
          ? Center(
              child: CircularProgressIndicator(),
            )
          : PDFView(
              filePath: localfile,
              fitEachPage: true,
              onPageChanged: (t, c) {
                setState(() {
                  current = t + 1;
                  total = c;
                });
              },
            ),
      floatingActionButton: total != null
          ? FloatingActionButton.extended(
              backgroundColor: Colors.white,
              onPressed: () {},
              label: Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: <Widget>[
                  Text(current.toString()),
                  SizedBox(
                    width: 20,
                  ),
                  Text(total.toString())
                ],
              ))
          : Container(),
    ));
  }
}

</code>```

答:
I found a similar Question on StackOverflow link.

When we build apk from the code, Flutter blocks the plugin code which results in crashing of the app.
Solution is to use progaurd rules to enable the pdf plugin to work. ProGaurd rules are mentioned in the link.

Body:
Package : flutter_pdfview

My app crashes when the pdf downloading is completed in apk I build using flutter apk build.

At the same operation in debugging after downloading is finished console gives an error but does not crashes and pdf_viewer works fine.

 W/System  (31159): A resource failed to call release.

Please suggest what i can do to stop my app to crash after downloading the file.

Code is like this

import 'dart:async';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/material.dart';
import 'package:flutter_pdfview/flutter_pdfview.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'dart:io';
import 'package:path_provider/path_provider.dart';

class PdfViewerPage extends StatefulWidget {
  final name;
  final title;
  PdfViewerPage({this.name, this.title});
  @override
  _PdfViewerPageState createState() => _PdfViewerPageState();
}

class _PdfViewerPageState extends State<PdfViewerPage> {
  bool loading = true;
  String localfile;
  int current = 1;
  int total;

  Future<String> loaddata() async {
    var dir = await getTemporaryDirectory();
    File file = new File(dir.path + widget.name);

    await FirebaseStorage()
        .ref()
        .child(widget.name)
        .getData(50000000)
        .then((value) async {
      file.writeAsBytes(value);
    }).catchError((onError) {
      Fluttertoast.showToast(msg: onError);
    });
    return file.path;
  }

  @override
  void initState() {
    super.initState();
    loaddata().then((value) {
      setState(() {
        localfile = value;
        loading = false;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
        child: Scaffold(
      appBar: AppBar(
        title: Text(widget.title, style: TextStyle(color: Colors.black)),
      ),
      body: loading
          ? Center(
              child: CircularProgressIndicator(),
            )
          : PDFView(
              filePath: localfile,
              fitEachPage: true,
              onPageChanged: (t, c) {
                setState(() {
                  current = t + 1;
                  total = c;
                });
              },
            ),
      floatingActionButton: total != null
          ? FloatingActionButton.extended(
              backgroundColor: Colors.white,
              onPressed: () {},
              label: Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: <Widget>[
                  Text(current.toString()),
                  SizedBox(
                    width: 20,
                  ),
                  Text(total.toString())
                ],
              ))
          : Container(),
    ));
  }
}


问:
React TypeError: this.state.List.map is not a function

import React, { Component } from "react";
import Project from "./components/Project.js"
import Form from "./Form.js";

class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
            projectList: [],
            myProjects: [],
            userList: [],
        };

        this.createProject = this.createProject.bind(this);
    }

    createProject(title, desc, langs, len, exp) {
        this.setState({
            projectList: this.state.projectList.push(
                {
                    title : title,
                    description : desc,
                    language : langs,
                    length : len,
                    experience : exp
                }
            )
        });
    }

    deleteProject(title) {
        const projects = this.state.projectList.filter(
            p => p.title !== title
        );
        this.setState({projects});
    }

    render() {
        return(

                <Form createProject = {this.createProject} />
                {this.state.projectList.map((params) =>
                <Project {...params}/>)}

        );
    }

}

export default App;```

Hello, when running this, createProject gets passed as a prop to another class, which calls createProject with certain parameters. However, upon trying to render, it returns this error. TypeError: this.state.projectList.map is not a function. Any advice on how to fix it?

答:
```<code>    Hi Adam,

    For the current problem below snippet would solve this issue

    this.setState({
                projectList: [...this.state.projectList,
                    {
                        title : title,
                        description : desc,
                        language : langs,
                        length : len,
                        experience : exp
                    }
                ]
            });

For better understanding refer below link:
    https://www.robinwieruch.de/react-state-array-add-update-remove
</code>```

Body:
import React, { Component } from "react";
import Project from "./components/Project.js"
import Form from "./Form.js";

class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
            projectList: [],
            myProjects: [],
            userList: [],
        };

        this.createProject = this.createProject.bind(this);
    }

    createProject(title, desc, langs, len, exp) {
        this.setState({
            projectList: this.state.projectList.push(
                {
                    title : title,
                    description : desc,
                    language : langs,
                    length : len,
                    experience : exp
                }
            )
        });
    }

    deleteProject(title) {
        const projects = this.state.projectList.filter(
            p => p.title !== title
        );
        this.setState({projects});
    }

    render() {
        return(

                <Form createProject = {this.createProject} />
                {this.state.projectList.map((params) =>
                <Project {...params}/>)}

        );
    }

}

export default App;

Hello, when running this, createProject gets passed as a prop to another class, which calls createProject with certain parameters. However, upon trying to render, it returns this error. TypeError: this.state.projectList.map is not a function. Any advice on how to fix it?


问:
java.io.EOFException in java eclipse
```<code>try {
            socket = new Socket("localhost", 9999);

            while(true) {
                ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
                byte[] buf = new byte[1024];
                FileOutputStream fout = new FileOutputStream("c:/hyebin/hyebin/excercise.jpg");

                while((ois.read(buf, 0, buf.length))!=-1){
                    fout.write(buf, 0, buf.length);
                }
                System.out.println("파일 수신 및 저장 성공");

            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }

java.io.EOFException
at java.base/java.io.ObjectInputStream$PeekInputStream.readFully(ObjectInputStream.java:2890)
at java.base/java.io.ObjectInputStream$BlockDataInputStream.readShort(ObjectInputStream.java:3385)
at java.base/java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:942)
at java.base/java.io.ObjectInputStream.<init>(ObjectInputStream.java:385)
at comm/comm.client.main(client.java:14)
</code>```

This is my client code. The first code runs normally. However, such an error occurs from the second time it is saved. I don't know where the error occurs.

答:
This code is all sorts of problematic.

The while(true) is just bizarre, and causes the exception you see.

ObjectInputStream is used, but for absolutely no reason. plain jane inputstreams have the read() function. Don't wrap your socket in the ObjectInputStream.

ois.read does not read the full buffer. It reads at least 1 byte, and probably more, possibly the entire buffer, but it doesn't have to. You ignore how many bytes it did read, and then write the full buffer to the file, which means that if for example the network packet size is smaller than the file size, your code breaks. you need to save the value returned by the read call, if it is -1, stop, if it is not, write that many bytes (provide that value instead of buf.length as third arg to the write method

Your exception handling is deplorable. On failure, this code prints and continues.

The error is in line 14 - see the client.java:14 bit in your stack trace? That's useful information.

Resources must be guarded: You MUST close resources, and you must do so even if your code exits via exception or otherwise. There is a construct for this, called the ARM construct (automatic resource management), also called try-with.

inputstreams have a method these days to ask them to just dump themselves into a file.

Combining it all:

```<code>private static final String OUT_FILE = "c:/hyebin/hyebin.exercise.jpg";
public static void main(String[] args) throws Exception {
    Socket socket = new Socket("localhost", 9999);
    try (
        InputStream in = socket.getInputStream();
        FileOutputStream out = new FileOutputStream(OUT_FILE)) {

        in.transferTo(out);
    }
    System.out.println("파일 수신 및 저장 성공");
}
</code>```

easy, isn't it? It's generally a good idea to look at the javadoc of stuff you're using to figure out how to use it, and to find any useful shortcuts, such as the transferTo method.

Title: java.io.EOFException in java eclipse

Body:
try {
            socket = new Socket("localhost", 9999);

            while(true) {
                ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
                byte[] buf = new byte[1024];
                FileOutputStream fout = new FileOutputStream("c:/hyebin/hyebin/excercise.jpg");

                while((ois.read(buf, 0, buf.length))!=-1){
                    fout.write(buf, 0, buf.length);
                }
                System.out.println("파일 수신 및 저장 성공");

            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }

java.io.EOFException
at java.base/java.io.ObjectInputStream$PeekInputStream.readFully(ObjectInputStream.java:2890)
at java.base/java.io.ObjectInputStream$BlockDataInputStream.readShort(ObjectInputStream.java:3385)
at java.base/java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:942)
at java.base/java.io.ObjectInputStream.<init>(ObjectInputStream.java:385)
at comm/comm.client.main(client.java:14)

This is my client code. The first code runs normally. However, such an error occurs from the second time it is saved. I don't know where the error occurs.

Body:
This code is all sorts of problematic.

The while(true) is just bizarre, and causes the exception you see.

ObjectInputStream is used, but for absolutely no reason. plain jane inputstreams have the read() function. Don't wrap your socket in the ObjectInputStream.

ois.read does not read the full buffer. It reads at least 1 byte, and probably more, possibly the entire buffer, but it doesn't have to. You ignore how many bytes it did read, and then write the full buffer to the file, which means that if for example the network packet size is smaller than the file size, your code breaks. you need to save the value returned by the read call, if it is -1, stop, if it is not, write that many bytes (provide that value instead of buf.length as third arg to the write method

Your exception handling is deplorable. On failure, this code prints and continues.

The error is in line 14 - see the client.java:14 bit in your stack trace? That's useful information.

Resources must be guarded: You MUST close resources, and you must do so even if your code exits via exception or otherwise. There is a construct for this, called the ARM construct (automatic resource management), also called try-with.

inputstreams have a method these days to ask them to just dump themselves into a file.

Combining it all:

private static final String OUT_FILE = "c:/hyebin/hyebin.exercise.jpg";
public static void main(String[] args) throws Exception {
    Socket socket = new Socket("localhost", 9999);
    try (
        InputStream in = socket.getInputStream();
        FileOutputStream out = new FileOutputStream(OUT_FILE)) {

        in.transferTo(out);
    }
    System.out.println("파일 수신 및 저장 성공");
}

easy, isn't it? It's generally a good idea to look at the javadoc of stuff you're using to figure out how to use it, and to find any useful shortcuts, such as the transferTo method.


问:
SQL server recovery mechanism
I have a service application in C# which queries data from one database and inserts it into another SQL database.

Sometimes, the MSSQLSERVER service crashed for unknown reason and my application will crash as well. I want to do a SQL recovery mechanism that where I check to make sure the sqlconnection state is fine before i write to the database but how i do that?

I tried stopping MSSQLSERVER service and sqlconnection.State is always open even when the MSSQLSERVER service is stopped.

答:
The general strategy of checking the connection state before calling a SQL command fundamentally won't work. What happens if the service crashes after your connection check, but before you call the SQL command?

You probably will need to figure out what exception is thrown when the database is down and recover from that exception at the appropriate layer of code.

Title: SQL server recovery mechanism