问:
Need Support with batch script to find, compress and move backup with daily schedule
I made a batch script to find and compress and move backup with daily schedule:

```<code>@echo off

robocopy C:\TempBackup  C:\TempBackup\X *.BAK* /w:0 /r:0 /np /fft /maxage:1 /maxlad:1

7z a -tzip X "X\*" -r

for /f "tokens=1-5 delims=/: " %%a in ('robocopy "|" . /njh ^| find ":"') do  set "CURRDATE=%%a%%b%%c" & set "CURRTIME=%%d%%e"

RENAME X.zip X_%CURRDATE%%CURRTIME%.zip

move /y C:\TempBackup\*.zip C:\Daily_Backup
rd /q  /s C:\TempBackup\X
del /q  C:\Tempbackup\*.BAK*

:stop
</code>```

This script has only one problem that I only find 1 compressed file for the current day in Daily_Backup folder instead of 1 file for each day that the script runs.

Body:
I made a batch script to find and compress and move backup with daily schedule:

@echo off

robocopy C:\TempBackup  C:\TempBackup\X *.BAK* /w:0 /r:0 /np /fft /maxage:1 /maxlad:1

7z a -tzip X "X\*" -r

for /f "tokens=1-5 delims=/: " %%a in ('robocopy "|" . /njh ^| find ":"') do  set "CURRDATE=%%a%%b%%c" & set "CURRTIME=%%d%%e"

RENAME X.zip X_%CURRDATE%%CURRTIME%.zip

move /y C:\TempBackup\*.zip C:\Daily_Backup
rd /q  /s C:\TempBackup\X
del /q  C:\Tempbackup\*.BAK*

:stop

This script has only one problem that I only find 1 compressed file for the current day in Daily_Backup folder instead of 1 file for each day that the script runs.


来源: stackexchange

问:
How to observe the event that a VM has booted?
I have a bare qemu or kvm virtual machine and would like to observe or wait for the event that the virtual machine has booted in a reliable way.

This is a generic question that may not have a generic answer. If it helps you may assume a subset of the following:

The VM is running Debian GNU/Linux.

The actual question is whether the contained ssh server is reachable. It is exported via user networking and a hostfwd.

Remarks:

reliable means that it is suitable for continous integration testing. It should fail in less than 0.1% of cases.

Running ssh -o ConnectionAttempts=30 sometimes produces a failure even though ssh would work afterwards.

ContentLicense: CC BY-SA 4.0


问:
to change decimal seperator and currency format for french language pack in magento
I have changed the locale to french in magento2. After applying french locale, currency symbol is moved to right and decimal separator changed from dot(.) to comma(,).
In french language pack, the price amount is like this:
10,00 £
this is the pricing after applying french langauage pack
I need to change it to:
£10.00
I need this pricing format

I had tried changing the fr.xml file in vendor/magento/zendframework1/library/Zend/Locale/Data.

```<code><symbols numberSystem="latn">
            <decimal>.</decimal>
            <group>,</group>
</code>```

After changing this,there is no change in fronted pricing format.
I want to set Pricing in french locale same as English locale.
Do you have any idea to change this currency format and decimal separator for french language in magento2?
Thanks

Body:
I have changed the locale to french in magento2. After applying french locale, currency symbol is moved to right and decimal separator changed from dot(.) to comma(,).
In french language pack, the price amount is like this:
10,00 £
this is the pricing after applying french langauage pack
I need to change it to:
£10.00
I need this pricing format

I had tried changing the fr.xml file in vendor/magento/zendframework1/library/Zend/Locale/Data.

<symbols numberSystem="latn">
            <decimal>.</decimal>
            <group>,</group>

After changing this,there is no change in fronted pricing format.
I want to set Pricing in french locale same as English locale.
Do you have any idea to change this currency format and decimal separator for french language in magento2?
Thanks


问:
How to add an attribute to all components in nextjs with javascript
I have this question that is any way to add an attribute to all for example Image tags in nextjs? For example, I need to add a loader function to all Image tags without editing tags. Like in _app.js file, Add this attribute to all tags. Any idea?


问:
change notification sound of ios(Flutter) using a network sound
using flutter my application users should be able to select notification sounds online dynamically, i am not able to find the solution for that, technology i am using is flutter

I have tried local notifications as well as different packages like ringtone. in android it is working smoothly but for iOS its not working. it gives an error


问:
Ways to draw a line with float end-points in OpenCV
I am annotating images for ML segmentation. Some of the objects are small and the boundary could take a fraction of a pixel. I found the annotator (CVAT) that can mark borders with sub-pixel accuracy, giving polygon's coordinates as floats. However, when I try to make a mask in OpenCV, all of the drawing functions (lines, polygons, contours) only accept coordinates as integers.

I understand that line either colors a pixel of it doesn't and there could never be a half-colored pixel without changing resolution. But I think there could be some benefit to providing float end-points of a line. Below are the examples of why I am seeking this functionality at all.

As you can see, both lines round to the same end-point pixels. But the float one passes through different pixels, which could eventually mark object's boundary on a mask with better precision. Note, I am not sure that is exactly how OpenCV draws lines, it is solely for demonstration purposes.

When I am generating masks directly from the annotation software it actually provides leaner masks than those I produce in OpenCV. Which I suspect is due to them using "sub-pixel precision polygons".

So my questions are:

Am I missing something and OpenCV actually has this functionality.

If not, what would be the best way to emulate it? The only thing that comes to mind now is traversing a line and manually coloring each individual pixel in numpy, which sounds very slow.

Is there any other Python library that does have this functionality?


问:
Spawn objects in same place on screen on different aspect ratios, but retain distances between one another
I am trying to make connect the dots game in landscape mode, and i need to spawn dots from coordinates(0-1000) in json file onto screen. It's easy to map out different viewport size to coordinates and make them spawn in same location from the edges / center of the screen, but since when you connect the dots it's suppose to be a drawing I don't want it to strech. F.e 4/3 display and 21/9 one will stretch the drawing completely differently. How can I make sure it looks the same on all devices?

I am thinking of making an invisible rectangular shape in the middle of the screen with a size 1000x1000 or max screen height) and maping coordinates to that shape, so the drawing will always be in center of the screen and will always look exactly the same, but not sure if it's possible to get a specific point in shape.

I just think there's easy solution and I overcomplicate this.


问:
how to filter date based on last circulated data
I would like to filter the date based on last report received date(working data clear daily basic from path). I am saving the data on SQLite and I filter dataframe with the date (Day-1) and append it on database. But in some cases, data do not receive daily basic, on those day I cannot filter day-1, may be two or more-day data need to filter. For the automation purpose how can I filter the date which is not yet uploaded on database. Now what I am doing is apply date number on date and subtract from last working date number. It will not work very beginning of the month.</p>
```<code>dt_yesday = datetime.strftime(datetime.now() - timedelta(1), '%Y-%m-%d') wk_dt = int(datetime.strftime(datetime.now() - timedelta(1), '%e')) day_1 = df[df['date'] == dt_yesday]

latest_report_data = str(df['date_number'].iloc[-1])
date_subtract = wk_dt - int(last_working_date.iloc[-1])

if date_subtract == 0:
    day_1 = df[df['date'] == dt_yesday]
elif date_subtract == 1:
    day_1 = df[df['date'] > dt_Last2Day]
</code>```

Body:
I would like to filter the date based on last report received date(working data clear daily basic from path). I am saving the data on SQLite and I filter dataframe with the date (Day-1) and append it on database. But in some cases, data do not receive daily basic, on those day I cannot filter day-1, may be two or more-day data need to filter. For the automation purpose how can I filter the date which is not yet uploaded on database. Now what I am doing is apply date number on date and subtract from last working date number. It will not work very beginning of the month.

dt_yesday = datetime.strftime(datetime.now() - timedelta(1), '%Y-%m-%d') wk_dt = int(datetime.strftime(datetime.now() - timedelta(1), '%e')) day_1 = df[df['date'] == dt_yesday]

latest_report_data = str(df['date_number'].iloc[-1])
date_subtract = wk_dt - int(last_working_date.iloc[-1])

if date_subtract == 0:
    day_1 = df[df['date'] == dt_yesday]
elif date_subtract == 1:
    day_1 = df[df['date'] > dt_Last2Day]


问:
Apache Echarts Two Date Data Options Problem
I am using Apache Ecarts stacked line chart. This chart is also available, there is a type date option. For example, like 'Mon,Tue,Wed..' I want to give the month to the user as a second option in the same table. When you click a button, months should be listed instead of days. I made several additions to the sample code below, but it did not see any of the tables.
How can I solve this?

import * as echarts from 'echarts';

var chartDom = document.getElementById('main');
var myChart = echarts.init(chartDom);
var option;

option = {
  title: {
    text: 'Stacked Line'
  },
  tooltip: {
    trigger: 'axis'
  },
  legend: {
    data: ['Email', 'Union Ads', 'Video Ads', 'Direct', 'Search Engine']
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  toolbox: {
    feature: {
      saveAsImage: {}
    }
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      name: 'Email',
      type: 'line',
      stack: 'Total',
      data: [120, 132, 101, 134, 90, 230, 210]
    },
    {
      name: 'Union Ads',
      type: 'line',
      stack: 'Total',
      data: [220, 182, 191, 234, 290, 330, 310]
    },
    {
      name: 'Video Ads',
      type: 'line',
      stack: 'Total',
      data: [150, 232, 201, 154, 190, 330, 410]
    },
    {
      name: 'Direct',
      type: 'line',
      stack: 'Total',
      data: [320, 332, 301, 334, 390, 330, 320]
    },
    {
      name: 'Search Engine',
      type: 'line',
      stack: 'Total',
      data: [820, 932, 901, 934, 1290, 1330, 1320]
    }
  ]
};

option && myChart.setOption(option);

```


问:
How can I call random of data with dataloader
When I am training a model, I should use only 10% of data for trainer.fit(model,datamodule)
so I should call DataModule just for 10% of data
Part of DataModule is:

```<code>class DataModule(pl.LightningDataModule):
  def __init__(self, train_dataset, val_dataset,  batch_size = 1):

    super(DataModule, self).__init__()
    self.train_dataset = train_dataset
    self.val_dataset = val_dataset
    self.batch_size = batch_size
  def train_dataloader(self):
    return DataLoader(self.train_dataset, batch_size = self.batch_size,
                      collate_fn = collate_fn, shuffle = True, num_workers = 2, pin_memory = True)

  def val_dataloader(self):
    return DataLoader(self.val_dataset, batch_size = self.batch_size,
                    collate_fn = collate_fn, shuffle = False, num_workers = 2, pin_memory = True)
</code>```

So I use a for loop

```<code>datamodule = DataModule(train_ds, val_ds)
for i,data in enumerate(datamodule.train_dataloader()):
    print( datamodule.train_dataloader(i,data))
</code>```

But it doesn't work. How can I change it?

Body:
When I am training a model, I should use only 10% of data for trainer.fit(model,datamodule)
so I should call DataModule just for 10% of data
Part of DataModule is:

class DataModule(pl.LightningDataModule):
  def __init__(self, train_dataset, val_dataset,  batch_size = 1):

    super(DataModule, self).__init__()
    self.train_dataset = train_dataset
    self.val_dataset = val_dataset
    self.batch_size = batch_size
  def train_dataloader(self):
    return DataLoader(self.train_dataset, batch_size = self.batch_size,
                      collate_fn = collate_fn, shuffle = True, num_workers = 2, pin_memory = True)

  def val_dataloader(self):
    return DataLoader(self.val_dataset, batch_size = self.batch_size,
                    collate_fn = collate_fn, shuffle = False, num_workers = 2, pin_memory = True)

So I use a for loop

datamodule = DataModule(train_ds, val_ds)
for i,data in enumerate(datamodule.train_dataloader()):
    print( datamodule.train_dataloader(i,data))

But it doesn't work. How can I change it?


问:
Google Sheet's Import XML with Xpath function resulting in error
So I'm trying to pull Price/Sales (ttm) for BMRI stocks, and im following the instruction i found in the internet : =importxml(url,xpath)

The url is : https://finance.yahoo.com/quote/BMRI.JK/key-statistics?p=BMRI.JK
and i tried taking the xpath using inspect element in my browser and using chrome xpath helper
enter image description here

I pasten the XPath in the formula and it resulted in

Error, Result at URL not found

Please advise

Here is the formula I used :

```<code>=ImportXML("https://finance.yahoo.com/quote/BMRI.JK/key-statistics?p=BMRI.JK", "//html[@id='atomic']/body[@class='has-scrolled']/div[@id='app']/div/div/div[@id='render-target-default']/div[@class='Bgc($bg-body) Mih(100%) W(100%) Bgc($layoutBgColor)! finance US']/div[@class='Pos(r) Bgc($bg-content) Bgc($lv2BgColor)! Miw(1007px) Maw(1260px) tablet_Miw(600px)--noRightRail Bxz(bb) Bdstartc(t) Bdstartw(20px) Bdendc(t) Bdends(s) Bdendw(20px) Bdstarts(s) Mx(a)']/div[@id='YDC-Col1']/div[@id='Main']/div[@id='Col1-0-KeyStatistics-Proxy']/section[@class='Pb(30px) Px(20px)']/div[@class='Mstart(a) Mend(a)']/div[@class='Fl(start) smartphone_W(100%) W(50%)']/div[@class='Mb(10px) smartphone_Pend(0px) Pend(20px)']/div[@class='Pos(r) Mt(10px)']/div/div/table[@class='W(100%) Bdcl(c) ']/tbody/tr[@class='Bxz(bb) H(36px) BdB Bdbc($seperatorColor) fi-row Bgc($hoverBgColor):h'][5]/td[@class='Fw(500) Ta(end) Pstart(10px) Miw(60px)']")
</code>```

Body:
So I'm trying to pull Price/Sales (ttm) for BMRI stocks, and im following the instruction i found in the internet : =importxml(url,xpath)

The url is : https://finance.yahoo.com/quote/BMRI.JK/key-statistics?p=BMRI.JK
and i tried taking the xpath using inspect element in my browser and using chrome xpath helper
enter image description here

I pasten the XPath in the formula and it resulted in

Error, Result at URL not found

Please advise

Here is the formula I used :

=ImportXML("https://finance.yahoo.com/quote/BMRI.JK/key-statistics?p=BMRI.JK", "//html[@id='atomic']/body[@class='has-scrolled']/div[@id='app']/div/div/div[@id='render-target-default']/div[@class='Bgc($bg-body) Mih(100%) W(100%) Bgc($layoutBgColor)! finance US']/div[@class='Pos(r) Bgc($bg-content) Bgc($lv2BgColor)! Miw(1007px) Maw(1260px) tablet_Miw(600px)--noRightRail Bxz(bb) Bdstartc(t) Bdstartw(20px) Bdendc(t) Bdends(s) Bdendw(20px) Bdstarts(s) Mx(a)']/div[@id='YDC-Col1']/div[@id='Main']/div[@id='Col1-0-KeyStatistics-Proxy']/section[@class='Pb(30px) Px(20px)']/div[@class='Mstart(a) Mend(a)']/div[@class='Fl(start) smartphone_W(100%) W(50%)']/div[@class='Mb(10px) smartphone_Pend(0px) Pend(20px)']/div[@class='Pos(r) Mt(10px)']/div/div/table[@class='W(100%) Bdcl(c) ']/tbody/tr[@class='Bxz(bb) H(36px) BdB Bdbc($seperatorColor) fi-row Bgc($hoverBgColor):h'][5]/td[@class='Fw(500) Ta(end) Pstart(10px) Miw(60px)']")


问:
Tkinter StringVar.set within loop not updating at Application level
I'm trying to create a GUI which allows the user to upload the contents of a dataframe into SQL Server by operating on df.iterrows adn executing an INSERT INTO command once a button is clicked. The resulting code loops through the dataframe [pulled in by aggregating several csv files into 1 dataframe] and then loops through each row, inserting that row in the SLQ server table. It works, but I would also like an attached StringVar to update after each row is parsed via the inner loop to tell the user when each row has been processed. The StringVar does not update until the end of the loop i.e the last row is being operated on. I know its something to do with the mainloop being paused while the inner loop is executing but how do I get this to update between rows please? Is this something to with setting a trace of some kind?

I have an example dataframe of 4 rows. self.open_files_create_big_df takes 4 separate csv files and pushes them altogether to form one final 4 row dataframe which I then use self.insert_into_sql to push the data into SQL.

I want the label to show:
"Saving row 1 out of 4..."
"Saving row 2 out of 4..."
"Saving row 3 out of 4... before finally printing:
"Saving row 4 out of 4..."
instead of it currently just showing:
"Saving row 4 out of 4..."
Cut-down code attached. Many thanks

```<code>
import tkinter as tk
import tkinter.messagebox
from tkinter import messagebox
import customtkinter
import pandas as pd
import datetime as dt
from datetime import datetime as dt
import numpy as np
import os
import glob
import pprint as pp
import xlwings as xw
import pyodbc
import time

class App(customtkinter.CTk):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.notification_label = tk.StringVar(self)
        # configure window
        self.geometry(f"{1000}x{700}")
        # etc etc
        #deleted code for brevity

        customtkinter.CTkLabel(self, textvariable = self.notification_label
                               ).grid(row=13, column=0, padx=20, pady=(90, 90), sticky=tk.W
                                      )

    def open_files_create_big_df(self, dir_path, sheet_name, rows_to_skip):
        list_dfs = []
        for file in os.listdir(dir_path):
            df = pd.read_excel(dir_path + "\\" + file, sheet_name=sheet_name, skiprows=rows_to_skip)
            list_dfs.append(df)

        all_dfs = pd.concat(list_dfs)
        return all_dfs

    def get_csv_and_upload_event(self):
        df = self.open_files_create_big_df(dir_path="test directory",
                                      sheet_name="Upload",
                                      rows_to_skip=8)
        self.insert_into_sql(df, servername="ABCDEFG")

    def insert_into_sql(self, df, servername="ABCDEFG", database="Mydb", driver="{SQL Server}",
                        tablename="ManualAdjustments"):
        conn_string = f"""Driver={driver};
                        Server={servername};
                        Database={database};
                        Trusted_Connection=yes"""

        conn = pyodbc.connect(conn_string)
        cursor = conn.cursor()
        counter = 1
        for index, row in df.iterrows():

            cursor.execute(f"INSERT INTO [{tablename}] ([CurrentMonthEndDateManualEntry],"
                           f"[EventCode],[EventName],[ClaimRef],[ClaimTitle],[LineOfBusiness],"
                           f"[SubLineOfBusiness],[UWY],[CurrentGrossERSIncurredPositive],"
                           f"[CurrentGrossManualPositive],[CurrentGrossAdjustedIncurredPositive],"
                           f"[CurrentCededERSIncurredPositive],[CurrentCededManualPositive],"
                           f"[CurrentCededAdjustedIncurredPositive],[CurrentCededRIPsPositive],[CurrentCededManualPositive2],"
                           f"[CurrentCededAdjustedRIPsPositive],[CurrentNetAdjustedIncurredPositive]) "
                           f"VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
                           (row[0], row[1], row[2], row[3], row[4], row[5], row[6],
                            row[7], row[8], row[9], row[10], row[11], row[12], row[13],
                            row[14], row[15], row[16], row[17]))
            self._notification_string = f"Saving row {counter} out of {df.shape[0]}"
            self.notification_label.set(self._notification_string)

            counter+=1
        conn.commit()
        cursor.close()
        conn.close()

if __name__ == "__main__":
    app = App()
    app.mainloop()
</code>```

Body:
I'm trying to create a GUI which allows the user to upload the contents of a dataframe into SQL Server by operating on df.iterrows adn executing an INSERT INTO command once a button is clicked. The resulting code loops through the dataframe [pulled in by aggregating several csv files into 1 dataframe] and then loops through each row, inserting that row in the SLQ server table. It works, but I would also like an attached StringVar to update after each row is parsed via the inner loop to tell the user when each row has been processed. The StringVar does not update until the end of the loop i.e the last row is being operated on. I know its something to do with the mainloop being paused while the inner loop is executing but how do I get this to update between rows please? Is this something to with setting a trace of some kind?

I have an example dataframe of 4 rows. self.open_files_create_big_df takes 4 separate csv files and pushes them altogether to form one final 4 row dataframe which I then use self.insert_into_sql to push the data into SQL.

I want the label to show:
"Saving row 1 out of 4..."
"Saving row 2 out of 4..."
"Saving row 3 out of 4... before finally printing:
"Saving row 4 out of 4..."
instead of it currently just showing:
"Saving row 4 out of 4..."
Cut-down code attached. Many thanks

import tkinter as tk
import tkinter.messagebox
from tkinter import messagebox
import customtkinter
import pandas as pd
import datetime as dt
from datetime import datetime as dt
import numpy as np
import os
import glob
import pprint as pp
import xlwings as xw
import pyodbc
import time

class App(customtkinter.CTk):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.notification_label = tk.StringVar(self)
        # configure window
        self.geometry(f"{1000}x{700}")
        # etc etc
        #deleted code for brevity

        customtkinter.CTkLabel(self, textvariable = self.notification_label
                               ).grid(row=13, column=0, padx=20, pady=(90, 90), sticky=tk.W
                                      )

    def open_files_create_big_df(self, dir_path, sheet_name, rows_to_skip):
        list_dfs = []
        for file in os.listdir(dir_path):
            df = pd.read_excel(dir_path + "\\" + file, sheet_name=sheet_name, skiprows=rows_to_skip)
            list_dfs.append(df)

        all_dfs = pd.concat(list_dfs)
        return all_dfs

    def get_csv_and_upload_event(self):
        df = self.open_files_create_big_df(dir_path="test directory",
                                      sheet_name="Upload",
                                      rows_to_skip=8)
        self.insert_into_sql(df, servername="ABCDEFG")

    def insert_into_sql(self, df, servername="ABCDEFG", database="Mydb", driver="{SQL Server}",
                        tablename="ManualAdjustments"):
        conn_string = f"""Driver={driver};
                        Server={servername};
                        Database={database};
                        Trusted_Connection=yes"""

        conn = pyodbc.connect(conn_string)
        cursor = conn.cursor()
        counter = 1
        for index, row in df.iterrows():

            cursor.execute(f"INSERT INTO [{tablename}] ([CurrentMonthEndDateManualEntry],"
                           f"[EventCode],[EventName],[ClaimRef],[ClaimTitle],[LineOfBusiness],"
                           f"[SubLineOfBusiness],[UWY],[CurrentGrossERSIncurredPositive],"
                           f"[CurrentGrossManualPositive],[CurrentGrossAdjustedIncurredPositive],"
                           f"[CurrentCededERSIncurredPositive],[CurrentCededManualPositive],"
                           f"[CurrentCededAdjustedIncurredPositive],[CurrentCededRIPsPositive],[CurrentCededManualPositive2],"
                           f"[CurrentCededAdjustedRIPsPositive],[CurrentNetAdjustedIncurredPositive]) "
                           f"VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
                           (row[0], row[1], row[2], row[3], row[4], row[5], row[6],
                            row[7], row[8], row[9], row[10], row[11], row[12], row[13],
                            row[14], row[15], row[16], row[17]))
            self._notification_string = f"Saving row {counter} out of {df.shape[0]}"
            self.notification_label.set(self._notification_string)

            counter+=1
        conn.commit()
        cursor.close()
        conn.close()

if __name__ == "__main__":
    app = App()
    app.mainloop()


问:
How to modify a single line in a large file?
I have a large .csv file where I need to edit a single value. Is there a way to do that without writing the entire file again?

I know that I can read a file line-by-line like this:

```<code>await for (var event in file
      .openRead()
      .transform(utf8.decoder)
      .transform(LineSplitter())) {
    if (isLineToEdit) {
      //edit the line
      break;
    }
  }
</code>```

However I don't know a way to edit a single line and write that to the file without having to write the entire file again. As far as I know, the only way to write to a file is by either overwriting it (FileMode.write) or by appending at the end (FileMode.append). Am I missing something? Is there some way to do that in dart?

Body:
I have a large .csv file where I need to edit a single value. Is there a way to do that without writing the entire file again?

I know that I can read a file line-by-line like this:

await for (var event in file
      .openRead()
      .transform(utf8.decoder)
      .transform(LineSplitter())) {
    if (isLineToEdit) {
      //edit the line
      break;
    }
  }

However I don't know a way to edit a single line and write that to the file without having to write the entire file again. As far as I know, the only way to write to a file is by either overwriting it (FileMode.write) or by appending at the end (FileMode.append). Am I missing something? Is there some way to do that in dart?


问:
Chrome extension v3 sandbox
I have a chrome extension that was working on the manifest version 2 without a problem. I had some javascript in the background that included web assembly and required wasm-eval. I have converted the extension to manifest version 3, which doesn't allow wasm-eval or unsafe-eval any more. What I did for a solution is I created a new window (mainpage.html) from the extension and this window includes an iframe (sandbox.html) and this iframe includes the web assembly code and communicates with the background service worker with postMessages.

I am wondering if there is a solution without opening a new window for my case. Something that will run the sandbox.html running in the background and the service worker can communicate with it. I tried to put the sandbox.html to the service worker, but the service worker doesn't accept html files running inside.

Popup script is not a solution because the user needs to click the extension icon to make it running. Content script worked but if the website has a content security policy that doesn't allow unsafe-eval, then it won't work. I need a more general solution.

There is something explained here with the Event pages for which I have no idea, and I believe it is deprecated as well. Service worker cannot have access to the DOM. https://developer.chrome.com/docs/extensions/mv3/sandboxingEval/

this is from the manifest.json

```<code>"sandbox": {
    "pages": ["sandbox.html"]
  }
</code>```

this is what mainpage.html looks like

```<code><iframe id="theFrame" src="sandbox.html" style="display: none;"></iframe>
    <script src="mainpage.js"></script>
</code>```

this is what the sandbox.html looks like

```<code>    <script src="wasm_exec.js"></script>
    <script src="wasm_startup.js"></script>
    <script src="assign_result.js"></script>
    <script src="event_listener.js"></script>
</code>```

Title: Chrome extension v3 sandbox

Body:
I have a chrome extension that was working on the manifest version 2 without a problem. I had some javascript in the background that included web assembly and required wasm-eval. I have converted the extension to manifest version 3, which doesn't allow wasm-eval or unsafe-eval any more. What I did for a solution is I created a new window (mainpage.html) from the extension and this window includes an iframe (sandbox.html) and this iframe includes the web assembly code and communicates with the background service worker with postMessages.

I am wondering if there is a solution without opening a new window for my case. Something that will run the sandbox.html running in the background and the service worker can communicate with it. I tried to put the sandbox.html to the service worker, but the service worker doesn't accept html files running inside.

Popup script is not a solution because the user needs to click the extension icon to make it running. Content script worked but if the website has a content security policy that doesn't allow unsafe-eval, then it won't work. I need a more general solution.

There is something explained here with the Event pages for which I have no idea, and I believe it is deprecated as well. Service worker cannot have access to the DOM. https://developer.chrome.com/docs/extensions/mv3/sandboxingEval/

this is from the manifest.json

"sandbox": {
    "pages": ["sandbox.html"]
  }

this is what mainpage.html looks like

this is what the sandbox.html looks like


问:
How do i intercept all the http request made from application using dojo framework
I have an application that uses dojo framework. I need to add csrf token in the header to all the http request made. How do i do that in dojo?</p>


问:
Jinja code rendered using ajax is enclosed witin doublequorts in django project

I am developing a todo app using django as backend and html,css,bootstrap for frontend,
I used Ajax in this project to load data from server without refresh.

**Look at the image **
the {%csrf_token%} is passed through ajax but is is renderd in html page as a text within a double quort.
How to fix this

I want to render the {%csrf_token%} in the webpage without double quorts.

Ajax code

```<code> $.ajax({
        type:'POST',
        url:'/task/'+todo_id+'/new_todo/',
        processData: false,
        contentType: false,
        data: data,
        success: function(response){
          console.log("**********Data send to backend");
          var new_id = response['new_id'];
          var new_color = response['new_color'];
          var new_status = response['new_status']
          var new_todo_note = response['new_todo_note']
          if (new_todo_note == null){
            my_note = " "
          }
          else{
            my_note = new_todo_note
          }
          $("#"+todo_id).hide();

          $.ajax({
            type:'GET',
            url:'/task/'+todo_id+'/new_todo/',
            data:data,
            dataType:'json',
            success: function(response){
              var todo_section = `<ol class="list-group mb-3 v1" id="${response.latest_todo.id}right">
              <li class="list-group-item d-flex justify-content-between align-items-start">
              <div class="ms-2 me-auto d-flex">
              <div>
              <div class="fw-bold">${response.latest_todo_name}</div>
              <p style="font-size: x-small; margin:0;">${response.latest_todo_added_date}</p>
              <div  style="max-width: 100px; display:flex; ">
              <div id="${new_id}task_note">

              ${my_note}
              </div>
              </div>
              </div>
              <div class="mt-1 ms-4">
              <a href="{%url 'todo-details' todo.id%}">
              <i class="fa-solid fa-arrow-up-right-from-square text-muted"></i>
              </a>
              </div>
              </div>
              <div class="d-flex flex-column">
              <div style="align-self: flex-end;" id="${new_id}badge_live">
              <span class="badge  rounded-pill" id="${new_id}badge" style="background-color:${new_color};">&nbsp&nbsp&nbsp
              </span>
              </div>
              <div class="mt-2 d-flex">
              <div class="me-2">
              <button type="button" class="btn btn-success" data-bs-toggle="modal"  data-bs-target="#exampleModal" style="font-size: xx-small;">
              Note
              </button>
              <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
              <div class="modal-dialog">
              <div class="modal-content">
              <div class="modal-header">
              <h1 class="modal-title fs-5" id="exampleModalLabel">Create Task Note</h1>
              <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
              </div>
              <form action="/todo/${new_id}/add_note/" method="post" id="task_note_form" name="${new_id}" enctype="multipart/form-data">

              {%csrf_token%}

              <div class="modal-body">
              <div>
              <h2>Add Task Note</h2>
              </div>
              <div class="mb-3">
              <textarea name="note" id="note${new_id}" cols="15" rows="5" class="form-control" required></textarea>
              </div>
              </div>
              <div class="modal-footer">
              <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
              <input type="submit" class="btn btn-primary note_submit_btns" value="Create" data-bs-dismiss="modal" name="${new_id}">
              </div>
              </form>
              </div>
              </div>
              </div>
              </div>
              <div id="${new_id}btn_live_change">
              <div id="${new_id}btn_live">
              <input type="submit" value="${new_status}" id="${new_id}"
              class="btn btn-primary stat_btns"
              style="font-size: xx-small;">
              </div>
              </div>
              </div>
              </div>
              </li>
              </ol>`

              $("#display-todo-data").append(todo_section);

              document.getElementById("task_note_form").reset();

            },
          });
        }

      });

    }
  });
</code>```

Body:
I am developing a todo app using django as backend and html,css,bootstrap for frontend,
I used Ajax in this project to load data from server without refresh.

**Look at the image **
the {%csrf_token%} is passed through ajax but is is renderd in html page as a text within a double quort.
How to fix this

I want to render the {%csrf_token%} in the webpage without double quorts.

Ajax code

 $.ajax({
        type:'POST',
        url:'/task/'+todo_id+'/new_todo/',
        processData: false,
        contentType: false,
        data: data,
        success: function(response){
          console.log("**********Data send to backend");
          var new_id = response['new_id'];
          var new_color = response['new_color'];
          var new_status = response['new_status']
          var new_todo_note = response['new_todo_note']
          if (new_todo_note == null){
            my_note = " "
          }
          else{
            my_note = new_todo_note
          }
          $("#"+todo_id).hide();

          $.ajax({
            type:'GET',
            url:'/task/'+todo_id+'/new_todo/',
            data:data,
            dataType:'json',
            success: function(response){
              var todo_section = `

${response.latest_todo_name}

${response.latest_todo_added_date}

              ${my_note}

              &nbsp&nbsp&nbsp

              <button type="button" class="btn btn-success" data-bs-toggle="modal"  data-bs-target="#exampleModal" style="font-size: xx-small;">
              Note
              </button>

Create Task Note

              <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>

              <form action="/todo/${new_id}/add_note/" method="post" id="task_note_form" name="${new_id}" enctype="multipart/form-data">

              {%csrf_token%}

Add Task Note

              <textarea name="note" id="note${new_id}" cols="15" rows="5" class="form-control" required></textarea>

              <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
              <input type="submit" class="btn btn-primary note_submit_btns" value="Create" data-bs-dismiss="modal" name="${new_id}">

              </form>

              <input type="submit" value="${new_status}" id="${new_id}"
              class="btn btn-primary stat_btns"
              style="font-size: xx-small;">

`

              $("#display-todo-data").append(todo_section);

              document.getElementById("task_note_form").reset();

            },
          });
        }

      });

    }
  });


问:
Delete first line in fwrite function
I have a function in PHP that aims to download a csv file, but there is always a blank line at the start of the file

How to delete the blank line at the beginning of the file
this is my code

```<code>$name_file = 'ekspor-kag-bri-' . date('Ym', strtotime($data_pendukung['tgl_trf'])) . '.csv';
        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename="'.$name_file.'"');

        $kata_header = "REKENING;NOMINAL;EMAIL"."\n";
        $kata_header .= "tes";
        $arr_isi_cell = [];
        foreach ($dt_gaji as $row) {
            $isi_cell = str_replace("-","",$row->norekening) . ';' . floatval($row->total_gaji) . ';' . 'inayohanes@gmail.com'."\n";
            array_push($arr_isi_cell,$isi_cell);
        }
        $myfile = fopen("php://output", "wb");
        fwrite($myfile,$kata_header);
        foreach($arr_isi_cell as $line){
            // fputcsv($myfile,explode(',',$line),",");
            fwrite($myfile,$line);
        }

        fclose($myfile)
</code>```

Title: Delete first line in fwrite function

Body:
I have a function in PHP that aims to download a csv file, but there is always a blank line at the start of the file

How to delete the blank line at the beginning of the file
this is my code

$name_file = 'ekspor-kag-bri-' . date('Ym', strtotime($data_pendukung['tgl_trf'])) . '.csv';
        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename="'.$name_file.'"');

        $kata_header = "REKENING;NOMINAL;EMAIL"."\n";
        $kata_header .= "tes";
        $arr_isi_cell = [];
        foreach ($dt_gaji as $row) {
            $isi_cell = str_replace("-","",$row->norekening) . ';' . floatval($row->total_gaji) . ';' . 'inayohanes@gmail.com'."\n";
            array_push($arr_isi_cell,$isi_cell);
        }
        $myfile = fopen("php://output", "wb");
        fwrite($myfile,$kata_header);
        foreach($arr_isi_cell as $line){
            // fputcsv($myfile,explode(',',$line),",");
            fwrite($myfile,$line);
        }

        fclose($myfile)


问:
Facebook Login on local host . http local host not working
I am building an project for which i require facebook login. I have created an app on facebook for developers and have followed all instructions and tutorial for it. Now when i call api. it is giving an error show in below image.

i have referred to this answer Working with Facebook login from localhost

and this one also
facebook login on localhost without https

using these two answers i have created an test app from original app on facebook but still cant toggle enforce https option

Is there any other way or any update on previous answers?


问:
How do I change my VSC settings so that it recognizes my relative path?
Good Day everyone,

I am having some difficulties figuring out how to set my VSC to accept my relative paths input, I'm frustrated with having to constantly type out my absolute path when importing or linking it to another file etc.. This occurred to me on my new PC and I have no idea how to set it.

For example, the file below is in the same folder as building.proto however, I have to list the absolute path in order to use it. I am currently using Golang too.

Is there a setting/configuration similar to the one in the link so that it can change my default path usage to relative for every language?

VS Code auto imports not using absolute paths and not indented

```<code>syntax = "proto3";

import "exercise_2/import/building.proto"; //RELATIVE PATH: building.proto

message Address{
    City city = 1;
    Street street = 2;
    Building building = 3;
}
</code>```

Body:
Good Day everyone,

I am having some difficulties figuring out how to set my VSC to accept my relative paths input, I'm frustrated with having to constantly type out my absolute path when importing or linking it to another file etc.. This occurred to me on my new PC and I have no idea how to set it.

For example, the file below is in the same folder as building.proto however, I have to list the absolute path in order to use it. I am currently using Golang too.

Is there a setting/configuration similar to the one in the link so that it can change my default path usage to relative for every language?

VS Code auto imports not using absolute paths and not indented

syntax = "proto3";

import "exercise_2/import/building.proto"; //RELATIVE PATH: building.proto

message Address{
    City city = 1;
    Street street = 2;
    Building building = 3;
}


问:
Run npm script if flag is given in CLI
I would like to conditionally run a script based on if a flag is passed to the script yes or no. Consider the following:

```<code>"scripts": {
    "clean": "rm -rf ./dist",
    "build": "npm run clean && npm run build:esm && npm run build:cjs && if(--css) npm run build:css",
    "build:css": "sass $INIT_CWD/src/scss/:dist/css && postcss dist/css/*.css --use autoprefixer -d dist/css",
    "build:esm": "tsc -p ./config/tsconfig.esm.json && mv dist/js/esm/index.js dist/js/esm/index.mjs",
    "build:cjs": "tsc -p ./config/tsconfig.cjs.json",
    "prepack": "npm run build"
    },
</code>```

After the build command, at the very end, if the flag --css was given I want to run build:css as well. Currently, I've put an example placeholder that obviously does not work. But how would I achieve this? Is it even possible?

Title: Run npm script if flag is given in CLI

Body:
I would like to conditionally run a script based on if a flag is passed to the script yes or no. Consider the following:

"scripts": {
    "clean": "rm -rf ./dist",
    "build": "npm run clean && npm run build:esm && npm run build:cjs && if(--css) npm run build:css",
    "build:css": "sass $INIT_CWD/src/scss/:dist/css && postcss dist/css/*.css --use autoprefixer -d dist/css",
    "build:esm": "tsc -p ./config/tsconfig.esm.json && mv dist/js/esm/index.js dist/js/esm/index.mjs",
    "build:cjs": "tsc -p ./config/tsconfig.cjs.json",
    "prepack": "npm run build"
    },

After the build command, at the very end, if the flag --css was given I want to run build:css as well. Currently, I've put an example placeholder that obviously does not work. But how would I achieve this? Is it even possible?


问:
Facebook login setting valid OAuth redirect URI I get "this URL has been identified as malicious and/or abusive."
Facebook login setting valid OAuth redirect URI
I get "this URL has been identified as malicious and/or abusive."

How can I fix it?


问:
Sticky Fn after Home is simulated programmatically, MacOS
When I try to simulate keys programmatically on MacOS.
I find some keys causes sticky "Fn".

The following code results "Fn" + "h".
Can anyone help explain whether it is intended?

```<code>#include <stdio.h>
#include <Carbon/Carbon.h>

void simulate_key(CGEventSourceRef source, CGKeyCode key, bool key_down)
{
    CGEventRef event = CGEventCreateKeyboardEvent(source, key, key_down);
    CGEventPost(kCGSessionEventTap, event);
    CFRelease(event);
    sleep(1);
}

void print33(void) {
    CGEventSourceRef source = CGEventSourceCreate(kCGEventSourceStatePrivate);

    printf("simulate #: ");
    fflush(stdout);
    simulate_key(source, kVK_Shift, true);
    simulate_key(source, kVK_ANSI_3, true);
    simulate_key(source, kVK_ANSI_3, false);
    simulate_key(source, kVK_Shift, false);

    // sticky Fn, after clicking Home.
    simulate_key(source, kVK_Home, true);
    simulate_key(source, kVK_Home, false);

    printf("\nSimulate h after Home.\n");
    fflush(stdout);

    // Simulate h. The behavior seems Fn + h.
    simulate_key(source, kVK_ANSI_H, true);
    simulate_key(source, kVK_ANSI_H, false);

    // So as simulating e and d...

    CFRelease(source);
}

int main(int argc, const char * argv[]) {
    print33();
    return 0;
}
</code>```

I've also tried to print CGEventFlags. It shows kCGEventFlagMaskSecondaryFn is set. But I don't know whether it is a side effect. How can I prevent the Fn flag to be set when I just simulate a Home key.

```<code>#include <stdio.h>
#include <Carbon/Carbon.h>

void simulate_key(CGEventSourceRef source, CGKeyCode key, bool key_down)
{
    CGEventRef event = CGEventCreateKeyboardEvent(source, key, key_down);
    // CGEventSetFlags(event, 0);
    CGEventFlags flags = CGEventGetFlags(event);
    printf("event flags: %llX\n", (int64_t)flags);
    CGEventPost(kCGSessionEventTap, event);
    CFRelease(event);
    sleep(1);
}

void print33(void) {
    CGEventSourceRef source = CGEventSourceCreate(kCGEventSourceStatePrivate);

//    printf("simulate #: ");
//    fflush(stdout);
//    simulate_key(source, kVK_Shift, true);
//    simulate_key(source, kVK_ANSI_3, true);
//    simulate_key(source, kVK_ANSI_3, false);
//    simulate_key(source, kVK_Shift, false);

    printf("kCGEventFlagMaskAlphaShift: %llX\n", (int64_t)kCGEventFlagMaskAlphaShift);
    printf("kCGEventFlagMaskShift: %llX\n", (int64_t)kCGEventFlagMaskShift);
    printf("kCGEventFlagMaskControl: %llX\n", (int64_t)kCGEventFlagMaskControl);
    printf("kCGEventFlagMaskAlternate: %llX\n", (int64_t)kCGEventFlagMaskAlternate);
    printf("kCGEventFlagMaskCommand: %llX\n", (int64_t)kCGEventFlagMaskCommand);
    printf("kCGEventFlagMaskHelp: %llX\n", (int64_t)kCGEventFlagMaskHelp);
    printf("kCGEventFlagMaskSecondaryFn: %llX\n", (int64_t)kCGEventFlagMaskSecondaryFn);
    printf("kCGEventFlagMaskNumericPad: %llX\n", (int64_t)kCGEventFlagMaskNumericPad);
    printf("kCGEventFlagMaskNonCoalesced: %llX\n", (int64_t)kCGEventFlagMaskNonCoalesced);

    // sticky Fn, after clicking Home.
    simulate_key(source, kVK_Home, true);
    simulate_key(source, kVK_Home, false);

    printf("\n\nSimulate h after Home.\n");
    fflush(stdout);

    // simulate_key(source, kVK_Shift, true);

    // Simulate h. The behavior seems Fn + h.
    simulate_key(source, kVK_ANSI_H, true);
    simulate_key(source, kVK_ANSI_H, false);

    // simulate_key(source, kVK_Shift, false);

    // So as simulating e and d...

    CFRelease(source);
}

int main(int argc, const char * argv[]) {
//    UInt8 keyboard_type = LMGetKbdType();
//    unsigned int layout_type = KBGetLayoutType(keyboard_type);
//    printf("LMGetKbdType(): %d, KBGetLayoutType(): %d\n", keyboard_type, layout_type);

    print33();
    return 0;
}
</code>```

Body:
When I try to simulate keys programmatically on MacOS.
I find some keys causes sticky "Fn".

The following code results "Fn" + "h".
Can anyone help explain whether it is intended?

#include <stdio.h>
#include <Carbon/Carbon.h>

void simulate_key(CGEventSourceRef source, CGKeyCode key, bool key_down)
{
    CGEventRef event = CGEventCreateKeyboardEvent(source, key, key_down);
    CGEventPost(kCGSessionEventTap, event);
    CFRelease(event);
    sleep(1);
}

void print33(void) {
    CGEventSourceRef source = CGEventSourceCreate(kCGEventSourceStatePrivate);

    printf("simulate #: ");
    fflush(stdout);
    simulate_key(source, kVK_Shift, true);
    simulate_key(source, kVK_ANSI_3, true);
    simulate_key(source, kVK_ANSI_3, false);
    simulate_key(source, kVK_Shift, false);

    // sticky Fn, after clicking Home.
    simulate_key(source, kVK_Home, true);
    simulate_key(source, kVK_Home, false);

    printf("\nSimulate h after Home.\n");
    fflush(stdout);

    // Simulate h. The behavior seems Fn + h.
    simulate_key(source, kVK_ANSI_H, true);
    simulate_key(source, kVK_ANSI_H, false);

    // So as simulating e and d...

    CFRelease(source);
}

int main(int argc, const char * argv[]) {
    print33();
    return 0;
}

I've also tried to print CGEventFlags. It shows kCGEventFlagMaskSecondaryFn is set. But I don't know whether it is a side effect. How can I prevent the Fn flag to be set when I just simulate a Home key.

#include <stdio.h>
#include <Carbon/Carbon.h>

void simulate_key(CGEventSourceRef source, CGKeyCode key, bool key_down)
{
    CGEventRef event = CGEventCreateKeyboardEvent(source, key, key_down);
    // CGEventSetFlags(event, 0);
    CGEventFlags flags = CGEventGetFlags(event);
    printf("event flags: %llX\n", (int64_t)flags);
    CGEventPost(kCGSessionEventTap, event);
    CFRelease(event);
    sleep(1);
}

void print33(void) {
    CGEventSourceRef source = CGEventSourceCreate(kCGEventSourceStatePrivate);

//    printf("simulate #: ");
//    fflush(stdout);
//    simulate_key(source, kVK_Shift, true);
//    simulate_key(source, kVK_ANSI_3, true);
//    simulate_key(source, kVK_ANSI_3, false);
//    simulate_key(source, kVK_Shift, false);

    printf("kCGEventFlagMaskAlphaShift: %llX\n", (int64_t)kCGEventFlagMaskAlphaShift);
    printf("kCGEventFlagMaskShift: %llX\n", (int64_t)kCGEventFlagMaskShift);
    printf("kCGEventFlagMaskControl: %llX\n", (int64_t)kCGEventFlagMaskControl);
    printf("kCGEventFlagMaskAlternate: %llX\n", (int64_t)kCGEventFlagMaskAlternate);
    printf("kCGEventFlagMaskCommand: %llX\n", (int64_t)kCGEventFlagMaskCommand);
    printf("kCGEventFlagMaskHelp: %llX\n", (int64_t)kCGEventFlagMaskHelp);
    printf("kCGEventFlagMaskSecondaryFn: %llX\n", (int64_t)kCGEventFlagMaskSecondaryFn);
    printf("kCGEventFlagMaskNumericPad: %llX\n", (int64_t)kCGEventFlagMaskNumericPad);
    printf("kCGEventFlagMaskNonCoalesced: %llX\n", (int64_t)kCGEventFlagMaskNonCoalesced);

    // sticky Fn, after clicking Home.
    simulate_key(source, kVK_Home, true);
    simulate_key(source, kVK_Home, false);

    printf("\n\nSimulate h after Home.\n");
    fflush(stdout);

    // simulate_key(source, kVK_Shift, true);

    // Simulate h. The behavior seems Fn + h.
    simulate_key(source, kVK_ANSI_H, true);
    simulate_key(source, kVK_ANSI_H, false);

    // simulate_key(source, kVK_Shift, false);

    // So as simulating e and d...

    CFRelease(source);
}

int main(int argc, const char * argv[]) {
//    UInt8 keyboard_type = LMGetKbdType();
//    unsigned int layout_type = KBGetLayoutType(keyboard_type);
//    printf("LMGetKbdType(): %d, KBGetLayoutType(): %d\n", keyboard_type, layout_type);

    print33();
    return 0;
}


问:
How put value in jsonb_set postgreSQL
I'm new to PostgreSQL and before I worked on SQL Server. I want to create a table with a key and a JSON column to write and update my JSON field. I use the jsonb_set method in PostgreSQL.

For example

update "Comment"
set "testJsonb" = jsonb_set("testJsonb",'{uuid}',SomeMethod,true)
```
<p>I want to replace this function <code>uuid_generate_v4()</code> with SomeMethod. I figured that I should not put function there, then I decided to put a variable there, but I can't do that and I don't know why.</p>
<p><code>DECLARE cnt varchar;</code></p>
<p>as you see above code doesn't work</p>
```DO $$
DECLARE
   myVar VARCHAR := 'myValue';
BEGIN
select myVar
END $$;
```
<p>another way</p>
```CREATE OR REPLACE FUNCTION clean_emp()
RETURNS void AS $$
DECLARE cnt varchar;
BEGIN
END;
$$ LANGUAGE plpgsql;
```

I can declare a variable in a function, but I don't want this because I can't put a function in SomeMethod in jsonb_set. Am I wrong? Or should this be done in another way?

Title: How put value in jsonb_set postgreSQL

Body:
I'm new to PostgreSQL and before I worked on SQL Server. I want to create a table with a key and a JSON column to write and update my JSON field. I use the jsonb_set method in PostgreSQL.

For example

update "Comment"
set "testJsonb" = jsonb_set("testJsonb",'{uuid}',SomeMethod,true)

I want to replace this function uuid_generate_v4() with SomeMethod. I figured that I should not put function there, then I decided to put a variable there, but I can't do that and I don't know why.

DECLARE cnt varchar;

as you see above code doesn't work

DO $$
DECLARE
   myVar VARCHAR := 'myValue';
BEGIN
select myVar
END $$;

another way

CREATE OR REPLACE FUNCTION clean_emp()
RETURNS void AS $$
DECLARE cnt varchar;
BEGIN
END;
$$ LANGUAGE plpgsql;

I can declare a variable in a function, but I don't want this because I can't put a function in SomeMethod in jsonb_set. Am I wrong? Or should this be done in another way?


问:
Is it possible to provide a scoring metric to sklearn RFE?
I need to get subsets of top 1, top 2, top 3, etc. features, and performance of my model on each of these subsets. Something like this:

Number of features
Features
Performance

1
A
0.7

2
A, D
0.72

3
A, D, B
0.75

I wanted to use RFE as a possible improvement over simply using feature importances from models.

In sklearn, the RFECV object has a ranking_ attribute, which would let me create the feature subsets. The problem is that all features below the number of features that RFECV found to be optimal are equal to 1, so the first k features are not ordered by importance.

I thought of using a simple RFE instead, but it doesn't accept the scoring parameter, and the default accuracy is not appropriate in my case where classes are very unbalanced.

Is there a way to either somehow provide a scoring metric to sklearn RFE, or to force RFECV (that does accept a scoring parameter) to evaluate ranking below the 'optimal' number of features?

I also considered using SFS but I have about 500 features and it takes days to run.


问:
Sweetalert2: How to pass values from 1 step to result
Hello i am trying to pass a value (1 or 2 or 3) from the first step of my Swal.queue

here is the code

```<code>    reason: number = 0;
btn1: any;
  btn2: any;
  btn3: any;
  notes: string = '';

        const steps = ['1', '2']
        const Queue = Swal.mixin({
          progressSteps: steps,
          confirmButtonText: '<b style="font-family:Arial;color:whitesmoke;font-size:15px">Next →</b>',
          showCancelButton: true,
          backdrop: false,
          confirmButtonColor: 'whitesmoke',
          // optional classes to avoid backdrop blinking between steps
          showClass: { backdrop: 'swal2-noanimation' },
          hideClass: { backdrop: 'swal2-noanimation' }
        })
        await Queue.fire({
          title: '<b style="font-size:17px!important;">' + this.translation.first_select_why_you_want_to_block_this_member + '</b><br />',
            html: '<br /><ion-textx [(ngModel)]="btn1" [ngClass]="btn1" id="btn_1"><a tabindex="1">' + this.translation.rude_or_inappropriate_language + '</a></ion-textx>' + '<br /><br />' +
              '<ion-textx [(ngModel)]="btn2" [ngClass]="btn2" id="btn_2"><a tabindex="2">' + this.translation.fake_or_spam_profile + '</a></ion-textx>' + '<br /><br />' +
              '<ion-textx [(ngModel)]="btn3" [ngClass]="btn3" id="btn_3"><a tabindex="3">' + this.translation.violent_or_strange_behaviour + '</a></ion-textx>' + '<br /><br />',
          currentProgressStep: 0,

        })
        await Queue.fire({
          title: '<b style="font-size:17px!important;">' + this.translation.tell_us_a_few_words + '</b>',
            html: '<textarea [(ngModel)]="notes" id="notes" [ngClass]="notes1" cols="20" rows="7" style="align-content:center; width: 100%;overflow:auto; border:1px outset #9999;"></textarea>',
          currentProgressStep: 1
        })
          .then((result: any) => {
              if (this.btn1) {
              this.reason = 1;
            }
            else if (this.btn2) {
              this.reason = 2;
            }//ok this is the problem that i told you about jquery so far i change it in user all you have to do is pass the parameters
            else if (this.btn3) {
              this.reason =  3;//this three btn_1 2 and three as reason and notes for notes as why wants to vblock someone. LET ME SHOW YOU
              // where you want ot pass this params?
            }
            this.notes = (<HTMLInputElement>document.getElementById('notes')).value;
            if (result.value) {
              Swal.fire({
                title: this.translation.are_you_sure_you_want_to_send_this_report,
                backdrop: false,
                confirmButtonText: '<b style="font-family:Arial;color: whitesmoke;font-size:15px">' +this.translation.send_your_repost+ '</b>',
              }).then(() => {
                let report = {
                  user_id: this.userDetails.uid,
                  reason: this.reason,
                  notes: this.notes
                };// di you get it?yes just didnt know about javascript ok now i got it. I ll finish it and see about uploading did you liked it? do i need to do more? I like it you are improving it did you
                this.userData.addUserReport(report).pipe(
                  map((data: any) => {
                    if (data.success) {
                      Swal.fire({
                        icon: 'success',
                        title: this.translation.you_temporary_blocked_this_member,
                        showConfirmButton: false,
                        backdrop: false,
                        timer: 2500
                      })
                      this.router.navigate(['app/tablinks/home']);
                    }
                  })
                ).subscribe()
              })
            }
          })
</code>```

I want to ask how to send btn1 or 2 or 3 and to keep the value to the next step

I know that i have to keep the value before it goes to the next step but how do i do that? this.notes is stored as wanted but reason is not. any help?

Body:
Hello i am trying to pass a value (1 or 2 or 3) from the first step of my Swal.queue

here is the code

    reason: number = 0;
btn1: any;
  btn2: any;
  btn3: any;
  notes: string = '';

        const steps = ['1', '2']
        const Queue = Swal.mixin({
          progressSteps: steps,
          confirmButtonText: 'Next →',
          showCancelButton: true,
          backdrop: false,
          confirmButtonColor: 'whitesmoke',
          // optional classes to avoid backdrop blinking between steps
          showClass: { backdrop: 'swal2-noanimation' },
          hideClass: { backdrop: 'swal2-noanimation' }
        })
        await Queue.fire({
          title: '' + this.translation.first_select_why_you_want_to_block_this_member + '
',
            html: '
<ion-textx [(ngModel)]="btn1" [ngClass]="btn1" id="btn_1">' + this.translation.rude_or_inappropriate_language + '</ion-textx>' + '

' +
              '<ion-textx [(ngModel)]="btn2" [ngClass]="btn2" id="btn_2">' + this.translation.fake_or_spam_profile + '</ion-textx>' + '

' +
              '<ion-textx [(ngModel)]="btn3" [ngClass]="btn3" id="btn_3">' + this.translation.violent_or_strange_behaviour + '</ion-textx>' + '

',
          currentProgressStep: 0,

        })
        await Queue.fire({
          title: '' + this.translation.tell_us_a_few_words + '',
            html: '<textarea [(ngModel)]="notes" id="notes" [ngClass]="notes1" cols="20" rows="7" style="align-content:center; width: 100%;overflow:auto; border:1px outset #9999;"></textarea>',
          currentProgressStep: 1
        })
          .then((result: any) => {
              if (this.btn1) {
              this.reason = 1;
            }
            else if (this.btn2) {
              this.reason = 2;
            }//ok this is the problem that i told you about jquery so far i change it in user all you have to do is pass the parameters
            else if (this.btn3) {
              this.reason =  3;//this three btn_1 2 and three as reason and notes for notes as why wants to vblock someone. LET ME SHOW YOU
              // where you want ot pass this params?
            }
            this.notes = (<HTMLInputElement>document.getElementById('notes')).value;
            if (result.value) {
              Swal.fire({
                title: this.translation.are_you_sure_you_want_to_send_this_report,
                backdrop: false,
                confirmButtonText: '' +this.translation.send_your_repost+ '',
              }).then(() => {
                let report = {
                  user_id: this.userDetails.uid,
                  reason: this.reason,
                  notes: this.notes
                };// di you get it?yes just didnt know about javascript ok now i got it. I ll finish it and see about uploading did you liked it? do i need to do more? I like it you are improving it did you
                this.userData.addUserReport(report).pipe(
                  map((data: any) => {
                    if (data.success) {
                      Swal.fire({
                        icon: 'success',
                        title: this.translation.you_temporary_blocked_this_member,
                        showConfirmButton: false,
                        backdrop: false,
                        timer: 2500
                      })
                      this.router.navigate(['app/tablinks/home']);
                    }
                  })
                ).subscribe()
              })
            }
          })

I want to ask how to send btn1 or 2 or 3 and to keep the value to the next step

I know that i have to keep the value before it goes to the next step but how do i do that? this.notes is stored as wanted but reason is not. any help?


问:
ESP32 dual core multi tasks priority issue
task1 : webServerTask,
task2 : guiTask (use mutex)
I assigned task1 to cpu0 and task2 to cpu1 using the xTaskCreatePinnedToCore function in esp32. Then I expected task1 and task2 to run concurrently on each other’s cpu regardless of their respective priorities, isn’t that right?
If I increase the priority of task1 over task2, task2 will not run. If I set the priorities to be the same, both tasks will run. Even if I assign tasks to different CPUs, does the execution of the tasks differ according to their priority? Or is it related to the use of semaphore in task2?

case 1: webServerTask run, guiTask does not work (priority: task1 > task2, task2 with mutex)

xTaskCreatePinnedToCore(webServerTask, "webServer", 4096, NULL, 2, NULL, 0);
xTaskCreatePinnedToCore(guiTask, "gui", 4096 * 2, NULL, 1, NULL, 1);
```
<p>case 2: both webServerTask and guiTask run (priority: task1 = task2, task2 with mutex)</p>
<pre class="lang-cpp prettyprint-override"><code>xTaskCreatePinnedToCore(webServerTask, "webServer", 4096, NULL, 1, NULL, 0);
xTaskCreatePinnedToCore(guiTask, "gui", 4096 * 2, NULL, 1, NULL, 1);
</code>```

case 3: both webServerTask and guiTask run (priority: task1 > task2, task2 without mutex)

xTaskCreatePinnedToCore(webServerTask, "webServer", 4096, NULL, 2, NULL, 0);
xTaskCreatePinnedToCore(guiTask, "gui", 4096 * 2, NULL, 1, NULL, 1)
```
<p>Task1 and Task2 are implemented as below:</p>
```static void webServerTask(void *pvParameters)
{
  // initialize wifi and the web server
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED)
  {
    vTaskDelay(500 / portTICK_PERIOD_MS);
    Serial.print(".");
  }

  // Run the web server loop indefinitely
  while(1)
  {
    WiFiClient client = server.available();
    if (client)
    {
      ...
     }
    vTaskDelay(10 / portTICK_PERIOD_MS);
  }
}

static void guiTask(void *pvParameter)
{
  xGuiSemaphore = xSemaphoreCreateMutex();
  ...  // display

  while (1)
  {
    vTaskDelay(pdMS_TO_TICKS(10));

    if (pdTRUE == xSemaphoreTake(xGuiSemaphore, portMAX_DELAY))
    {
      lv_task_handler();
      xSemaphoreGive(xGuiSemaphore);
    }
  }
}
```

Body:
task1 : webServerTask,
task2 : guiTask (use mutex)
I assigned task1 to cpu0 and task2 to cpu1 using the xTaskCreatePinnedToCore function in esp32. Then I expected task1 and task2 to run concurrently on each other’s cpu regardless of their respective priorities, isn’t that right?
If I increase the priority of task1 over task2, task2 will not run. If I set the priorities to be the same, both tasks will run. Even if I assign tasks to different CPUs, does the execution of the tasks differ according to their priority? Or is it related to the use of semaphore in task2?

case 1: webServerTask run, guiTask does not work (priority: task1 > task2, task2 with mutex)

xTaskCreatePinnedToCore(webServerTask, "webServer", 4096, NULL, 2, NULL, 0);
xTaskCreatePinnedToCore(guiTask, "gui", 4096 * 2, NULL, 1, NULL, 1);

case 2: both webServerTask and guiTask run (priority: task1 = task2, task2 with mutex)

xTaskCreatePinnedToCore(webServerTask, "webServer", 4096, NULL, 1, NULL, 0);
xTaskCreatePinnedToCore(guiTask, "gui", 4096 * 2, NULL, 1, NULL, 1);

case 3: both webServerTask and guiTask run (priority: task1 > task2, task2 without mutex)

xTaskCreatePinnedToCore(webServerTask, "webServer", 4096, NULL, 2, NULL, 0);
xTaskCreatePinnedToCore(guiTask, "gui", 4096 * 2, NULL, 1, NULL, 1)

Task1 and Task2 are implemented as below:

static void webServerTask(void *pvParameters)
{
  // initialize wifi and the web server
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED)
  {
    vTaskDelay(500 / portTICK_PERIOD_MS);
    Serial.print(".");
  }

  // Run the web server loop indefinitely
  while(1)
  {
    WiFiClient client = server.available();
    if (client)
    {
      ...
     }
    vTaskDelay(10 / portTICK_PERIOD_MS);
  }
}

static void guiTask(void *pvParameter)
{
  xGuiSemaphore = xSemaphoreCreateMutex();
  ...  // display

  while (1)
  {
    vTaskDelay(pdMS_TO_TICKS(10));

    if (pdTRUE == xSemaphoreTake(xGuiSemaphore, portMAX_DELAY))
    {
      lv_task_handler();
      xSemaphoreGive(xGuiSemaphore);
    }
  }
}


问:
How to safely update the balance field in django
I need to use a wallet model in my project. If I need to update the balance of the wallet, what is the safest way to do it? For example, if different threads or different processes increase the balance of the wallet at the same time, will there be any problems?

```<code>class Wallet(models.Model):
    balance = models.DecimalField(_('Balance'), max_digits=18, decimal_places=8, default=0)

    def withdraw(self,amount):
        self.balance = self.balance - amount

    def deposit(self,amount):
        self.balance = self.balance + amount
</code>```

Is this model above safe? If not, what is the best practice?

Body:
I need to use a wallet model in my project. If I need to update the balance of the wallet, what is the safest way to do it? For example, if different threads or different processes increase the balance of the wallet at the same time, will there be any problems?

class Wallet(models.Model):
    balance = models.DecimalField(_('Balance'), max_digits=18, decimal_places=8, default=0)

    def withdraw(self,amount):
        self.balance = self.balance - amount

    def deposit(self,amount):
        self.balance = self.balance + amount

Is this model above safe? If not, what is the best practice?


问:
VSCode Test Explorer not finding module despite PYTHONPATH defined
EDIT

Thanks the comment below, I've managed to get the command to work from the CLI. However, I'm still struggling to make it work using VSCode's test explorer.
Here's my current settings.json:

{
    ...
    "python.testing.pytestEnabled": false,
    "python.testing.unittestEnabled": true,
    "python.testing.cwd": "./data-quality/tests"
}
```
<p>Thru the Python output on VSCode, I'm getting <code>modulenotfound</code> errors, as if the <code>PYTHONPATH</code> wasn't taken in account.</p>
<pre class="lang-bash prettyprint-override"><code>> /usr/local/bin/python3 ~/.vscode/extensions/ms-python.python-2022.20.1/pythonFiles/testing_tools/unittest_discovery.py . *test*.py
cwd: ./data-quality/tests
[ERROR 2022-11-28 11:31:16.278]: Error discovering unittest tests:
 Failed to import test module: test_helpers
Traceback (most recent call last):
  File "/usr/local/Cellar/python@3.10/3.10.8/Frameworks/Python.framework/Versions/3.10/lib/python3.10/unittest/loader.py", line 436, in _find_test_path
    module = self._get_module_from_name(name)
  File "/usr/local/Cellar/python@3.10/3.10.8/Frameworks/Python.framework/Versions/3.10/lib/python3.10/unittest/loader.py", line 377, in _get_module_from_name
    __import__(name)
  File "/Users/b242pn/Documents/SOC/data-quality/data-quality/tests/test_helpers.py", line 1, in <module>
    from helpers import group_columns_by_vendor_product
ModuleNotFoundError: No module named 'helpers'
</code>```

=====================================================================

I've got a project with the following structure:

```<code>├── data-quality
│   ├── __pycache__
|   ├── helpers.py
│   └── tests
│       └── __pycache__
|       └── test_helpers.py
├── include
└── share
</code>```

I'm currently in tests, trying to use a module in its parent folder, data-quality. I've heard that to use them in a testing context, it is important to use absolute imports, so I tried doing so:

import sys
sys.path.append('../')
from helpers import group_columns_by_vendor_product
import unittest
...
```
<p>However, whenever I use python to discover these tests, I get a modulenotfound error:</p>
<pre class="lang-bash prettyprint-override"><code> python3 -m unittest discover -v -s data-quality/tests -p 'test_*.py'
======================================================================
ERROR: test_helpers (unittest.loader._FailedTest)
----------------------------------------------------------------------
ImportError: Failed to import test module: test_helpers
Traceback (most recent call last):
  File "/usr/local/Cellar/python@3.10/3.10.8/Frameworks/Python.framework/Versions/3.10/lib/python3.10/unittest/loader.py", line 436, in _find_test_path
    module = self._get_module_from_name(name)
  File "/usr/local/Cellar/python@3.10/3.10.8/Frameworks/Python.framework/Versions/3.10/lib/python3.10/unittest/loader.py", line 377, in _get_module_from_name
    __import__(name)
  File "data-quality/tests/test_helpers.py", line 4, in <module>
    from helpers import group_columns_by_vendor_product
ModuleNotFoundError: No module named 'helpers'
</code>```

Am I missing something?

TIA

P.S: I noticed that the tests run when I run the command locally, and inside of the data-quality folder, but not above:

python3 -m unittest discover -v -s . -p 'test_*.py'
test_group_columns_by_vendor_product_normal_behavior (test_helpers.TestGroupColumnsByVendorProduct) ... FAIL

======================================================================
FAIL: test_group_columns_by_vendor_product_normal_behavior (test_helpers.TestGroupColumnsByVendorProduct)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Users/b242pn/Documents/SOC/data-quality/data-quality/tests/test_helpers.py", line 54, in test_group_columns_by_vendor_product_normal_behavior
    self.assertEqual([("Microsoft", "Microsoft Windows")], result)
AssertionError: Lists differ: [('Microsoft', 'Microsoft Windows')] != []

First list contains 1 additional elements.
First extra element 0:
('Microsoft', 'Microsoft Windows')

- [('Microsoft', 'Microsoft Windows')]
+ []

----------------------------------------------------------------------
Ran 1 test in 0.001s

python3 -m unittest discover -v -s ./tests -p 'test_*.py'
test_group_columns_by_vendor_product_normal_behavior (test_helpers.TestGroupColumnsByVendorProduct) ... FAIL

======================================================================
FAIL: test_group_columns_by_vendor_product_normal_behavior (test_helpers.TestGroupColumnsByVendorProduct)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Users/b242pn/Documents/SOC/data-quality/data-quality/tests/test_helpers.py", line 54, in test_group_columns_by_vendor_product_normal_behavior
    self.assertEqual([("Microsoft", "Microsoft Windows")], result)
AssertionError: Lists differ: [('Microsoft', 'Microsoft Windows')] != []

First list contains 1 additional elements.
First extra element 0:
('Microsoft', 'Microsoft Windows')

- [('Microsoft', 'Microsoft Windows')]
+ []

----------------------------------------------------------------------
Ran 1 test in 0.001s
```

Body:
EDIT

Thanks the comment below, I've managed to get the command to work from the CLI. However, I'm still struggling to make it work using VSCode's test explorer.
Here's my current settings.json:

{
    ...
    "python.testing.pytestEnabled": false,
    "python.testing.unittestEnabled": true,
    "python.testing.cwd": "./data-quality/tests"
}

Thru the Python output on VSCode, I'm getting modulenotfound errors, as if the PYTHONPATH wasn't taken in account.

> /usr/local/bin/python3 ~/.vscode/extensions/ms-python.python-2022.20.1/pythonFiles/testing_tools/unittest_discovery.py . *test*.py
cwd: ./data-quality/tests
[ERROR 2022-11-28 11:31:16.278]: Error discovering unittest tests:
 Failed to import test module: test_helpers
Traceback (most recent call last):
  File "/usr/local/Cellar/python@3.10/3.10.8/Frameworks/Python.framework/Versions/3.10/lib/python3.10/unittest/loader.py", line 436, in _find_test_path
    module = self._get_module_from_name(name)
  File "/usr/local/Cellar/python@3.10/3.10.8/Frameworks/Python.framework/Versions/3.10/lib/python3.10/unittest/loader.py", line 377, in _get_module_from_name
    __import__(name)
  File "/Users/b242pn/Documents/SOC/data-quality/data-quality/tests/test_helpers.py", line 1, in <module>
    from helpers import group_columns_by_vendor_product
ModuleNotFoundError: No module named 'helpers'

=====================================================================

I've got a project with the following structure:

├── data-quality
│   ├── __pycache__
|   ├── helpers.py
│   └── tests
│       └── __pycache__
|       └── test_helpers.py
├── include
└── share

I'm currently in tests, trying to use a module in its parent folder, data-quality. I've heard that to use them in a testing context, it is important to use absolute imports, so I tried doing so:

import sys
sys.path.append('../')
from helpers import group_columns_by_vendor_product
import unittest
...

However, whenever I use python to discover these tests, I get a modulenotfound error:

 python3 -m unittest discover -v -s data-quality/tests -p 'test_*.py'
======================================================================
ERROR: test_helpers (unittest.loader._FailedTest)
----------------------------------------------------------------------
ImportError: Failed to import test module: test_helpers
Traceback (most recent call last):
  File "/usr/local/Cellar/python@3.10/3.10.8/Frameworks/Python.framework/Versions/3.10/lib/python3.10/unittest/loader.py", line 436, in _find_test_path
    module = self._get_module_from_name(name)
  File "/usr/local/Cellar/python@3.10/3.10.8/Frameworks/Python.framework/Versions/3.10/lib/python3.10/unittest/loader.py", line 377, in _get_module_from_name
    __import__(name)
  File "data-quality/tests/test_helpers.py", line 4, in <module>
    from helpers import group_columns_by_vendor_product
ModuleNotFoundError: No module named 'helpers'

Am I missing something?

TIA

P.S: I noticed that the tests run when I run the command locally, and inside of the data-quality folder, but not above:

python3 -m unittest discover -v -s . -p 'test_*.py'
test_group_columns_by_vendor_product_normal_behavior (test_helpers.TestGroupColumnsByVendorProduct) ... FAIL

======================================================================
FAIL: test_group_columns_by_vendor_product_normal_behavior (test_helpers.TestGroupColumnsByVendorProduct)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Users/b242pn/Documents/SOC/data-quality/data-quality/tests/test_helpers.py", line 54, in test_group_columns_by_vendor_product_normal_behavior
    self.assertEqual([("Microsoft", "Microsoft Windows")], result)
AssertionError: Lists differ: [('Microsoft', 'Microsoft Windows')] != []

First list contains 1 additional elements.
First extra element 0:
('Microsoft', 'Microsoft Windows')

- [('Microsoft', 'Microsoft Windows')]
+ []

----------------------------------------------------------------------
Ran 1 test in 0.001s

python3 -m unittest discover -v -s ./tests -p 'test_*.py'
test_group_columns_by_vendor_product_normal_behavior (test_helpers.TestGroupColumnsByVendorProduct) ... FAIL

======================================================================
FAIL: test_group_columns_by_vendor_product_normal_behavior (test_helpers.TestGroupColumnsByVendorProduct)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Users/b242pn/Documents/SOC/data-quality/data-quality/tests/test_helpers.py", line 54, in test_group_columns_by_vendor_product_normal_behavior
    self.assertEqual([("Microsoft", "Microsoft Windows")], result)
AssertionError: Lists differ: [('Microsoft', 'Microsoft Windows')] != []

First list contains 1 additional elements.
First extra element 0:
('Microsoft', 'Microsoft Windows')

- [('Microsoft', 'Microsoft Windows')]
+ []

----------------------------------------------------------------------
Ran 1 test in 0.001s


问:
Plotting imshow inside subplot
I am trying to plot tests from an imshow function inside an subplot. This works fine when I only include one object to be plotted, but when I use 4 objects, still only one is shown. The function I am using to create the objects are from here.

Apart from not all objects being shown I also get the following error:

ValueError: x, y, and format string must not be None

```<code>fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2, figsize=(8,8))
ax1.set_title('Zone 1')
ax1.plot(plot_multivariate_DM_test(df['Price_REG1'].iloc[17544:],
                          predictions_22_1, norm=1, title='DM test', savefig=False, path=''))
ax2.set_title('Zone 2')
ax2.plot(plot_multivariate_DM_test(df['Price_REG2'].iloc[17544:],
                          predictions_22_2, norm=1, title='DM test', savefig=False, path=''))
ax3.set_title('Zone 3')
ax3.plot(plot_multivariate_DM_test(df['Price_REG3'].iloc[17544:],
                          predictions_22_3, norm=1, title='DM test', savefig=False, path=''))
ax4.set_title('Zone 4')
ax4.plot(plot_multivariate_DM_test(df['Price_REG4'].iloc[17544:],
                          predictions_22_4, norm=1, title='DM test', savefig=False, path=''))
fig.tight_layout()
plt.show()
</code>```

Title: Plotting imshow inside subplot

Body:
I am trying to plot tests from an imshow function inside an subplot. This works fine when I only include one object to be plotted, but when I use 4 objects, still only one is shown. The function I am using to create the objects are from here.

Apart from not all objects being shown I also get the following error:

ValueError: x, y, and format string must not be None

fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2, figsize=(8,8))
ax1.set_title('Zone 1')
ax1.plot(plot_multivariate_DM_test(df['Price_REG1'].iloc[17544:],
                          predictions_22_1, norm=1, title='DM test', savefig=False, path=''))
ax2.set_title('Zone 2')
ax2.plot(plot_multivariate_DM_test(df['Price_REG2'].iloc[17544:],
                          predictions_22_2, norm=1, title='DM test', savefig=False, path=''))
ax3.set_title('Zone 3')
ax3.plot(plot_multivariate_DM_test(df['Price_REG3'].iloc[17544:],
                          predictions_22_3, norm=1, title='DM test', savefig=False, path=''))
ax4.set_title('Zone 4')
ax4.plot(plot_multivariate_DM_test(df['Price_REG4'].iloc[17544:],
                          predictions_22_4, norm=1, title='DM test', savefig=False, path=''))
fig.tight_layout()
plt.show()


问:
Ghost Text transformation on vertical scroll
while scrolling the page I need to load the ghost text effect when the specific section enters the screen or at least in the middle of screen but its showing effect when 80% of the section passes the screen vertically.

const square = document.querySelector('.square');
square.classList.remove('square-transition');

// Create the observer, same as before:
const observer = new IntersectionObserver(entries => {
  entries.forEach(entry => {
    if (entry.isIntersecting) {
      square.classList.add('square-transition');
      return;
    }

    square.classList.remove('square-transition');
  });
});

observer.observe(document.querySelector('.square-wrapper'));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.square {
  width: 100%;
  position: absolute;
  z-index: 1;
  opacity: 0.2;
  font-size: 200px;
  text-align: center;
  padding-top: 190px;
}

@media (prefers-reduced-motion: no-preference) {
  .square {
    transition: opacity 0.5s ease, transform 1.5s ease;
  }
}

.square-transition {
  opacity: 0.01;
  transform: translate3d(-10px, 0.2in, 0px);
}</code>```

Design Concept

........
```

Body:
while scrolling the page I need to load the ghost text effect when the specific section enters the screen or at least in the middle of screen but its showing effect when 80% of the section passes the screen vertically.

const square = document.querySelector('.square');
square.classList.remove('square-transition');

// Create the observer, same as before:
const observer = new IntersectionObserver(entries => {
  entries.forEach(entry => {
    if (entry.isIntersecting) {
      square.classList.add('square-transition');
      return;
    }

    square.classList.remove('square-transition');
  });
});

observer.observe(document.querySelector('.square-wrapper'));

.square {
  width: 100%;
  position: absolute;
  z-index: 1;
  opacity: 0.2;
  font-size: 200px;
  text-align: center;
  padding-top: 190px;
}

@media (prefers-reduced-motion: no-preference) {
  .square {
    transition: opacity 0.5s ease, transform 1.5s ease;
  }
}

.square-transition {
  opacity: 0.01;
  transform: translate3d(-10px, 0.2in, 0px);
}

Design Concept

........


问:
Is it a bad idea to #include C source files to select implementation of an API?
I am working on a C project where I'm defining an API, and then have multiple different implementations of that API, something like the below:

```<code>|-api.h
|-implementation_1.c
|-implementation_2.c
</code>```

I'm working with CMake, so currently to select which implementation is used by the application, the user has to set a define, e.g. -DIMPLEMENTATION_SEL_1 and also select which of the implemmentation_x.c files are included in the build.

I was thinking it could be nice to simplify the selection to depend only on the define, by adding an extra source file with #includes to the implementation-specific source files, something like this...

```<code>|-api.h
|-implementation.c
|-implementation_1.c
|-implementation_2.c
</code>```
```<code>//implementation.c

#if defined IMPLEMENTATION_SEL_1
    #include "implementation_1.c"
#elif defined IMPLEMENTATION_SEL_2
    #include "implementation_2.c"
#else
    #error "Invalid API implementation selected"
#endif
</code>```

This way my CMake file only ever has to specify implementation.c as part of the build, and only the define should change to select between implementations.

My question is: is there any reason I should avoid this approach? I've heard it's bad practice to include source files, but to me it seems in this case it might be cleaner than the alternatives

Body:
I am working on a C project where I'm defining an API, and then have multiple different implementations of that API, something like the below:

|-api.h
|-implementation_1.c
|-implementation_2.c

I'm working with CMake, so currently to select which implementation is used by the application, the user has to set a define, e.g. -DIMPLEMENTATION_SEL_1 and also select which of the implemmentation_x.c files are included in the build.

I was thinking it could be nice to simplify the selection to depend only on the define, by adding an extra source file with #includes to the implementation-specific source files, something like this...

|-api.h
|-implementation.c
|-implementation_1.c
|-implementation_2.c

//implementation.c

#if defined IMPLEMENTATION_SEL_1
    #include "implementation_1.c"
#elif defined IMPLEMENTATION_SEL_2
    #include "implementation_2.c"
#else
    #error "Invalid API implementation selected"
#endif

This way my CMake file only ever has to specify implementation.c as part of the build, and only the define should change to select between implementations.

My question is: is there any reason I should avoid this approach? I've heard it's bad practice to include source files, but to me it seems in this case it might be cleaner than the alternatives


问:
How can I combine 2 different models with union?
I want to combine the results of the queries of two different models with union, but sql code parts are different, and Django throws an exception:

Unable to get repr for <class 'django.db.models.query.QuerySet'>
django.db.utils.ProgrammingError: UNION types numeric and character varying cannot be matched
LINE 1: ...order"."update_date", "core_filled"."status", "core_trig..

```<code>custom_qs = active_qs.annotate(**{'order_numberx': F('order_number'),
                                  'condition_side': Value('GTE', output_field=CharField()),
                                  }).values("order_number", "account_id",
                                              "order_type",  "price",
                                              "buy_sell", "status",
                                              "add_date", "update_date",
                                              "status", "condition_side",
                                              "total_price")

filled_qs = trigger_qs.annotate(**{'order_numberx': F('order_number'),
                                    'total_price': Value(0, output_field=DecimalField())
                                    }).values("order_number", "account_id",
                                              "order_type",  "price",
                                              "buy_sell", "status",
                                              "add_date", "update_date",
                                              "status", "condition_side",
                                              "total_price")

orders_qs = active_qs.union(trigger_qs)

</code>```

SQL QUERY

```<code>(SELECT "core_custom"."order_number", "core_custom"."account_id", "core_custom"."order_type", "core_custom"."market_code", "core_custom"."channel_code", "core_custom"."price", "core_custom"."volume", "core_custom"."volume_executed", "core_custom"."buy_sell", "core_custom"."status", "core_custom"."add_date", "core_custom"."update_date", "core_custom"."client_id", "core_custom"."post_only", "core_custom"."status", "core_custom"."total_price", GTE AS "condition_side"
FROM "core_custom"
WHERE ("core_custom"."account_id" = 1549 AND "core_custom"."status" IN (N, P)))
UNION
(SELECT "core_filled"."order_number", "core_filled"."account_id", "core_filled"."order_type", "core_filled"."market_code", "core_filled"."channel_code", "core_filled"."price", "core_triggerorder"."volume", "core_filled"."volume_executed", "core_filled"."buy_sell", "core_filled"."status", "core_filled"."add_date", "core_filled"."update_date", "core_filled"."client_id", "core_filled"."post_only", "core_filled"."status", "core_filled"."condition_side", 0 AS "total_price"
FROM "core_filled"
WHERE ("core_triggerorder"."account_id" = 1549 AND "core_filled"."status" = N))
</code>```

How can I control order of columns in sql query generated by ORM?

Body:
I want to combine the results of the queries of two different models with union, but sql code parts are different, and Django throws an exception:

Unable to get repr for <class 'django.db.models.query.QuerySet'>
django.db.utils.ProgrammingError: UNION types numeric and character varying cannot be matched
LINE 1: ...order"."update_date", "core_filled"."status", "core_trig..

custom_qs = active_qs.annotate(**{'order_numberx': F('order_number'),
                                  'condition_side': Value('GTE', output_field=CharField()),
                                  }).values("order_number", "account_id",
                                              "order_type",  "price",
                                              "buy_sell", "status",
                                              "add_date", "update_date",
                                              "status", "condition_side",
                                              "total_price")

filled_qs = trigger_qs.annotate(**{'order_numberx': F('order_number'),
                                    'total_price': Value(0, output_field=DecimalField())
                                    }).values("order_number", "account_id",
                                              "order_type",  "price",
                                              "buy_sell", "status",
                                              "add_date", "update_date",
                                              "status", "condition_side",
                                              "total_price")

orders_qs = active_qs.union(trigger_qs)

SQL QUERY

(SELECT "core_custom"."order_number", "core_custom"."account_id", "core_custom"."order_type", "core_custom"."market_code", "core_custom"."channel_code", "core_custom"."price", "core_custom"."volume", "core_custom"."volume_executed", "core_custom"."buy_sell", "core_custom"."status", "core_custom"."add_date", "core_custom"."update_date", "core_custom"."client_id", "core_custom"."post_only", "core_custom"."status", "core_custom"."total_price", GTE AS "condition_side"
FROM "core_custom"
WHERE ("core_custom"."account_id" = 1549 AND "core_custom"."status" IN (N, P)))
UNION
(SELECT "core_filled"."order_number", "core_filled"."account_id", "core_filled"."order_type", "core_filled"."market_code", "core_filled"."channel_code", "core_filled"."price", "core_triggerorder"."volume", "core_filled"."volume_executed", "core_filled"."buy_sell", "core_filled"."status", "core_filled"."add_date", "core_filled"."update_date", "core_filled"."client_id", "core_filled"."post_only", "core_filled"."status", "core_filled"."condition_side", 0 AS "total_price"
FROM "core_filled"
WHERE ("core_triggerorder"."account_id" = 1549 AND "core_filled"."status" = N))

How can I control order of columns in sql query generated by ORM?


问:
The route configured by SpringMVC shows that 404 does not find resources
HelloController.java

web.xml
springmvc-servlet.xml

And I tried to add dependencies to the lib directory in the project structure
workpiece
tomcat configuration


问:
Facebook complains that the app is not secure
When I try to login via Facebook, it throws the following error;

facebook has detected app isn't using a secure connection to transfer information

But I'm pretty sure that it is secured via 'Let's encrypt'.
I have checked Web and Client OAuth login boxes and set the corresponding redirect uris on developer facebook.

On maui side, I am calling the following code piece and AppSettings.BaseUrl is correct, I have checked that;

```<code>WebAuthenticatorResult authResult = await WebAuthenticator.Default.AuthenticateAsync(
                new WebAuthenticatorOptions()
                {
                    Url = new Uri($"{AppSettings.BaseUrl}account/authentication/{scheme}"),
                    CallbackUrl = new Uri("tibi://"),
                    PrefersEphemeralWebBrowserSession = true
                });
</code>```

And on backend side, the following api is requested;

```<code>        [HttpGet("authentication/{scheme}")]
    [AllowAnonymous]
    public async Task Get([FromRoute] string scheme)
    {
        var auth = await Request.HttpContext.AuthenticateAsync(scheme);

        if (!auth.Succeeded
            || auth?.Principal == null
            || !auth.Principal.Identities.Any(id => id.IsAuthenticated)
            || string.IsNullOrEmpty(auth.Properties.GetTokenValue("access_token")))
        {
            // Not authenticated, challenge
            await Request.HttpContext.ChallengeAsync(scheme);
        }
        else
        {
            var claims = auth.Principal.Identities.FirstOrDefault()?.Claims;
            var email = string.Empty;
            email = claims?.FirstOrDefault(c => c.Type == System.Security.Claims.ClaimTypes.Email)?.Value;

            // Get parameters to send back to the callback
            var qs = new Dictionary<string, string>
            {
                { "access_token", auth.Properties.GetTokenValue("access_token") },
                { "refresh_token", auth.Properties.GetTokenValue("refresh_token") ?? string.Empty },
                { "expires_in", (auth.Properties.ExpiresUtc?.ToUnixTimeSeconds() ?? -1).ToString() },
                { "email", email }
            };

            // Build the result url
            var url = callbackScheme + "://#" + string.Join(
                "&",
                qs.Where(kvp => !string.IsNullOrEmpty(kvp.Value) && kvp.Value != "-1")
                .Select(kvp => $"{WebUtility.UrlEncode(kvp.Key)}={WebUtility.UrlEncode(kvp.Value)}"));

            // Redirect to final url
            Request.Host = HostString.FromUriComponent(AppSettingsProvider.GatewayUrl);
            Request.HttpContext.Response.Redirect(url);
        }
    }
</code>```

Challenge is invoked successfully and redirects me to the Facebook login but when I sign in, I get the error above.

Body:
When I try to login via Facebook, it throws the following error;

facebook has detected app isn't using a secure connection to transfer information

But I'm pretty sure that it is secured via 'Let's encrypt'.
I have checked Web and Client OAuth login boxes and set the corresponding redirect uris on developer facebook.

On maui side, I am calling the following code piece and AppSettings.BaseUrl is correct, I have checked that;

WebAuthenticatorResult authResult = await WebAuthenticator.Default.AuthenticateAsync(
                new WebAuthenticatorOptions()
                {
                    Url = new Uri($"{AppSettings.BaseUrl}account/authentication/{scheme}"),
                    CallbackUrl = new Uri("tibi://"),
                    PrefersEphemeralWebBrowserSession = true
                });

And on backend side, the following api is requested;

        [HttpGet("authentication/{scheme}")]
    [AllowAnonymous]
    public async Task Get([FromRoute] string scheme)
    {
        var auth = await Request.HttpContext.AuthenticateAsync(scheme);

        if (!auth.Succeeded
            || auth?.Principal == null
            || !auth.Principal.Identities.Any(id => id.IsAuthenticated)
            || string.IsNullOrEmpty(auth.Properties.GetTokenValue("access_token")))
        {
            // Not authenticated, challenge
            await Request.HttpContext.ChallengeAsync(scheme);
        }
        else
        {
            var claims = auth.Principal.Identities.FirstOrDefault()?.Claims;
            var email = string.Empty;
            email = claims?.FirstOrDefault(c => c.Type == System.Security.Claims.ClaimTypes.Email)?.Value;

            // Get parameters to send back to the callback
            var qs = new Dictionary<string, string>
            {
                { "access_token", auth.Properties.GetTokenValue("access_token") },
                { "refresh_token", auth.Properties.GetTokenValue("refresh_token") ?? string.Empty },
                { "expires_in", (auth.Properties.ExpiresUtc?.ToUnixTimeSeconds() ?? -1).ToString() },
                { "email", email }
            };

            // Build the result url
            var url = callbackScheme + "://#" + string.Join(
                "&",
                qs.Where(kvp => !string.IsNullOrEmpty(kvp.Value) && kvp.Value != "-1")
                .Select(kvp => $"{WebUtility.UrlEncode(kvp.Key)}={WebUtility.UrlEncode(kvp.Value)}"));

            // Redirect to final url
            Request.Host = HostString.FromUriComponent(AppSettingsProvider.GatewayUrl);
            Request.HttpContext.Response.Redirect(url);
        }
    }

Challenge is invoked successfully and redirects me to the Facebook login but when I sign in, I get the error above.


问:
Bluetooth LE, once read fails, it returns "Read Characteristic Fail" for subsequent requests, but able to receive notifications
Scenario 1 -

Reading characteristics from BLE device, one request fails ("Read Timeout"), then all subsequent requests fails ("Read Characteristic Fail"), but when BLE device sends notification, it receives. but unable to Read or Write. Device is still connected.

`12-28 13:25:00.620 25648 25666 D Device  : resolve: read|<F9...SERVICE_UUID>|<06...CHARACTERISTIC_UUID> 03 E8 00 64 01 7D 50 00 01 F5 01 2D 00 5B 00 47 00 15 00 09

// FULL 20 BYTES RETURNED at 13:25:00, it was working normally then

12-28 13:25:26.230 25648 25666 D Device  : reject: read|<F9...SERVICE_UUID>|<06...CHARACTERISTIC_UUID>

// REJECTED at 13:25:26, errors started from here`

Scenario 2 -

Reading characteristics from BLE device, one request returns ~half data (was expecting 20 bytes, but only received 9 bytes). then all subsequent requests fails ("Read Characteristic Fail"), but when BLE device sends notification, it receives. but unable to Read or Write. Device is still connected.

Logs

`12-28 13:25:00.620 25648 25666 D Device  : resolve: read|<F9...SERVICE_UUID>|<06...CHARACTERISTIC_UUID> 03 E8 00 64 01 7D 50 00 01 F5 01 2D 00 5B 00 47 00 15 00 09

// FULL 20 BYTES RETURNED at 13:25:00, it was working normally then

12-28 13:25:26.230 25648 25666 D Device  : resolve: read|<F9...SERVICE_UUID>|<06...CHARACTERISTIC_UUID> 0F 00 C5 00 00 00 10 00 00

// ONLY 9 BYTES RETURNED at 13:25:26, errors started from here`

Can't BLE ignore one "read fail", and continue reading ? when it is still connected. When reading same characteristic again, it also returns "Read Characteristic Fail"

Most probably notifications and read requests are conflicting (can't avoid, because notification can come anytime), and starting/ stopping notifications multiple times causes same issues.

Environment

Ionic--6.20.6

Angular--15.0.4

Capacitor--4.6.1

capacitor-community/bluetooth-le--2.0.1

Device

Xiaomi Redmi Note 10 Pro (android 12)
Also tested with other android/ios phones, but same result

I did tried -

Reading same characteristic again, but same error

Tried reading 1 second after notification came (1 second time gap after notification received, it is not possible to add time gap before notification arrives because it can arrive at any time, and in random numbers)

implemented Queue, at a time only 1 request will be active.